backtrace.c 9.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363
  1. /* Copyright (c) 2013-2019, The Tor Project, Inc. */
  2. /* See LICENSE for licensing information */
  3. /**
  4. * \file backtrace.c
  5. *
  6. * \brief Functions to produce backtraces on bugs, crashes, or assertion
  7. * failures.
  8. *
  9. * Currently, we've only got an implementation here using the backtrace()
  10. * family of functions, which are sometimes provided by libc and sometimes
  11. * provided by libexecinfo. We tie into the sigaction() backend in order to
  12. * detect crashes.
  13. *
  14. * This is one of the lowest-level modules, since nearly everything needs to
  15. * be able to log an error. As such, it doesn't call the log module or any
  16. * other higher-level modules directly.
  17. */
  18. #include "orconfig.h"
  19. #include "lib/err/torerr.h"
  20. #ifdef HAVE_EXECINFO_H
  21. #include <execinfo.h>
  22. #endif
  23. #ifdef HAVE_FCNTL_H
  24. #include <fcntl.h>
  25. #endif
  26. #ifdef HAVE_UNISTD_H
  27. #include <unistd.h>
  28. #endif
  29. #ifdef HAVE_SIGNAL_H
  30. #include <signal.h>
  31. #endif
  32. #ifdef HAVE_SYS_PARAM_H
  33. #include <sys/param.h>
  34. #endif
  35. #include <errno.h>
  36. #include <stdlib.h>
  37. #include <string.h>
  38. #include <stdio.h>
  39. #ifdef HAVE_CYGWIN_SIGNAL_H
  40. #include <cygwin/signal.h>
  41. #elif defined(HAVE_SYS_UCONTEXT_H)
  42. #include <sys/ucontext.h>
  43. #elif defined(HAVE_UCONTEXT_H)
  44. #include <ucontext.h>
  45. #endif /* defined(HAVE_CYGWIN_SIGNAL_H) || ... */
  46. #ifdef HAVE_PTHREAD_H
  47. #include <pthread.h>
  48. #endif
  49. #include "lib/cc/ctassert.h"
  50. #define EXPOSE_CLEAN_BACKTRACE
  51. #include "lib/err/backtrace.h"
  52. #include "lib/err/torerr.h"
  53. #if defined(HAVE_EXECINFO_H) && defined(HAVE_BACKTRACE) && \
  54. defined(HAVE_BACKTRACE_SYMBOLS_FD) && defined(HAVE_SIGACTION) && \
  55. defined(HAVE_PTHREAD_H)
  56. #define USE_BACKTRACE
  57. #endif
  58. #if !defined(USE_BACKTRACE)
  59. #define NO_BACKTRACE_IMPL
  60. #endif
  61. // Redundant with util.h, but doing it here so we can avoid that dependency.
  62. #define raw_free free
  63. /** Version of Tor to report in backtrace messages. */
  64. static char bt_version[128] = "";
  65. #ifdef USE_BACKTRACE
  66. /** Largest stack depth to try to dump. */
  67. #define MAX_DEPTH 256
  68. /** The size of the callback buffer, so we can clear it in unlock_cb_buf(). */
  69. #define SIZEOF_CB_BUF (MAX_DEPTH * sizeof(void *))
  70. /** Protects cb_buf from concurrent access. Pthreads, since this code
  71. * is Unix-only, and since this code needs to be lowest-level. */
  72. static pthread_mutex_t cb_buf_mutex = PTHREAD_MUTEX_INITIALIZER;
  73. /** Lock and return a static stack pointer buffer that can hold up to
  74. * MAX_DEPTH function pointers. */
  75. static void *
  76. lock_cb_buf(void)
  77. {
  78. /* Lock the mutex first, before even declaring the buffer. */
  79. pthread_mutex_lock(&cb_buf_mutex);
  80. /** Static allocation of stack to dump. This is static so we avoid stack
  81. * pressure. */
  82. static void *cb_buf[MAX_DEPTH];
  83. CTASSERT(SIZEOF_CB_BUF == sizeof(cb_buf));
  84. memset(cb_buf, 0, SIZEOF_CB_BUF);
  85. return cb_buf;
  86. }
  87. /** Unlock the static stack pointer buffer. */
  88. static void
  89. unlock_cb_buf(void *cb_buf)
  90. {
  91. memset(cb_buf, 0, SIZEOF_CB_BUF);
  92. pthread_mutex_unlock(&cb_buf_mutex);
  93. }
  94. /** Change a stacktrace in <b>stack</b> of depth <b>depth</b> so that it will
  95. * log the correct function from which a signal was received with context
  96. * <b>ctx</b>. (When we get a signal, the current function will not have
  97. * called any other function, and will therefore have not pushed its address
  98. * onto the stack. Fortunately, we usually have the program counter in the
  99. * ucontext_t structure.
  100. */
  101. void
  102. clean_backtrace(void **stack, size_t depth, const ucontext_t *ctx)
  103. {
  104. #ifdef PC_FROM_UCONTEXT
  105. #if defined(__linux__)
  106. const size_t n = 1;
  107. #elif defined(__darwin__) || defined(__APPLE__) || defined(OpenBSD) \
  108. || defined(__FreeBSD__)
  109. const size_t n = 2;
  110. #else
  111. const size_t n = 1;
  112. #endif /* defined(__linux__) || ... */
  113. if (depth <= n)
  114. return;
  115. stack[n] = (void*) ctx->PC_FROM_UCONTEXT;
  116. #else /* !(defined(PC_FROM_UCONTEXT)) */
  117. (void) depth;
  118. (void) ctx;
  119. (void) stack;
  120. #endif /* defined(PC_FROM_UCONTEXT) */
  121. }
  122. /** Log a message <b>msg</b> at <b>severity</b> in <b>domain</b>, and follow
  123. * that with a backtrace log. Send messages via the tor_log function at
  124. * logger". */
  125. void
  126. log_backtrace_impl(int severity, log_domain_mask_t domain, const char *msg,
  127. tor_log_fn logger)
  128. {
  129. size_t depth;
  130. char **symbols;
  131. size_t i;
  132. void *cb_buf = lock_cb_buf();
  133. depth = backtrace(cb_buf, MAX_DEPTH);
  134. symbols = backtrace_symbols(cb_buf, (int)depth);
  135. logger(severity, domain, "%s: %s. Stack trace:", bt_version, msg);
  136. if (!symbols) {
  137. /* LCOV_EXCL_START -- we can't provoke this. */
  138. logger(severity, domain, " Unable to generate backtrace.");
  139. goto done;
  140. /* LCOV_EXCL_STOP */
  141. }
  142. for (i=0; i < depth; ++i) {
  143. logger(severity, domain, " %s", symbols[i]);
  144. }
  145. raw_free(symbols);
  146. done:
  147. unlock_cb_buf(cb_buf);
  148. }
  149. static void crash_handler(int sig, siginfo_t *si, void *ctx_)
  150. __attribute__((noreturn));
  151. /** Signal handler: write a crash message with a stack trace, and die. */
  152. static void
  153. crash_handler(int sig, siginfo_t *si, void *ctx_)
  154. {
  155. char buf[40];
  156. size_t depth;
  157. ucontext_t *ctx = (ucontext_t *) ctx_;
  158. int n_fds, i;
  159. const int *fds = NULL;
  160. void *cb_buf = lock_cb_buf();
  161. (void) si;
  162. depth = backtrace(cb_buf, MAX_DEPTH);
  163. /* Clean up the top stack frame so we get the real function
  164. * name for the most recently failing function. */
  165. clean_backtrace(cb_buf, depth, ctx);
  166. format_dec_number_sigsafe((unsigned)sig, buf, sizeof(buf));
  167. tor_log_err_sigsafe(bt_version, " died: Caught signal ", buf, "\n",
  168. NULL);
  169. n_fds = tor_log_get_sigsafe_err_fds(&fds);
  170. for (i=0; i < n_fds; ++i)
  171. backtrace_symbols_fd(cb_buf, (int)depth, fds[i]);
  172. unlock_cb_buf(cb_buf);
  173. tor_raw_abort_();
  174. }
  175. /** Write a backtrace to all of the emergency-error fds. */
  176. void
  177. dump_stack_symbols_to_error_fds(void)
  178. {
  179. int n_fds, i;
  180. const int *fds = NULL;
  181. size_t depth;
  182. void *cb_buf = lock_cb_buf();
  183. depth = backtrace(cb_buf, MAX_DEPTH);
  184. n_fds = tor_log_get_sigsafe_err_fds(&fds);
  185. for (i=0; i < n_fds; ++i)
  186. backtrace_symbols_fd(cb_buf, (int)depth, fds[i]);
  187. unlock_cb_buf(cb_buf);
  188. }
  189. /* The signals that we want our backtrace handler to trap */
  190. static int trap_signals[] = { SIGSEGV, SIGILL, SIGFPE, SIGBUS, SIGSYS,
  191. SIGIO, -1 };
  192. /** Install signal handlers as needed so that when we crash, we produce a
  193. * useful stack trace. Return 0 on success, -errno on failure. */
  194. static int
  195. install_bt_handler(void)
  196. {
  197. int i, rv=0;
  198. struct sigaction sa;
  199. memset(&sa, 0, sizeof(sa));
  200. sa.sa_sigaction = crash_handler;
  201. sa.sa_flags = SA_SIGINFO;
  202. sigfillset(&sa.sa_mask);
  203. for (i = 0; trap_signals[i] >= 0; ++i) {
  204. if (sigaction(trap_signals[i], &sa, NULL) == -1) {
  205. /* LCOV_EXCL_START */
  206. rv = -errno;
  207. /* LCOV_EXCL_STOP */
  208. }
  209. }
  210. {
  211. /* Now, generate (but do not log) a backtrace. This ensures that
  212. * libc has pre-loaded the symbols we need to dump things, so that later
  213. * reads won't be denied by the sandbox code */
  214. char **symbols;
  215. void *cb_buf = lock_cb_buf();
  216. size_t depth = backtrace(cb_buf, MAX_DEPTH);
  217. symbols = backtrace_symbols(cb_buf, (int) depth);
  218. if (symbols)
  219. raw_free(symbols);
  220. unlock_cb_buf(cb_buf);
  221. }
  222. return rv;
  223. }
  224. /** Uninstall crash handlers. */
  225. static void
  226. remove_bt_handler(void)
  227. {
  228. int i;
  229. struct sigaction sa;
  230. memset(&sa, 0, sizeof(sa));
  231. sa.sa_handler = SIG_DFL;
  232. sigfillset(&sa.sa_mask);
  233. for (i = 0; trap_signals[i] >= 0; ++i) {
  234. /* remove_bt_handler() is called on shutdown, from low-level code.
  235. * It's not a fatal error, so we just ignore it. */
  236. (void)sigaction(trap_signals[i], &sa, NULL);
  237. }
  238. /* cb_buf_mutex is statically initialised, so we can not destroy it.
  239. * If we destroy it, and then re-initialise tor, all our backtraces will
  240. * fail. */
  241. }
  242. #endif /* defined(USE_BACKTRACE) */
  243. #ifdef NO_BACKTRACE_IMPL
  244. void
  245. log_backtrace_impl(int severity, log_domain_mask_t domain, const char *msg,
  246. tor_log_fn logger)
  247. {
  248. logger(severity, domain, "%s: %s. (Stack trace not available)",
  249. bt_version, msg);
  250. }
  251. static int
  252. install_bt_handler(void)
  253. {
  254. return 0;
  255. }
  256. static void
  257. remove_bt_handler(void)
  258. {
  259. }
  260. void
  261. dump_stack_symbols_to_error_fds(void)
  262. {
  263. }
  264. #endif /* defined(NO_BACKTRACE_IMPL) */
  265. /** Return the tor version used for error messages on crashes.
  266. * Signal-safe: returns a pointer to a static array. */
  267. const char *
  268. get_tor_backtrace_version(void)
  269. {
  270. return bt_version;
  271. }
  272. /** Set up code to handle generating error messages on crashes. */
  273. int
  274. configure_backtrace_handler(const char *tor_version)
  275. {
  276. char version[128] = "Tor\0";
  277. if (tor_version) {
  278. int snp_rv = 0;
  279. /* We can't use strlcat() here, because it is defined in
  280. * string/compat_string.h on some platforms, and string uses torerr. */
  281. snp_rv = snprintf(version, sizeof(version), "Tor %s", tor_version);
  282. /* It's safe to call raw_assert() here, because raw_assert() does not
  283. * call configure_backtrace_handler(). */
  284. raw_assert(snp_rv < (int)sizeof(version));
  285. raw_assert(snp_rv >= 0);
  286. }
  287. char *str_rv = NULL;
  288. /* We can't use strlcpy() here, see the note about strlcat() above. */
  289. str_rv = strncpy(bt_version, version, sizeof(bt_version) - 1);
  290. /* We must terminate bt_version, then raw_assert(), because raw_assert()
  291. * uses bt_version. */
  292. bt_version[sizeof(bt_version) - 1] = 0;
  293. raw_assert(str_rv == bt_version);
  294. return install_bt_handler();
  295. }
  296. /** Perform end-of-process cleanup for code that generates error messages on
  297. * crashes. */
  298. void
  299. clean_up_backtrace_handler(void)
  300. {
  301. remove_bt_handler();
  302. }