1207618Srdivacky//===- lib/Support/ErrorHandling.cpp - Callbacks for errors ---------------===//
2198090Srdivacky//
3353358Sdim// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4353358Sdim// See https://llvm.org/LICENSE.txt for license information.
5353358Sdim// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6198090Srdivacky//
7198090Srdivacky//===----------------------------------------------------------------------===//
8198090Srdivacky//
9207618Srdivacky// This file defines an API used to indicate fatal error conditions.  Non-fatal
10207618Srdivacky// errors (most of them) should be handled through LLVMContext.
11207618Srdivacky//
12198090Srdivacky//===----------------------------------------------------------------------===//
13198090Srdivacky
14249423Sdim#include "llvm/Support/ErrorHandling.h"
15296417Sdim#include "llvm-c/ErrorHandling.h"
16249423Sdim#include "llvm/ADT/SmallVector.h"
17198090Srdivacky#include "llvm/ADT/Twine.h"
18249423Sdim#include "llvm/Config/config.h"
19202375Srdivacky#include "llvm/Support/Debug.h"
20276479Sdim#include "llvm/Support/Errc.h"
21309124Sdim#include "llvm/Support/Error.h"
22360784Sdim#include "llvm/Support/Process.h"
23280031Sdim#include "llvm/Support/Signals.h"
24218893Sdim#include "llvm/Support/Threading.h"
25276479Sdim#include "llvm/Support/WindowsError.h"
26249423Sdim#include "llvm/Support/raw_ostream.h"
27198090Srdivacky#include <cassert>
28198090Srdivacky#include <cstdlib>
29321369Sdim#include <mutex>
30321369Sdim#include <new>
31212904Sdim
32212904Sdim#if defined(HAVE_UNISTD_H)
33212904Sdim# include <unistd.h>
34212904Sdim#endif
35212904Sdim#if defined(_MSC_VER)
36212904Sdim# include <io.h>
37212904Sdim# include <fcntl.h>
38212904Sdim#endif
39212904Sdim
40198090Srdivackyusing namespace llvm;
41198090Srdivacky
42276479Sdimstatic fatal_error_handler_t ErrorHandler = nullptr;
43276479Sdimstatic void *ErrorHandlerUserData = nullptr;
44198090Srdivacky
45321369Sdimstatic fatal_error_handler_t BadAllocErrorHandler = nullptr;
46321369Sdimstatic void *BadAllocErrorHandlerUserData = nullptr;
47276479Sdim
48321369Sdim#if LLVM_ENABLE_THREADS == 1
49321369Sdim// Mutexes to synchronize installing error handlers and calling error handlers.
50321369Sdim// Do not use ManagedStatic, or that may allocate memory while attempting to
51321369Sdim// report an OOM.
52321369Sdim//
53321369Sdim// This usage of std::mutex has to be conditionalized behind ifdefs because
54321369Sdim// of this script:
55321369Sdim//   compiler-rt/lib/sanitizer_common/symbolizer/scripts/build_symbolizer.sh
56321369Sdim// That script attempts to statically link the LLVM symbolizer library with the
57321369Sdim// STL and hide all of its symbols with 'opt -internalize'. To reduce size, it
58321369Sdim// cuts out the threading portions of the hermetic copy of libc++ that it
59321369Sdim// builds. We can remove these ifdefs if that script goes away.
60321369Sdimstatic std::mutex ErrorHandlerMutex;
61321369Sdimstatic std::mutex BadAllocErrorHandlerMutex;
62321369Sdim#endif
63321369Sdim
64207618Srdivackyvoid llvm::install_fatal_error_handler(fatal_error_handler_t handler,
65207618Srdivacky                                       void *user_data) {
66321369Sdim#if LLVM_ENABLE_THREADS == 1
67321369Sdim  std::lock_guard<std::mutex> Lock(ErrorHandlerMutex);
68321369Sdim#endif
69198090Srdivacky  assert(!ErrorHandler && "Error handler already registered!\n");
70198090Srdivacky  ErrorHandler = handler;
71198090Srdivacky  ErrorHandlerUserData = user_data;
72198090Srdivacky}
73198090Srdivacky
74207618Srdivackyvoid llvm::remove_fatal_error_handler() {
75321369Sdim#if LLVM_ENABLE_THREADS == 1
76321369Sdim  std::lock_guard<std::mutex> Lock(ErrorHandlerMutex);
77321369Sdim#endif
78276479Sdim  ErrorHandler = nullptr;
79276479Sdim  ErrorHandlerUserData = nullptr;
80198090Srdivacky}
81198090Srdivacky
82249423Sdimvoid llvm::report_fatal_error(const char *Reason, bool GenCrashDiag) {
83249423Sdim  report_fatal_error(Twine(Reason), GenCrashDiag);
84198090Srdivacky}
85198090Srdivacky
86249423Sdimvoid llvm::report_fatal_error(const std::string &Reason, bool GenCrashDiag) {
87249423Sdim  report_fatal_error(Twine(Reason), GenCrashDiag);
88198090Srdivacky}
89198090Srdivacky
90249423Sdimvoid llvm::report_fatal_error(StringRef Reason, bool GenCrashDiag) {
91249423Sdim  report_fatal_error(Twine(Reason), GenCrashDiag);
92218893Sdim}
93218893Sdim
94249423Sdimvoid llvm::report_fatal_error(const Twine &Reason, bool GenCrashDiag) {
95276479Sdim  llvm::fatal_error_handler_t handler = nullptr;
96276479Sdim  void* handlerData = nullptr;
97276479Sdim  {
98276479Sdim    // Only acquire the mutex while reading the handler, so as not to invoke a
99276479Sdim    // user-supplied callback under a lock.
100321369Sdim#if LLVM_ENABLE_THREADS == 1
101321369Sdim    std::lock_guard<std::mutex> Lock(ErrorHandlerMutex);
102321369Sdim#endif
103276479Sdim    handler = ErrorHandler;
104276479Sdim    handlerData = ErrorHandlerUserData;
105276479Sdim  }
106276479Sdim
107276479Sdim  if (handler) {
108276479Sdim    handler(handlerData, Reason.str(), GenCrashDiag);
109198090Srdivacky  } else {
110212904Sdim    // Blast the result out to stderr.  We don't try hard to make sure this
111212904Sdim    // succeeds (e.g. handling EINTR) and we can't use errs() here because
112212904Sdim    // raw ostreams can call report_fatal_error.
113212904Sdim    SmallVector<char, 64> Buffer;
114212904Sdim    raw_svector_ostream OS(Buffer);
115212904Sdim    OS << "LLVM ERROR: " << Reason << "\n";
116212904Sdim    StringRef MessageStr = OS.str();
117218893Sdim    ssize_t written = ::write(2, MessageStr.data(), MessageStr.size());
118218893Sdim    (void)written; // If something went wrong, we deliberately just give up.
119198090Srdivacky  }
120208599Srdivacky
121208599Srdivacky  // If we reached here, we are failing ungracefully. Run the interrupt handlers
122208599Srdivacky  // to make sure any special cleanups get done, in particular that we remove
123208599Srdivacky  // files registered with RemoveFileOnSignal.
124208599Srdivacky  sys::RunInterruptHandlers();
125208599Srdivacky
126360784Sdim  sys::Process::Exit(1);
127198090Srdivacky}
128198090Srdivacky
129321369Sdimvoid llvm::install_bad_alloc_error_handler(fatal_error_handler_t handler,
130321369Sdim                                           void *user_data) {
131321369Sdim#if LLVM_ENABLE_THREADS == 1
132321369Sdim  std::lock_guard<std::mutex> Lock(BadAllocErrorHandlerMutex);
133321369Sdim#endif
134321369Sdim  assert(!ErrorHandler && "Bad alloc error handler already registered!\n");
135321369Sdim  BadAllocErrorHandler = handler;
136321369Sdim  BadAllocErrorHandlerUserData = user_data;
137321369Sdim}
138321369Sdim
139321369Sdimvoid llvm::remove_bad_alloc_error_handler() {
140321369Sdim#if LLVM_ENABLE_THREADS == 1
141321369Sdim  std::lock_guard<std::mutex> Lock(BadAllocErrorHandlerMutex);
142321369Sdim#endif
143321369Sdim  BadAllocErrorHandler = nullptr;
144321369Sdim  BadAllocErrorHandlerUserData = nullptr;
145321369Sdim}
146321369Sdim
147321369Sdimvoid llvm::report_bad_alloc_error(const char *Reason, bool GenCrashDiag) {
148321369Sdim  fatal_error_handler_t Handler = nullptr;
149321369Sdim  void *HandlerData = nullptr;
150321369Sdim  {
151321369Sdim    // Only acquire the mutex while reading the handler, so as not to invoke a
152321369Sdim    // user-supplied callback under a lock.
153321369Sdim#if LLVM_ENABLE_THREADS == 1
154321369Sdim    std::lock_guard<std::mutex> Lock(BadAllocErrorHandlerMutex);
155321369Sdim#endif
156321369Sdim    Handler = BadAllocErrorHandler;
157321369Sdim    HandlerData = BadAllocErrorHandlerUserData;
158321369Sdim  }
159321369Sdim
160321369Sdim  if (Handler) {
161321369Sdim    Handler(HandlerData, Reason, GenCrashDiag);
162321369Sdim    llvm_unreachable("bad alloc handler should not return");
163321369Sdim  }
164321369Sdim
165321369Sdim#ifdef LLVM_ENABLE_EXCEPTIONS
166321369Sdim  // If exceptions are enabled, make OOM in malloc look like OOM in new.
167321369Sdim  throw std::bad_alloc();
168321369Sdim#else
169321369Sdim  // Don't call the normal error handler. It may allocate memory. Directly write
170321369Sdim  // an OOM to stderr and abort.
171321369Sdim  char OOMMessage[] = "LLVM ERROR: out of memory\n";
172321723Sdim  ssize_t written = ::write(2, OOMMessage, strlen(OOMMessage));
173321723Sdim  (void)written;
174321369Sdim  abort();
175321369Sdim#endif
176321369Sdim}
177321369Sdim
178341825Sdim#ifdef LLVM_ENABLE_EXCEPTIONS
179341825Sdim// Do not set custom new handler if exceptions are enabled. In this case OOM
180341825Sdim// errors are handled by throwing 'std::bad_alloc'.
181341825Sdimvoid llvm::install_out_of_memory_new_handler() {
182341825Sdim}
183341825Sdim#else
184341825Sdim// Causes crash on allocation failure. It is called prior to the handler set by
185341825Sdim// 'install_bad_alloc_error_handler'.
186341825Sdimstatic void out_of_memory_new_handler() {
187341825Sdim  llvm::report_bad_alloc_error("Allocation failed");
188341825Sdim}
189341825Sdim
190353358Sdim// Installs new handler that causes crash on allocation failure. It is called by
191353358Sdim// InitLLVM.
192341825Sdimvoid llvm::install_out_of_memory_new_handler() {
193353358Sdim  std::new_handler old = std::set_new_handler(out_of_memory_new_handler);
194353358Sdim  (void)old;
195353358Sdim  assert(old == nullptr && "new-handler already installed");
196341825Sdim}
197341825Sdim#endif
198341825Sdim
199207618Srdivackyvoid llvm::llvm_unreachable_internal(const char *msg, const char *file,
200207618Srdivacky                                     unsigned line) {
201198090Srdivacky  // This code intentionally doesn't call the ErrorHandler callback, because
202198090Srdivacky  // llvm_unreachable is intended to be used to indicate "impossible"
203198090Srdivacky  // situations, and not legitimate runtime errors.
204198090Srdivacky  if (msg)
205202375Srdivacky    dbgs() << msg << "\n";
206202375Srdivacky  dbgs() << "UNREACHABLE executed";
207198090Srdivacky  if (file)
208202375Srdivacky    dbgs() << " at " << file << ":" << line;
209202375Srdivacky  dbgs() << "!\n";
210198090Srdivacky  abort();
211261991Sdim#ifdef LLVM_BUILTIN_UNREACHABLE
212261991Sdim  // Windows systems and possibly others don't declare abort() to be noreturn,
213261991Sdim  // so use the unreachable builtin to avoid a Clang self-host warning.
214261991Sdim  LLVM_BUILTIN_UNREACHABLE;
215261991Sdim#endif
216198090Srdivacky}
217261991Sdim
218261991Sdimstatic void bindingsErrorHandler(void *user_data, const std::string& reason,
219261991Sdim                                 bool gen_crash_diag) {
220261991Sdim  LLVMFatalErrorHandler handler =
221261991Sdim      LLVM_EXTENSION reinterpret_cast<LLVMFatalErrorHandler>(user_data);
222261991Sdim  handler(reason.c_str());
223261991Sdim}
224261991Sdim
225261991Sdimvoid LLVMInstallFatalErrorHandler(LLVMFatalErrorHandler Handler) {
226261991Sdim  install_fatal_error_handler(bindingsErrorHandler,
227261991Sdim                              LLVM_EXTENSION reinterpret_cast<void *>(Handler));
228261991Sdim}
229261991Sdim
230261991Sdimvoid LLVMResetFatalErrorHandler() {
231261991Sdim  remove_fatal_error_handler();
232261991Sdim}
233276479Sdim
234341825Sdim#ifdef _WIN32
235276479Sdim
236276479Sdim#include <winerror.h>
237276479Sdim
238276479Sdim// I'd rather not double the line count of the following.
239276479Sdim#define MAP_ERR_TO_COND(x, y)                                                  \
240276479Sdim  case x:                                                                      \
241276479Sdim    return make_error_code(errc::y)
242276479Sdim
243276479Sdimstd::error_code llvm::mapWindowsError(unsigned EV) {
244276479Sdim  switch (EV) {
245276479Sdim    MAP_ERR_TO_COND(ERROR_ACCESS_DENIED, permission_denied);
246276479Sdim    MAP_ERR_TO_COND(ERROR_ALREADY_EXISTS, file_exists);
247276479Sdim    MAP_ERR_TO_COND(ERROR_BAD_UNIT, no_such_device);
248276479Sdim    MAP_ERR_TO_COND(ERROR_BUFFER_OVERFLOW, filename_too_long);
249276479Sdim    MAP_ERR_TO_COND(ERROR_BUSY, device_or_resource_busy);
250276479Sdim    MAP_ERR_TO_COND(ERROR_BUSY_DRIVE, device_or_resource_busy);
251276479Sdim    MAP_ERR_TO_COND(ERROR_CANNOT_MAKE, permission_denied);
252276479Sdim    MAP_ERR_TO_COND(ERROR_CANTOPEN, io_error);
253276479Sdim    MAP_ERR_TO_COND(ERROR_CANTREAD, io_error);
254276479Sdim    MAP_ERR_TO_COND(ERROR_CANTWRITE, io_error);
255276479Sdim    MAP_ERR_TO_COND(ERROR_CURRENT_DIRECTORY, permission_denied);
256276479Sdim    MAP_ERR_TO_COND(ERROR_DEV_NOT_EXIST, no_such_device);
257276479Sdim    MAP_ERR_TO_COND(ERROR_DEVICE_IN_USE, device_or_resource_busy);
258276479Sdim    MAP_ERR_TO_COND(ERROR_DIR_NOT_EMPTY, directory_not_empty);
259276479Sdim    MAP_ERR_TO_COND(ERROR_DIRECTORY, invalid_argument);
260276479Sdim    MAP_ERR_TO_COND(ERROR_DISK_FULL, no_space_on_device);
261276479Sdim    MAP_ERR_TO_COND(ERROR_FILE_EXISTS, file_exists);
262276479Sdim    MAP_ERR_TO_COND(ERROR_FILE_NOT_FOUND, no_such_file_or_directory);
263276479Sdim    MAP_ERR_TO_COND(ERROR_HANDLE_DISK_FULL, no_space_on_device);
264276479Sdim    MAP_ERR_TO_COND(ERROR_INVALID_ACCESS, permission_denied);
265276479Sdim    MAP_ERR_TO_COND(ERROR_INVALID_DRIVE, no_such_device);
266276479Sdim    MAP_ERR_TO_COND(ERROR_INVALID_FUNCTION, function_not_supported);
267276479Sdim    MAP_ERR_TO_COND(ERROR_INVALID_HANDLE, invalid_argument);
268276479Sdim    MAP_ERR_TO_COND(ERROR_INVALID_NAME, invalid_argument);
269276479Sdim    MAP_ERR_TO_COND(ERROR_LOCK_VIOLATION, no_lock_available);
270276479Sdim    MAP_ERR_TO_COND(ERROR_LOCKED, no_lock_available);
271276479Sdim    MAP_ERR_TO_COND(ERROR_NEGATIVE_SEEK, invalid_argument);
272276479Sdim    MAP_ERR_TO_COND(ERROR_NOACCESS, permission_denied);
273276479Sdim    MAP_ERR_TO_COND(ERROR_NOT_ENOUGH_MEMORY, not_enough_memory);
274276479Sdim    MAP_ERR_TO_COND(ERROR_NOT_READY, resource_unavailable_try_again);
275276479Sdim    MAP_ERR_TO_COND(ERROR_OPEN_FAILED, io_error);
276276479Sdim    MAP_ERR_TO_COND(ERROR_OPEN_FILES, device_or_resource_busy);
277276479Sdim    MAP_ERR_TO_COND(ERROR_OUTOFMEMORY, not_enough_memory);
278276479Sdim    MAP_ERR_TO_COND(ERROR_PATH_NOT_FOUND, no_such_file_or_directory);
279276479Sdim    MAP_ERR_TO_COND(ERROR_BAD_NETPATH, no_such_file_or_directory);
280276479Sdim    MAP_ERR_TO_COND(ERROR_READ_FAULT, io_error);
281276479Sdim    MAP_ERR_TO_COND(ERROR_RETRY, resource_unavailable_try_again);
282276479Sdim    MAP_ERR_TO_COND(ERROR_SEEK, io_error);
283276479Sdim    MAP_ERR_TO_COND(ERROR_SHARING_VIOLATION, permission_denied);
284276479Sdim    MAP_ERR_TO_COND(ERROR_TOO_MANY_OPEN_FILES, too_many_files_open);
285276479Sdim    MAP_ERR_TO_COND(ERROR_WRITE_FAULT, io_error);
286276479Sdim    MAP_ERR_TO_COND(ERROR_WRITE_PROTECT, permission_denied);
287276479Sdim    MAP_ERR_TO_COND(WSAEACCES, permission_denied);
288276479Sdim    MAP_ERR_TO_COND(WSAEBADF, bad_file_descriptor);
289276479Sdim    MAP_ERR_TO_COND(WSAEFAULT, bad_address);
290276479Sdim    MAP_ERR_TO_COND(WSAEINTR, interrupted);
291276479Sdim    MAP_ERR_TO_COND(WSAEINVAL, invalid_argument);
292276479Sdim    MAP_ERR_TO_COND(WSAEMFILE, too_many_files_open);
293276479Sdim    MAP_ERR_TO_COND(WSAENAMETOOLONG, filename_too_long);
294276479Sdim  default:
295276479Sdim    return std::error_code(EV, std::system_category());
296276479Sdim  }
297276479Sdim}
298276479Sdim
299276479Sdim#endif
300