72 lines · cpp
1// RUN: %clangxx -O2 %s -o %t && %run %t 2>&1 | FileCheck %s2 3// Malloc/free hooks are not supported on Windows.4// XFAIL: target={{.*windows-msvc.*}}5 6// Must not be implemented, no other reason to install interceptors.7// XFAIL: ubsan8 9#include <stdlib.h>10#include <unistd.h>11#include <sanitizer/allocator_interface.h>12 13extern "C" {14const volatile void *global_ptr;15 16#define WRITE(s) write(1, s, sizeof(s))17 18// Note: avoid calling functions that allocate memory in malloc/free19// to avoid infinite recursion.20void __sanitizer_malloc_hook(const volatile void *ptr, size_t sz) {21 if (__sanitizer_get_ownership(ptr) && sz == sizeof(int)) {22 WRITE("MallocHook\n");23 global_ptr = ptr;24 }25}26void __sanitizer_free_hook(const volatile void *ptr) {27 if (__sanitizer_get_ownership(ptr) && ptr == global_ptr)28 WRITE("FreeHook\n");29}30} // extern "C"31 32volatile int *x;33 34void MallocHook1(const volatile void *ptr, size_t sz) { WRITE("MH1\n"); }35void MallocHook2(const volatile void *ptr, size_t sz) { WRITE("MH2\n"); }36void FreeHook1(const volatile void *ptr) { WRITE("FH1\n"); }37void FreeHook2(const volatile void *ptr) { WRITE("FH2\n"); }38// Call this function with uninitialized arguments to poison39// TLS shadow for function parameters before calling operator40// new and, eventually, user-provided hook.41__attribute__((noinline)) void allocate(int *unused1, int *unused2) {42 x = reinterpret_cast<int *>(malloc(sizeof(int)));43}44 45int main() {46 __sanitizer_install_malloc_and_free_hooks(MallocHook1, FreeHook1);47 __sanitizer_install_malloc_and_free_hooks(MallocHook2, FreeHook2);48 int *undef1, *undef2;49 allocate(undef1, undef2);50 // CHECK: MallocHook51 // CHECK: MH152 // CHECK: MH253 // Check that malloc hook was called with correct argument.54 if (global_ptr != (void*)x) {55 _exit(1);56 }57 58 // Check that realloc invokes hooks59 // We realloc to 128 here to avoid potential oversizing by allocators60 // making this a no-op.61 x = reinterpret_cast<int *>(realloc((int *)x, sizeof(int) * 128));62 // CHECK-DAG: FreeHook{{[[:space:]].*}}FH1{{[[:space:]].*}}FH263 // CHECK-DAG: MH1{{[[:space:]].*}}MH264 65 x[0] = 0;66 x[127] = -1;67 free((void *)x);68 // CHECK: FH169 // CHECK: FH270 return 0;71}72