ErrorHandling.cpp 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303
  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. #include "llvm/Support/ErrorHandling.h"
  14. #include "llvm-c/ErrorHandling.h"
  15. #include "llvm/ADT/SmallVector.h"
  16. #include "llvm/ADT/Twine.h"
  17. #include "llvm/Config/config.h"
  18. #include "llvm/Support/Debug.h"
  19. #include "llvm/Support/Errc.h"
  20. #include "llvm/Support/Error.h"
  21. #include "llvm/Support/Process.h"
  22. #include "llvm/Support/Signals.h"
  23. #include "llvm/Support/Threading.h"
  24. #include "llvm/Support/WindowsError.h"
  25. #include "llvm/Support/raw_ostream.h"
  26. #include <cassert>
  27. #include <cstdlib>
  28. #include <mutex>
  29. #include <new>
  30. #if defined(HAVE_UNISTD_H)
  31. # include <unistd.h>
  32. #endif
  33. #if defined(_MSC_VER)
  34. # include <io.h>
  35. # include <fcntl.h>
  36. #endif
  37. using namespace llvm;
  38. static fatal_error_handler_t ErrorHandler = nullptr;
  39. static void *ErrorHandlerUserData = nullptr;
  40. static fatal_error_handler_t BadAllocErrorHandler = nullptr;
  41. static void *BadAllocErrorHandlerUserData = nullptr;
  42. #if LLVM_ENABLE_THREADS == 1
  43. // Mutexes to synchronize installing error handlers and calling error handlers.
  44. // Do not use ManagedStatic, or that may allocate memory while attempting to
  45. // report an OOM.
  46. //
  47. // This usage of std::mutex has to be conditionalized behind ifdefs because
  48. // of this script:
  49. // compiler-rt/lib/sanitizer_common/symbolizer/scripts/build_symbolizer.sh
  50. // That script attempts to statically link the LLVM symbolizer library with the
  51. // STL and hide all of its symbols with 'opt -internalize'. To reduce size, it
  52. // cuts out the threading portions of the hermetic copy of libc++ that it
  53. // builds. We can remove these ifdefs if that script goes away.
  54. static std::mutex ErrorHandlerMutex;
  55. static std::mutex BadAllocErrorHandlerMutex;
  56. #endif
  57. void llvm::install_fatal_error_handler(fatal_error_handler_t handler,
  58. void *user_data) {
  59. #if LLVM_ENABLE_THREADS == 1
  60. std::lock_guard<std::mutex> Lock(ErrorHandlerMutex);
  61. #endif
  62. assert(!ErrorHandler && "Error handler already registered!\n");
  63. ErrorHandler = handler;
  64. ErrorHandlerUserData = user_data;
  65. }
  66. void llvm::remove_fatal_error_handler() {
  67. #if LLVM_ENABLE_THREADS == 1
  68. std::lock_guard<std::mutex> Lock(ErrorHandlerMutex);
  69. #endif
  70. ErrorHandler = nullptr;
  71. ErrorHandlerUserData = nullptr;
  72. }
  73. void llvm::report_fatal_error(const char *Reason, bool GenCrashDiag) {
  74. report_fatal_error(Twine(Reason), GenCrashDiag);
  75. }
  76. void llvm::report_fatal_error(StringRef Reason, bool GenCrashDiag) {
  77. report_fatal_error(Twine(Reason), GenCrashDiag);
  78. }
  79. void llvm::report_fatal_error(const Twine &Reason, bool GenCrashDiag) {
  80. llvm::fatal_error_handler_t handler = nullptr;
  81. void* handlerData = nullptr;
  82. {
  83. // Only acquire the mutex while reading the handler, so as not to invoke a
  84. // user-supplied callback under a lock.
  85. #if LLVM_ENABLE_THREADS == 1
  86. std::lock_guard<std::mutex> Lock(ErrorHandlerMutex);
  87. #endif
  88. handler = ErrorHandler;
  89. handlerData = ErrorHandlerUserData;
  90. }
  91. if (handler) {
  92. handler(handlerData, Reason.str().c_str(), GenCrashDiag);
  93. } else {
  94. // Blast the result out to stderr. We don't try hard to make sure this
  95. // succeeds (e.g. handling EINTR) and we can't use errs() here because
  96. // raw ostreams can call report_fatal_error.
  97. SmallVector<char, 64> Buffer;
  98. raw_svector_ostream OS(Buffer);
  99. OS << "LLVM ERROR: " << Reason << "\n";
  100. StringRef MessageStr = OS.str();
  101. ssize_t written = ::write(2, MessageStr.data(), MessageStr.size());
  102. (void)written; // If something went wrong, we deliberately just give up.
  103. }
  104. // If we reached here, we are failing ungracefully. Run the interrupt handlers
  105. // to make sure any special cleanups get done, in particular that we remove
  106. // files registered with RemoveFileOnSignal.
  107. sys::RunInterruptHandlers();
  108. abort();
  109. }
  110. void llvm::install_bad_alloc_error_handler(fatal_error_handler_t handler,
  111. void *user_data) {
  112. #if LLVM_ENABLE_THREADS == 1
  113. std::lock_guard<std::mutex> Lock(BadAllocErrorHandlerMutex);
  114. #endif
  115. assert(!ErrorHandler && "Bad alloc error handler already registered!\n");
  116. BadAllocErrorHandler = handler;
  117. BadAllocErrorHandlerUserData = user_data;
  118. }
  119. void llvm::remove_bad_alloc_error_handler() {
  120. #if LLVM_ENABLE_THREADS == 1
  121. std::lock_guard<std::mutex> Lock(BadAllocErrorHandlerMutex);
  122. #endif
  123. BadAllocErrorHandler = nullptr;
  124. BadAllocErrorHandlerUserData = nullptr;
  125. }
  126. void llvm::report_bad_alloc_error(const char *Reason, bool GenCrashDiag) {
  127. fatal_error_handler_t Handler = nullptr;
  128. void *HandlerData = nullptr;
  129. {
  130. // Only acquire the mutex while reading the handler, so as not to invoke a
  131. // user-supplied callback under a lock.
  132. #if LLVM_ENABLE_THREADS == 1
  133. std::lock_guard<std::mutex> Lock(BadAllocErrorHandlerMutex);
  134. #endif
  135. Handler = BadAllocErrorHandler;
  136. HandlerData = BadAllocErrorHandlerUserData;
  137. }
  138. if (Handler) {
  139. Handler(HandlerData, Reason, GenCrashDiag);
  140. llvm_unreachable("bad alloc handler should not return");
  141. }
  142. #ifdef LLVM_ENABLE_EXCEPTIONS
  143. // If exceptions are enabled, make OOM in malloc look like OOM in new.
  144. throw std::bad_alloc();
  145. #else
  146. // Don't call the normal error handler. It may allocate memory. Directly write
  147. // an OOM to stderr and abort.
  148. const char *OOMMessage = "LLVM ERROR: out of memory\n";
  149. const char *Newline = "\n";
  150. (void)!::write(2, OOMMessage, strlen(OOMMessage));
  151. (void)!::write(2, Reason, strlen(Reason));
  152. (void)!::write(2, Newline, strlen(Newline));
  153. abort();
  154. #endif
  155. }
  156. #ifdef LLVM_ENABLE_EXCEPTIONS
  157. // Do not set custom new handler if exceptions are enabled. In this case OOM
  158. // errors are handled by throwing 'std::bad_alloc'.
  159. void llvm::install_out_of_memory_new_handler() {
  160. }
  161. #else
  162. // Causes crash on allocation failure. It is called prior to the handler set by
  163. // 'install_bad_alloc_error_handler'.
  164. static void out_of_memory_new_handler() {
  165. llvm::report_bad_alloc_error("Allocation failed");
  166. }
  167. // Installs new handler that causes crash on allocation failure. It is called by
  168. // InitLLVM.
  169. void llvm::install_out_of_memory_new_handler() {
  170. std::new_handler old = std::set_new_handler(out_of_memory_new_handler);
  171. (void)old;
  172. assert((old == nullptr || old == out_of_memory_new_handler) &&
  173. "new-handler already installed");
  174. }
  175. #endif
  176. void llvm::llvm_unreachable_internal(const char *msg, const char *file,
  177. unsigned line) {
  178. // This code intentionally doesn't call the ErrorHandler callback, because
  179. // llvm_unreachable is intended to be used to indicate "impossible"
  180. // situations, and not legitimate runtime errors.
  181. if (msg)
  182. dbgs() << msg << "\n";
  183. dbgs() << "UNREACHABLE executed";
  184. if (file)
  185. dbgs() << " at " << file << ":" << line;
  186. dbgs() << "!\n";
  187. abort();
  188. #ifdef LLVM_BUILTIN_UNREACHABLE
  189. // Windows systems and possibly others don't declare abort() to be noreturn,
  190. // so use the unreachable builtin to avoid a Clang self-host warning.
  191. LLVM_BUILTIN_UNREACHABLE;
  192. #endif
  193. }
  194. static void bindingsErrorHandler(void *user_data, const char *reason,
  195. bool gen_crash_diag) {
  196. LLVMFatalErrorHandler handler =
  197. LLVM_EXTENSION reinterpret_cast<LLVMFatalErrorHandler>(user_data);
  198. handler(reason);
  199. }
  200. void LLVMInstallFatalErrorHandler(LLVMFatalErrorHandler Handler) {
  201. install_fatal_error_handler(bindingsErrorHandler,
  202. LLVM_EXTENSION reinterpret_cast<void *>(Handler));
  203. }
  204. void LLVMResetFatalErrorHandler() {
  205. remove_fatal_error_handler();
  206. }
  207. #ifdef _WIN32
  208. #include <winerror.h>
  209. // I'd rather not double the line count of the following.
  210. #define MAP_ERR_TO_COND(x, y) \
  211. case x: \
  212. return make_error_code(errc::y)
  213. std::error_code llvm::mapWindowsError(unsigned EV) {
  214. switch (EV) {
  215. MAP_ERR_TO_COND(ERROR_ACCESS_DENIED, permission_denied);
  216. MAP_ERR_TO_COND(ERROR_ALREADY_EXISTS, file_exists);
  217. MAP_ERR_TO_COND(ERROR_BAD_NETPATH, no_such_file_or_directory);
  218. MAP_ERR_TO_COND(ERROR_BAD_PATHNAME, no_such_file_or_directory);
  219. MAP_ERR_TO_COND(ERROR_BAD_UNIT, no_such_device);
  220. MAP_ERR_TO_COND(ERROR_BROKEN_PIPE, broken_pipe);
  221. MAP_ERR_TO_COND(ERROR_BUFFER_OVERFLOW, filename_too_long);
  222. MAP_ERR_TO_COND(ERROR_BUSY, device_or_resource_busy);
  223. MAP_ERR_TO_COND(ERROR_BUSY_DRIVE, device_or_resource_busy);
  224. MAP_ERR_TO_COND(ERROR_CANNOT_MAKE, permission_denied);
  225. MAP_ERR_TO_COND(ERROR_CANTOPEN, io_error);
  226. MAP_ERR_TO_COND(ERROR_CANTREAD, io_error);
  227. MAP_ERR_TO_COND(ERROR_CANTWRITE, io_error);
  228. MAP_ERR_TO_COND(ERROR_CURRENT_DIRECTORY, permission_denied);
  229. MAP_ERR_TO_COND(ERROR_DEV_NOT_EXIST, no_such_device);
  230. MAP_ERR_TO_COND(ERROR_DEVICE_IN_USE, device_or_resource_busy);
  231. MAP_ERR_TO_COND(ERROR_DIR_NOT_EMPTY, directory_not_empty);
  232. MAP_ERR_TO_COND(ERROR_DIRECTORY, invalid_argument);
  233. MAP_ERR_TO_COND(ERROR_DISK_FULL, no_space_on_device);
  234. MAP_ERR_TO_COND(ERROR_FILE_EXISTS, file_exists);
  235. MAP_ERR_TO_COND(ERROR_FILE_NOT_FOUND, no_such_file_or_directory);
  236. MAP_ERR_TO_COND(ERROR_HANDLE_DISK_FULL, no_space_on_device);
  237. MAP_ERR_TO_COND(ERROR_INVALID_ACCESS, permission_denied);
  238. MAP_ERR_TO_COND(ERROR_INVALID_DRIVE, no_such_device);
  239. MAP_ERR_TO_COND(ERROR_INVALID_FUNCTION, function_not_supported);
  240. MAP_ERR_TO_COND(ERROR_INVALID_HANDLE, invalid_argument);
  241. MAP_ERR_TO_COND(ERROR_INVALID_NAME, invalid_argument);
  242. MAP_ERR_TO_COND(ERROR_INVALID_PARAMETER, invalid_argument);
  243. MAP_ERR_TO_COND(ERROR_LOCK_VIOLATION, no_lock_available);
  244. MAP_ERR_TO_COND(ERROR_LOCKED, no_lock_available);
  245. MAP_ERR_TO_COND(ERROR_NEGATIVE_SEEK, invalid_argument);
  246. MAP_ERR_TO_COND(ERROR_NOACCESS, permission_denied);
  247. MAP_ERR_TO_COND(ERROR_NOT_ENOUGH_MEMORY, not_enough_memory);
  248. MAP_ERR_TO_COND(ERROR_NOT_READY, resource_unavailable_try_again);
  249. MAP_ERR_TO_COND(ERROR_NOT_SUPPORTED, not_supported);
  250. MAP_ERR_TO_COND(ERROR_OPEN_FAILED, io_error);
  251. MAP_ERR_TO_COND(ERROR_OPEN_FILES, device_or_resource_busy);
  252. MAP_ERR_TO_COND(ERROR_OUTOFMEMORY, not_enough_memory);
  253. MAP_ERR_TO_COND(ERROR_PATH_NOT_FOUND, no_such_file_or_directory);
  254. MAP_ERR_TO_COND(ERROR_READ_FAULT, io_error);
  255. MAP_ERR_TO_COND(ERROR_REPARSE_TAG_INVALID, invalid_argument);
  256. MAP_ERR_TO_COND(ERROR_RETRY, resource_unavailable_try_again);
  257. MAP_ERR_TO_COND(ERROR_SEEK, io_error);
  258. MAP_ERR_TO_COND(ERROR_SHARING_VIOLATION, permission_denied);
  259. MAP_ERR_TO_COND(ERROR_TOO_MANY_OPEN_FILES, too_many_files_open);
  260. MAP_ERR_TO_COND(ERROR_WRITE_FAULT, io_error);
  261. MAP_ERR_TO_COND(ERROR_WRITE_PROTECT, permission_denied);
  262. MAP_ERR_TO_COND(WSAEACCES, permission_denied);
  263. MAP_ERR_TO_COND(WSAEBADF, bad_file_descriptor);
  264. MAP_ERR_TO_COND(WSAEFAULT, bad_address);
  265. MAP_ERR_TO_COND(WSAEINTR, interrupted);
  266. MAP_ERR_TO_COND(WSAEINVAL, invalid_argument);
  267. MAP_ERR_TO_COND(WSAEMFILE, too_many_files_open);
  268. MAP_ERR_TO_COND(WSAENAMETOOLONG, filename_too_long);
  269. default:
  270. return std::error_code(EV, std::system_category());
  271. }
  272. }
  273. #endif