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/libc/private/MallocXmlElem.h b/libc/private/MallocXmlElem.h
index 04d3eee..a367972 100644
--- a/libc/private/MallocXmlElem.h
+++ b/libc/private/MallocXmlElem.h
@@ -18,38 +18,39 @@
#include <stdarg.h>
#include <stdio.h>
+#include <unistd.h>
#include <private/bionic_macros.h>
class MallocXmlElem {
public:
// Name must be valid throughout lifetime of the object.
- explicit MallocXmlElem(FILE* fp, const char* name,
- const char* attr_fmt = nullptr, ...) : fp_(fp), name_(name) {
- fprintf(fp, "<%s", name_);
+ explicit MallocXmlElem(int fd, const char* name,
+ const char* attr_fmt = nullptr, ...) : fd_(fd), name_(name) {
+ dprintf(fd_, "<%s", name_);
if (attr_fmt != nullptr) {
va_list args;
va_start(args, attr_fmt);
- fputc(' ', fp_);
- vfprintf(fp_, attr_fmt, args);
+ write(fd_, " ", 1);
+ vdprintf(fd_, attr_fmt, args);
va_end(args);
}
- fputc('>', fp_);
+ write(fd_, ">", 1);
}
~MallocXmlElem() noexcept {
- fprintf(fp_, "</%s>", name_);
+ dprintf(fd_, "</%s>", name_);
}
void Contents(const char* fmt, ...) {
va_list args;
va_start(args, fmt);
- vfprintf(fp_, fmt, args);
+ vdprintf(fd_, fmt, args);
va_end(args);
}
private:
- FILE* fp_;
+ int fd_;
const char* name_;
BIONIC_DISALLOW_IMPLICIT_CONSTRUCTORS(MallocXmlElem);