blob: 1727f88515d3dae71fa0b1d1578b94831e02ffa6 [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>
25#include <signal.h>
26#include <stdio.h>
27#include <stdlib.h>
Josh Gao85a78cf2017-03-20 16:26:42 -070028
29#include <utility>
Dave Allisonf4b80bc2014-05-14 15:41:25 -070030
Dave Allisoncefcea82014-09-16 10:01:01 -070031#include "sigchain.h"
32
Dave Allison69dfe512014-07-11 17:11:58 +000033#if defined(__APPLE__)
34#define _NSIG NSIG
Dave Allison38680092014-08-29 12:29:34 -070035#define sighandler_t sig_t
Josh Gaodd241ae2017-03-20 14:17:23 -070036
37// Darwin has an #error when ucontext.h is included without _XOPEN_SOURCE defined.
38#define _XOPEN_SOURCE
Dave Allison69dfe512014-07-11 17:11:58 +000039#endif
40
Josh Gaodd241ae2017-03-20 14:17:23 -070041#include <ucontext.h>
42
Josh Gao85a78cf2017-03-20 16:26:42 -070043// libsigchain provides an interception layer for signal handlers, to allow ART and others to give
44// their signal handlers the first stab at handling signals before passing them on to user code.
45//
46// It implements wrapper functions for signal, sigaction, and sigprocmask, and a handler that
47// forwards signals appropriately.
48//
49// In our handler, we start off with all signals blocked, fetch the original signal mask from the
50// passed in ucontext, and then adjust our signal mask appropriately for the user handler.
51//
52// It's somewhat tricky for us to properly handle some flag cases:
53// SA_NOCLDSTOP and SA_NOCLDWAIT: shouldn't matter, we don't have special handlers for SIGCHLD.
54// SA_NODEFER: unimplemented, we can manually change the signal mask appropriately.
55// ~SA_ONSTACK: always silently enable this
56// SA_RESETHAND: unimplemented, but we can probably do this?
57// ~SA_RESTART: unimplemented, maybe we can reserve an RT signal, register an empty handler that
58// doesn't have SA_RESTART, and raise the signal to avoid restarting syscalls that are
59// expected to be interrupted?
Dave Allisonf4b80bc2014-05-14 15:41:25 -070060
Dave Allisonf4b80bc2014-05-14 15:41:25 -070061
62static void log(const char* format, ...) {
63 char buf[256];
64 va_list ap;
65 va_start(ap, format);
66 vsnprintf(buf, sizeof(buf), format, ap);
Bilyan Borisovbb661c02016-04-04 16:27:32 +010067#ifdef ART_TARGET_ANDROID
Dave Allisonf4b80bc2014-05-14 15:41:25 -070068 __android_log_write(ANDROID_LOG_ERROR, "libsigchain", buf);
Dave Allison69dfe512014-07-11 17:11:58 +000069#else
70 std::cout << buf << "\n";
71#endif
Dave Allisonf4b80bc2014-05-14 15:41:25 -070072 va_end(ap);
73}
74
Josh Gao85a78cf2017-03-20 16:26:42 -070075#define fatal(...) log(__VA_ARGS__); abort()
Josh Gao7600fa92017-03-15 17:40:42 -070076
Josh Gao85a78cf2017-03-20 16:26:42 -070077static int sigorset(sigset_t* dest, sigset_t* left, sigset_t* right) {
78 sigemptyset(dest);
79 for (size_t i = 0; i < sizeof(sigset_t) * CHAR_BIT; ++i) {
80 if (sigismember(left, i) == 1 || sigismember(right, i) == 1) {
81 sigaddset(dest, i);
Dave Allisonf4b80bc2014-05-14 15:41:25 -070082 }
Josh Gao85a78cf2017-03-20 16:26:42 -070083 }
84 return 0;
85}
86
87namespace art {
88
89static decltype(&sigaction) linked_sigaction;
90static decltype(&sigprocmask) linked_sigprocmask;
91__thread bool handling_signal;
92
93class SignalChain {
94 public:
95 SignalChain() : claimed_(false) {
Jin Qian33dca562017-03-18 02:51:37 +000096 }
97
Josh Gao85a78cf2017-03-20 16:26:42 -070098 bool IsClaimed() {
99 return claimed_;
100 }
101
102 void Claim(int signo) {
103 if (!claimed_) {
104 Register(signo);
105 claimed_ = true;
Jin Qian33dca562017-03-18 02:51:37 +0000106 }
Josh Gao85a78cf2017-03-20 16:26:42 -0700107 }
108
109 // Register the signal chain with the kernel if needed.
110 void Register(int signo) {
111 struct sigaction handler_action = {};
112 handler_action.sa_sigaction = SignalChain::Handler;
113 handler_action.sa_flags = SA_RESTART | SA_SIGINFO | SA_ONSTACK;
114 sigfillset(&handler_action.sa_mask);
115 linked_sigaction(signo, &handler_action, &action_);
116 }
117
118 void SetAction(const struct sigaction* action) {
119 action_ = *action;
120 }
121
122 struct sigaction GetAction() {
123 return action_;
124 }
125
126 void AddSpecialHandler(SpecialSignalHandlerFn fn) {
127 for (SpecialSignalHandlerFn& slot : special_handlers_) {
128 if (slot == nullptr) {
129 slot = fn;
130 return;
131 }
132 }
133
134 fatal("too many special signal handlers");
135 }
136
137 void RemoveSpecialHandler(SpecialSignalHandlerFn fn) {
138 // This isn't thread safe, but it's unlikely to be a real problem.
139 size_t len = sizeof(special_handlers_)/sizeof(*special_handlers_);
140 for (size_t i = 0; i < len; ++i) {
141 if (special_handlers_[i] == fn) {
142 for (size_t j = i; j < len - 1; ++j) {
143 special_handlers_[j] = special_handlers_[j + 1];
144 }
145 special_handlers_[len - 1] = nullptr;
146 return;
147 }
148 }
149
150 fatal("failed to find special handler to remove");
151 }
152
153
154 static void Handler(int signo, siginfo_t* siginfo, void*);
155
156 private:
157 bool claimed_;
158 struct sigaction action_;
159 SpecialSignalHandlerFn special_handlers_[2];
160};
161
162static SignalChain chains[_NSIG];
163
Josh Gao90444552017-03-20 14:58:25 -0700164class ScopedFlagRestorer {
Josh Gao85a78cf2017-03-20 16:26:42 -0700165 public:
Josh Gao90444552017-03-20 14:58:25 -0700166 explicit ScopedFlagRestorer(bool* flag) : flag_(flag), original_value_(*flag) {
Josh Gao85a78cf2017-03-20 16:26:42 -0700167 }
168
Josh Gao90444552017-03-20 14:58:25 -0700169 ~ScopedFlagRestorer() {
170 *flag_ = original_value_;
Josh Gao85a78cf2017-03-20 16:26:42 -0700171 }
172
173 private:
174 bool* flag_;
Josh Gao90444552017-03-20 14:58:25 -0700175 bool original_value_;
Josh Gao85a78cf2017-03-20 16:26:42 -0700176};
177
178class ScopedSignalUnblocker {
179 public:
180 explicit ScopedSignalUnblocker(const std::initializer_list<int>& signals) {
181 sigset_t new_mask;
182 sigemptyset(&new_mask);
183 for (int signal : signals) {
184 sigaddset(&new_mask, signal);
185 }
186 if (sigprocmask(SIG_UNBLOCK, &new_mask, &previous_mask_) != 0) {
187 fatal("failed to unblock signals: %s", strerror(errno));
188 }
189 }
190
191 ~ScopedSignalUnblocker() {
192 if (sigprocmask(SIG_SETMASK, &previous_mask_, nullptr) != 0) {
193 fatal("failed to unblock signals: %s", strerror(errno));
194 }
195 }
196
197 private:
198 sigset_t previous_mask_;
199};
200
Josh Gao85a78cf2017-03-20 16:26:42 -0700201void SignalChain::Handler(int signo, siginfo_t* siginfo, void* ucontext_raw) {
Josh Gao90444552017-03-20 14:58:25 -0700202 ScopedFlagRestorer flag(&handling_signal);
203
Josh Gao85a78cf2017-03-20 16:26:42 -0700204 // Try the special handlers first.
205 // If one of them crashes, we'll reenter this handler and pass that crash onto the user handler.
206 if (!handling_signal) {
Josh Gao90444552017-03-20 14:58:25 -0700207 ScopedSignalUnblocker unblocked { SIGABRT, SIGBUS, SIGFPE, SIGILL, SIGSEGV }; // NOLINT
208 handling_signal = true;
Josh Gao85a78cf2017-03-20 16:26:42 -0700209
210 for (const auto& handler : chains[signo].special_handlers_) {
211 if (handler != nullptr && handler(signo, siginfo, ucontext_raw)) {
212 return;
213 }
214 }
215 }
216
217 // Forward to the user's signal handler.
218 int handler_flags = chains[signo].action_.sa_flags;
219 ucontext_t* ucontext = static_cast<ucontext_t*>(ucontext_raw);
220 sigset_t mask;
221 sigorset(&mask, &ucontext->uc_sigmask, &chains[signo].action_.sa_mask);
222 if ((handler_flags & SA_NODEFER)) {
223 sigdelset(&mask, signo);
224 }
225 sigprocmask(SIG_SETMASK, &mask, nullptr);
226
227 if ((handler_flags & SA_SIGINFO)) {
228 chains[signo].action_.sa_sigaction(signo, siginfo, ucontext_raw);
Jin Qian33dca562017-03-18 02:51:37 +0000229 } else {
Josh Gao85a78cf2017-03-20 16:26:42 -0700230 auto handler = chains[signo].action_.sa_handler;
231 if (handler == SIG_IGN) {
232 return;
233 } else if (handler == SIG_DFL) {
Josh Gaofb539a42017-03-20 16:23:41 -0700234 fatal("exiting due to SIG_DFL handler for signal %d", signo);
Jin Qian33dca562017-03-18 02:51:37 +0000235 } else {
Josh Gao85a78cf2017-03-20 16:26:42 -0700236 handler(signo);
Jin Qian33dca562017-03-18 02:51:37 +0000237 }
238 }
239}
240
Dmitriy Ivanovf57874d2014-10-07 13:43:23 -0700241extern "C" int sigaction(int signal, const struct sigaction* new_action, struct sigaction* old_action) {
Dave Allisonf4b80bc2014-05-14 15:41:25 -0700242 // If this signal has been claimed as a signal chain, record the user's
243 // action but don't pass it on to the kernel.
244 // Note that we check that the signal number is in range here. An out of range signal
245 // number should behave exactly as the libc sigaction.
Josh Gao85a78cf2017-03-20 16:26:42 -0700246 if (signal < 0 || signal >= _NSIG) {
247 errno = EINVAL;
248 return -1;
249 }
250
Josh Gao9d631dd2017-03-23 20:04:58 -0700251 if (chains[signal].IsClaimed()) {
Josh Gao85a78cf2017-03-20 16:26:42 -0700252 struct sigaction saved_action = chains[signal].GetAction();
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700253 if (new_action != nullptr) {
Josh Gao85a78cf2017-03-20 16:26:42 -0700254 chains[signal].SetAction(new_action);
Dave Allisonf4b80bc2014-05-14 15:41:25 -0700255 }
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700256 if (old_action != nullptr) {
Dmitriy Ivanovc01683b2015-01-06 14:55:26 -0800257 *old_action = saved_action;
258 }
Dave Allisonf4b80bc2014-05-14 15:41:25 -0700259 return 0;
260 }
261
262 // Will only get here if the signal chain has not been claimed. We want
263 // to pass the sigaction on to the kernel via the real sigaction in libc.
Josh Gao85a78cf2017-03-20 16:26:42 -0700264 InitializeSignalChain();
Dave Allisonf4b80bc2014-05-14 15:41:25 -0700265 return linked_sigaction(signal, new_action, old_action);
266}
267
Josh Gao85a78cf2017-03-20 16:26:42 -0700268extern "C" sighandler_t signal(int signo, sighandler_t handler) {
269 if (signo < 0 || signo > _NSIG) {
270 errno = EINVAL;
271 return SIG_ERR;
272 }
273
274 struct sigaction sa = {};
Dave Allison91a83662014-08-28 16:12:40 -0700275 sigemptyset(&sa.sa_mask);
276 sa.sa_handler = handler;
Josh Gao85a78cf2017-03-20 16:26:42 -0700277 sa.sa_flags = SA_RESTART | SA_ONSTACK;
Dave Allison91a83662014-08-28 16:12:40 -0700278 sighandler_t oldhandler;
279
280 // If this signal has been claimed as a signal chain, record the user's
281 // action but don't pass it on to the kernel.
Josh Gao85a78cf2017-03-20 16:26:42 -0700282 if (chains[signo].IsClaimed()) {
283 oldhandler = reinterpret_cast<sighandler_t>(chains[signo].GetAction().sa_handler);
284 chains[signo].SetAction(&sa);
Dave Allison91a83662014-08-28 16:12:40 -0700285 return oldhandler;
286 }
287
288 // Will only get here if the signal chain has not been claimed. We want
289 // to pass the sigaction on to the kernel via the real sigaction in libc.
Josh Gao85a78cf2017-03-20 16:26:42 -0700290 InitializeSignalChain();
291 if (linked_sigaction(signo, &sa, &sa) == -1) {
Dave Allison91a83662014-08-28 16:12:40 -0700292 return SIG_ERR;
293 }
294
295 return reinterpret_cast<sighandler_t>(sa.sa_handler);
296}
297
Dimitry Ivanov82b67b92016-08-01 11:19:03 -0700298#if !defined(__LP64__)
Josh Gao85a78cf2017-03-20 16:26:42 -0700299extern "C" sighandler_t bsd_signal(int signo, sighandler_t handler) {
300 return signal(signo, handler);
Dimitry Ivanov82b67b92016-08-01 11:19:03 -0700301}
302#endif
303
Dmitriy Ivanovf57874d2014-10-07 13:43:23 -0700304extern "C" int sigprocmask(int how, const sigset_t* bionic_new_set, sigset_t* bionic_old_set) {
Josh Gao90444552017-03-20 14:58:25 -0700305 // When inside a signal handler, forward directly to the actual sigprocmask.
306 if (handling_signal) {
307 return linked_sigprocmask(how, bionic_new_set, bionic_old_set);
308 }
309
Dave Allisonf4b80bc2014-05-14 15:41:25 -0700310 const sigset_t* new_set_ptr = bionic_new_set;
311 sigset_t tmpset;
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700312 if (bionic_new_set != nullptr) {
Dave Allisonf4b80bc2014-05-14 15:41:25 -0700313 tmpset = *bionic_new_set;
314
315 if (how == SIG_BLOCK) {
316 // Don't allow claimed signals in the mask. If a signal chain has been claimed
317 // we can't allow the user to block that signal.
318 for (int i = 0 ; i < _NSIG; ++i) {
Josh Gao85a78cf2017-03-20 16:26:42 -0700319 if (chains[i].IsClaimed() && sigismember(&tmpset, i)) {
Dmitriy Ivanova3164b92015-04-01 11:08:45 -0700320 sigdelset(&tmpset, i);
Dave Allisonf4b80bc2014-05-14 15:41:25 -0700321 }
322 }
323 }
324 new_set_ptr = &tmpset;
325 }
326
Josh Gao85a78cf2017-03-20 16:26:42 -0700327 InitializeSignalChain();
Dave Allisonf4b80bc2014-05-14 15:41:25 -0700328 return linked_sigprocmask(how, new_set_ptr, bionic_old_set);
329}
Dave Allisoncefcea82014-09-16 10:01:01 -0700330
Dmitriy Ivanovf57874d2014-10-07 13:43:23 -0700331extern "C" void InitializeSignalChain() {
Dave Allisoncefcea82014-09-16 10:01:01 -0700332 // Warning.
333 // Don't call this from within a signal context as it makes calls to
334 // dlsym. Calling into the dynamic linker will result in locks being
335 // taken and if it so happens that a signal occurs while one of these
336 // locks is already taken, dlsym will block trying to reenter a
337 // mutex and we will never get out of it.
Josh Gao85a78cf2017-03-20 16:26:42 -0700338 static bool initialized = false;
Dave Allisoncefcea82014-09-16 10:01:01 -0700339 if (initialized) {
340 // Don't initialize twice.
341 return;
342 }
Josh Gao85a78cf2017-03-20 16:26:42 -0700343
344 void* linked_sigaction_sym = dlsym(RTLD_NEXT, "sigaction");
Dave Allisoncefcea82014-09-16 10:01:01 -0700345 if (linked_sigaction_sym == nullptr) {
346 linked_sigaction_sym = dlsym(RTLD_DEFAULT, "sigaction");
347 if (linked_sigaction_sym == nullptr ||
Dmitriy Ivanova3164b92015-04-01 11:08:45 -0700348 linked_sigaction_sym == reinterpret_cast<void*>(sigaction)) {
Josh Gao85a78cf2017-03-20 16:26:42 -0700349 fatal("Unable to find next sigaction in signal chain");
Dave Allisoncefcea82014-09-16 10:01:01 -0700350 }
351 }
352
Josh Gao85a78cf2017-03-20 16:26:42 -0700353 void* linked_sigprocmask_sym = dlsym(RTLD_NEXT, "sigprocmask");
Dave Allisoncefcea82014-09-16 10:01:01 -0700354 if (linked_sigprocmask_sym == nullptr) {
355 linked_sigprocmask_sym = dlsym(RTLD_DEFAULT, "sigprocmask");
356 if (linked_sigprocmask_sym == nullptr ||
357 linked_sigprocmask_sym == reinterpret_cast<void*>(sigprocmask)) {
Josh Gao85a78cf2017-03-20 16:26:42 -0700358 fatal("Unable to find next sigprocmask in signal chain");
Dave Allisoncefcea82014-09-16 10:01:01 -0700359 }
360 }
Josh Gao85a78cf2017-03-20 16:26:42 -0700361
362 linked_sigaction = reinterpret_cast<decltype(linked_sigaction)>(linked_sigaction_sym);
363 linked_sigprocmask = reinterpret_cast<decltype(linked_sigprocmask)>(linked_sigprocmask_sym);
Dave Allisoncefcea82014-09-16 10:01:01 -0700364 initialized = true;
365}
Mathieu Chartierd0004802014-10-15 16:59:47 -0700366
Josh Gao85a78cf2017-03-20 16:26:42 -0700367extern "C" void AddSpecialSignalHandlerFn(int signal, SpecialSignalHandlerFn fn) {
368 if (signal <= 0 || signal >= _NSIG) {
369 fatal("Invalid signal %d", signal);
370 }
Andreas Gampe03c2cc82015-05-22 18:31:50 -0700371
372 // Set the managed_handler.
Josh Gao85a78cf2017-03-20 16:26:42 -0700373 chains[signal].AddSpecialHandler(fn);
374 chains[signal].Claim(signal);
375}
Andreas Gampe03c2cc82015-05-22 18:31:50 -0700376
Josh Gao85a78cf2017-03-20 16:26:42 -0700377extern "C" void RemoveSpecialSignalHandlerFn(int signal, SpecialSignalHandlerFn fn) {
378 if (signal <= 0 || signal >= _NSIG) {
379 fatal("Invalid signal %d", signal);
380 }
381
382 chains[signal].RemoveSpecialHandler(fn);
383}
384
385extern "C" void EnsureFrontOfChain(int signal) {
386 if (signal <= 0 || signal >= _NSIG) {
387 fatal("Invalid signal %d", signal);
388 }
389
390 // Read the current action without looking at the chain, it should be the expected action.
391 struct sigaction current_action;
392 InitializeSignalChain();
393 linked_sigaction(signal, nullptr, &current_action);
394 // If the sigactions don't match then we put the current action on the chain and make ourself as
395 // the main action.
396 if (current_action.sa_sigaction != SignalChain::Handler) {
397 log("Warning: Unexpected sigaction action found %p\n", current_action.sa_sigaction);
398 chains[signal].Register(signal);
Andreas Gampe03c2cc82015-05-22 18:31:50 -0700399 }
400}
401
Dave Allisonf4b80bc2014-05-14 15:41:25 -0700402} // namespace art
403