blob: f4799d2dcee1781e6358ba3efeb2a6c6f6de3685 [file] [log] [blame]
Dave Allisonf4b80bc2014-05-14 15:41:25 -07001/*
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
Bilyan Borisovbb661c02016-04-04 16:27:32 +010017#ifdef ART_TARGET_ANDROID
Dave Allisonf4b80bc2014-05-14 15:41:25 -070018#include <android/log.h>
Dave Allison69dfe512014-07-11 17:11:58 +000019#else
20#include <stdarg.h>
21#include <iostream>
22#endif
23
Dave Allisonf4b80bc2014-05-14 15:41:25 -070024#include <dlfcn.h>
Luis Hector Chavez33cac0f2017-04-06 14:18:09 -070025#include <errno.h>
Josh Gao99875e92017-04-17 15:58:36 -070026#include <pthread.h>
Dave Allisonf4b80bc2014-05-14 15:41:25 -070027#include <signal.h>
28#include <stdio.h>
29#include <stdlib.h>
Luis Hector Chavez33cac0f2017-04-06 14:18:09 -070030#include <string.h>
Josh Gao85a78cf2017-03-20 16:26:42 -070031
Luis Hector Chavez33cac0f2017-04-06 14:18:09 -070032#include <initializer_list>
Josh Gao99875e92017-04-17 15:58:36 -070033#include <mutex>
Josh Gao85a78cf2017-03-20 16:26:42 -070034#include <utility>
Dave Allisonf4b80bc2014-05-14 15:41:25 -070035
Dave Allisoncefcea82014-09-16 10:01:01 -070036#include "sigchain.h"
37
Dave Allison69dfe512014-07-11 17:11:58 +000038#if defined(__APPLE__)
39#define _NSIG NSIG
Dave Allison38680092014-08-29 12:29:34 -070040#define sighandler_t sig_t
Josh Gaodd241ae2017-03-20 14:17:23 -070041
42// Darwin has an #error when ucontext.h is included without _XOPEN_SOURCE defined.
43#define _XOPEN_SOURCE
Dave Allison69dfe512014-07-11 17:11:58 +000044#endif
45
Josh Gaodd241ae2017-03-20 14:17:23 -070046#include <ucontext.h>
47
Josh Gao85a78cf2017-03-20 16:26:42 -070048// 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?
Dave Allisonf4b80bc2014-05-14 15:41:25 -070065
Dave Allisonf4b80bc2014-05-14 15:41:25 -070066static 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);
Bilyan Borisovbb661c02016-04-04 16:27:32 +010071#ifdef ART_TARGET_ANDROID
Dave Allisonf4b80bc2014-05-14 15:41:25 -070072 __android_log_write(ANDROID_LOG_ERROR, "libsigchain", buf);
Dave Allison69dfe512014-07-11 17:11:58 +000073#else
74 std::cout << buf << "\n";
75#endif
Dave Allisonf4b80bc2014-05-14 15:41:25 -070076 va_end(ap);
77}
78
Josh Gao85a78cf2017-03-20 16:26:42 -070079#define fatal(...) log(__VA_ARGS__); abort()
Josh Gao7600fa92017-03-15 17:40:42 -070080
Josh Gao85a78cf2017-03-20 16:26:42 -070081static 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);
Dave Allisonf4b80bc2014-05-14 15:41:25 -070086 }
Josh Gao85a78cf2017-03-20 16:26:42 -070087 }
88 return 0;
89}
90
91namespace art {
92
93static decltype(&sigaction) linked_sigaction;
94static decltype(&sigprocmask) linked_sigprocmask;
Josh Gao99875e92017-04-17 15:58:36 -070095
96static pthread_key_t GetHandlingSignalKey() {
97 static pthread_key_t key;
98 static std::once_flag once;
99 std::call_once(once, []() {
100 int rc = pthread_key_create(&key, nullptr);
101 if (rc != 0) {
102 fatal("failed to create sigchain pthread key: %s", strerror(rc));
103 }
104 });
105 return key;
106}
107
108static bool GetHandlingSignal() {
109 void* result = pthread_getspecific(GetHandlingSignalKey());
110 return reinterpret_cast<uintptr_t>(result);
111}
112
113static void SetHandlingSignal(bool value) {
114 pthread_setspecific(GetHandlingSignalKey(),
115 reinterpret_cast<void*>(static_cast<uintptr_t>(value)));
116}
117
118class ScopedHandlingSignal {
119 public:
120 ScopedHandlingSignal() : original_value_(GetHandlingSignal()) {
121 }
122
123 ~ScopedHandlingSignal() {
124 SetHandlingSignal(original_value_);
125 }
126
127 private:
128 bool original_value_;
129};
Josh Gao85a78cf2017-03-20 16:26:42 -0700130
131class SignalChain {
132 public:
133 SignalChain() : claimed_(false) {
Jin Qian33dca562017-03-18 02:51:37 +0000134 }
135
Josh Gao85a78cf2017-03-20 16:26:42 -0700136 bool IsClaimed() {
137 return claimed_;
138 }
139
140 void Claim(int signo) {
141 if (!claimed_) {
142 Register(signo);
143 claimed_ = true;
Jin Qian33dca562017-03-18 02:51:37 +0000144 }
Josh Gao85a78cf2017-03-20 16:26:42 -0700145 }
146
147 // Register the signal chain with the kernel if needed.
148 void Register(int signo) {
149 struct sigaction handler_action = {};
150 handler_action.sa_sigaction = SignalChain::Handler;
151 handler_action.sa_flags = SA_RESTART | SA_SIGINFO | SA_ONSTACK;
152 sigfillset(&handler_action.sa_mask);
153 linked_sigaction(signo, &handler_action, &action_);
154 }
155
156 void SetAction(const struct sigaction* action) {
157 action_ = *action;
158 }
159
160 struct sigaction GetAction() {
161 return action_;
162 }
163
164 void AddSpecialHandler(SpecialSignalHandlerFn fn) {
165 for (SpecialSignalHandlerFn& slot : special_handlers_) {
166 if (slot == nullptr) {
167 slot = fn;
168 return;
169 }
170 }
171
172 fatal("too many special signal handlers");
173 }
174
175 void RemoveSpecialHandler(SpecialSignalHandlerFn fn) {
176 // This isn't thread safe, but it's unlikely to be a real problem.
177 size_t len = sizeof(special_handlers_)/sizeof(*special_handlers_);
178 for (size_t i = 0; i < len; ++i) {
179 if (special_handlers_[i] == fn) {
180 for (size_t j = i; j < len - 1; ++j) {
181 special_handlers_[j] = special_handlers_[j + 1];
182 }
183 special_handlers_[len - 1] = nullptr;
184 return;
185 }
186 }
187
188 fatal("failed to find special handler to remove");
189 }
190
191
192 static void Handler(int signo, siginfo_t* siginfo, void*);
193
194 private:
195 bool claimed_;
196 struct sigaction action_;
197 SpecialSignalHandlerFn special_handlers_[2];
198};
199
200static SignalChain chains[_NSIG];
201
Josh Gao85a78cf2017-03-20 16:26:42 -0700202class ScopedSignalUnblocker {
203 public:
204 explicit ScopedSignalUnblocker(const std::initializer_list<int>& signals) {
205 sigset_t new_mask;
206 sigemptyset(&new_mask);
207 for (int signal : signals) {
208 sigaddset(&new_mask, signal);
209 }
210 if (sigprocmask(SIG_UNBLOCK, &new_mask, &previous_mask_) != 0) {
211 fatal("failed to unblock signals: %s", strerror(errno));
212 }
213 }
214
215 ~ScopedSignalUnblocker() {
216 if (sigprocmask(SIG_SETMASK, &previous_mask_, nullptr) != 0) {
217 fatal("failed to unblock signals: %s", strerror(errno));
218 }
219 }
220
221 private:
222 sigset_t previous_mask_;
223};
224
Josh Gao85a78cf2017-03-20 16:26:42 -0700225void SignalChain::Handler(int signo, siginfo_t* siginfo, void* ucontext_raw) {
Josh Gao99875e92017-04-17 15:58:36 -0700226 ScopedHandlingSignal handling_signal;
Josh Gao90444552017-03-20 14:58:25 -0700227
Josh Gao85a78cf2017-03-20 16:26:42 -0700228 // Try the special handlers first.
229 // If one of them crashes, we'll reenter this handler and pass that crash onto the user handler.
Josh Gao99875e92017-04-17 15:58:36 -0700230 if (!GetHandlingSignal()) {
Josh Gao90444552017-03-20 14:58:25 -0700231 ScopedSignalUnblocker unblocked { SIGABRT, SIGBUS, SIGFPE, SIGILL, SIGSEGV }; // NOLINT
Josh Gao99875e92017-04-17 15:58:36 -0700232 SetHandlingSignal(true);
Josh Gao85a78cf2017-03-20 16:26:42 -0700233
234 for (const auto& handler : chains[signo].special_handlers_) {
235 if (handler != nullptr && handler(signo, siginfo, ucontext_raw)) {
236 return;
237 }
238 }
239 }
240
241 // Forward to the user's signal handler.
242 int handler_flags = chains[signo].action_.sa_flags;
243 ucontext_t* ucontext = static_cast<ucontext_t*>(ucontext_raw);
244 sigset_t mask;
245 sigorset(&mask, &ucontext->uc_sigmask, &chains[signo].action_.sa_mask);
246 if ((handler_flags & SA_NODEFER)) {
247 sigdelset(&mask, signo);
248 }
249 sigprocmask(SIG_SETMASK, &mask, nullptr);
250
251 if ((handler_flags & SA_SIGINFO)) {
252 chains[signo].action_.sa_sigaction(signo, siginfo, ucontext_raw);
Jin Qian33dca562017-03-18 02:51:37 +0000253 } else {
Josh Gao85a78cf2017-03-20 16:26:42 -0700254 auto handler = chains[signo].action_.sa_handler;
255 if (handler == SIG_IGN) {
256 return;
257 } else if (handler == SIG_DFL) {
Josh Gaofb539a42017-03-20 16:23:41 -0700258 fatal("exiting due to SIG_DFL handler for signal %d", signo);
Jin Qian33dca562017-03-18 02:51:37 +0000259 } else {
Josh Gao85a78cf2017-03-20 16:26:42 -0700260 handler(signo);
Jin Qian33dca562017-03-18 02:51:37 +0000261 }
262 }
263}
264
Dmitriy Ivanovf57874d2014-10-07 13:43:23 -0700265extern "C" int sigaction(int signal, const struct sigaction* new_action, struct sigaction* old_action) {
Dave Allisonf4b80bc2014-05-14 15:41:25 -0700266 // If this signal has been claimed as a signal chain, record the user's
267 // action but don't pass it on to the kernel.
268 // Note that we check that the signal number is in range here. An out of range signal
269 // number should behave exactly as the libc sigaction.
Josh Gao85a78cf2017-03-20 16:26:42 -0700270 if (signal < 0 || signal >= _NSIG) {
271 errno = EINVAL;
272 return -1;
273 }
274
Josh Gao9d631dd2017-03-23 20:04:58 -0700275 if (chains[signal].IsClaimed()) {
Josh Gao85a78cf2017-03-20 16:26:42 -0700276 struct sigaction saved_action = chains[signal].GetAction();
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700277 if (new_action != nullptr) {
Josh Gao85a78cf2017-03-20 16:26:42 -0700278 chains[signal].SetAction(new_action);
Dave Allisonf4b80bc2014-05-14 15:41:25 -0700279 }
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700280 if (old_action != nullptr) {
Dmitriy Ivanovc01683b2015-01-06 14:55:26 -0800281 *old_action = saved_action;
282 }
Dave Allisonf4b80bc2014-05-14 15:41:25 -0700283 return 0;
284 }
285
286 // Will only get here if the signal chain has not been claimed. We want
287 // to pass the sigaction on to the kernel via the real sigaction in libc.
Josh Gao85a78cf2017-03-20 16:26:42 -0700288 InitializeSignalChain();
Dave Allisonf4b80bc2014-05-14 15:41:25 -0700289 return linked_sigaction(signal, new_action, old_action);
290}
291
Josh Gao85a78cf2017-03-20 16:26:42 -0700292extern "C" sighandler_t signal(int signo, sighandler_t handler) {
293 if (signo < 0 || signo > _NSIG) {
294 errno = EINVAL;
295 return SIG_ERR;
296 }
297
298 struct sigaction sa = {};
Dave Allison91a83662014-08-28 16:12:40 -0700299 sigemptyset(&sa.sa_mask);
300 sa.sa_handler = handler;
Josh Gao85a78cf2017-03-20 16:26:42 -0700301 sa.sa_flags = SA_RESTART | SA_ONSTACK;
Dave Allison91a83662014-08-28 16:12:40 -0700302 sighandler_t oldhandler;
303
304 // If this signal has been claimed as a signal chain, record the user's
305 // action but don't pass it on to the kernel.
Josh Gao85a78cf2017-03-20 16:26:42 -0700306 if (chains[signo].IsClaimed()) {
307 oldhandler = reinterpret_cast<sighandler_t>(chains[signo].GetAction().sa_handler);
308 chains[signo].SetAction(&sa);
Dave Allison91a83662014-08-28 16:12:40 -0700309 return oldhandler;
310 }
311
312 // Will only get here if the signal chain has not been claimed. We want
313 // to pass the sigaction on to the kernel via the real sigaction in libc.
Josh Gao85a78cf2017-03-20 16:26:42 -0700314 InitializeSignalChain();
315 if (linked_sigaction(signo, &sa, &sa) == -1) {
Dave Allison91a83662014-08-28 16:12:40 -0700316 return SIG_ERR;
317 }
318
319 return reinterpret_cast<sighandler_t>(sa.sa_handler);
320}
321
Dimitry Ivanov82b67b92016-08-01 11:19:03 -0700322#if !defined(__LP64__)
Josh Gao85a78cf2017-03-20 16:26:42 -0700323extern "C" sighandler_t bsd_signal(int signo, sighandler_t handler) {
324 return signal(signo, handler);
Dimitry Ivanov82b67b92016-08-01 11:19:03 -0700325}
326#endif
327
Dmitriy Ivanovf57874d2014-10-07 13:43:23 -0700328extern "C" int sigprocmask(int how, const sigset_t* bionic_new_set, sigset_t* bionic_old_set) {
Josh Gao90444552017-03-20 14:58:25 -0700329 // When inside a signal handler, forward directly to the actual sigprocmask.
Josh Gao99875e92017-04-17 15:58:36 -0700330 if (GetHandlingSignal()) {
Josh Gao90444552017-03-20 14:58:25 -0700331 return linked_sigprocmask(how, bionic_new_set, bionic_old_set);
332 }
333
Dave Allisonf4b80bc2014-05-14 15:41:25 -0700334 const sigset_t* new_set_ptr = bionic_new_set;
335 sigset_t tmpset;
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700336 if (bionic_new_set != nullptr) {
Dave Allisonf4b80bc2014-05-14 15:41:25 -0700337 tmpset = *bionic_new_set;
338
339 if (how == SIG_BLOCK) {
340 // Don't allow claimed signals in the mask. If a signal chain has been claimed
341 // we can't allow the user to block that signal.
342 for (int i = 0 ; i < _NSIG; ++i) {
Josh Gao85a78cf2017-03-20 16:26:42 -0700343 if (chains[i].IsClaimed() && sigismember(&tmpset, i)) {
Dmitriy Ivanova3164b92015-04-01 11:08:45 -0700344 sigdelset(&tmpset, i);
Dave Allisonf4b80bc2014-05-14 15:41:25 -0700345 }
346 }
347 }
348 new_set_ptr = &tmpset;
349 }
350
Josh Gao85a78cf2017-03-20 16:26:42 -0700351 InitializeSignalChain();
Dave Allisonf4b80bc2014-05-14 15:41:25 -0700352 return linked_sigprocmask(how, new_set_ptr, bionic_old_set);
353}
Dave Allisoncefcea82014-09-16 10:01:01 -0700354
Dmitriy Ivanovf57874d2014-10-07 13:43:23 -0700355extern "C" void InitializeSignalChain() {
Dave Allisoncefcea82014-09-16 10:01:01 -0700356 // Warning.
357 // Don't call this from within a signal context as it makes calls to
358 // dlsym. Calling into the dynamic linker will result in locks being
359 // taken and if it so happens that a signal occurs while one of these
360 // locks is already taken, dlsym will block trying to reenter a
361 // mutex and we will never get out of it.
Josh Gao85a78cf2017-03-20 16:26:42 -0700362 static bool initialized = false;
Dave Allisoncefcea82014-09-16 10:01:01 -0700363 if (initialized) {
364 // Don't initialize twice.
365 return;
366 }
Josh Gao85a78cf2017-03-20 16:26:42 -0700367
368 void* linked_sigaction_sym = dlsym(RTLD_NEXT, "sigaction");
Dave Allisoncefcea82014-09-16 10:01:01 -0700369 if (linked_sigaction_sym == nullptr) {
370 linked_sigaction_sym = dlsym(RTLD_DEFAULT, "sigaction");
371 if (linked_sigaction_sym == nullptr ||
Dmitriy Ivanova3164b92015-04-01 11:08:45 -0700372 linked_sigaction_sym == reinterpret_cast<void*>(sigaction)) {
Josh Gao85a78cf2017-03-20 16:26:42 -0700373 fatal("Unable to find next sigaction in signal chain");
Dave Allisoncefcea82014-09-16 10:01:01 -0700374 }
375 }
376
Josh Gao85a78cf2017-03-20 16:26:42 -0700377 void* linked_sigprocmask_sym = dlsym(RTLD_NEXT, "sigprocmask");
Dave Allisoncefcea82014-09-16 10:01:01 -0700378 if (linked_sigprocmask_sym == nullptr) {
379 linked_sigprocmask_sym = dlsym(RTLD_DEFAULT, "sigprocmask");
380 if (linked_sigprocmask_sym == nullptr ||
381 linked_sigprocmask_sym == reinterpret_cast<void*>(sigprocmask)) {
Josh Gao85a78cf2017-03-20 16:26:42 -0700382 fatal("Unable to find next sigprocmask in signal chain");
Dave Allisoncefcea82014-09-16 10:01:01 -0700383 }
384 }
Josh Gao85a78cf2017-03-20 16:26:42 -0700385
386 linked_sigaction = reinterpret_cast<decltype(linked_sigaction)>(linked_sigaction_sym);
387 linked_sigprocmask = reinterpret_cast<decltype(linked_sigprocmask)>(linked_sigprocmask_sym);
Dave Allisoncefcea82014-09-16 10:01:01 -0700388 initialized = true;
389}
Mathieu Chartierd0004802014-10-15 16:59:47 -0700390
Josh Gao85a78cf2017-03-20 16:26:42 -0700391extern "C" void AddSpecialSignalHandlerFn(int signal, SpecialSignalHandlerFn fn) {
392 if (signal <= 0 || signal >= _NSIG) {
393 fatal("Invalid signal %d", signal);
394 }
Andreas Gampe03c2cc82015-05-22 18:31:50 -0700395
396 // Set the managed_handler.
Josh Gao85a78cf2017-03-20 16:26:42 -0700397 chains[signal].AddSpecialHandler(fn);
398 chains[signal].Claim(signal);
399}
Andreas Gampe03c2cc82015-05-22 18:31:50 -0700400
Josh Gao85a78cf2017-03-20 16:26:42 -0700401extern "C" void RemoveSpecialSignalHandlerFn(int signal, SpecialSignalHandlerFn fn) {
402 if (signal <= 0 || signal >= _NSIG) {
403 fatal("Invalid signal %d", signal);
404 }
405
406 chains[signal].RemoveSpecialHandler(fn);
407}
408
409extern "C" void EnsureFrontOfChain(int signal) {
410 if (signal <= 0 || signal >= _NSIG) {
411 fatal("Invalid signal %d", signal);
412 }
413
414 // Read the current action without looking at the chain, it should be the expected action.
415 struct sigaction current_action;
416 InitializeSignalChain();
417 linked_sigaction(signal, nullptr, &current_action);
418 // If the sigactions don't match then we put the current action on the chain and make ourself as
419 // the main action.
420 if (current_action.sa_sigaction != SignalChain::Handler) {
421 log("Warning: Unexpected sigaction action found %p\n", current_action.sa_sigaction);
422 chains[signal].Register(signal);
Andreas Gampe03c2cc82015-05-22 18:31:50 -0700423 }
424}
425
Dave Allisonf4b80bc2014-05-14 15:41:25 -0700426} // namespace art
427