[llvm] [Support] Report OOM from `allocate_buffer` (PR #85449)

Josh Stone via llvm-commits llvm-commits at lists.llvm.org
Fri Mar 15 12:09:38 PDT 2024


https://github.com/cuviper created https://github.com/llvm/llvm-project/pull/85449

Previously, it called `::operator new` which may throw `std::bad_alloc`,
regardless of whether LLVM itself was built with exception handling, and
this can cause safety issues if outside code has destructors that will
call back into LLVM. Now we use `::operator new(..., nothrow)` and call
`llvm::report_bad_alloc_error` when allocation fails, which will abort
when LLVM is built without exceptions.

Ref: https://github.com/llvm/llvm-project/issues/85281


>From fd9ddc5baf44768a4d13a2af89a4efed5501f82d Mon Sep 17 00:00:00 2001
From: Josh Stone <jistone at redhat.com>
Date: Fri, 15 Mar 2024 11:53:07 -0700
Subject: [PATCH] [Support] Report OOM from `allocate_buffer`

Previously, it called `::operator new` which may throw `std::bad_alloc`,
regardless of whether LLVM itself was built with exception handling, and
this can cause safety issues if outside code has destructors that will
call back into LLVM. Now we use `::operator new(..., nothrow)` and call
`llvm::report_bad_alloc_error` when allocation fails, which will abort
when LLVM is built without exceptions.

Ref: https://github.com/llvm/llvm-project/issues/85281
---
 llvm/lib/Support/MemAlloc.cpp | 11 +++++++----
 1 file changed, 7 insertions(+), 4 deletions(-)

diff --git a/llvm/lib/Support/MemAlloc.cpp b/llvm/lib/Support/MemAlloc.cpp
index 07a26cf26480b3..6adc9abd75c5b9 100644
--- a/llvm/lib/Support/MemAlloc.cpp
+++ b/llvm/lib/Support/MemAlloc.cpp
@@ -13,12 +13,15 @@
 
 LLVM_ATTRIBUTE_RETURNS_NONNULL LLVM_ATTRIBUTE_RETURNS_NOALIAS void *
 llvm::allocate_buffer(size_t Size, size_t Alignment) {
-  return ::operator new(Size
+  void *Result = ::operator new(Size,
 #ifdef __cpp_aligned_new
-                        ,
-                        std::align_val_t(Alignment)
+                                std::align_val_t(Alignment),
 #endif
-  );
+                                std::nothrow);
+  if (Result == nullptr) {
+    report_bad_alloc_error("Buffer allocation failed");
+  }
+  return Result;
 }
 
 void llvm::deallocate_buffer(void *Ptr, size_t Size, size_t Alignment) {



More information about the llvm-commits mailing list