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"
29 #pragma comment(lib, "psapi.lib")
30 #pragma comment(lib, "dbghelp.lib")
32 #if ((HAVE_LIBIMAGEHLP != 1) || (HAVE_LIBPSAPI != 1))
33 #error "libimagehlp.a & libpsapi.a should be present"
35 // The version of g++ that comes with MinGW does *not* properly understand
36 // the ll format specifier for printf. However, MinGW passes the format
37 // specifiers on to the MSVCRT entirely, and the CRT understands the ll
38 // specifier. So these warnings are spurious in this case. Since we compile
39 // with -Wall, this will generate these warnings which should be ignored. So
40 // we will turn off the warnings for this just file. However, MinGW also does
41 // not support push and pop for diagnostics, so we have to manually turn it
42 // back on at the end of the file.
43 #pragma GCC diagnostic ignored "-Wformat"
44 #pragma GCC diagnostic ignored "-Wformat-extra-args"
46 #if !defined(__MINGW64_VERSION_MAJOR)
47 // MinGW.org does not have updated support for the 64-bit versions of the
48 // DebugHlp APIs. So we will have to load them manually. The structures and
49 // method signatures were pulled from DbgHelp.h in the Windows Platform SDK,
50 // and adjusted for brevity.
51 typedef struct _IMAGEHLP_LINE64 {
57 } IMAGEHLP_LINE64, *PIMAGEHLP_LINE64;
59 typedef struct _IMAGEHLP_SYMBOL64 {
66 } IMAGEHLP_SYMBOL64, *PIMAGEHLP_SYMBOL64;
68 typedef struct _tagADDRESS64 {
72 } ADDRESS64, *LPADDRESS64;
74 typedef struct _KDHELP64 {
76 DWORD ThCallbackStack;
77 DWORD ThCallbackBStore;
80 DWORD64 KiCallUserMode;
81 DWORD64 KeUserCallbackDispatcher;
82 DWORD64 SystemRangeStart;
83 DWORD64 KiUserExceptionDispatcher;
87 } KDHELP64, *PKDHELP64;
89 typedef struct _tagSTACKFRAME64 {
101 } STACKFRAME64, *LPSTACKFRAME64;
103 typedef BOOL (__stdcall *PREAD_PROCESS_MEMORY_ROUTINE64)(HANDLE hProcess,
104 DWORD64 qwBaseAddress, PVOID lpBuffer, DWORD nSize,
105 LPDWORD lpNumberOfBytesRead);
107 typedef PVOID (__stdcall *PFUNCTION_TABLE_ACCESS_ROUTINE64)( HANDLE ahProcess,
110 typedef DWORD64 (__stdcall *PGET_MODULE_BASE_ROUTINE64)(HANDLE hProcess,
113 typedef DWORD64 (__stdcall *PTRANSLATE_ADDRESS_ROUTINE64)(HANDLE hProcess,
114 HANDLE hThread, LPADDRESS64 lpaddr);
116 typedef BOOL (WINAPI *fpStackWalk64)(DWORD, HANDLE, HANDLE, LPSTACKFRAME64,
117 PVOID, PREAD_PROCESS_MEMORY_ROUTINE64,
118 PFUNCTION_TABLE_ACCESS_ROUTINE64,
119 PGET_MODULE_BASE_ROUTINE64,
120 PTRANSLATE_ADDRESS_ROUTINE64);
121 static fpStackWalk64 StackWalk64;
123 typedef DWORD64 (WINAPI *fpSymGetModuleBase64)(HANDLE, DWORD64);
124 static fpSymGetModuleBase64 SymGetModuleBase64;
126 typedef BOOL (WINAPI *fpSymGetSymFromAddr64)(HANDLE, DWORD64,
127 PDWORD64, PIMAGEHLP_SYMBOL64);
128 static fpSymGetSymFromAddr64 SymGetSymFromAddr64;
130 typedef BOOL (WINAPI *fpSymGetLineFromAddr64)(HANDLE, DWORD64,
131 PDWORD, PIMAGEHLP_LINE64);
132 static fpSymGetLineFromAddr64 SymGetLineFromAddr64;
134 typedef PVOID (WINAPI *fpSymFunctionTableAccess64)(HANDLE, DWORD64);
135 static fpSymFunctionTableAccess64 SymFunctionTableAccess64;
137 static bool load64BitDebugHelp(void) {
138 HMODULE hLib = ::LoadLibrary("Dbghelp.dll");
140 StackWalk64 = (fpStackWalk64)
141 ::GetProcAddress(hLib, "StackWalk64");
142 SymGetModuleBase64 = (fpSymGetModuleBase64)
143 ::GetProcAddress(hLib, "SymGetModuleBase64");
144 SymGetSymFromAddr64 = (fpSymGetSymFromAddr64)
145 ::GetProcAddress(hLib, "SymGetSymFromAddr64");
146 SymGetLineFromAddr64 = (fpSymGetLineFromAddr64)
147 ::GetProcAddress(hLib, "SymGetLineFromAddr64");
148 SymFunctionTableAccess64 = (fpSymFunctionTableAccess64)
149 ::GetProcAddress(hLib, "SymFunctionTableAccess64");
151 return StackWalk64 != NULL;
153 #endif // !defined(__MINGW64_VERSION_MAJOR)
154 #endif // __MINGW32__
157 static LONG WINAPI LLVMUnhandledExceptionFilter(LPEXCEPTION_POINTERS ep);
158 static BOOL WINAPI LLVMConsoleCtrlHandler(DWORD dwCtrlType);
160 // InterruptFunction - The function to call if ctrl-c is pressed.
161 static void (*InterruptFunction)() = 0;
163 static std::vector<std::string> *FilesToRemove = NULL;
164 static std::vector<std::pair<void(*)(void*), void*> > *CallBacksToRun = 0;
165 static bool RegisteredUnhandledExceptionFilter = false;
166 static bool CleanupExecuted = false;
167 static bool ExitOnUnhandledExceptions = false;
168 static PTOP_LEVEL_EXCEPTION_FILTER OldFilter = NULL;
170 // Windows creates a new thread to execute the console handler when an event
171 // (such as CTRL/C) occurs. This causes concurrency issues with the above
172 // globals which this critical section addresses.
173 static CRITICAL_SECTION CriticalSection;
177 //===----------------------------------------------------------------------===//
178 //=== WARNING: Implementation here must contain only Win32 specific code
179 //=== and must not be UNIX code
180 //===----------------------------------------------------------------------===//
183 /// AvoidMessageBoxHook - Emulates hitting "retry" from an "abort, retry,
184 /// ignore" CRT debug report dialog. "retry" raises an exception which
185 /// ultimately triggers our stack dumper.
186 static int AvoidMessageBoxHook(int ReportType, char *Message, int *Return) {
187 // Set *Return to the retry code for the return value of _CrtDbgReport:
188 // http://msdn.microsoft.com/en-us/library/8hyw4sy7(v=vs.71).aspx
189 // This may also trigger just-in-time debugging via DebugBreak().
192 // Don't call _CrtDbgReport.
196 /// CRTReportHook - Function called on a CRT debugging event.
197 static int CRTReportHook(int ReportType, char *Message, int *Return) {
198 // Don't cause a DebugBreak() on return.
202 switch (ReportType) {
205 fprintf(stderr, "CRT assert: %s\n", Message);
206 // FIXME: Is there a way to just crash? Perhaps throw to the unhandled
207 // exception code? Perhaps SetErrorMode() handles this.
211 fprintf(stderr, "CRT error: %s\n", Message);
212 // FIXME: Is there a way to just crash? Perhaps throw to the unhandled
213 // exception code? Perhaps SetErrorMode() handles this.
217 fprintf(stderr, "CRT warn: %s\n", Message);
221 // Don't call _CrtDbgReport.
226 static void RegisterHandler() {
227 #if __MINGW32__ && !defined(__MINGW64_VERSION_MAJOR)
228 // On MinGW.org, we need to load up the symbols explicitly, because the
229 // Win32 framework they include does not have support for the 64-bit
230 // versions of the APIs we need. If we cannot load up the APIs (which
231 // would be unexpected as they should exist on every version of Windows
232 // we support), we will bail out since there would be nothing to report.
233 if (!load64BitDebugHelp()) {
234 assert(false && "These APIs should always be available");
239 if (RegisteredUnhandledExceptionFilter) {
240 EnterCriticalSection(&CriticalSection);
244 // Now's the time to create the critical section. This is the first time
245 // through here, and there's only one thread.
246 InitializeCriticalSection(&CriticalSection);
248 // Enter it immediately. Now if someone hits CTRL/C, the console handler
249 // can't proceed until the globals are updated.
250 EnterCriticalSection(&CriticalSection);
252 RegisteredUnhandledExceptionFilter = true;
253 OldFilter = SetUnhandledExceptionFilter(LLVMUnhandledExceptionFilter);
254 SetConsoleCtrlHandler(LLVMConsoleCtrlHandler, TRUE);
257 const char *EnableMsgbox = getenv("LLVM_ENABLE_CRT_REPORT");
258 if (!EnableMsgbox || strcmp("0", EnableMsgbox) == 0) {
259 // Setting a report hook overrides the default behavior of popping an "abort,
260 // retry, or ignore" dialog.
261 _CrtSetReportHook(AvoidMessageBoxHook);
265 // Environment variable to disable any kind of crash dialog.
266 if (getenv("LLVM_DISABLE_CRASH_REPORT")) {
268 _CrtSetReportHook(CRTReportHook);
270 SetErrorMode(SEM_FAILCRITICALERRORS |
271 SEM_NOGPFAULTERRORBOX |
272 SEM_NOOPENFILEERRORBOX);
273 ExitOnUnhandledExceptions = true;
276 // IMPORTANT NOTE: Caller must call LeaveCriticalSection(&CriticalSection) or
277 // else multi-threading problems will ensue.
280 // RemoveFileOnSignal - The public API
281 bool sys::RemoveFileOnSignal(StringRef Filename, std::string* ErrMsg) {
284 if (CleanupExecuted) {
286 *ErrMsg = "Process terminating -- cannot register for removal";
290 if (FilesToRemove == NULL)
291 FilesToRemove = new std::vector<std::string>;
293 FilesToRemove->push_back(Filename);
295 LeaveCriticalSection(&CriticalSection);
299 // DontRemoveFileOnSignal - The public API
300 void sys::DontRemoveFileOnSignal(StringRef Filename) {
301 if (FilesToRemove == NULL)
306 FilesToRemove->push_back(Filename);
307 std::vector<std::string>::reverse_iterator I =
308 std::find(FilesToRemove->rbegin(), FilesToRemove->rend(), Filename);
309 if (I != FilesToRemove->rend())
310 FilesToRemove->erase(I.base()-1);
312 LeaveCriticalSection(&CriticalSection);
315 /// PrintStackTraceOnErrorSignal - When an error signal (such as SIBABRT or
316 /// SIGSEGV) is delivered to the process, print a stack trace and then exit.
317 void sys::PrintStackTraceOnErrorSignal() {
319 LeaveCriticalSection(&CriticalSection);
322 void llvm::sys::PrintStackTrace(FILE *) {
327 void sys::SetInterruptFunction(void (*IF)()) {
329 InterruptFunction = IF;
330 LeaveCriticalSection(&CriticalSection);
334 /// AddSignalHandler - Add a function to be called when a signal is delivered
335 /// to the process. The handler can have a cookie passed to it to identify
336 /// what instance of the handler it is.
337 void sys::AddSignalHandler(void (*FnPtr)(void *), void *Cookie) {
338 if (CallBacksToRun == 0)
339 CallBacksToRun = new std::vector<std::pair<void(*)(void*), void*> >();
340 CallBacksToRun->push_back(std::make_pair(FnPtr, Cookie));
342 LeaveCriticalSection(&CriticalSection);
346 static void Cleanup() {
347 EnterCriticalSection(&CriticalSection);
349 // Prevent other thread from registering new files and directories for
350 // removal, should we be executing because of the console handler callback.
351 CleanupExecuted = true;
353 // FIXME: open files cannot be deleted.
355 if (FilesToRemove != NULL)
356 while (!FilesToRemove->empty()) {
358 llvm::sys::fs::remove(FilesToRemove->back(), Existed);
359 FilesToRemove->pop_back();
363 for (unsigned i = 0, e = CallBacksToRun->size(); i != e; ++i)
364 (*CallBacksToRun)[i].first((*CallBacksToRun)[i].second);
366 LeaveCriticalSection(&CriticalSection);
369 void llvm::sys::RunInterruptHandlers() {
373 static LONG WINAPI LLVMUnhandledExceptionFilter(LPEXCEPTION_POINTERS ep) {
376 // Initialize the STACKFRAME structure.
377 STACKFRAME64 StackFrame;
378 memset(&StackFrame, 0, sizeof(StackFrame));
382 machineType = IMAGE_FILE_MACHINE_AMD64;
383 StackFrame.AddrPC.Offset = ep->ContextRecord->Rip;
384 StackFrame.AddrPC.Mode = AddrModeFlat;
385 StackFrame.AddrStack.Offset = ep->ContextRecord->Rsp;
386 StackFrame.AddrStack.Mode = AddrModeFlat;
387 StackFrame.AddrFrame.Offset = ep->ContextRecord->Rbp;
388 StackFrame.AddrFrame.Mode = AddrModeFlat;
389 #elif defined(_M_IX86)
390 machineType = IMAGE_FILE_MACHINE_I386;
391 StackFrame.AddrPC.Offset = ep->ContextRecord->Eip;
392 StackFrame.AddrPC.Mode = AddrModeFlat;
393 StackFrame.AddrStack.Offset = ep->ContextRecord->Esp;
394 StackFrame.AddrStack.Mode = AddrModeFlat;
395 StackFrame.AddrFrame.Offset = ep->ContextRecord->Ebp;
396 StackFrame.AddrFrame.Mode = AddrModeFlat;
399 HANDLE hProcess = GetCurrentProcess();
400 HANDLE hThread = GetCurrentThread();
402 // Initialize the symbol handler.
403 SymSetOptions(SYMOPT_DEFERRED_LOADS|SYMOPT_LOAD_LINES);
404 SymInitialize(hProcess, NULL, TRUE);
407 if (!StackWalk64(machineType, hProcess, hThread, &StackFrame,
408 ep->ContextRecord, NULL, SymFunctionTableAccess64,
409 SymGetModuleBase64, NULL)) {
413 if (StackFrame.AddrFrame.Offset == 0)
416 // Print the PC in hexadecimal.
417 DWORD64 PC = StackFrame.AddrPC.Offset;
419 fprintf(stderr, "0x%016llX", PC);
420 #elif defined(_M_IX86)
421 fprintf(stderr, "0x%08lX", static_cast<DWORD>(PC));
424 // Print the parameters. Assume there are four.
426 fprintf(stderr, " (0x%016llX 0x%016llX 0x%016llX 0x%016llX)",
427 StackFrame.Params[0],
428 StackFrame.Params[1],
429 StackFrame.Params[2],
430 StackFrame.Params[3]);
431 #elif defined(_M_IX86)
432 fprintf(stderr, " (0x%08lX 0x%08lX 0x%08lX 0x%08lX)",
433 static_cast<DWORD>(StackFrame.Params[0]),
434 static_cast<DWORD>(StackFrame.Params[1]),
435 static_cast<DWORD>(StackFrame.Params[2]),
436 static_cast<DWORD>(StackFrame.Params[3]));
438 // Verify the PC belongs to a module in this process.
439 if (!SymGetModuleBase64(hProcess, PC)) {
440 fputs(" <unknown module>\n", stderr);
444 // Print the symbol name.
446 IMAGEHLP_SYMBOL64 *symbol = reinterpret_cast<IMAGEHLP_SYMBOL64 *>(buffer);
447 memset(symbol, 0, sizeof(IMAGEHLP_SYMBOL64));
448 symbol->SizeOfStruct = sizeof(IMAGEHLP_SYMBOL64);
449 symbol->MaxNameLength = 512 - sizeof(IMAGEHLP_SYMBOL64);
452 if (!SymGetSymFromAddr64(hProcess, PC, &dwDisp, symbol)) {
459 fprintf(stderr, ", %s() + 0x%llX bytes(s)", symbol->Name, dwDisp);
461 fprintf(stderr, ", %s", symbol->Name);
463 // Print the source file and line number information.
464 IMAGEHLP_LINE64 line;
466 memset(&line, 0, sizeof(line));
467 line.SizeOfStruct = sizeof(line);
468 if (SymGetLineFromAddr64(hProcess, PC, &dwLineDisp, &line)) {
469 fprintf(stderr, ", %s, line %lu", line.FileName, line.LineNumber);
471 fprintf(stderr, " + 0x%lX byte(s)", dwLineDisp);
477 if (ExitOnUnhandledExceptions)
478 _exit(ep->ExceptionRecord->ExceptionCode);
480 // Allow dialog box to pop up allowing choice to start debugger.
482 return (*OldFilter)(ep);
484 return EXCEPTION_CONTINUE_SEARCH;
487 static BOOL WINAPI LLVMConsoleCtrlHandler(DWORD dwCtrlType) {
488 // We are running in our very own thread, courtesy of Windows.
489 EnterCriticalSection(&CriticalSection);
492 // If an interrupt function has been set, go and run one it; otherwise,
494 void (*IF)() = InterruptFunction;
495 InterruptFunction = 0; // Don't run it on another CTRL-C.
498 // Note: if the interrupt function throws an exception, there is nothing
499 // to catch it in this thread so it will kill the process.
501 LeaveCriticalSection(&CriticalSection);
502 return TRUE; // Don't kill the process.
505 // Allow normal processing to take place; i.e., the process dies.
506 LeaveCriticalSection(&CriticalSection);
511 // We turned these warnings off for this file so that MinGW-g++ doesn't
512 // complain about the ll format specifiers used. Now we are turning the
513 // warnings back on. If MinGW starts to support diagnostic stacks, we can
514 // replace this with a pop.
515 #pragma GCC diagnostic warning "-Wformat"
516 #pragma GCC diagnostic warning "-Wformat-extra-args"