• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 //
2 // Copyright 2018 The Abseil Authors.
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 //      https://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 #include "absl/debugging/failure_signal_handler.h"
18 
19 #include "absl/base/config.h"
20 
21 #ifdef _WIN32
22 #include <windows.h>
23 #else
24 #include <sched.h>
25 #include <unistd.h>
26 #endif
27 
28 #ifdef __APPLE__
29 #include <TargetConditionals.h>
30 #endif
31 
32 #ifdef ABSL_HAVE_MMAP
33 #include <sys/mman.h>
34 #endif
35 
36 #include <algorithm>
37 #include <atomic>
38 #include <cerrno>
39 #include <csignal>
40 #include <cstdio>
41 #include <cstring>
42 #include <ctime>
43 
44 #include "absl/base/attributes.h"
45 #include "absl/base/internal/errno_saver.h"
46 #include "absl/base/internal/raw_logging.h"
47 #include "absl/base/internal/sysinfo.h"
48 #include "absl/debugging/internal/examine_stack.h"
49 #include "absl/debugging/stacktrace.h"
50 
51 #ifndef _WIN32
52 #define ABSL_HAVE_SIGACTION
53 // Apple WatchOS and TVOS don't allow sigaltstack
54 #if !(defined(TARGET_OS_WATCH) && TARGET_OS_WATCH) && \
55     !(defined(TARGET_OS_TV) && TARGET_OS_TV) && !defined(__QNX__)
56 #define ABSL_HAVE_SIGALTSTACK
57 #endif
58 #endif
59 
60 namespace absl {
61 ABSL_NAMESPACE_BEGIN
62 
63 ABSL_CONST_INIT static FailureSignalHandlerOptions fsh_options;
64 
65 // Resets the signal handler for signo to the default action for that
66 // signal, then raises the signal.
RaiseToDefaultHandler(int signo)67 static void RaiseToDefaultHandler(int signo) {
68   signal(signo, SIG_DFL);
69   raise(signo);
70 }
71 
72 struct FailureSignalData {
73   const int signo;
74   const char* const as_string;
75 #ifdef ABSL_HAVE_SIGACTION
76   struct sigaction previous_action;
77   // StructSigaction is used to silence -Wmissing-field-initializers.
78   using StructSigaction = struct sigaction;
79   #define FSD_PREVIOUS_INIT FailureSignalData::StructSigaction()
80 #else
81   void (*previous_handler)(int);
82   #define FSD_PREVIOUS_INIT SIG_DFL
83 #endif
84 };
85 
86 ABSL_CONST_INIT static FailureSignalData failure_signal_data[] = {
87     {SIGSEGV, "SIGSEGV", FSD_PREVIOUS_INIT},
88     {SIGILL, "SIGILL", FSD_PREVIOUS_INIT},
89     {SIGFPE, "SIGFPE", FSD_PREVIOUS_INIT},
90     {SIGABRT, "SIGABRT", FSD_PREVIOUS_INIT},
91     {SIGTERM, "SIGTERM", FSD_PREVIOUS_INIT},
92 #ifndef _WIN32
93     {SIGBUS, "SIGBUS", FSD_PREVIOUS_INIT},
94     {SIGTRAP, "SIGTRAP", FSD_PREVIOUS_INIT},
95 #endif
96 };
97 
98 #undef FSD_PREVIOUS_INIT
99 
RaiseToPreviousHandler(int signo)100 static void RaiseToPreviousHandler(int signo) {
101   // Search for the previous handler.
102   for (const auto& it : failure_signal_data) {
103     if (it.signo == signo) {
104 #ifdef ABSL_HAVE_SIGACTION
105       sigaction(signo, &it.previous_action, nullptr);
106 #else
107       signal(signo, it.previous_handler);
108 #endif
109       raise(signo);
110       return;
111     }
112   }
113 
114   // Not found, use the default handler.
115   RaiseToDefaultHandler(signo);
116 }
117 
118 namespace debugging_internal {
119 
FailureSignalToString(int signo)120 const char* FailureSignalToString(int signo) {
121   for (const auto& it : failure_signal_data) {
122     if (it.signo == signo) {
123       return it.as_string;
124     }
125   }
126   return "";
127 }
128 
129 }  // namespace debugging_internal
130 
131 #ifdef ABSL_HAVE_SIGALTSTACK
132 
SetupAlternateStackOnce()133 static bool SetupAlternateStackOnce() {
134 #if defined(__wasm__) || defined (__asjms__)
135   const size_t page_mask = getpagesize() - 1;
136 #else
137   const size_t page_mask = sysconf(_SC_PAGESIZE) - 1;
138 #endif
139   size_t stack_size =
140       (std::max<size_t>(SIGSTKSZ, 65536) + page_mask) & ~page_mask;
141 #if defined(ABSL_HAVE_ADDRESS_SANITIZER) || \
142     defined(ABSL_HAVE_MEMORY_SANITIZER) || defined(ABSL_HAVE_THREAD_SANITIZER)
143   // Account for sanitizer instrumentation requiring additional stack space.
144   stack_size *= 5;
145 #endif
146 
147   stack_t sigstk;
148   memset(&sigstk, 0, sizeof(sigstk));
149   sigstk.ss_size = stack_size;
150 
151 #ifdef ABSL_HAVE_MMAP
152 #ifndef MAP_STACK
153 #define MAP_STACK 0
154 #endif
155 #if defined(MAP_ANON) && !defined(MAP_ANONYMOUS)
156 #define MAP_ANONYMOUS MAP_ANON
157 #endif
158   sigstk.ss_sp = mmap(nullptr, sigstk.ss_size, PROT_READ | PROT_WRITE,
159                       MAP_PRIVATE | MAP_ANONYMOUS | MAP_STACK, -1, 0);
160   if (sigstk.ss_sp == MAP_FAILED) {
161     ABSL_RAW_LOG(FATAL, "mmap() for alternate signal stack failed");
162   }
163 #else
164   sigstk.ss_sp = malloc(sigstk.ss_size);
165   if (sigstk.ss_sp == nullptr) {
166     ABSL_RAW_LOG(FATAL, "malloc() for alternate signal stack failed");
167   }
168 #endif
169 
170   if (sigaltstack(&sigstk, nullptr) != 0) {
171     ABSL_RAW_LOG(FATAL, "sigaltstack() failed with errno=%d", errno);
172   }
173   return true;
174 }
175 
176 #endif
177 
178 #ifdef ABSL_HAVE_SIGACTION
179 
180 // Sets up an alternate stack for signal handlers once.
181 // Returns the appropriate flag for sig_action.sa_flags
182 // if the system supports using an alternate stack.
MaybeSetupAlternateStack()183 static int MaybeSetupAlternateStack() {
184 #ifdef ABSL_HAVE_SIGALTSTACK
185   ABSL_ATTRIBUTE_UNUSED static const bool kOnce = SetupAlternateStackOnce();
186   return SA_ONSTACK;
187 #else
188   return 0;
189 #endif
190 }
191 
InstallOneFailureHandler(FailureSignalData * data,void (* handler)(int,siginfo_t *,void *))192 static void InstallOneFailureHandler(FailureSignalData* data,
193                                      void (*handler)(int, siginfo_t*, void*)) {
194   struct sigaction act;
195   memset(&act, 0, sizeof(act));
196   sigemptyset(&act.sa_mask);
197   act.sa_flags |= SA_SIGINFO;
198   // SA_NODEFER is required to handle SIGABRT from
199   // ImmediateAbortSignalHandler().
200   act.sa_flags |= SA_NODEFER;
201   if (fsh_options.use_alternate_stack) {
202     act.sa_flags |= MaybeSetupAlternateStack();
203   }
204   act.sa_sigaction = handler;
205   ABSL_RAW_CHECK(sigaction(data->signo, &act, &data->previous_action) == 0,
206                  "sigaction() failed");
207 }
208 
209 #else
210 
InstallOneFailureHandler(FailureSignalData * data,void (* handler)(int))211 static void InstallOneFailureHandler(FailureSignalData* data,
212                                      void (*handler)(int)) {
213   data->previous_handler = signal(data->signo, handler);
214   ABSL_RAW_CHECK(data->previous_handler != SIG_ERR, "signal() failed");
215 }
216 
217 #endif
218 
WriteToStderr(const char * data)219 static void WriteToStderr(const char* data) {
220   absl::base_internal::ErrnoSaver errno_saver;
221   absl::raw_logging_internal::SafeWriteToStderr(data, strlen(data));
222 }
223 
WriteSignalMessage(int signo,int cpu,void (* writerfn)(const char *))224 static void WriteSignalMessage(int signo, int cpu,
225                                void (*writerfn)(const char*)) {
226   char buf[96];
227   char on_cpu[32] = {0};
228   if (cpu != -1) {
229     snprintf(on_cpu, sizeof(on_cpu), " on cpu %d", cpu);
230   }
231   const char* const signal_string =
232       debugging_internal::FailureSignalToString(signo);
233   if (signal_string != nullptr && signal_string[0] != '\0') {
234     snprintf(buf, sizeof(buf), "*** %s received at time=%ld%s ***\n",
235              signal_string,
236              static_cast<long>(time(nullptr)),   // NOLINT(runtime/int)
237              on_cpu);
238   } else {
239     snprintf(buf, sizeof(buf), "*** Signal %d received at time=%ld%s ***\n",
240              signo, static_cast<long>(time(nullptr)),  // NOLINT(runtime/int)
241              on_cpu);
242   }
243   writerfn(buf);
244 }
245 
246 // `void*` might not be big enough to store `void(*)(const char*)`.
247 struct WriterFnStruct {
248   void (*writerfn)(const char*);
249 };
250 
251 // Many of the absl::debugging_internal::Dump* functions in
252 // examine_stack.h take a writer function pointer that has a void* arg
253 // for historical reasons. failure_signal_handler_writer only takes a
254 // data pointer. This function converts between these types.
WriterFnWrapper(const char * data,void * arg)255 static void WriterFnWrapper(const char* data, void* arg) {
256   static_cast<WriterFnStruct*>(arg)->writerfn(data);
257 }
258 
259 // Convenient wrapper around DumpPCAndFrameSizesAndStackTrace() for signal
260 // handlers. "noinline" so that GetStackFrames() skips the top-most stack
261 // frame for this function.
WriteStackTrace(void * ucontext,bool symbolize_stacktrace,void (* writerfn)(const char *,void *),void * writerfn_arg)262 ABSL_ATTRIBUTE_NOINLINE static void WriteStackTrace(
263     void* ucontext, bool symbolize_stacktrace,
264     void (*writerfn)(const char*, void*), void* writerfn_arg) {
265   constexpr int kNumStackFrames = 32;
266   void* stack[kNumStackFrames];
267   int frame_sizes[kNumStackFrames];
268   int min_dropped_frames;
269   int depth = absl::GetStackFramesWithContext(
270       stack, frame_sizes, kNumStackFrames,
271       1,  // Do not include this function in stack trace.
272       ucontext, &min_dropped_frames);
273   absl::debugging_internal::DumpPCAndFrameSizesAndStackTrace(
274       absl::debugging_internal::GetProgramCounter(ucontext), stack, frame_sizes,
275       depth, min_dropped_frames, symbolize_stacktrace, writerfn, writerfn_arg);
276 }
277 
278 // Called by AbslFailureSignalHandler() to write the failure info. It is
279 // called once with writerfn set to WriteToStderr() and then possibly
280 // with writerfn set to the user provided function.
WriteFailureInfo(int signo,void * ucontext,int cpu,void (* writerfn)(const char *))281 static void WriteFailureInfo(int signo, void* ucontext, int cpu,
282                              void (*writerfn)(const char*)) {
283   WriterFnStruct writerfn_struct{writerfn};
284   WriteSignalMessage(signo, cpu, writerfn);
285   WriteStackTrace(ucontext, fsh_options.symbolize_stacktrace, WriterFnWrapper,
286                   &writerfn_struct);
287 }
288 
289 // absl::SleepFor() can't be used here since AbslInternalSleepFor()
290 // may be overridden to do something that isn't async-signal-safe on
291 // some platforms.
PortableSleepForSeconds(int seconds)292 static void PortableSleepForSeconds(int seconds) {
293 #ifdef _WIN32
294   Sleep(seconds * 1000);
295 #else
296   struct timespec sleep_time;
297   sleep_time.tv_sec = seconds;
298   sleep_time.tv_nsec = 0;
299   while (nanosleep(&sleep_time, &sleep_time) != 0 && errno == EINTR) {}
300 #endif
301 }
302 
303 #ifdef ABSL_HAVE_ALARM
304 // AbslFailureSignalHandler() installs this as a signal handler for
305 // SIGALRM, then sets an alarm to be delivered to the program after a
306 // set amount of time. If AbslFailureSignalHandler() hangs for more than
307 // the alarm timeout, ImmediateAbortSignalHandler() will abort the
308 // program.
ImmediateAbortSignalHandler(int)309 static void ImmediateAbortSignalHandler(int) {
310   RaiseToDefaultHandler(SIGABRT);
311 }
312 #endif
313 
314 // absl::base_internal::GetTID() returns pid_t on most platforms, but
315 // returns absl::base_internal::pid_t on Windows.
316 using GetTidType = decltype(absl::base_internal::GetTID());
317 ABSL_CONST_INIT static std::atomic<GetTidType> failed_tid(0);
318 
319 #ifndef ABSL_HAVE_SIGACTION
AbslFailureSignalHandler(int signo)320 static void AbslFailureSignalHandler(int signo) {
321   void* ucontext = nullptr;
322 #else
323 static void AbslFailureSignalHandler(int signo, siginfo_t*, void* ucontext) {
324 #endif
325 
326   const GetTidType this_tid = absl::base_internal::GetTID();
327   GetTidType previous_failed_tid = 0;
328   if (!failed_tid.compare_exchange_strong(
329           previous_failed_tid, static_cast<intptr_t>(this_tid),
330           std::memory_order_acq_rel, std::memory_order_relaxed)) {
331     ABSL_RAW_LOG(
332         ERROR,
333         "Signal %d raised at PC=%p while already in AbslFailureSignalHandler()",
334         signo, absl::debugging_internal::GetProgramCounter(ucontext));
335     if (this_tid != previous_failed_tid) {
336       // Another thread is already in AbslFailureSignalHandler(), so wait
337       // a bit for it to finish. If the other thread doesn't kill us,
338       // we do so after sleeping.
339       PortableSleepForSeconds(3);
340       RaiseToDefaultHandler(signo);
341       // The recursively raised signal may be blocked until we return.
342       return;
343     }
344   }
345 
346   // Increase the chance that the CPU we report was the same CPU on which the
347   // signal was received by doing this as early as possible, i.e. after
348   // verifying that this is not a recursive signal handler invocation.
349   int my_cpu = -1;
350 #ifdef ABSL_HAVE_SCHED_GETCPU
351   my_cpu = sched_getcpu();
352 #endif
353 
354 #ifdef ABSL_HAVE_ALARM
355   // Set an alarm to abort the program in case this code hangs or deadlocks.
356   if (fsh_options.alarm_on_failure_secs > 0) {
357     alarm(0);  // Cancel any existing alarms.
358     signal(SIGALRM, ImmediateAbortSignalHandler);
359     alarm(fsh_options.alarm_on_failure_secs);
360   }
361 #endif
362 
363   // First write to stderr.
364   WriteFailureInfo(signo, ucontext, my_cpu, WriteToStderr);
365 
366   // Riskier code (because it is less likely to be async-signal-safe)
367   // goes after this point.
368   if (fsh_options.writerfn != nullptr) {
369     WriteFailureInfo(signo, ucontext, my_cpu, fsh_options.writerfn);
370     fsh_options.writerfn(nullptr);
371   }
372 
373   if (fsh_options.call_previous_handler) {
374     RaiseToPreviousHandler(signo);
375   } else {
376     RaiseToDefaultHandler(signo);
377   }
378 }
379 
380 void InstallFailureSignalHandler(const FailureSignalHandlerOptions& options) {
381   fsh_options = options;
382   for (auto& it : failure_signal_data) {
383     InstallOneFailureHandler(&it, AbslFailureSignalHandler);
384   }
385 }
386 
387 ABSL_NAMESPACE_END
388 }  // namespace absl
389