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