1//===- lib/Support/ErrorHandling.cpp - Callbacks for errors ---------------===//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
7//===----------------------------------------------------------------------===//
9// This file defines an API used to indicate fatal error conditions. Non-fatal
10// errors (most of them) should be handled through LLVMContext.
12//===----------------------------------------------------------------------===//
18#include "llvm/Config/config.h"
19#include "llvm/Config/llvm-config.h" // for LLVM_ENABLE_THREADS
34#if defined(HAVE_UNISTD_H)
50#if LLVM_ENABLE_THREADS == 1
51// Mutexes to synchronize installing error handlers and calling error handlers.
52// Do not use ManagedStatic, or that may allocate memory while attempting to
55// This usage of std::mutex has to be conditionalized behind ifdefs because
57// compiler-rt/lib/sanitizer_common/symbolizer/scripts/build_symbolizer.sh
58// That script attempts to statically link the LLVM symbolizer library with the
59// STL and hide all of its symbols with 'opt -internalize'. To reduce size, it
60// cuts out the threading portions of the hermetic copy of libc++ that it
61// builds. We can remove these ifdefs if that script goes away.
62static std::mutex ErrorHandlerMutex;
63static std::mutex BadAllocErrorHandlerMutex;
79#if LLVM_ENABLE_THREADS == 1
80 std::lock_guard<std::mutex> Lock(ErrorHandlerMutex);
88#if LLVM_ENABLE_THREADS == 1
89 std::lock_guard<std::mutex> Lock(ErrorHandlerMutex);
105 void* handlerData =
nullptr;
107 // Only acquire the mutex while reading the handler, so as not to invoke a
108 // user-supplied callback under a lock.
109#if LLVM_ENABLE_THREADS == 1
110 std::lock_guard<std::mutex> Lock(ErrorHandlerMutex);
117 handler(handlerData, Reason.
str().c_str(), GenCrashDiag);
119 // Blast the result out to stderr. We don't try hard to make sure this
120 // succeeds (e.g. handling EINTR) and we can't use errs() here because
121 // raw ostreams can call report_fatal_error.
124 OS <<
"LLVM ERROR: " << Reason <<
"\n";
129 // If we reached here, we are failing ungracefully. Run the interrupt handlers
130 // to make sure any special cleanups get done, in particular that we remove
131 // files registered with RemoveFileOnSignal.
161#if LLVM_ENABLE_THREADS == 1
162 std::lock_guard<std::mutex> Lock(BadAllocErrorHandlerMutex);
165 "Bad alloc error handler already registered!\n");
171#if LLVM_ENABLE_THREADS == 1
172 std::lock_guard<std::mutex> Lock(BadAllocErrorHandlerMutex);
180 void *HandlerData =
nullptr;
182 // Only acquire the mutex while reading the handler, so as not to invoke a
183 // user-supplied callback under a lock.
184#if LLVM_ENABLE_THREADS == 1
185 std::lock_guard<std::mutex> Lock(BadAllocErrorHandlerMutex);
192 Handler(HandlerData, Reason, GenCrashDiag);
196#ifdef LLVM_ENABLE_EXCEPTIONS
197 // If exceptions are enabled, make OOM in malloc look like OOM in new.
198 throw std::bad_alloc();
200 // Don't call the normal error handler. It may allocate memory. Directly write
201 // an OOM to stderr and abort.
202 const char *OOMMessage =
"LLVM ERROR: out of memory\n";
203 const char *Newline =
"\n";
211#ifdef LLVM_ENABLE_EXCEPTIONS
212// Do not set custom new handler if exceptions are enabled. In this case OOM
213// errors are handled by throwing 'std::bad_alloc'.
217// Causes crash on allocation failure. It is called prior to the handler set by
218// 'install_bad_alloc_error_handler'.
223// Installs new handler that causes crash on allocation failure. It is called by
229 "new-handler already installed");
235 // This code intentionally doesn't call the ErrorHandler callback, because
236 // llvm_unreachable is intended to be used to indicate "impossible"
237 // situations, and not legitimate runtime errors.
239 dbgs() << msg <<
"\n";
240 dbgs() <<
"UNREACHABLE executed";
242 dbgs() <<
" at " <<
file <<
":" << line;
245#ifdef LLVM_BUILTIN_UNREACHABLE
246 // Windows systems and possibly others don't declare abort() to be noreturn,
247 // so use the unreachable builtin to avoid a Clang self-host warning.
248 LLVM_BUILTIN_UNREACHABLE;
253 bool gen_crash_diag) {
270#define WIN32_NO_STATUS
272#undef WIN32_NO_STATUS
276// This is equivalent to NtCurrentTeb()->LastStatusValue, but the public
277// _TEB definition does not expose the LastStatusValue field directly.
278// Avoid offsetting into this structure by calling RtlGetLastNtStatus
281// The return of this function will roughly match that of
282// GetLastError, but this lower level API disambiguates some cases
283// that GetLastError does not.
285// For more information, see:
286// https://www.geoffchappell.com/studies/windows/km/ntoskrnl/inc/api/pebteb/teb/index.htm
287// https://github.com/llvm/llvm-project/issues/89137
288extern "C" NTSYSAPI NTSTATUS NTAPI RtlGetLastNtStatus();
290// This function obtains the last error code and maps it. It may call
291// RtlGetLastNtStatus, which is a lower level API that can return a
292// more specific error code than GetLastError.
294 unsigned EV = ::GetLastError();
295 // The mapping of NTSTATUS to Win32 error loses some information; special
296 // case the generic ERROR_ACCESS_DENIED code to check the underlying
297 // NTSTATUS and potentially return a more accurate error code.
298 if (EV == ERROR_ACCESS_DENIED) {
299 llvm::errc code = RtlGetLastNtStatus() == STATUS_DELETE_PENDING
307// I'd rather not double the line count of the following.
308#define MAP_ERR_TO_COND(x, y) \
310 return make_error_code(errc::y)
315 MAP_ERR_TO_COND(ERROR_ALREADY_EXISTS,
file_exists);
324 MAP_ERR_TO_COND(ERROR_CANTOPEN,
io_error);
325 MAP_ERR_TO_COND(ERROR_CANTREAD,
io_error);
326 MAP_ERR_TO_COND(ERROR_CANTWRITE,
io_error);
349 MAP_ERR_TO_COND(ERROR_OPEN_FAILED,
io_error);
353 MAP_ERR_TO_COND(ERROR_READ_FAULT,
io_error);
356 MAP_ERR_TO_COND(ERROR_SEEK,
io_error);
359 MAP_ERR_TO_COND(ERROR_WRITE_FAULT,
io_error);
369 return std::error_code(EV, std::system_category());
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
#define LLVM_EXTENSION
LLVM_EXTENSION - Support compilers where we have a keyword to suppress pedantic diagnostics.
static fatal_error_handler_t ErrorHandler
static void out_of_memory_new_handler()
static bool write_retry(int fd, const char *buf, size_t count)
static void bindingsErrorHandler(void *user_data, const char *reason, bool gen_crash_diag)
static fatal_error_handler_t BadAllocErrorHandler
static void * BadAllocErrorHandlerUserData
static void * ErrorHandlerUserData
Provides a library for accessing information about this process and other processes on the operating ...
dot regions Print regions of function to dot file(with no function bodies)"
This file defines the SmallVector class.
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
StringRef - Represent a constant reference to a string, i.e.
constexpr size_t size() const
size - Get the string size.
constexpr const char * data() const
data - Get a pointer to the start of the string (which may not be null terminated).
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
LLVM_ABI std::string str() const
Return the twine contents as a std::string.
A raw_ostream that writes to an SmallVector or SmallString.
StringRef str() const
Return a StringRef for the vector contents.
void LLVMResetFatalErrorHandler()
Reset the fatal error handler.
void(* LLVMFatalErrorHandler)(const char *Reason)
void LLVMInstallFatalErrorHandler(LLVMFatalErrorHandler Handler)
Install a fatal error handler.
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
decltype(auto) RetryAfterSignal(const FailT &Fail, const Fun &F, const Args &... As)
LLVM_ABI void RunInterruptHandlers()
This function runs all the registered interrupt handlers, including the removal of files registered b...
This is an optimization pass for GlobalISel generic memory operations.
LLVM_ABI std::error_code mapLastWindowsError()
std::error_code make_error_code(BitcodeError E)
LLVM_ABI void install_fatal_error_handler(fatal_error_handler_t handler, void *user_data=nullptr)
install_fatal_error_handler - Installs a new error handler to be used whenever a serious (non-recover...
LLVM_ABI void install_bad_alloc_error_handler(fatal_error_handler_t handler, void *user_data=nullptr)
Installs a new bad alloc error handler that should be used whenever a bad alloc error,...
LLVM_ABI void remove_bad_alloc_error_handler()
Restores default bad alloc error handling behavior.
LLVM_ABI void reportFatalInternalError(Error Err)
Report a fatal error that indicates a bug in LLVM.
@ no_such_file_or_directory
@ device_or_resource_busy
@ resource_unavailable_try_again
LLVM_ABI Error write(MCStreamer &Out, ArrayRef< std::string > Inputs, OnCuIndexOverflow OverflowOptValue)
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
LLVM_ABI void report_fatal_error(Error Err, bool gen_crash_diag=true)
LLVM_ABI void install_out_of_memory_new_handler()
LLVM_ABI void llvm_unreachable_internal(const char *msg=nullptr, const char *file=nullptr, unsigned line=0)
This function calls abort(), and prints the optional message to stderr.
void(*)(void *user_data, const char *reason, bool gen_crash_diag) fatal_error_handler_t
An error handler callback.
auto count(R &&Range, const E &Element)
Wrapper function around std::count to count the number of times an element Element occurs in the give...
LLVM_ABI void remove_fatal_error_handler()
Restores default error handling behaviour.
LLVM_ABI std::error_code mapWindowsError(unsigned EV)
LLVM_ABI void report_bad_alloc_error(const char *Reason, bool GenCrashDiag=true)
Reports a bad alloc error, calling any user defined bad alloc error handler.
LLVM_ABI void reportFatalUsageError(Error Err)
Report a fatal error that does not indicate a bug in LLVM.