1// Test the behavior of malloc/calloc/realloc when the allocation size is huge.
2// By default (allocator_may_return_null=0) the process should crash.
3// With allocator_may_return_null=1 the allocator should return 0.
4//
5// RUN: %clangxx_tsan -O0 %s -o %t
6// RUN: not %run %t malloc 2>&1 | FileCheck %s --check-prefix=CHECK-mCRASH
7// RUN: TSAN_OPTIONS=allocator_may_return_null=0 not %run %t malloc 2>&1 | FileCheck %s --check-prefix=CHECK-mCRASH
8// RUN: TSAN_OPTIONS=allocator_may_return_null=0 not %run %t calloc 2>&1 | FileCheck %s --check-prefix=CHECK-cCRASH
9// RUN: TSAN_OPTIONS=allocator_may_return_null=0 not %run %t calloc-overflow 2>&1 | FileCheck %s --check-prefix=CHECK-coCRASH
10// RUN: TSAN_OPTIONS=allocator_may_return_null=0 not %run %t realloc 2>&1 | FileCheck %s --check-prefix=CHECK-rCRASH
11// RUN: TSAN_OPTIONS=allocator_may_return_null=0 not %run %t realloc-after-malloc 2>&1 | FileCheck %s --check-prefix=CHECK-mrCRASH
12
13#include <limits.h>
14#include <stdlib.h>
15#include <string.h>
16#include <stdio.h>
17#include <assert.h>
18#include <limits>
19int main(int argc, char **argv) {
20  volatile size_t size = std::numeric_limits<size_t>::max() - 10000;
21  assert(argc == 2);
22  char *x = 0;
23  if (!strcmp(argv[1], "malloc")) {
24    fprintf(stderr, "malloc:\n");
25    x = (char*)malloc(size);
26  }
27  if (!strcmp(argv[1], "calloc")) {
28    fprintf(stderr, "calloc:\n");
29    x = (char*)calloc(size / 4, 4);
30  }
31
32  if (!strcmp(argv[1], "calloc-overflow")) {
33    fprintf(stderr, "calloc-overflow:\n");
34    volatile size_t kMaxSizeT = std::numeric_limits<size_t>::max();
35    size_t kArraySize = 4096;
36    volatile size_t kArraySize2 = kMaxSizeT / kArraySize + 10;
37    x = (char*)calloc(kArraySize, kArraySize2);
38  }
39
40  if (!strcmp(argv[1], "realloc")) {
41    fprintf(stderr, "realloc:\n");
42    x = (char*)realloc(0, size);
43  }
44  if (!strcmp(argv[1], "realloc-after-malloc")) {
45    fprintf(stderr, "realloc-after-malloc:\n");
46    char *t = (char*)malloc(100);
47    *t = 42;
48    x = (char*)realloc(t, size);
49    assert(*t == 42);
50  }
51  fprintf(stderr, "x: %p\n", x);
52  return x != 0;
53}
54// CHECK-mCRASH: malloc:
55// CHECK-mCRASH: ThreadSanitizer's allocator is terminating the process
56// CHECK-cCRASH: calloc:
57// CHECK-cCRASH: ThreadSanitizer's allocator is terminating the process
58// CHECK-coCRASH: calloc-overflow:
59// CHECK-coCRASH: ThreadSanitizer's allocator is terminating the process
60// CHECK-rCRASH: realloc:
61// CHECK-rCRASH: ThreadSanitizer's allocator is terminating the process
62// CHECK-mrCRASH: realloc-after-malloc:
63// CHECK-mrCRASH: ThreadSanitizer's allocator is terminating the process
64
65