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 memset(&line, 0, sizeof(line));
253 line.SizeOfStruct = sizeof(line);
254 if (SymGetLineFromAddr64(hProcess, PC, &dwLineDisp, &line)) {
255 OS << format(", %s, line %lu", line.FileName, line.LineNumber);
257 OS << format(" + 0x%lX byte(s)", dwLineDisp);
266 //===----------------------------------------------------------------------===//
267 //=== WARNING: Implementation here must contain only Win32 specific code
268 //=== and must not be UNIX code
269 //===----------------------------------------------------------------------===//
272 /// AvoidMessageBoxHook - Emulates hitting "retry" from an "abort, retry,
273 /// ignore" CRT debug report dialog. "retry" raises an exception which
274 /// ultimately triggers our stack dumper.
275 static LLVM_ATTRIBUTE_UNUSED int
276 AvoidMessageBoxHook(int ReportType, char *Message, int *Return) {
277 // Set *Return to the retry code for the return value of _CrtDbgReport:
278 // http://msdn.microsoft.com/en-us/library/8hyw4sy7(v=vs.71).aspx
279 // This may also trigger just-in-time debugging via DebugBreak().
282 // Don't call _CrtDbgReport.
288 extern "C" void HandleAbort(int Sig) {
289 if (Sig == SIGABRT) {
294 static void InitializeThreading() {
295 if (CriticalSectionInitialized)
298 // Now's the time to create the critical section. This is the first time
299 // through here, and there's only one thread.
300 InitializeCriticalSection(&CriticalSection);
301 CriticalSectionInitialized = true;
304 static void RegisterHandler() {
305 #if __MINGW32__ && !defined(__MINGW64_VERSION_MAJOR)
306 // On MinGW.org, we need to load up the symbols explicitly, because the
307 // Win32 framework they include does not have support for the 64-bit
308 // versions of the APIs we need. If we cannot load up the APIs (which
309 // would be unexpected as they should exist on every version of Windows
310 // we support), we will bail out since there would be nothing to report.
311 if (!load64BitDebugHelp()) {
312 assert(false && "These APIs should always be available");
317 if (RegisteredUnhandledExceptionFilter) {
318 EnterCriticalSection(&CriticalSection);
322 InitializeThreading();
324 // Enter it immediately. Now if someone hits CTRL/C, the console handler
325 // can't proceed until the globals are updated.
326 EnterCriticalSection(&CriticalSection);
328 RegisteredUnhandledExceptionFilter = true;
329 OldFilter = SetUnhandledExceptionFilter(LLVMUnhandledExceptionFilter);
330 SetConsoleCtrlHandler(LLVMConsoleCtrlHandler, TRUE);
332 // IMPORTANT NOTE: Caller must call LeaveCriticalSection(&CriticalSection) or
333 // else multi-threading problems will ensue.
336 // RemoveFileOnSignal - The public API
337 bool sys::RemoveFileOnSignal(StringRef Filename, std::string* ErrMsg) {
340 if (CleanupExecuted) {
342 *ErrMsg = "Process terminating -- cannot register for removal";
346 if (FilesToRemove == NULL)
347 FilesToRemove = new std::vector<std::string>;
349 FilesToRemove->push_back(Filename);
351 LeaveCriticalSection(&CriticalSection);
355 // DontRemoveFileOnSignal - The public API
356 void sys::DontRemoveFileOnSignal(StringRef Filename) {
357 if (FilesToRemove == NULL)
362 FilesToRemove->push_back(Filename);
363 std::vector<std::string>::reverse_iterator I =
364 std::find(FilesToRemove->rbegin(), FilesToRemove->rend(), Filename);
365 if (I != FilesToRemove->rend())
366 FilesToRemove->erase(I.base()-1);
368 LeaveCriticalSection(&CriticalSection);
371 void sys::DisableSystemDialogsOnCrash() {
372 // Crash to stack trace handler on abort.
373 signal(SIGABRT, HandleAbort);
375 // The following functions are not reliably accessible on MinGW.
377 // We're already handling writing a "something went wrong" message.
378 _set_abort_behavior(0, _WRITE_ABORT_MSG);
379 // Disable Dr. Watson.
380 _set_abort_behavior(0, _CALL_REPORTFAULT);
381 _CrtSetReportHook(AvoidMessageBoxHook);
384 // Disable standard error dialog box.
385 SetErrorMode(SEM_FAILCRITICALERRORS | SEM_NOGPFAULTERRORBOX |
386 SEM_NOOPENFILEERRORBOX);
387 _set_error_mode(_OUT_TO_STDERR);
390 /// PrintStackTraceOnErrorSignal - When an error signal (such as SIBABRT or
391 /// SIGSEGV) is delivered to the process, print a stack trace and then exit.
392 void sys::PrintStackTraceOnErrorSignal(bool DisableCrashReporting) {
393 DisableSystemDialogsOnCrash();
395 LeaveCriticalSection(&CriticalSection);
399 #if defined(__MINGW32__) && !defined(__MINGW64_VERSION_MAJOR)
400 // Provide a prototype for RtlCaptureContext, mingw32 from mingw.org is
401 // missing it but mingw-w64 has it.
402 extern "C" VOID WINAPI RtlCaptureContext(PCONTEXT ContextRecord);
405 void llvm::sys::PrintStackTrace(raw_ostream &OS) {
407 STACKFRAME64 StackFrame = {};
408 CONTEXT Context = {0};
409 ::RtlCaptureContext(&Context);
411 StackFrame.AddrPC.Offset = Context.Rip;
412 StackFrame.AddrStack.Offset = Context.Rsp;
413 StackFrame.AddrFrame.Offset = Context.Rbp;
415 StackFrame.AddrPC.Offset = Context.Eip;
416 StackFrame.AddrStack.Offset = Context.Esp;
417 StackFrame.AddrFrame.Offset = Context.Ebp;
419 StackFrame.AddrPC.Mode = AddrModeFlat;
420 StackFrame.AddrStack.Mode = AddrModeFlat;
421 StackFrame.AddrFrame.Mode = AddrModeFlat;
422 PrintStackTraceForThread(OS, GetCurrentProcess(), GetCurrentThread(),
423 StackFrame, &Context);
427 void llvm::sys::SetInterruptFunction(void (*IF)()) {
429 InterruptFunction = IF;
430 LeaveCriticalSection(&CriticalSection);
434 /// AddSignalHandler - Add a function to be called when a signal is delivered
435 /// to the process. The handler can have a cookie passed to it to identify
436 /// what instance of the handler it is.
437 void llvm::sys::AddSignalHandler(void (*FnPtr)(void *), void *Cookie) {
438 if (CallBacksToRun == 0)
439 CallBacksToRun = new std::vector<std::pair<void(*)(void*), void*> >();
440 CallBacksToRun->push_back(std::make_pair(FnPtr, Cookie));
442 LeaveCriticalSection(&CriticalSection);
445 static void Cleanup() {
446 EnterCriticalSection(&CriticalSection);
448 // Prevent other thread from registering new files and directories for
449 // removal, should we be executing because of the console handler callback.
450 CleanupExecuted = true;
452 // FIXME: open files cannot be deleted.
454 if (FilesToRemove != NULL)
455 while (!FilesToRemove->empty()) {
456 llvm::sys::fs::remove(FilesToRemove->back());
457 FilesToRemove->pop_back();
461 for (unsigned i = 0, e = CallBacksToRun->size(); i != e; ++i)
462 (*CallBacksToRun)[i].first((*CallBacksToRun)[i].second);
464 LeaveCriticalSection(&CriticalSection);
467 void llvm::sys::RunInterruptHandlers() {
468 // The interrupt handler may be called from an interrupt, but it may also be
469 // called manually (such as the case of report_fatal_error with no registered
470 // error handler). We must ensure that the critical section is properly
472 InitializeThreading();
476 static LONG WINAPI LLVMUnhandledExceptionFilter(LPEXCEPTION_POINTERS ep) {
479 // Initialize the STACKFRAME structure.
480 STACKFRAME64 StackFrame;
481 memset(&StackFrame, 0, sizeof(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"