Fix allocations escaping malloc debug.
When using a FILE object for some malloc debug functions, calling
fprintf will trigger an allocation to be put in the object. The problem
is that these allocations were not allocated by the malloc debug
wrapper and they get freed during the fclose as if they are malloc
debug allocation. In most cases, the code will detect the bad pointer
and leak the memory, but it might also cause a crash.
The fix is to avoid using fprintf so that no allocations are made
in the object that survive and need to be freed in the fclose call.
Change the MallocXmlElem.h to use a file decsriptor not a FILE object.
Add new unit and system tests to detect this case.
Bug: 143742907
Test: Ran unit and system tests.
Test: Ran bionic unit tests.
Change-Id: I524392de822a29483aa5be8f14c680e70033eba2
diff --git a/tests/malloc_test.cpp b/tests/malloc_test.cpp
index 0407553..ebbd247 100644
--- a/tests/malloc_test.cpp
+++ b/tests/malloc_test.cpp
@@ -358,15 +358,20 @@
TEST(malloc, malloc_info) {
#ifdef __BIONIC__
SKIP_WITH_HWASAN; // hwasan does not implement malloc_info
- char* buf;
- size_t bufsize;
- FILE* memstream = open_memstream(&buf, &bufsize);
- ASSERT_NE(nullptr, memstream);
- ASSERT_EQ(0, malloc_info(0, memstream));
- ASSERT_EQ(0, fclose(memstream));
+
+ TemporaryFile tf;
+ ASSERT_TRUE(tf.fd != -1);
+ FILE* fp = fdopen(tf.fd, "w+");
+ tf.release();
+ ASSERT_TRUE(fp != nullptr);
+ ASSERT_EQ(0, malloc_info(0, fp));
+ ASSERT_EQ(0, fclose(fp));
+
+ std::string contents;
+ ASSERT_TRUE(android::base::ReadFileToString(tf.path, &contents));
tinyxml2::XMLDocument doc;
- ASSERT_EQ(tinyxml2::XML_SUCCESS, doc.Parse(buf));
+ ASSERT_EQ(tinyxml2::XML_SUCCESS, doc.Parse(contents.c_str()));
auto root = doc.FirstChildElement();
ASSERT_NE(nullptr, root);
@@ -416,17 +421,21 @@
#ifdef __BIONIC__
SKIP_WITH_HWASAN; // hwasan does not implement malloc_info
- char* buf;
- size_t bufsize;
- FILE* memstream = open_memstream(&buf, &bufsize);
- ASSERT_NE(nullptr, memstream);
+ TemporaryFile tf;
+ ASSERT_TRUE(tf.fd != -1);
+ FILE* fp = fdopen(tf.fd, "w+");
+ tf.release();
+ ASSERT_TRUE(fp != nullptr);
size_t mallinfo_before_allocated_bytes = mallinfo().uordblks;
- ASSERT_EQ(0, malloc_info(0, memstream));
+ ASSERT_EQ(0, malloc_info(0, fp));
size_t mallinfo_after_allocated_bytes = mallinfo().uordblks;
- ASSERT_EQ(0, fclose(memstream));
+ ASSERT_EQ(0, fclose(fp));
+
+ std::string contents;
+ ASSERT_TRUE(android::base::ReadFileToString(tf.path, &contents));
tinyxml2::XMLDocument doc;
- ASSERT_EQ(tinyxml2::XML_SUCCESS, doc.Parse(buf));
+ ASSERT_EQ(tinyxml2::XML_SUCCESS, doc.Parse(contents.c_str()));
size_t total_allocated_bytes = 0;
auto root = doc.FirstChildElement();