llvm-project/llvm/lib/Support/MemAlloc.cpp
Josh Stone b80965efc1
[Support] Report OOM from allocate_buffer (#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
2025-01-27 09:04:43 -08:00

39 lines
1.2 KiB
C++

//===- MemAlloc.cpp - Memory allocation functions -------------------------===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
#include "llvm/Support/MemAlloc.h"
#include <new>
// These are out of line to have __cpp_aligned_new not affect ABI.
LLVM_ATTRIBUTE_RETURNS_NONNULL LLVM_ATTRIBUTE_RETURNS_NOALIAS void *
llvm::allocate_buffer(size_t Size, size_t Alignment) {
void *Result = ::operator new(Size,
#ifdef __cpp_aligned_new
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) {
::operator delete(Ptr
#ifdef __cpp_sized_deallocation
,
Size
#endif
#ifdef __cpp_aligned_new
,
std::align_val_t(Alignment)
#endif
);
}