2 * Copyright 2013 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"
21 #include <sys/types.h>
30 #include <glog/logging.h>
32 #include "folly/Conv.h"
33 #include "folly/FileUtil.h"
34 #include "folly/Portability.h"
35 #include "folly/ScopeGuard.h"
36 #include "folly/experimental/symbolizer/Symbolizer.h"
38 namespace folly { namespace symbolizer {
43 * Fatal signal handler registry.
45 class FatalSignalCallbackRegistry {
47 FatalSignalCallbackRegistry();
49 void add(SignalCallback func);
54 std::atomic<bool> installed_;
56 std::vector<SignalCallback> handlers_;
59 FatalSignalCallbackRegistry::FatalSignalCallbackRegistry()
63 void FatalSignalCallbackRegistry::add(SignalCallback func) {
64 std::lock_guard<std::mutex> lock(mutex_);
66 << "FatalSignalCallbackRegistry::add may not be used "
67 "after installing the signal handlers.";
68 handlers_.push_back(func);
71 void FatalSignalCallbackRegistry::markInstalled() {
72 std::lock_guard<std::mutex> lock(mutex_);
73 CHECK(!installed_.exchange(true))
74 << "FatalSignalCallbackRegistry::markInstalled must be called "
78 void FatalSignalCallbackRegistry::run() {
80 return; // Shouldn't happen
83 for (auto& fn : handlers_) {
88 // Leak it so we don't have to worry about destruction order
89 FatalSignalCallbackRegistry* gFatalSignalCallbackRegistry =
90 new FatalSignalCallbackRegistry;
95 struct sigaction oldAction;
97 { SIGSEGV, "SIGSEGV" },
100 { SIGABRT, "SIGABRT" },
101 { SIGBUS, "SIGBUS" },
102 { SIGTERM, "SIGTERM" },
106 void callPreviousSignalHandler(int signum) {
107 // Restore disposition to old disposition, then kill ourselves with the same
108 // signal. The signal will be blocked until we return from our handler,
109 // then it will invoke the default handler and abort.
110 for (auto p = kFatalSignals; p->name; ++p) {
111 if (p->number == signum) {
112 sigaction(signum, &p->oldAction, nullptr);
117 // Not one of the signals we know about. Oh well. Reset to default.
119 memset(&sa, 0, sizeof(sa));
120 sa.sa_handler = SIG_DFL;
121 sigaction(signum, &sa, nullptr);
125 void printDec(uint64_t val) {
127 uint32_t n = uint64ToBufferUnsafe(val, buf);
128 writeFull(STDERR_FILENO, buf, n);
131 const char kHexChars[] = "0123456789abcdef";
132 void printHex(uint64_t val) {
133 // TODO(tudorb): Add this to folly/Conv.h
134 char buf[2 + 2 * sizeof(uint64_t)]; // "0x" prefix, 2 digits for each byte
136 char* end = buf + sizeof(buf);
139 *--p = kHexChars[val & 0x0f];
145 writeFull(STDERR_FILENO, p, end - p);
148 void print(StringPiece sp) {
149 writeFull(STDERR_FILENO, sp.data(), sp.size());
152 void dumpTimeInfo() {
153 SCOPE_EXIT { fsyncNoInt(STDERR_FILENO); };
154 time_t now = time(nullptr);
155 print("*** Aborted at ");
157 print(" (Unix time, try 'date -d @");
162 void dumpSignalInfo(int signum, siginfo_t* siginfo) {
163 SCOPE_EXIT { fsyncNoInt(STDERR_FILENO); };
164 // Get the signal name, if possible.
165 const char* name = nullptr;
166 for (auto p = kFatalSignals; p->name; ++p) {
167 if (p->number == signum) {
173 print("*** Signal ");
182 printHex(reinterpret_cast<uint64_t>(siginfo->si_addr));
183 print(") received by PID ");
186 printHex((uint64_t)pthread_self());
187 print("), stack trace: ***\n");
190 void dumpStackTrace() {
191 SCOPE_EXIT { fsyncNoInt(STDERR_FILENO); };
192 // Get and symbolize stack trace
193 constexpr size_t kMaxStackTraceDepth = 100;
194 FrameArray<kMaxStackTraceDepth> addresses;
196 // Skip the getStackTrace frame
197 if (!getStackTrace(addresses)) {
198 print("(error retrieving stack trace)\n");
200 Symbolizer symbolizer;
201 symbolizer.symbolize(addresses);
203 FDSymbolizePrinter printer(STDERR_FILENO);
204 printer.println(addresses);
208 std::atomic<pthread_t*> gSignalThread;
211 void innerSignalHandler(int signum, siginfo_t* info, void* uctx) {
212 // First, let's only let one thread in here at a time.
213 pthread_t myId = pthread_self();
215 pthread_t* prevSignalThread = nullptr;
216 while (!gSignalThread.compare_exchange_strong(prevSignalThread, &myId)) {
217 if (pthread_equal(*prevSignalThread, myId)) {
218 print("Entered fatal signal handler recursively. We're in trouble.\n");
222 // Wait a while, try again.
225 ts.tv_nsec = 100L * 1000 * 1000; // 100ms
226 nanosleep(&ts, nullptr);
228 prevSignalThread = nullptr;
232 dumpSignalInfo(signum, info);
235 // Run user callbacks
236 gFatalSignalCallbackRegistry->run();
239 void signalHandler(int signum, siginfo_t* info, void* uctx) {
240 SCOPE_EXIT { fsyncNoInt(STDERR_FILENO); };
241 innerSignalHandler(signum, info, uctx);
243 gSignalThread = nullptr;
244 // Kill ourselves with the previous handler.
245 callPreviousSignalHandler(signum);
250 void addFatalSignalCallback(SignalCallback cb) {
251 gFatalSignalCallbackRegistry->add(cb);
256 std::atomic<bool> gAlreadyInstalled;
260 void installFatalSignalHandler() {
261 if (gAlreadyInstalled.exchange(true)) {
266 gFatalSignalCallbackRegistry->markInstalled();
269 memset(&sa, 0, sizeof(sa));
270 sigemptyset(&sa.sa_mask);
271 sa.sa_flags |= SA_SIGINFO;
272 sa.sa_sigaction = &signalHandler;
274 for (auto p = kFatalSignals; p->name; ++p) {
275 CHECK_ERR(sigaction(p->number, &sa, &p->oldAction));