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 //===----------------------------------------------------------------------===//
13 #include "llvm/Support/FileSystem.h"
19 #include "llvm/Support/Format.h"
20 #include "llvm/Support/raw_ostream.h"
22 // The Windows.h header must be after LLVM and standard headers.
23 #include "WindowsSupport.h"
33 #pragma comment(lib, "psapi.lib")
34 #pragma comment(lib, "dbghelp.lib")
36 #if ((HAVE_LIBIMAGEHLP != 1) || (HAVE_LIBPSAPI != 1))
37 #error "libimagehlp.a & libpsapi.a should be present"
39 // The version of g++ that comes with MinGW does *not* properly understand
40 // the ll format specifier for printf. However, MinGW passes the format
41 // specifiers on to the MSVCRT entirely, and the CRT understands the ll
42 // specifier. So these warnings are spurious in this case. Since we compile
43 // with -Wall, this will generate these warnings which should be ignored. So
44 // we will turn off the warnings for this just file. However, MinGW also does
45 // not support push and pop for diagnostics, so we have to manually turn it
46 // back on at the end of the file.
47 #pragma GCC diagnostic ignored "-Wformat"
48 #pragma GCC diagnostic ignored "-Wformat-extra-args"
50 #if !defined(__MINGW64_VERSION_MAJOR)
51 // MinGW.org does not have updated support for the 64-bit versions of the
52 // DebugHlp APIs. So we will have to load them manually. The structures and
53 // method signatures were pulled from DbgHelp.h in the Windows Platform SDK,
54 // and adjusted for brevity.
55 typedef struct _IMAGEHLP_LINE64 {
61 } IMAGEHLP_LINE64, *PIMAGEHLP_LINE64;
63 typedef struct _IMAGEHLP_SYMBOL64 {
70 } IMAGEHLP_SYMBOL64, *PIMAGEHLP_SYMBOL64;
72 typedef struct _tagADDRESS64 {
76 } ADDRESS64, *LPADDRESS64;
78 typedef struct _KDHELP64 {
80 DWORD ThCallbackStack;
81 DWORD ThCallbackBStore;
84 DWORD64 KiCallUserMode;
85 DWORD64 KeUserCallbackDispatcher;
86 DWORD64 SystemRangeStart;
87 DWORD64 KiUserExceptionDispatcher;
91 } KDHELP64, *PKDHELP64;
93 typedef struct _tagSTACKFRAME64 {
105 } STACKFRAME64, *LPSTACKFRAME64;
107 typedef BOOL (__stdcall *PREAD_PROCESS_MEMORY_ROUTINE64)(HANDLE hProcess,
108 DWORD64 qwBaseAddress, PVOID lpBuffer, DWORD nSize,
109 LPDWORD lpNumberOfBytesRead);
111 typedef PVOID (__stdcall *PFUNCTION_TABLE_ACCESS_ROUTINE64)( HANDLE ahProcess,
114 typedef DWORD64 (__stdcall *PGET_MODULE_BASE_ROUTINE64)(HANDLE hProcess,
117 typedef DWORD64 (__stdcall *PTRANSLATE_ADDRESS_ROUTINE64)(HANDLE hProcess,
118 HANDLE hThread, LPADDRESS64 lpaddr);
120 typedef BOOL (WINAPI *fpStackWalk64)(DWORD, HANDLE, HANDLE, LPSTACKFRAME64,
121 PVOID, PREAD_PROCESS_MEMORY_ROUTINE64,
122 PFUNCTION_TABLE_ACCESS_ROUTINE64,
123 PGET_MODULE_BASE_ROUTINE64,
124 PTRANSLATE_ADDRESS_ROUTINE64);
125 static fpStackWalk64 StackWalk64;
127 typedef DWORD64 (WINAPI *fpSymGetModuleBase64)(HANDLE, DWORD64);
128 static fpSymGetModuleBase64 SymGetModuleBase64;
130 typedef BOOL (WINAPI *fpSymGetSymFromAddr64)(HANDLE, DWORD64,
131 PDWORD64, PIMAGEHLP_SYMBOL64);
132 static fpSymGetSymFromAddr64 SymGetSymFromAddr64;
134 typedef BOOL (WINAPI *fpSymGetLineFromAddr64)(HANDLE, DWORD64,
135 PDWORD, PIMAGEHLP_LINE64);
136 static fpSymGetLineFromAddr64 SymGetLineFromAddr64;
138 typedef PVOID (WINAPI *fpSymFunctionTableAccess64)(HANDLE, DWORD64);
139 static fpSymFunctionTableAccess64 SymFunctionTableAccess64;
141 static bool load64BitDebugHelp(void) {
142 HMODULE hLib = ::LoadLibraryW(L"Dbghelp.dll");
144 StackWalk64 = (fpStackWalk64)
145 ::GetProcAddress(hLib, "StackWalk64");
146 SymGetModuleBase64 = (fpSymGetModuleBase64)
147 ::GetProcAddress(hLib, "SymGetModuleBase64");
148 SymGetSymFromAddr64 = (fpSymGetSymFromAddr64)
149 ::GetProcAddress(hLib, "SymGetSymFromAddr64");
150 SymGetLineFromAddr64 = (fpSymGetLineFromAddr64)
151 ::GetProcAddress(hLib, "SymGetLineFromAddr64");
152 SymFunctionTableAccess64 = (fpSymFunctionTableAccess64)
153 ::GetProcAddress(hLib, "SymFunctionTableAccess64");
155 return StackWalk64 != NULL;
157 #endif // !defined(__MINGW64_VERSION_MAJOR)
158 #endif // __MINGW32__
161 static LONG WINAPI LLVMUnhandledExceptionFilter(LPEXCEPTION_POINTERS ep);
162 static BOOL WINAPI LLVMConsoleCtrlHandler(DWORD dwCtrlType);
164 // InterruptFunction - The function to call if ctrl-c is pressed.
165 static void (*InterruptFunction)() = 0;
167 static std::vector<std::string> *FilesToRemove = NULL;
168 static std::vector<std::pair<void(*)(void*), void*> > *CallBacksToRun = 0;
169 static bool RegisteredUnhandledExceptionFilter = false;
170 static bool CleanupExecuted = false;
171 static PTOP_LEVEL_EXCEPTION_FILTER OldFilter = NULL;
173 // Windows creates a new thread to execute the console handler when an event
174 // (such as CTRL/C) occurs. This causes concurrency issues with the above
175 // globals which this critical section addresses.
176 static CRITICAL_SECTION CriticalSection;
177 static bool CriticalSectionInitialized = false;
179 static void PrintStackTraceForThread(llvm::raw_ostream &OS, HANDLE hProcess,
180 HANDLE hThread, STACKFRAME64 &StackFrame,
184 machineType = IMAGE_FILE_MACHINE_AMD64;
186 machineType = IMAGE_FILE_MACHINE_I386;
189 // Initialize the symbol handler.
190 SymSetOptions(SYMOPT_DEFERRED_LOADS | SYMOPT_LOAD_LINES);
191 SymInitialize(hProcess, NULL, TRUE);
194 if (!StackWalk64(machineType, hProcess, hThread, &StackFrame, Context, NULL,
195 SymFunctionTableAccess64, SymGetModuleBase64, NULL)) {
199 if (StackFrame.AddrFrame.Offset == 0)
202 using namespace llvm;
203 // Print the PC in hexadecimal.
204 DWORD64 PC = StackFrame.AddrPC.Offset;
206 OS << format("0x%016llX", PC);
207 #elif defined(_M_IX86)
208 OS << format("0x%08lX", static_cast<DWORD>(PC));
211 // Print the parameters. Assume there are four.
213 OS << format(" (0x%016llX 0x%016llX 0x%016llX 0x%016llX)",
214 StackFrame.Params[0], StackFrame.Params[1], StackFrame.Params[2],
215 StackFrame.Params[3]);
216 #elif defined(_M_IX86)
217 OS << format(" (0x%08lX 0x%08lX 0x%08lX 0x%08lX)",
218 static_cast<DWORD>(StackFrame.Params[0]),
219 static_cast<DWORD>(StackFrame.Params[1]),
220 static_cast<DWORD>(StackFrame.Params[2]),
221 static_cast<DWORD>(StackFrame.Params[3]));
223 // Verify the PC belongs to a module in this process.
224 if (!SymGetModuleBase64(hProcess, PC)) {
225 OS << " <unknown module>\n";
229 // Print the symbol name.
231 IMAGEHLP_SYMBOL64 *symbol = reinterpret_cast<IMAGEHLP_SYMBOL64 *>(buffer);
232 memset(symbol, 0, sizeof(IMAGEHLP_SYMBOL64));
233 symbol->SizeOfStruct = sizeof(IMAGEHLP_SYMBOL64);
234 symbol->MaxNameLength = 512 - sizeof(IMAGEHLP_SYMBOL64);
237 if (!SymGetSymFromAddr64(hProcess, PC, &dwDisp, symbol)) {
244 OS << format(", %s() + 0x%llX bytes(s)", (const char*)symbol->Name,
247 OS << format(", %s", (const char*)symbol->Name);
249 // Print the source file and line number information.
250 IMAGEHLP_LINE64 line = {};
252 line.SizeOfStruct = sizeof(line);
253 if (SymGetLineFromAddr64(hProcess, PC, &dwLineDisp, &line)) {
254 OS << format(", %s, line %lu", line.FileName, line.LineNumber);
256 OS << format(" + 0x%lX byte(s)", dwLineDisp);
265 //===----------------------------------------------------------------------===//
266 //=== WARNING: Implementation here must contain only Win32 specific code
267 //=== and must not be UNIX code
268 //===----------------------------------------------------------------------===//
271 /// AvoidMessageBoxHook - Emulates hitting "retry" from an "abort, retry,
272 /// ignore" CRT debug report dialog. "retry" raises an exception which
273 /// ultimately triggers our stack dumper.
274 static LLVM_ATTRIBUTE_UNUSED int
275 AvoidMessageBoxHook(int ReportType, char *Message, int *Return) {
276 // Set *Return to the retry code for the return value of _CrtDbgReport:
277 // http://msdn.microsoft.com/en-us/library/8hyw4sy7(v=vs.71).aspx
278 // This may also trigger just-in-time debugging via DebugBreak().
281 // Don't call _CrtDbgReport.
287 extern "C" void HandleAbort(int Sig) {
288 if (Sig == SIGABRT) {
293 static void InitializeThreading() {
294 if (CriticalSectionInitialized)
297 // Now's the time to create the critical section. This is the first time
298 // through here, and there's only one thread.
299 InitializeCriticalSection(&CriticalSection);
300 CriticalSectionInitialized = true;
303 static void RegisterHandler() {
304 #if __MINGW32__ && !defined(__MINGW64_VERSION_MAJOR)
305 // On MinGW.org, we need to load up the symbols explicitly, because the
306 // Win32 framework they include does not have support for the 64-bit
307 // versions of the APIs we need. If we cannot load up the APIs (which
308 // would be unexpected as they should exist on every version of Windows
309 // we support), we will bail out since there would be nothing to report.
310 if (!load64BitDebugHelp()) {
311 assert(false && "These APIs should always be available");
316 if (RegisteredUnhandledExceptionFilter) {
317 EnterCriticalSection(&CriticalSection);
321 InitializeThreading();
323 // Enter it immediately. Now if someone hits CTRL/C, the console handler
324 // can't proceed until the globals are updated.
325 EnterCriticalSection(&CriticalSection);
327 RegisteredUnhandledExceptionFilter = true;
328 OldFilter = SetUnhandledExceptionFilter(LLVMUnhandledExceptionFilter);
329 SetConsoleCtrlHandler(LLVMConsoleCtrlHandler, TRUE);
331 // IMPORTANT NOTE: Caller must call LeaveCriticalSection(&CriticalSection) or
332 // else multi-threading problems will ensue.
335 // RemoveFileOnSignal - The public API
336 bool sys::RemoveFileOnSignal(StringRef Filename, std::string* ErrMsg) {
339 if (CleanupExecuted) {
341 *ErrMsg = "Process terminating -- cannot register for removal";
345 if (FilesToRemove == NULL)
346 FilesToRemove = new std::vector<std::string>;
348 FilesToRemove->push_back(Filename);
350 LeaveCriticalSection(&CriticalSection);
354 // DontRemoveFileOnSignal - The public API
355 void sys::DontRemoveFileOnSignal(StringRef Filename) {
356 if (FilesToRemove == NULL)
361 std::vector<std::string>::reverse_iterator I =
362 std::find(FilesToRemove->rbegin(), FilesToRemove->rend(), Filename);
363 if (I != FilesToRemove->rend())
364 FilesToRemove->erase(I.base()-1);
366 LeaveCriticalSection(&CriticalSection);
369 void sys::DisableSystemDialogsOnCrash() {
370 // Crash to stack trace handler on abort.
371 signal(SIGABRT, HandleAbort);
373 // The following functions are not reliably accessible on MinGW.
375 // We're already handling writing a "something went wrong" message.
376 _set_abort_behavior(0, _WRITE_ABORT_MSG);
377 // Disable Dr. Watson.
378 _set_abort_behavior(0, _CALL_REPORTFAULT);
379 _CrtSetReportHook(AvoidMessageBoxHook);
382 // Disable standard error dialog box.
383 SetErrorMode(SEM_FAILCRITICALERRORS | SEM_NOGPFAULTERRORBOX |
384 SEM_NOOPENFILEERRORBOX);
385 _set_error_mode(_OUT_TO_STDERR);
388 /// PrintStackTraceOnErrorSignal - When an error signal (such as SIBABRT or
389 /// SIGSEGV) is delivered to the process, print a stack trace and then exit.
390 void sys::PrintStackTraceOnErrorSignal(bool DisableCrashReporting) {
391 DisableSystemDialogsOnCrash();
393 LeaveCriticalSection(&CriticalSection);
397 #if defined(__MINGW32__) && !defined(__MINGW64_VERSION_MAJOR)
398 // Provide a prototype for RtlCaptureContext, mingw32 from mingw.org is
399 // missing it but mingw-w64 has it.
400 extern "C" VOID WINAPI RtlCaptureContext(PCONTEXT ContextRecord);
403 void llvm::sys::PrintStackTrace(raw_ostream &OS) {
405 STACKFRAME64 StackFrame = {};
406 CONTEXT Context = {};
407 ::RtlCaptureContext(&Context);
409 StackFrame.AddrPC.Offset = Context.Rip;
410 StackFrame.AddrStack.Offset = Context.Rsp;
411 StackFrame.AddrFrame.Offset = Context.Rbp;
413 StackFrame.AddrPC.Offset = Context.Eip;
414 StackFrame.AddrStack.Offset = Context.Esp;
415 StackFrame.AddrFrame.Offset = Context.Ebp;
417 StackFrame.AddrPC.Mode = AddrModeFlat;
418 StackFrame.AddrStack.Mode = AddrModeFlat;
419 StackFrame.AddrFrame.Mode = AddrModeFlat;
420 PrintStackTraceForThread(OS, GetCurrentProcess(), GetCurrentThread(),
421 StackFrame, &Context);
425 void llvm::sys::SetInterruptFunction(void (*IF)()) {
427 InterruptFunction = IF;
428 LeaveCriticalSection(&CriticalSection);
432 /// AddSignalHandler - Add a function to be called when a signal is delivered
433 /// to the process. The handler can have a cookie passed to it to identify
434 /// what instance of the handler it is.
435 void llvm::sys::AddSignalHandler(void (*FnPtr)(void *), void *Cookie) {
436 if (CallBacksToRun == 0)
437 CallBacksToRun = new std::vector<std::pair<void(*)(void*), void*> >();
438 CallBacksToRun->push_back(std::make_pair(FnPtr, Cookie));
440 LeaveCriticalSection(&CriticalSection);
443 static void Cleanup() {
447 EnterCriticalSection(&CriticalSection);
449 // Prevent other thread from registering new files and directories for
450 // removal, should we be executing because of the console handler callback.
451 CleanupExecuted = true;
453 // FIXME: open files cannot be deleted.
455 if (FilesToRemove != NULL)
456 while (!FilesToRemove->empty()) {
457 llvm::sys::fs::remove(FilesToRemove->back());
458 FilesToRemove->pop_back();
462 for (auto &I : *CallBacksToRun)
465 LeaveCriticalSection(&CriticalSection);
468 void llvm::sys::RunInterruptHandlers() {
469 // The interrupt handler may be called from an interrupt, but it may also be
470 // called manually (such as the case of report_fatal_error with no registered
471 // error handler). We must ensure that the critical section is properly
473 InitializeThreading();
477 static LONG WINAPI LLVMUnhandledExceptionFilter(LPEXCEPTION_POINTERS ep) {
480 // Initialize the STACKFRAME structure.
481 STACKFRAME64 StackFrame = {};
484 StackFrame.AddrPC.Offset = ep->ContextRecord->Rip;
485 StackFrame.AddrPC.Mode = AddrModeFlat;
486 StackFrame.AddrStack.Offset = ep->ContextRecord->Rsp;
487 StackFrame.AddrStack.Mode = AddrModeFlat;
488 StackFrame.AddrFrame.Offset = ep->ContextRecord->Rbp;
489 StackFrame.AddrFrame.Mode = AddrModeFlat;
490 #elif defined(_M_IX86)
491 StackFrame.AddrPC.Offset = ep->ContextRecord->Eip;
492 StackFrame.AddrPC.Mode = AddrModeFlat;
493 StackFrame.AddrStack.Offset = ep->ContextRecord->Esp;
494 StackFrame.AddrStack.Mode = AddrModeFlat;
495 StackFrame.AddrFrame.Offset = ep->ContextRecord->Ebp;
496 StackFrame.AddrFrame.Mode = AddrModeFlat;
499 HANDLE hProcess = GetCurrentProcess();
500 HANDLE hThread = GetCurrentThread();
501 PrintStackTraceForThread(llvm::errs(), hProcess, hThread, StackFrame,
504 _exit(ep->ExceptionRecord->ExceptionCode);
507 static BOOL WINAPI LLVMConsoleCtrlHandler(DWORD dwCtrlType) {
508 // We are running in our very own thread, courtesy of Windows.
509 EnterCriticalSection(&CriticalSection);
512 // If an interrupt function has been set, go and run one it; otherwise,
514 void (*IF)() = InterruptFunction;
515 InterruptFunction = 0; // Don't run it on another CTRL-C.
518 // Note: if the interrupt function throws an exception, there is nothing
519 // to catch it in this thread so it will kill the process.
521 LeaveCriticalSection(&CriticalSection);
522 return TRUE; // Don't kill the process.
525 // Allow normal processing to take place; i.e., the process dies.
526 LeaveCriticalSection(&CriticalSection);
531 // We turned these warnings off for this file so that MinGW-g++ doesn't
532 // complain about the ll format specifiers used. Now we are turning the
533 // warnings back on. If MinGW starts to support diagnostic stacks, we can
534 // replace this with a pop.
535 #pragma GCC diagnostic warning "-Wformat"
536 #pragma GCC diagnostic warning "-Wformat-extra-args"