failure_signal_handler.cc
Go to the documentation of this file.
00001 //
00002 // Copyright 2018 The Abseil Authors.
00003 //
00004 // Licensed under the Apache License, Version 2.0 (the "License");
00005 // you may not use this file except in compliance with the License.
00006 // You may obtain a copy of the License at
00007 //
00008 //      https://www.apache.org/licenses/LICENSE-2.0
00009 //
00010 // Unless required by applicable law or agreed to in writing, software
00011 // distributed under the License is distributed on an "AS IS" BASIS,
00012 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
00013 // See the License for the specific language governing permissions and
00014 // limitations under the License.
00015 //
00016 
00017 #include "absl/debugging/failure_signal_handler.h"
00018 
00019 #include "absl/base/config.h"
00020 
00021 #ifdef _WIN32
00022 #include <windows.h>
00023 #else
00024 #include <unistd.h>
00025 #endif
00026 
00027 #ifdef ABSL_HAVE_MMAP
00028 #include <sys/mman.h>
00029 #endif
00030 
00031 #include <algorithm>
00032 #include <atomic>
00033 #include <cerrno>
00034 #include <csignal>
00035 #include <cstdio>
00036 #include <cstring>
00037 #include <ctime>
00038 
00039 #include "absl/base/attributes.h"
00040 #include "absl/base/internal/raw_logging.h"
00041 #include "absl/base/internal/sysinfo.h"
00042 #include "absl/debugging/internal/examine_stack.h"
00043 #include "absl/debugging/stacktrace.h"
00044 
00045 #ifndef _WIN32
00046 #define ABSL_HAVE_SIGACTION
00047 #endif
00048 
00049 namespace absl {
00050 
00051 ABSL_CONST_INIT static FailureSignalHandlerOptions fsh_options;
00052 
00053 // Resets the signal handler for signo to the default action for that
00054 // signal, then raises the signal.
00055 static void RaiseToDefaultHandler(int signo) {
00056   signal(signo, SIG_DFL);
00057   raise(signo);
00058 }
00059 
00060 struct FailureSignalData {
00061   const int signo;
00062   const char* const as_string;
00063 #ifdef ABSL_HAVE_SIGACTION
00064   struct sigaction previous_action;
00065   // StructSigaction is used to silence -Wmissing-field-initializers.
00066   using StructSigaction = struct sigaction;
00067   #define FSD_PREVIOUS_INIT FailureSignalData::StructSigaction()
00068 #else
00069   void (*previous_handler)(int);
00070   #define FSD_PREVIOUS_INIT SIG_DFL
00071 #endif
00072 };
00073 
00074 ABSL_CONST_INIT static FailureSignalData failure_signal_data[] = {
00075     {SIGSEGV, "SIGSEGV", FSD_PREVIOUS_INIT},
00076     {SIGILL, "SIGILL", FSD_PREVIOUS_INIT},
00077     {SIGFPE, "SIGFPE", FSD_PREVIOUS_INIT},
00078     {SIGABRT, "SIGABRT", FSD_PREVIOUS_INIT},
00079     {SIGTERM, "SIGTERM", FSD_PREVIOUS_INIT},
00080 #ifndef _WIN32
00081     {SIGBUS, "SIGBUS", FSD_PREVIOUS_INIT},
00082     {SIGTRAP, "SIGTRAP", FSD_PREVIOUS_INIT},
00083 #endif
00084 };
00085 
00086 #undef FSD_PREVIOUS_INIT
00087 
00088 static void RaiseToPreviousHandler(int signo) {
00089   // Search for the previous handler.
00090   for (const auto& it : failure_signal_data) {
00091     if (it.signo == signo) {
00092 #ifdef ABSL_HAVE_SIGACTION
00093       sigaction(signo, &it.previous_action, nullptr);
00094 #else
00095       signal(signo, it.previous_handler);
00096 #endif
00097       raise(signo);
00098       return;
00099     }
00100   }
00101 
00102   // Not found, use the default handler.
00103   RaiseToDefaultHandler(signo);
00104 }
00105 
00106 namespace debugging_internal {
00107 
00108 const char* FailureSignalToString(int signo) {
00109   for (const auto& it : failure_signal_data) {
00110     if (it.signo == signo) {
00111       return it.as_string;
00112     }
00113   }
00114   return "";
00115 }
00116 
00117 }  // namespace debugging_internal
00118 
00119 #ifndef _WIN32
00120 
00121 static bool SetupAlternateStackOnce() {
00122 #if defined(__wasm__) || defined (__asjms__)
00123   const size_t page_mask = getpagesize() - 1;
00124 #else
00125   const size_t page_mask = sysconf(_SC_PAGESIZE) - 1;
00126 #endif
00127   size_t stack_size = (std::max(SIGSTKSZ, 65536) + page_mask) & ~page_mask;
00128 #if defined(ADDRESS_SANITIZER) || defined(MEMORY_SANITIZER) || \
00129     defined(THREAD_SANITIZER)
00130   // Account for sanitizer instrumentation requiring additional stack space.
00131   stack_size *= 5;
00132 #endif
00133 
00134   stack_t sigstk;
00135   memset(&sigstk, 0, sizeof(sigstk));
00136   sigstk.ss_size = stack_size;
00137 
00138 #ifdef ABSL_HAVE_MMAP
00139 #ifndef MAP_STACK
00140 #define MAP_STACK 0
00141 #endif
00142 #if defined(MAP_ANON) && !defined(MAP_ANONYMOUS)
00143 #define MAP_ANONYMOUS MAP_ANON
00144 #endif
00145   sigstk.ss_sp = mmap(nullptr, sigstk.ss_size, PROT_READ | PROT_WRITE,
00146                       MAP_PRIVATE | MAP_ANONYMOUS | MAP_STACK, -1, 0);
00147   if (sigstk.ss_sp == MAP_FAILED) {
00148     ABSL_RAW_LOG(FATAL, "mmap() for alternate signal stack failed");
00149   }
00150 #else
00151   sigstk.ss_sp = malloc(sigstk.ss_size);
00152   if (sigstk.ss_sp == nullptr) {
00153     ABSL_RAW_LOG(FATAL, "malloc() for alternate signal stack failed");
00154   }
00155 #endif
00156 
00157   if (sigaltstack(&sigstk, nullptr) != 0) {
00158     ABSL_RAW_LOG(FATAL, "sigaltstack() failed with errno=%d", errno);
00159   }
00160   return true;
00161 }
00162 
00163 #endif
00164 
00165 #ifdef ABSL_HAVE_SIGACTION
00166 
00167 // Sets up an alternate stack for signal handlers once.
00168 // Returns the appropriate flag for sig_action.sa_flags
00169 // if the system supports using an alternate stack.
00170 static int MaybeSetupAlternateStack() {
00171 #ifndef _WIN32
00172   ABSL_ATTRIBUTE_UNUSED static const bool kOnce = SetupAlternateStackOnce();
00173   return SA_ONSTACK;
00174 #else
00175   return 0;
00176 #endif
00177 }
00178 
00179 static void InstallOneFailureHandler(FailureSignalData* data,
00180                                      void (*handler)(int, siginfo_t*, void*)) {
00181   struct sigaction act;
00182   memset(&act, 0, sizeof(act));
00183   sigemptyset(&act.sa_mask);
00184   act.sa_flags |= SA_SIGINFO;
00185   // SA_NODEFER is required to handle SIGABRT from
00186   // ImmediateAbortSignalHandler().
00187   act.sa_flags |= SA_NODEFER;
00188   if (fsh_options.use_alternate_stack) {
00189     act.sa_flags |= MaybeSetupAlternateStack();
00190   }
00191   act.sa_sigaction = handler;
00192   ABSL_RAW_CHECK(sigaction(data->signo, &act, &data->previous_action) == 0,
00193                  "sigaction() failed");
00194 }
00195 
00196 #else
00197 
00198 static void InstallOneFailureHandler(FailureSignalData* data,
00199                                      void (*handler)(int)) {
00200   data->previous_handler = signal(data->signo, handler);
00201   ABSL_RAW_CHECK(data->previous_handler != SIG_ERR, "signal() failed");
00202 }
00203 
00204 #endif
00205 
00206 static void WriteToStderr(const char* data) {
00207   int old_errno = errno;
00208   absl::raw_logging_internal::SafeWriteToStderr(data, strlen(data));
00209   errno = old_errno;
00210 }
00211 
00212 static void WriteSignalMessage(int signo, void (*writerfn)(const char*)) {
00213   char buf[64];
00214   const char* const signal_string =
00215       debugging_internal::FailureSignalToString(signo);
00216   if (signal_string != nullptr && signal_string[0] != '\0') {
00217     snprintf(buf, sizeof(buf), "*** %s received at time=%ld ***\n",
00218              signal_string,
00219              static_cast<long>(time(nullptr)));  // NOLINT(runtime/int)
00220   } else {
00221     snprintf(buf, sizeof(buf), "*** Signal %d received at time=%ld ***\n",
00222              signo, static_cast<long>(time(nullptr)));  // NOLINT(runtime/int)
00223   }
00224   writerfn(buf);
00225 }
00226 
00227 // `void*` might not be big enough to store `void(*)(const char*)`.
00228 struct WriterFnStruct {
00229   void (*writerfn)(const char*);
00230 };
00231 
00232 // Many of the absl::debugging_internal::Dump* functions in
00233 // examine_stack.h take a writer function pointer that has a void* arg
00234 // for historical reasons. failure_signal_handler_writer only takes a
00235 // data pointer. This function converts between these types.
00236 static void WriterFnWrapper(const char* data, void* arg) {
00237   static_cast<WriterFnStruct*>(arg)->writerfn(data);
00238 }
00239 
00240 // Convenient wrapper around DumpPCAndFrameSizesAndStackTrace() for signal
00241 // handlers. "noinline" so that GetStackFrames() skips the top-most stack
00242 // frame for this function.
00243 ABSL_ATTRIBUTE_NOINLINE static void WriteStackTrace(
00244     void* ucontext, bool symbolize_stacktrace,
00245     void (*writerfn)(const char*, void*), void* writerfn_arg) {
00246   constexpr int kNumStackFrames = 32;
00247   void* stack[kNumStackFrames];
00248   int frame_sizes[kNumStackFrames];
00249   int min_dropped_frames;
00250   int depth = absl::GetStackFramesWithContext(
00251       stack, frame_sizes, kNumStackFrames,
00252       1,  // Do not include this function in stack trace.
00253       ucontext, &min_dropped_frames);
00254   absl::debugging_internal::DumpPCAndFrameSizesAndStackTrace(
00255       absl::debugging_internal::GetProgramCounter(ucontext), stack, frame_sizes,
00256       depth, min_dropped_frames, symbolize_stacktrace, writerfn, writerfn_arg);
00257 }
00258 
00259 // Called by AbslFailureSignalHandler() to write the failure info. It is
00260 // called once with writerfn set to WriteToStderr() and then possibly
00261 // with writerfn set to the user provided function.
00262 static void WriteFailureInfo(int signo, void* ucontext,
00263                              void (*writerfn)(const char*)) {
00264   WriterFnStruct writerfn_struct{writerfn};
00265   WriteSignalMessage(signo, writerfn);
00266   WriteStackTrace(ucontext, fsh_options.symbolize_stacktrace, WriterFnWrapper,
00267                   &writerfn_struct);
00268 }
00269 
00270 // absl::SleepFor() can't be used here since AbslInternalSleepFor()
00271 // may be overridden to do something that isn't async-signal-safe on
00272 // some platforms.
00273 static void PortableSleepForSeconds(int seconds) {
00274 #ifdef _WIN32
00275   Sleep(seconds * 1000);
00276 #else
00277   struct timespec sleep_time;
00278   sleep_time.tv_sec = seconds;
00279   sleep_time.tv_nsec = 0;
00280   while (nanosleep(&sleep_time, &sleep_time) != 0 && errno == EINTR) {}
00281 #endif
00282 }
00283 
00284 #ifdef ABSL_HAVE_ALARM
00285 // AbslFailureSignalHandler() installs this as a signal handler for
00286 // SIGALRM, then sets an alarm to be delivered to the program after a
00287 // set amount of time. If AbslFailureSignalHandler() hangs for more than
00288 // the alarm timeout, ImmediateAbortSignalHandler() will abort the
00289 // program.
00290 static void ImmediateAbortSignalHandler(int) {
00291   RaiseToDefaultHandler(SIGABRT);
00292 }
00293 #endif
00294 
00295 // absl::base_internal::GetTID() returns pid_t on most platforms, but
00296 // returns absl::base_internal::pid_t on Windows.
00297 using GetTidType = decltype(absl::base_internal::GetTID());
00298 ABSL_CONST_INIT static std::atomic<GetTidType> failed_tid(0);
00299 
00300 #ifndef ABSL_HAVE_SIGACTION
00301 static void AbslFailureSignalHandler(int signo) {
00302   void* ucontext = nullptr;
00303 #else
00304 static void AbslFailureSignalHandler(int signo, siginfo_t*, void* ucontext) {
00305 #endif
00306 
00307   const GetTidType this_tid = absl::base_internal::GetTID();
00308   GetTidType previous_failed_tid = 0;
00309   if (!failed_tid.compare_exchange_strong(
00310           previous_failed_tid, static_cast<intptr_t>(this_tid),
00311           std::memory_order_acq_rel, std::memory_order_relaxed)) {
00312     ABSL_RAW_LOG(
00313         ERROR,
00314         "Signal %d raised at PC=%p while already in AbslFailureSignalHandler()",
00315         signo, absl::debugging_internal::GetProgramCounter(ucontext));
00316     if (this_tid != previous_failed_tid) {
00317       // Another thread is already in AbslFailureSignalHandler(), so wait
00318       // a bit for it to finish. If the other thread doesn't kill us,
00319       // we do so after sleeping.
00320       PortableSleepForSeconds(3);
00321       RaiseToDefaultHandler(signo);
00322       // The recursively raised signal may be blocked until we return.
00323       return;
00324     }
00325   }
00326 
00327 #ifdef ABSL_HAVE_ALARM
00328   // Set an alarm to abort the program in case this code hangs or deadlocks.
00329   if (fsh_options.alarm_on_failure_secs > 0) {
00330     alarm(0);  // Cancel any existing alarms.
00331     signal(SIGALRM, ImmediateAbortSignalHandler);
00332     alarm(fsh_options.alarm_on_failure_secs);
00333   }
00334 #endif
00335 
00336   // First write to stderr.
00337   WriteFailureInfo(signo, ucontext, WriteToStderr);
00338 
00339   // Riskier code (because it is less likely to be async-signal-safe)
00340   // goes after this point.
00341   if (fsh_options.writerfn != nullptr) {
00342     WriteFailureInfo(signo, ucontext, fsh_options.writerfn);
00343   }
00344 
00345   if (fsh_options.call_previous_handler) {
00346     RaiseToPreviousHandler(signo);
00347   } else {
00348     RaiseToDefaultHandler(signo);
00349   }
00350 }
00351 
00352 void InstallFailureSignalHandler(const FailureSignalHandlerOptions& options) {
00353   fsh_options = options;
00354   for (auto& it : failure_signal_data) {
00355     InstallOneFailureHandler(&it, AbslFailureSignalHandler);
00356   }
00357 }
00358 
00359 }  // namespace absl


abseil_cpp
Author(s):
autogenerated on Wed Jun 19 2019 19:42:14