[Windows] Implement PrintStackTrace(FILE*)
[oota-llvm.git] / lib / Support / Windows / Signals.inc
1 //===- Win32/Signals.cpp - Win32 Signals Implementation ---------*- C++ -*-===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file provides the Win32 specific implementation of the Signals class.
11 //
12 //===----------------------------------------------------------------------===//
13 #include "llvm/Support/FileSystem.h"
14 #include <algorithm>
15 #include <signal.h>
16 #include <stdio.h>
17 #include <vector>
18
19 // The Windows.h header must be after LLVM and standard headers.
20 #include "WindowsSupport.h"
21
22 #ifdef __MINGW32__
23  #include <imagehlp.h>
24 #else
25  #include <dbghelp.h>
26 #endif
27 #include <psapi.h>
28
29 #ifdef _MSC_VER
30  #pragma comment(lib, "psapi.lib")
31  #pragma comment(lib, "dbghelp.lib")
32 #elif __MINGW32__
33  #if ((HAVE_LIBIMAGEHLP != 1) || (HAVE_LIBPSAPI != 1))
34   #error "libimagehlp.a & libpsapi.a should be present"
35  #endif
36  // The version of g++ that comes with MinGW does *not* properly understand
37  // the ll format specifier for printf. However, MinGW passes the format
38  // specifiers on to the MSVCRT entirely, and the CRT understands the ll
39  // specifier. So these warnings are spurious in this case. Since we compile
40  // with -Wall, this will generate these warnings which should be ignored. So
41  // we will turn off the warnings for this just file. However, MinGW also does
42  // not support push and pop for diagnostics, so we have to manually turn it
43  // back on at the end of the file.
44  #pragma GCC diagnostic ignored "-Wformat"
45  #pragma GCC diagnostic ignored "-Wformat-extra-args"
46
47  #if !defined(__MINGW64_VERSION_MAJOR)
48  // MinGW.org does not have updated support for the 64-bit versions of the
49  // DebugHlp APIs. So we will have to load them manually. The structures and
50  // method signatures were pulled from DbgHelp.h in the Windows Platform SDK,
51  // and adjusted for brevity.
52  typedef struct _IMAGEHLP_LINE64 {
53    DWORD    SizeOfStruct;
54    PVOID    Key;
55    DWORD    LineNumber;
56    PCHAR    FileName;
57    DWORD64  Address;
58  } IMAGEHLP_LINE64, *PIMAGEHLP_LINE64;
59
60  typedef struct _IMAGEHLP_SYMBOL64 {
61    DWORD   SizeOfStruct;
62    DWORD64 Address;
63    DWORD   Size;
64    DWORD   Flags;
65    DWORD   MaxNameLength;
66    CHAR    Name[1];
67  } IMAGEHLP_SYMBOL64, *PIMAGEHLP_SYMBOL64;
68
69  typedef struct _tagADDRESS64 {
70    DWORD64       Offset;
71    WORD          Segment;
72    ADDRESS_MODE  Mode;
73  } ADDRESS64, *LPADDRESS64;
74
75  typedef struct _KDHELP64 {
76    DWORD64   Thread;
77    DWORD   ThCallbackStack;
78    DWORD   ThCallbackBStore;
79    DWORD   NextCallback;
80    DWORD   FramePointer;
81    DWORD64   KiCallUserMode;
82    DWORD64   KeUserCallbackDispatcher;
83    DWORD64   SystemRangeStart;
84    DWORD64   KiUserExceptionDispatcher;
85    DWORD64   StackBase;
86    DWORD64   StackLimit;
87    DWORD64   Reserved[5];
88  } KDHELP64, *PKDHELP64;
89
90  typedef struct _tagSTACKFRAME64 {
91    ADDRESS64   AddrPC;
92    ADDRESS64   AddrReturn;
93    ADDRESS64   AddrFrame;
94    ADDRESS64   AddrStack;
95    ADDRESS64   AddrBStore;
96    PVOID       FuncTableEntry;
97    DWORD64     Params[4];
98    BOOL        Far;
99    BOOL        Virtual;
100    DWORD64     Reserved[3];
101    KDHELP64    KdHelp;
102  } STACKFRAME64, *LPSTACKFRAME64;
103
104 typedef BOOL (__stdcall *PREAD_PROCESS_MEMORY_ROUTINE64)(HANDLE hProcess,
105                       DWORD64 qwBaseAddress, PVOID lpBuffer, DWORD nSize,
106                       LPDWORD lpNumberOfBytesRead);
107
108 typedef PVOID (__stdcall *PFUNCTION_TABLE_ACCESS_ROUTINE64)( HANDLE ahProcess,
109                       DWORD64 AddrBase);
110
111 typedef DWORD64 (__stdcall *PGET_MODULE_BASE_ROUTINE64)(HANDLE hProcess,
112                       DWORD64 Address);
113
114 typedef DWORD64 (__stdcall *PTRANSLATE_ADDRESS_ROUTINE64)(HANDLE hProcess,
115                       HANDLE hThread, LPADDRESS64 lpaddr);
116
117 typedef BOOL (WINAPI *fpStackWalk64)(DWORD, HANDLE, HANDLE, LPSTACKFRAME64,
118                       PVOID, PREAD_PROCESS_MEMORY_ROUTINE64,
119                       PFUNCTION_TABLE_ACCESS_ROUTINE64,
120                       PGET_MODULE_BASE_ROUTINE64,
121                       PTRANSLATE_ADDRESS_ROUTINE64);
122 static fpStackWalk64 StackWalk64;
123
124 typedef DWORD64 (WINAPI *fpSymGetModuleBase64)(HANDLE, DWORD64);
125 static fpSymGetModuleBase64 SymGetModuleBase64;
126
127 typedef BOOL (WINAPI *fpSymGetSymFromAddr64)(HANDLE, DWORD64,
128                       PDWORD64, PIMAGEHLP_SYMBOL64);
129 static fpSymGetSymFromAddr64 SymGetSymFromAddr64;
130
131 typedef BOOL (WINAPI *fpSymGetLineFromAddr64)(HANDLE, DWORD64,
132                       PDWORD, PIMAGEHLP_LINE64);
133 static fpSymGetLineFromAddr64 SymGetLineFromAddr64;
134
135 typedef PVOID (WINAPI *fpSymFunctionTableAccess64)(HANDLE, DWORD64);
136 static fpSymFunctionTableAccess64 SymFunctionTableAccess64;
137
138 static bool load64BitDebugHelp(void) {
139   HMODULE hLib = ::LoadLibraryW(L"Dbghelp.dll");
140   if (hLib) {
141     StackWalk64 = (fpStackWalk64)
142                       ::GetProcAddress(hLib, "StackWalk64");
143     SymGetModuleBase64 = (fpSymGetModuleBase64)
144                       ::GetProcAddress(hLib, "SymGetModuleBase64");
145     SymGetSymFromAddr64 = (fpSymGetSymFromAddr64)
146                       ::GetProcAddress(hLib, "SymGetSymFromAddr64");
147     SymGetLineFromAddr64 = (fpSymGetLineFromAddr64)
148                       ::GetProcAddress(hLib, "SymGetLineFromAddr64");
149     SymFunctionTableAccess64 = (fpSymFunctionTableAccess64)
150                      ::GetProcAddress(hLib, "SymFunctionTableAccess64");
151   }
152   return StackWalk64 != NULL;
153 }
154  #endif // !defined(__MINGW64_VERSION_MAJOR)
155 #endif // __MINGW32__
156
157 // Forward declare.
158 static LONG WINAPI LLVMUnhandledExceptionFilter(LPEXCEPTION_POINTERS ep);
159 static BOOL WINAPI LLVMConsoleCtrlHandler(DWORD dwCtrlType);
160
161 // InterruptFunction - The function to call if ctrl-c is pressed.
162 static void (*InterruptFunction)() = 0;
163
164 static std::vector<std::string> *FilesToRemove = NULL;
165 static std::vector<std::pair<void(*)(void*), void*> > *CallBacksToRun = 0;
166 static bool RegisteredUnhandledExceptionFilter = false;
167 static bool CleanupExecuted = false;
168 static PTOP_LEVEL_EXCEPTION_FILTER OldFilter = NULL;
169
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;
174
175 static void PrintStackTraceForThread(FILE *File, HANDLE hProcess,
176                                      HANDLE hThread, STACKFRAME64 &StackFrame,
177                                      CONTEXT *Context) {
178   DWORD machineType;
179 #if defined(_M_X64)
180   machineType = IMAGE_FILE_MACHINE_AMD64;
181 #else
182   machineType = IMAGE_FILE_MACHINE_I386;
183 #endif
184
185   // Initialize the symbol handler.
186   SymSetOptions(SYMOPT_DEFERRED_LOADS | SYMOPT_LOAD_LINES);
187   SymInitialize(hProcess, NULL, TRUE);
188
189   while (true) {
190     if (!StackWalk64(machineType, hProcess, hThread, &StackFrame, Context, NULL,
191                      SymFunctionTableAccess64, SymGetModuleBase64, NULL)) {
192       break;
193     }
194
195     if (StackFrame.AddrFrame.Offset == 0)
196       break;
197
198     // Print the PC in hexadecimal.
199     DWORD64 PC = StackFrame.AddrPC.Offset;
200 #if defined(_M_X64)
201     fprintf(File, "0x%016llX", PC);
202 #elif defined(_M_IX86)
203     fprintf(File, "0x%08lX", static_cast<DWORD>(PC));
204 #endif
205
206 // Print the parameters.  Assume there are four.
207 #if defined(_M_X64)
208     fprintf(File, " (0x%016llX 0x%016llX 0x%016llX 0x%016llX)",
209             StackFrame.Params[0], StackFrame.Params[1], StackFrame.Params[2],
210             StackFrame.Params[3]);
211 #elif defined(_M_IX86)
212     fprintf(File, " (0x%08lX 0x%08lX 0x%08lX 0x%08lX)",
213             static_cast<DWORD>(StackFrame.Params[0]),
214             static_cast<DWORD>(StackFrame.Params[1]),
215             static_cast<DWORD>(StackFrame.Params[2]),
216             static_cast<DWORD>(StackFrame.Params[3]));
217 #endif
218     // Verify the PC belongs to a module in this process.
219     if (!SymGetModuleBase64(hProcess, PC)) {
220       fputs(" <unknown module>\n", File);
221       continue;
222     }
223
224     // Print the symbol name.
225     char buffer[512];
226     IMAGEHLP_SYMBOL64 *symbol = reinterpret_cast<IMAGEHLP_SYMBOL64 *>(buffer);
227     memset(symbol, 0, sizeof(IMAGEHLP_SYMBOL64));
228     symbol->SizeOfStruct = sizeof(IMAGEHLP_SYMBOL64);
229     symbol->MaxNameLength = 512 - sizeof(IMAGEHLP_SYMBOL64);
230
231     DWORD64 dwDisp;
232     if (!SymGetSymFromAddr64(hProcess, PC, &dwDisp, symbol)) {
233       fputc('\n', File);
234       continue;
235     }
236
237     buffer[511] = 0;
238     if (dwDisp > 0)
239       fprintf(File, ", %s() + 0x%llX bytes(s)", symbol->Name, dwDisp);
240     else
241       fprintf(File, ", %s", symbol->Name);
242
243     // Print the source file and line number information.
244     IMAGEHLP_LINE64 line;
245     DWORD dwLineDisp;
246     memset(&line, 0, sizeof(line));
247     line.SizeOfStruct = sizeof(line);
248     if (SymGetLineFromAddr64(hProcess, PC, &dwLineDisp, &line)) {
249       fprintf(File, ", %s, line %lu", line.FileName, line.LineNumber);
250       if (dwLineDisp > 0)
251         fprintf(File, " + 0x%lX byte(s)", dwLineDisp);
252     }
253
254     fputc('\n', File);
255   }
256 }
257
258 namespace llvm {
259
260 //===----------------------------------------------------------------------===//
261 //=== WARNING: Implementation here must contain only Win32 specific code
262 //===          and must not be UNIX code
263 //===----------------------------------------------------------------------===//
264
265 #ifdef _MSC_VER
266 /// AvoidMessageBoxHook - Emulates hitting "retry" from an "abort, retry,
267 /// ignore" CRT debug report dialog.  "retry" raises an exception which
268 /// ultimately triggers our stack dumper.
269 static LLVM_ATTRIBUTE_UNUSED int
270 AvoidMessageBoxHook(int ReportType, char *Message, int *Return) {
271   // Set *Return to the retry code for the return value of _CrtDbgReport:
272   // http://msdn.microsoft.com/en-us/library/8hyw4sy7(v=vs.71).aspx
273   // This may also trigger just-in-time debugging via DebugBreak().
274   if (Return)
275     *Return = 1;
276   // Don't call _CrtDbgReport.
277   return TRUE;
278 }
279
280 #endif
281
282 extern "C" void HandleAbort(int Sig) {
283   if (Sig == SIGABRT) {
284     LLVM_BUILTIN_TRAP;
285   }
286 }
287
288 static void RegisterHandler() {
289 #if __MINGW32__ && !defined(__MINGW64_VERSION_MAJOR)
290   // On MinGW.org, we need to load up the symbols explicitly, because the
291   // Win32 framework they include does not have support for the 64-bit
292   // versions of the APIs we need.  If we cannot load up the APIs (which
293   // would be unexpected as they should exist on every version of Windows
294   // we support), we will bail out since there would be nothing to report.
295   if (!load64BitDebugHelp()) {
296     assert(false && "These APIs should always be available");
297     return;
298   }
299 #endif
300
301   if (RegisteredUnhandledExceptionFilter) {
302     EnterCriticalSection(&CriticalSection);
303     return;
304   }
305
306   // Now's the time to create the critical section.  This is the first time
307   // through here, and there's only one thread.
308   InitializeCriticalSection(&CriticalSection);
309
310   // Enter it immediately.  Now if someone hits CTRL/C, the console handler
311   // can't proceed until the globals are updated.
312   EnterCriticalSection(&CriticalSection);
313
314   RegisteredUnhandledExceptionFilter = true;
315   OldFilter = SetUnhandledExceptionFilter(LLVMUnhandledExceptionFilter);
316   SetConsoleCtrlHandler(LLVMConsoleCtrlHandler, TRUE);
317
318   // IMPORTANT NOTE: Caller must call LeaveCriticalSection(&CriticalSection) or
319   // else multi-threading problems will ensue.
320 }
321
322 // RemoveFileOnSignal - The public API
323 bool sys::RemoveFileOnSignal(StringRef Filename, std::string* ErrMsg) {
324   RegisterHandler();
325
326   if (CleanupExecuted) {
327     if (ErrMsg)
328       *ErrMsg = "Process terminating -- cannot register for removal";
329     return true;
330   }
331
332   if (FilesToRemove == NULL)
333     FilesToRemove = new std::vector<std::string>;
334
335   FilesToRemove->push_back(Filename);
336
337   LeaveCriticalSection(&CriticalSection);
338   return false;
339 }
340
341 // DontRemoveFileOnSignal - The public API
342 void sys::DontRemoveFileOnSignal(StringRef Filename) {
343   if (FilesToRemove == NULL)
344     return;
345
346   RegisterHandler();
347
348   FilesToRemove->push_back(Filename);
349   std::vector<std::string>::reverse_iterator I =
350   std::find(FilesToRemove->rbegin(), FilesToRemove->rend(), Filename);
351   if (I != FilesToRemove->rend())
352     FilesToRemove->erase(I.base()-1);
353
354   LeaveCriticalSection(&CriticalSection);
355 }
356
357 void sys::DisableSystemDialogsOnCrash() {
358   // Crash to stack trace handler on abort.
359   signal(SIGABRT, HandleAbort);
360
361   // The following functions are not reliably accessible on MinGW.
362 #ifdef _MSC_VER
363   // We're already handling writing a "something went wrong" message.
364   _set_abort_behavior(0, _WRITE_ABORT_MSG);
365   // Disable Dr. Watson.
366   _set_abort_behavior(0, _CALL_REPORTFAULT);
367   _CrtSetReportHook(AvoidMessageBoxHook);
368 #endif
369
370   // Disable standard error dialog box.
371   SetErrorMode(SEM_FAILCRITICALERRORS | SEM_NOGPFAULTERRORBOX |
372                SEM_NOOPENFILEERRORBOX);
373   _set_error_mode(_OUT_TO_STDERR);
374 }
375
376 /// PrintStackTraceOnErrorSignal - When an error signal (such as SIBABRT or
377 /// SIGSEGV) is delivered to the process, print a stack trace and then exit.
378 void sys::PrintStackTraceOnErrorSignal() {
379   DisableSystemDialogsOnCrash();
380   RegisterHandler();
381   LeaveCriticalSection(&CriticalSection);
382 }
383
384 void llvm::sys::PrintStackTrace(FILE *File) {
385
386   STACKFRAME64 StackFrame = {0};
387   CONTEXT Context = {0};
388   ::RtlCaptureContext(&Context);
389 #if defined(_M_X64)
390   StackFrame.AddrPC.Offset = Context.Rip;
391   StackFrame.AddrStack.Offset = Context.Rsp;
392   StackFrame.AddrFrame.Offset = Context.Rbp;
393 #else
394   StackFrame.AddrPC.Offset = Context.Eip;
395   StackFrame.AddrStack.Offset = Context.Esp;
396   StackFrame.AddrFrame.Offset = Context.Ebp;
397 #endif
398   StackFrame.AddrPC.Mode = AddrModeFlat;
399   StackFrame.AddrStack.Mode = AddrModeFlat;
400   StackFrame.AddrFrame.Mode = AddrModeFlat;
401   PrintStackTraceForThread(File, GetCurrentProcess(), GetCurrentThread(),
402                            StackFrame, &Context);
403 }
404
405
406 void sys::SetInterruptFunction(void (*IF)()) {
407   RegisterHandler();
408   InterruptFunction = IF;
409   LeaveCriticalSection(&CriticalSection);
410 }
411
412
413 /// AddSignalHandler - Add a function to be called when a signal is delivered
414 /// to the process.  The handler can have a cookie passed to it to identify
415 /// what instance of the handler it is.
416 void sys::AddSignalHandler(void (*FnPtr)(void *), void *Cookie) {
417   if (CallBacksToRun == 0)
418     CallBacksToRun = new std::vector<std::pair<void(*)(void*), void*> >();
419   CallBacksToRun->push_back(std::make_pair(FnPtr, Cookie));
420   RegisterHandler();
421   LeaveCriticalSection(&CriticalSection);
422 }
423 }
424
425 static void Cleanup() {
426   EnterCriticalSection(&CriticalSection);
427
428   // Prevent other thread from registering new files and directories for
429   // removal, should we be executing because of the console handler callback.
430   CleanupExecuted = true;
431
432   // FIXME: open files cannot be deleted.
433
434   if (FilesToRemove != NULL)
435     while (!FilesToRemove->empty()) {
436       llvm::sys::fs::remove(FilesToRemove->back());
437       FilesToRemove->pop_back();
438     }
439
440   if (CallBacksToRun)
441     for (unsigned i = 0, e = CallBacksToRun->size(); i != e; ++i)
442       (*CallBacksToRun)[i].first((*CallBacksToRun)[i].second);
443
444   LeaveCriticalSection(&CriticalSection);
445 }
446
447 void llvm::sys::RunInterruptHandlers() {
448   Cleanup();
449 }
450
451 static LONG WINAPI LLVMUnhandledExceptionFilter(LPEXCEPTION_POINTERS ep) {
452   Cleanup();
453
454   // Initialize the STACKFRAME structure.
455   STACKFRAME64 StackFrame;
456   memset(&StackFrame, 0, sizeof(StackFrame));
457
458 #if defined(_M_X64)
459   StackFrame.AddrPC.Offset = ep->ContextRecord->Rip;
460   StackFrame.AddrPC.Mode = AddrModeFlat;
461   StackFrame.AddrStack.Offset = ep->ContextRecord->Rsp;
462   StackFrame.AddrStack.Mode = AddrModeFlat;
463   StackFrame.AddrFrame.Offset = ep->ContextRecord->Rbp;
464   StackFrame.AddrFrame.Mode = AddrModeFlat;
465 #elif defined(_M_IX86)
466   StackFrame.AddrPC.Offset = ep->ContextRecord->Eip;
467   StackFrame.AddrPC.Mode = AddrModeFlat;
468   StackFrame.AddrStack.Offset = ep->ContextRecord->Esp;
469   StackFrame.AddrStack.Mode = AddrModeFlat;
470   StackFrame.AddrFrame.Offset = ep->ContextRecord->Ebp;
471   StackFrame.AddrFrame.Mode = AddrModeFlat;
472 #endif
473
474   HANDLE hProcess = GetCurrentProcess();
475   HANDLE hThread = GetCurrentThread();
476   PrintStackTraceForThread(stderr, hProcess, hThread, StackFrame,
477                            ep->ContextRecord);
478
479   _exit(ep->ExceptionRecord->ExceptionCode);
480 }
481
482 static BOOL WINAPI LLVMConsoleCtrlHandler(DWORD dwCtrlType) {
483   // We are running in our very own thread, courtesy of Windows.
484   EnterCriticalSection(&CriticalSection);
485   Cleanup();
486
487   // If an interrupt function has been set, go and run one it; otherwise,
488   // the process dies.
489   void (*IF)() = InterruptFunction;
490   InterruptFunction = 0;      // Don't run it on another CTRL-C.
491
492   if (IF) {
493     // Note: if the interrupt function throws an exception, there is nothing
494     // to catch it in this thread so it will kill the process.
495     IF();                     // Run it now.
496     LeaveCriticalSection(&CriticalSection);
497     return TRUE;              // Don't kill the process.
498   }
499
500   // Allow normal processing to take place; i.e., the process dies.
501   LeaveCriticalSection(&CriticalSection);
502   return FALSE;
503 }
504
505 #if __MINGW32__
506  // We turned these warnings off for this file so that MinGW-g++ doesn't
507  // complain about the ll format specifiers used.  Now we are turning the
508  // warnings back on.  If MinGW starts to support diagnostic stacks, we can
509  // replace this with a pop.
510  #pragma GCC diagnostic warning "-Wformat"
511  #pragma GCC diagnostic warning "-Wformat-extra-args"
512 #endif