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