Skip to content

Commit b3452d9

Browse files
authored
[asan] Detect dereferencing zero-alloc as heap buffer overflow (#155943)
When a zero-byte allocation is requested, ASan actually allocates 1-byte for compatibility. This change poisons that byte, to detect dereferences. Also updates the test from #155933
1 parent 8784dce commit b3452d9

File tree

2 files changed

+6
-4
lines changed

2 files changed

+6
-4
lines changed

compiler-rt/lib/asan/asan_allocator.cpp

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -547,6 +547,7 @@ struct Allocator {
547547
ComputeUserRequestedAlignmentLog(alignment);
548548
if (alignment < min_alignment)
549549
alignment = min_alignment;
550+
bool upgraded_from_zero = false;
550551
if (size == 0) {
551552
// We'd be happy to avoid allocating memory for zero-size requests, but
552553
// some programs/tests depend on this behavior and assume that malloc
@@ -555,6 +556,7 @@ struct Allocator {
555556
// consecutive "new" calls must be different even if the allocated size
556557
// is zero.
557558
size = 1;
559+
upgraded_from_zero = true;
558560
}
559561
CHECK(IsPowerOfTwo(alignment));
560562
uptr rz_log = ComputeRZLog(size);
@@ -637,6 +639,10 @@ struct Allocator {
637639
*shadow = fl.poison_partial ? (size & (ASAN_SHADOW_GRANULARITY - 1)) : 0;
638640
}
639641

642+
if (upgraded_from_zero)
643+
PoisonShadow(user_beg, ASAN_SHADOW_GRANULARITY,
644+
kAsanHeapLeftRedzoneMagic);
645+
640646
AsanStats &thread_stats = GetCurrentThreadStats();
641647
thread_stats.mallocs++;
642648
thread_stats.malloced += size;

compiler-rt/test/asan/TestCases/zero_alloc.cpp

Lines changed: 0 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,5 @@
11
// RUN: %clang_asan -Wno-alloc-size -fsanitize-recover=address %s -o %t && %env_asan_opts=halt_on_error=0 %run %t 2>&1 | FileCheck %s
22

3-
// ASan doesn't catch this because internally it translates 0-byte allocations
4-
// into 1-byte
5-
// XFAIL: *
6-
73
#include <malloc.h>
84
#include <stdio.h>
95

0 commit comments

Comments
 (0)