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