1 // RUN: %clang_scudo %s -o %t
2 // RUN: SCUDO_OPTIONS=allocator_may_return_null=0 not %run %t malloc 2>&1 | FileCheck %s
3 // RUN: SCUDO_OPTIONS=allocator_may_return_null=1     %run %t malloc 2>&1
4 // RUN: SCUDO_OPTIONS=allocator_may_return_null=0 not %run %t calloc 2>&1 | FileCheck %s
5 // RUN: SCUDO_OPTIONS=allocator_may_return_null=1     %run %t calloc 2>&1
6 // RUN:                                               %run %t usable 2>&1
7 
8 // Tests for various edge cases related to sizes, notably the maximum size the
9 // allocator can allocate. Tests that an integer overflow in the parameters of
10 // calloc is caught.
11 
12 #include <assert.h>
13 #include <malloc.h>
14 #include <stdlib.h>
15 #include <string.h>
16 
17 #include <limits>
18 
19 int main(int argc, char **argv)
20 {
21   assert(argc == 2);
22   if (!strcmp(argv[1], "malloc")) {
23     // Currently the maximum size the allocator can allocate is 1ULL<<40 bytes.
24     size_t size = std::numeric_limits<size_t>::max();
25     void *p = malloc(size);
26     assert(!p);
27     size = (1ULL << 40) - 16;
28     p = malloc(size);
29     assert(!p);
30   }
31   if (!strcmp(argv[1], "calloc")) {
32     // Trigger an overflow in calloc.
33     size_t size = std::numeric_limits<size_t>::max();
34     void *p = calloc((size / 0x1000) + 1, 0x1000);
35     assert(!p);
36   }
37   if (!strcmp(argv[1], "usable")) {
38     // Playing with the actual usable size of a chunk.
39     void *p = malloc(1007);
40     assert(p);
41     size_t size = malloc_usable_size(p);
42     assert(size >= 1007);
43     memset(p, 'A', size);
44     p = realloc(p, 2014);
45     assert(p);
46     size = malloc_usable_size(p);
47     assert(size >= 2014);
48     memset(p, 'B', size);
49     free(p);
50   }
51   return 0;
52 }
53 
54 // CHECK: allocator is terminating the process
55