1//===- lib/Support/ErrorHandling.cpp - Callbacks for errors ---------------===//
2//
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
6//
7//===----------------------------------------------------------------------===//
8//
9// This file defines an API used to indicate fatal error conditions. Non-fatal
10// errors (most of them) should be handled through LLVMContext.
11//
12//===----------------------------------------------------------------------===//
13
14#include "llvm/Support/ErrorHandling.h"
15#include "llvm-c/ErrorHandling.h"
16#include "llvm/ADT/SmallVector.h"
17#include "llvm/ADT/Twine.h"
18#include "llvm/Config/config.h"
19#include "llvm/Config/llvm-config.h" // for LLVM_ENABLE_THREADS
20#include "llvm/Support/Debug.h"
21#include "llvm/Support/Errc.h"
22#include "llvm/Support/Error.h"
23#include "llvm/Support/Process.h"
24#include "llvm/Support/Signals.h"
25#include "llvm/Support/Threading.h"
26#include "llvm/Support/WindowsError.h"
27#include "llvm/Support/raw_ostream.h"
28#include <cassert>
29#include <cstdlib>
30#include <mutex>
31#include <new>
32
33#if defined(HAVE_UNISTD_H)
34# include <unistd.h>
35#endif
36#if defined(_WIN32)
37# include <io.h>
38# include <fcntl.h>
39#endif
40
41using namespace llvm;
42
43static fatal_error_handler_t ErrorHandler = nullptr;
44static void *ErrorHandlerUserData = nullptr;
45
46static fatal_error_handler_t BadAllocErrorHandler = nullptr;
47static void *BadAllocErrorHandlerUserData = nullptr;
48
49#if LLVM_ENABLE_THREADS == 1
50// Mutexes to synchronize installing error handlers and calling error handlers.
51// Do not use ManagedStatic, or that may allocate memory while attempting to
52// report an OOM.
53//
54// This usage of std::mutex has to be conditionalized behind ifdefs because
55// of this script:
56// compiler-rt/lib/sanitizer_common/symbolizer/scripts/build_symbolizer.sh
57// That script attempts to statically link the LLVM symbolizer library with the
58// STL and hide all of its symbols with 'opt -internalize'. To reduce size, it
59// cuts out the threading portions of the hermetic copy of libc++ that it
60// builds. We can remove these ifdefs if that script goes away.
61static std::mutex ErrorHandlerMutex;
62static std::mutex BadAllocErrorHandlerMutex;
63#endif
64
65void llvm::install_fatal_error_handler(fatal_error_handler_t handler,
66 void *user_data) {
67#if LLVM_ENABLE_THREADS == 1
68 std::lock_guard<std::mutex> Lock(ErrorHandlerMutex);
69#endif
70 assert(!ErrorHandler && "Error handler already registered!\n");
71 ErrorHandler = handler;
72 ErrorHandlerUserData = user_data;
73}
74
75void llvm::remove_fatal_error_handler() {
76#if LLVM_ENABLE_THREADS == 1
77 std::lock_guard<std::mutex> Lock(ErrorHandlerMutex);
78#endif
79 ErrorHandler = nullptr;
80 ErrorHandlerUserData = nullptr;
81}
82
83void llvm::report_fatal_error(const char *Reason, bool GenCrashDiag) {
84 report_fatal_error(reason: Twine(Reason), gen_crash_diag: GenCrashDiag);
85}
86
87void llvm::report_fatal_error(StringRef Reason, bool GenCrashDiag) {
88 report_fatal_error(reason: Twine(Reason), gen_crash_diag: GenCrashDiag);
89}
90
91void llvm::report_fatal_error(const Twine &Reason, bool GenCrashDiag) {
92 llvm::fatal_error_handler_t handler = nullptr;
93 void* handlerData = nullptr;
94 {
95 // Only acquire the mutex while reading the handler, so as not to invoke a
96 // user-supplied callback under a lock.
97#if LLVM_ENABLE_THREADS == 1
98 std::lock_guard<std::mutex> Lock(ErrorHandlerMutex);
99#endif
100 handler = ErrorHandler;
101 handlerData = ErrorHandlerUserData;
102 }
103
104 if (handler) {
105 handler(handlerData, Reason.str().c_str(), GenCrashDiag);
106 } else {
107 // Blast the result out to stderr. We don't try hard to make sure this
108 // succeeds (e.g. handling EINTR) and we can't use errs() here because
109 // raw ostreams can call report_fatal_error.
110 SmallVector<char, 64> Buffer;
111 raw_svector_ostream OS(Buffer);
112 OS << "LLVM ERROR: " << Reason << "\n";
113 StringRef MessageStr = OS.str();
114 ssize_t written = ::write(fd: 2, buf: MessageStr.data(), n: MessageStr.size());
115 (void)written; // If something went wrong, we deliberately just give up.
116 }
117
118 // If we reached here, we are failing ungracefully. Run the interrupt handlers
119 // to make sure any special cleanups get done, in particular that we remove
120 // files registered with RemoveFileOnSignal.
121 sys::RunInterruptHandlers();
122
123 if (GenCrashDiag)
124 abort();
125 else
126 exit(status: 1);
127}
128
129void llvm::reportFatalInternalError(const char *reason) {
130 report_fatal_error(Reason: reason, /*GenCrashDiag=*/true);
131}
132void llvm::reportFatalInternalError(StringRef reason) {
133 report_fatal_error(Reason: reason, /*GenCrashDiag=*/true);
134}
135void llvm::reportFatalInternalError(const Twine &reason) {
136 report_fatal_error(Reason: reason, /*GenCrashDiag=*/true);
137}
138void llvm::reportFatalUsageError(const char *reason) {
139 report_fatal_error(Reason: reason, /*GenCrashDiag=*/false);
140}
141void llvm::reportFatalUsageError(StringRef reason) {
142 report_fatal_error(Reason: reason, /*GenCrashDiag=*/false);
143}
144void llvm::reportFatalUsageError(const Twine &reason) {
145 report_fatal_error(Reason: reason, /*GenCrashDiag=*/false);
146}
147
148void llvm::install_bad_alloc_error_handler(fatal_error_handler_t handler,
149 void *user_data) {
150#if LLVM_ENABLE_THREADS == 1
151 std::lock_guard<std::mutex> Lock(BadAllocErrorHandlerMutex);
152#endif
153 assert(!BadAllocErrorHandler &&
154 "Bad alloc error handler already registered!\n");
155 BadAllocErrorHandler = handler;
156 BadAllocErrorHandlerUserData = user_data;
157}
158
159void llvm::remove_bad_alloc_error_handler() {
160#if LLVM_ENABLE_THREADS == 1
161 std::lock_guard<std::mutex> Lock(BadAllocErrorHandlerMutex);
162#endif
163 BadAllocErrorHandler = nullptr;
164 BadAllocErrorHandlerUserData = nullptr;
165}
166
167void llvm::report_bad_alloc_error(const char *Reason, bool GenCrashDiag) {
168 fatal_error_handler_t Handler = nullptr;
169 void *HandlerData = nullptr;
170 {
171 // Only acquire the mutex while reading the handler, so as not to invoke a
172 // user-supplied callback under a lock.
173#if LLVM_ENABLE_THREADS == 1
174 std::lock_guard<std::mutex> Lock(BadAllocErrorHandlerMutex);
175#endif
176 Handler = BadAllocErrorHandler;
177 HandlerData = BadAllocErrorHandlerUserData;
178 }
179
180 if (Handler) {
181 Handler(HandlerData, Reason, GenCrashDiag);
182 llvm_unreachable("bad alloc handler should not return");
183 }
184
185#ifdef LLVM_ENABLE_EXCEPTIONS
186 // If exceptions are enabled, make OOM in malloc look like OOM in new.
187 throw std::bad_alloc();
188#else
189 // Don't call the normal error handler. It may allocate memory. Directly write
190 // an OOM to stderr and abort.
191 const char *OOMMessage = "LLVM ERROR: out of memory\n";
192 const char *Newline = "\n";
193 (void)!::write(fd: 2, buf: OOMMessage, n: strlen(s: OOMMessage));
194 (void)!::write(fd: 2, buf: Reason, n: strlen(s: Reason));
195 (void)!::write(fd: 2, buf: Newline, n: strlen(s: Newline));
196 abort();
197#endif
198}
199
200#ifdef LLVM_ENABLE_EXCEPTIONS
201// Do not set custom new handler if exceptions are enabled. In this case OOM
202// errors are handled by throwing 'std::bad_alloc'.
203void llvm::install_out_of_memory_new_handler() {
204}
205#else
206// Causes crash on allocation failure. It is called prior to the handler set by
207// 'install_bad_alloc_error_handler'.
208static void out_of_memory_new_handler() {
209 llvm::report_bad_alloc_error(Reason: "Allocation failed");
210}
211
212// Installs new handler that causes crash on allocation failure. It is called by
213// InitLLVM.
214void llvm::install_out_of_memory_new_handler() {
215 std::new_handler old = std::set_new_handler(out_of_memory_new_handler);
216 (void)old;
217 assert((old == nullptr || old == out_of_memory_new_handler) &&
218 "new-handler already installed");
219}
220#endif
221
222void llvm::llvm_unreachable_internal(const char *msg, const char *file,
223 unsigned line) {
224 // This code intentionally doesn't call the ErrorHandler callback, because
225 // llvm_unreachable is intended to be used to indicate "impossible"
226 // situations, and not legitimate runtime errors.
227 if (msg)
228 dbgs() << msg << "\n";
229 dbgs() << "UNREACHABLE executed";
230 if (file)
231 dbgs() << " at " << file << ":" << line;
232 dbgs() << "!\n";
233 abort();
234#ifdef LLVM_BUILTIN_UNREACHABLE
235 // Windows systems and possibly others don't declare abort() to be noreturn,
236 // so use the unreachable builtin to avoid a Clang self-host warning.
237 LLVM_BUILTIN_UNREACHABLE;
238#endif
239}
240
241static void bindingsErrorHandler(void *user_data, const char *reason,
242 bool gen_crash_diag) {
243 LLVMFatalErrorHandler handler =
244 LLVM_EXTENSION reinterpret_cast<LLVMFatalErrorHandler>(user_data);
245 handler(reason);
246}
247
248void LLVMInstallFatalErrorHandler(LLVMFatalErrorHandler Handler) {
249 install_fatal_error_handler(handler: bindingsErrorHandler,
250 LLVM_EXTENSION reinterpret_cast<void *>(Handler));
251}
252
253void LLVMResetFatalErrorHandler() {
254 remove_fatal_error_handler();
255}
256
257#ifdef _WIN32
258
259#define WIN32_NO_STATUS
260#include "llvm/Support/Windows/WindowsSupport.h"
261#undef WIN32_NO_STATUS
262#include <ntstatus.h>
263#include <winerror.h>
264
265// This is equivalent to NtCurrentTeb()->LastStatusValue, but the public
266// _TEB definition does not expose the LastStatusValue field directly.
267// Avoid offsetting into this structure by calling RtlGetLastNtStatus
268// from ntdll.dll.
269//
270// The return of this function will roughly match that of
271// GetLastError, but this lower level API disambiguates some cases
272// that GetLastError does not.
273//
274// For more information, see:
275// https://www.geoffchappell.com/studies/windows/km/ntoskrnl/inc/api/pebteb/teb/index.htm
276// https://github.com/llvm/llvm-project/issues/89137
277extern "C" NTSYSAPI NTSTATUS NTAPI RtlGetLastNtStatus();
278
279// This function obtains the last error code and maps it. It may call
280// RtlGetLastNtStatus, which is a lower level API that can return a
281// more specific error code than GetLastError.
282std::error_code llvm::mapLastWindowsError() {
283 unsigned EV = ::GetLastError();
284 // The mapping of NTSTATUS to Win32 error loses some information; special
285 // case the generic ERROR_ACCESS_DENIED code to check the underlying
286 // NTSTATUS and potentially return a more accurate error code.
287 if (EV == ERROR_ACCESS_DENIED) {
288 llvm::errc code = RtlGetLastNtStatus() == STATUS_DELETE_PENDING
289 ? errc::delete_pending
290 : errc::permission_denied;
291 return make_error_code(code);
292 }
293 return mapWindowsError(EV);
294}
295
296// I'd rather not double the line count of the following.
297#define MAP_ERR_TO_COND(x, y) \
298 case x: \
299 return make_error_code(errc::y)
300
301std::error_code llvm::mapWindowsError(unsigned EV) {
302 switch (EV) {
303 MAP_ERR_TO_COND(ERROR_ACCESS_DENIED, permission_denied);
304 MAP_ERR_TO_COND(ERROR_ALREADY_EXISTS, file_exists);
305 MAP_ERR_TO_COND(ERROR_BAD_NETPATH, no_such_file_or_directory);
306 MAP_ERR_TO_COND(ERROR_BAD_PATHNAME, no_such_file_or_directory);
307 MAP_ERR_TO_COND(ERROR_BAD_UNIT, no_such_device);
308 MAP_ERR_TO_COND(ERROR_BROKEN_PIPE, broken_pipe);
309 MAP_ERR_TO_COND(ERROR_BUFFER_OVERFLOW, filename_too_long);
310 MAP_ERR_TO_COND(ERROR_BUSY, device_or_resource_busy);
311 MAP_ERR_TO_COND(ERROR_BUSY_DRIVE, device_or_resource_busy);
312 MAP_ERR_TO_COND(ERROR_CANNOT_MAKE, permission_denied);
313 MAP_ERR_TO_COND(ERROR_CANTOPEN, io_error);
314 MAP_ERR_TO_COND(ERROR_CANTREAD, io_error);
315 MAP_ERR_TO_COND(ERROR_CANTWRITE, io_error);
316 MAP_ERR_TO_COND(ERROR_CURRENT_DIRECTORY, permission_denied);
317 MAP_ERR_TO_COND(ERROR_DEV_NOT_EXIST, no_such_device);
318 MAP_ERR_TO_COND(ERROR_DEVICE_IN_USE, device_or_resource_busy);
319 MAP_ERR_TO_COND(ERROR_DIR_NOT_EMPTY, directory_not_empty);
320 MAP_ERR_TO_COND(ERROR_DIRECTORY, invalid_argument);
321 MAP_ERR_TO_COND(ERROR_DISK_FULL, no_space_on_device);
322 MAP_ERR_TO_COND(ERROR_FILE_EXISTS, file_exists);
323 MAP_ERR_TO_COND(ERROR_FILE_NOT_FOUND, no_such_file_or_directory);
324 MAP_ERR_TO_COND(ERROR_HANDLE_DISK_FULL, no_space_on_device);
325 MAP_ERR_TO_COND(ERROR_INVALID_ACCESS, permission_denied);
326 MAP_ERR_TO_COND(ERROR_INVALID_DRIVE, no_such_device);
327 MAP_ERR_TO_COND(ERROR_INVALID_FUNCTION, function_not_supported);
328 MAP_ERR_TO_COND(ERROR_INVALID_HANDLE, invalid_argument);
329 MAP_ERR_TO_COND(ERROR_INVALID_NAME, invalid_argument);
330 MAP_ERR_TO_COND(ERROR_INVALID_PARAMETER, invalid_argument);
331 MAP_ERR_TO_COND(ERROR_LOCK_VIOLATION, no_lock_available);
332 MAP_ERR_TO_COND(ERROR_LOCKED, no_lock_available);
333 MAP_ERR_TO_COND(ERROR_NEGATIVE_SEEK, invalid_argument);
334 MAP_ERR_TO_COND(ERROR_NOACCESS, permission_denied);
335 MAP_ERR_TO_COND(ERROR_NOT_ENOUGH_MEMORY, not_enough_memory);
336 MAP_ERR_TO_COND(ERROR_NOT_READY, resource_unavailable_try_again);
337 MAP_ERR_TO_COND(ERROR_NOT_SUPPORTED, not_supported);
338 MAP_ERR_TO_COND(ERROR_OPEN_FAILED, io_error);
339 MAP_ERR_TO_COND(ERROR_OPEN_FILES, device_or_resource_busy);
340 MAP_ERR_TO_COND(ERROR_OUTOFMEMORY, not_enough_memory);
341 MAP_ERR_TO_COND(ERROR_PATH_NOT_FOUND, no_such_file_or_directory);
342 MAP_ERR_TO_COND(ERROR_READ_FAULT, io_error);
343 MAP_ERR_TO_COND(ERROR_REPARSE_TAG_INVALID, invalid_argument);
344 MAP_ERR_TO_COND(ERROR_RETRY, resource_unavailable_try_again);
345 MAP_ERR_TO_COND(ERROR_SEEK, io_error);
346 MAP_ERR_TO_COND(ERROR_SHARING_VIOLATION, permission_denied);
347 MAP_ERR_TO_COND(ERROR_TOO_MANY_OPEN_FILES, too_many_files_open);
348 MAP_ERR_TO_COND(ERROR_WRITE_FAULT, io_error);
349 MAP_ERR_TO_COND(ERROR_WRITE_PROTECT, permission_denied);
350 MAP_ERR_TO_COND(WSAEACCES, permission_denied);
351 MAP_ERR_TO_COND(WSAEBADF, bad_file_descriptor);
352 MAP_ERR_TO_COND(WSAEFAULT, bad_address);
353 MAP_ERR_TO_COND(WSAEINTR, interrupted);
354 MAP_ERR_TO_COND(WSAEINVAL, invalid_argument);
355 MAP_ERR_TO_COND(WSAEMFILE, too_many_files_open);
356 MAP_ERR_TO_COND(WSAENAMETOOLONG, filename_too_long);
357 default:
358 return std::error_code(EV, std::system_category());
359 }
360}
361
362#endif
363