1// RUN: %clang_hwasan %s -o %t
2// RUN: %run %t 1 2>&1
3// RUN: %run %t 2 2>&1
4
5// REQUIRES: pointer-tagging
6
7#include <sanitizer/hwasan_interface.h>
8#include <stdio.h>
9#include <stdlib.h>
10#include <sys/mman.h>
11#include <unistd.h>
12
13int main(int argc, char **argv) {
14 const size_t kPS = sysconf(_SC_PAGESIZE);
15 const int kSize = kPS / atoi(nptr: argv[1]);
16 const int kTag = 47;
17
18 // Get any mmaped pointer.
19 void *r =
20 mmap(addr: 0, len: kSize, PROT_READ | PROT_WRITE, MAP_ANON | MAP_PRIVATE, fd: -1, offset: 0);
21 if (r == MAP_FAILED) {
22 perror(s: "Failed to mmap: ");
23 abort();
24 }
25
26 // Check that the pointer is untagged.
27 if (r != __hwasan_tag_pointer(p: r, tag: 0)) {
28 fprintf(stderr, format: "Pointer returned by mmap should be untagged.\n");
29 abort();
30 }
31
32 // Manually tag the pointer and the memory.
33 __hwasan_tag_memory(p: r, tag: kTag, size: kPS);
34 int *p1 = __hwasan_tag_pointer(p: r, tag: kTag);
35
36 // Check that the pointer and the tag match.
37 if (__hwasan_test_shadow(x: p1, size: kPS) != -1) {
38 fprintf(stderr, format: "Failed to tag.\n");
39 abort();
40 }
41
42 if (munmap(addr: (char *)r + 1, len: kSize) == 0) {
43 perror(s: "munmap should fail: ");
44 abort();
45 }
46
47 if (__hwasan_test_shadow(x: p1, size: kPS) != -1) {
48 fprintf(stderr, format: "Still must be tagged.\n");
49 abort();
50 }
51
52 // First munmmap and then mmap the same pointer using MAP_FIXED.
53 if (munmap(addr: (char *)r, len: kSize) != 0) {
54 perror(s: "Failed to unmap: ");
55 abort();
56 }
57
58 if (__hwasan_test_shadow(x: r, size: kPS) != -1) {
59 fprintf(stderr, format: "Shadow memory was not cleaned by munmap.\n");
60 abort();
61 }
62 __hwasan_tag_memory(p: r, tag: kTag, size: kPS);
63 int *p2 = (int *)mmap(addr: r, len: kSize, PROT_READ | PROT_WRITE,
64 MAP_FIXED | MAP_ANON | MAP_PRIVATE, fd: -1, offset: 0);
65
66 // Check that the pointer has no tag in it.
67 if (p2 != r) {
68 fprintf(stderr, format: "The mmap pointer has a non-zero tag in it.\n");
69 abort();
70 }
71
72 // Make sure we can access the shadow with an untagged pointer.
73 if (__hwasan_test_shadow(x: p2, size: kPS) != -1) {
74 fprintf(stderr, format: "Shadow memory was not cleaned by mmap.\n");
75 abort();
76 }
77 return 0;
78}
79

source code of compiler-rt/test/hwasan/TestCases/munmap.c