• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (C) 2023 The Android Open Source Project
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 #include "berberis/runtime_primitives/crash_reporter.h"
18 
19 #include <sys/syscall.h>  // SYS_rt_tgdigqueueinfo
20 #include <unistd.h>       // syscall
21 
22 #include <csignal>
23 
24 #include "berberis/base/gettid.h"
25 #include "berberis/base/tracing.h"
26 #include "berberis/instrument/crash.h"
27 
28 namespace berberis {
29 
30 namespace {
31 
32 struct sigaction g_orig_action[NSIG];
33 
34 }  // namespace
35 
HandleFatalSignal(int sig,siginfo_t * info,void * context)36 void HandleFatalSignal(int sig, siginfo_t* info, void* context) {
37   TRACE("Fatal signal %d", sig);
38 
39   OnCrash(sig, info, context);
40 
41   // Let the default crash reporter do the job. Restore the original signal action, as the default
42   // crash reporter can re-raise the signal.
43   sigaction(sig, &g_orig_action[sig], nullptr);
44   if (g_orig_action[sig].sa_flags & SA_SIGINFO) {
45     // Run the original signal action manually and provide actual siginfo and context.
46     g_orig_action[sig].sa_sigaction(sig, info, context);
47   } else {
48     // This should be rare as debuggerd sets siginfo handlers for most signals. The original action
49     // doesn't accept siginfo and context, so we re-raise the signal as accurate as possible and
50     // hope for the best. If the signal is currently blocked we'll need to return from this handler
51     // for the signal to be delivered.
52     // TODO(b/232598137): Since the action doesn't accept siginfo it'll be ignored anyway, so
53     // maybe we should just call g_orig_action[sig].sa_handler(sig) for immediate delivery.
54     syscall(SYS_rt_tgsigqueueinfo, GetpidSyscall(), GettidSyscall(), sig, info);
55   }
56 }
57 
InitCrashReporter()58 void InitCrashReporter() {
59   struct sigaction action {};
60   action.sa_sigaction = HandleFatalSignal;
61   action.sa_flags = SA_SIGINFO | SA_ONSTACK;
62   sigfillset(&action.sa_mask);
63 
64   sigaction(SIGSEGV, &action, &g_orig_action[SIGSEGV]);
65   sigaction(SIGILL, &action, &g_orig_action[SIGILL]);
66   sigaction(SIGFPE, &action, &g_orig_action[SIGFPE]);
67   sigaction(SIGABRT, &action, &g_orig_action[SIGABRT]);
68 }
69 
70 }  // namespace berberis
71