Fix race in malloc debug option free_track.
The free track mechanism could fail if, at the same time a free occurs,
another thread is trying to free and verify the same allocation. This
doesn't work if the freed allocation is added to the list and we still
do work on it. The fix is to only add to the free list when we are done
with the allocation.
Also fix a problem where the usable size is computed incorrectly because
two of the arguments where reversed.
In addition, add a check that the allocation being verified has the correct
tag before trying to check the body of the allocation.
Add a test to catch the original failure.
Add a test for the tag being different.
Bug: 27601650
Change-Id: Ie9200677d066255b8e668a48422f23f909f4ddee
diff --git a/libc/malloc_debug/FreeTrackData.cpp b/libc/malloc_debug/FreeTrackData.cpp
index 3ac54bf..ed41981 100644
--- a/libc/malloc_debug/FreeTrackData.cpp
+++ b/libc/malloc_debug/FreeTrackData.cpp
@@ -67,18 +67,25 @@
const void* pointer) {
ScopedDisableDebugCalls disable;
- const uint8_t* memory = reinterpret_cast<const uint8_t*>(pointer);
- size_t bytes = header->usable_size;
- bytes = (bytes < debug.config().fill_on_free_bytes) ? bytes : debug.config().fill_on_free_bytes;
- while (bytes > 0) {
- size_t bytes_to_cmp = (bytes < cmp_mem_.size()) ? bytes : cmp_mem_.size();
- if (memcmp(memory, cmp_mem_.data(), bytes_to_cmp) != 0) {
- LogFreeError(debug, header, reinterpret_cast<const uint8_t*>(pointer));
- break;
+ if (header->tag != DEBUG_FREE_TAG) {
+ error_log(LOG_DIVIDER);
+ error_log("+++ ALLOCATION %p HAS CORRUPTED HEADER TAG 0x%x AFTER FREE", pointer, header->tag);
+ error_log(LOG_DIVIDER);
+ } else {
+ const uint8_t* memory = reinterpret_cast<const uint8_t*>(pointer);
+ size_t bytes = header->usable_size;
+ bytes = (bytes < debug.config().fill_on_free_bytes) ? bytes : debug.config().fill_on_free_bytes;
+ while (bytes > 0) {
+ size_t bytes_to_cmp = (bytes < cmp_mem_.size()) ? bytes : cmp_mem_.size();
+ if (memcmp(memory, cmp_mem_.data(), bytes_to_cmp) != 0) {
+ LogFreeError(debug, header, reinterpret_cast<const uint8_t*>(pointer));
+ break;
+ }
+ bytes -= bytes_to_cmp;
+ memory = &memory[bytes_to_cmp];
}
- bytes -= bytes_to_cmp;
- memory = &memory[bytes_to_cmp];
}
+
auto back_iter = backtraces_.find(header);
if (back_iter != backtraces_.end()) {
g_dispatch->free(reinterpret_cast<void*>(back_iter->second));
@@ -98,7 +105,6 @@
list_.pop_back();
}
- // Only log the free backtrace if we are using the free track feature.
if (backtrace_num_frames_ > 0) {
BacktraceHeader* back_header = reinterpret_cast<BacktraceHeader*>(
g_dispatch->malloc(sizeof(BacktraceHeader) + backtrace_num_frames_ * sizeof(uintptr_t)));