• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 // RUN: %clangxx -O2 %s -o %t && %run %t 2>&1 | FileCheck %s
2 
3 // Malloc/free hooks are not supported on Windows.
4 // XFAIL: win32
5 
6 #include <stdlib.h>
7 #include <unistd.h>
8 #include <sanitizer/allocator_interface.h>
9 
10 extern "C" {
11 const volatile void *global_ptr;
12 
13 // Note: avoid calling functions that allocate memory in malloc/free
14 // to avoid infinite recursion.
__sanitizer_malloc_hook(const volatile void * ptr,size_t sz)15 void __sanitizer_malloc_hook(const volatile void *ptr, size_t sz) {
16   if (__sanitizer_get_ownership(ptr)) {
17     write(1, "MallocHook\n", sizeof("MallocHook\n"));
18     global_ptr = ptr;
19   }
20 }
__sanitizer_free_hook(const volatile void * ptr)21 void __sanitizer_free_hook(const volatile void *ptr) {
22   if (__sanitizer_get_ownership(ptr) && ptr == global_ptr)
23     write(1, "FreeHook\n", sizeof("FreeHook\n"));
24 }
25 }  // extern "C"
26 
main()27 int main() {
28   volatile int *x = new int;
29   // CHECK: MallocHook
30   // Check that malloc hook was called with correct argument.
31   if (global_ptr != (void*)x) {
32     _exit(1);
33   }
34   *x = 0;
35   delete x;
36   // CHECK: FreeHook
37   return 0;
38 }
39