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