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.

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