2 * Copyright 2017 Facebook, Inc.
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
8 * http://www.apache.org/licenses/LICENSE-2.0
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.
17 // This is heavily inspired by the signal handler from google-glog
19 #include <folly/experimental/symbolizer/SignalHandler.h>
23 #include <sys/types.h>
32 #include <glog/logging.h>
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>
42 namespace folly { namespace symbolizer {
47 * Fatal signal handler registry.
49 class FatalSignalCallbackRegistry {
51 FatalSignalCallbackRegistry();
53 void add(SignalCallback func);
58 std::atomic<bool> installed_;
60 std::vector<SignalCallback> handlers_;
63 FatalSignalCallbackRegistry::FatalSignalCallbackRegistry()
67 void FatalSignalCallbackRegistry::add(SignalCallback func) {
68 std::lock_guard<std::mutex> lock(mutex_);
70 << "FatalSignalCallbackRegistry::add may not be used "
71 "after installing the signal handlers.";
72 handlers_.push_back(func);
75 void FatalSignalCallbackRegistry::markInstalled() {
76 std::lock_guard<std::mutex> lock(mutex_);
77 CHECK(!installed_.exchange(true))
78 << "FatalSignalCallbackRegistry::markInstalled must be called "
82 void FatalSignalCallbackRegistry::run() {
87 for (auto& fn : handlers_) {
92 // Leak it so we don't have to worry about destruction order
93 FatalSignalCallbackRegistry* gFatalSignalCallbackRegistry =
94 new FatalSignalCallbackRegistry;
99 struct sigaction oldAction;
100 } kFatalSignals[] = {
101 { SIGSEGV, "SIGSEGV", {} },
102 { SIGILL, "SIGILL", {} },
103 { SIGFPE, "SIGFPE", {} },
104 { SIGABRT, "SIGABRT", {} },
105 { SIGBUS, "SIGBUS", {} },
106 { SIGTERM, "SIGTERM", {} },
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);
122 // Not one of the signals we know about. Oh well. Reset to default.
124 memset(&sa, 0, sizeof(sa));
125 sa.sa_handler = SIG_DFL;
126 sigaction(signum, &sa, nullptr);
130 // Note: not thread-safe, but that's okay, as we only let one thread
131 // in our signal handler at a time.
133 // Leak it so we don't have to worry about destruction order
134 StackTracePrinter* gStackTracePrinter = new StackTracePrinter();
136 void printDec(uint64_t val) {
138 uint32_t n = uint64ToBufferUnsafe(val, buf);
139 gStackTracePrinter->print(StringPiece(buf, n));
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
147 char* end = buf + sizeof(buf);
150 *--p = kHexChars[val & 0x0f];
156 gStackTracePrinter->print(StringPiece(p, end));
159 void print(StringPiece sp) {
160 gStackTracePrinter->print(sp);
164 gStackTracePrinter->flush();
167 void dumpTimeInfo() {
168 SCOPE_EXIT { flush(); };
169 time_t now = time(nullptr);
170 print("*** Aborted at ");
172 print(" (Unix time, try 'date -d @");
177 const char* sigill_reason(int si_code) {
180 return "illegal opcode";
182 return "illegal operand";
184 return "illegal addressing mode";
186 return "illegal trap";
188 return "privileged opcode";
190 return "privileged register";
192 return "coprocessor error";
194 return "internal stack error";
201 const char* sigfpe_reason(int si_code) {
204 return "integer divide by zero";
206 return "integer overflow";
208 return "floating-point divide by zero";
210 return "floating-point overflow";
212 return "floating-point underflow";
214 return "floating-point inexact result";
216 return "floating-point invalid operation";
218 return "subscript out of range";
225 const char* sigsegv_reason(int si_code) {
228 return "address not mapped to object";
230 return "invalid permissions for mapped object";
237 const char* sigbus_reason(int si_code) {
240 return "invalid address alignment";
242 return "nonexistent physical address";
244 return "object-specific hardware error";
246 // MCEERR_AR and MCEERR_AO: in sigaction(2) but not in headers.
253 const char* sigtrap_reason(int si_code) {
256 return "process breakpoint";
258 return "process trace trap";
260 // TRAP_BRANCH and TRAP_HWBKPT: in sigaction(2) but not in headers.
267 const char* sigchld_reason(int si_code) {
270 return "child has exited";
272 return "child was killed";
274 return "child terminated abnormally";
276 return "traced child has trapped";
278 return "child has stopped";
280 return "stopped child has continued";
287 const char* sigio_reason(int si_code) {
290 return "data input available";
292 return "output buffers available";
294 return "input message available";
298 return "high priority input available";
300 return "device disconnected";
307 const char* signal_reason(int signum, int si_code) {
310 return sigill_reason(si_code);
312 return sigfpe_reason(si_code);
314 return sigsegv_reason(si_code);
316 return sigbus_reason(si_code);
318 return sigtrap_reason(si_code);
320 return sigchld_reason(si_code);
322 return sigio_reason(si_code); // aka SIGPOLL
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) {
340 print("*** Signal ");
349 printHex(reinterpret_cast<uint64_t>(siginfo->si_addr));
350 print(") received by PID ");
352 print(" (pthread TID ");
353 printHex((uint64_t)pthread_self());
354 print(") (linux TID ");
355 printDec(syscall(__NR_gettid));
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);
362 printDec(siginfo->si_uid);
365 auto reason = signal_reason(signum, siginfo->si_code);
367 if (reason != nullptr) {
372 print("), stack trace: ***\n");
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".
378 // POSIX defines PTHREAD_NULL for this purpose, but that's not available.
379 constexpr pthread_t kInvalidThreadId = 0;
381 std::atomic<pthread_t> gSignalThread(kInvalidThreadId);
382 std::atomic<bool> gInRecursiveSignalHandler(false);
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();
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
395 if (!gInRecursiveSignalHandler.exchange(true)) {
396 print("Entered fatal signal handler recursively. We're in trouble.\n");
397 gStackTracePrinter->printStackTrace(false); // no symbolization
402 // Wait a while, try again.
405 ts.tv_nsec = 100L * 1000 * 1000; // 100ms
406 nanosleep(&ts, nullptr);
408 prevSignalThread = kInvalidThreadId;
412 dumpSignalInfo(signum, info);
413 gStackTracePrinter->printStackTrace(true); // with symbolization
415 // Run user callbacks
416 gFatalSignalCallbackRegistry->run();
419 void signalHandler(int signum, siginfo_t* info, void* uctx) {
420 SCOPE_EXIT { flush(); };
421 innerSignalHandler(signum, info, uctx);
423 gSignalThread = kInvalidThreadId;
424 // Kill ourselves with the previous handler.
425 callPreviousSignalHandler(signum);
430 void addFatalSignalCallback(SignalCallback cb) {
431 gFatalSignalCallbackRegistry->add(cb);
434 void installFatalSignalCallbacks() {
435 gFatalSignalCallbackRegistry->markInstalled();
440 std::atomic<bool> gAlreadyInstalled;
444 void installFatalSignalHandler() {
445 if (gAlreadyInstalled.exchange(true)) {
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
458 sa.sa_flags |= SA_SIGINFO | SA_ONSTACK;
459 sa.sa_sigaction = &signalHandler;
461 for (auto p = kFatalSignals; p->name; ++p) {
462 CHECK_ERR(sigaction(p->number, &sa, &p->oldAction));