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