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_utils2"
9 #include "cmptest.h"
10 
11 #ifdef __SANITIZE_ADDRESS__
12 # warning The sodium_utils2 test is expected to fail with address sanitizer
13 #endif
14 
15 #undef sodium_malloc
16 #undef sodium_free
17 #undef sodium_allocarray
18 
19 __attribute__((noreturn)) static void
segv_handler(int sig)20 segv_handler(int sig)
21 {
22     (void) sig;
23 
24     printf("Intentional segfault / bus error caught\n");
25     printf("OK\n");
26 #ifdef SIG_DFL
27 # ifdef SIGSEGV
28     signal(SIGSEGV, SIG_DFL);
29 # endif
30 # ifdef SIGBUS
31     signal(SIGBUS, SIG_DFL);
32 # endif
33 # ifdef SIGABRT
34     signal(SIGABRT, SIG_DFL);
35 # endif
36 #endif
37     exit(0);
38 }
39 
40 int
main(void)41 main(void)
42 {
43     void *       buf;
44     size_t       size;
45     unsigned int i;
46 
47     if (sodium_malloc(SIZE_MAX - 1U) != NULL) {
48         return 1;
49     }
50     if (sodium_malloc(0U) == NULL) {
51         return 1;
52     }
53     if (sodium_allocarray(SIZE_MAX / 2U + 1U, SIZE_MAX / 2U) != NULL) {
54         return 1;
55     }
56     sodium_free(sodium_allocarray(0U, 0U));
57     sodium_free(sodium_allocarray(0U, 1U));
58     sodium_free(sodium_allocarray(1U, 0U));
59 
60     buf = sodium_allocarray(1000U, 50U);
61     memset(buf, 0, 50000U);
62     sodium_free(buf);
63 
64     sodium_free(sodium_malloc(0U));
65     sodium_free(NULL);
66     for (i = 0U; i < 10000U; i++) {
67         size = 1U + randombytes_uniform(100000U);
68         buf  = sodium_malloc(size);
69         assert(buf != NULL);
70         memset(buf, i, size);
71         sodium_mprotect_noaccess(buf);
72         sodium_free(buf);
73     }
74     printf("OK\n");
75 #ifdef SIG_DFL
76 # ifdef SIGSEGV
77     signal(SIGSEGV, segv_handler);
78 # endif
79 # ifdef SIGBUS
80     signal(SIGBUS, segv_handler);
81 # endif
82 # ifdef SIGABRT
83     signal(SIGABRT, segv_handler);
84 # endif
85 #endif
86     size = 1U + randombytes_uniform(100000U);
87     buf  = sodium_malloc(size);
88     assert(buf != NULL);
89 
90 /* old versions of asan emit a warning because they don't support mlock*() */
91 #ifndef __SANITIZE_ADDRESS__
92     sodium_mprotect_readonly(buf);
93     sodium_mprotect_readwrite(buf);
94 #endif
95 
96 #if defined(HAVE_CATCHABLE_SEGV) && !defined(__EMSCRIPTEN__) && !defined(__SANITIZE_ADDRESS__)
97     sodium_memzero(((unsigned char *) buf) + size, 1U);
98     sodium_mprotect_noaccess(buf);
99     sodium_free(buf);
100     printf("Overflow not caught\n");
101 #else
102     segv_handler(0);
103 #endif
104     return 0;
105 }
106