1// RUN: %clangxx %s -o %t
2// RUN: %env_tool_opts=detect_write_exec=1 %run %t 2>&1 | FileCheck %s
3// RUN: %env_tool_opts=detect_write_exec=0 %run %t 2>&1 | FileCheck %s \
4// RUN: --check-prefix=CHECK-DISABLED
5// ubsan and lsan do not install mmap interceptors UNSUPPORTED: ubsan, lsan
6
7// TODO: Fix option on Android, it hangs there for unknown reasons.
8// XFAIL: android
9
10#if defined(__APPLE__)
11#include <Availability.h>
12#endif
13#include <pthread.h>
14#include <stdio.h>
15#include <sys/mman.h>
16
17int main(int argc, char **argv) {
18 char *p = (char *)mmap(addr: 0, len: 1024, PROT_READ | PROT_WRITE | PROT_EXEC,
19 MAP_ANONYMOUS | MAP_PRIVATE, fd: -1, offset: 0);
20 // CHECK: WARNING: {{.*}}Sanitizer: writable-executable page usage
21 // CHECK: #{{[0-9]+.*}}main{{.*}}mmap_write_exec.cpp:[[@LINE-3]]
22 // CHECK: SUMMARY: {{.*}}Sanitizer: w-and-x-usage
23
24 char *q = (char *)mmap(addr: p, len: 64, PROT_READ | PROT_WRITE,
25 MAP_ANONYMOUS | MAP_PRIVATE | MAP_FIXED, fd: -1, offset: 0);
26 (void)mprotect(addr: q, len: 64, PROT_WRITE | PROT_EXEC);
27 // CHECK: WARNING: {{.*}}Sanitizer: writable-executable page usage
28 // CHECK: #{{[0-9]+.*}}main{{.*}}mmap_write_exec.cpp:[[@LINE-2]]
29 // CHECK: SUMMARY: {{.*}}Sanitizer: w-and-x-usage
30
31 char *a = (char *)mmap(addr: 0, len: 1024, PROT_READ | PROT_WRITE,
32 MAP_ANONYMOUS | MAP_PRIVATE, fd: -1, offset: 0);
33 char *b = (char *)mmap(addr: a, len: 64, PROT_READ | PROT_WRITE,
34 MAP_ANONYMOUS | MAP_PRIVATE | MAP_FIXED, fd: -1, offset: 0);
35 (void)mprotect(addr: q, len: 64, PROT_READ | PROT_EXEC);
36 // CHECK-NOT: Sanitizer
37#if defined(__APPLE__)
38# if (defined(__MAC_OS_X_VERSION_MIN_REQUIRED) && \
39 __MAC_OS_X_VERSION_MIN_REQUIRED >= 110000)
40 pthread_jit_write_protect_np(false);
41# endif
42 char *c = (char *)mmap(0, 128, PROT_WRITE | PROT_EXEC,
43 MAP_ANONYMOUS | MAP_PRIVATE | MAP_JIT, -1, 0);
44 // CHECK-NOT: Sanitizer
45#endif
46
47 printf(format: "done\n");
48 // CHECK-DISABLED-NOT: Sanitizer
49 // CHECK-DISABLED: done
50}
51

source code of compiler-rt/test/sanitizer_common/TestCases/Posix/mmap_write_exec.cpp