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"
20 // The Windows.h header must be after LLVM and standard headers.
21 #include "WindowsSupport.h"
31 #pragma comment(lib, "psapi.lib")
32 #pragma comment(lib, "dbghelp.lib")
34 #if ((HAVE_LIBIMAGEHLP != 1) || (HAVE_LIBPSAPI != 1))
35 #error "libimagehlp.a & 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;
105 typedef BOOL (__stdcall *PREAD_PROCESS_MEMORY_ROUTINE64)(HANDLE hProcess,
106 DWORD64 qwBaseAddress, PVOID lpBuffer, DWORD nSize,
107 LPDWORD lpNumberOfBytesRead);
109 typedef PVOID (__stdcall *PFUNCTION_TABLE_ACCESS_ROUTINE64)( HANDLE ahProcess,
112 typedef DWORD64 (__stdcall *PGET_MODULE_BASE_ROUTINE64)(HANDLE hProcess,
115 typedef DWORD64 (__stdcall *PTRANSLATE_ADDRESS_ROUTINE64)(HANDLE hProcess,
116 HANDLE hThread, LPADDRESS64 lpaddr);
118 typedef BOOL (WINAPI *fpStackWalk64)(DWORD, HANDLE, HANDLE, LPSTACKFRAME64,
119 PVOID, PREAD_PROCESS_MEMORY_ROUTINE64,
120 PFUNCTION_TABLE_ACCESS_ROUTINE64,
121 PGET_MODULE_BASE_ROUTINE64,
122 PTRANSLATE_ADDRESS_ROUTINE64);
123 static fpStackWalk64 StackWalk64;
125 typedef DWORD64 (WINAPI *fpSymGetModuleBase64)(HANDLE, DWORD64);
126 static fpSymGetModuleBase64 SymGetModuleBase64;
128 typedef BOOL (WINAPI *fpSymGetSymFromAddr64)(HANDLE, DWORD64,
129 PDWORD64, PIMAGEHLP_SYMBOL64);
130 static fpSymGetSymFromAddr64 SymGetSymFromAddr64;
132 typedef BOOL (WINAPI *fpSymGetLineFromAddr64)(HANDLE, DWORD64,
133 PDWORD, PIMAGEHLP_LINE64);
134 static fpSymGetLineFromAddr64 SymGetLineFromAddr64;
136 typedef PVOID (WINAPI *fpSymFunctionTableAccess64)(HANDLE, DWORD64);
137 static fpSymFunctionTableAccess64 SymFunctionTableAccess64;
139 static bool load64BitDebugHelp(void) {
140 HMODULE hLib = ::LoadLibraryW(L"Dbghelp.dll");
142 StackWalk64 = (fpStackWalk64)
143 ::GetProcAddress(hLib, "StackWalk64");
144 SymGetModuleBase64 = (fpSymGetModuleBase64)
145 ::GetProcAddress(hLib, "SymGetModuleBase64");
146 SymGetSymFromAddr64 = (fpSymGetSymFromAddr64)
147 ::GetProcAddress(hLib, "SymGetSymFromAddr64");
148 SymGetLineFromAddr64 = (fpSymGetLineFromAddr64)
149 ::GetProcAddress(hLib, "SymGetLineFromAddr64");
150 SymFunctionTableAccess64 = (fpSymFunctionTableAccess64)
151 ::GetProcAddress(hLib, "SymFunctionTableAccess64");
153 return StackWalk64 != NULL;
155 #endif // !defined(__MINGW64_VERSION_MAJOR)
156 #endif // __MINGW32__
159 static LONG WINAPI LLVMUnhandledExceptionFilter(LPEXCEPTION_POINTERS ep);
160 static BOOL WINAPI LLVMConsoleCtrlHandler(DWORD dwCtrlType);
162 // InterruptFunction - The function to call if ctrl-c is pressed.
163 static void (*InterruptFunction)() = 0;
165 static std::vector<std::string> *FilesToRemove = NULL;
166 static std::vector<std::pair<void(*)(void*), void*> > *CallBacksToRun = 0;
167 static bool RegisteredUnhandledExceptionFilter = false;
168 static bool CleanupExecuted = 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 LLVM_ATTRIBUTE_UNUSED int
188 AvoidMessageBoxHook(int ReportType, char *Message, int *Return) {
189 // Set *Return to the retry code for the return value of _CrtDbgReport:
190 // http://msdn.microsoft.com/en-us/library/8hyw4sy7(v=vs.71).aspx
191 // This may also trigger just-in-time debugging via DebugBreak().
194 // Don't call _CrtDbgReport.
200 extern "C" void HandleAbort(int Sig) {
201 if (Sig == SIGABRT) {
206 static void RegisterHandler() {
207 #if __MINGW32__ && !defined(__MINGW64_VERSION_MAJOR)
208 // On MinGW.org, we need to load up the symbols explicitly, because the
209 // Win32 framework they include does not have support for the 64-bit
210 // versions of the APIs we need. If we cannot load up the APIs (which
211 // would be unexpected as they should exist on every version of Windows
212 // we support), we will bail out since there would be nothing to report.
213 if (!load64BitDebugHelp()) {
214 assert(false && "These APIs should always be available");
219 if (RegisteredUnhandledExceptionFilter) {
220 EnterCriticalSection(&CriticalSection);
224 // Now's the time to create the critical section. This is the first time
225 // through here, and there's only one thread.
226 InitializeCriticalSection(&CriticalSection);
228 // Enter it immediately. Now if someone hits CTRL/C, the console handler
229 // can't proceed until the globals are updated.
230 EnterCriticalSection(&CriticalSection);
232 RegisteredUnhandledExceptionFilter = true;
233 OldFilter = SetUnhandledExceptionFilter(LLVMUnhandledExceptionFilter);
234 SetConsoleCtrlHandler(LLVMConsoleCtrlHandler, TRUE);
236 // IMPORTANT NOTE: Caller must call LeaveCriticalSection(&CriticalSection) or
237 // else multi-threading problems will ensue.
240 // RemoveFileOnSignal - The public API
241 bool sys::RemoveFileOnSignal(StringRef Filename, std::string* ErrMsg) {
244 if (CleanupExecuted) {
246 *ErrMsg = "Process terminating -- cannot register for removal";
250 if (FilesToRemove == NULL)
251 FilesToRemove = new std::vector<std::string>;
253 FilesToRemove->push_back(Filename);
255 LeaveCriticalSection(&CriticalSection);
259 // DontRemoveFileOnSignal - The public API
260 void sys::DontRemoveFileOnSignal(StringRef Filename) {
261 if (FilesToRemove == NULL)
266 FilesToRemove->push_back(Filename);
267 std::vector<std::string>::reverse_iterator I =
268 std::find(FilesToRemove->rbegin(), FilesToRemove->rend(), Filename);
269 if (I != FilesToRemove->rend())
270 FilesToRemove->erase(I.base()-1);
272 LeaveCriticalSection(&CriticalSection);
275 void sys::DisableSystemDialogsOnCrash() {
276 // Crash to stack trace handler on abort.
277 signal(SIGABRT, HandleAbort);
279 // The following functions are not reliably accessible on MinGW.
281 // We're already handling writing a "something went wrong" message.
282 _set_abort_behavior(0, _WRITE_ABORT_MSG);
283 // Disable Dr. Watson.
284 _set_abort_behavior(0, _CALL_REPORTFAULT);
285 _CrtSetReportHook(AvoidMessageBoxHook);
288 // Disable standard error dialog box.
289 SetErrorMode(SEM_FAILCRITICALERRORS | SEM_NOGPFAULTERRORBOX |
290 SEM_NOOPENFILEERRORBOX);
291 _set_error_mode(_OUT_TO_STDERR);
294 /// PrintStackTraceOnErrorSignal - When an error signal (such as SIBABRT or
295 /// SIGSEGV) is delivered to the process, print a stack trace and then exit.
296 void sys::PrintStackTraceOnErrorSignal() {
297 DisableSystemDialogsOnCrash();
299 LeaveCriticalSection(&CriticalSection);
302 void llvm::sys::PrintStackTrace(FILE *) {
307 void sys::SetInterruptFunction(void (*IF)()) {
309 InterruptFunction = IF;
310 LeaveCriticalSection(&CriticalSection);
314 /// AddSignalHandler - Add a function to be called when a signal is delivered
315 /// to the process. The handler can have a cookie passed to it to identify
316 /// what instance of the handler it is.
317 void sys::AddSignalHandler(void (*FnPtr)(void *), void *Cookie) {
318 if (CallBacksToRun == 0)
319 CallBacksToRun = new std::vector<std::pair<void(*)(void*), void*> >();
320 CallBacksToRun->push_back(std::make_pair(FnPtr, Cookie));
322 LeaveCriticalSection(&CriticalSection);
326 static void Cleanup() {
327 EnterCriticalSection(&CriticalSection);
329 // Prevent other thread from registering new files and directories for
330 // removal, should we be executing because of the console handler callback.
331 CleanupExecuted = true;
333 // FIXME: open files cannot be deleted.
335 if (FilesToRemove != NULL)
336 while (!FilesToRemove->empty()) {
337 llvm::sys::fs::remove(FilesToRemove->back());
338 FilesToRemove->pop_back();
342 for (unsigned i = 0, e = CallBacksToRun->size(); i != e; ++i)
343 (*CallBacksToRun)[i].first((*CallBacksToRun)[i].second);
345 LeaveCriticalSection(&CriticalSection);
348 void llvm::sys::RunInterruptHandlers() {
352 static LONG WINAPI LLVMUnhandledExceptionFilter(LPEXCEPTION_POINTERS ep) {
355 // Initialize the STACKFRAME structure.
356 STACKFRAME64 StackFrame;
357 memset(&StackFrame, 0, sizeof(StackFrame));
361 machineType = IMAGE_FILE_MACHINE_AMD64;
362 StackFrame.AddrPC.Offset = ep->ContextRecord->Rip;
363 StackFrame.AddrPC.Mode = AddrModeFlat;
364 StackFrame.AddrStack.Offset = ep->ContextRecord->Rsp;
365 StackFrame.AddrStack.Mode = AddrModeFlat;
366 StackFrame.AddrFrame.Offset = ep->ContextRecord->Rbp;
367 StackFrame.AddrFrame.Mode = AddrModeFlat;
368 #elif defined(_M_IX86)
369 machineType = IMAGE_FILE_MACHINE_I386;
370 StackFrame.AddrPC.Offset = ep->ContextRecord->Eip;
371 StackFrame.AddrPC.Mode = AddrModeFlat;
372 StackFrame.AddrStack.Offset = ep->ContextRecord->Esp;
373 StackFrame.AddrStack.Mode = AddrModeFlat;
374 StackFrame.AddrFrame.Offset = ep->ContextRecord->Ebp;
375 StackFrame.AddrFrame.Mode = AddrModeFlat;
378 HANDLE hProcess = GetCurrentProcess();
379 HANDLE hThread = GetCurrentThread();
381 // Initialize the symbol handler.
382 SymSetOptions(SYMOPT_DEFERRED_LOADS|SYMOPT_LOAD_LINES);
383 SymInitialize(hProcess, NULL, TRUE);
386 if (!StackWalk64(machineType, hProcess, hThread, &StackFrame,
387 ep->ContextRecord, NULL, SymFunctionTableAccess64,
388 SymGetModuleBase64, NULL)) {
392 if (StackFrame.AddrFrame.Offset == 0)
395 // Print the PC in hexadecimal.
396 DWORD64 PC = StackFrame.AddrPC.Offset;
398 fprintf(stderr, "0x%016llX", PC);
399 #elif defined(_M_IX86)
400 fprintf(stderr, "0x%08lX", static_cast<DWORD>(PC));
403 // Print the parameters. Assume there are four.
405 fprintf(stderr, " (0x%016llX 0x%016llX 0x%016llX 0x%016llX)",
406 StackFrame.Params[0],
407 StackFrame.Params[1],
408 StackFrame.Params[2],
409 StackFrame.Params[3]);
410 #elif defined(_M_IX86)
411 fprintf(stderr, " (0x%08lX 0x%08lX 0x%08lX 0x%08lX)",
412 static_cast<DWORD>(StackFrame.Params[0]),
413 static_cast<DWORD>(StackFrame.Params[1]),
414 static_cast<DWORD>(StackFrame.Params[2]),
415 static_cast<DWORD>(StackFrame.Params[3]));
417 // Verify the PC belongs to a module in this process.
418 if (!SymGetModuleBase64(hProcess, PC)) {
419 fputs(" <unknown module>\n", stderr);
423 // Print the symbol name.
425 IMAGEHLP_SYMBOL64 *symbol = reinterpret_cast<IMAGEHLP_SYMBOL64 *>(buffer);
426 memset(symbol, 0, sizeof(IMAGEHLP_SYMBOL64));
427 symbol->SizeOfStruct = sizeof(IMAGEHLP_SYMBOL64);
428 symbol->MaxNameLength = 512 - sizeof(IMAGEHLP_SYMBOL64);
431 if (!SymGetSymFromAddr64(hProcess, PC, &dwDisp, symbol)) {
438 fprintf(stderr, ", %s() + 0x%llX bytes(s)", symbol->Name, dwDisp);
440 fprintf(stderr, ", %s", symbol->Name);
442 // Print the source file and line number information.
443 IMAGEHLP_LINE64 line;
445 memset(&line, 0, sizeof(line));
446 line.SizeOfStruct = sizeof(line);
447 if (SymGetLineFromAddr64(hProcess, PC, &dwLineDisp, &line)) {
448 fprintf(stderr, ", %s, line %lu", line.FileName, line.LineNumber);
450 fprintf(stderr, " + 0x%lX byte(s)", dwLineDisp);
456 _exit(ep->ExceptionRecord->ExceptionCode);
459 static BOOL WINAPI LLVMConsoleCtrlHandler(DWORD dwCtrlType) {
460 // We are running in our very own thread, courtesy of Windows.
461 EnterCriticalSection(&CriticalSection);
464 // If an interrupt function has been set, go and run one it; otherwise,
466 void (*IF)() = InterruptFunction;
467 InterruptFunction = 0; // Don't run it on another CTRL-C.
470 // Note: if the interrupt function throws an exception, there is nothing
471 // to catch it in this thread so it will kill the process.
473 LeaveCriticalSection(&CriticalSection);
474 return TRUE; // Don't kill the process.
477 // Allow normal processing to take place; i.e., the process dies.
478 LeaveCriticalSection(&CriticalSection);
483 // We turned these warnings off for this file so that MinGW-g++ doesn't
484 // complain about the ll format specifiers used. Now we are turning the
485 // warnings back on. If MinGW starts to support diagnostic stacks, we can
486 // replace this with a pop.
487 #pragma GCC diagnostic warning "-Wformat"
488 #pragma GCC diagnostic warning "-Wformat-extra-args"