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 #ifdef ART_TARGET_ANDROID
18 #include <android/log.h>
19 #else
20 #include <stdarg.h>
21 #include <iostream>
22 #endif
23 
24 #include <dlfcn.h>
25 #include <errno.h>
26 #include <pthread.h>
27 #include <signal.h>
28 #include <stdio.h>
29 #include <stdlib.h>
30 #include <string.h>
31 
32 #include <initializer_list>
33 #include <mutex>
34 #include <utility>
35 
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 #include <ucontext.h>
47 
48 // libsigchain provides an interception layer for signal handlers, to allow ART and others to give
49 // their signal handlers the first stab at handling signals before passing them on to user code.
50 //
51 // It implements wrapper functions for signal, sigaction, and sigprocmask, and a handler that
52 // forwards signals appropriately.
53 //
54 // In our handler, we start off with all signals blocked, fetch the original signal mask from the
55 // passed in ucontext, and then adjust our signal mask appropriately for the user handler.
56 //
57 // It's somewhat tricky for us to properly handle some flag cases:
58 //   SA_NOCLDSTOP and SA_NOCLDWAIT: shouldn't matter, we don't have special handlers for SIGCHLD.
59 //   SA_NODEFER: unimplemented, we can manually change the signal mask appropriately.
60 //  ~SA_ONSTACK: always silently enable this
61 //   SA_RESETHAND: unimplemented, but we can probably do this?
62 //  ~SA_RESTART: unimplemented, maybe we can reserve an RT signal, register an empty handler that
63 //               doesn't have SA_RESTART, and raise the signal to avoid restarting syscalls that are
64 //               expected to be interrupted?
65 
log(const char * format,...)66 static void log(const char* format, ...) {
67   char buf[256];
68   va_list ap;
69   va_start(ap, format);
70   vsnprintf(buf, sizeof(buf), format, ap);
71 #ifdef ART_TARGET_ANDROID
72   __android_log_write(ANDROID_LOG_ERROR, "libsigchain", buf);
73 #else
74   std::cout << buf << "\n";
75 #endif
76   va_end(ap);
77 }
78 
79 #define fatal(...) log(__VA_ARGS__); abort()
80 
sigorset(sigset_t * dest,sigset_t * left,sigset_t * right)81 static int sigorset(sigset_t* dest, sigset_t* left, sigset_t* right) {
82   sigemptyset(dest);
83   for (size_t i = 0; i < sizeof(sigset_t) * 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 
InitializeSignalChain()96 __attribute__((constructor)) static void InitializeSignalChain() {
97   static std::once_flag once;
98   std::call_once(once, []() {
99     void* linked_sigaction_sym = dlsym(RTLD_NEXT, "sigaction");
100     if (linked_sigaction_sym == nullptr) {
101       linked_sigaction_sym = dlsym(RTLD_DEFAULT, "sigaction");
102       if (linked_sigaction_sym == nullptr ||
103           linked_sigaction_sym == reinterpret_cast<void*>(sigaction)) {
104         fatal("Unable to find next sigaction in signal chain");
105       }
106     }
107 
108     void* linked_sigprocmask_sym = dlsym(RTLD_NEXT, "sigprocmask");
109     if (linked_sigprocmask_sym == nullptr) {
110       linked_sigprocmask_sym = dlsym(RTLD_DEFAULT, "sigprocmask");
111       if (linked_sigprocmask_sym == nullptr ||
112           linked_sigprocmask_sym == reinterpret_cast<void*>(sigprocmask)) {
113         fatal("Unable to find next sigprocmask in signal chain");
114       }
115     }
116 
117     linked_sigaction =
118         reinterpret_cast<decltype(linked_sigaction)>(linked_sigaction_sym);
119     linked_sigprocmask =
120         reinterpret_cast<decltype(linked_sigprocmask)>(linked_sigprocmask_sym);
121   });
122 }
123 
124 
GetHandlingSignalKey()125 static pthread_key_t GetHandlingSignalKey() {
126   static pthread_key_t key;
127   static std::once_flag once;
128   std::call_once(once, []() {
129     int rc = pthread_key_create(&key, nullptr);
130     if (rc != 0) {
131       fatal("failed to create sigchain pthread key: %s", strerror(rc));
132     }
133   });
134   return key;
135 }
136 
GetHandlingSignal()137 static bool GetHandlingSignal() {
138   void* result = pthread_getspecific(GetHandlingSignalKey());
139   return reinterpret_cast<uintptr_t>(result);
140 }
141 
SetHandlingSignal(bool value)142 static void SetHandlingSignal(bool value) {
143   pthread_setspecific(GetHandlingSignalKey(),
144                       reinterpret_cast<void*>(static_cast<uintptr_t>(value)));
145 }
146 
147 class ScopedHandlingSignal {
148  public:
ScopedHandlingSignal()149   ScopedHandlingSignal() : original_value_(GetHandlingSignal()) {
150   }
151 
~ScopedHandlingSignal()152   ~ScopedHandlingSignal() {
153     SetHandlingSignal(original_value_);
154   }
155 
156  private:
157   bool original_value_;
158 };
159 
160 class SignalChain {
161  public:
SignalChain()162   SignalChain() : claimed_(false) {
163   }
164 
IsClaimed()165   bool IsClaimed() {
166     return claimed_;
167   }
168 
Claim(int signo)169   void Claim(int signo) {
170     if (!claimed_) {
171       Register(signo);
172       claimed_ = true;
173     }
174   }
175 
176   // Register the signal chain with the kernel if needed.
Register(int signo)177   void Register(int signo) {
178     struct sigaction handler_action = {};
179     handler_action.sa_sigaction = SignalChain::Handler;
180     handler_action.sa_flags = SA_RESTART | SA_SIGINFO | SA_ONSTACK;
181     sigfillset(&handler_action.sa_mask);
182     linked_sigaction(signo, &handler_action, &action_);
183   }
184 
SetAction(const struct sigaction * action)185   void SetAction(const struct sigaction* action) {
186     action_ = *action;
187   }
188 
GetAction()189   struct sigaction GetAction() {
190     return action_;
191   }
192 
AddSpecialHandler(SigchainAction * sa)193   void AddSpecialHandler(SigchainAction* sa) {
194     for (SigchainAction& slot : special_handlers_) {
195       if (slot.sc_sigaction == nullptr) {
196         slot = *sa;
197         return;
198       }
199     }
200 
201     fatal("too many special signal handlers");
202   }
203 
RemoveSpecialHandler(bool (* fn)(int,siginfo_t *,void *))204   void RemoveSpecialHandler(bool (*fn)(int, siginfo_t*, void*)) {
205     // This isn't thread safe, but it's unlikely to be a real problem.
206     size_t len = sizeof(special_handlers_)/sizeof(*special_handlers_);
207     for (size_t i = 0; i < len; ++i) {
208       if (special_handlers_[i].sc_sigaction == fn) {
209         for (size_t j = i; j < len - 1; ++j) {
210           special_handlers_[j] = special_handlers_[j + 1];
211         }
212         special_handlers_[len - 1].sc_sigaction = nullptr;
213         return;
214       }
215     }
216 
217     fatal("failed to find special handler to remove");
218   }
219 
220 
221   static void Handler(int signo, siginfo_t* siginfo, void*);
222 
223  private:
224   bool claimed_;
225   struct sigaction action_;
226   SigchainAction special_handlers_[2];
227 };
228 
229 static SignalChain chains[_NSIG];
230 
Handler(int signo,siginfo_t * siginfo,void * ucontext_raw)231 void SignalChain::Handler(int signo, siginfo_t* siginfo, void* ucontext_raw) {
232   // Try the special handlers first.
233   // If one of them crashes, we'll reenter this handler and pass that crash onto the user handler.
234   if (!GetHandlingSignal()) {
235     for (const auto& handler : chains[signo].special_handlers_) {
236       if (handler.sc_sigaction == nullptr) {
237         break;
238       }
239 
240       // The native bridge signal handler might not return.
241       // Avoid setting the thread local flag in this case, since we'll never
242       // get a chance to restore it.
243       bool handler_noreturn = (handler.sc_flags & SIGCHAIN_ALLOW_NORETURN);
244       sigset_t previous_mask;
245       linked_sigprocmask(SIG_SETMASK, &handler.sc_mask, &previous_mask);
246 
247       ScopedHandlingSignal restorer;
248       if (!handler_noreturn) {
249         SetHandlingSignal(true);
250       }
251 
252       if (handler.sc_sigaction(signo, siginfo, ucontext_raw)) {
253         return;
254       }
255 
256       linked_sigprocmask(SIG_SETMASK, &previous_mask, nullptr);
257     }
258   }
259 
260   // Forward to the user's signal handler.
261   int handler_flags = chains[signo].action_.sa_flags;
262   ucontext_t* ucontext = static_cast<ucontext_t*>(ucontext_raw);
263   sigset_t mask;
264   sigorset(&mask, &ucontext->uc_sigmask, &chains[signo].action_.sa_mask);
265   if (!(handler_flags & SA_NODEFER)) {
266     sigaddset(&mask, signo);
267   }
268   linked_sigprocmask(SIG_SETMASK, &mask, nullptr);
269 
270   if ((handler_flags & SA_SIGINFO)) {
271     chains[signo].action_.sa_sigaction(signo, siginfo, ucontext_raw);
272   } else {
273     auto handler = chains[signo].action_.sa_handler;
274     if (handler == SIG_IGN) {
275       return;
276     } else if (handler == SIG_DFL) {
277       fatal("exiting due to SIG_DFL handler for signal %d", signo);
278     } else {
279       handler(signo);
280     }
281   }
282 }
283 
sigaction(int signal,const struct sigaction * new_action,struct sigaction * old_action)284 extern "C" int sigaction(int signal, const struct sigaction* new_action, struct sigaction* old_action) {
285   InitializeSignalChain();
286 
287   // If this signal has been claimed as a signal chain, record the user's
288   // action but don't pass it on to the kernel.
289   // Note that we check that the signal number is in range here.  An out of range signal
290   // number should behave exactly as the libc sigaction.
291   if (signal < 0 || signal >= _NSIG) {
292     errno = EINVAL;
293     return -1;
294   }
295 
296   if (chains[signal].IsClaimed()) {
297     struct sigaction saved_action = chains[signal].GetAction();
298     if (new_action != nullptr) {
299       chains[signal].SetAction(new_action);
300     }
301     if (old_action != nullptr) {
302       *old_action = saved_action;
303     }
304     return 0;
305   }
306 
307   // Will only get here if the signal chain has not been claimed.  We want
308   // to pass the sigaction on to the kernel via the real sigaction in libc.
309   return linked_sigaction(signal, new_action, old_action);
310 }
311 
signal(int signo,sighandler_t handler)312 extern "C" sighandler_t signal(int signo, sighandler_t handler) {
313   InitializeSignalChain();
314 
315   if (signo < 0 || signo > _NSIG) {
316     errno = EINVAL;
317     return SIG_ERR;
318   }
319 
320   struct sigaction sa = {};
321   sigemptyset(&sa.sa_mask);
322   sa.sa_handler = handler;
323   sa.sa_flags = SA_RESTART | SA_ONSTACK;
324   sighandler_t oldhandler;
325 
326   // If this signal has been claimed as a signal chain, record the user's
327   // action but don't pass it on to the kernel.
328   if (chains[signo].IsClaimed()) {
329     oldhandler = reinterpret_cast<sighandler_t>(chains[signo].GetAction().sa_handler);
330     chains[signo].SetAction(&sa);
331     return oldhandler;
332   }
333 
334   // Will only get here if the signal chain has not been claimed.  We want
335   // to pass the sigaction on to the kernel via the real sigaction in libc.
336   if (linked_sigaction(signo, &sa, &sa) == -1) {
337     return SIG_ERR;
338   }
339 
340   return reinterpret_cast<sighandler_t>(sa.sa_handler);
341 }
342 
343 #if !defined(__LP64__)
bsd_signal(int signo,sighandler_t handler)344 extern "C" sighandler_t bsd_signal(int signo, sighandler_t handler) {
345   InitializeSignalChain();
346 
347   return signal(signo, handler);
348 }
349 #endif
350 
sigprocmask(int how,const sigset_t * bionic_new_set,sigset_t * bionic_old_set)351 extern "C" int sigprocmask(int how, const sigset_t* bionic_new_set, sigset_t* bionic_old_set) {
352   InitializeSignalChain();
353 
354   // When inside a signal handler, forward directly to the actual sigprocmask.
355   if (GetHandlingSignal()) {
356     return linked_sigprocmask(how, bionic_new_set, bionic_old_set);
357   }
358 
359   const sigset_t* new_set_ptr = bionic_new_set;
360   sigset_t tmpset;
361   if (bionic_new_set != nullptr) {
362     tmpset = *bionic_new_set;
363 
364     if (how == SIG_BLOCK) {
365       // Don't allow claimed signals in the mask.  If a signal chain has been claimed
366       // we can't allow the user to block that signal.
367       for (int i = 0 ; i < _NSIG; ++i) {
368         if (chains[i].IsClaimed() && sigismember(&tmpset, i)) {
369           sigdelset(&tmpset, i);
370         }
371       }
372     }
373     new_set_ptr = &tmpset;
374   }
375 
376   return linked_sigprocmask(how, new_set_ptr, bionic_old_set);
377 }
378 
AddSpecialSignalHandlerFn(int signal,SigchainAction * sa)379 extern "C" void AddSpecialSignalHandlerFn(int signal, SigchainAction* sa) {
380   InitializeSignalChain();
381 
382   if (signal <= 0 || signal >= _NSIG) {
383     fatal("Invalid signal %d", signal);
384   }
385 
386   // Set the managed_handler.
387   chains[signal].AddSpecialHandler(sa);
388   chains[signal].Claim(signal);
389 }
390 
RemoveSpecialSignalHandlerFn(int signal,bool (* fn)(int,siginfo_t *,void *))391 extern "C" void RemoveSpecialSignalHandlerFn(int signal, bool (*fn)(int, siginfo_t*, void*)) {
392   InitializeSignalChain();
393 
394   if (signal <= 0 || signal >= _NSIG) {
395     fatal("Invalid signal %d", signal);
396   }
397 
398   chains[signal].RemoveSpecialHandler(fn);
399 }
400 
EnsureFrontOfChain(int signal)401 extern "C" void EnsureFrontOfChain(int signal) {
402   InitializeSignalChain();
403 
404   if (signal <= 0 || signal >= _NSIG) {
405     fatal("Invalid signal %d", signal);
406   }
407 
408   // Read the current action without looking at the chain, it should be the expected action.
409   struct sigaction current_action;
410   linked_sigaction(signal, nullptr, &current_action);
411 
412   // If the sigactions don't match then we put the current action on the chain and make ourself as
413   // the main action.
414   if (current_action.sa_sigaction != SignalChain::Handler) {
415     log("Warning: Unexpected sigaction action found %p\n", current_action.sa_sigaction);
416     chains[signal].Register(signal);
417   }
418 }
419 
420 }   // namespace art
421 
422