stacktrace.cc 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807
  1. /* Copyright (c) 2001, 2019, Oracle and/or its affiliates. All rights reserved.
  2. This program is free software; you can redistribute it and/or modify
  3. it under the terms of the GNU General Public License, version 2.0,
  4. as published by the Free Software Foundation.
  5. This program is also distributed with certain software (including
  6. but not limited to OpenSSL) that is licensed under separate terms,
  7. as designated in a particular file or component or in included license
  8. documentation. The authors of MySQL hereby grant you an additional
  9. permission to link the program and your derivative works with the
  10. separately licensed software that they have included with MySQL.
  11. Without limiting anything contained in the foregoing, this file,
  12. which is part of C Driver for MySQL (Connector/C), is also subject to the
  13. Universal FOSS Exception, version 1.0, a copy of which can be found at
  14. http://oss.oracle.com/licenses/universal-foss-exception.
  15. This program is distributed in the hope that it will be useful,
  16. but WITHOUT ANY WARRANTY; without even the implied warranty of
  17. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  18. GNU General Public License, version 2.0, for more details.
  19. You should have received a copy of the GNU General Public License
  20. along with this program; if not, write to the Free Software
  21. Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */
  22. /**
  23. @file mysys/stacktrace.cc
  24. */
  25. #include "my_config.h"
  26. #include <errno.h>
  27. #include <fcntl.h>
  28. #include <stdarg.h>
  29. #include <stdio.h>
  30. #include <stdlib.h>
  31. #include <string.h>
  32. #include <sys/types.h>
  33. #ifdef __linux__
  34. #include <syscall.h>
  35. #endif
  36. #include <time.h>
  37. #include "my_inttypes.h"
  38. #include "my_macros.h"
  39. #include "my_stacktrace.h"
  40. #ifndef _WIN32
  41. #include <signal.h>
  42. #include "my_thread.h"
  43. #ifdef HAVE_UNISTD_H
  44. #include <unistd.h>
  45. #endif
  46. #ifdef HAVE_STACKTRACE
  47. #ifdef __linux__
  48. #include <ctype.h> /* isprint */
  49. #endif
  50. #ifdef HAVE_EXECINFO_H
  51. #include <execinfo.h>
  52. #endif
  53. #ifdef __FreeBSD__
  54. #define UNW_LOCAL_ONLY
  55. #error #include <libunwind.h>
  56. #endif
  57. #ifdef __linux__
  58. /* __bss_start doesn't seem to work on FreeBSD and doesn't exist on OSX/Solaris.
  59. */
  60. static const char *heap_start;
  61. extern char *__bss_start;
  62. #endif /* __linux */
  63. static inline bool ptr_sane(const char *p MY_ATTRIBUTE((unused)),
  64. const char *heap_end MY_ATTRIBUTE((unused))) {
  65. #ifdef __linux__
  66. return p && p >= heap_start && p <= heap_end;
  67. #else
  68. return true;
  69. #endif
  70. }
  71. void my_init_stacktrace() {
  72. #ifdef __linux__
  73. heap_start = (char *)&__bss_start;
  74. #endif /* __linux__ */
  75. }
  76. #ifdef __linux__
  77. static void print_buffer(char *buffer, size_t count) {
  78. const char s[] = " ";
  79. for (; count && *buffer; --count) {
  80. my_write_stderr(isprint(*buffer) ? buffer : s, 1);
  81. ++buffer;
  82. }
  83. }
  84. /**
  85. Access the pages of this process through /proc/self/task/<tid>/mem
  86. in order to safely print the contents of a memory address range.
  87. @param addr The address at the start of the memory region.
  88. @param max_len The length of the memory region.
  89. @return Zero on success.
  90. */
  91. static int safe_print_str(const char *addr, int max_len) {
  92. int fd;
  93. pid_t tid;
  94. off_t offset;
  95. ssize_t nbytes = 0;
  96. size_t total, count;
  97. char buf[256];
  98. tid = (pid_t)syscall(SYS_gettid);
  99. sprintf(buf, "/proc/self/task/%d/mem", tid);
  100. if ((fd = open(buf, O_RDONLY)) < 0) return -1;
  101. static_assert(sizeof(off_t) >= sizeof(intptr),
  102. "off_t needs to be able to hold a pointer.");
  103. total = max_len;
  104. offset = (intptr)addr;
  105. /* Read up to the maximum number of bytes. */
  106. while (total) {
  107. count = MY_MIN(sizeof(buf), total);
  108. if ((nbytes = pread(fd, buf, count, offset)) < 0) {
  109. /* Just in case... */
  110. if (errno == EINTR)
  111. continue;
  112. else
  113. break;
  114. }
  115. /* Advance offset into memory. */
  116. total -= nbytes;
  117. offset += nbytes;
  118. addr += nbytes;
  119. /* Output the printable characters. */
  120. print_buffer(buf, nbytes);
  121. /* Break if less than requested... */
  122. if ((count - nbytes)) break;
  123. }
  124. /* Output a new line if something was printed. */
  125. if (total != (size_t)max_len) my_safe_printf_stderr("%s", "\n");
  126. if (nbytes == -1) my_safe_printf_stderr("Can't read from address %p\n", addr);
  127. close(fd);
  128. return 0;
  129. }
  130. #endif /* __linux __ */
  131. void my_safe_puts_stderr(const char *val, size_t max_len) {
  132. const char *heap_end = nullptr;
  133. #ifdef __linux__
  134. if (!safe_print_str(val, max_len)) return;
  135. /* Only needed by the linux version of ptr_sane() */
  136. heap_end = static_cast<const char *>(sbrk(0));
  137. #endif
  138. if (!ptr_sane(val, heap_end)) {
  139. my_safe_printf_stderr("%s", "is an invalid pointer\n");
  140. return;
  141. }
  142. for (; max_len && ptr_sane(val, heap_end) && *val; --max_len)
  143. my_write_stderr((val++), 1);
  144. my_safe_printf_stderr("%s", "\n");
  145. }
  146. #if defined(HAVE_BACKTRACE)
  147. #ifdef HAVE_ABI_CXA_DEMANGLE
  148. #include <cxxabi.h>
  149. static char *my_demangle(const char *mangled_name, int *status) {
  150. return abi::__cxa_demangle(mangled_name, NULL, NULL, status);
  151. }
  152. static bool my_demangle_symbol(char *line) {
  153. char *demangled = NULL;
  154. #ifdef __APPLE__ // OS X formatting of stacktraces is different from Linux
  155. char *begin = strstr(line, "_Z");
  156. char *end = begin ? strchr(begin, ' ') : NULL;
  157. if (begin && end) {
  158. begin[-1] = '\0';
  159. *end = '\0';
  160. int status;
  161. demangled = my_demangle(begin, &status);
  162. if (!demangled || status) {
  163. demangled = NULL;
  164. begin[-1] = '_';
  165. *end = ' ';
  166. }
  167. }
  168. if (demangled) my_safe_printf_stderr("%s %s %s\n", line, demangled, end + 1);
  169. #elif defined(__SUNPRO_CC) // Solaris has different formatting .....
  170. char *begin = strchr(line, '\'');
  171. char *end = begin ? strchr(begin, '+') : NULL;
  172. if (begin && end) {
  173. *begin++ = *end++ = '\0';
  174. int status = 0;
  175. demangled = my_demangle(begin, &status);
  176. if (!demangled || status) {
  177. demangled = NULL;
  178. begin[-1] = ' ';
  179. end[-1] = '+';
  180. }
  181. }
  182. if (demangled) my_safe_printf_stderr("%s %s+%s\n", line, demangled, end);
  183. #else // !__APPLE__ and !__SUNPRO_CC
  184. char *begin = strchr(line, '(');
  185. char *end = begin ? strchr(begin, '+') : NULL;
  186. if (begin && end) {
  187. *begin++ = *end++ = '\0';
  188. int status;
  189. demangled = my_demangle(begin, &status);
  190. if (!demangled || status) {
  191. demangled = NULL;
  192. begin[-1] = '(';
  193. end[-1] = '+';
  194. }
  195. }
  196. if (demangled) my_safe_printf_stderr("%s(%s+%s\n", line, demangled, end);
  197. #endif
  198. bool ret = (demangled == NULL);
  199. free(demangled);
  200. return (ret);
  201. }
  202. // If it does not start with "_Z" it is a C function, and demangling fails.
  203. // Print the original line, with modifications done by my_demangle_symbol().
  204. static void my_demangle_symbols(char **addrs, int n) {
  205. for (int i = 0; i < n; i++) {
  206. if (my_demangle_symbol(addrs[i])) // demangling failed
  207. my_safe_printf_stderr("%s\n", addrs[i]);
  208. }
  209. }
  210. #endif /* HAVE_ABI_CXA_DEMANGLE */
  211. void my_print_stacktrace(uchar *stack_bottom, ulong thread_stack) {
  212. #if defined(__FreeBSD__)
  213. static char procname_buffer[2048];
  214. unw_cursor_t cursor;
  215. unw_context_t uc;
  216. unw_word_t ip;
  217. unw_getcontext(&uc);
  218. unw_init_local(&cursor, &uc);
  219. unw_word_t offp;
  220. while (unw_step(&cursor) > 0) {
  221. unw_get_reg(&cursor, UNW_REG_IP, &ip);
  222. unw_get_proc_name(&cursor, procname_buffer, sizeof(procname_buffer), &offp);
  223. int status;
  224. char *demangled = my_demangle(procname_buffer, &status);
  225. my_safe_printf_stderr("[0x%lx] %s+0x%lx\n", ip,
  226. demangled ? demangled : procname_buffer, offp);
  227. if (demangled) free(demangled);
  228. }
  229. #endif
  230. void *addrs[128];
  231. char **strings = NULL;
  232. int n = backtrace(addrs, array_elements(addrs));
  233. my_safe_printf_stderr("stack_bottom = %p thread_stack 0x%lx\n", stack_bottom,
  234. thread_stack);
  235. #ifdef HAVE_ABI_CXA_DEMANGLE
  236. if ((strings = backtrace_symbols(addrs, n))) {
  237. my_demangle_symbols(strings, n);
  238. free(strings);
  239. }
  240. #endif
  241. if (!strings) {
  242. backtrace_symbols_fd(addrs, n, fileno(stderr));
  243. }
  244. }
  245. #endif /* HAVE_BACKTRACE */
  246. #endif /* HAVE_STACKTRACE */
  247. /* Produce a core for the thread */
  248. void my_write_core(int sig) {
  249. signal(sig, SIG_DFL);
  250. pthread_kill(my_thread_self(), sig);
  251. #if defined(P_MYID)
  252. /* On Solaris, the above kill is not enough */
  253. sigsend(P_PID, P_MYID, sig);
  254. #endif
  255. }
  256. #else /* _WIN32*/
  257. #include <dbghelp.h>
  258. #include <tlhelp32.h>
  259. #if _MSC_VER
  260. #pragma comment(lib, "dbghelp")
  261. #endif
  262. static EXCEPTION_POINTERS *exception_ptrs;
  263. #define MODULE64_SIZE_WINXP 576
  264. #define STACKWALK_MAX_FRAMES 64
  265. void my_init_stacktrace() {}
  266. void my_set_exception_pointers(EXCEPTION_POINTERS *ep) { exception_ptrs = ep; }
  267. /*
  268. Appends directory to symbol path.
  269. */
  270. static void add_to_symbol_path(char *path, size_t path_buffer_size, char *dir,
  271. size_t dir_buffer_size) {
  272. strcat_s(dir, dir_buffer_size, ";");
  273. if (!strstr(path, dir)) {
  274. strcat_s(path, path_buffer_size, dir);
  275. }
  276. }
  277. /*
  278. Get symbol path - semicolon-separated list of directories to search for debug
  279. symbols. We expect PDB in the same directory as corresponding exe or dll,
  280. so the path is build from directories of the loaded modules. If environment
  281. variable _NT_SYMBOL_PATH is set, it's value appended to the symbol search path
  282. */
  283. static void get_symbol_path(char *path, size_t size) {
  284. HANDLE hSnap;
  285. char *envvar;
  286. char *p;
  287. #ifndef DBUG_OFF
  288. static char pdb_debug_dir[MAX_PATH + 7];
  289. #endif
  290. path[0] = '\0';
  291. #ifndef DBUG_OFF
  292. /*
  293. Add "debug" subdirectory of the application directory, sometimes PDB will
  294. placed here by installation.
  295. */
  296. GetModuleFileName(NULL, pdb_debug_dir, MAX_PATH);
  297. p = strrchr(pdb_debug_dir, '\\');
  298. if (p) {
  299. *p = 0;
  300. strcat_s(pdb_debug_dir, sizeof(pdb_debug_dir), "\\debug;");
  301. add_to_symbol_path(path, size, pdb_debug_dir, sizeof(pdb_debug_dir));
  302. }
  303. #endif
  304. /*
  305. Enumerate all modules, and add their directories to the path.
  306. Avoid duplicate entries.
  307. */
  308. hSnap = CreateToolhelp32Snapshot(TH32CS_SNAPMODULE, GetCurrentProcessId());
  309. if (hSnap != INVALID_HANDLE_VALUE) {
  310. BOOL ret;
  311. MODULEENTRY32 mod;
  312. mod.dwSize = sizeof(MODULEENTRY32);
  313. for (ret = Module32First(hSnap, &mod); ret;
  314. ret = Module32Next(hSnap, &mod)) {
  315. char *module_dir = mod.szExePath;
  316. p = strrchr(module_dir, '\\');
  317. if (!p) {
  318. /*
  319. Path separator was not found. Not known to happen, if ever happens,
  320. will indicate current directory.
  321. */
  322. module_dir[0] = '.';
  323. module_dir[1] = '\0';
  324. } else {
  325. *p = '\0';
  326. }
  327. add_to_symbol_path(path, size, module_dir, sizeof(mod.szExePath));
  328. }
  329. CloseHandle(hSnap);
  330. }
  331. /* Add _NT_SYMBOL_PATH, if present. */
  332. envvar = getenv("_NT_SYMBOL_PATH");
  333. if (envvar) {
  334. strcat_s(path, size, envvar);
  335. }
  336. }
  337. #define MAX_SYMBOL_PATH 32768
  338. /* Platform SDK in VS2003 does not have definition for SYMOPT_NO_PROMPTS*/
  339. #ifndef SYMOPT_NO_PROMPTS
  340. #define SYMOPT_NO_PROMPTS 0
  341. #endif
  342. void my_print_stacktrace(uchar *unused1, ulong unused2) {
  343. HANDLE hProcess = GetCurrentProcess();
  344. HANDLE hThread = GetCurrentThread();
  345. static IMAGEHLP_MODULE64 module = {sizeof(module)};
  346. static IMAGEHLP_SYMBOL64_PACKAGE package;
  347. DWORD64 addr;
  348. DWORD machine;
  349. int i;
  350. CONTEXT context;
  351. STACKFRAME64 frame = {0};
  352. static char symbol_path[MAX_SYMBOL_PATH];
  353. if (!exception_ptrs) return;
  354. /* Copy context, as stackwalking on original will unwind the stack */
  355. context = *(exception_ptrs->ContextRecord);
  356. /*Initialize symbols.*/
  357. SymSetOptions(SYMOPT_LOAD_LINES | SYMOPT_NO_PROMPTS | SYMOPT_DEFERRED_LOADS |
  358. SYMOPT_DEBUG);
  359. get_symbol_path(symbol_path, sizeof(symbol_path));
  360. SymInitialize(hProcess, symbol_path, true);
  361. /*Prepare stackframe for the first StackWalk64 call*/
  362. frame.AddrFrame.Mode = frame.AddrPC.Mode = frame.AddrStack.Mode =
  363. AddrModeFlat;
  364. #if (defined _M_X64)
  365. machine = IMAGE_FILE_MACHINE_AMD64;
  366. frame.AddrFrame.Offset = context.Rbp;
  367. frame.AddrPC.Offset = context.Rip;
  368. frame.AddrStack.Offset = context.Rsp;
  369. #else
  370. /*There is currently no need to support IA64*/
  371. #pragma error("unsupported architecture")
  372. #endif
  373. package.sym.SizeOfStruct = sizeof(package.sym);
  374. package.sym.MaxNameLength = sizeof(package.name);
  375. /*Walk the stack, output useful information*/
  376. for (i = 0; i < STACKWALK_MAX_FRAMES; i++) {
  377. DWORD64 function_offset = 0;
  378. DWORD line_offset = 0;
  379. IMAGEHLP_LINE64 line = {sizeof(line)};
  380. BOOL have_module = false;
  381. BOOL have_symbol = false;
  382. BOOL have_source = false;
  383. if (!StackWalk64(machine, hProcess, hThread, &frame, &context, 0, 0, 0, 0))
  384. break;
  385. addr = frame.AddrPC.Offset;
  386. have_module = SymGetModuleInfo64(hProcess, addr, &module);
  387. have_symbol =
  388. SymGetSymFromAddr64(hProcess, addr, &function_offset, &(package.sym));
  389. have_source = SymGetLineFromAddr64(hProcess, addr, &line_offset, &line);
  390. my_safe_printf_stderr("%p ", addr);
  391. if (have_module) {
  392. char *base_image_name = strrchr(module.ImageName, '\\');
  393. if (base_image_name)
  394. base_image_name++;
  395. else
  396. base_image_name = module.ImageName;
  397. my_safe_printf_stderr("%s!", base_image_name);
  398. }
  399. if (have_symbol)
  400. my_safe_printf_stderr("%s()", package.sym.Name);
  401. else if (have_module)
  402. my_safe_printf_stderr("%s", "???");
  403. if (have_source) {
  404. char *base_file_name = strrchr(line.FileName, '\\');
  405. if (base_file_name)
  406. base_file_name++;
  407. else
  408. base_file_name = line.FileName;
  409. my_safe_printf_stderr("[%s:%u]", base_file_name, line.LineNumber);
  410. }
  411. my_safe_printf_stderr("%s", "\n");
  412. }
  413. }
  414. /*
  415. Write dump. The dump is created in current directory,
  416. file name is constructed from executable name plus
  417. ".dmp" extension
  418. */
  419. void my_write_core(int unused) {
  420. char path[MAX_PATH];
  421. // See comment below for clarification about size of dump_fname
  422. char dump_fname[MAX_PATH + 1 + 10 + 4 + 1] = "core.dmp";
  423. if (!exception_ptrs) return;
  424. if (GetModuleFileName(NULL, path, sizeof(path))) {
  425. char module_name[MAX_PATH];
  426. _splitpath(path, NULL, NULL, module_name, NULL);
  427. // max length of a value being placed to dump_fname is
  428. // MAX_PATH + 1 byte for '.' + up to 10 bytes for string
  429. // representation of DWORD value + 4 bytes for .dmp suffix +
  430. // 1 byte for termitated \0. Such size of output buffer guarantees
  431. // that there is enough space to place a result of string formatting
  432. // performed by snprintf().
  433. snprintf(dump_fname, sizeof(dump_fname), "%s.%u.dmp", module_name,
  434. GetCurrentProcessId());
  435. }
  436. my_create_minidump(dump_fname, 0, 0);
  437. }
  438. /** Create a minidump.
  439. @param name path of minidump file.
  440. @param process HANDLE to process. (0 for own process).
  441. @param pid Process id.
  442. */
  443. void my_create_minidump(const char *name, HANDLE process, DWORD pid) {
  444. char path[MAX_PATH];
  445. MINIDUMP_EXCEPTION_INFORMATION info;
  446. PMINIDUMP_EXCEPTION_INFORMATION info_ptr = NULL;
  447. HANDLE hFile;
  448. if (process == 0) {
  449. /* Does not need to CloseHandle() for the below. */
  450. process = GetCurrentProcess();
  451. pid = GetCurrentProcessId();
  452. info.ExceptionPointers = exception_ptrs;
  453. info.ClientPointers = false;
  454. info.ThreadId = GetCurrentThreadId();
  455. info_ptr = &info;
  456. }
  457. hFile = CreateFile(name, GENERIC_WRITE, 0, 0, CREATE_ALWAYS,
  458. FILE_ATTRIBUTE_NORMAL, 0);
  459. if (hFile) {
  460. MINIDUMP_TYPE mdt =
  461. (MINIDUMP_TYPE)(MiniDumpNormal | MiniDumpWithThreadInfo |
  462. MiniDumpWithProcessThreadData);
  463. /* Create minidump, use info only if same process. */
  464. if (MiniDumpWriteDump(process, pid, hFile, mdt, info_ptr, 0, 0)) {
  465. my_safe_printf_stderr("Minidump written to %s\n",
  466. _fullpath(path, name, sizeof(path)) ? path : name);
  467. } else {
  468. my_safe_printf_stderr("MiniDumpWriteDump() failed, last error %d\n",
  469. GetLastError());
  470. }
  471. CloseHandle(hFile);
  472. } else {
  473. my_safe_printf_stderr("CreateFile(%s) failed, last error %d\n", name,
  474. GetLastError());
  475. }
  476. }
  477. void my_safe_puts_stderr(const char *val, size_t len) {
  478. __try {
  479. my_write_stderr(val, len);
  480. my_safe_printf_stderr("%s", "\n");
  481. } __except (EXCEPTION_EXECUTE_HANDLER) {
  482. my_safe_printf_stderr("%s", "is an invalid string pointer\n");
  483. }
  484. }
  485. #endif /* _WIN32 */
  486. #ifdef _WIN32
  487. size_t my_write_stderr(const void *buf, size_t count) {
  488. DWORD bytes_written;
  489. SetFilePointer(GetStdHandle(STD_ERROR_HANDLE), 0, NULL, FILE_END);
  490. WriteFile(GetStdHandle(STD_ERROR_HANDLE), buf, (DWORD)count, &bytes_written,
  491. NULL);
  492. return bytes_written;
  493. }
  494. #else
  495. size_t my_write_stderr(const void *buf, size_t count) {
  496. return (size_t)write(STDERR_FILENO, buf, count);
  497. }
  498. #endif
  499. static const char digits[] = "0123456789abcdef";
  500. char *my_safe_utoa(int base, ulonglong val, char *buf) {
  501. *buf-- = 0;
  502. do {
  503. *buf-- = digits[val % base];
  504. } while ((val /= base) != 0);
  505. return buf + 1;
  506. }
  507. char *my_safe_itoa(int base, longlong val, char *buf) {
  508. char *orig_buf = buf;
  509. const bool is_neg = (val < 0);
  510. *buf-- = 0;
  511. if (is_neg) val = -val;
  512. if (is_neg && base == 16) {
  513. int ix;
  514. val -= 1;
  515. for (ix = 0; ix < 16; ++ix) buf[-ix] = '0';
  516. }
  517. do {
  518. *buf-- = digits[val % base];
  519. } while ((val /= base) != 0);
  520. if (is_neg && base == 10) *buf-- = '-';
  521. if (is_neg && base == 16) {
  522. int ix;
  523. buf = orig_buf - 1;
  524. for (ix = 0; ix < 16; ++ix, --buf) {
  525. switch (*buf) {
  526. case '0':
  527. *buf = 'f';
  528. break;
  529. case '1':
  530. *buf = 'e';
  531. break;
  532. case '2':
  533. *buf = 'd';
  534. break;
  535. case '3':
  536. *buf = 'c';
  537. break;
  538. case '4':
  539. *buf = 'b';
  540. break;
  541. case '5':
  542. *buf = 'a';
  543. break;
  544. case '6':
  545. *buf = '9';
  546. break;
  547. case '7':
  548. *buf = '8';
  549. break;
  550. case '8':
  551. *buf = '7';
  552. break;
  553. case '9':
  554. *buf = '6';
  555. break;
  556. case 'a':
  557. *buf = '5';
  558. break;
  559. case 'b':
  560. *buf = '4';
  561. break;
  562. case 'c':
  563. *buf = '3';
  564. break;
  565. case 'd':
  566. *buf = '2';
  567. break;
  568. case 'e':
  569. *buf = '1';
  570. break;
  571. case 'f':
  572. *buf = '0';
  573. break;
  574. }
  575. }
  576. }
  577. return buf + 1;
  578. }
  579. static const char *check_longlong(const char *fmt, bool *have_longlong) {
  580. *have_longlong = false;
  581. if (*fmt == 'l') {
  582. fmt++;
  583. if (*fmt != 'l')
  584. *have_longlong = (sizeof(long) == sizeof(longlong));
  585. else {
  586. fmt++;
  587. *have_longlong = true;
  588. }
  589. }
  590. return fmt;
  591. }
  592. static size_t my_safe_vsnprintf(char *to, size_t size, const char *format,
  593. va_list ap) {
  594. char *start = to;
  595. char *end = start + size - 1;
  596. for (; *format; ++format) {
  597. bool have_longlong = false;
  598. if (*format != '%') {
  599. if (to == end) /* end of buffer */
  600. break;
  601. *to++ = *format; /* copy ordinary char */
  602. continue;
  603. }
  604. ++format; /* skip '%' */
  605. format = check_longlong(format, &have_longlong);
  606. switch (*format) {
  607. case 'd':
  608. case 'i':
  609. case 'u':
  610. case 'x':
  611. case 'p': {
  612. longlong ival = 0;
  613. ulonglong uval = 0;
  614. if (*format == 'p')
  615. have_longlong = (sizeof(void *) == sizeof(longlong));
  616. if (have_longlong) {
  617. if (*format == 'u')
  618. uval = va_arg(ap, ulonglong);
  619. else
  620. ival = va_arg(ap, longlong);
  621. } else {
  622. if (*format == 'u')
  623. uval = va_arg(ap, unsigned int);
  624. else
  625. ival = va_arg(ap, int);
  626. }
  627. {
  628. char buff[22];
  629. const int base = (*format == 'x' || *format == 'p') ? 16 : 10;
  630. char *val_as_str =
  631. (*format == 'u')
  632. ? my_safe_utoa(base, uval, &buff[sizeof(buff) - 1])
  633. : my_safe_itoa(base, ival, &buff[sizeof(buff) - 1]);
  634. /*
  635. Strip off "ffffffff" if we have 'x' format without 'll'
  636. Similarly for 'p' format on 32bit systems.
  637. */
  638. if (base == 16 && !have_longlong && ival < 0) val_as_str += 8;
  639. while (*val_as_str && to < end) *to++ = *val_as_str++;
  640. continue;
  641. }
  642. }
  643. case 's': {
  644. const char *val = va_arg(ap, char *);
  645. if (!val) val = "(null)";
  646. while (*val && to < end) *to++ = *val++;
  647. continue;
  648. }
  649. }
  650. }
  651. *to = 0;
  652. return to - start;
  653. }
  654. size_t my_safe_snprintf(char *to, size_t n, const char *fmt, ...) {
  655. size_t result;
  656. va_list args;
  657. va_start(args, fmt);
  658. result = my_safe_vsnprintf(to, n, fmt, args);
  659. va_end(args);
  660. return result;
  661. }
  662. size_t my_safe_printf_stderr(const char *fmt, ...) {
  663. char to[512];
  664. size_t result;
  665. va_list args;
  666. va_start(args, fmt);
  667. result = my_safe_vsnprintf(to, sizeof(to), fmt, args);
  668. va_end(args);
  669. my_write_stderr(to, result);
  670. return result;
  671. }
  672. void my_safe_print_system_time() {
  673. char hrs_buf[3] = "00";
  674. char mins_buf[3] = "00";
  675. char secs_buf[3] = "00";
  676. int base = 10;
  677. #ifdef _WIN32
  678. SYSTEMTIME utc_time;
  679. long hrs, mins, secs;
  680. GetSystemTime(&utc_time);
  681. hrs = utc_time.wHour;
  682. mins = utc_time.wMinute;
  683. secs = utc_time.wSecond;
  684. #else
  685. /* Using time() instead of my_time() to avoid looping */
  686. const time_t curr_time = time(NULL);
  687. /* Calculate time of day */
  688. const long tmins = curr_time / 60;
  689. const long thrs = tmins / 60;
  690. const long hrs = thrs % 24;
  691. const long mins = tmins % 60;
  692. const long secs = curr_time % 60;
  693. #endif
  694. my_safe_itoa(base, hrs, &hrs_buf[2]);
  695. my_safe_itoa(base, mins, &mins_buf[2]);
  696. my_safe_itoa(base, secs, &secs_buf[2]);
  697. my_safe_printf_stderr("---------- %s:%s:%s UTC - ", hrs_buf, mins_buf,
  698. secs_buf);
  699. }