From bb9cf083c460fc5d851129d4b2f17db25be95927 Mon Sep 17 00:00:00 2001 From: Andreas Kling Date: Wed, 24 Feb 2021 23:03:38 +0100 Subject: [PATCH] LibC: Avoid double memory clearing in calloc() calloc() was internally calling malloc_impl() which would scrub out all the allocated memory with the scrub byte (0xdc). We would then immediately zero-fill the memory. This was obviously a waste of time, and our hash tables were doing it all the time. :^) --- Userland/Libraries/LibC/malloc.cpp | 13 +++++++++---- 1 file changed, 9 insertions(+), 4 deletions(-) diff --git a/Userland/Libraries/LibC/malloc.cpp b/Userland/Libraries/LibC/malloc.cpp index a340e04c9f..fe410c9467 100644 --- a/Userland/Libraries/LibC/malloc.cpp +++ b/Userland/Libraries/LibC/malloc.cpp @@ -166,7 +166,12 @@ static void os_free(void* ptr, size_t size) assert(rc == 0); } -static void* malloc_impl(size_t size) +enum class CallerWillInitializeMemory { + No, + Yes, +}; + +static void* malloc_impl(size_t size, CallerWillInitializeMemory caller_will_initialize_memory) { LOCKER(malloc_lock()); @@ -265,7 +270,7 @@ static void* malloc_impl(size_t size) } dbgln_if(MALLOC_DEBUG, "LibC: allocated {:p} (chunk in block {:p}, size {})", ptr, block, block->bytes_per_chunk()); - if (s_scrub_malloc) + if (s_scrub_malloc && caller_will_initialize_memory == CallerWillInitializeMemory::No) memset(ptr, MALLOC_SCRUB_BYTE, block->m_size); ue_notify_malloc(ptr, size); @@ -356,7 +361,7 @@ static void free_impl(void* ptr) [[gnu::flatten]] void* malloc(size_t size) { - void* ptr = malloc_impl(size); + void* ptr = malloc_impl(size, CallerWillInitializeMemory::No); if (s_profiling) perf_event(PERF_EVENT_MALLOC, size, reinterpret_cast(ptr)); return ptr; @@ -373,7 +378,7 @@ static void free_impl(void* ptr) void* calloc(size_t count, size_t size) { size_t new_size = count * size; - auto* ptr = malloc(new_size); + auto* ptr = malloc_impl(new_size, CallerWillInitializeMemory::Yes); if (ptr) memset(ptr, 0, new_size); return ptr;