1 //===- lib/Support/ErrorHandling.cpp - Callbacks for errors ---------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file defines an API used to indicate fatal error conditions.  Non-fatal
11 // errors (most of them) should be handled through LLVMContext.
12 //
13 //===----------------------------------------------------------------------===//
14 
15 #include "llvm/Support/ErrorHandling.h"
16 #include "llvm-c/ErrorHandling.h"
17 #include "llvm/ADT/SmallVector.h"
18 #include "llvm/ADT/Twine.h"
19 #include "llvm/Config/config.h"
20 #include "llvm/Support/Debug.h"
21 #include "llvm/Support/Errc.h"
22 #include "llvm/Support/Error.h"
23 #include "llvm/Support/Signals.h"
24 #include "llvm/Support/Threading.h"
25 #include "llvm/Support/WindowsError.h"
26 #include "llvm/Support/raw_ostream.h"
27 #include <cassert>
28 #include <cstdlib>
29 #include <mutex>
30 #include <new>
31 
32 #if defined(HAVE_UNISTD_H)
33 # include <unistd.h>
34 #endif
35 #if defined(_MSC_VER)
36 # include <io.h>
37 # include <fcntl.h>
38 #endif
39 
40 using namespace llvm;
41 
42 static fatal_error_handler_t ErrorHandler = nullptr;
43 static void *ErrorHandlerUserData = nullptr;
44 
45 static fatal_error_handler_t BadAllocErrorHandler = nullptr;
46 static void *BadAllocErrorHandlerUserData = nullptr;
47 
48 // Mutexes to synchronize installing error handlers and calling error handlers.
49 // Do not use ManagedStatic, or that may allocate memory while attempting to
50 // report an OOM.
51 static std::mutex ErrorHandlerMutex;
52 static std::mutex BadAllocErrorHandlerMutex;
53 
54 void llvm::install_fatal_error_handler(fatal_error_handler_t handler,
55                                        void *user_data) {
56   std::lock_guard<std::mutex> Lock(ErrorHandlerMutex);
57   assert(!ErrorHandler && "Error handler already registered!\n");
58   ErrorHandler = handler;
59   ErrorHandlerUserData = user_data;
60 }
61 
62 void llvm::remove_fatal_error_handler() {
63   std::lock_guard<std::mutex> Lock(ErrorHandlerMutex);
64   ErrorHandler = nullptr;
65   ErrorHandlerUserData = nullptr;
66 }
67 
68 void llvm::report_fatal_error(const char *Reason, bool GenCrashDiag) {
69   report_fatal_error(Twine(Reason), GenCrashDiag);
70 }
71 
72 void llvm::report_fatal_error(const std::string &Reason, bool GenCrashDiag) {
73   report_fatal_error(Twine(Reason), GenCrashDiag);
74 }
75 
76 void llvm::report_fatal_error(StringRef Reason, bool GenCrashDiag) {
77   report_fatal_error(Twine(Reason), GenCrashDiag);
78 }
79 
80 void llvm::report_fatal_error(const Twine &Reason, bool GenCrashDiag) {
81   llvm::fatal_error_handler_t handler = nullptr;
82   void* handlerData = nullptr;
83   {
84     // Only acquire the mutex while reading the handler, so as not to invoke a
85     // user-supplied callback under a lock.
86     std::lock_guard<std::mutex> Lock(ErrorHandlerMutex);
87     handler = ErrorHandler;
88     handlerData = ErrorHandlerUserData;
89   }
90 
91   if (handler) {
92     handler(handlerData, Reason.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 
105   // If we reached here, we are failing ungracefully. Run the interrupt handlers
106   // to make sure any special cleanups get done, in particular that we remove
107   // files registered with RemoveFileOnSignal.
108   sys::RunInterruptHandlers();
109 
110   exit(1);
111 }
112 
113 void llvm::install_bad_alloc_error_handler(fatal_error_handler_t handler,
114                                            void *user_data) {
115   std::lock_guard<std::mutex> Lock(BadAllocErrorHandlerMutex);
116   assert(!ErrorHandler && "Bad alloc error handler already registered!\n");
117   BadAllocErrorHandler = handler;
118   BadAllocErrorHandlerUserData = user_data;
119 }
120 
121 void llvm::remove_bad_alloc_error_handler() {
122   std::lock_guard<std::mutex> Lock(BadAllocErrorHandlerMutex);
123   BadAllocErrorHandler = nullptr;
124   BadAllocErrorHandlerUserData = nullptr;
125 }
126 
127 void llvm::report_bad_alloc_error(const char *Reason, bool GenCrashDiag) {
128   fatal_error_handler_t Handler = nullptr;
129   void *HandlerData = nullptr;
130   {
131     // Only acquire the mutex while reading the handler, so as not to invoke a
132     // user-supplied callback under a lock.
133     std::lock_guard<std::mutex> Lock(BadAllocErrorHandlerMutex);
134     Handler = BadAllocErrorHandler;
135     HandlerData = BadAllocErrorHandlerUserData;
136   }
137 
138   if (Handler) {
139     Handler(HandlerData, Reason, GenCrashDiag);
140     llvm_unreachable("bad alloc handler should not return");
141   }
142 
143 #ifdef LLVM_ENABLE_EXCEPTIONS
144   // If exceptions are enabled, make OOM in malloc look like OOM in new.
145   throw std::bad_alloc();
146 #else
147   // Don't call the normal error handler. It may allocate memory. Directly write
148   // an OOM to stderr and abort.
149   char OOMMessage[] = "LLVM ERROR: out of memory\n";
150   (void)::write(2, OOMMessage, strlen(OOMMessage));
151   abort();
152 #endif
153 }
154 
155 void llvm::llvm_unreachable_internal(const char *msg, const char *file,
156                                      unsigned line) {
157   // This code intentionally doesn't call the ErrorHandler callback, because
158   // llvm_unreachable is intended to be used to indicate "impossible"
159   // situations, and not legitimate runtime errors.
160   if (msg)
161     dbgs() << msg << "\n";
162   dbgs() << "UNREACHABLE executed";
163   if (file)
164     dbgs() << " at " << file << ":" << line;
165   dbgs() << "!\n";
166   abort();
167 #ifdef LLVM_BUILTIN_UNREACHABLE
168   // Windows systems and possibly others don't declare abort() to be noreturn,
169   // so use the unreachable builtin to avoid a Clang self-host warning.
170   LLVM_BUILTIN_UNREACHABLE;
171 #endif
172 }
173 
174 static void bindingsErrorHandler(void *user_data, const std::string& reason,
175                                  bool gen_crash_diag) {
176   LLVMFatalErrorHandler handler =
177       LLVM_EXTENSION reinterpret_cast<LLVMFatalErrorHandler>(user_data);
178   handler(reason.c_str());
179 }
180 
181 void LLVMInstallFatalErrorHandler(LLVMFatalErrorHandler Handler) {
182   install_fatal_error_handler(bindingsErrorHandler,
183                               LLVM_EXTENSION reinterpret_cast<void *>(Handler));
184 }
185 
186 void LLVMResetFatalErrorHandler() {
187   remove_fatal_error_handler();
188 }
189 
190 #ifdef LLVM_ON_WIN32
191 
192 #include <winerror.h>
193 
194 // I'd rather not double the line count of the following.
195 #define MAP_ERR_TO_COND(x, y)                                                  \
196   case x:                                                                      \
197     return make_error_code(errc::y)
198 
199 std::error_code llvm::mapWindowsError(unsigned EV) {
200   switch (EV) {
201     MAP_ERR_TO_COND(ERROR_ACCESS_DENIED, permission_denied);
202     MAP_ERR_TO_COND(ERROR_ALREADY_EXISTS, file_exists);
203     MAP_ERR_TO_COND(ERROR_BAD_UNIT, no_such_device);
204     MAP_ERR_TO_COND(ERROR_BUFFER_OVERFLOW, filename_too_long);
205     MAP_ERR_TO_COND(ERROR_BUSY, device_or_resource_busy);
206     MAP_ERR_TO_COND(ERROR_BUSY_DRIVE, device_or_resource_busy);
207     MAP_ERR_TO_COND(ERROR_CANNOT_MAKE, permission_denied);
208     MAP_ERR_TO_COND(ERROR_CANTOPEN, io_error);
209     MAP_ERR_TO_COND(ERROR_CANTREAD, io_error);
210     MAP_ERR_TO_COND(ERROR_CANTWRITE, io_error);
211     MAP_ERR_TO_COND(ERROR_CURRENT_DIRECTORY, permission_denied);
212     MAP_ERR_TO_COND(ERROR_DEV_NOT_EXIST, no_such_device);
213     MAP_ERR_TO_COND(ERROR_DEVICE_IN_USE, device_or_resource_busy);
214     MAP_ERR_TO_COND(ERROR_DIR_NOT_EMPTY, directory_not_empty);
215     MAP_ERR_TO_COND(ERROR_DIRECTORY, invalid_argument);
216     MAP_ERR_TO_COND(ERROR_DISK_FULL, no_space_on_device);
217     MAP_ERR_TO_COND(ERROR_FILE_EXISTS, file_exists);
218     MAP_ERR_TO_COND(ERROR_FILE_NOT_FOUND, no_such_file_or_directory);
219     MAP_ERR_TO_COND(ERROR_HANDLE_DISK_FULL, no_space_on_device);
220     MAP_ERR_TO_COND(ERROR_INVALID_ACCESS, permission_denied);
221     MAP_ERR_TO_COND(ERROR_INVALID_DRIVE, no_such_device);
222     MAP_ERR_TO_COND(ERROR_INVALID_FUNCTION, function_not_supported);
223     MAP_ERR_TO_COND(ERROR_INVALID_HANDLE, invalid_argument);
224     MAP_ERR_TO_COND(ERROR_INVALID_NAME, invalid_argument);
225     MAP_ERR_TO_COND(ERROR_LOCK_VIOLATION, no_lock_available);
226     MAP_ERR_TO_COND(ERROR_LOCKED, no_lock_available);
227     MAP_ERR_TO_COND(ERROR_NEGATIVE_SEEK, invalid_argument);
228     MAP_ERR_TO_COND(ERROR_NOACCESS, permission_denied);
229     MAP_ERR_TO_COND(ERROR_NOT_ENOUGH_MEMORY, not_enough_memory);
230     MAP_ERR_TO_COND(ERROR_NOT_READY, resource_unavailable_try_again);
231     MAP_ERR_TO_COND(ERROR_OPEN_FAILED, io_error);
232     MAP_ERR_TO_COND(ERROR_OPEN_FILES, device_or_resource_busy);
233     MAP_ERR_TO_COND(ERROR_OUTOFMEMORY, not_enough_memory);
234     MAP_ERR_TO_COND(ERROR_PATH_NOT_FOUND, no_such_file_or_directory);
235     MAP_ERR_TO_COND(ERROR_BAD_NETPATH, no_such_file_or_directory);
236     MAP_ERR_TO_COND(ERROR_READ_FAULT, io_error);
237     MAP_ERR_TO_COND(ERROR_RETRY, resource_unavailable_try_again);
238     MAP_ERR_TO_COND(ERROR_SEEK, io_error);
239     MAP_ERR_TO_COND(ERROR_SHARING_VIOLATION, permission_denied);
240     MAP_ERR_TO_COND(ERROR_TOO_MANY_OPEN_FILES, too_many_files_open);
241     MAP_ERR_TO_COND(ERROR_WRITE_FAULT, io_error);
242     MAP_ERR_TO_COND(ERROR_WRITE_PROTECT, permission_denied);
243     MAP_ERR_TO_COND(WSAEACCES, permission_denied);
244     MAP_ERR_TO_COND(WSAEBADF, bad_file_descriptor);
245     MAP_ERR_TO_COND(WSAEFAULT, bad_address);
246     MAP_ERR_TO_COND(WSAEINTR, interrupted);
247     MAP_ERR_TO_COND(WSAEINVAL, invalid_argument);
248     MAP_ERR_TO_COND(WSAEMFILE, too_many_files_open);
249     MAP_ERR_TO_COND(WSAENAMETOOLONG, filename_too_long);
250   default:
251     return std::error_code(EV, std::system_category());
252   }
253 }
254 
255 #endif
256