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