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