A collection of basic/generally desirable code I use across multiple C++ projects.
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

343 lines
13 KiB

1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
  1. #include <stdarg.h> // va_list, va_start, va_end
  2. #include <stdio.h> // FILE, stderr, stdout | vfprintf
  3. #include <stdlib.h> // exit
  4. #include "alloc.h"
  5. #include "string.h"
  6. #include "print.h"
  7. #include "types.h"
  8. void vprint(const char* format, va_list args) {
  9. ULE_TYPES_H_FTAG;
  10. vfprintf(stdout, format, args);
  11. }
  12. void vprintln(const char* format, va_list args) {
  13. ULE_TYPES_H_FTAG;
  14. vprint(format, args);
  15. print("\n");
  16. }
  17. /**
  18. * The entire purpose of this is so we don't have to #import <stdio.h> everywhere
  19. * +we intend to replace printf at some point with this
  20. */
  21. void print(const char* format, ...) {
  22. ULE_TYPES_H_FTAG;
  23. if (format == null) { print("null"); return; }
  24. va_list args;
  25. va_start(args, format);
  26. vprint(format, args);
  27. va_end(args);
  28. }
  29. void println(const char* format, ...) {
  30. ULE_TYPES_H_FTAG;
  31. if (format == null) { print("null\n"); return; }
  32. va_list args;
  33. va_start(args, format);
  34. vprintln(format, args);
  35. va_end(args);
  36. }
  37. /**
  38. * Prints a stack trace.
  39. * Implementation varies for Win32 vs. *nix
  40. */
  41. #define BACKTRACE_MAX_FRAMES 63
  42. #ifdef _WIN32
  43. #include <windows.h>
  44. #include <dbghelp.h>
  45. // if |string| is non-null, then the stack trace will be concatenated to it instead of being printed to stdout.
  46. void trace(String* string) {
  47. ULE_TYPES_H_FTAG;
  48. #define BACKTRACE_MAX_FUNCTION_NAME_LENGTH 1024
  49. HANDLE processHandle = GetCurrentProcess();
  50. SymInitialize(processHandle, null, true);
  51. void* stack[BACKTRACE_MAX_FRAMES];
  52. unsigned short numFrames = CaptureStackBackTrace(0, BACKTRACE_MAX_FRAMES, stack, null);
  53. char buffer[sizeof(SYMBOL_INFO) + (BACKTRACE_MAX_FUNCTION_NAME_LENGTH - 1) * sizeof(TCHAR)];
  54. SYMBOL_INFO* symbol = (SYMBOL_INFO*) buffer;
  55. symbol->MaxNameLen = BACKTRACE_MAX_FUNCTION_NAME_LENGTH;
  56. symbol->SizeOfStruct = sizeof(SYMBOL_INFO);
  57. DWORD displacement;
  58. IMAGEHLP_LINE64 line;
  59. line.SizeOfStruct = sizeof(IMAGEHLP_LINE64);
  60. for (u32 i = 0; i < numFrames; i++) {
  61. DWORD64 address = (DWORD64) stack[i];
  62. SymFromAddr(processHandle, address, null, symbol);
  63. if (SymGetLineFromAddr64(processHandle, address, &displacement, &line)) {
  64. if (string == null) {
  65. print("\tat %s in %s: line: %lu: address %0x%0X\n", symbol->Name, line.FileName, line.LineNumber, symbol->Address);
  66. } else {
  67. string->appendf("\tat %s in %s: line: %lu: address %0x%0X\n", symbol->Name, line.FileName, line.LineNumber, symbol->Address);
  68. }
  69. } else {
  70. if (string == null) {
  71. print("\tSymGetLineFromAddr64 returned error code %lu.\n", GetLastError());
  72. print("\tat %s, address 0x%0X.\n", symbol->Name, symbol->Address);
  73. } else {
  74. string->appendf("\tSymGetLineFromAddr64 returned error code %lu.\n", GetLastError());
  75. string->appendf("\tat %s, address 0x%0X.\n", symbol->Name, symbol->Address);
  76. }
  77. }
  78. }
  79. #undef BACKTRACE_MAX_FUNCTION_NAME_LENGTH
  80. }
  81. #else
  82. // OSX and Linux stacktrace stuff.
  83. #include <execinfo.h> // backtrace, backtrace_symbols
  84. #include <cxxabi.h> // abi::__cxa_demangle
  85. // if |string| is non-null, then the stack trace will be concatenated to it instead of being printed to stdout.
  86. void trace(String* string) {
  87. ULE_TYPES_H_FTAG;
  88. void* stack[BACKTRACE_MAX_FRAMES];
  89. u32 stackSize = backtrace(stack, BACKTRACE_MAX_FRAMES);
  90. // resolve addresses into strings containing "filename(function+address)"
  91. // this array must be free()-ed
  92. char** traces = backtrace_symbols(stack, stackSize);
  93. // iterate over the returned symbol lines. skip the first, it is the address of this function
  94. for (u32 i = 1; i < stackSize; i++) {
  95. // the names as provided by 'backtrace_symbols' are mangled for some reason.
  96. // we have to demangle them, using this weird api
  97. // example mangled names (wrapped in double quotes):
  98. // "2 shard_tracy 0x00000001032d5618 _ZL17drawSettingsPanelv + 904"
  99. // "2 shard 0x000000010ed8be34 _ZN6ShaderC2EPKcS1_P5ArrayIS1_ES1_ + 1108"
  100. // "12 shard 0x000000010ed5edeb main + 43"
  101. //
  102. // the rule for finding the 'first' character is annoying, because it's usually but not always starting with an underscore,
  103. // and when it is an underscore it's usually but not always the first underscore in the string.
  104. char buffer[1024];
  105. const char* mangledNameEnd = String::lastCharOccurence(traces[i], '+'); // it actually ends one char before.
  106. const char* mangledNameBegin = null;
  107. if (mangledNameEnd != null && ((mangledNameEnd - traces[i]) > 2)) {
  108. const char* cursor = mangledNameEnd - 2;
  109. while (cursor != traces[i]) {
  110. if (*cursor == '_') {
  111. mangledNameBegin = cursor;
  112. } else if (*cursor == ' ') {
  113. mangledNameBegin = cursor + 1;
  114. break;
  115. }
  116. cursor--;
  117. }
  118. }
  119. if (mangledNameBegin == null || mangledNameEnd == null) {
  120. // we can't demangle this name for some reason, just copy the mangled name to the buffer
  121. size_t length = String::len(traces[i]);
  122. String::memcpy(buffer, (void*)traces[i], length);
  123. buffer[length] = '\0';
  124. } else {
  125. size_t length = mangledNameEnd - mangledNameBegin - 1;
  126. String::memcpy(buffer, (void*)mangledNameBegin, length);
  127. buffer[length] = '\0';
  128. }
  129. s32 status = -1;
  130. char* trace = abi::__cxa_demangle(buffer, null, null, &status);
  131. if (trace == null) {
  132. // @HACK, both 'main' and 'start' symbols will fail to be demangled, and we don't really care about printing them
  133. // in most cases. your application (certainly true for us) will have its own endpoint which itself is of questionable
  134. // usefulness to print, but 'main' and 'start' are even less useful.
  135. if (String::memeq((const unsigned char*)(mangledNameBegin), (const unsigned char*)"main", sizeof("main") - 1)) {
  136. continue;
  137. } else if (String::memeq((const unsigned char*)(mangledNameBegin), (const unsigned char*)"start", sizeof("start") - 1)) {
  138. continue;
  139. } else {
  140. println("warning: failed to demangle name: %s, exit status of attempt: %d", traces[i], status);
  141. // just write back the original trace, un-demangled.
  142. trace = traces[i];
  143. }
  144. }
  145. if (string == null) {
  146. print("%s\n", trace);
  147. } else {
  148. string->appendf("%s\n", trace);
  149. }
  150. }
  151. pFree(traces);
  152. }
  153. #undef BACKTRACE_MAX_FRAMES
  154. #endif
  155. void _debug(const char* format, ...) {
  156. ULE_TYPES_H_FTAG;
  157. if (format == null) {
  158. print("%sdebug:%s null\n", ANSI_BLUE, ANSI_RESET);
  159. return;
  160. }
  161. va_list args;
  162. va_start(args, format);
  163. print("%sdebug:%s ", ANSI_BLUE, ANSI_RESET);
  164. vprintln(format, args);
  165. va_end(args);
  166. }
  167. void _warn(const char* format, ...) {
  168. ULE_TYPES_H_FTAG;
  169. if (format == null) {
  170. print("%swarning:%s null\n", ANSI_YELLOW, ANSI_RESET);
  171. return;
  172. }
  173. va_list args;
  174. va_start(args, format);
  175. print("%swarning:%s ", ANSI_YELLOW, ANSI_RESET);
  176. vprintln(format, args);
  177. va_end(args);
  178. }
  179. static void (*customDie)(const char* string) = null;
  180. // if you want to override what happens by default when your program calls 'die', you can do so here.
  181. // just keep in mind the intention is for 'die' to be for when your program has encountered a fatal, unrecoverable error.
  182. void setCustomDieBehavior(void (*dieBehavior)(const char* string)) {
  183. customDie = dieBehavior;
  184. }
  185. #ifdef _WIN32
  186. #include <Minidumpapiset.h>
  187. #include <tchar.h>
  188. static void writeMinidump(EXCEPTION_POINTERS* pep) {
  189. // create a file
  190. HANDLE hFile = CreateFile(_T("MiniDump.dmp"), GENERIC_READ | GENERIC_WRITE, 0, null, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, null);
  191. if ((hFile != null) && (hFile != INVALID_HANDLE_VALUE)) {
  192. // carry on with creating the minidump
  193. MINIDUMP_EXCEPTION_INFORMATION mdei;
  194. mdei.ThreadId = GetCurrentThreadId();
  195. mdei.ExceptionPointers = pep;
  196. mdei.ClientPointers = FALSE;
  197. MINIDUMP_TYPE mdt = MiniDumpNormal;
  198. BOOL rv = MiniDumpWriteDump(GetCurrentProcess(), GetCurrentProcessId(), hFile, mdt, (pep != 0) ? &mdei : 0, 0, 0);
  199. if (!rv) {
  200. println(_T("MiniDumpWriteDump failed. Error: %u"), GetLastError());
  201. } else {
  202. println(_T("MiniDump created."));
  203. }
  204. CloseHandle(hFile);
  205. } else {
  206. println(_T("Failed to CreateFile for MiniDump. Error: %u"), GetLastError());
  207. }
  208. }
  209. #endif
  210. // for fatal errors which may occur at runtime, even on a release binary.
  211. // if a fatal error should not occur at runtime on a release binary, consider preferring 'massert'
  212. // it's unclear when you should use asserts vs. die actually. idk man, they kinda do the same thing right now
  213. void die(const char* format, ...) {
  214. ULE_TYPES_H_FTAG;
  215. if (format == null) {
  216. if (customDie == null) {
  217. print("%serror:%s (unspecified error)\n", ANSI_RED, ANSI_RESET);
  218. trace();
  219. exit(1);
  220. return;
  221. } else {
  222. String string = String128f("error: (unspecified error)\n");
  223. trace(&string);
  224. customDie(string.c_str());
  225. return;
  226. }
  227. }
  228. va_list args;
  229. va_start(args, format);
  230. if (customDie == null) {
  231. println("%serror:%s", ANSI_RED, ANSI_RESET);
  232. vprintln(format, args);
  233. println();
  234. va_end(args);
  235. trace();
  236. exit(1);
  237. } else {
  238. String string = String128f("");
  239. string.appendfv(format, args);
  240. string.append("\n");
  241. trace(&string);
  242. va_end(args);
  243. customDie(string.c_str());
  244. }
  245. }
  246. void print(bool b) { ULE_TYPES_H_FTAG; print("%s", b ? "true" : "false"); }
  247. void print(char c) { ULE_TYPES_H_FTAG; print("%c", c); }
  248. void print(signed int i) { ULE_TYPES_H_FTAG; print("%d", i); }
  249. void print(unsigned int i) { ULE_TYPES_H_FTAG; print("%u", i); }
  250. void print(float f) { ULE_TYPES_H_FTAG; print("%.14g", f); }
  251. void print(double d) { ULE_TYPES_H_FTAG; print("%.14g", d); }
  252. void print(void* p) { ULE_TYPES_H_FTAG; print("%p", p); }
  253. void print(char* s) { ULE_TYPES_H_FTAG; print("%s", s); }
  254. #ifndef _WIN32
  255. void print(size_t i) { ULE_TYPES_H_FTAG; print("%u", i); }
  256. void println(size_t i) { ULE_TYPES_H_FTAG; print(i); print("\n"); }
  257. #endif
  258. void println(bool b) { ULE_TYPES_H_FTAG; print(b); print("\n"); }
  259. void println(char c) { ULE_TYPES_H_FTAG; print(c); print("\n"); }
  260. void println(signed int i) { ULE_TYPES_H_FTAG; print(i); print("\n"); }
  261. void println(unsigned int i) { ULE_TYPES_H_FTAG; print(i); print("\n"); }
  262. void println(float f) { ULE_TYPES_H_FTAG; print(f); print("\n"); }
  263. void println(double d) { ULE_TYPES_H_FTAG; print(d); print("\n"); }
  264. void println(void* p) { ULE_TYPES_H_FTAG; print(p); print("\n"); }
  265. void println(char* s) { ULE_TYPES_H_FTAG; print(s); print("\n"); }
  266. void println() { ULE_TYPES_H_FTAG; print("\n"); }
  267. #ifdef ULE_CONFIG_OPTION_USE_GLM
  268. void print(glm::vec<2, float, (glm::qualifier) 3> v) { ULE_TYPES_H_FTAG; print("vec2: %.14g,%.14g", v.x, v.y); }
  269. void print(glm::vec<3, float, (glm::qualifier) 3> v) { ULE_TYPES_H_FTAG; print("vec3: %.14g,%.14g,%.14g", v.x, v.y, v.z); }
  270. void print(glm::vec<4, float, (glm::qualifier) 3> v) { ULE_TYPES_H_FTAG; print("vec4: %.14g,%.14g,%.14g,%.14g", v.x, v.y, v.z, v.w); }
  271. void print(glm::mat<2, 2, float, (glm::qualifier) 3> m) { ULE_TYPES_H_FTAG; print("mat2: "); print(m[0]); print(m[1]); }
  272. void print(glm::mat<3, 3, float, (glm::qualifier) 3> m) { ULE_TYPES_H_FTAG; print("mat3: "); print(m[0]); print(m[1]); print(m[2]); }
  273. void print(glm::mat<4, 4, float, (glm::qualifier) 3> m) { ULE_TYPES_H_FTAG; print("mat4: "); print(m[0]); print(m[1]); print(m[2]); print(m[3]); }
  274. void println(glm::vec<2, float, (glm::qualifier) 3> v) { ULE_TYPES_H_FTAG; print(v); print("\n"); }
  275. void println(glm::vec<3, float, (glm::qualifier) 3> v) { ULE_TYPES_H_FTAG; print(v); print("\n"); }
  276. void println(glm::vec<4, float, (glm::qualifier) 3> v) { ULE_TYPES_H_FTAG; print(v); print("\n"); }
  277. void println(glm::mat<2, 2, float, (glm::qualifier) 3> m) { ULE_TYPES_H_FTAG; print(m); print("\n"); }
  278. void println(glm::mat<3, 3, float, (glm::qualifier) 3> m) { ULE_TYPES_H_FTAG; print(m); print("\n"); }
  279. void println(glm::mat<4, 4, float, (glm::qualifier) 3> m) { ULE_TYPES_H_FTAG; print(m); print("\n"); }
  280. #endif // ULE_CONFIG_OPTION_USE_GLM