xref: /llvm-project/compiler-rt/test/tsan/Darwin/malloc_size.mm (revision 4399f3b6b0df2aa2c57e4a3049f5494b53f6921c)
1// Test that malloc_zone_from_ptr returns a valid zone for a 0-sized allocation.
2// Test that malloc_size does not crash for an invalid pointer.
3
4// RUN: %clang_tsan %s -o %t -framework Foundation
5// RUN: %run %t 2>&1 | FileCheck %s
6
7#include <malloc/malloc.h>
8#include <stdio.h>
9#include <stdlib.h>
10#include <sys/mman.h>
11
12int some_global;
13
14void describe_zone(void *p) {
15  malloc_zone_t *z = malloc_zone_from_ptr(p);
16  if (z) {
17    fprintf(stderr, "zone = %p\n", z);
18  }	else {
19  	fprintf(stderr, "zone = no zone\n");
20  }
21}
22
23int main() {
24  void *p;
25  size_t s;
26
27  p = malloc(0x40);
28  s = malloc_size(p);
29  fprintf(stderr, "size = 0x%zx\n", s);
30  // CHECK: size = 0x40
31  describe_zone(p);
32  // CHECK: zone = 0x{{[0-9a-f]+}}
33
34  p = malloc(0);
35  s = malloc_size(p);
36  fprintf(stderr, "size = 0x%zx\n", s);
37  // CHECK: size = 0x1
38  describe_zone(p);
39  // CHECK: zone = 0x{{[0-9a-f]+}}
40
41  p = &some_global;
42  s = malloc_size(p);
43  fprintf(stderr, "size = 0x%zx\n", s);
44  // CHECK: size = 0x0
45  describe_zone(p);
46  // CHECK: zone = no zone
47
48  p = mmap(0, 0x1000, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_ANON, -1, 0);
49  if (!p) {
50  	fprintf(stderr, "mmap failed\n");
51  	exit(1);
52  }
53  s = malloc_size(p);
54  fprintf(stderr, "size = 0x%zx\n", s);
55  // CHECK: size = 0x0
56  describe_zone(p);
57  // CHECK: zone = no zone
58
59  p = (void *)0x42;  // invalid pointer
60  s = malloc_size(p);
61  fprintf(stderr, "size = 0x%zx\n", s);
62  // CHECK: size = 0x0
63  describe_zone(p);
64  // CHECK: zone = no zone
65
66  return 0;
67}
68