ARADebug.c 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302
  1. //------------------------------------------------------------------------------
  2. //! \file ARADebug.c
  3. //! debug helpers for the ARA SDK Library
  4. //! \project ARA SDK Library
  5. //! \copyright Copyright (c) 2012-2021, Celemony Software GmbH, All Rights Reserved.
  6. //! \license Licensed under the Apache License, Version 2.0 (the "License");
  7. //! you may not use this file except in compliance with the License.
  8. //! You may obtain a copy of the License at
  9. //!
  10. //! http://www.apache.org/licenses/LICENSE-2.0
  11. //!
  12. //! Unless required by applicable law or agreed to in writing, software
  13. //! distributed under the License is distributed on an "AS IS" BASIS,
  14. //! WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  15. //! See the License for the specific language governing permissions and
  16. //! limitations under the License.
  17. //------------------------------------------------------------------------------
  18. #include "ARADebug.h"
  19. #include <stdlib.h>
  20. #include <stdio.h>
  21. #include <string.h>
  22. #include <stdarg.h>
  23. #if defined(_WIN32)
  24. #define WIN32_LEAN_AND_MEAN
  25. #include <Windows.h>
  26. // Windows string printing functions defined for compatibility
  27. #define snprintf(ptr, size, ...) do { sprintf_s(ptr, (size) - 1, __VA_ARGS__); ptr[(size) - 1] = 0; } while (0)
  28. #define vsnprintf(ptr, size, ...) do { vsprintf_s(ptr, (size) - 1, __VA_ARGS__); ptr[(size) - 1] = 0; } while (0)
  29. #elif defined(__APPLE__)
  30. #include <sys/sysctl.h>
  31. #include <unistd.h>
  32. #elif defined(__linux__)
  33. #include <sys/stat.h>
  34. #include <unistd.h>
  35. #include <fcntl.h>
  36. #include <ctype.h>
  37. #endif
  38. #if defined(__cplusplus)
  39. namespace ARA
  40. {
  41. extern "C"
  42. {
  43. #endif
  44. // prevent warnings about using NULL if this is compiled as C++ (despite being a .c file)
  45. #if defined(__cplusplus)
  46. #if defined(NULL)
  47. #undef NULL
  48. #endif
  49. #define NULL nullptr
  50. #endif
  51. //------------------------------------------------------------------------------
  52. #if ARA_ENABLE_INTERNAL_ASSERTS
  53. static ARABool IsDebuggerAttached(void);
  54. static ARABool IsDebuggerAttached(void)
  55. {
  56. #if defined(_WIN32)
  57. // Windows provides an explicit debugger test
  58. return (IsDebuggerPresent()) ? kARATrue : kARAFalse;
  59. #elif defined(__APPLE__)
  60. // From Technical Q&A QA1361: https://developer.apple.com/qa/qa2004/qa1361.html
  61. // Returns true if the current process is being debugged (either
  62. // running under the debugger or has a debugger attached post facto).
  63. // Initialize mib, which tells sysctl the info we want, in this case
  64. // we're looking for information about a specific process ID.
  65. int mib[4];
  66. mib[0] = CTL_KERN;
  67. mib[1] = KERN_PROC;
  68. mib[2] = KERN_PROC_PID;
  69. mib[3] = getpid();
  70. // Initialize the flags so that, if sysctl fails for some bizarre
  71. // reason, we get a predictable result.
  72. struct kinfo_proc info;
  73. info.kp_proc.p_flag = 0;
  74. // Call sysctl.
  75. size_t size = sizeof(info);
  76. /*int junk =*/ sysctl(mib, (u_int)(sizeof(mib) / sizeof(*mib)), &info, &size, NULL, 0);
  77. //assert(junk == 0);
  78. // We're being debugged if the P_TRACED flag is set.
  79. return (info.kp_proc.p_flag & P_TRACED) ? kARATrue : kARAFalse;
  80. #elif defined (__linux__)
  81. char buf[4096];
  82. const int status_fd = open("/proc/self/status", O_RDONLY);
  83. if (status_fd == -1)
  84. return kARAFalse;
  85. const ssize_t num_read = read(status_fd, buf, sizeof(buf) - 1);
  86. if (num_read <= 0)
  87. return kARAFalse;
  88. buf[num_read] = '\0';
  89. const char tracerPidString[] = "TracerPid:";
  90. const char* tracer_pid_ptr = strstr(buf, tracerPidString);
  91. if (tracer_pid_ptr == NULL)
  92. return kARAFalse;
  93. for (const char* characterPtr = tracer_pid_ptr + sizeof(tracerPidString) - 1; characterPtr <= buf + num_read; ++characterPtr)
  94. {
  95. if (isspace(*characterPtr))
  96. continue;
  97. return (isdigit(*characterPtr) != 0 && *characterPtr != '0') ? kARATrue : kARAFalse;
  98. }
  99. return kARAFalse;
  100. #else
  101. #error "checking for debugger not yet implemented on this platform"
  102. return kARAFalse;
  103. #endif
  104. }
  105. #endif // ARA_ENABLE_INTERNAL_ASSERTS
  106. //void BreakIntoDebugger();
  107. //We use a macro instead of a function here to suppress the extra call stack frame displayed by the debugger.
  108. #if defined(_MSC_VER)
  109. // Visual Studio provides an explicit debugger call
  110. #define BreakIntoDebugger(...) __debugbreak()
  111. #elif defined(__GNUC__)
  112. #if defined __has_builtin
  113. #if __has_builtin(__builtin_debugtrap)
  114. #define BreakIntoDebugger(...) __builtin_debugtrap()
  115. #endif
  116. #endif
  117. #if !defined(BreakIntoDebugger)
  118. // GDB: signal SIGINT to have the debugger stop directly at the expression
  119. // see https://cocoawithlove.com/2008/03/break-into-debugger.html
  120. // #if ARA_CPU_PPC
  121. // #define BreakIntoDebugger(...) __asm__ volatile("li r0,20\n sc\n nop\n li r0,37\n li r4,2\n sc\n nop\n" : : : "memory","r0","r4")
  122. #if ARA_CPU_X86
  123. #define BreakIntoDebugger(...) __asm__ volatile("int $3\n nop\n" : : )
  124. #else
  125. #warning "BreakIntoDebugger() not yet implemented for this processor, falling back to __builtin_trap() which aborts the program."
  126. #define BreakIntoDebugger(...) __builtin_trap()
  127. #endif
  128. #endif
  129. #else
  130. #error "not yet implemented on this platform"
  131. #endif
  132. //------------------------------------------------------------------------------
  133. #if ARA_ENABLE_DEBUG_OUTPUT
  134. // optional binary-global logging prefix
  135. static const char * debugPrefix = "";
  136. static const char * prefixSpace = "";
  137. void ARASetupDebugMessagePrefix(const char * prefix)
  138. {
  139. if (prefix && strlen(prefix))
  140. {
  141. debugPrefix = prefix;
  142. prefixSpace = " ";
  143. }
  144. else
  145. {
  146. debugPrefix = "";
  147. prefixSpace = "";
  148. }
  149. }
  150. void ARADebugMessage(ARADebugLevel level, const char * file, int line, const char * text, ...)
  151. {
  152. char textString[2048] = { 0 };
  153. char lineString[64] = { 0 };
  154. char output[4096] = { 0 };
  155. #if defined (__GNUC__)
  156. _Pragma ("GCC diagnostic push")
  157. _Pragma ("GCC diagnostic ignored \"-Wformat-nonliteral\"")
  158. #endif
  159. va_list vargs;
  160. va_start (vargs, text);
  161. vsnprintf (textString, sizeof(textString), text, vargs);
  162. va_end(vargs);
  163. #if defined (__GNUC__)
  164. _Pragma ("GCC diagnostic pop")
  165. #endif
  166. if (line > 0)
  167. {
  168. #if defined(_MSC_VER)
  169. snprintf (lineString, sizeof(lineString), "(%i)", line);
  170. #else
  171. snprintf (lineString, sizeof(lineString), ":%i", line);
  172. #endif
  173. }
  174. switch (level)
  175. {
  176. case kARADebugLevelLog: snprintf (output, sizeof(output), "[%s%sARA_LOG] %s", debugPrefix, prefixSpace, textString); break;
  177. case kARADebugLevelWarning: snprintf (output, sizeof(output), "[%s%sARA_WARN] in file %s%s:\n\t%s", debugPrefix, prefixSpace, file, lineString, textString); break;
  178. case kARADebugLevelAssert: snprintf (output, sizeof(output), "[%s%sARA_ASSERT] in file %s%s:\n\t%s", debugPrefix, prefixSpace, file, lineString, textString); break;
  179. }
  180. #if defined(_WIN32)
  181. OutputDebugStringA(output);
  182. OutputDebugStringA("\n");
  183. #endif
  184. fprintf(stderr, "%s\n", output);
  185. fflush(stderr);
  186. }
  187. #endif // ARA_ENABLE_DEBUG_OUTPUT
  188. //------------------------------------------------------------------------------
  189. #if ARA_ENABLE_INTERNAL_ASSERTS
  190. void ARAHandleAssert(const char * file, int line, const char * diagnosis)
  191. {
  192. #if ARA_ENABLE_DEBUG_OUTPUT
  193. ARA_DEBUG_MESSAGE(kARADebugLevelAssert, file, line, diagnosis);
  194. #endif
  195. if (IsDebuggerAttached())
  196. BreakIntoDebugger();
  197. abort(); // conforms to the behavior of C's standard assert() macro, should yield proper crash dump.
  198. }
  199. #endif // ARA_ENABLE_INTERNAL_ASSERTS
  200. //------------------------------------------------------------------------------
  201. #if ARA_VALIDATE_API_CALLS
  202. static ARAAssertFunction * araExternalAssert = NULL;
  203. void ARASetExternalAssertReference(ARAAssertFunction * address)
  204. {
  205. araExternalAssert = address;
  206. }
  207. #if defined (__GNUC__)
  208. // this might be returning depending on what ARA_HANDLE_ASSERT() injects, so just silence the warning
  209. _Pragma ("GCC diagnostic push")
  210. _Pragma ("GCC diagnostic ignored \"-Wmissing-noreturn\"")
  211. #endif
  212. void ARAAssertionFailure(ARAAssertCategory category, const void * problematicArgument, const char * file, int line, const char * diagnosis)
  213. {
  214. #if ARA_ENABLE_INTERNAL_ASSERTS
  215. const char * categoryText;
  216. switch (category)
  217. {
  218. case kARAAssertUnspecified: categoryText = "unspecified failure"; break;
  219. case kARAAssertInvalidArgument: categoryText = "invalid argument"; break;
  220. case kARAAssertInvalidState: categoryText = "invalid state"; break;
  221. case kARAAssertInvalidThread: categoryText = "invalid thread"; break;
  222. default: categoryText = "unknown failure"; break;
  223. }
  224. char failure[1024];
  225. snprintf (failure, sizeof(failure), "ARA API violation (%s, pointer = %p): %s", categoryText, problematicArgument, diagnosis);
  226. ARA_HANDLE_ASSERT(file, line, failure);
  227. #else
  228. (void)category; (void)problematicArgument; (void)file; (void)line; (void)diagnosis; // prevent unused argument warnings
  229. #endif // ARA_ENABLE_INTERNAL_ASSERTS
  230. }
  231. #if defined (__GNUC__)
  232. _Pragma ("GCC diagnostic pop")
  233. #endif
  234. void ARAInterfaceAssert(ARAAssertCategory category, const void * problematicArgument, const char * diagnosis)
  235. {
  236. ARAAssertionFailure(category, problematicArgument, "ARA API PARTNER BINARY", 0, diagnosis);
  237. }
  238. void ARAValidationFailure(ARAAssertCategory category, const void * problematicArgument, const char * file, int line, const char * diagnosis)
  239. {
  240. if (araExternalAssert && *araExternalAssert && (*araExternalAssert != &ARAInterfaceAssert))
  241. (*araExternalAssert)(category, problematicArgument, diagnosis);
  242. else
  243. ARAAssertionFailure(category, problematicArgument, file, line, diagnosis);
  244. }
  245. ARABool ARACheckFunctionPointersAreValid(const void * interfacePointer)
  246. {
  247. // the structs start off with "ARASize structSize", followed by function pointers until the specified end of struct
  248. ARASize size = *(ARASize *)interfacePointer;
  249. for (const void ** functionPointer = (const void **)(((uintptr_t)interfacePointer) + sizeof(ARASize));
  250. functionPointer < (const void **)(((uintptr_t)interfacePointer) + size); ++functionPointer)
  251. {
  252. if (*functionPointer == NULL)
  253. return kARAFalse;
  254. }
  255. return kARATrue;
  256. }
  257. #endif // ARA_VALIDATE_API_CALLS
  258. //------------------------------------------------------------------------------
  259. #if defined(__cplusplus)
  260. } // extern "C"
  261. } // namespace ARA
  262. #endif