From 3f954f575156bce8ac81d6b4d94de443786befed Mon Sep 17 00:00:00 2001 From: Aaron Ballman Date: Wed, 15 May 2024 12:33:54 -0400 Subject: [PATCH] Correct mismatched allocation/deallocation calls This amends dceaa0f4491ebe30c0b0f1bc7fa5ec365b60ced6 because ASAN caught an issue where the allocation and deallocation were not properly paired: https://lab.llvm.org/buildbot/#/builders/239/builds/7001 Use malloc and free throughout this file to ensure that all kinds of memory buffers use the proper pairing. --- llvm/lib/Support/MemoryBuffer.cpp | 14 +++++++++++--- 1 file changed, 11 insertions(+), 3 deletions(-) diff --git a/llvm/lib/Support/MemoryBuffer.cpp b/llvm/lib/Support/MemoryBuffer.cpp index 50308bd2bf4a..fb7e804fd7e8 100644 --- a/llvm/lib/Support/MemoryBuffer.cpp +++ b/llvm/lib/Support/MemoryBuffer.cpp @@ -79,8 +79,16 @@ void *operator new(size_t N, const NamedBufferAlloc &Alloc) { SmallString<256> NameBuf; StringRef NameRef = Alloc.Name.toStringRef(NameBuf); - char *Mem = static_cast(operator new(N + sizeof(size_t) + - NameRef.size() + 1)); + // We use malloc() and manually handle it returning null instead of calling + // operator new because we need all uses of NamedBufferAlloc to be + // deallocated with a call to free() due to needing to use malloc() in + // WritableMemoryBuffer::getNewUninitMemBuffer() to work around the out-of- + // memory handler installed by default in LLVM. See operator delete() member + // functions within this file for the paired call to free(). + char *Mem = + static_cast(std::malloc(N + sizeof(size_t) + NameRef.size() + 1)); + if (!Mem) + llvm::report_bad_alloc_error("Allocation failed"); *reinterpret_cast(Mem + N) = NameRef.size(); CopyStringRef(Mem + N + sizeof(size_t), NameRef); return Mem; @@ -225,7 +233,7 @@ public: /// Disable sized deallocation for MemoryBufferMMapFile, because it has /// tail-allocated data. - void operator delete(void *p) { ::operator delete(p); } + void operator delete(void *p) { std::free(p); } StringRef getBufferIdentifier() const override { // The name is stored after the class itself.