1 /*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
4 This file is part of systemd.
6 Copyright 2014 Lennart Poettering
8 systemd is free software; you can redistribute it and/or modify it
9 under the terms of the GNU Lesser General Public License as published by
10 the Free Software Foundation; either version 2.1 of the License, or
11 (at your option) any later version.
13 systemd is distributed in the hope that it will be useful, but
14 WITHOUT ANY WARRANTY; without even the implied warranty of
15 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
16 Lesser General Public License for more details.
18 You should have received a copy of the GNU Lesser General Public License
19 along with systemd; If not, see <http://www.gnu.org/licenses/>.
29 #define SIGBUS_QUEUE_MAX 64
31 static struct sigaction old_sigaction;
32 static unsigned n_installed = 0;
34 /* We maintain a fixed size list of page addresses that triggered a
35 SIGBUS. We access with list with atomic operations, so that we
36 don't have to deal with locks between signal handler and main
37 programs in possibly multiple threads. */
39 static void* volatile sigbus_queue[SIGBUS_QUEUE_MAX];
40 static volatile sig_atomic_t n_sigbus_queue = 0;
42 static void sigbus_push(void *addr) {
47 /* Find a free place, increase the number of entries and leave, if we can */
48 for (u = 0; u < SIGBUS_QUEUE_MAX; u++)
49 if (__sync_bool_compare_and_swap(&sigbus_queue[u], NULL, addr)) {
50 __sync_fetch_and_add(&n_sigbus_queue, 1);
54 /* If we can't, make sure the queue size is out of bounds, to
55 * mark it as overflow */
62 if (c > SIGBUS_QUEUE_MAX) /* already overflow */
65 if (__sync_bool_compare_and_swap(&n_sigbus_queue, c, c + SIGBUS_QUEUE_MAX))
70 int sigbus_pop(void **ret) {
82 if (_unlikely_(c >= SIGBUS_QUEUE_MAX))
85 for (u = 0; u < SIGBUS_QUEUE_MAX; u++) {
88 addr = sigbus_queue[u];
92 if (__sync_bool_compare_and_swap(&sigbus_queue[u], addr, NULL)) {
93 __sync_fetch_and_sub(&n_sigbus_queue, 1);
101 static void sigbus_handler(int sn, siginfo_t *si, void *data) {
105 assert(sn == SIGBUS);
108 if (si->si_code != BUS_ADRERR || !si->si_addr) {
109 assert_se(sigaction(SIGBUS, &old_sigaction, NULL) == 0);
114 ul = (unsigned long) si->si_addr;
115 ul = ul / page_size();
116 ul = ul * page_size();
117 aligned = (void*) ul;
119 /* Let's remember which address failed */
120 sigbus_push(aligned);
122 /* Replace mapping with an anonymous page, so that the
123 * execution can continue, however with a zeroed out page */
124 assert_se(mmap(aligned, page_size(), PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_ANONYMOUS|MAP_FIXED, -1, 0) == aligned);
127 void sigbus_install(void) {
128 struct sigaction sa = {
129 .sa_sigaction = sigbus_handler,
130 .sa_flags = SA_SIGINFO,
135 if (n_installed == 1)
136 assert_se(sigaction(SIGBUS, &sa, &old_sigaction) == 0);
141 void sigbus_reset(void) {
143 if (n_installed <= 0)
148 if (n_installed == 0)
149 assert_se(sigaction(SIGBUS, &old_sigaction, NULL) == 0);