From 68057c0feb00d82f2ed0ef1195282846d6d7a4ce Mon Sep 17 00:00:00 2001 From: Thurston Dang Date: Thu, 28 Aug 2025 22:57:00 +0000 Subject: [PATCH] [msan] Detect dereferencing zero-alloc as use-of-uninitialized-memory When a zero-byte allocation is requested, MSan actually allocates 1-byte for compatibility. This change poisons that byte, to detect dereferences. Also updates the test from #155934 --- compiler-rt/lib/msan/msan_allocator.cpp | 6 ++++++ compiler-rt/test/msan/zero_alloc.cpp | 4 ---- 2 files changed, 6 insertions(+), 4 deletions(-) diff --git a/compiler-rt/lib/msan/msan_allocator.cpp b/compiler-rt/lib/msan/msan_allocator.cpp index 2b543db49d36e..64df863839c06 100644 --- a/compiler-rt/lib/msan/msan_allocator.cpp +++ b/compiler-rt/lib/msan/msan_allocator.cpp @@ -230,6 +230,12 @@ static void *MsanAllocate(BufferedStackTrace *stack, uptr size, uptr alignment, __msan_set_origin(allocated, size, o.raw_id()); } } + + uptr actually_allocated_size = allocator.GetActuallyAllocatedSize(allocated); + // For compatibility, the allocator converted 0-sized allocations into 1 byte + if (size == 0 && actually_allocated_size > 0 && flags()->poison_in_malloc) + __msan_poison(allocated, 1); + UnpoisonParam(2); RunMallocHooks(allocated, size); return allocated; diff --git a/compiler-rt/test/msan/zero_alloc.cpp b/compiler-rt/test/msan/zero_alloc.cpp index e60051872eba2..6e38ce4c0a8f8 100644 --- a/compiler-rt/test/msan/zero_alloc.cpp +++ b/compiler-rt/test/msan/zero_alloc.cpp @@ -1,9 +1,5 @@ // RUN: %clang_msan -Wno-alloc-size -fsanitize-recover=memory %s -o %t && not %run %t 2>&1 | FileCheck %s -// MSan doesn't catch this because internally it translates 0-byte allocations -// into 1-byte -// XFAIL: * - #include #include