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
HandleFatalSignal(int sig,siginfo_t * info,void * context)34 void HandleFatalSignal(int sig, siginfo_t* info, void* context) {
35 TRACE("fatal signal %d", sig);
36
37 OnCrash(sig, info, context);
38
39 // Let default crash reporter do the job.
40 // Restore original signal action, as default crash reporter can re-raise the signal.
41 sigaction(sig, &g_orig_action[sig], nullptr);
42 if (g_orig_action[sig].sa_flags & SA_SIGINFO) {
43 // Run original signal action manually and provide actual siginfo and context.
44 g_orig_action[sig].sa_sigaction(sig, info, context);
45 } else {
46 // This should be rare as debuggerd sets siginfo handlers for most signals!
47 // Original action doesn't accept siginfo and context :(
48 // Re-raise the signal as accurate as possible and hope for the best.
49 syscall(SYS_rt_tgsigqueueinfo, GetpidSyscall(), GettidSyscall(), sig, info);
50 }
51 }
52
53 } // namespace
54
InitCrashReporter()55 void InitCrashReporter() {
56 struct sigaction action {};
57 action.sa_sigaction = HandleFatalSignal;
58 action.sa_flags = SA_SIGINFO | SA_ONSTACK;
59 sigfillset(&action.sa_mask);
60
61 sigaction(SIGSEGV, &action, &g_orig_action[SIGSEGV]);
62 sigaction(SIGILL, &action, &g_orig_action[SIGILL]);
63 sigaction(SIGFPE, &action, &g_orig_action[SIGFPE]);
64 sigaction(SIGABRT, &action, &g_orig_action[SIGABRT]);
65 }
66
67 } // namespace berberis
68