79 lines · c
1// RUN: %clang_hwasan %s -o %t2// RUN: %run %t 1 2>&13// RUN: %run %t 2 2>&14 5// REQUIRES: pointer-tagging6 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(argv[1]);16 const int kTag = 47;17 18 // Get any mmaped pointer.19 void *r =20 mmap(0, kSize, PROT_READ | PROT_WRITE, MAP_ANON | MAP_PRIVATE, -1, 0);21 if (r == MAP_FAILED) {22 perror("Failed to mmap: ");23 abort();24 }25 26 // Check that the pointer is untagged.27 if (r != __hwasan_tag_pointer(r, 0)) {28 fprintf(stderr, "Pointer returned by mmap should be untagged.\n");29 abort();30 }31 32 // Manually tag the pointer and the memory.33 __hwasan_tag_memory(r, kTag, kPS);34 int *p1 = __hwasan_tag_pointer(r, kTag);35 36 // Check that the pointer and the tag match.37 if (__hwasan_test_shadow(p1, kPS) != -1) {38 fprintf(stderr, "Failed to tag.\n");39 abort();40 }41 42 if (munmap((char *)r + 1, kSize) == 0) {43 perror("munmap should fail: ");44 abort();45 }46 47 if (__hwasan_test_shadow(p1, kPS) != -1) {48 fprintf(stderr, "Still must be tagged.\n");49 abort();50 }51 52 // First munmmap and then mmap the same pointer using MAP_FIXED.53 if (munmap((char *)r, kSize) != 0) {54 perror("Failed to unmap: ");55 abort();56 }57 58 if (__hwasan_test_shadow(r, kPS) != -1) {59 fprintf(stderr, "Shadow memory was not cleaned by munmap.\n");60 abort();61 }62 __hwasan_tag_memory(r, kTag, kPS);63 int *p2 = (int *)mmap(r, kSize, PROT_READ | PROT_WRITE,64 MAP_FIXED | MAP_ANON | MAP_PRIVATE, -1, 0);65 66 // Check that the pointer has no tag in it.67 if (p2 != r) {68 fprintf(stderr, "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(p2, kPS) != -1) {74 fprintf(stderr, "Shadow memory was not cleaned by mmap.\n");75 abort();76 }77 return 0;78}79