ErrorHandling.cpp 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306
  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. if (GenCrashDiag)
  109. abort();
  110. else
  111. exit(1);
  112. }
  113. void llvm::install_bad_alloc_error_handler(fatal_error_handler_t handler,
  114. void *user_data) {
  115. #if LLVM_ENABLE_THREADS == 1
  116. std::lock_guard<std::mutex> Lock(BadAllocErrorHandlerMutex);
  117. #endif
  118. assert(!ErrorHandler && "Bad alloc error handler already registered!\n");
  119. BadAllocErrorHandler = handler;
  120. BadAllocErrorHandlerUserData = user_data;
  121. }
  122. void llvm::remove_bad_alloc_error_handler() {
  123. #if LLVM_ENABLE_THREADS == 1
  124. std::lock_guard<std::mutex> Lock(BadAllocErrorHandlerMutex);
  125. #endif
  126. BadAllocErrorHandler = nullptr;
  127. BadAllocErrorHandlerUserData = nullptr;
  128. }
  129. void llvm::report_bad_alloc_error(const char *Reason, bool GenCrashDiag) {
  130. fatal_error_handler_t Handler = nullptr;
  131. void *HandlerData = nullptr;
  132. {
  133. // Only acquire the mutex while reading the handler, so as not to invoke a
  134. // user-supplied callback under a lock.
  135. #if LLVM_ENABLE_THREADS == 1
  136. std::lock_guard<std::mutex> Lock(BadAllocErrorHandlerMutex);
  137. #endif
  138. Handler = BadAllocErrorHandler;
  139. HandlerData = BadAllocErrorHandlerUserData;
  140. }
  141. if (Handler) {
  142. Handler(HandlerData, Reason, GenCrashDiag);
  143. llvm_unreachable("bad alloc handler should not return");
  144. }
  145. #ifdef LLVM_ENABLE_EXCEPTIONS
  146. // If exceptions are enabled, make OOM in malloc look like OOM in new.
  147. throw std::bad_alloc();
  148. #else
  149. // Don't call the normal error handler. It may allocate memory. Directly write
  150. // an OOM to stderr and abort.
  151. const char *OOMMessage = "LLVM ERROR: out of memory\n";
  152. const char *Newline = "\n";
  153. (void)!::write(2, OOMMessage, strlen(OOMMessage));
  154. (void)!::write(2, Reason, strlen(Reason));
  155. (void)!::write(2, Newline, strlen(Newline));
  156. abort();
  157. #endif
  158. }
  159. #ifdef LLVM_ENABLE_EXCEPTIONS
  160. // Do not set custom new handler if exceptions are enabled. In this case OOM
  161. // errors are handled by throwing 'std::bad_alloc'.
  162. void llvm::install_out_of_memory_new_handler() {
  163. }
  164. #else
  165. // Causes crash on allocation failure. It is called prior to the handler set by
  166. // 'install_bad_alloc_error_handler'.
  167. static void out_of_memory_new_handler() {
  168. llvm::report_bad_alloc_error("Allocation failed");
  169. }
  170. // Installs new handler that causes crash on allocation failure. It is called by
  171. // InitLLVM.
  172. void llvm::install_out_of_memory_new_handler() {
  173. std::new_handler old = std::set_new_handler(out_of_memory_new_handler);
  174. (void)old;
  175. assert((old == nullptr || old == out_of_memory_new_handler) &&
  176. "new-handler already installed");
  177. }
  178. #endif
  179. void llvm::llvm_unreachable_internal(const char *msg, const char *file,
  180. unsigned line) {
  181. // This code intentionally doesn't call the ErrorHandler callback, because
  182. // llvm_unreachable is intended to be used to indicate "impossible"
  183. // situations, and not legitimate runtime errors.
  184. if (msg)
  185. dbgs() << msg << "\n";
  186. dbgs() << "UNREACHABLE executed";
  187. if (file)
  188. dbgs() << " at " << file << ":" << line;
  189. dbgs() << "!\n";
  190. abort();
  191. #ifdef LLVM_BUILTIN_UNREACHABLE
  192. // Windows systems and possibly others don't declare abort() to be noreturn,
  193. // so use the unreachable builtin to avoid a Clang self-host warning.
  194. LLVM_BUILTIN_UNREACHABLE;
  195. #endif
  196. }
  197. static void bindingsErrorHandler(void *user_data, const char *reason,
  198. bool gen_crash_diag) {
  199. LLVMFatalErrorHandler handler =
  200. LLVM_EXTENSION reinterpret_cast<LLVMFatalErrorHandler>(user_data);
  201. handler(reason);
  202. }
  203. void LLVMInstallFatalErrorHandler(LLVMFatalErrorHandler Handler) {
  204. install_fatal_error_handler(bindingsErrorHandler,
  205. LLVM_EXTENSION reinterpret_cast<void *>(Handler));
  206. }
  207. void LLVMResetFatalErrorHandler() {
  208. remove_fatal_error_handler();
  209. }
  210. #ifdef _WIN32
  211. #include <winerror.h>
  212. // I'd rather not double the line count of the following.
  213. #define MAP_ERR_TO_COND(x, y) \
  214. case x: \
  215. return make_error_code(errc::y)
  216. std::error_code llvm::mapWindowsError(unsigned EV) {
  217. switch (EV) {
  218. MAP_ERR_TO_COND(ERROR_ACCESS_DENIED, permission_denied);
  219. MAP_ERR_TO_COND(ERROR_ALREADY_EXISTS, file_exists);
  220. MAP_ERR_TO_COND(ERROR_BAD_NETPATH, no_such_file_or_directory);
  221. MAP_ERR_TO_COND(ERROR_BAD_PATHNAME, no_such_file_or_directory);
  222. MAP_ERR_TO_COND(ERROR_BAD_UNIT, no_such_device);
  223. MAP_ERR_TO_COND(ERROR_BROKEN_PIPE, broken_pipe);
  224. MAP_ERR_TO_COND(ERROR_BUFFER_OVERFLOW, filename_too_long);
  225. MAP_ERR_TO_COND(ERROR_BUSY, device_or_resource_busy);
  226. MAP_ERR_TO_COND(ERROR_BUSY_DRIVE, device_or_resource_busy);
  227. MAP_ERR_TO_COND(ERROR_CANNOT_MAKE, permission_denied);
  228. MAP_ERR_TO_COND(ERROR_CANTOPEN, io_error);
  229. MAP_ERR_TO_COND(ERROR_CANTREAD, io_error);
  230. MAP_ERR_TO_COND(ERROR_CANTWRITE, io_error);
  231. MAP_ERR_TO_COND(ERROR_CURRENT_DIRECTORY, permission_denied);
  232. MAP_ERR_TO_COND(ERROR_DEV_NOT_EXIST, no_such_device);
  233. MAP_ERR_TO_COND(ERROR_DEVICE_IN_USE, device_or_resource_busy);
  234. MAP_ERR_TO_COND(ERROR_DIR_NOT_EMPTY, directory_not_empty);
  235. MAP_ERR_TO_COND(ERROR_DIRECTORY, invalid_argument);
  236. MAP_ERR_TO_COND(ERROR_DISK_FULL, no_space_on_device);
  237. MAP_ERR_TO_COND(ERROR_FILE_EXISTS, file_exists);
  238. MAP_ERR_TO_COND(ERROR_FILE_NOT_FOUND, no_such_file_or_directory);
  239. MAP_ERR_TO_COND(ERROR_HANDLE_DISK_FULL, no_space_on_device);
  240. MAP_ERR_TO_COND(ERROR_INVALID_ACCESS, permission_denied);
  241. MAP_ERR_TO_COND(ERROR_INVALID_DRIVE, no_such_device);
  242. MAP_ERR_TO_COND(ERROR_INVALID_FUNCTION, function_not_supported);
  243. MAP_ERR_TO_COND(ERROR_INVALID_HANDLE, invalid_argument);
  244. MAP_ERR_TO_COND(ERROR_INVALID_NAME, invalid_argument);
  245. MAP_ERR_TO_COND(ERROR_INVALID_PARAMETER, invalid_argument);
  246. MAP_ERR_TO_COND(ERROR_LOCK_VIOLATION, no_lock_available);
  247. MAP_ERR_TO_COND(ERROR_LOCKED, no_lock_available);
  248. MAP_ERR_TO_COND(ERROR_NEGATIVE_SEEK, invalid_argument);
  249. MAP_ERR_TO_COND(ERROR_NOACCESS, permission_denied);
  250. MAP_ERR_TO_COND(ERROR_NOT_ENOUGH_MEMORY, not_enough_memory);
  251. MAP_ERR_TO_COND(ERROR_NOT_READY, resource_unavailable_try_again);
  252. MAP_ERR_TO_COND(ERROR_NOT_SUPPORTED, not_supported);
  253. MAP_ERR_TO_COND(ERROR_OPEN_FAILED, io_error);
  254. MAP_ERR_TO_COND(ERROR_OPEN_FILES, device_or_resource_busy);
  255. MAP_ERR_TO_COND(ERROR_OUTOFMEMORY, not_enough_memory);
  256. MAP_ERR_TO_COND(ERROR_PATH_NOT_FOUND, no_such_file_or_directory);
  257. MAP_ERR_TO_COND(ERROR_READ_FAULT, io_error);
  258. MAP_ERR_TO_COND(ERROR_REPARSE_TAG_INVALID, invalid_argument);
  259. MAP_ERR_TO_COND(ERROR_RETRY, resource_unavailable_try_again);
  260. MAP_ERR_TO_COND(ERROR_SEEK, io_error);
  261. MAP_ERR_TO_COND(ERROR_SHARING_VIOLATION, permission_denied);
  262. MAP_ERR_TO_COND(ERROR_TOO_MANY_OPEN_FILES, too_many_files_open);
  263. MAP_ERR_TO_COND(ERROR_WRITE_FAULT, io_error);
  264. MAP_ERR_TO_COND(ERROR_WRITE_PROTECT, permission_denied);
  265. MAP_ERR_TO_COND(WSAEACCES, permission_denied);
  266. MAP_ERR_TO_COND(WSAEBADF, bad_file_descriptor);
  267. MAP_ERR_TO_COND(WSAEFAULT, bad_address);
  268. MAP_ERR_TO_COND(WSAEINTR, interrupted);
  269. MAP_ERR_TO_COND(WSAEINVAL, invalid_argument);
  270. MAP_ERR_TO_COND(WSAEMFILE, too_many_files_open);
  271. MAP_ERR_TO_COND(WSAENAMETOOLONG, filename_too_long);
  272. default:
  273. return std::error_code(EV, std::system_category());
  274. }
  275. }
  276. #endif