1 // RUN: %clangxx_cfi_dso -std=c++11 -g -DSHARED_LIB %s -fPIC -shared -o %t-cfi-so.so 2 // RUN: %clangxx -std=c++11 -g -DSHARED_LIB %s -fPIC -shared -o %t-nocfi-so.so 3 // RUN: %clangxx_cfi_dso -std=c++11 -g %s -o %t 4 5 // RUN: %expect_crash %t start 2>&1 | FileCheck %s 6 // RUN: %expect_crash %t mmap 2>&1 | FileCheck %s 7 // RUN: %expect_crash %t dlopen %t-cfi-so.so 2>&1 | FileCheck %s 8 // RUN: %expect_crash %t dlclose %t-cfi-so.so 2>&1 | FileCheck %s 9 // RUN: %expect_crash %t dlopen %t-nocfi-so.so 2>&1 | FileCheck %s 10 // RUN: %expect_crash %t dlclose %t-nocfi-so.so 2>&1 | FileCheck %s 11 12 // Tests that shadow is read-only most of the time. 13 // REQUIRES: cxxabi 14 15 #include <assert.h> 16 #include <dlfcn.h> 17 #include <stdio.h> 18 #include <stdint.h> 19 #include <stdlib.h> 20 #include <string.h> 21 #include <sys/mman.h> 22 23 struct A { 24 virtual void f(); 25 }; 26 27 #ifdef SHARED_LIB 28 29 void A::f() {} 30 31 extern "C" A *create_A() { return new A(); } 32 33 #else 34 35 constexpr unsigned kShadowGranularity = 12; 36 37 namespace __cfi { 38 uintptr_t GetShadow(); 39 } 40 41 void write_shadow(void *ptr) { 42 uintptr_t base = __cfi::GetShadow(); 43 uint16_t *s = 44 (uint16_t *)(base + (((uintptr_t)ptr >> kShadowGranularity) << 1)); 45 fprintf(stderr, "going to crash\n"); 46 // CHECK: going to crash 47 *s = 42; 48 fprintf(stderr, "did not crash\n"); 49 // CHECK-NOT: did not crash 50 exit(1); 51 } 52 53 int main(int argc, char *argv[]) { 54 assert(argc > 1); 55 const bool test_mmap = strcmp(argv[1], "mmap") == 0; 56 const bool test_start = strcmp(argv[1], "start") == 0; 57 const bool test_dlopen = strcmp(argv[1], "dlopen") == 0; 58 const bool test_dlclose = strcmp(argv[1], "dlclose") == 0; 59 const char *lib = argc > 2 ? argv[2] : nullptr; 60 61 if (test_start) 62 write_shadow((void *)&main); 63 64 if (test_mmap) { 65 void *p = mmap(nullptr, 1 << 20, PROT_READ | PROT_WRITE | PROT_EXEC, 66 MAP_PRIVATE | MAP_ANONYMOUS, 0, 0); 67 assert(p != MAP_FAILED); 68 write_shadow((char *)p + 100); 69 } else { 70 void *handle = dlopen(lib, RTLD_NOW); 71 assert(handle); 72 void *create_A = dlsym(handle, "create_A"); 73 assert(create_A); 74 75 if (test_dlopen) 76 write_shadow(create_A); 77 78 int res = dlclose(handle); 79 assert(res == 0); 80 81 if (test_dlclose) 82 write_shadow(create_A); 83 } 84 } 85 #endif 86