xref: /llvm-project/compiler-rt/test/tsan/large_malloc_meta.cpp (revision bcaeed49cb063de9fe504aa29e1cadff8a7be710)
1*bcaeed49SFangrui Song // RUN: %clangxx_tsan -O1 %s -o %t && %run %t 2>&1 | FileCheck %s
2*bcaeed49SFangrui Song 
3*bcaeed49SFangrui Song // UNSUPPORTED: ios
4*bcaeed49SFangrui Song 
5*bcaeed49SFangrui Song #include "test.h"
6*bcaeed49SFangrui Song #include <sys/mman.h>
7*bcaeed49SFangrui Song 
8*bcaeed49SFangrui Song // Test for previously unbounded memory consumption for large mallocs.
9*bcaeed49SFangrui Song // Code allocates a large memory block (that is handled by LargeMmapAllocator),
10*bcaeed49SFangrui Song // and forces allocation of meta shadow for the block. Then freed the block.
11*bcaeed49SFangrui Song // But meta shadow was not unmapped. Then code occupies the virtual memory
12*bcaeed49SFangrui Song // range of the block with something else (that does not need meta shadow).
13*bcaeed49SFangrui Song // And repeats. As the result meta shadow growed infinitely.
14*bcaeed49SFangrui Song // This program used to consume >2GB. Now it consumes <50MB.
15*bcaeed49SFangrui Song 
main()16*bcaeed49SFangrui Song int main() {
17*bcaeed49SFangrui Song   for (int i = 0; i < 1000; i++) {
18*bcaeed49SFangrui Song     const int kSize = 1 << 20;
19*bcaeed49SFangrui Song     const int kPageSize = 4 << 10;
20*bcaeed49SFangrui Song     volatile int *p = new int[kSize];
21*bcaeed49SFangrui Song     for (int j = 0; j < kSize; j += kPageSize / sizeof(*p))
22*bcaeed49SFangrui Song       __atomic_store_n(&p[i], 1, __ATOMIC_RELEASE);
23*bcaeed49SFangrui Song     delete[] p;
24*bcaeed49SFangrui Song     mmap(0, kSize * sizeof(*p) + kPageSize, PROT_NONE, MAP_PRIVATE | MAP_ANON,
25*bcaeed49SFangrui Song         -1, 0);
26*bcaeed49SFangrui Song   }
27*bcaeed49SFangrui Song   fprintf(stderr, "DONE\n");
28*bcaeed49SFangrui Song   return 0;
29*bcaeed49SFangrui Song }
30*bcaeed49SFangrui Song 
31*bcaeed49SFangrui Song // CHECK: DONE
32