xref: /llvm-project/compiler-rt/test/gwp_asan/realloc.cpp (revision a62586846fa90054bd9224912b07095d2fca662c)
121184ec5SMitch Phillips // REQUIRES: gwp_asan
221184ec5SMitch Phillips // RUN: %clangxx_gwp_asan %s -o %t -DTEST_MALLOC
3*a6258684SMitch Phillips // RUN: %expect_crash %run %t 2>&1 | FileCheck %s --check-prefix CHECK-MALLOC
421184ec5SMitch Phillips 
521184ec5SMitch Phillips // Check both C++98 and C.
621184ec5SMitch Phillips // RUN: %clangxx_gwp_asan -std=c++98 %s -o %t -DTEST_FREE
721184ec5SMitch Phillips // RUN: %expect_crash %run %t 2>&1 | FileCheck %s --check-prefix CHECK-FREE
821184ec5SMitch Phillips // RUN: cp %s %t.c && %clang_gwp_asan %t.c -o %t -DTEST_FREE
921184ec5SMitch Phillips // RUN: %expect_crash %run %t 2>&1 | FileCheck %s --check-prefix CHECK-FREE
1021184ec5SMitch Phillips 
1121184ec5SMitch Phillips // Ensure GWP-ASan stub implementation of realloc() in Scudo works to-spec. In
1221184ec5SMitch Phillips // particular, the behaviour regarding realloc of size zero is interesting, as
1321184ec5SMitch Phillips // it's defined as free().
1421184ec5SMitch Phillips 
1521184ec5SMitch Phillips #include <stdlib.h>
1621184ec5SMitch Phillips 
main()1721184ec5SMitch Phillips int main() {
1821184ec5SMitch Phillips #if defined(TEST_MALLOC)
1921184ec5SMitch Phillips   // realloc(nullptr, size) is equivalent to malloc(size).
2021184ec5SMitch Phillips   char *Ptr = reinterpret_cast<char *>(realloc(nullptr, 1));
2121184ec5SMitch Phillips   *Ptr = 0;
2221184ec5SMitch Phillips   // Trigger an INVALID_FREE to the right.
2321184ec5SMitch Phillips   free(Ptr + 1);
2421184ec5SMitch Phillips 
2521184ec5SMitch Phillips   // CHECK-MALLOC: GWP-ASan detected a memory error
26*a6258684SMitch Phillips   // CHECK-MALLOC: Invalid (Wild) Free at 0x{{[a-f0-9]+}} (1 byte to the right
277339ca27SMitch Phillips   // CHECK-MALLOC-SAME: of a 1-byte allocation
2821184ec5SMitch Phillips #elif defined(TEST_FREE)
2921184ec5SMitch Phillips   char *Ptr = (char *) malloc(1);
3021184ec5SMitch Phillips   // realloc(ptr, 0) is equivalent to free(ptr) and must return nullptr. Note
3121184ec5SMitch Phillips   // that this is only the specification in C++98 and C.
3221184ec5SMitch Phillips   if (realloc(Ptr, 0) != NULL) {
3321184ec5SMitch Phillips 
3421184ec5SMitch Phillips   }
3521184ec5SMitch Phillips   // Trigger a USE_AFTER_FREE.
3621184ec5SMitch Phillips   *Ptr = 0;
3721184ec5SMitch Phillips 
3821184ec5SMitch Phillips   // CHECK-FREE: GWP-ASan detected a memory error
39*a6258684SMitch Phillips   // CHECK-FREE: Use After Free at 0x{{[a-f0-9]+}} (0 bytes into a 1-byte
407339ca27SMitch Phillips   // CHECK-FREE-SAME: allocation
4121184ec5SMitch Phillips #endif
4221184ec5SMitch Phillips 
4321184ec5SMitch Phillips   return 0;
4421184ec5SMitch Phillips }
45