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