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"
18 #include "llvm/Support/Format.h"
19 #include "llvm/Support/raw_ostream.h"
21 // The Windows.h header must be after LLVM and standard headers.
22 #include "WindowsSupport.h"
32 #pragma comment(lib, "psapi.lib")
34 #if (HAVE_LIBPSAPI != 1)
35 #error "libpsapi.a should be present"
37 // The version of g++ that comes with MinGW does *not* properly understand
38 // the ll format specifier for printf. However, MinGW passes the format
39 // specifiers on to the MSVCRT entirely, and the CRT understands the ll
40 // specifier. So these warnings are spurious in this case. Since we compile
41 // with -Wall, this will generate these warnings which should be ignored. So
42 // we will turn off the warnings for this just file. However, MinGW also does
43 // not support push and pop for diagnostics, so we have to manually turn it
44 // back on at the end of the file.
45 #pragma GCC diagnostic ignored "-Wformat"
46 #pragma GCC diagnostic ignored "-Wformat-extra-args"
48 #if !defined(__MINGW64_VERSION_MAJOR)
49 // MinGW.org does not have updated support for the 64-bit versions of the
50 // DebugHlp APIs. So we will have to load them manually. The structures and
51 // method signatures were pulled from DbgHelp.h in the Windows Platform SDK,
52 // and adjusted for brevity.
53 typedef struct _IMAGEHLP_LINE64 {
59 } IMAGEHLP_LINE64, *PIMAGEHLP_LINE64;
61 typedef struct _IMAGEHLP_SYMBOL64 {
68 } IMAGEHLP_SYMBOL64, *PIMAGEHLP_SYMBOL64;
70 typedef struct _tagADDRESS64 {
74 } ADDRESS64, *LPADDRESS64;
76 typedef struct _KDHELP64 {
78 DWORD ThCallbackStack;
79 DWORD ThCallbackBStore;
82 DWORD64 KiCallUserMode;
83 DWORD64 KeUserCallbackDispatcher;
84 DWORD64 SystemRangeStart;
85 DWORD64 KiUserExceptionDispatcher;
89 } KDHELP64, *PKDHELP64;
91 typedef struct _tagSTACKFRAME64 {
103 } STACKFRAME64, *LPSTACKFRAME64;
104 #endif // !defined(__MINGW64_VERSION_MAJOR)
105 #endif // __MINGW32__
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 fStackWalk64;
127 typedef DWORD64 (WINAPI *fpSymGetModuleBase64)(HANDLE, DWORD64);
128 static fpSymGetModuleBase64 fSymGetModuleBase64;
130 typedef BOOL (WINAPI *fpSymGetSymFromAddr64)(HANDLE, DWORD64,
131 PDWORD64, PIMAGEHLP_SYMBOL64);
132 static fpSymGetSymFromAddr64 fSymGetSymFromAddr64;
134 typedef BOOL (WINAPI *fpSymGetLineFromAddr64)(HANDLE, DWORD64,
135 PDWORD, PIMAGEHLP_LINE64);
136 static fpSymGetLineFromAddr64 fSymGetLineFromAddr64;
138 typedef PVOID (WINAPI *fpSymFunctionTableAccess64)(HANDLE, DWORD64);
139 static fpSymFunctionTableAccess64 fSymFunctionTableAccess64;
141 typedef DWORD (WINAPI *fpSymSetOptions)(DWORD);
142 static fpSymSetOptions fSymSetOptions;
144 typedef BOOL (WINAPI *fpSymInitialize)(HANDLE, PCSTR, BOOL);
145 static fpSymInitialize fSymInitialize;
147 static bool load64BitDebugHelp(void) {
148 HMODULE hLib = ::LoadLibraryW(L"Dbghelp.dll");
150 fStackWalk64 = (fpStackWalk64)
151 ::GetProcAddress(hLib, "StackWalk64");
152 fSymGetModuleBase64 = (fpSymGetModuleBase64)
153 ::GetProcAddress(hLib, "SymGetModuleBase64");
154 fSymGetSymFromAddr64 = (fpSymGetSymFromAddr64)
155 ::GetProcAddress(hLib, "SymGetSymFromAddr64");
156 fSymGetLineFromAddr64 = (fpSymGetLineFromAddr64)
157 ::GetProcAddress(hLib, "SymGetLineFromAddr64");
158 fSymFunctionTableAccess64 = (fpSymFunctionTableAccess64)
159 ::GetProcAddress(hLib, "SymFunctionTableAccess64");
160 fSymSetOptions = (fpSymSetOptions)::GetProcAddress(hLib, "SymSetOptions");
161 fSymInitialize = (fpSymInitialize)::GetProcAddress(hLib, "SymInitialize");
163 return fStackWalk64 && fSymInitialize && fSymSetOptions;
166 using namespace llvm;
169 static LONG WINAPI LLVMUnhandledExceptionFilter(LPEXCEPTION_POINTERS ep);
170 static BOOL WINAPI LLVMConsoleCtrlHandler(DWORD dwCtrlType);
172 // InterruptFunction - The function to call if ctrl-c is pressed.
173 static void (*InterruptFunction)() = 0;
175 static std::vector<std::string> *FilesToRemove = NULL;
176 static bool RegisteredUnhandledExceptionFilter = false;
177 static bool CleanupExecuted = false;
178 static PTOP_LEVEL_EXCEPTION_FILTER OldFilter = NULL;
180 // Windows creates a new thread to execute the console handler when an event
181 // (such as CTRL/C) occurs. This causes concurrency issues with the above
182 // globals which this critical section addresses.
183 static CRITICAL_SECTION CriticalSection;
184 static bool CriticalSectionInitialized = false;
186 static void PrintStackTraceForThread(llvm::raw_ostream &OS, HANDLE hProcess,
187 HANDLE hThread, STACKFRAME64 &StackFrame,
191 machineType = IMAGE_FILE_MACHINE_AMD64;
193 machineType = IMAGE_FILE_MACHINE_I386;
196 // Initialize the symbol handler.
197 fSymSetOptions(SYMOPT_DEFERRED_LOADS | SYMOPT_LOAD_LINES);
198 fSymInitialize(hProcess, NULL, TRUE);
201 if (!fStackWalk64(machineType, hProcess, hThread, &StackFrame, Context, 0,
202 fSymFunctionTableAccess64, fSymGetModuleBase64, 0)) {
206 if (StackFrame.AddrFrame.Offset == 0)
209 using namespace llvm;
210 // Print the PC in hexadecimal.
211 DWORD64 PC = StackFrame.AddrPC.Offset;
213 OS << format("0x%016llX", PC);
214 #elif defined(_M_IX86)
215 OS << format("0x%08lX", static_cast<DWORD>(PC));
218 // Print the parameters. Assume there are four.
220 OS << format(" (0x%016llX 0x%016llX 0x%016llX 0x%016llX)",
221 StackFrame.Params[0], StackFrame.Params[1], StackFrame.Params[2],
222 StackFrame.Params[3]);
223 #elif defined(_M_IX86)
224 OS << format(" (0x%08lX 0x%08lX 0x%08lX 0x%08lX)",
225 static_cast<DWORD>(StackFrame.Params[0]),
226 static_cast<DWORD>(StackFrame.Params[1]),
227 static_cast<DWORD>(StackFrame.Params[2]),
228 static_cast<DWORD>(StackFrame.Params[3]));
230 // Verify the PC belongs to a module in this process.
231 if (!fSymGetModuleBase64(hProcess, PC)) {
232 OS << " <unknown module>\n";
236 // Print the symbol name.
238 IMAGEHLP_SYMBOL64 *symbol = reinterpret_cast<IMAGEHLP_SYMBOL64 *>(buffer);
239 memset(symbol, 0, sizeof(IMAGEHLP_SYMBOL64));
240 symbol->SizeOfStruct = sizeof(IMAGEHLP_SYMBOL64);
241 symbol->MaxNameLength = 512 - sizeof(IMAGEHLP_SYMBOL64);
244 if (!fSymGetSymFromAddr64(hProcess, PC, &dwDisp, symbol)) {
251 OS << format(", %s() + 0x%llX bytes(s)", (const char*)symbol->Name,
254 OS << format(", %s", (const char*)symbol->Name);
256 // Print the source file and line number information.
257 IMAGEHLP_LINE64 line = {};
259 line.SizeOfStruct = sizeof(line);
260 if (fSymGetLineFromAddr64(hProcess, PC, &dwLineDisp, &line)) {
261 OS << format(", %s, line %lu", line.FileName, line.LineNumber);
263 OS << format(" + 0x%lX byte(s)", dwLineDisp);
272 //===----------------------------------------------------------------------===//
273 //=== WARNING: Implementation here must contain only Win32 specific code
274 //=== and must not be UNIX code
275 //===----------------------------------------------------------------------===//
278 /// AvoidMessageBoxHook - Emulates hitting "retry" from an "abort, retry,
279 /// ignore" CRT debug report dialog. "retry" raises an exception which
280 /// ultimately triggers our stack dumper.
281 static LLVM_ATTRIBUTE_UNUSED int
282 AvoidMessageBoxHook(int ReportType, char *Message, int *Return) {
283 // Set *Return to the retry code for the return value of _CrtDbgReport:
284 // http://msdn.microsoft.com/en-us/library/8hyw4sy7(v=vs.71).aspx
285 // This may also trigger just-in-time debugging via DebugBreak().
288 // Don't call _CrtDbgReport.
294 extern "C" void HandleAbort(int Sig) {
295 if (Sig == SIGABRT) {
300 static void InitializeThreading() {
301 if (CriticalSectionInitialized)
304 // Now's the time to create the critical section. This is the first time
305 // through here, and there's only one thread.
306 InitializeCriticalSection(&CriticalSection);
307 CriticalSectionInitialized = true;
310 static void RegisterHandler() {
311 // If we cannot load up the APIs (which would be unexpected as they should
312 // exist on every version of Windows we support), we will bail out since
313 // there would be nothing to report.
314 if (!load64BitDebugHelp()) {
315 assert(false && "These APIs should always be available");
319 if (RegisteredUnhandledExceptionFilter) {
320 EnterCriticalSection(&CriticalSection);
324 InitializeThreading();
326 // Enter it immediately. Now if someone hits CTRL/C, the console handler
327 // can't proceed until the globals are updated.
328 EnterCriticalSection(&CriticalSection);
330 RegisteredUnhandledExceptionFilter = true;
331 OldFilter = SetUnhandledExceptionFilter(LLVMUnhandledExceptionFilter);
332 SetConsoleCtrlHandler(LLVMConsoleCtrlHandler, TRUE);
334 // IMPORTANT NOTE: Caller must call LeaveCriticalSection(&CriticalSection) or
335 // else multi-threading problems will ensue.
338 // RemoveFileOnSignal - The public API
339 bool sys::RemoveFileOnSignal(StringRef Filename, std::string* ErrMsg) {
342 if (CleanupExecuted) {
344 *ErrMsg = "Process terminating -- cannot register for removal";
348 if (FilesToRemove == NULL)
349 FilesToRemove = new std::vector<std::string>;
351 FilesToRemove->push_back(Filename);
353 LeaveCriticalSection(&CriticalSection);
357 // DontRemoveFileOnSignal - The public API
358 void sys::DontRemoveFileOnSignal(StringRef Filename) {
359 if (FilesToRemove == NULL)
364 std::vector<std::string>::reverse_iterator I =
365 std::find(FilesToRemove->rbegin(), FilesToRemove->rend(), Filename);
366 if (I != FilesToRemove->rend())
367 FilesToRemove->erase(I.base()-1);
369 LeaveCriticalSection(&CriticalSection);
372 void sys::DisableSystemDialogsOnCrash() {
373 // Crash to stack trace handler on abort.
374 signal(SIGABRT, HandleAbort);
376 // The following functions are not reliably accessible on MinGW.
378 // We're already handling writing a "something went wrong" message.
379 _set_abort_behavior(0, _WRITE_ABORT_MSG);
380 // Disable Dr. Watson.
381 _set_abort_behavior(0, _CALL_REPORTFAULT);
382 _CrtSetReportHook(AvoidMessageBoxHook);
385 // Disable standard error dialog box.
386 SetErrorMode(SEM_FAILCRITICALERRORS | SEM_NOGPFAULTERRORBOX |
387 SEM_NOOPENFILEERRORBOX);
388 _set_error_mode(_OUT_TO_STDERR);
391 /// PrintStackTraceOnErrorSignal - When an error signal (such as SIBABRT or
392 /// SIGSEGV) is delivered to the process, print a stack trace and then exit.
393 void sys::PrintStackTraceOnErrorSignal(bool DisableCrashReporting) {
394 DisableSystemDialogsOnCrash();
396 LeaveCriticalSection(&CriticalSection);
400 #if defined(__MINGW32__) && !defined(__MINGW64_VERSION_MAJOR)
401 // Provide a prototype for RtlCaptureContext, mingw32 from mingw.org is
402 // missing it but mingw-w64 has it.
403 extern "C" VOID WINAPI RtlCaptureContext(PCONTEXT ContextRecord);
406 void llvm::sys::PrintStackTrace(raw_ostream &OS) {
408 STACKFRAME64 StackFrame = {};
409 CONTEXT Context = {};
410 ::RtlCaptureContext(&Context);
412 StackFrame.AddrPC.Offset = Context.Rip;
413 StackFrame.AddrStack.Offset = Context.Rsp;
414 StackFrame.AddrFrame.Offset = Context.Rbp;
416 StackFrame.AddrPC.Offset = Context.Eip;
417 StackFrame.AddrStack.Offset = Context.Esp;
418 StackFrame.AddrFrame.Offset = Context.Ebp;
420 StackFrame.AddrPC.Mode = AddrModeFlat;
421 StackFrame.AddrStack.Mode = AddrModeFlat;
422 StackFrame.AddrFrame.Mode = AddrModeFlat;
423 PrintStackTraceForThread(OS, GetCurrentProcess(), GetCurrentThread(),
424 StackFrame, &Context);
428 void llvm::sys::SetInterruptFunction(void (*IF)()) {
430 InterruptFunction = IF;
431 LeaveCriticalSection(&CriticalSection);
435 /// AddSignalHandler - Add a function to be called when a signal is delivered
436 /// to the process. The handler can have a cookie passed to it to identify
437 /// what instance of the handler it is.
438 void llvm::sys::AddSignalHandler(void (*FnPtr)(void *), void *Cookie) {
439 CallBacksToRun->push_back(std::make_pair(FnPtr, Cookie));
441 LeaveCriticalSection(&CriticalSection);
444 static void Cleanup() {
448 EnterCriticalSection(&CriticalSection);
450 // Prevent other thread from registering new files and directories for
451 // removal, should we be executing because of the console handler callback.
452 CleanupExecuted = true;
454 // 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();
460 llvm::sys::RunSignalHandlers();
461 LeaveCriticalSection(&CriticalSection);
464 void llvm::sys::RunInterruptHandlers() {
465 // The interrupt handler may be called from an interrupt, but it may also be
466 // called manually (such as the case of report_fatal_error with no registered
467 // error handler). We must ensure that the critical section is properly
469 InitializeThreading();
473 static LONG WINAPI LLVMUnhandledExceptionFilter(LPEXCEPTION_POINTERS ep) {
476 // Initialize the STACKFRAME structure.
477 STACKFRAME64 StackFrame = {};
480 StackFrame.AddrPC.Offset = ep->ContextRecord->Rip;
481 StackFrame.AddrPC.Mode = AddrModeFlat;
482 StackFrame.AddrStack.Offset = ep->ContextRecord->Rsp;
483 StackFrame.AddrStack.Mode = AddrModeFlat;
484 StackFrame.AddrFrame.Offset = ep->ContextRecord->Rbp;
485 StackFrame.AddrFrame.Mode = AddrModeFlat;
486 #elif defined(_M_IX86)
487 StackFrame.AddrPC.Offset = ep->ContextRecord->Eip;
488 StackFrame.AddrPC.Mode = AddrModeFlat;
489 StackFrame.AddrStack.Offset = ep->ContextRecord->Esp;
490 StackFrame.AddrStack.Mode = AddrModeFlat;
491 StackFrame.AddrFrame.Offset = ep->ContextRecord->Ebp;
492 StackFrame.AddrFrame.Mode = AddrModeFlat;
495 HANDLE hProcess = GetCurrentProcess();
496 HANDLE hThread = GetCurrentThread();
497 PrintStackTraceForThread(llvm::errs(), hProcess, hThread, StackFrame,
500 _exit(ep->ExceptionRecord->ExceptionCode);
503 static BOOL WINAPI LLVMConsoleCtrlHandler(DWORD dwCtrlType) {
504 // We are running in our very own thread, courtesy of Windows.
505 EnterCriticalSection(&CriticalSection);
508 // If an interrupt function has been set, go and run one it; otherwise,
510 void (*IF)() = InterruptFunction;
511 InterruptFunction = 0; // Don't run it on another CTRL-C.
514 // Note: if the interrupt function throws an exception, there is nothing
515 // to catch it in this thread so it will kill the process.
517 LeaveCriticalSection(&CriticalSection);
518 return TRUE; // Don't kill the process.
521 // Allow normal processing to take place; i.e., the process dies.
522 LeaveCriticalSection(&CriticalSection);
527 // We turned these warnings off for this file so that MinGW-g++ doesn't
528 // complain about the ll format specifiers used. Now we are turning the
529 // warnings back on. If MinGW starts to support diagnostic stacks, we can
530 // replace this with a pop.
531 #pragma GCC diagnostic warning "-Wformat"
532 #pragma GCC diagnostic warning "-Wformat-extra-args"