2 * Copyright 2013-present 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>
22 #include <sys/types.h>
30 #include <glog/logging.h>
32 #include <folly/Conv.h>
33 #include <folly/ScopeGuard.h>
34 #include <folly/experimental/symbolizer/ElfCache.h>
35 #include <folly/experimental/symbolizer/Symbolizer.h>
36 #include <folly/portability/PThread.h>
37 #include <folly/portability/SysSyscall.h>
38 #include <folly/portability/Unistd.h>
41 namespace symbolizer {
46 * Fatal signal handler registry.
48 class FatalSignalCallbackRegistry {
50 FatalSignalCallbackRegistry();
52 void add(SignalCallback func);
57 std::atomic<bool> installed_;
59 std::vector<SignalCallback> handlers_;
62 FatalSignalCallbackRegistry::FatalSignalCallbackRegistry()
63 : installed_(false) {}
65 void FatalSignalCallbackRegistry::add(SignalCallback func) {
66 std::lock_guard<std::mutex> lock(mutex_);
67 CHECK(!installed_) << "FatalSignalCallbackRegistry::add may not be used "
68 "after installing the signal handlers.";
69 handlers_.push_back(func);
72 void FatalSignalCallbackRegistry::markInstalled() {
73 std::lock_guard<std::mutex> lock(mutex_);
74 CHECK(!installed_.exchange(true))
75 << "FatalSignalCallbackRegistry::markInstalled must be called "
79 void FatalSignalCallbackRegistry::run() {
84 for (auto& fn : handlers_) {
89 // Leak it so we don't have to worry about destruction order
90 FatalSignalCallbackRegistry* gFatalSignalCallbackRegistry =
91 new FatalSignalCallbackRegistry;
96 struct sigaction oldAction;
98 {SIGSEGV, "SIGSEGV", {}},
99 {SIGILL, "SIGILL", {}},
100 {SIGFPE, "SIGFPE", {}},
101 {SIGABRT, "SIGABRT", {}},
102 {SIGBUS, "SIGBUS", {}},
103 {SIGTERM, "SIGTERM", {}},
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);
119 // Not one of the signals we know about. Oh well. Reset to default.
121 memset(&sa, 0, sizeof(sa));
122 sa.sa_handler = SIG_DFL;
123 sigaction(signum, &sa, nullptr);
127 // Note: not thread-safe, but that's okay, as we only let one thread
128 // in our signal handler at a time.
130 // Leak it so we don't have to worry about destruction order
131 StackTracePrinter* gStackTracePrinter = new StackTracePrinter();
133 void printDec(uint64_t val) {
135 uint32_t n = uint64ToBufferUnsafe(val, buf);
136 gStackTracePrinter->print(StringPiece(buf, n));
139 const char kHexChars[] = "0123456789abcdef";
140 void printHex(uint64_t val) {
141 // TODO(tudorb): Add this to folly/Conv.h
142 char buf[2 + 2 * sizeof(uint64_t)]; // "0x" prefix, 2 digits for each byte
144 char* end = buf + sizeof(buf);
147 *--p = kHexChars[val & 0x0f];
153 gStackTracePrinter->print(StringPiece(p, end));
156 void print(StringPiece sp) {
157 gStackTracePrinter->print(sp);
161 gStackTracePrinter->flush();
164 void dumpTimeInfo() {
168 time_t now = time(nullptr);
169 print("*** Aborted at ");
171 print(" (Unix time, try 'date -d @");
176 const char* sigill_reason(int si_code) {
179 return "illegal opcode";
181 return "illegal operand";
183 return "illegal addressing mode";
185 return "illegal trap";
187 return "privileged opcode";
189 return "privileged register";
191 return "coprocessor error";
193 return "internal stack error";
200 const char* sigfpe_reason(int si_code) {
203 return "integer divide by zero";
205 return "integer overflow";
207 return "floating-point divide by zero";
209 return "floating-point overflow";
211 return "floating-point underflow";
213 return "floating-point inexact result";
215 return "floating-point invalid operation";
217 return "subscript out of range";
224 const char* sigsegv_reason(int si_code) {
227 return "address not mapped to object";
229 return "invalid permissions for mapped object";
236 const char* sigbus_reason(int si_code) {
239 return "invalid address alignment";
241 return "nonexistent physical address";
243 return "object-specific hardware error";
245 // MCEERR_AR and MCEERR_AO: in sigaction(2) but not in headers.
252 const char* sigtrap_reason(int si_code) {
255 return "process breakpoint";
257 return "process trace trap";
259 // TRAP_BRANCH and TRAP_HWBKPT: in sigaction(2) but not in headers.
266 const char* sigchld_reason(int si_code) {
269 return "child has exited";
271 return "child was killed";
273 return "child terminated abnormally";
275 return "traced child has trapped";
277 return "child has stopped";
279 return "stopped child has continued";
286 const char* sigio_reason(int si_code) {
289 return "data input available";
291 return "output buffers available";
293 return "input message available";
297 return "high priority input available";
299 return "device disconnected";
306 const char* signal_reason(int signum, int si_code) {
309 return sigill_reason(si_code);
311 return sigfpe_reason(si_code);
313 return sigsegv_reason(si_code);
315 return sigbus_reason(si_code);
317 return sigtrap_reason(si_code);
319 return sigchld_reason(si_code);
321 return sigio_reason(si_code); // aka SIGPOLL
328 void dumpSignalInfo(int signum, siginfo_t* siginfo) {
332 // Get the signal name, if possible.
333 const char* name = nullptr;
334 for (auto p = kFatalSignals; p->name; ++p) {
335 if (p->number == signum) {
341 print("*** Signal ");
350 printHex(reinterpret_cast<uint64_t>(siginfo->si_addr));
351 print(") received by PID ");
353 print(" (pthread TID ");
354 printHex((uint64_t)pthread_self());
355 print(") (linux TID ");
356 printDec(syscall(__NR_gettid));
358 // Kernel-sourced signals don't give us useful info for pid/uid.
359 if (siginfo->si_code != SI_KERNEL) {
360 print(") (maybe from PID ");
361 printDec(siginfo->si_pid);
363 printDec(siginfo->si_uid);
366 auto reason = signal_reason(signum, siginfo->si_code);
368 if (reason != nullptr) {
373 print("), stack trace: ***\n");
376 // On Linux, pthread_t is a pointer, so 0 is an invalid value, which we
377 // take to indicate "no thread in the signal handler".
379 // POSIX defines PTHREAD_NULL for this purpose, but that's not available.
380 constexpr pthread_t kInvalidThreadId = 0;
382 std::atomic<pthread_t> gSignalThread(kInvalidThreadId);
383 std::atomic<bool> gInRecursiveSignalHandler(false);
386 void innerSignalHandler(int signum, siginfo_t* info, void* /* uctx */) {
387 // First, let's only let one thread in here at a time.
388 pthread_t myId = pthread_self();
390 pthread_t prevSignalThread = kInvalidThreadId;
391 while (!gSignalThread.compare_exchange_strong(prevSignalThread, myId)) {
392 if (pthread_equal(prevSignalThread, myId)) {
393 // First time here. Try to dump the stack trace without symbolization.
394 // If we still fail, well, we're mightily screwed, so we do nothing the
396 if (!gInRecursiveSignalHandler.exchange(true)) {
397 print("Entered fatal signal handler recursively. We're in trouble.\n");
398 gStackTracePrinter->printStackTrace(false); // no symbolization
403 // Wait a while, try again.
406 ts.tv_nsec = 100L * 1000 * 1000; // 100ms
407 nanosleep(&ts, nullptr);
409 prevSignalThread = kInvalidThreadId;
413 dumpSignalInfo(signum, info);
414 gStackTracePrinter->printStackTrace(true); // with symbolization
416 // Run user callbacks
417 gFatalSignalCallbackRegistry->run();
420 void signalHandler(int signum, siginfo_t* info, void* uctx) {
424 innerSignalHandler(signum, info, uctx);
426 gSignalThread = kInvalidThreadId;
427 // Kill ourselves with the previous handler.
428 callPreviousSignalHandler(signum);
433 void addFatalSignalCallback(SignalCallback cb) {
434 gFatalSignalCallbackRegistry->add(cb);
437 void installFatalSignalCallbacks() {
438 gFatalSignalCallbackRegistry->markInstalled();
443 std::atomic<bool> gAlreadyInstalled;
447 void installFatalSignalHandler() {
448 if (gAlreadyInstalled.exchange(true)) {
454 memset(&sa, 0, sizeof(sa));
455 sigemptyset(&sa.sa_mask);
456 // By default signal handlers are run on the signaled thread's stack.
457 // In case of stack overflow running the SIGSEGV signal handler on
458 // the same stack leads to another SIGSEGV and crashes the program.
459 // Use SA_ONSTACK, so alternate stack is used (only if configured via
461 sa.sa_flags |= SA_SIGINFO | SA_ONSTACK;
462 sa.sa_sigaction = &signalHandler;
464 for (auto p = kFatalSignals; p->name; ++p) {
465 CHECK_ERR(sigaction(p->number, &sa, &p->oldAction));
468 } // namespace symbolizer