From ca9c18a2e81357d3b9563851ed0a0ddf7e19db87 Mon Sep 17 00:00:00 2001 From: Vitaly Buka Date: Thu, 22 Jun 2023 17:12:37 -0700 Subject: [PATCH] [msan] Optimize zeroing allocated memory Reviewed By: thurston Differential Revision: https://reviews.llvm.org/D153599 --- compiler-rt/lib/msan/msan_allocator.cpp | 10 +++++++--- .../test/sanitizer_common/TestCases/Posix/huge_malloc.c | 8 +++----- 2 files changed, 10 insertions(+), 8 deletions(-) diff --git a/compiler-rt/lib/msan/msan_allocator.cpp b/compiler-rt/lib/msan/msan_allocator.cpp index 72296da..4c22305 100644 --- a/compiler-rt/lib/msan/msan_allocator.cpp +++ b/compiler-rt/lib/msan/msan_allocator.cpp @@ -192,7 +192,10 @@ static void *MsanAllocate(StackTrace *stack, uptr size, uptr alignment, reinterpret_cast(allocator.GetMetaData(allocated)); meta->requested_size = size; if (zeroise) { - __msan_clear_and_unpoison(allocated, size); + if (allocator.FromPrimary(allocated)) + __msan_clear_and_unpoison(allocated, size); + else + __msan_unpoison(allocated, size); // Mem is already zeroed. } else if (flags()->poison_in_malloc) { __msan_poison(allocated, size); if (__msan_get_track_origins()) { @@ -215,8 +218,9 @@ void MsanDeallocate(StackTrace *stack, void *p) { uptr size = meta->requested_size; meta->requested_size = 0; // This memory will not be reused by anyone else, so we are free to keep it - // poisoned. - if (flags()->poison_in_free) { + // poisoned. The secondary allocator will unmap and unpoison by + // MsanMapUnmapCallback, no need to poison it here. + if (flags()->poison_in_free && allocator.FromPrimary(p)) { __msan_poison(p, size); if (__msan_get_track_origins()) { stack->tag = StackTrace::TAG_DEALLOC; diff --git a/compiler-rt/test/sanitizer_common/TestCases/Posix/huge_malloc.c b/compiler-rt/test/sanitizer_common/TestCases/Posix/huge_malloc.c index 00b0e01..a3e9cd7 100644 --- a/compiler-rt/test/sanitizer_common/TestCases/Posix/huge_malloc.c +++ b/compiler-rt/test/sanitizer_common/TestCases/Posix/huge_malloc.c @@ -9,9 +9,6 @@ // FIXME: Hangs. // UNSUPPORTED: tsan -// FIXME: Make it work. Don't xfail to avoid excessive memory usage. -// UNSUPPORTED: msan - // Hwasan requires tagging of new allocations, so needs RSS for shadow. // UNSUPPORTED: hwasan @@ -19,8 +16,9 @@ void *p; int main(int argc, char **argv) { for (int i = 0; i < sizeof(void *) * 8; ++i) { - p = malloc(1ull << i); - fprintf(stderr, "%llu: %p\n", (1ull << i), p); + // Calloc avoids MSAN shadow poisoning. + p = calloc(1ull << i, 1); + fprintf(stderr, "%d %llu: %p\n", i, (1ull << i), p); free(p); } return 0; -- 2.7.4