1 //===- Win32/Signals.cpp - Win32 Signals Implementation ---------*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file provides the Win32 specific implementation of the Signals class.
12 //===----------------------------------------------------------------------===//
14 #include "llvm/Support/FileSystem.h"
19 // The Windows.h header must be after LLVM and standard headers.
20 #include "WindowsSupport.h"
30 #pragma comment(lib, "psapi.lib")
31 #pragma comment(lib, "dbghelp.lib")
33 #if ((HAVE_LIBIMAGEHLP != 1) || (HAVE_LIBPSAPI != 1))
34 #error "libimagehlp.a & libpsapi.a should be present"
36 // The version of g++ that comes with MinGW does *not* properly understand
37 // the ll format specifier for printf. However, MinGW passes the format
38 // specifiers on to the MSVCRT entirely, and the CRT understands the ll
39 // specifier. So these warnings are spurious in this case. Since we compile
40 // with -Wall, this will generate these warnings which should be ignored. So
41 // we will turn off the warnings for this just file. However, MinGW also does
42 // not support push and pop for diagnostics, so we have to manually turn it
43 // back on at the end of the file.
44 #pragma GCC diagnostic ignored "-Wformat"
45 #pragma GCC diagnostic ignored "-Wformat-extra-args"
47 #if !defined(__MINGW64_VERSION_MAJOR)
48 // MinGW.org does not have updated support for the 64-bit versions of the
49 // DebugHlp APIs. So we will have to load them manually. The structures and
50 // method signatures were pulled from DbgHelp.h in the Windows Platform SDK,
51 // and adjusted for brevity.
52 typedef struct _IMAGEHLP_LINE64 {
58 } IMAGEHLP_LINE64, *PIMAGEHLP_LINE64;
60 typedef struct _IMAGEHLP_SYMBOL64 {
67 } IMAGEHLP_SYMBOL64, *PIMAGEHLP_SYMBOL64;
69 typedef struct _tagADDRESS64 {
73 } ADDRESS64, *LPADDRESS64;
75 typedef struct _KDHELP64 {
77 DWORD ThCallbackStack;
78 DWORD ThCallbackBStore;
81 DWORD64 KiCallUserMode;
82 DWORD64 KeUserCallbackDispatcher;
83 DWORD64 SystemRangeStart;
84 DWORD64 KiUserExceptionDispatcher;
88 } KDHELP64, *PKDHELP64;
90 typedef struct _tagSTACKFRAME64 {
102 } STACKFRAME64, *LPSTACKFRAME64;
104 typedef BOOL (__stdcall *PREAD_PROCESS_MEMORY_ROUTINE64)(HANDLE hProcess,
105 DWORD64 qwBaseAddress, PVOID lpBuffer, DWORD nSize,
106 LPDWORD lpNumberOfBytesRead);
108 typedef PVOID (__stdcall *PFUNCTION_TABLE_ACCESS_ROUTINE64)( HANDLE ahProcess,
111 typedef DWORD64 (__stdcall *PGET_MODULE_BASE_ROUTINE64)(HANDLE hProcess,
114 typedef DWORD64 (__stdcall *PTRANSLATE_ADDRESS_ROUTINE64)(HANDLE hProcess,
115 HANDLE hThread, LPADDRESS64 lpaddr);
117 typedef BOOL (WINAPI *fpStackWalk64)(DWORD, HANDLE, HANDLE, LPSTACKFRAME64,
118 PVOID, PREAD_PROCESS_MEMORY_ROUTINE64,
119 PFUNCTION_TABLE_ACCESS_ROUTINE64,
120 PGET_MODULE_BASE_ROUTINE64,
121 PTRANSLATE_ADDRESS_ROUTINE64);
122 static fpStackWalk64 StackWalk64;
124 typedef DWORD64 (WINAPI *fpSymGetModuleBase64)(HANDLE, DWORD64);
125 static fpSymGetModuleBase64 SymGetModuleBase64;
127 typedef BOOL (WINAPI *fpSymGetSymFromAddr64)(HANDLE, DWORD64,
128 PDWORD64, PIMAGEHLP_SYMBOL64);
129 static fpSymGetSymFromAddr64 SymGetSymFromAddr64;
131 typedef BOOL (WINAPI *fpSymGetLineFromAddr64)(HANDLE, DWORD64,
132 PDWORD, PIMAGEHLP_LINE64);
133 static fpSymGetLineFromAddr64 SymGetLineFromAddr64;
135 typedef PVOID (WINAPI *fpSymFunctionTableAccess64)(HANDLE, DWORD64);
136 static fpSymFunctionTableAccess64 SymFunctionTableAccess64;
138 static bool load64BitDebugHelp(void) {
139 HMODULE hLib = ::LoadLibraryW(L"Dbghelp.dll");
141 StackWalk64 = (fpStackWalk64)
142 ::GetProcAddress(hLib, "StackWalk64");
143 SymGetModuleBase64 = (fpSymGetModuleBase64)
144 ::GetProcAddress(hLib, "SymGetModuleBase64");
145 SymGetSymFromAddr64 = (fpSymGetSymFromAddr64)
146 ::GetProcAddress(hLib, "SymGetSymFromAddr64");
147 SymGetLineFromAddr64 = (fpSymGetLineFromAddr64)
148 ::GetProcAddress(hLib, "SymGetLineFromAddr64");
149 SymFunctionTableAccess64 = (fpSymFunctionTableAccess64)
150 ::GetProcAddress(hLib, "SymFunctionTableAccess64");
152 return StackWalk64 != NULL;
154 #endif // !defined(__MINGW64_VERSION_MAJOR)
155 #endif // __MINGW32__
158 static LONG WINAPI LLVMUnhandledExceptionFilter(LPEXCEPTION_POINTERS ep);
159 static BOOL WINAPI LLVMConsoleCtrlHandler(DWORD dwCtrlType);
161 // InterruptFunction - The function to call if ctrl-c is pressed.
162 static void (*InterruptFunction)() = 0;
164 static std::vector<std::string> *FilesToRemove = NULL;
165 static std::vector<std::pair<void(*)(void*), void*> > *CallBacksToRun = 0;
166 static bool RegisteredUnhandledExceptionFilter = false;
167 static bool CleanupExecuted = false;
168 static bool ExitOnUnhandledExceptions = false;
169 static PTOP_LEVEL_EXCEPTION_FILTER OldFilter = NULL;
171 // Windows creates a new thread to execute the console handler when an event
172 // (such as CTRL/C) occurs. This causes concurrency issues with the above
173 // globals which this critical section addresses.
174 static CRITICAL_SECTION CriticalSection;
178 //===----------------------------------------------------------------------===//
179 //=== WARNING: Implementation here must contain only Win32 specific code
180 //=== and must not be UNIX code
181 //===----------------------------------------------------------------------===//
184 /// AvoidMessageBoxHook - Emulates hitting "retry" from an "abort, retry,
185 /// ignore" CRT debug report dialog. "retry" raises an exception which
186 /// ultimately triggers our stack dumper.
187 static int AvoidMessageBoxHook(int ReportType, char *Message, int *Return) {
188 // Set *Return to the retry code for the return value of _CrtDbgReport:
189 // http://msdn.microsoft.com/en-us/library/8hyw4sy7(v=vs.71).aspx
190 // This may also trigger just-in-time debugging via DebugBreak().
193 // Don't call _CrtDbgReport.
199 static void RegisterHandler() {
200 #if __MINGW32__ && !defined(__MINGW64_VERSION_MAJOR)
201 // On MinGW.org, we need to load up the symbols explicitly, because the
202 // Win32 framework they include does not have support for the 64-bit
203 // versions of the APIs we need. If we cannot load up the APIs (which
204 // would be unexpected as they should exist on every version of Windows
205 // we support), we will bail out since there would be nothing to report.
206 if (!load64BitDebugHelp()) {
207 assert(false && "These APIs should always be available");
212 if (RegisteredUnhandledExceptionFilter) {
213 EnterCriticalSection(&CriticalSection);
217 // Now's the time to create the critical section. This is the first time
218 // through here, and there's only one thread.
219 InitializeCriticalSection(&CriticalSection);
221 // Enter it immediately. Now if someone hits CTRL/C, the console handler
222 // can't proceed until the globals are updated.
223 EnterCriticalSection(&CriticalSection);
225 RegisteredUnhandledExceptionFilter = true;
226 OldFilter = SetUnhandledExceptionFilter(LLVMUnhandledExceptionFilter);
227 SetConsoleCtrlHandler(LLVMConsoleCtrlHandler, TRUE);
229 // Environment variable to disable any kind of crash dialog.
230 if (getenv("LLVM_DISABLE_CRASH_REPORT")) {
232 _CrtSetReportHook(AvoidMessageBoxHook);
234 SetErrorMode(SEM_FAILCRITICALERRORS |
235 SEM_NOGPFAULTERRORBOX |
236 SEM_NOOPENFILEERRORBOX);
237 ExitOnUnhandledExceptions = true;
240 // IMPORTANT NOTE: Caller must call LeaveCriticalSection(&CriticalSection) or
241 // else multi-threading problems will ensue.
244 // RemoveFileOnSignal - The public API
245 bool sys::RemoveFileOnSignal(StringRef Filename, std::string* ErrMsg) {
248 if (CleanupExecuted) {
250 *ErrMsg = "Process terminating -- cannot register for removal";
254 if (FilesToRemove == NULL)
255 FilesToRemove = new std::vector<std::string>;
257 FilesToRemove->push_back(Filename);
259 LeaveCriticalSection(&CriticalSection);
263 // DontRemoveFileOnSignal - The public API
264 void sys::DontRemoveFileOnSignal(StringRef Filename) {
265 if (FilesToRemove == NULL)
270 FilesToRemove->push_back(Filename);
271 std::vector<std::string>::reverse_iterator I =
272 std::find(FilesToRemove->rbegin(), FilesToRemove->rend(), Filename);
273 if (I != FilesToRemove->rend())
274 FilesToRemove->erase(I.base()-1);
276 LeaveCriticalSection(&CriticalSection);
279 /// PrintStackTraceOnErrorSignal - When an error signal (such as SIBABRT or
280 /// SIGSEGV) is delivered to the process, print a stack trace and then exit.
281 void sys::PrintStackTraceOnErrorSignal() {
282 // Don't pop up any dialog boxes.
283 // We're already handling writing a "something went wrong" message.
284 _set_abort_behavior(0, _WRITE_ABORT_MSG);
285 // Disable Dr. Watson.
286 _set_abort_behavior(0, _CALL_REPORTFAULT);
287 // Disable standard error dialog box.
288 SetErrorMode(SEM_FAILCRITICALERRORS | SEM_NOGPFAULTERRORBOX);
291 LeaveCriticalSection(&CriticalSection);
294 void llvm::sys::PrintStackTrace(FILE *) {
299 void sys::SetInterruptFunction(void (*IF)()) {
301 InterruptFunction = IF;
302 LeaveCriticalSection(&CriticalSection);
306 /// AddSignalHandler - Add a function to be called when a signal is delivered
307 /// to the process. The handler can have a cookie passed to it to identify
308 /// what instance of the handler it is.
309 void sys::AddSignalHandler(void (*FnPtr)(void *), void *Cookie) {
310 if (CallBacksToRun == 0)
311 CallBacksToRun = new std::vector<std::pair<void(*)(void*), void*> >();
312 CallBacksToRun->push_back(std::make_pair(FnPtr, Cookie));
314 LeaveCriticalSection(&CriticalSection);
318 static void Cleanup() {
319 EnterCriticalSection(&CriticalSection);
321 // Prevent other thread from registering new files and directories for
322 // removal, should we be executing because of the console handler callback.
323 CleanupExecuted = true;
325 // FIXME: open files cannot be deleted.
327 if (FilesToRemove != NULL)
328 while (!FilesToRemove->empty()) {
329 llvm::sys::fs::remove(FilesToRemove->back());
330 FilesToRemove->pop_back();
334 for (unsigned i = 0, e = CallBacksToRun->size(); i != e; ++i)
335 (*CallBacksToRun)[i].first((*CallBacksToRun)[i].second);
337 LeaveCriticalSection(&CriticalSection);
340 void llvm::sys::RunInterruptHandlers() {
344 static LONG WINAPI LLVMUnhandledExceptionFilter(LPEXCEPTION_POINTERS ep) {
347 // Initialize the STACKFRAME structure.
348 STACKFRAME64 StackFrame;
349 memset(&StackFrame, 0, sizeof(StackFrame));
353 machineType = IMAGE_FILE_MACHINE_AMD64;
354 StackFrame.AddrPC.Offset = ep->ContextRecord->Rip;
355 StackFrame.AddrPC.Mode = AddrModeFlat;
356 StackFrame.AddrStack.Offset = ep->ContextRecord->Rsp;
357 StackFrame.AddrStack.Mode = AddrModeFlat;
358 StackFrame.AddrFrame.Offset = ep->ContextRecord->Rbp;
359 StackFrame.AddrFrame.Mode = AddrModeFlat;
360 #elif defined(_M_IX86)
361 machineType = IMAGE_FILE_MACHINE_I386;
362 StackFrame.AddrPC.Offset = ep->ContextRecord->Eip;
363 StackFrame.AddrPC.Mode = AddrModeFlat;
364 StackFrame.AddrStack.Offset = ep->ContextRecord->Esp;
365 StackFrame.AddrStack.Mode = AddrModeFlat;
366 StackFrame.AddrFrame.Offset = ep->ContextRecord->Ebp;
367 StackFrame.AddrFrame.Mode = AddrModeFlat;
370 HANDLE hProcess = GetCurrentProcess();
371 HANDLE hThread = GetCurrentThread();
373 // Initialize the symbol handler.
374 SymSetOptions(SYMOPT_DEFERRED_LOADS|SYMOPT_LOAD_LINES);
375 SymInitialize(hProcess, NULL, TRUE);
378 if (!StackWalk64(machineType, hProcess, hThread, &StackFrame,
379 ep->ContextRecord, NULL, SymFunctionTableAccess64,
380 SymGetModuleBase64, NULL)) {
384 if (StackFrame.AddrFrame.Offset == 0)
387 // Print the PC in hexadecimal.
388 DWORD64 PC = StackFrame.AddrPC.Offset;
390 fprintf(stderr, "0x%016llX", PC);
391 #elif defined(_M_IX86)
392 fprintf(stderr, "0x%08lX", static_cast<DWORD>(PC));
395 // Print the parameters. Assume there are four.
397 fprintf(stderr, " (0x%016llX 0x%016llX 0x%016llX 0x%016llX)",
398 StackFrame.Params[0],
399 StackFrame.Params[1],
400 StackFrame.Params[2],
401 StackFrame.Params[3]);
402 #elif defined(_M_IX86)
403 fprintf(stderr, " (0x%08lX 0x%08lX 0x%08lX 0x%08lX)",
404 static_cast<DWORD>(StackFrame.Params[0]),
405 static_cast<DWORD>(StackFrame.Params[1]),
406 static_cast<DWORD>(StackFrame.Params[2]),
407 static_cast<DWORD>(StackFrame.Params[3]));
409 // Verify the PC belongs to a module in this process.
410 if (!SymGetModuleBase64(hProcess, PC)) {
411 fputs(" <unknown module>\n", stderr);
415 // Print the symbol name.
417 IMAGEHLP_SYMBOL64 *symbol = reinterpret_cast<IMAGEHLP_SYMBOL64 *>(buffer);
418 memset(symbol, 0, sizeof(IMAGEHLP_SYMBOL64));
419 symbol->SizeOfStruct = sizeof(IMAGEHLP_SYMBOL64);
420 symbol->MaxNameLength = 512 - sizeof(IMAGEHLP_SYMBOL64);
423 if (!SymGetSymFromAddr64(hProcess, PC, &dwDisp, symbol)) {
430 fprintf(stderr, ", %s() + 0x%llX bytes(s)", symbol->Name, dwDisp);
432 fprintf(stderr, ", %s", symbol->Name);
434 // Print the source file and line number information.
435 IMAGEHLP_LINE64 line;
437 memset(&line, 0, sizeof(line));
438 line.SizeOfStruct = sizeof(line);
439 if (SymGetLineFromAddr64(hProcess, PC, &dwLineDisp, &line)) {
440 fprintf(stderr, ", %s, line %lu", line.FileName, line.LineNumber);
442 fprintf(stderr, " + 0x%lX byte(s)", dwLineDisp);
448 if (ExitOnUnhandledExceptions)
449 _exit(ep->ExceptionRecord->ExceptionCode);
451 // Allow dialog box to pop up allowing choice to start debugger.
453 return (*OldFilter)(ep);
455 return EXCEPTION_CONTINUE_SEARCH;
458 static BOOL WINAPI LLVMConsoleCtrlHandler(DWORD dwCtrlType) {
459 // We are running in our very own thread, courtesy of Windows.
460 EnterCriticalSection(&CriticalSection);
463 // If an interrupt function has been set, go and run one it; otherwise,
465 void (*IF)() = InterruptFunction;
466 InterruptFunction = 0; // Don't run it on another CTRL-C.
469 // Note: if the interrupt function throws an exception, there is nothing
470 // to catch it in this thread so it will kill the process.
472 LeaveCriticalSection(&CriticalSection);
473 return TRUE; // Don't kill the process.
476 // Allow normal processing to take place; i.e., the process dies.
477 LeaveCriticalSection(&CriticalSection);
482 // We turned these warnings off for this file so that MinGW-g++ doesn't
483 // complain about the ll format specifiers used. Now we are turning the
484 // warnings back on. If MinGW starts to support diagnostic stacks, we can
485 // replace this with a pop.
486 #pragma GCC diagnostic warning "-Wformat"
487 #pragma GCC diagnostic warning "-Wformat-extra-args"