Fix bad free when limit exceeded. If the android limit code is enabled and a realloc would cross the limit, the old code would free the original pointer. However, this is invalid and the original pointer should not be changed. No longer free the pointer in this case and add a test for this case. Bug: 501541998 hashtag:b/501541998 Test: All unit tests pass. Test: Verify that reverting back to old behavior, new test fails. (cherry picked from commit d00918bfbbe06d4a0841d52aabe6dea3a2432787) Cherrypick-From: https://googleplex-android-review.googlesource.com/q/commit:345215d183a59011b3cd4efa9745ef33415ab57b Merged-In: I52ccd62f4f513aa55989fb7dda816d13e3171120 Change-Id: I52ccd62f4f513aa55989fb7dda816d13e3171120
diff --git a/libc/bionic/malloc_limit.cpp b/libc/bionic/malloc_limit.cpp index 1405a39..187b5ec 100644 --- a/libc/bionic/malloc_limit.cpp +++ b/libc/bionic/malloc_limit.cpp
@@ -199,8 +199,7 @@ if (bytes > old_usable_size && !CheckLimit(bytes - old_usable_size)) { warning_log("malloc_limit: realloc(%p, %zu) exceeds limit %" PRId64, old_mem, bytes, gAllocLimit); - // Free the old pointer. - LimitFree(old_mem); + // Do not free the old pointer, it's still valid. return nullptr; }
diff --git a/tests/malloc_test.cpp b/tests/malloc_test.cpp index 22905f4..d9fc017 100644 --- a/tests/malloc_test.cpp +++ b/tests/malloc_test.cpp
@@ -1279,8 +1279,10 @@ memory = realloc(memory, 80 * 1024 * 1024); ASSERT_TRUE(memory != nullptr); // Now push past limit. - memory = realloc(memory, 130 * 1024 * 1024); - ASSERT_TRUE(memory == nullptr); + void* new_memory = realloc(memory, 130 * 1024 * 1024); + ASSERT_TRUE(new_memory == nullptr); + // The original pointer should still be valid, so free it. + free(memory); VerifyMaxPointers(max_pointers); #else