1// Test that mmap (without MAP_FIXED) always returns valid application addresses.
2// RUN: %clangxx_msan -O0 %s -o %t && %run %t
3// RUN: %clangxx_msan -O0 -fsanitize-memory-track-origins %s -o %t && %run %t
4
5#include <assert.h>
6#include <errno.h>
7#include <stdint.h>
8#include <sys/mman.h>
9#include <stdio.h>
10#include <stdlib.h>
11#include "test.h"
12
13bool AddrIsApp(void *p) {
14 uintptr_t addr = (uintptr_t)p;
15#if defined(__FreeBSD__) && defined(__x86_64__)
16 return addr < 0x010000000000ULL || addr >= 0x600000000000ULL;
17#elif defined(__x86_64__)
18 return (addr >= 0x000000000000ULL && addr < 0x010000000000ULL) ||
19 (addr >= 0x510000000000ULL && addr < 0x600000000000ULL) ||
20 (addr >= 0x700000000000ULL && addr < 0x800000000000ULL);
21#elif defined(__loongarch_lp64)
22 return (addr >= 0x000000000000ULL && addr < 0x010000000000ULL) ||
23 (addr >= 0x510000000000ULL && addr < 0x600000000000ULL) ||
24 (addr >= 0x700000000000ULL && addr < 0x800000000000ULL);
25#elif defined(__mips64)
26 return (addr >= 0x0000000000ULL && addr <= 0x0200000000ULL) ||
27 (addr >= 0xa200000000ULL && addr <= 0xc000000000ULL) ||
28 addr >= 0xe200000000ULL;
29#elif defined(__powerpc64__)
30 return addr < 0x000100000000ULL || addr >= 0x300000000000ULL;
31#elif defined(__s390x__)
32 return addr < 0x040000000000ULL ||
33 (addr >= 0x440000000000ULL && addr < 0x500000000000);
34#elif defined(__aarch64__)
35
36 struct AddrMapping {
37 uintptr_t start;
38 uintptr_t end;
39 } mappings[] = {
40 {0x0000000000000ULL, 0x0100000000000ULL},
41 {0x0A00000000000ULL, 0x0B00000000000ULL},
42 {0x0E00000000000ULL, 0x0F00000000000ULL},
43 {0x0F00000000000ULL, 0x1000000000000ULL},
44 };
45 const size_t mappingsSize = sizeof (mappings) / sizeof (mappings[0]);
46
47 for (int i=0; i<mappingsSize; ++i)
48 if (addr >= mappings[i].start && addr < mappings[i].end)
49 return true;
50 return false;
51#endif
52}
53
54int main() {
55 // Large enough to quickly exhaust the entire address space.
56#if defined(__mips64) || defined(__aarch64__)
57 const size_t kMapSize = 0x100000000ULL;
58#else
59 const size_t kMapSize = 0x1000000000ULL;
60#endif
61 int success_count = 0;
62 int flags = MAP_PRIVATE | MAP_ANONYMOUS;
63#if defined(MAP_NORESERVE)
64 flags |= MAP_NORESERVE;
65#endif
66 while (true) {
67 void *p = mmap(addr: 0, len: kMapSize, PROT_WRITE,
68 flags: flags, fd: -1, offset: 0);
69 printf(format: "%p\n", p);
70 if (p == MAP_FAILED) {
71 assert(errno == ENOMEM);
72 break;
73 }
74 assert(AddrIsApp(p));
75 success_count++;
76 }
77 printf(format: "successful mappings: %d\n", success_count);
78 assert(success_count > 5);
79}
80

source code of compiler-rt/test/msan/mmap.cpp