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