1 /*
2 * Copyright (C) 2014 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 <dlfcn.h>
18 #include <errno.h>
19 #include <inttypes.h>
20 #include <pthread.h>
21 #include <signal.h>
22 #include <stdio.h>
23 #include <stdlib.h>
24 #include <string.h>
25
26 #if defined(__BIONIC__)
27 #include <bionic/macros.h>
28 #include <unwindstack/AndroidUnwinder.h>
29 #endif
30
31 #include <algorithm>
32 #include <atomic>
33 #include <initializer_list>
34 #include <mutex>
35 #include <type_traits>
36 #include <utility>
37
38 #include "log.h"
39 #include "sigchain.h"
40
41 #if defined(__APPLE__)
42 #define _NSIG NSIG
43 #define sighandler_t sig_t
44
45 // Darwin has an #error when ucontext.h is included without _XOPEN_SOURCE defined.
46 #define _XOPEN_SOURCE
47 #endif
48
49 #define SA_UNSUPPORTED 0x00000400
50 #define SA_EXPOSE_TAGBITS 0x00000800
51
52 #include <ucontext.h>
53
54 // libsigchain provides an interception layer for signal handlers, to allow ART and others to give
55 // their signal handlers the first stab at handling signals before passing them on to user code.
56 //
57 // It implements wrapper functions for signal, sigaction, and sigprocmask, and a handler that
58 // forwards signals appropriately.
59 //
60 // In our handler, we start off with all signals blocked, fetch the original signal mask from the
61 // passed in ucontext, and then adjust our signal mask appropriately for the user handler.
62 //
63 // It's somewhat tricky for us to properly handle some flag cases:
64 // SA_NOCLDSTOP and SA_NOCLDWAIT: shouldn't matter, we don't have special handlers for SIGCHLD.
65 // SA_NODEFER: unimplemented, we can manually change the signal mask appropriately.
66 // ~SA_ONSTACK: always silently enable this
67 // SA_RESETHAND: unimplemented, but we can probably do this?
68 // ~SA_RESTART: unimplemented, maybe we can reserve an RT signal, register an empty handler that
69 // doesn't have SA_RESTART, and raise the signal to avoid restarting syscalls that are
70 // expected to be interrupted?
71
72 #if defined(__BIONIC__) && !defined(__LP64__)
sigismember(const sigset64_t * sigset,int signum)73 static int sigismember(const sigset64_t* sigset, int signum) {
74 return sigismember64(sigset, signum);
75 }
76
sigemptyset(sigset64_t * sigset)77 static int sigemptyset(sigset64_t* sigset) {
78 return sigemptyset64(sigset);
79 }
80
sigaddset(sigset64_t * sigset,int signum)81 static int sigaddset(sigset64_t* sigset, int signum) {
82 return sigaddset64(sigset, signum);
83 }
84
sigdelset(sigset64_t * sigset,int signum)85 static int sigdelset(sigset64_t* sigset, int signum) {
86 return sigdelset64(sigset, signum);
87 }
88 #endif
89
90 template<typename SigsetType>
sigorset(SigsetType * dest,SigsetType * left,SigsetType * right)91 static int sigorset(SigsetType* dest, SigsetType* left, SigsetType* right) {
92 sigemptyset(dest);
93 for (size_t i = 0; i < sizeof(SigsetType) * CHAR_BIT; ++i) {
94 if (sigismember(left, i) == 1 || sigismember(right, i) == 1) {
95 sigaddset(dest, i);
96 }
97 }
98 return 0;
99 }
100
LogStack()101 void LogStack() {
102 #if defined(__BIONIC__)
103 unwindstack::AndroidLocalUnwinder unwinder;
104 unwindstack::AndroidUnwinderData data;
105 if (!unwinder.Unwind(data)) {
106 LogError("Failed to get callstack.");
107 return;
108 }
109 data.DemangleFunctionNames();
110 for (const unwindstack::FrameData& frame : data.frames) {
111 auto& map = frame.map_info;
112 LogError(" #%02zu pc %08" PRIx64 " %s (%s+%" PRIu64 ") (BuildId: %s)",
113 frame.num,
114 frame.rel_pc,
115 map != nullptr ? map->name().c_str() : "???",
116 frame.function_name.c_str(),
117 frame.function_offset,
118 map != nullptr ? map->GetPrintableBuildID().c_str() : "???");
119 }
120 #endif
121 }
122
123 namespace art {
124
125 static decltype(&sigaction) linked_sigaction;
126 static decltype(&sigprocmask) linked_sigprocmask;
127
128 #if defined(__BIONIC__)
129 static decltype(&sigaction64) linked_sigaction64;
130 static decltype(&sigprocmask64) linked_sigprocmask64;
131 #endif
132
133 template <typename T>
lookup_libc_symbol(T * output,T wrapper,const char * name)134 static void lookup_libc_symbol(T* output, T wrapper, const char* name) {
135 #if defined(__BIONIC__)
136 constexpr const char* libc_name = "libc.so";
137 #elif defined(__GLIBC__)
138 #if __GNU_LIBRARY__ != 6
139 #error unsupported glibc version
140 #endif
141 constexpr const char* libc_name = "libc.so.6";
142 #elif defined(ANDROID_HOST_MUSL)
143 constexpr const char* libc_name = "libc_musl.so";
144 #else
145 #error unsupported libc: not bionic or glibc?
146 #endif
147
148 static void* libc = []() {
149 void* result = dlopen(libc_name, RTLD_LOCAL | RTLD_LAZY);
150 if (!result) {
151 fatal("failed to dlopen %s: %s", libc_name, dlerror());
152 }
153 return result;
154 }();
155
156 void* sym = dlsym(libc, name); // NOLINT glibc triggers cert-dcl16-c with RTLD_NEXT.
157 if (sym == nullptr) {
158 sym = dlsym(RTLD_DEFAULT, name);
159 if (sym == wrapper || sym == sigaction) {
160 fatal("Unable to find next %s in signal chain", name);
161 }
162 }
163 *output = reinterpret_cast<T>(sym);
164 }
165
InitializeSignalChain()166 __attribute__((constructor)) static void InitializeSignalChain() {
167 static std::once_flag once;
168 std::call_once(once, []() {
169 lookup_libc_symbol(&linked_sigaction, sigaction, "sigaction");
170 lookup_libc_symbol(&linked_sigprocmask, sigprocmask, "sigprocmask");
171
172 #if defined(__BIONIC__)
173 lookup_libc_symbol(&linked_sigaction64, sigaction64, "sigaction64");
174 lookup_libc_symbol(&linked_sigprocmask64, sigprocmask64, "sigprocmask64");
175 #endif
176 });
177 }
178
179 template <typename T>
IsPowerOfTwo(T x)180 static constexpr bool IsPowerOfTwo(T x) {
181 static_assert(std::is_integral_v<T>, "T must be integral");
182 static_assert(std::is_unsigned_v<T>, "T must be unsigned");
183 return (x & (x - 1)) == 0;
184 }
185
186 template <typename T>
RoundUp(T x,T n)187 static constexpr T RoundUp(T x, T n) {
188 return (x + n - 1) & -n;
189 }
190 // Use a bitmap to indicate which signal is being handled so that other
191 // non-blocked signals are allowed to be handled, if raised.
192 static constexpr size_t kSignalSetLength = _NSIG - 1;
193 static constexpr size_t kNumSignalsPerKey = std::numeric_limits<uintptr_t>::digits;
194 static_assert(IsPowerOfTwo(kNumSignalsPerKey));
195 static constexpr size_t kHandlingSignalKeyCount =
196 RoundUp(kSignalSetLength, kNumSignalsPerKey) / kNumSignalsPerKey;
197
198 // We rely on bionic's implementation of pthread_(get/set)specific being
199 // async-signal safe.
GetHandlingSignalKey(size_t idx)200 static pthread_key_t GetHandlingSignalKey(size_t idx) {
201 static pthread_key_t key[kHandlingSignalKeyCount];
202 static std::once_flag once;
203 std::call_once(once, []() {
204 for (size_t i = 0; i < kHandlingSignalKeyCount; i++) {
205 int rc = pthread_key_create(&key[i], nullptr);
206 if (rc != 0) {
207 fatal("failed to create sigchain pthread key: %s", strerror(rc));
208 }
209 }
210 });
211 return key[idx];
212 }
213
GetHandlingSignal()214 static bool GetHandlingSignal() {
215 for (size_t i = 0; i < kHandlingSignalKeyCount; i++) {
216 void* result = pthread_getspecific(GetHandlingSignalKey(i));
217 if (reinterpret_cast<uintptr_t>(result) != 0) {
218 return true;
219 }
220 }
221 return false;
222 }
223
GetHandlingSignal(int signo)224 static bool GetHandlingSignal(int signo) {
225 size_t bit_idx = signo - 1;
226 size_t key_idx = bit_idx / kNumSignalsPerKey;
227 uintptr_t bit_mask = static_cast<uintptr_t>(1) << (bit_idx % kNumSignalsPerKey);
228 uintptr_t result =
229 reinterpret_cast<uintptr_t>(pthread_getspecific(GetHandlingSignalKey(key_idx)));
230 return result & bit_mask;
231 }
232
SetHandlingSignal(int signo,bool value)233 static bool SetHandlingSignal(int signo, bool value) {
234 // Use signal-fence to ensure that compiler doesn't reorder generated code
235 // across signal handlers.
236 size_t bit_idx = signo - 1;
237 size_t key_idx = bit_idx / kNumSignalsPerKey;
238 uintptr_t bit_mask = static_cast<uintptr_t>(1) << (bit_idx % kNumSignalsPerKey);
239 pthread_key_t key = GetHandlingSignalKey(key_idx);
240 std::atomic_signal_fence(std::memory_order_seq_cst);
241 uintptr_t bitmap = reinterpret_cast<uintptr_t>(pthread_getspecific(key));
242 bool ret = bitmap & bit_mask;
243 if (value) {
244 bitmap |= bit_mask;
245 } else {
246 bitmap &= ~bit_mask;
247 }
248 pthread_setspecific(key, reinterpret_cast<void*>(bitmap));
249 std::atomic_signal_fence(std::memory_order_seq_cst);
250 return ret;
251 }
252
253 class ScopedHandlingSignal {
254 public:
ScopedHandlingSignal(int signo,bool set)255 ScopedHandlingSignal(int signo, bool set)
256 : signo_(signo),
257 original_value_(set ? SetHandlingSignal(signo, true) : GetHandlingSignal(signo)) {}
258
~ScopedHandlingSignal()259 ~ScopedHandlingSignal() {
260 SetHandlingSignal(signo_, original_value_);
261 }
262
263 private:
264 int signo_;
265 bool original_value_;
266 };
267
268 class SignalChain {
269 public:
SignalChain()270 SignalChain() : claimed_(false) {
271 }
272
IsClaimed()273 bool IsClaimed() {
274 return claimed_;
275 }
276
Claim(int signo)277 void Claim(int signo) {
278 if (!claimed_) {
279 Register(signo);
280 claimed_ = true;
281 }
282 }
283
284 // Register the signal chain with the kernel if needed.
Register(int signo)285 void Register(int signo) {
286 #if defined(__BIONIC__)
287 struct sigaction64 handler_action = {};
288 sigfillset64(&handler_action.sa_mask);
289 #else
290 struct sigaction handler_action = {};
291 sigfillset(&handler_action.sa_mask);
292 #endif
293
294 handler_action.sa_sigaction = SignalChain::Handler;
295 handler_action.sa_flags = SA_RESTART | SA_SIGINFO | SA_ONSTACK |
296 SA_UNSUPPORTED | SA_EXPOSE_TAGBITS;
297
298 #if defined(__BIONIC__)
299 linked_sigaction64(signo, &handler_action, &action_);
300 linked_sigaction64(signo, nullptr, &handler_action);
301 #else
302 linked_sigaction(signo, &handler_action, &action_);
303 linked_sigaction(signo, nullptr, &handler_action);
304 #endif
305
306 // Newer kernels clear unknown flags from sigaction.sa_flags in order to
307 // allow userspace to determine which flag bits are supported. We use this
308 // behavior in turn to implement the same flag bit support detection
309 // protocol regardless of kernel version. Due to the lack of a flag bit
310 // support detection protocol in older kernels we assume support for a base
311 // set of flags that have been supported since at least 2003 [1]. No flags
312 // were introduced since then until the introduction of SA_EXPOSE_TAGBITS
313 // handled below. glibc headers do not define SA_RESTORER so we define it
314 // ourselves.
315 //
316 // TODO(pcc): The new kernel behavior has been implemented in a kernel
317 // patch [2] that has not yet landed. Update the code if necessary once it
318 // lands.
319 //
320 // [1] https://github.com/mpe/linux-fullhistory/commit/c0f806c86fc8b07ad426df023f1a4bb0e53c64f6
321 // [2] https://lore.kernel.org/linux-arm-kernel/cover.1605235762.git.pcc@google.com/
322 #if !defined(__BIONIC__)
323 #define SA_RESTORER 0x04000000
324 #endif
325 kernel_supported_flags_ = SA_NOCLDSTOP | SA_NOCLDWAIT | SA_SIGINFO | SA_ONSTACK | SA_RESTART |
326 SA_NODEFER | SA_RESETHAND;
327 #if defined(SA_RESTORER)
328 kernel_supported_flags_ |= SA_RESTORER;
329 #endif
330
331 // Determine whether the kernel supports SA_EXPOSE_TAGBITS. For newer
332 // kernels we use the flag support detection protocol described above. In
333 // order to allow userspace to distinguish old and new kernels,
334 // SA_UNSUPPORTED has been reserved as an unsupported flag. If the kernel
335 // did not clear it then we know that we have an old kernel that would not
336 // support SA_EXPOSE_TAGBITS anyway.
337 if (!(handler_action.sa_flags & SA_UNSUPPORTED) &&
338 (handler_action.sa_flags & SA_EXPOSE_TAGBITS)) {
339 kernel_supported_flags_ |= SA_EXPOSE_TAGBITS;
340 }
341 }
342
343 template <typename SigactionType>
GetAction()344 SigactionType GetAction() {
345 if constexpr (std::is_same_v<decltype(action_), SigactionType>) {
346 return action_;
347 } else {
348 SigactionType result;
349 result.sa_flags = action_.sa_flags;
350 result.sa_handler = action_.sa_handler;
351 #if defined(SA_RESTORER)
352 result.sa_restorer = action_.sa_restorer;
353 #endif
354 memcpy(&result.sa_mask, &action_.sa_mask,
355 std::min(sizeof(action_.sa_mask), sizeof(result.sa_mask)));
356 return result;
357 }
358 }
359
360 template <typename SigactionType>
SetAction(const SigactionType * new_action)361 void SetAction(const SigactionType* new_action) {
362 if constexpr (std::is_same_v<decltype(action_), SigactionType>) {
363 action_ = *new_action;
364 } else {
365 action_.sa_flags = new_action->sa_flags;
366 action_.sa_handler = new_action->sa_handler;
367 #if defined(SA_RESTORER)
368 action_.sa_restorer = new_action->sa_restorer;
369 #endif
370 sigemptyset(&action_.sa_mask);
371 memcpy(&action_.sa_mask, &new_action->sa_mask,
372 std::min(sizeof(action_.sa_mask), sizeof(new_action->sa_mask)));
373 }
374 action_.sa_flags &= kernel_supported_flags_;
375 }
376
AddSpecialHandler(SigchainAction * sa)377 void AddSpecialHandler(SigchainAction* sa) {
378 for (SigchainAction& slot : special_handlers_) {
379 if (slot.sc_sigaction == nullptr) {
380 slot = *sa;
381 return;
382 }
383 }
384
385 fatal("too many special signal handlers");
386 }
387
RemoveSpecialHandler(bool (* fn)(int,siginfo_t *,void *))388 void RemoveSpecialHandler(bool (*fn)(int, siginfo_t*, void*)) {
389 // This isn't thread safe, but it's unlikely to be a real problem.
390 size_t len = sizeof(special_handlers_)/sizeof(*special_handlers_);
391 for (size_t i = 0; i < len; ++i) {
392 if (special_handlers_[i].sc_sigaction == fn) {
393 for (size_t j = i; j < len - 1; ++j) {
394 special_handlers_[j] = special_handlers_[j + 1];
395 }
396 special_handlers_[len - 1].sc_sigaction = nullptr;
397 return;
398 }
399 }
400
401 fatal("failed to find special handler to remove");
402 }
403
404
405 static void Handler(int signo, siginfo_t* siginfo, void*);
406
407 private:
408 bool claimed_;
409 int kernel_supported_flags_;
410 #if defined(__BIONIC__)
411 struct sigaction64 action_;
412 #else
413 struct sigaction action_;
414 #endif
415 SigchainAction special_handlers_[2];
416 };
417
418 // _NSIG is 1 greater than the highest valued signal, but signals start from 1.
419 // Leave an empty element at index 0 for convenience.
420 static SignalChain chains[_NSIG];
421
422 static bool is_signal_hook_debuggable = false;
423
424 // Weak linkage, as the ART APEX might be deployed on devices where this symbol doesn't exist (i.e.
425 // all OS's before Android U). This symbol comes from libdl.
426 __attribute__((weak)) extern "C" bool android_handle_signal(int signal_number,
427 siginfo_t* info,
428 void* context);
429
Handler(int signo,siginfo_t * siginfo,void * ucontext_raw)430 void SignalChain::Handler(int signo, siginfo_t* siginfo, void* ucontext_raw) {
431 // Try the special handlers first.
432 // If one of them crashes, we'll reenter this handler and pass that crash onto the user handler.
433 if (!GetHandlingSignal(signo)) {
434 for (const auto& handler : chains[signo].special_handlers_) {
435 if (handler.sc_sigaction == nullptr) {
436 break;
437 }
438
439 // The native bridge signal handler might not return.
440 // Avoid setting the thread local flag in this case, since we'll never
441 // get a chance to restore it.
442 bool handler_noreturn = (handler.sc_flags & SIGCHAIN_ALLOW_NORETURN);
443 sigset_t previous_mask;
444 linked_sigprocmask(SIG_SETMASK, &handler.sc_mask, &previous_mask);
445
446 ScopedHandlingSignal restorer(signo, !handler_noreturn);
447
448 if (handler.sc_sigaction(signo, siginfo, ucontext_raw)) {
449 return;
450 }
451
452 linked_sigprocmask(SIG_SETMASK, &previous_mask, nullptr);
453 }
454 } else {
455 #if defined(__aarch64__)
456 // Log the specific value if we're handling more than one signal (or if the bit is
457 // concurrently cleared) to help diagnose rare crashes. Multiple bits set may
458 // indicate memory corruption of the specific value in TLS. Bugs: 304237198, 294339122.
459 size_t bit_idx = signo - 1;
460 size_t key_idx = bit_idx / kNumSignalsPerKey;
461 uintptr_t expected = static_cast<uintptr_t>(1) << (bit_idx % kNumSignalsPerKey);
462 uintptr_t value =
463 reinterpret_cast<uintptr_t>(pthread_getspecific(GetHandlingSignalKey(key_idx)));
464 if (value != expected) {
465 LogError(
466 "Already handling signal %d, value=0x%" PRIxPTR " differs from expected=0x%" PRIxPTR,
467 signo,
468 value,
469 expected);
470 }
471 #endif
472 }
473
474 // In Android 14, there's a special feature called "recoverable" GWP-ASan. GWP-ASan is a tool that
475 // finds heap-buffer-overflow and heap-use-after-free on native heap allocations (e.g. malloc()
476 // inside of JNI, not the ART heap). The way it catches buffer overflow (roughly) is by rounding
477 // up the malloc() so that it's page-sized, and mapping an inaccessible page on the left- and
478 // right-hand side. It catches use-after-free by mprotecting the allocation page to be PROT_NONE
479 // on free(). The new "recoverable" mode is designed to allow debuggerd to print a crash report,
480 // but for the app or process in question to not crash (i.e. recover) and continue even after the
481 // bug is detected. Sigchain thus must allow debuggerd to handle the signal first, and if
482 // debuggerd has promised that it can recover, and it's done the steps to allow recovery (as
483 // identified by android_handle_signal returning true), then we should return from this handler
484 // and let the app continue.
485 //
486 // For all non-GWP-ASan-recoverable crashes, or crashes where recovery is not possible,
487 // android_handle_signal returns false, and we will continue to the rest of the sigchain handler
488 // logic.
489 if (android_handle_signal != nullptr && android_handle_signal(signo, siginfo, ucontext_raw)) {
490 return;
491 }
492
493 // Forward to the user's signal handler.
494 int handler_flags = chains[signo].action_.sa_flags;
495 ucontext_t* ucontext = static_cast<ucontext_t*>(ucontext_raw);
496 #if defined(__BIONIC__)
497 sigset64_t mask;
498 sigorset(&mask, &ucontext->uc_sigmask64, &chains[signo].action_.sa_mask);
499 #else
500 sigset_t mask;
501 sigorset(&mask, &ucontext->uc_sigmask, &chains[signo].action_.sa_mask);
502 #endif
503 if (!(handler_flags & SA_NODEFER)) {
504 sigaddset(&mask, signo);
505 }
506
507 #if defined(__BIONIC__)
508 linked_sigprocmask64(SIG_SETMASK, &mask, nullptr);
509 #else
510 linked_sigprocmask(SIG_SETMASK, &mask, nullptr);
511 #endif
512
513 if ((handler_flags & SA_SIGINFO)) {
514 // If the chained handler is not expecting tag bits in the fault address,
515 // mask them out now.
516 #if defined(__BIONIC__)
517 if (!(handler_flags & SA_EXPOSE_TAGBITS) &&
518 (signo == SIGILL || signo == SIGFPE || signo == SIGSEGV ||
519 signo == SIGBUS || signo == SIGTRAP) &&
520 siginfo->si_code > SI_USER && siginfo->si_code < SI_KERNEL &&
521 !(signo == SIGTRAP && siginfo->si_code == TRAP_HWBKPT)) {
522 siginfo->si_addr = untag_address(siginfo->si_addr);
523 }
524 #endif
525 chains[signo].action_.sa_sigaction(signo, siginfo, ucontext_raw);
526 } else {
527 auto handler = chains[signo].action_.sa_handler;
528 if (handler == SIG_IGN) {
529 return;
530 } else if (handler == SIG_DFL) {
531 // We'll only get here if debuggerd is disabled. In that case, whatever next tries to handle
532 // the crash will have no way to know our ucontext, and thus no way to dump the original crash
533 // stack (since we're on an alternate stack.) Let's remove our handler and return. Then the
534 // pre-crash state is restored, the crash happens again, and the next handler gets a chance.
535 LogError("reverting to SIG_DFL handler for signal %d, ucontext %p", signo, ucontext);
536 LogStack();
537 struct sigaction dfl = {};
538 dfl.sa_handler = SIG_DFL;
539 linked_sigaction(signo, &dfl, nullptr);
540 return;
541 } else {
542 handler(signo);
543 }
544 }
545 }
546
547 template <typename SigactionType>
__sigaction(int signal,const SigactionType * new_action,SigactionType * old_action,int (* linked)(int,const SigactionType *,SigactionType *))548 static int __sigaction(int signal, const SigactionType* new_action,
549 SigactionType* old_action,
550 int (*linked)(int, const SigactionType*,
551 SigactionType*)) {
552 if (is_signal_hook_debuggable) {
553 return 0;
554 }
555
556 // If this signal has been claimed as a signal chain, record the user's
557 // action but don't pass it on to the kernel.
558 // Note that we check that the signal number is in range here. An out of range signal
559 // number should behave exactly as the libc sigaction.
560 if (signal <= 0 || signal >= _NSIG) {
561 errno = EINVAL;
562 return -1;
563 }
564
565 if (signal == SIGSEGV && new_action != nullptr && new_action->sa_handler == SIG_DFL) {
566 LogError("Setting SIGSEGV to SIG_DFL");
567 LogStack();
568 }
569
570 if (chains[signal].IsClaimed()) {
571 SigactionType saved_action = chains[signal].GetAction<SigactionType>();
572 if (new_action != nullptr) {
573 chains[signal].SetAction(new_action);
574 }
575 if (old_action != nullptr) {
576 *old_action = saved_action;
577 }
578 return 0;
579 }
580
581 // Will only get here if the signal chain has not been claimed. We want
582 // to pass the sigaction on to the kernel via the real sigaction in libc.
583 return linked(signal, new_action, old_action);
584 }
585
sigaction(int signal,const struct sigaction * new_action,struct sigaction * old_action)586 extern "C" int sigaction(int signal, const struct sigaction* new_action,
587 struct sigaction* old_action) {
588 InitializeSignalChain();
589 return __sigaction(signal, new_action, old_action, linked_sigaction);
590 }
591
592 #if defined(__BIONIC__)
sigaction64(int signal,const struct sigaction64 * new_action,struct sigaction64 * old_action)593 extern "C" int sigaction64(int signal, const struct sigaction64* new_action,
594 struct sigaction64* old_action) {
595 InitializeSignalChain();
596 return __sigaction(signal, new_action, old_action, linked_sigaction64);
597 }
598 #endif
599
signal(int signo,sighandler_t handler)600 extern "C" sighandler_t signal(int signo, sighandler_t handler) {
601 InitializeSignalChain();
602
603 if (signo <= 0 || signo >= _NSIG) {
604 errno = EINVAL;
605 return SIG_ERR;
606 }
607
608 struct sigaction sa = {};
609 sigemptyset(&sa.sa_mask);
610 sa.sa_handler = handler;
611 sa.sa_flags = SA_RESTART | SA_ONSTACK;
612 sighandler_t oldhandler;
613
614 // If this signal has been claimed as a signal chain, record the user's
615 // action but don't pass it on to the kernel.
616 if (chains[signo].IsClaimed()) {
617 oldhandler = reinterpret_cast<sighandler_t>(
618 chains[signo].GetAction<struct sigaction>().sa_handler);
619 chains[signo].SetAction(&sa);
620 return oldhandler;
621 }
622
623 // Will only get here if the signal chain has not been claimed. We want
624 // to pass the sigaction on to the kernel via the real sigaction in libc.
625 if (linked_sigaction(signo, &sa, &sa) == -1) {
626 return SIG_ERR;
627 }
628
629 return reinterpret_cast<sighandler_t>(sa.sa_handler);
630 }
631
632 #if !defined(__LP64__)
bsd_signal(int signo,sighandler_t handler)633 extern "C" sighandler_t bsd_signal(int signo, sighandler_t handler) {
634 InitializeSignalChain();
635
636 return signal(signo, handler);
637 }
638 #endif
639
640 template <typename SigsetType>
__sigprocmask(int how,const SigsetType * new_set,SigsetType * old_set,int (* linked)(int,const SigsetType *,SigsetType *))641 int __sigprocmask(int how, const SigsetType* new_set, SigsetType* old_set,
642 int (*linked)(int, const SigsetType*, SigsetType*)) {
643 // When inside a signal handler, forward directly to the actual sigprocmask.
644 if (GetHandlingSignal()) {
645 return linked(how, new_set, old_set);
646 }
647
648 const SigsetType* new_set_ptr = new_set;
649 SigsetType tmpset;
650 if (new_set != nullptr) {
651 tmpset = *new_set;
652
653 if (how == SIG_BLOCK || how == SIG_SETMASK) {
654 // Don't allow claimed signals in the mask. If a signal chain has been claimed
655 // we can't allow the user to block that signal.
656 for (int i = 1; i < _NSIG; ++i) {
657 if (chains[i].IsClaimed() && sigismember(&tmpset, i)) {
658 sigdelset(&tmpset, i);
659 }
660 }
661 }
662 new_set_ptr = &tmpset;
663 }
664
665 return linked(how, new_set_ptr, old_set);
666 }
667
sigprocmask(int how,const sigset_t * new_set,sigset_t * old_set)668 extern "C" int sigprocmask(int how, const sigset_t* new_set,
669 sigset_t* old_set) {
670 InitializeSignalChain();
671 return __sigprocmask(how, new_set, old_set, linked_sigprocmask);
672 }
673
674 #if defined(__BIONIC__)
sigprocmask64(int how,const sigset64_t * new_set,sigset64_t * old_set)675 extern "C" int sigprocmask64(int how, const sigset64_t* new_set,
676 sigset64_t* old_set) {
677 InitializeSignalChain();
678 return __sigprocmask(how, new_set, old_set, linked_sigprocmask64);
679 }
680 #endif
681
AddSpecialSignalHandlerFn(int signal,SigchainAction * sa)682 extern "C" void AddSpecialSignalHandlerFn(int signal, SigchainAction* sa) {
683 InitializeSignalChain();
684
685 if (signal <= 0 || signal >= _NSIG) {
686 fatal("Invalid signal %d", signal);
687 }
688
689 // Set the managed_handler.
690 chains[signal].AddSpecialHandler(sa);
691 chains[signal].Claim(signal);
692 }
693
RemoveSpecialSignalHandlerFn(int signal,bool (* fn)(int,siginfo_t *,void *))694 extern "C" void RemoveSpecialSignalHandlerFn(int signal, bool (*fn)(int, siginfo_t*, void*)) {
695 InitializeSignalChain();
696
697 if (signal <= 0 || signal >= _NSIG) {
698 fatal("Invalid signal %d", signal);
699 }
700
701 chains[signal].RemoveSpecialHandler(fn);
702 }
703
EnsureFrontOfChain(int signal)704 extern "C" void EnsureFrontOfChain(int signal) {
705 InitializeSignalChain();
706
707 if (signal <= 0 || signal >= _NSIG) {
708 fatal("Invalid signal %d", signal);
709 }
710
711 // Read the current action without looking at the chain, it should be the expected action.
712 #if defined(__BIONIC__)
713 struct sigaction64 current_action;
714 linked_sigaction64(signal, nullptr, ¤t_action);
715 #else
716 struct sigaction current_action;
717 linked_sigaction(signal, nullptr, ¤t_action);
718 #endif
719
720 // If the sigactions don't match then we put the current action on the chain and make ourself as
721 // the main action.
722 if (current_action.sa_sigaction != SignalChain::Handler) {
723 LogError("Warning: Unexpected sigaction action found %p\n", current_action.sa_sigaction);
724 chains[signal].Register(signal);
725 }
726 }
727
SkipAddSignalHandler(bool value)728 extern "C" void SkipAddSignalHandler(bool value) {
729 is_signal_hook_debuggable = value;
730 }
731
732 } // namespace art
733
734