58 lines · cpp
1// RUN: %clangxx_nsan %s -o %t && %run %t 2>&1 | FileCheck %s2 3#include <sanitizer/allocator_interface.h>4#include <stdlib.h>5#include <unistd.h>6 7extern "C" {8const volatile void *global_ptr;9 10#define WRITE(s) write(1, s, sizeof(s))11 12// Note: avoid calling functions that allocate memory in malloc/free13// to avoid infinite recursion.14void __sanitizer_malloc_hook(const volatile void *ptr, size_t sz) {15 if (__sanitizer_get_ownership(ptr) && sz == 4) {16 WRITE("MallocHook\n");17 global_ptr = ptr;18 }19}20void __sanitizer_free_hook(const volatile void *ptr) {21 if (__sanitizer_get_ownership(ptr) && ptr == global_ptr)22 WRITE("FreeHook\n");23}24} // extern "C"25 26volatile int *x;27 28void MallocHook1(const volatile void *ptr, size_t sz) { WRITE("MH1\n"); }29void MallocHook2(const volatile void *ptr, size_t sz) { WRITE("MH2\n"); }30void FreeHook1(const volatile void *ptr) { WRITE("FH1\n"); }31void FreeHook2(const volatile void *ptr) { WRITE("FH2\n"); }32// Call this function with uninitialized arguments to poison33// TLS shadow for function parameters before calling operator34// new and, eventually, user-provided hook.35__attribute__((noinline)) void allocate(int *unused1, int *unused2) {36 x = new int;37}38 39int main() {40 __sanitizer_install_malloc_and_free_hooks(MallocHook1, FreeHook1);41 __sanitizer_install_malloc_and_free_hooks(MallocHook2, FreeHook2);42 int *undef1, *undef2;43 allocate(undef1, undef2);44 // CHECK: MallocHook45 // CHECK: MH146 // CHECK: MH247 // Check that malloc hook was called with correct argument.48 if (global_ptr != (void *)x) {49 _exit(1);50 }51 *x = 0;52 delete x;53 // CHECK: FreeHook54 // CHECK: FH155 // CHECK: FH256 return 0;57}58