1 /* SPDX-License-Identifier: LGPL-2.1-or-later */
2 
3 #include <fcntl.h>
4 #include <sys/mman.h>
5 #include <unistd.h>
6 
7 #if HAVE_VALGRIND_VALGRIND_H
8 #  include <valgrind/valgrind.h>
9 #endif
10 
11 #include "fd-util.h"
12 #include "fs-util.h"
13 #include "memory-util.h"
14 #include "sigbus.h"
15 #include "tests.h"
16 
main(int argc,char * argv[])17 int main(int argc, char *argv[]) {
18         _cleanup_close_ int fd = -1;
19         char template[] = "/tmp/sigbus-test-XXXXXX";
20         void *addr = NULL;
21         uint8_t *p;
22 
23         test_setup_logging(LOG_INFO);
24 
25 #if HAS_FEATURE_ADDRESS_SANITIZER
26         return log_tests_skipped("address-sanitizer is enabled");
27 #endif
28 #if HAVE_VALGRIND_VALGRIND_H
29         if (RUNNING_ON_VALGRIND)
30                 return log_tests_skipped("This test cannot run on valgrind");
31 #endif
32 
33         sigbus_install();
34 
35         assert_se(sigbus_pop(&addr) == 0);
36 
37         assert_se((fd = mkostemp(template, O_RDWR|O_CREAT|O_EXCL)) >= 0);
38         assert_se(unlink(template) >= 0);
39         assert_se(posix_fallocate_loop(fd, 0, page_size() * 8) >= 0);
40 
41         p = mmap(NULL, page_size() * 16, PROT_READ|PROT_WRITE, MAP_SHARED, fd, 0);
42         assert_se(p != MAP_FAILED);
43 
44         assert_se(sigbus_pop(&addr) == 0);
45 
46         p[0] = 0xFF;
47         assert_se(sigbus_pop(&addr) == 0);
48 
49         p[page_size()] = 0xFF;
50         assert_se(sigbus_pop(&addr) == 0);
51 
52         p[page_size()*8] = 0xFF;
53         p[page_size()*8+1] = 0xFF;
54         p[page_size()*10] = 0xFF;
55         assert_se(sigbus_pop(&addr) > 0);
56         assert_se(addr == p + page_size() * 8);
57         assert_se(sigbus_pop(&addr) > 0);
58         assert_se(addr == p + page_size() * 10);
59         assert_se(sigbus_pop(&addr) == 0);
60 
61         sigbus_reset();
62 }
63