xref: /freebsd/sys/contrib/libsodium/test/default/sodium_utils3.c (revision 19fae0f66023a97a9b464b3beeeabb2081f575b3)
1 
2 #include <stdlib.h>
3 #include <sys/types.h>
4 
5 #include <limits.h>
6 #include <signal.h>
7 
8 #define TEST_NAME "sodium_utils3"
9 #include "cmptest.h"
10 
11 #ifdef __SANITIZE_ADDRESS__
12 # warning The sodium_utils3 test is expected to fail with address sanitizer
13 #endif
14 
15 __attribute__((noreturn)) static void
16 segv_handler(int sig)
17 {
18     (void) sig;
19 
20     printf("Intentional segfault / bus error caught\n");
21     printf("OK\n");
22 #ifdef SIGSEGV
23     signal(SIGSEGV, SIG_DFL);
24 #endif
25 #ifdef SIGBUS
26     signal(SIGBUS, SIG_DFL);
27 #endif
28 #ifdef SIGABRT
29     signal(SIGABRT, SIG_DFL);
30 #endif
31     exit(0);
32 }
33 
34 int
35 main(void)
36 {
37     void * buf;
38     size_t size;
39 
40 #ifdef SIGSEGV
41     signal(SIGSEGV, segv_handler);
42 #endif
43 #ifdef SIGBUS
44     signal(SIGBUS, segv_handler);
45 #endif
46 #ifdef SIGABRT
47     signal(SIGABRT, segv_handler);
48 #endif
49     size = 1U + randombytes_uniform(100000U);
50     buf  = sodium_malloc(size);
51     assert(buf != NULL);
52 
53 /* old versions of asan emit a warning because they don't support mlock*() */
54 #ifndef __SANITIZE_ADDRESS__
55     sodium_mprotect_noaccess(buf);
56     sodium_mprotect_readwrite(buf);
57 #endif
58 
59 #if defined(HAVE_CATCHABLE_SEGV) && !defined(__EMSCRIPTEN__) && !defined(__SANITIZE_ADDRESS__)
60     sodium_memzero(((unsigned char *) buf) - 8, 8U);
61     sodium_mprotect_readonly(buf);
62     sodium_free(buf);
63     printf("Underflow not caught\n");
64 #else
65     segv_handler(0);
66 #endif
67     return 0;
68 }
69