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__) && !defined(__mips__)
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_next_symbol(T * output,T wrapper,const char * name)102 static void lookup_next_symbol(T* output, T wrapper, const char* name) {
103 void* sym = dlsym(RTLD_NEXT, name); // NOLINT glibc triggers cert-dcl16-c with RTLD_NEXT.
104 if (sym == nullptr) {
105 sym = dlsym(RTLD_DEFAULT, name);
106 if (sym == wrapper || sym == sigaction) {
107 fatal("Unable to find next %s in signal chain", name);
108 }
109 }
110 *output = reinterpret_cast<T>(sym);
111 }
112
InitializeSignalChain()113 __attribute__((constructor)) static void InitializeSignalChain() {
114 static std::once_flag once;
115 std::call_once(once, []() {
116 lookup_next_symbol(&linked_sigaction, sigaction, "sigaction");
117 lookup_next_symbol(&linked_sigprocmask, sigprocmask, "sigprocmask");
118
119 #if defined(__BIONIC__)
120 lookup_next_symbol(&linked_sigaction64, sigaction64, "sigaction64");
121 lookup_next_symbol(&linked_sigprocmask64, sigprocmask64, "sigprocmask64");
122 #endif
123 });
124 }
125
GetHandlingSignalKey()126 static pthread_key_t GetHandlingSignalKey() {
127 static pthread_key_t key;
128 static std::once_flag once;
129 std::call_once(once, []() {
130 int rc = pthread_key_create(&key, nullptr);
131 if (rc != 0) {
132 fatal("failed to create sigchain pthread key: %s", strerror(rc));
133 }
134 });
135 return key;
136 }
137
GetHandlingSignal()138 static bool GetHandlingSignal() {
139 void* result = pthread_getspecific(GetHandlingSignalKey());
140 return reinterpret_cast<uintptr_t>(result);
141 }
142
SetHandlingSignal(bool value)143 static void SetHandlingSignal(bool value) {
144 pthread_setspecific(GetHandlingSignalKey(),
145 reinterpret_cast<void*>(static_cast<uintptr_t>(value)));
146 }
147
148 class ScopedHandlingSignal {
149 public:
ScopedHandlingSignal()150 ScopedHandlingSignal() : original_value_(GetHandlingSignal()) {
151 }
152
~ScopedHandlingSignal()153 ~ScopedHandlingSignal() {
154 SetHandlingSignal(original_value_);
155 }
156
157 private:
158 bool original_value_;
159 };
160
161 class SignalChain {
162 public:
SignalChain()163 SignalChain() : claimed_(false) {
164 }
165
IsClaimed()166 bool IsClaimed() {
167 return claimed_;
168 }
169
Claim(int signo)170 void Claim(int signo) {
171 if (!claimed_) {
172 Register(signo);
173 claimed_ = true;
174 }
175 }
176
177 // Register the signal chain with the kernel if needed.
Register(int signo)178 void Register(int signo) {
179 #if defined(__BIONIC__)
180 struct sigaction64 handler_action = {};
181 sigfillset64(&handler_action.sa_mask);
182 #else
183 struct sigaction handler_action = {};
184 sigfillset(&handler_action.sa_mask);
185 #endif
186
187 handler_action.sa_sigaction = SignalChain::Handler;
188 handler_action.sa_flags = SA_RESTART | SA_SIGINFO | SA_ONSTACK;
189
190 #if defined(__BIONIC__)
191 linked_sigaction64(signo, &handler_action, &action_);
192 #else
193 linked_sigaction(signo, &handler_action, &action_);
194 #endif
195 }
196
197 template <typename SigactionType>
GetAction()198 SigactionType GetAction() {
199 if constexpr (std::is_same_v<decltype(action_), SigactionType>) {
200 return action_;
201 } else {
202 SigactionType result;
203 result.sa_flags = action_.sa_flags;
204 result.sa_handler = action_.sa_handler;
205 #if defined(SA_RESTORER)
206 result.sa_restorer = action_.sa_restorer;
207 #endif
208 memcpy(&result.sa_mask, &action_.sa_mask,
209 std::min(sizeof(action_.sa_mask), sizeof(result.sa_mask)));
210 return result;
211 }
212 }
213
214 template <typename SigactionType>
SetAction(const SigactionType * new_action)215 void SetAction(const SigactionType* new_action) {
216 if constexpr (std::is_same_v<decltype(action_), SigactionType>) {
217 action_ = *new_action;
218 } else {
219 action_.sa_flags = new_action->sa_flags;
220 action_.sa_handler = new_action->sa_handler;
221 #if defined(SA_RESTORER)
222 action_.sa_restorer = new_action->sa_restorer;
223 #endif
224 sigemptyset(&action_.sa_mask);
225 memcpy(&action_.sa_mask, &new_action->sa_mask,
226 std::min(sizeof(action_.sa_mask), sizeof(new_action->sa_mask)));
227 }
228 }
229
AddSpecialHandler(SigchainAction * sa)230 void AddSpecialHandler(SigchainAction* sa) {
231 for (SigchainAction& slot : special_handlers_) {
232 if (slot.sc_sigaction == nullptr) {
233 slot = *sa;
234 return;
235 }
236 }
237
238 fatal("too many special signal handlers");
239 }
240
RemoveSpecialHandler(bool (* fn)(int,siginfo_t *,void *))241 void RemoveSpecialHandler(bool (*fn)(int, siginfo_t*, void*)) {
242 // This isn't thread safe, but it's unlikely to be a real problem.
243 size_t len = sizeof(special_handlers_)/sizeof(*special_handlers_);
244 for (size_t i = 0; i < len; ++i) {
245 if (special_handlers_[i].sc_sigaction == fn) {
246 for (size_t j = i; j < len - 1; ++j) {
247 special_handlers_[j] = special_handlers_[j + 1];
248 }
249 special_handlers_[len - 1].sc_sigaction = nullptr;
250 return;
251 }
252 }
253
254 fatal("failed to find special handler to remove");
255 }
256
257
258 static void Handler(int signo, siginfo_t* siginfo, void*);
259
260 private:
261 bool claimed_;
262 #if defined(__BIONIC__)
263 struct sigaction64 action_;
264 #else
265 struct sigaction action_;
266 #endif
267 SigchainAction special_handlers_[2];
268 };
269
270 // _NSIG is 1 greater than the highest valued signal, but signals start from 1.
271 // Leave an empty element at index 0 for convenience.
272 static SignalChain chains[_NSIG + 1];
273
Handler(int signo,siginfo_t * siginfo,void * ucontext_raw)274 void SignalChain::Handler(int signo, siginfo_t* siginfo, void* ucontext_raw) {
275 // Try the special handlers first.
276 // If one of them crashes, we'll reenter this handler and pass that crash onto the user handler.
277 if (!GetHandlingSignal()) {
278 for (const auto& handler : chains[signo].special_handlers_) {
279 if (handler.sc_sigaction == nullptr) {
280 break;
281 }
282
283 // The native bridge signal handler might not return.
284 // Avoid setting the thread local flag in this case, since we'll never
285 // get a chance to restore it.
286 bool handler_noreturn = (handler.sc_flags & SIGCHAIN_ALLOW_NORETURN);
287 sigset_t previous_mask;
288 linked_sigprocmask(SIG_SETMASK, &handler.sc_mask, &previous_mask);
289
290 ScopedHandlingSignal restorer;
291 if (!handler_noreturn) {
292 SetHandlingSignal(true);
293 }
294
295 if (handler.sc_sigaction(signo, siginfo, ucontext_raw)) {
296 return;
297 }
298
299 linked_sigprocmask(SIG_SETMASK, &previous_mask, nullptr);
300 }
301 }
302
303 // Forward to the user's signal handler.
304 int handler_flags = chains[signo].action_.sa_flags;
305 ucontext_t* ucontext = static_cast<ucontext_t*>(ucontext_raw);
306 #if defined(__BIONIC__)
307 sigset64_t mask;
308 sigorset(&mask, &ucontext->uc_sigmask64, &chains[signo].action_.sa_mask);
309 #else
310 sigset_t mask;
311 sigorset(&mask, &ucontext->uc_sigmask, &chains[signo].action_.sa_mask);
312 #endif
313 if (!(handler_flags & SA_NODEFER)) {
314 sigaddset(&mask, signo);
315 }
316
317 #if defined(__BIONIC__)
318 linked_sigprocmask64(SIG_SETMASK, &mask, nullptr);
319 #else
320 linked_sigprocmask(SIG_SETMASK, &mask, nullptr);
321 #endif
322
323 if ((handler_flags & SA_SIGINFO)) {
324 chains[signo].action_.sa_sigaction(signo, siginfo, ucontext_raw);
325 } else {
326 auto handler = chains[signo].action_.sa_handler;
327 if (handler == SIG_IGN) {
328 return;
329 } else if (handler == SIG_DFL) {
330 fatal("exiting due to SIG_DFL handler for signal %d", signo);
331 } else {
332 handler(signo);
333 }
334 }
335 }
336
337 template <typename SigactionType>
__sigaction(int signal,const SigactionType * new_action,SigactionType * old_action,int (* linked)(int,const SigactionType *,SigactionType *))338 static int __sigaction(int signal, const SigactionType* new_action,
339 SigactionType* old_action,
340 int (*linked)(int, const SigactionType*,
341 SigactionType*)) {
342 // If this signal has been claimed as a signal chain, record the user's
343 // action but don't pass it on to the kernel.
344 // Note that we check that the signal number is in range here. An out of range signal
345 // number should behave exactly as the libc sigaction.
346 if (signal <= 0 || signal >= _NSIG) {
347 errno = EINVAL;
348 return -1;
349 }
350
351 if (chains[signal].IsClaimed()) {
352 SigactionType saved_action = chains[signal].GetAction<SigactionType>();
353 if (new_action != nullptr) {
354 chains[signal].SetAction(new_action);
355 }
356 if (old_action != nullptr) {
357 *old_action = saved_action;
358 }
359 return 0;
360 }
361
362 // Will only get here if the signal chain has not been claimed. We want
363 // to pass the sigaction on to the kernel via the real sigaction in libc.
364 return linked(signal, new_action, old_action);
365 }
366
sigaction(int signal,const struct sigaction * new_action,struct sigaction * old_action)367 extern "C" int sigaction(int signal, const struct sigaction* new_action,
368 struct sigaction* old_action) {
369 InitializeSignalChain();
370 return __sigaction(signal, new_action, old_action, linked_sigaction);
371 }
372
373 #if defined(__BIONIC__)
sigaction64(int signal,const struct sigaction64 * new_action,struct sigaction64 * old_action)374 extern "C" int sigaction64(int signal, const struct sigaction64* new_action,
375 struct sigaction64* old_action) {
376 InitializeSignalChain();
377 return __sigaction(signal, new_action, old_action, linked_sigaction64);
378 }
379 #endif
380
signal(int signo,sighandler_t handler)381 extern "C" sighandler_t signal(int signo, sighandler_t handler) {
382 InitializeSignalChain();
383
384 if (signo <= 0 || signo >= _NSIG) {
385 errno = EINVAL;
386 return SIG_ERR;
387 }
388
389 struct sigaction sa = {};
390 sigemptyset(&sa.sa_mask);
391 sa.sa_handler = handler;
392 sa.sa_flags = SA_RESTART | SA_ONSTACK;
393 sighandler_t oldhandler;
394
395 // If this signal has been claimed as a signal chain, record the user's
396 // action but don't pass it on to the kernel.
397 if (chains[signo].IsClaimed()) {
398 oldhandler = reinterpret_cast<sighandler_t>(
399 chains[signo].GetAction<struct sigaction>().sa_handler);
400 chains[signo].SetAction(&sa);
401 return oldhandler;
402 }
403
404 // Will only get here if the signal chain has not been claimed. We want
405 // to pass the sigaction on to the kernel via the real sigaction in libc.
406 if (linked_sigaction(signo, &sa, &sa) == -1) {
407 return SIG_ERR;
408 }
409
410 return reinterpret_cast<sighandler_t>(sa.sa_handler);
411 }
412
413 #if !defined(__LP64__)
bsd_signal(int signo,sighandler_t handler)414 extern "C" sighandler_t bsd_signal(int signo, sighandler_t handler) {
415 InitializeSignalChain();
416
417 return signal(signo, handler);
418 }
419 #endif
420
421 template <typename SigsetType>
__sigprocmask(int how,const SigsetType * new_set,SigsetType * old_set,int (* linked)(int,const SigsetType *,SigsetType *))422 int __sigprocmask(int how, const SigsetType* new_set, SigsetType* old_set,
423 int (*linked)(int, const SigsetType*, SigsetType*)) {
424 // When inside a signal handler, forward directly to the actual sigprocmask.
425 if (GetHandlingSignal()) {
426 return linked(how, new_set, old_set);
427 }
428
429 const SigsetType* new_set_ptr = new_set;
430 SigsetType tmpset;
431 if (new_set != nullptr) {
432 tmpset = *new_set;
433
434 if (how == SIG_BLOCK || how == SIG_SETMASK) {
435 // Don't allow claimed signals in the mask. If a signal chain has been claimed
436 // we can't allow the user to block that signal.
437 for (int i = 1; i < _NSIG; ++i) {
438 if (chains[i].IsClaimed() && sigismember(&tmpset, i)) {
439 sigdelset(&tmpset, i);
440 }
441 }
442 }
443 new_set_ptr = &tmpset;
444 }
445
446 return linked(how, new_set_ptr, old_set);
447 }
448
sigprocmask(int how,const sigset_t * new_set,sigset_t * old_set)449 extern "C" int sigprocmask(int how, const sigset_t* new_set,
450 sigset_t* old_set) {
451 InitializeSignalChain();
452 return __sigprocmask(how, new_set, old_set, linked_sigprocmask);
453 }
454
455 #if defined(__BIONIC__)
sigprocmask64(int how,const sigset64_t * new_set,sigset64_t * old_set)456 extern "C" int sigprocmask64(int how, const sigset64_t* new_set,
457 sigset64_t* old_set) {
458 InitializeSignalChain();
459 return __sigprocmask(how, new_set, old_set, linked_sigprocmask64);
460 }
461 #endif
462
AddSpecialSignalHandlerFn(int signal,SigchainAction * sa)463 extern "C" void AddSpecialSignalHandlerFn(int signal, SigchainAction* sa) {
464 InitializeSignalChain();
465
466 if (signal <= 0 || signal >= _NSIG) {
467 fatal("Invalid signal %d", signal);
468 }
469
470 // Set the managed_handler.
471 chains[signal].AddSpecialHandler(sa);
472 chains[signal].Claim(signal);
473 }
474
RemoveSpecialSignalHandlerFn(int signal,bool (* fn)(int,siginfo_t *,void *))475 extern "C" void RemoveSpecialSignalHandlerFn(int signal, bool (*fn)(int, siginfo_t*, void*)) {
476 InitializeSignalChain();
477
478 if (signal <= 0 || signal >= _NSIG) {
479 fatal("Invalid signal %d", signal);
480 }
481
482 chains[signal].RemoveSpecialHandler(fn);
483 }
484
EnsureFrontOfChain(int signal)485 extern "C" void EnsureFrontOfChain(int signal) {
486 InitializeSignalChain();
487
488 if (signal <= 0 || signal >= _NSIG) {
489 fatal("Invalid signal %d", signal);
490 }
491
492 // Read the current action without looking at the chain, it should be the expected action.
493 #if defined(__BIONIC__)
494 struct sigaction64 current_action;
495 linked_sigaction64(signal, nullptr, ¤t_action);
496 #else
497 struct sigaction current_action;
498 linked_sigaction(signal, nullptr, ¤t_action);
499 #endif
500
501 // If the sigactions don't match then we put the current action on the chain and make ourself as
502 // the main action.
503 if (current_action.sa_sigaction != SignalChain::Handler) {
504 log("Warning: Unexpected sigaction action found %p\n", current_action.sa_sigaction);
505 chains[signal].Register(signal);
506 }
507 }
508
509 } // namespace art
510
511