fix callPreviousSignalHandler()
[folly.git] / folly / experimental / symbolizer / SignalHandler.cpp
1 /*
2  * Copyright 2013 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 <atomic>
23 #include <ctime>
24 #include <mutex>
25 #include <pthread.h>
26 #include <signal.h>
27 #include <unistd.h>
28 #include <vector>
29
30 #include <glog/logging.h>
31
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"
37
38 namespace folly { namespace symbolizer {
39
40 namespace {
41
42 /**
43  * Fatal signal handler registry.
44  */
45 class FatalSignalCallbackRegistry {
46  public:
47   FatalSignalCallbackRegistry();
48
49   void add(SignalCallback func);
50   void markInstalled();
51   void run();
52
53  private:
54   std::atomic<bool> installed_;
55   std::mutex mutex_;
56   std::vector<SignalCallback> handlers_;
57 };
58
59 FatalSignalCallbackRegistry::FatalSignalCallbackRegistry()
60   : installed_(false) {
61 }
62
63 void FatalSignalCallbackRegistry::add(SignalCallback func) {
64   std::lock_guard<std::mutex> lock(mutex_);
65   CHECK(!installed_)
66     << "FatalSignalCallbackRegistry::add may not be used "
67        "after installing the signal handlers.";
68   handlers_.push_back(func);
69 }
70
71 void FatalSignalCallbackRegistry::markInstalled() {
72   std::lock_guard<std::mutex> lock(mutex_);
73   CHECK(!installed_.exchange(true))
74     << "FatalSignalCallbackRegistry::markInstalled must be called "
75     << "at most once";
76 }
77
78 void FatalSignalCallbackRegistry::run() {
79   if (!installed_) {
80     return;
81   }
82
83   for (auto& fn : handlers_) {
84     fn();
85   }
86 }
87
88 // Leak it so we don't have to worry about destruction order
89 FatalSignalCallbackRegistry* gFatalSignalCallbackRegistry =
90   new FatalSignalCallbackRegistry;
91
92 struct {
93   int number;
94   const char* name;
95   struct sigaction oldAction;
96 } kFatalSignals[] = {
97   { SIGSEGV, "SIGSEGV" },
98   { SIGILL,  "SIGILL"  },
99   { SIGFPE,  "SIGFPE"  },
100   { SIGABRT, "SIGABRT" },
101   { SIGBUS,  "SIGBUS"  },
102   { SIGTERM, "SIGTERM" },
103   { 0,       nullptr   }
104 };
105
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);
113       raise(signum);
114       return;
115     }
116   }
117
118   // Not one of the signals we know about. Oh well. Reset to default.
119   struct sigaction sa;
120   memset(&sa, 0, sizeof(sa));
121   sa.sa_handler = SIG_DFL;
122   sigaction(signum, &sa, nullptr);
123   raise(signum);
124 }
125
126 void printDec(uint64_t val) {
127   char buf[20];
128   uint32_t n = uint64ToBufferUnsafe(val, buf);
129   writeFull(STDERR_FILENO, buf, n);
130 }
131
132 const char kHexChars[] = "0123456789abcdef";
133 void printHex(uint64_t val) {
134   // TODO(tudorb): Add this to folly/Conv.h
135   char buf[2 + 2 * sizeof(uint64_t)];  // "0x" prefix, 2 digits for each byte
136
137   char* end = buf + sizeof(buf);
138   char* p = end;
139   do {
140     *--p = kHexChars[val & 0x0f];
141     val >>= 4;
142   } while (val != 0);
143   *--p = 'x';
144   *--p = '0';
145
146   writeFull(STDERR_FILENO, p, end - p);
147 }
148
149 void print(StringPiece sp) {
150   writeFull(STDERR_FILENO, sp.data(), sp.size());
151 }
152
153 void dumpTimeInfo() {
154   SCOPE_EXIT { fsyncNoInt(STDERR_FILENO); };
155   time_t now = time(nullptr);
156   print("*** Aborted at ");
157   printDec(now);
158   print(" (Unix time, try 'date -d @");
159   printDec(now);
160   print("') ***\n");
161 }
162
163 void dumpSignalInfo(int signum, siginfo_t* siginfo) {
164   SCOPE_EXIT { fsyncNoInt(STDERR_FILENO); };
165   // Get the signal name, if possible.
166   const char* name = nullptr;
167   for (auto p = kFatalSignals; p->name; ++p) {
168     if (p->number == signum) {
169       name = p->name;
170       break;
171     }
172   }
173
174   print("*** Signal ");
175   printDec(signum);
176   if (name) {
177     print(" (");
178     print(name);
179     print(")");
180   }
181
182   print(" (");
183   printHex(reinterpret_cast<uint64_t>(siginfo->si_addr));
184   print(") received by PID ");
185   printDec(getpid());
186   print(" (TID ");
187   printHex((uint64_t)pthread_self());
188   print("), stack trace: ***\n");
189 }
190
191 void dumpStackTrace() {
192   SCOPE_EXIT { fsyncNoInt(STDERR_FILENO); };
193   // Get and symbolize stack trace
194   constexpr size_t kMaxStackTraceDepth = 100;
195   FrameArray<kMaxStackTraceDepth> addresses;
196
197   // Skip the getStackTrace frame
198   if (!getStackTrace(addresses)) {
199     print("(error retrieving stack trace)\n");
200   } else {
201     Symbolizer symbolizer;
202     symbolizer.symbolize(addresses);
203
204     FDSymbolizePrinter printer(STDERR_FILENO);
205     printer.println(addresses);
206   }
207 }
208
209 std::atomic<pthread_t*> gSignalThread;
210
211 // Here be dragons.
212 void innerSignalHandler(int signum, siginfo_t* info, void* uctx) {
213   // First, let's only let one thread in here at a time.
214   pthread_t myId = pthread_self();
215
216   pthread_t* prevSignalThread = nullptr;
217   while (!gSignalThread.compare_exchange_strong(prevSignalThread, &myId)) {
218     if (pthread_equal(*prevSignalThread, myId)) {
219       print("Entered fatal signal handler recursively. We're in trouble.\n");
220       return;
221     }
222
223     // Wait a while, try again.
224     timespec ts;
225     ts.tv_sec = 0;
226     ts.tv_nsec = 100L * 1000 * 1000;  // 100ms
227     nanosleep(&ts, nullptr);
228
229     prevSignalThread = nullptr;
230   }
231
232   dumpTimeInfo();
233   dumpSignalInfo(signum, info);
234   dumpStackTrace();
235
236   // Run user callbacks
237   gFatalSignalCallbackRegistry->run();
238 }
239
240 void signalHandler(int signum, siginfo_t* info, void* uctx) {
241   SCOPE_EXIT { fsyncNoInt(STDERR_FILENO); };
242   innerSignalHandler(signum, info, uctx);
243
244   gSignalThread = nullptr;
245   // Kill ourselves with the previous handler.
246   callPreviousSignalHandler(signum);
247 }
248
249 }  // namespace
250
251 void addFatalSignalCallback(SignalCallback cb) {
252   gFatalSignalCallbackRegistry->add(cb);
253 }
254
255 void installFatalSignalCallbacks() {
256   gFatalSignalCallbackRegistry->markInstalled();
257 }
258
259 namespace {
260
261 std::atomic<bool> gAlreadyInstalled;
262
263 }  // namespace
264
265 void installFatalSignalHandler() {
266   if (gAlreadyInstalled.exchange(true)) {
267     // Already done.
268     return;
269   }
270
271   struct sigaction sa;
272   memset(&sa, 0, sizeof(sa));
273   sigemptyset(&sa.sa_mask);
274   sa.sa_flags |= SA_SIGINFO;
275   sa.sa_sigaction = &signalHandler;
276
277   for (auto p = kFatalSignals; p->name; ++p) {
278     CHECK_ERR(sigaction(p->number, &sa, &p->oldAction));
279   }
280 }
281
282 }}  // namespaces
283