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.

313 lines
11 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 name (wrapped in double quotes):
  98. // "2 shard_tracy 0x00000001032d5618 _ZL17drawSettingsPanelv + 904"
  99. char buffer[1024];
  100. const char* mangledNameBegin = String::lastCharOccurence(traces[i], '_');
  101. const char* mangledNameEnd = String::lastCharOccurence(traces[i], '+'); // it actually ends one char before.
  102. if (mangledNameBegin == null || mangledNameEnd == null) {
  103. // we can't demangle this name for some reason, just copy the mangled name to the buffer
  104. size_t length = String::len(traces[i]);
  105. String::memcpy(buffer, (void*)traces[i], length);
  106. buffer[length] = '\0';
  107. } else {
  108. size_t length = mangledNameEnd - 1 - mangledNameBegin;
  109. String::memcpy(buffer, (void*)mangledNameBegin, length);
  110. buffer[length] = '\0';
  111. }
  112. s32 status = -1;
  113. char* trace = abi::__cxa_demangle(buffer, null, null, &status);
  114. if (trace == null) {
  115. println("warning: failed to demangle name: %s, exit status of attempt: %d", traces[i], status);
  116. // just write back the original trace, un-demangled.
  117. trace = traces[i];
  118. }
  119. if (string == null) {
  120. print("%s\n", trace);
  121. } else {
  122. string->appendf("%s\n", trace);
  123. }
  124. }
  125. pFree(traces);
  126. }
  127. #undef BACKTRACE_MAX_FRAMES
  128. #endif
  129. void _debug(const char* format, ...) {
  130. ULE_TYPES_H_FTAG;
  131. if (format == null) {
  132. print("%sdebug:%s null\n", ANSI_BLUE, ANSI_RESET);
  133. return;
  134. }
  135. va_list args;
  136. va_start(args, format);
  137. print("%sdebug:%s ", ANSI_BLUE, ANSI_RESET);
  138. vprintln(format, args);
  139. va_end(args);
  140. }
  141. void _warn(const char* format, ...) {
  142. ULE_TYPES_H_FTAG;
  143. if (format == null) {
  144. print("%swarning:%s null\n", ANSI_YELLOW, ANSI_RESET);
  145. return;
  146. }
  147. va_list args;
  148. va_start(args, format);
  149. print("%swarning:%s ", ANSI_YELLOW, ANSI_RESET);
  150. vprintln(format, args);
  151. va_end(args);
  152. }
  153. static void (*customDie)(const char* string) = null;
  154. // if you want to override what happens by default when your program calls 'die', you can do so here.
  155. // just keep in mind the intention is for 'die' to be for when your program has encountered a fatal, unrecoverable error.
  156. void setCustomDieBehavior(void (*dieBehavior)(const char* string)) {
  157. customDie = dieBehavior;
  158. }
  159. #ifdef _WIN32
  160. #include <Minidumpapiset.h>
  161. #include <tchar.h>
  162. static void writeMinidump(EXCEPTION_POINTERS* pep) {
  163. // create a file
  164. HANDLE hFile = CreateFile(_T("MiniDump.dmp"), GENERIC_READ | GENERIC_WRITE, 0, null, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, null);
  165. if ((hFile != null) && (hFile != INVALID_HANDLE_VALUE)) {
  166. // carry on with creating the minidump
  167. MINIDUMP_EXCEPTION_INFORMATION mdei;
  168. mdei.ThreadId = GetCurrentThreadId();
  169. mdei.ExceptionPointers = pep;
  170. mdei.ClientPointers = FALSE;
  171. MINIDUMP_TYPE mdt = MiniDumpNormal;
  172. BOOL rv = MiniDumpWriteDump(GetCurrentProcess(), GetCurrentProcessId(), hFile, mdt, (pep != 0) ? &mdei : 0, 0, 0);
  173. if (!rv) {
  174. println(_T("MiniDumpWriteDump failed. Error: %u"), GetLastError());
  175. } else {
  176. println(_T("MiniDump created."));
  177. }
  178. CloseHandle(hFile);
  179. } else {
  180. println(_T("Failed to CreateFile for MiniDump. Error: %u"), GetLastError());
  181. }
  182. }
  183. #endif
  184. // for fatal errors which may occur at runtime, even on a release binary.
  185. // if a fatal error should not occur at runtime on a release binary, consider preferring 'massert'
  186. // it's unclear when you should use asserts vs. die actually. idk man, they kinda do the same thing right now
  187. void die(const char* format, ...) {
  188. ULE_TYPES_H_FTAG;
  189. if (format == null) {
  190. if (customDie == null) {
  191. print("%serror:%s (unspecified error)\n", ANSI_RED, ANSI_RESET);
  192. trace();
  193. exit(1);
  194. return;
  195. } else {
  196. String string = String128f("error: (unspecified error)\n");
  197. trace(&string);
  198. customDie(string.c_str());
  199. return;
  200. }
  201. }
  202. va_list args;
  203. va_start(args, format);
  204. if (customDie == null) {
  205. println("%serror:%s", ANSI_RED, ANSI_RESET);
  206. vprintln(format, args);
  207. println();
  208. va_end(args);
  209. trace();
  210. exit(1);
  211. } else {
  212. String string = String128f("");
  213. string.appendfv(format, args);
  214. string.append("\n");
  215. trace(&string);
  216. va_end(args);
  217. customDie(string.c_str());
  218. }
  219. }
  220. void print(bool b) { ULE_TYPES_H_FTAG; print("%s", b ? "true" : "false"); }
  221. void print(char c) { ULE_TYPES_H_FTAG; print("%c", c); }
  222. void print(signed int i) { ULE_TYPES_H_FTAG; print("%d", i); }
  223. void print(unsigned int i) { ULE_TYPES_H_FTAG; print("%u", i); }
  224. void print(float f) { ULE_TYPES_H_FTAG; print("%.14g", f); }
  225. void print(double d) { ULE_TYPES_H_FTAG; print("%.14g", d); }
  226. void print(void* p) { ULE_TYPES_H_FTAG; print("%p", p); }
  227. void print(char* s) { ULE_TYPES_H_FTAG; print("%s", s); }
  228. #ifndef _WIN32
  229. void print(size_t i) { ULE_TYPES_H_FTAG; print("%u", i); }
  230. void println(size_t i) { ULE_TYPES_H_FTAG; print(i); print("\n"); }
  231. #endif
  232. void println(bool b) { ULE_TYPES_H_FTAG; print(b); print("\n"); }
  233. void println(char c) { ULE_TYPES_H_FTAG; print(c); print("\n"); }
  234. void println(signed int i) { ULE_TYPES_H_FTAG; print(i); print("\n"); }
  235. void println(unsigned int i) { ULE_TYPES_H_FTAG; print(i); print("\n"); }
  236. void println(float f) { ULE_TYPES_H_FTAG; print(f); print("\n"); }
  237. void println(double d) { ULE_TYPES_H_FTAG; print(d); print("\n"); }
  238. void println(void* p) { ULE_TYPES_H_FTAG; print(p); print("\n"); }
  239. void println(char* s) { ULE_TYPES_H_FTAG; print(s); print("\n"); }
  240. void println() { ULE_TYPES_H_FTAG; print("\n"); }
  241. #ifdef ULE_CONFIG_OPTION_USE_GLM
  242. void print(glm::vec<2, float, (glm::qualifier) 3> v) { ULE_TYPES_H_FTAG; print("vec2: %.14g,%.14g", v.x, v.y); }
  243. 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); }
  244. 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); }
  245. void print(glm::mat<2, 2, float, (glm::qualifier) 3> m) { ULE_TYPES_H_FTAG; print("mat2: "); print(m[0]); print(m[1]); }
  246. 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]); }
  247. 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]); }
  248. void println(glm::vec<2, float, (glm::qualifier) 3> v) { ULE_TYPES_H_FTAG; print(v); print("\n"); }
  249. void println(glm::vec<3, float, (glm::qualifier) 3> v) { ULE_TYPES_H_FTAG; print(v); print("\n"); }
  250. void println(glm::vec<4, float, (glm::qualifier) 3> v) { ULE_TYPES_H_FTAG; print(v); print("\n"); }
  251. void println(glm::mat<2, 2, float, (glm::qualifier) 3> m) { ULE_TYPES_H_FTAG; print(m); print("\n"); }
  252. void println(glm::mat<3, 3, float, (glm::qualifier) 3> m) { ULE_TYPES_H_FTAG; print(m); print("\n"); }
  253. void println(glm::mat<4, 4, float, (glm::qualifier) 3> m) { ULE_TYPES_H_FTAG; print(m); print("\n"); }
  254. #endif // ULE_CONFIG_OPTION_USE_GLM