Expose folly::symbolizer::dumpStackTrace().
[folly.git] / folly / experimental / symbolizer / SignalHandler.cpp
1 /*
2  * Copyright 2016 Facebook, Inc.
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *   http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16
17 // This is heavily inspired by the signal handler from google-glog
18
19 #include <folly/experimental/symbolizer/SignalHandler.h>
20
21 #include <pthread.h>
22 #include <signal.h>
23 #include <sys/types.h>
24 #include <unistd.h>
25
26 #include <algorithm>
27 #include <atomic>
28 #include <ctime>
29 #include <mutex>
30 #include <vector>
31
32 #include <glog/logging.h>
33
34 #include <folly/Conv.h>
35 #include <folly/FileUtil.h>
36 #include <folly/Portability.h>
37 #include <folly/ScopeGuard.h>
38 #include <folly/experimental/symbolizer/ElfCache.h>
39 #include <folly/experimental/symbolizer/Symbolizer.h>
40 #include <folly/portability/SysSyscall.h>
41
42 namespace folly { namespace symbolizer {
43
44 namespace {
45
46 /**
47  * Fatal signal handler registry.
48  */
49 class FatalSignalCallbackRegistry {
50  public:
51   FatalSignalCallbackRegistry();
52
53   void add(SignalCallback func);
54   void markInstalled();
55   void run();
56
57  private:
58   std::atomic<bool> installed_;
59   std::mutex mutex_;
60   std::vector<SignalCallback> handlers_;
61 };
62
63 FatalSignalCallbackRegistry::FatalSignalCallbackRegistry()
64   : installed_(false) {
65 }
66
67 void FatalSignalCallbackRegistry::add(SignalCallback func) {
68   std::lock_guard<std::mutex> lock(mutex_);
69   CHECK(!installed_)
70     << "FatalSignalCallbackRegistry::add may not be used "
71        "after installing the signal handlers.";
72   handlers_.push_back(func);
73 }
74
75 void FatalSignalCallbackRegistry::markInstalled() {
76   std::lock_guard<std::mutex> lock(mutex_);
77   CHECK(!installed_.exchange(true))
78     << "FatalSignalCallbackRegistry::markInstalled must be called "
79     << "at most once";
80 }
81
82 void FatalSignalCallbackRegistry::run() {
83   if (!installed_) {
84     return;
85   }
86
87   for (auto& fn : handlers_) {
88     fn();
89   }
90 }
91
92 // Leak it so we don't have to worry about destruction order
93 FatalSignalCallbackRegistry* gFatalSignalCallbackRegistry =
94   new FatalSignalCallbackRegistry;
95
96 struct {
97   int number;
98   const char* name;
99   struct sigaction oldAction;
100 } kFatalSignals[] = {
101   { SIGSEGV, "SIGSEGV", {} },
102   { SIGILL,  "SIGILL",  {} },
103   { SIGFPE,  "SIGFPE",  {} },
104   { SIGABRT, "SIGABRT", {} },
105   { SIGBUS,  "SIGBUS",  {} },
106   { SIGTERM, "SIGTERM", {} },
107   { 0,       nullptr,   {} }
108 };
109
110 void callPreviousSignalHandler(int signum) {
111   // Restore disposition to old disposition, then kill ourselves with the same
112   // signal. The signal will be blocked until we return from our handler,
113   // then it will invoke the default handler and abort.
114   for (auto p = kFatalSignals; p->name; ++p) {
115     if (p->number == signum) {
116       sigaction(signum, &p->oldAction, nullptr);
117       raise(signum);
118       return;
119     }
120   }
121
122   // Not one of the signals we know about. Oh well. Reset to default.
123   struct sigaction sa;
124   memset(&sa, 0, sizeof(sa));
125   sa.sa_handler = SIG_DFL;
126   sigaction(signum, &sa, nullptr);
127   raise(signum);
128 }
129
130 // Note: not thread-safe, but that's okay, as we only let one thread
131 // in our signal handler at a time.
132 //
133 // Leak it so we don't have to worry about destruction order
134 StackTracePrinter* gStackTracePrinter = new StackTracePrinter();
135
136 void printDec(uint64_t val) {
137   char buf[20];
138   uint32_t n = uint64ToBufferUnsafe(val, buf);
139   gStackTracePrinter->print(StringPiece(buf, n));
140 }
141
142 const char kHexChars[] = "0123456789abcdef";
143 void printHex(uint64_t val) {
144   // TODO(tudorb): Add this to folly/Conv.h
145   char buf[2 + 2 * sizeof(uint64_t)];  // "0x" prefix, 2 digits for each byte
146
147   char* end = buf + sizeof(buf);
148   char* p = end;
149   do {
150     *--p = kHexChars[val & 0x0f];
151     val >>= 4;
152   } while (val != 0);
153   *--p = 'x';
154   *--p = '0';
155
156   gStackTracePrinter->print(StringPiece(p, end));
157 }
158
159 void print(StringPiece sp) {
160   gStackTracePrinter->print(sp);
161 }
162
163 void flush() {
164   gStackTracePrinter->flush();
165 }
166
167 void dumpTimeInfo() {
168   SCOPE_EXIT { flush(); };
169   time_t now = time(nullptr);
170   print("*** Aborted at ");
171   printDec(now);
172   print(" (Unix time, try 'date -d @");
173   printDec(now);
174   print("') ***\n");
175 }
176
177 const char* sigill_reason(int si_code) {
178   switch (si_code) {
179     case ILL_ILLOPC:
180       return "illegal opcode";
181     case ILL_ILLOPN:
182       return "illegal operand";
183     case ILL_ILLADR:
184       return "illegal addressing mode";
185     case ILL_ILLTRP:
186       return "illegal trap";
187     case ILL_PRVOPC:
188       return "privileged opcode";
189     case ILL_PRVREG:
190       return "privileged register";
191     case ILL_COPROC:
192       return "coprocessor error";
193     case ILL_BADSTK:
194       return "internal stack error";
195
196     default:
197       return nullptr;
198   }
199 }
200
201 const char* sigfpe_reason(int si_code) {
202   switch (si_code) {
203     case FPE_INTDIV:
204       return "integer divide by zero";
205     case FPE_INTOVF:
206       return "integer overflow";
207     case FPE_FLTDIV:
208       return "floating-point divide by zero";
209     case FPE_FLTOVF:
210       return "floating-point overflow";
211     case FPE_FLTUND:
212       return "floating-point underflow";
213     case FPE_FLTRES:
214       return "floating-point inexact result";
215     case FPE_FLTINV:
216       return "floating-point invalid operation";
217     case FPE_FLTSUB:
218       return "subscript out of range";
219
220     default:
221       return nullptr;
222   }
223 }
224
225 const char* sigsegv_reason(int si_code) {
226   switch (si_code) {
227     case SEGV_MAPERR:
228       return "address not mapped to object";
229     case SEGV_ACCERR:
230       return "invalid permissions for mapped object";
231
232     default:
233       return nullptr;
234   }
235 }
236
237 const char* sigbus_reason(int si_code) {
238   switch (si_code) {
239     case BUS_ADRALN:
240       return "invalid address alignment";
241     case BUS_ADRERR:
242       return "nonexistent physical address";
243     case BUS_OBJERR:
244       return "object-specific hardware error";
245
246     // MCEERR_AR and MCEERR_AO: in sigaction(2) but not in headers.
247
248     default:
249       return nullptr;
250   }
251 }
252
253 const char* sigtrap_reason(int si_code) {
254   switch (si_code) {
255     case TRAP_BRKPT:
256       return "process breakpoint";
257     case TRAP_TRACE:
258       return "process trace trap";
259
260     // TRAP_BRANCH and TRAP_HWBKPT: in sigaction(2) but not in headers.
261
262     default:
263       return nullptr;
264   }
265 }
266
267 const char* sigchld_reason(int si_code) {
268   switch (si_code) {
269     case CLD_EXITED:
270       return "child has exited";
271     case CLD_KILLED:
272       return "child was killed";
273     case CLD_DUMPED:
274       return "child terminated abnormally";
275     case CLD_TRAPPED:
276       return "traced child has trapped";
277     case CLD_STOPPED:
278       return "child has stopped";
279     case CLD_CONTINUED:
280       return "stopped child has continued";
281
282     default:
283       return nullptr;
284   }
285 }
286
287 const char* sigio_reason(int si_code) {
288   switch (si_code) {
289     case POLL_IN:
290       return "data input available";
291     case POLL_OUT:
292       return "output buffers available";
293     case POLL_MSG:
294       return "input message available";
295     case POLL_ERR:
296       return "I/O error";
297     case POLL_PRI:
298       return "high priority input available";
299     case POLL_HUP:
300       return "device disconnected";
301
302     default:
303       return nullptr;
304   }
305 }
306
307 const char* signal_reason(int signum, int si_code) {
308   switch (signum) {
309     case SIGILL:
310       return sigill_reason(si_code);
311     case SIGFPE:
312       return sigfpe_reason(si_code);
313     case SIGSEGV:
314       return sigsegv_reason(si_code);
315     case SIGBUS:
316       return sigbus_reason(si_code);
317     case SIGTRAP:
318       return sigtrap_reason(si_code);
319     case SIGCHLD:
320       return sigchld_reason(si_code);
321     case SIGIO:
322       return sigio_reason(si_code); // aka SIGPOLL
323
324     default:
325       return nullptr;
326   }
327 }
328
329 void dumpSignalInfo(int signum, siginfo_t* siginfo) {
330   SCOPE_EXIT { flush(); };
331   // Get the signal name, if possible.
332   const char* name = nullptr;
333   for (auto p = kFatalSignals; p->name; ++p) {
334     if (p->number == signum) {
335       name = p->name;
336       break;
337     }
338   }
339
340   print("*** Signal ");
341   printDec(signum);
342   if (name) {
343     print(" (");
344     print(name);
345     print(")");
346   }
347
348   print(" (");
349   printHex(reinterpret_cast<uint64_t>(siginfo->si_addr));
350   print(") received by PID ");
351   printDec(getpid());
352   print(" (pthread TID ");
353   printHex((uint64_t)pthread_self());
354   print(") (linux TID ");
355   printDec(syscall(__NR_gettid));
356
357   // Kernel-sourced signals don't give us useful info for pid/uid.
358   if (siginfo->si_code != SI_KERNEL) {
359     print(") (maybe from PID ");
360     printDec(siginfo->si_pid);
361     print(", UID ");
362     printDec(siginfo->si_uid);
363   }
364
365   auto reason = signal_reason(signum, siginfo->si_code);
366
367   if (reason != nullptr) {
368     print(") (code: ");
369     print(reason);
370   }
371
372   print("), stack trace: ***\n");
373 }
374
375 // On Linux, pthread_t is a pointer, so 0 is an invalid value, which we
376 // take to indicate "no thread in the signal handler".
377 //
378 // POSIX defines PTHREAD_NULL for this purpose, but that's not available.
379 constexpr pthread_t kInvalidThreadId = 0;
380
381 std::atomic<pthread_t> gSignalThread(kInvalidThreadId);
382 std::atomic<bool> gInRecursiveSignalHandler(false);
383
384 // Here be dragons.
385 void innerSignalHandler(int signum, siginfo_t* info, void* /* uctx */) {
386   // First, let's only let one thread in here at a time.
387   pthread_t myId = pthread_self();
388
389   pthread_t prevSignalThread = kInvalidThreadId;
390   while (!gSignalThread.compare_exchange_strong(prevSignalThread, myId)) {
391     if (pthread_equal(prevSignalThread, myId)) {
392       // First time here. Try to dump the stack trace without symbolization.
393       // If we still fail, well, we're mightily screwed, so we do nothing the
394       // next time around.
395       if (!gInRecursiveSignalHandler.exchange(true)) {
396         print("Entered fatal signal handler recursively. We're in trouble.\n");
397         gStackTracePrinter->printStackTrace(false); // no symbolization
398       }
399       return;
400     }
401
402     // Wait a while, try again.
403     timespec ts;
404     ts.tv_sec = 0;
405     ts.tv_nsec = 100L * 1000 * 1000;  // 100ms
406     nanosleep(&ts, nullptr);
407
408     prevSignalThread = kInvalidThreadId;
409   }
410
411   dumpTimeInfo();
412   dumpSignalInfo(signum, info);
413   gStackTracePrinter->printStackTrace(true); // with symbolization
414
415   // Run user callbacks
416   gFatalSignalCallbackRegistry->run();
417 }
418
419 void signalHandler(int signum, siginfo_t* info, void* uctx) {
420   SCOPE_EXIT { flush(); };
421   innerSignalHandler(signum, info, uctx);
422
423   gSignalThread = kInvalidThreadId;
424   // Kill ourselves with the previous handler.
425   callPreviousSignalHandler(signum);
426 }
427
428 }  // namespace
429
430 void addFatalSignalCallback(SignalCallback cb) {
431   gFatalSignalCallbackRegistry->add(cb);
432 }
433
434 void installFatalSignalCallbacks() {
435   gFatalSignalCallbackRegistry->markInstalled();
436 }
437
438 namespace {
439
440 std::atomic<bool> gAlreadyInstalled;
441
442 }  // namespace
443
444 void installFatalSignalHandler() {
445   if (gAlreadyInstalled.exchange(true)) {
446     // Already done.
447     return;
448   }
449
450   struct sigaction sa;
451   memset(&sa, 0, sizeof(sa));
452   sigemptyset(&sa.sa_mask);
453   // By default signal handlers are run on the signaled thread's stack.
454   // In case of stack overflow running the SIGSEGV signal handler on
455   // the same stack leads to another SIGSEGV and crashes the program.
456   // Use SA_ONSTACK, so alternate stack is used (only if configured via
457   // sigaltstack).
458   sa.sa_flags |= SA_SIGINFO | SA_ONSTACK;
459   sa.sa_sigaction = &signalHandler;
460
461   for (auto p = kFatalSignals; p->name; ++p) {
462     CHECK_ERR(sigaction(p->number, &sa, &p->oldAction));
463   }
464 }
465
466 }}  // namespaces