1 // Copyright 2018 the V8 project authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
4 
5 // PLEASE READ BEFORE CHANGING THIS FILE!
6 //
7 // This file implements the support code for the out of bounds signal handler.
8 // Nothing in here actually runs in the signal handler, but the code here
9 // manipulates data structures used by the signal handler so we still need to be
10 // careful. In order to minimize this risk, here are some rules to follow.
11 //
12 // 1. Avoid introducing new external dependencies. The files in src/trap-handler
13 //    should be as self-contained as possible to make it easy to audit the code.
14 //
15 // 2. Any changes must be reviewed by someone from the crash reporting
16 //    or security team. Se OWNERS for suggested reviewers.
17 //
18 // For more information, see https://goo.gl/yMeyUY.
19 //
20 // For the code that runs in the signal handler itself, see handler-inside.cc.
21 
22 #include <signal.h>
23 
24 #include "src/trap-handler/trap-handler-internal.h"
25 #include "src/trap-handler/trap-handler.h"
26 
27 namespace v8 {
28 namespace internal {
29 namespace trap_handler {
30 
31 #if V8_TRAP_HANDLER_SUPPORTED
RegisterDefaultTrapHandler()32 bool RegisterDefaultTrapHandler() {
33   CHECK(!g_is_default_signal_handler_registered);
34 
35   struct sigaction action;
36   action.sa_sigaction = HandleSignal;
37   action.sa_flags = SA_SIGINFO;
38   sigemptyset(&action.sa_mask);
39   // {sigaction} installs a new custom segfault handler. On success, it returns
40   // 0. If we get a nonzero value, we report an error to the caller by returning
41   // false.
42   if (sigaction(SIGSEGV, &action, &g_old_handler) != 0) {
43     return false;
44   }
45 
46 // Sanitizers often prevent us from installing our own signal handler. Attempt
47 // to detect this and if so, refuse to enable trap handling.
48 //
49 // TODO(chromium:830894): Remove this once all bots support custom signal
50 // handlers.
51 #if defined(ADDRESS_SANITIZER) || defined(MEMORY_SANITIZER) || \
52     defined(THREAD_SANITIZER) || defined(LEAK_SANITIZER) ||    \
53     defined(UNDEFINED_SANITIZER)
54   struct sigaction installed_handler;
55   CHECK_EQ(sigaction(SIGSEGV, NULL, &installed_handler), 0);
56   // If the installed handler does not point to HandleSignal, then
57   // allow_user_segv_handler is 0.
58   if (installed_handler.sa_sigaction != HandleSignal) {
59     printf(
60         "WARNING: sanitizers are preventing signal handler installation. "
61         "Trap handlers are disabled.\n");
62     return false;
63   }
64 #endif
65 
66   g_is_default_signal_handler_registered = true;
67   return true;
68 }
69 #endif
70 
71 }  // namespace trap_handler
72 }  // namespace internal
73 }  // namespace v8
74