1 /* SPDX-License-Identifier: LGPL-2.1+ */
3 Copyright 2014 Lennart Poettering
15 #define SIGBUS_QUEUE_MAX 64
17 static struct sigaction old_sigaction;
18 static unsigned n_installed = 0;
20 /* We maintain a fixed size list of page addresses that triggered a
21 SIGBUS. We access with list with atomic operations, so that we
22 don't have to deal with locks between signal handler and main
23 programs in possibly multiple threads. */
25 static void* volatile sigbus_queue[SIGBUS_QUEUE_MAX];
26 static volatile sig_atomic_t n_sigbus_queue = 0;
28 static void sigbus_push(void *addr) {
33 /* Find a free place, increase the number of entries and leave, if we can */
34 for (u = 0; u < SIGBUS_QUEUE_MAX; u++)
35 if (__sync_bool_compare_and_swap(&sigbus_queue[u], NULL, addr)) {
36 __sync_fetch_and_add(&n_sigbus_queue, 1);
40 /* If we can't, make sure the queue size is out of bounds, to
41 * mark it as overflow */
48 if (c > SIGBUS_QUEUE_MAX) /* already overflow */
51 if (__sync_bool_compare_and_swap(&n_sigbus_queue, c, c + SIGBUS_QUEUE_MAX))
56 int sigbus_pop(void **ret) {
68 if (_unlikely_(c >= SIGBUS_QUEUE_MAX))
71 for (u = 0; u < SIGBUS_QUEUE_MAX; u++) {
74 addr = sigbus_queue[u];
78 if (__sync_bool_compare_and_swap(&sigbus_queue[u], addr, NULL)) {
79 __sync_fetch_and_sub(&n_sigbus_queue, 1);
87 static void sigbus_handler(int sn, siginfo_t *si, void *data) {
94 if (si->si_code != BUS_ADRERR || !si->si_addr) {
95 assert_se(sigaction(SIGBUS, &old_sigaction, NULL) == 0);
100 ul = (unsigned long) si->si_addr;
101 ul = ul / page_size();
102 ul = ul * page_size();
103 aligned = (void*) ul;
105 /* Let's remember which address failed */
106 sigbus_push(aligned);
108 /* Replace mapping with an anonymous page, so that the
109 * execution can continue, however with a zeroed out page */
110 assert_se(mmap(aligned, page_size(), PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_ANONYMOUS|MAP_FIXED, -1, 0) == aligned);
113 void sigbus_install(void) {
114 struct sigaction sa = {
115 .sa_sigaction = sigbus_handler,
116 .sa_flags = SA_SIGINFO,
121 if (n_installed == 1)
122 assert_se(sigaction(SIGBUS, &sa, &old_sigaction) == 0);
127 void sigbus_reset(void) {
129 if (n_installed <= 0)
134 if (n_installed == 0)
135 assert_se(sigaction(SIGBUS, &old_sigaction, NULL) == 0);