From b5a60ec7feee21a68230761e1f4d71526ee51a0e Mon Sep 17 00:00:00 2001 From: Kuba Brecka Date: Tue, 2 Aug 2016 14:22:12 +0000 Subject: [PATCH] [tsan] Fix behavior of realloc(nullptr, 0) on Darwin On Darwin, there are some apps that rely on realloc(nullptr, 0) returning a valid pointer. TSan currently returns nullptr in this case, let's fix it to avoid breaking binary compatibility. Differential Revision: https://reviews.llvm.org/D22800 llvm-svn: 277458 --- compiler-rt/lib/tsan/rtl/tsan_mman.cc | 18 +++++++----------- compiler-rt/test/tsan/Darwin/realloc-zero.cc | 20 ++++++++++++++++++++ 2 files changed, 27 insertions(+), 11 deletions(-) create mode 100644 compiler-rt/test/tsan/Darwin/realloc-zero.cc diff --git a/compiler-rt/lib/tsan/rtl/tsan_mman.cc b/compiler-rt/lib/tsan/rtl/tsan_mman.cc index 7693077f622b..f99ddb35bbdd 100644 --- a/compiler-rt/lib/tsan/rtl/tsan_mman.cc +++ b/compiler-rt/lib/tsan/rtl/tsan_mman.cc @@ -195,20 +195,16 @@ void OnUserFree(ThreadState *thr, uptr pc, uptr p, bool write) { } void *user_realloc(ThreadState *thr, uptr pc, void *p, uptr sz) { - void *p2 = 0; // FIXME: Handle "shrinking" more efficiently, // it seems that some software actually does this. - if (sz) { - p2 = user_alloc(thr, pc, sz); - if (p2 == 0) - return 0; - if (p) { - uptr oldsz = user_alloc_usable_size(p); - internal_memcpy(p2, p, min(oldsz, sz)); - } - } - if (p) + void *p2 = user_alloc(thr, pc, sz); + if (p2 == 0) + return 0; + if (p) { + uptr oldsz = user_alloc_usable_size(p); + internal_memcpy(p2, p, min(oldsz, sz)); user_free(thr, pc, p); + } return p2; } diff --git a/compiler-rt/test/tsan/Darwin/realloc-zero.cc b/compiler-rt/test/tsan/Darwin/realloc-zero.cc new file mode 100644 index 000000000000..c5053c3eeb29 --- /dev/null +++ b/compiler-rt/test/tsan/Darwin/realloc-zero.cc @@ -0,0 +1,20 @@ +// Test that realloc(nullptr, 0) return a non-NULL pointer. + +// RUN: %clang_tsan %s -o %t +// RUN: %run %t 2>&1 | FileCheck %s + +#include +#include +#include +#include + +int main() { + void *p = realloc(nullptr, 0); + if (!p) { + abort(); + } + fprintf(stderr, "Okay.\n"); + return 0; +} + +// CHECK: Okay.