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