xref: /llvm-project/compiler-rt/test/nsan/Posix/allocator_mapping.cpp (revision 652707a6457eeb3927a1fe82e6b2cbc2a1fa22f5)
1*652707a6SFangrui Song /// From msan/allocator_mapping.cpp
2*652707a6SFangrui Song /// Test that a module constructor can not map memory over the NSan heap
3*652707a6SFangrui Song /// (without MAP_FIXED, of course).
4*652707a6SFangrui Song // RUN: %clangxx_nsan -O0 %s -o %t_1
5*652707a6SFangrui Song // RUN: %clangxx_nsan -O0 -DHEAP_ADDRESS=$(%run %t_1) %s -o %t_2 && %run %t_2
6*652707a6SFangrui Song 
7*652707a6SFangrui Song #include <assert.h>
8*652707a6SFangrui Song #include <stdio.h>
9*652707a6SFangrui Song #include <stdlib.h>
10*652707a6SFangrui Song #include <sys/mman.h>
11*652707a6SFangrui Song 
12*652707a6SFangrui Song #ifdef HEAP_ADDRESS
13*652707a6SFangrui Song struct A {
14*652707a6SFangrui Song   A() {
15*652707a6SFangrui Song     void *const hint = reinterpret_cast<void *>(HEAP_ADDRESS);
16*652707a6SFangrui Song     void *p = mmap(hint, 4096, PROT_READ | PROT_WRITE,
17*652707a6SFangrui Song                    MAP_PRIVATE | MAP_ANONYMOUS, -1, 0);
18*652707a6SFangrui Song     // This address must be already mapped. Check that mmap() succeeds, but at a
19*652707a6SFangrui Song     // different address.
20*652707a6SFangrui Song     assert(p != reinterpret_cast<void *>(-1));
21*652707a6SFangrui Song     assert(p != hint);
22*652707a6SFangrui Song   }
23*652707a6SFangrui Song } a;
24*652707a6SFangrui Song #endif
25*652707a6SFangrui Song 
26*652707a6SFangrui Song int main() {
27*652707a6SFangrui Song   void *p = malloc(10);
28*652707a6SFangrui Song   printf("0x%zx\n", reinterpret_cast<size_t>(p) & (~0xfff));
29*652707a6SFangrui Song   free(p);
30*652707a6SFangrui Song }
31