From 04fd535409ddc601a4654e38ff28db3f13c10713 Mon Sep 17 00:00:00 2001 From: Thurston Dang Date: Sat, 13 May 2023 00:00:31 +0000 Subject: ASan: add backtrace_symbols test and clarify code is correct This is another patch for https://github.com/google/sanitizers/issues/321 (sanitizer interceptors can write to freed memory, causing corruption), in this case for backtrace_symbols. backtrace_symbols is already correct, hence this patch removes the TODO note. Additionally, this patch adds a test case for it. Differential Revision: https://reviews.llvm.org/D150498 --- .../sanitizer_common_interceptors.inc | 5 ++- .../TestCases/backtrace_symbols_interceptor.cpp | 36 ++++++++++++++++++++++ 2 files changed, 38 insertions(+), 3 deletions(-) create mode 100644 compiler-rt/test/asan/TestCases/backtrace_symbols_interceptor.cpp (limited to 'compiler-rt') diff --git a/compiler-rt/lib/sanitizer_common/sanitizer_common_interceptors.inc b/compiler-rt/lib/sanitizer_common/sanitizer_common_interceptors.inc index 490a8b12d8b1..1c315a5183c6 100644 --- a/compiler-rt/lib/sanitizer_common/sanitizer_common_interceptors.inc +++ b/compiler-rt/lib/sanitizer_common/sanitizer_common_interceptors.inc @@ -4418,9 +4418,8 @@ INTERCEPTOR(char **, backtrace_symbols, void **buffer, int size) { COMMON_INTERCEPTOR_ENTER(ctx, backtrace_symbols, buffer, size); if (buffer && size) COMMON_INTERCEPTOR_READ_RANGE(ctx, buffer, size * sizeof(*buffer)); - // FIXME: under ASan the call below may write to freed memory and corrupt - // its metadata. See - // https://github.com/google/sanitizers/issues/321. + // The COMMON_INTERCEPTOR_READ_RANGE above ensures that 'buffer' is + // valid for reading. char **res = REAL(backtrace_symbols)(buffer, size); if (res && size) { COMMON_INTERCEPTOR_WRITE_RANGE(ctx, res, size * sizeof(*res)); diff --git a/compiler-rt/test/asan/TestCases/backtrace_symbols_interceptor.cpp b/compiler-rt/test/asan/TestCases/backtrace_symbols_interceptor.cpp new file mode 100644 index 000000000000..a78969408a7f --- /dev/null +++ b/compiler-rt/test/asan/TestCases/backtrace_symbols_interceptor.cpp @@ -0,0 +1,36 @@ +// RUN: %clangxx_asan -O0 %s -o %t && not %run %t 2>&1 | FileCheck %s + +// Test the backtrace_symbols() interceptor. + +#include +#include +#include +#include +#include + +#define MAX_BT 100 + +int main() { + void **buffer = (void **)malloc(sizeof(void *) * MAX_BT); + assert(buffer != NULL); + + int numEntries = backtrace(buffer, MAX_BT); + printf("backtrace returned %d entries\n", numEntries); + + free(buffer); + + // Deliberate use-after-free of 'buffer'. We expect ASan to + // catch this, without triggering internal sanitizer errors. + char **strings = backtrace_symbols(buffer, numEntries); + assert(strings != NULL); + + for (int i = 0; i < numEntries; i++) { + printf("%s\n", strings[i]); + } + + free(strings); + + // CHECK: use-after-free + // CHECK: SUMMARY + return 0; +} -- cgit v1.2.1