brintos

brintos / llvm-project-archived public Read only

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