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