Signals.inc revision 251662
1166124Srafan//===- Win32/Signals.cpp - Win32 Signals Implementation ---------*- C++ -*-===//
2174993Srafan//
3166124Srafan//                     The LLVM Compiler Infrastructure
4166124Srafan//
5166124Srafan// This file is distributed under the University of Illinois Open Source
6166124Srafan// License. See LICENSE.TXT for details.
7166124Srafan//
8166124Srafan//===----------------------------------------------------------------------===//
9166124Srafan//
10166124Srafan// This file provides the Win32 specific implementation of the Signals class.
11166124Srafan//
12166124Srafan//===----------------------------------------------------------------------===//
13166124Srafan
14166124Srafan#include "Windows.h"
15166124Srafan#include <algorithm>
16166124Srafan#include <stdio.h>
17166124Srafan#include <vector>
18166124Srafan
19166124Srafan#ifdef __MINGW32__
20166124Srafan #include <imagehlp.h>
21166124Srafan#else
22166124Srafan #include <dbghelp.h>
23166124Srafan#endif
24166124Srafan#include <psapi.h>
25166124Srafan
26166124Srafan#ifdef _MSC_VER
27166124Srafan #pragma comment(lib, "psapi.lib")
28174993Srafan #pragma comment(lib, "dbghelp.lib")
29174993Srafan#elif __MINGW32__
30174993Srafan #if ((HAVE_LIBIMAGEHLP != 1) || (HAVE_LIBPSAPI != 1))
31174993Srafan  #error "libimagehlp.a & libpsapi.a should be present"
32174993Srafan #endif
33174993Srafan // The version of g++ that comes with MinGW does *not* properly understand
34174993Srafan // the ll format specifier for printf. However, MinGW passes the format
35174993Srafan // specifiers on to the MSVCRT entirely, and the CRT understands the ll
36174993Srafan // specifier. So these warnings are spurious in this case. Since we compile
37174993Srafan // with -Wall, this will generate these warnings which should be ignored. So
38174993Srafan // we will turn off the warnings for this just file. However, MinGW also does
39174993Srafan // not support push and pop for diagnostics, so we have to manually turn it
40174993Srafan // back on at the end of the file.
41174993Srafan #pragma GCC diagnostic ignored "-Wformat"
42174993Srafan #pragma GCC diagnostic ignored "-Wformat-extra-args"
43174993Srafan
44174993Srafan #if !defined(__MINGW64_VERSION_MAJOR)
45174993Srafan // MinGW.org does not have updated support for the 64-bit versions of the
46174993Srafan // DebugHlp APIs. So we will have to load them manually. The structures and
47174993Srafan // method signatures were pulled from DbgHelp.h in the Windows Platform SDK,
48174993Srafan // and adjusted for brevity.
4950276Speter typedef struct _IMAGEHLP_LINE64 {
50174993Srafan   DWORD    SizeOfStruct;
51174993Srafan   PVOID    Key;
52174993Srafan   DWORD    LineNumber;
53174993Srafan   PCHAR    FileName;
54174993Srafan   DWORD64  Address;
55174993Srafan } IMAGEHLP_LINE64, *PIMAGEHLP_LINE64;
56174993Srafan
57174993Srafan typedef struct _IMAGEHLP_SYMBOL64 {
58174993Srafan   DWORD   SizeOfStruct;
59174993Srafan   DWORD64 Address;
60174993Srafan   DWORD   Size;
6150276Speter   DWORD   Flags;
62174993Srafan   DWORD   MaxNameLength;
63174993Srafan   CHAR    Name[1];
64174993Srafan } IMAGEHLP_SYMBOL64, *PIMAGEHLP_SYMBOL64;
65174993Srafan
66174993Srafan typedef struct _tagADDRESS64 {
67174993Srafan   DWORD64       Offset;
68174993Srafan   WORD          Segment;
6950276Speter   ADDRESS_MODE  Mode;
70174993Srafan } ADDRESS64, *LPADDRESS64;
71174993Srafan
72174993Srafan typedef struct _KDHELP64 {
73174993Srafan   DWORD64   Thread;
74174993Srafan   DWORD   ThCallbackStack;
75174993Srafan   DWORD   ThCallbackBStore;
76174993Srafan   DWORD   NextCallback;
77174993Srafan   DWORD   FramePointer;
78174993Srafan   DWORD64   KiCallUserMode;
79174993Srafan   DWORD64   KeUserCallbackDispatcher;
80174993Srafan   DWORD64   SystemRangeStart;
81174993Srafan   DWORD64   KiUserExceptionDispatcher;
82174993Srafan   DWORD64   StackBase;
83174993Srafan   DWORD64   StackLimit;
84174993Srafan   DWORD64   Reserved[5];
85174993Srafan } KDHELP64, *PKDHELP64;
86174993Srafan
87174993Srafan typedef struct _tagSTACKFRAME64 {
88174993Srafan   ADDRESS64   AddrPC;
89174993Srafan   ADDRESS64   AddrReturn;
90174993Srafan   ADDRESS64   AddrFrame;
91174993Srafan   ADDRESS64   AddrStack;
92174993Srafan   ADDRESS64   AddrBStore;
93174993Srafan   PVOID       FuncTableEntry;
94174993Srafan   DWORD64     Params[4];
95   BOOL        Far;
96   BOOL        Virtual;
97   DWORD64     Reserved[3];
98   KDHELP64    KdHelp;
99 } STACKFRAME64, *LPSTACKFRAME64;
100
101typedef BOOL (__stdcall *PREAD_PROCESS_MEMORY_ROUTINE64)(HANDLE hProcess,
102                      DWORD64 qwBaseAddress, PVOID lpBuffer, DWORD nSize,
103                      LPDWORD lpNumberOfBytesRead);
104
105typedef PVOID (__stdcall *PFUNCTION_TABLE_ACCESS_ROUTINE64)( HANDLE ahProcess,
106                      DWORD64 AddrBase);
107
108typedef DWORD64 (__stdcall *PGET_MODULE_BASE_ROUTINE64)(HANDLE hProcess,
109                      DWORD64 Address);
110
111typedef DWORD64 (__stdcall *PTRANSLATE_ADDRESS_ROUTINE64)(HANDLE hProcess,
112                      HANDLE hThread, LPADDRESS64 lpaddr);
113
114typedef BOOL (WINAPI *fpStackWalk64)(DWORD, HANDLE, HANDLE, LPSTACKFRAME64,
115                      PVOID, PREAD_PROCESS_MEMORY_ROUTINE64,
116                      PFUNCTION_TABLE_ACCESS_ROUTINE64,
117                      PGET_MODULE_BASE_ROUTINE64,
118                      PTRANSLATE_ADDRESS_ROUTINE64);
119static fpStackWalk64 StackWalk64;
120
121typedef DWORD64 (WINAPI *fpSymGetModuleBase64)(HANDLE, DWORD64);
122static fpSymGetModuleBase64 SymGetModuleBase64;
123
124typedef BOOL (WINAPI *fpSymGetSymFromAddr64)(HANDLE, DWORD64,
125                      PDWORD64, PIMAGEHLP_SYMBOL64);
126static fpSymGetSymFromAddr64 SymGetSymFromAddr64;
127
128typedef BOOL (WINAPI *fpSymGetLineFromAddr64)(HANDLE, DWORD64,
129                      PDWORD, PIMAGEHLP_LINE64);
130static fpSymGetLineFromAddr64 SymGetLineFromAddr64;
131
132typedef PVOID (WINAPI *fpSymFunctionTableAccess64)(HANDLE, DWORD64);
133static fpSymFunctionTableAccess64 SymFunctionTableAccess64;
134
135static bool load64BitDebugHelp(void) {
136  HMODULE hLib = ::LoadLibrary("Dbghelp.dll");
137  if (hLib) {
138    StackWalk64 = (fpStackWalk64)
139                      ::GetProcAddress(hLib, "StackWalk64");
140    SymGetModuleBase64 = (fpSymGetModuleBase64)
141                      ::GetProcAddress(hLib, "SymGetModuleBase64");
142    SymGetSymFromAddr64 = (fpSymGetSymFromAddr64)
143                      ::GetProcAddress(hLib, "SymGetSymFromAddr64");
144    SymGetLineFromAddr64 = (fpSymGetLineFromAddr64)
145                      ::GetProcAddress(hLib, "SymGetLineFromAddr64");
146    SymFunctionTableAccess64 = (fpSymFunctionTableAccess64)
147                     ::GetProcAddress(hLib, "SymFunctionTableAccess64");
148  }
149  return StackWalk64 != NULL;
150}
151 #endif // !defined(__MINGW64_VERSION_MAJOR)
152#endif // __MINGW32__
153
154// Forward declare.
155static LONG WINAPI LLVMUnhandledExceptionFilter(LPEXCEPTION_POINTERS ep);
156static BOOL WINAPI LLVMConsoleCtrlHandler(DWORD dwCtrlType);
157
158// InterruptFunction - The function to call if ctrl-c is pressed.
159static void (*InterruptFunction)() = 0;
160
161static std::vector<llvm::sys::Path> *FilesToRemove = NULL;
162static std::vector<std::pair<void(*)(void*), void*> > *CallBacksToRun = 0;
163static bool RegisteredUnhandledExceptionFilter = false;
164static bool CleanupExecuted = false;
165static bool ExitOnUnhandledExceptions = false;
166static PTOP_LEVEL_EXCEPTION_FILTER OldFilter = NULL;
167
168// Windows creates a new thread to execute the console handler when an event
169// (such as CTRL/C) occurs.  This causes concurrency issues with the above
170// globals which this critical section addresses.
171static CRITICAL_SECTION CriticalSection;
172
173namespace llvm {
174
175//===----------------------------------------------------------------------===//
176//=== WARNING: Implementation here must contain only Win32 specific code
177//===          and must not be UNIX code
178//===----------------------------------------------------------------------===//
179
180#ifdef _MSC_VER
181/// AvoidMessageBoxHook - Emulates hitting "retry" from an "abort, retry,
182/// ignore" CRT debug report dialog.  "retry" raises an exception which
183/// ultimately triggers our stack dumper.
184static int AvoidMessageBoxHook(int ReportType, char *Message, int *Return) {
185  // Set *Return to the retry code for the return value of _CrtDbgReport:
186  // http://msdn.microsoft.com/en-us/library/8hyw4sy7(v=vs.71).aspx
187  // This may also trigger just-in-time debugging via DebugBreak().
188  if (Return)
189    *Return = 1;
190  // Don't call _CrtDbgReport.
191  return TRUE;
192}
193
194/// CRTReportHook - Function called on a CRT debugging event.
195static int CRTReportHook(int ReportType, char *Message, int *Return) {
196  // Don't cause a DebugBreak() on return.
197  if (Return)
198    *Return = 0;
199
200  switch (ReportType) {
201  default:
202  case _CRT_ASSERT:
203    fprintf(stderr, "CRT assert: %s\n", Message);
204    // FIXME: Is there a way to just crash? Perhaps throw to the unhandled
205    // exception code? Perhaps SetErrorMode() handles this.
206    _exit(3);
207    break;
208  case _CRT_ERROR:
209    fprintf(stderr, "CRT error: %s\n", Message);
210    // FIXME: Is there a way to just crash? Perhaps throw to the unhandled
211    // exception code? Perhaps SetErrorMode() handles this.
212    _exit(3);
213    break;
214  case _CRT_WARN:
215    fprintf(stderr, "CRT warn: %s\n", Message);
216    break;
217  }
218
219  // Don't call _CrtDbgReport.
220  return TRUE;
221}
222#endif
223
224static void RegisterHandler() {
225#if __MINGW32__ && !defined(__MINGW64_VERSION_MAJOR)
226  // On MinGW.org, we need to load up the symbols explicitly, because the
227  // Win32 framework they include does not have support for the 64-bit
228  // versions of the APIs we need.  If we cannot load up the APIs (which
229  // would be unexpected as they should exist on every version of Windows
230  // we support), we will bail out since there would be nothing to report.
231  if (!load64BitDebugHelp()) {
232    assert(false && "These APIs should always be available");
233    return;
234  }
235#endif
236
237  if (RegisteredUnhandledExceptionFilter) {
238    EnterCriticalSection(&CriticalSection);
239    return;
240  }
241
242  // Now's the time to create the critical section.  This is the first time
243  // through here, and there's only one thread.
244  InitializeCriticalSection(&CriticalSection);
245
246  // Enter it immediately.  Now if someone hits CTRL/C, the console handler
247  // can't proceed until the globals are updated.
248  EnterCriticalSection(&CriticalSection);
249
250  RegisteredUnhandledExceptionFilter = true;
251  OldFilter = SetUnhandledExceptionFilter(LLVMUnhandledExceptionFilter);
252  SetConsoleCtrlHandler(LLVMConsoleCtrlHandler, TRUE);
253
254#ifdef _MSC_VER
255  const char *EnableMsgbox = getenv("LLVM_ENABLE_CRT_REPORT");
256  if (!EnableMsgbox || strcmp("0", EnableMsgbox) == 0) {
257    // Setting a report hook overrides the default behavior of popping an "abort,
258    // retry, or ignore" dialog.
259    _CrtSetReportHook(AvoidMessageBoxHook);
260  }
261#endif
262
263  // Environment variable to disable any kind of crash dialog.
264  if (getenv("LLVM_DISABLE_CRASH_REPORT")) {
265#ifdef _MSC_VER
266    _CrtSetReportHook(CRTReportHook);
267#endif
268    SetErrorMode(SEM_FAILCRITICALERRORS |
269                 SEM_NOGPFAULTERRORBOX |
270                 SEM_NOOPENFILEERRORBOX);
271    ExitOnUnhandledExceptions = true;
272  }
273
274  // IMPORTANT NOTE: Caller must call LeaveCriticalSection(&CriticalSection) or
275  // else multi-threading problems will ensue.
276}
277
278// RemoveFileOnSignal - The public API
279bool sys::RemoveFileOnSignal(const sys::Path &Filename, std::string* ErrMsg) {
280  RegisterHandler();
281
282  if (CleanupExecuted) {
283    if (ErrMsg)
284      *ErrMsg = "Process terminating -- cannot register for removal";
285    return true;
286  }
287
288  if (FilesToRemove == NULL)
289    FilesToRemove = new std::vector<sys::Path>;
290
291  FilesToRemove->push_back(Filename);
292
293  LeaveCriticalSection(&CriticalSection);
294  return false;
295}
296
297// DontRemoveFileOnSignal - The public API
298void sys::DontRemoveFileOnSignal(const sys::Path &Filename) {
299  if (FilesToRemove == NULL)
300    return;
301
302  RegisterHandler();
303
304  FilesToRemove->push_back(Filename);
305  std::vector<sys::Path>::reverse_iterator I =
306  std::find(FilesToRemove->rbegin(), FilesToRemove->rend(), Filename);
307  if (I != FilesToRemove->rend())
308    FilesToRemove->erase(I.base()-1);
309
310  LeaveCriticalSection(&CriticalSection);
311}
312
313/// PrintStackTraceOnErrorSignal - When an error signal (such as SIBABRT or
314/// SIGSEGV) is delivered to the process, print a stack trace and then exit.
315void sys::PrintStackTraceOnErrorSignal() {
316  RegisterHandler();
317  LeaveCriticalSection(&CriticalSection);
318}
319
320void llvm::sys::PrintStackTrace(FILE *) {
321  // FIXME: Implement.
322}
323
324
325void sys::SetInterruptFunction(void (*IF)()) {
326  RegisterHandler();
327  InterruptFunction = IF;
328  LeaveCriticalSection(&CriticalSection);
329}
330
331
332/// AddSignalHandler - Add a function to be called when a signal is delivered
333/// to the process.  The handler can have a cookie passed to it to identify
334/// what instance of the handler it is.
335void sys::AddSignalHandler(void (*FnPtr)(void *), void *Cookie) {
336  if (CallBacksToRun == 0)
337    CallBacksToRun = new std::vector<std::pair<void(*)(void*), void*> >();
338  CallBacksToRun->push_back(std::make_pair(FnPtr, Cookie));
339  RegisterHandler();
340  LeaveCriticalSection(&CriticalSection);
341}
342}
343
344static void Cleanup() {
345  EnterCriticalSection(&CriticalSection);
346
347  // Prevent other thread from registering new files and directories for
348  // removal, should we be executing because of the console handler callback.
349  CleanupExecuted = true;
350
351  // FIXME: open files cannot be deleted.
352
353  if (FilesToRemove != NULL)
354    while (!FilesToRemove->empty()) {
355      FilesToRemove->back().eraseFromDisk();
356      FilesToRemove->pop_back();
357    }
358
359  if (CallBacksToRun)
360    for (unsigned i = 0, e = CallBacksToRun->size(); i != e; ++i)
361      (*CallBacksToRun)[i].first((*CallBacksToRun)[i].second);
362
363  LeaveCriticalSection(&CriticalSection);
364}
365
366void llvm::sys::RunInterruptHandlers() {
367  Cleanup();
368}
369
370static LONG WINAPI LLVMUnhandledExceptionFilter(LPEXCEPTION_POINTERS ep) {
371  Cleanup();
372
373  // Initialize the STACKFRAME structure.
374  STACKFRAME64 StackFrame;
375  memset(&StackFrame, 0, sizeof(StackFrame));
376
377  DWORD machineType;
378#if defined(_M_X64)
379  machineType = IMAGE_FILE_MACHINE_AMD64;
380  StackFrame.AddrPC.Offset = ep->ContextRecord->Rip;
381  StackFrame.AddrPC.Mode = AddrModeFlat;
382  StackFrame.AddrStack.Offset = ep->ContextRecord->Rsp;
383  StackFrame.AddrStack.Mode = AddrModeFlat;
384  StackFrame.AddrFrame.Offset = ep->ContextRecord->Rbp;
385  StackFrame.AddrFrame.Mode = AddrModeFlat;
386#elif defined(_M_IX86)
387  machineType = IMAGE_FILE_MACHINE_I386;
388  StackFrame.AddrPC.Offset = ep->ContextRecord->Eip;
389  StackFrame.AddrPC.Mode = AddrModeFlat;
390  StackFrame.AddrStack.Offset = ep->ContextRecord->Esp;
391  StackFrame.AddrStack.Mode = AddrModeFlat;
392  StackFrame.AddrFrame.Offset = ep->ContextRecord->Ebp;
393  StackFrame.AddrFrame.Mode = AddrModeFlat;
394#endif
395
396  HANDLE hProcess = GetCurrentProcess();
397  HANDLE hThread = GetCurrentThread();
398
399  // Initialize the symbol handler.
400  SymSetOptions(SYMOPT_DEFERRED_LOADS|SYMOPT_LOAD_LINES);
401  SymInitialize(hProcess, NULL, TRUE);
402
403  while (true) {
404    if (!StackWalk64(machineType, hProcess, hThread, &StackFrame,
405                   ep->ContextRecord, NULL, SymFunctionTableAccess64,
406                   SymGetModuleBase64, NULL)) {
407      break;
408    }
409
410    if (StackFrame.AddrFrame.Offset == 0)
411      break;
412
413    // Print the PC in hexadecimal.
414    DWORD64 PC = StackFrame.AddrPC.Offset;
415#if defined(_M_X64)
416    fprintf(stderr, "0x%016llX", PC);
417#elif defined(_M_IX86)
418    fprintf(stderr, "0x%08lX", static_cast<DWORD>(PC));
419#endif
420
421    // Print the parameters.  Assume there are four.
422#if defined(_M_X64)
423    fprintf(stderr, " (0x%016llX 0x%016llX 0x%016llX 0x%016llX)",
424                StackFrame.Params[0],
425                StackFrame.Params[1],
426                StackFrame.Params[2],
427                StackFrame.Params[3]);
428#elif defined(_M_IX86)
429    fprintf(stderr, " (0x%08lX 0x%08lX 0x%08lX 0x%08lX)",
430                static_cast<DWORD>(StackFrame.Params[0]),
431                static_cast<DWORD>(StackFrame.Params[1]),
432                static_cast<DWORD>(StackFrame.Params[2]),
433                static_cast<DWORD>(StackFrame.Params[3]));
434#endif
435    // Verify the PC belongs to a module in this process.
436    if (!SymGetModuleBase64(hProcess, PC)) {
437      fputs(" <unknown module>\n", stderr);
438      continue;
439    }
440
441    // Print the symbol name.
442    char buffer[512];
443    IMAGEHLP_SYMBOL64 *symbol = reinterpret_cast<IMAGEHLP_SYMBOL64 *>(buffer);
444    memset(symbol, 0, sizeof(IMAGEHLP_SYMBOL64));
445    symbol->SizeOfStruct = sizeof(IMAGEHLP_SYMBOL64);
446    symbol->MaxNameLength = 512 - sizeof(IMAGEHLP_SYMBOL64);
447
448    DWORD64 dwDisp;
449    if (!SymGetSymFromAddr64(hProcess, PC, &dwDisp, symbol)) {
450      fputc('\n', stderr);
451      continue;
452    }
453
454    buffer[511] = 0;
455    if (dwDisp > 0)
456      fprintf(stderr, ", %s() + 0x%llX bytes(s)", symbol->Name, dwDisp);
457    else
458      fprintf(stderr, ", %s", symbol->Name);
459
460    // Print the source file and line number information.
461    IMAGEHLP_LINE64 line;
462    DWORD dwLineDisp;
463    memset(&line, 0, sizeof(line));
464    line.SizeOfStruct = sizeof(line);
465    if (SymGetLineFromAddr64(hProcess, PC, &dwLineDisp, &line)) {
466      fprintf(stderr, ", %s, line %lu", line.FileName, line.LineNumber);
467      if (dwLineDisp > 0)
468        fprintf(stderr, " + 0x%lX byte(s)", dwLineDisp);
469    }
470
471    fputc('\n', stderr);
472  }
473
474  if (ExitOnUnhandledExceptions)
475    _exit(ep->ExceptionRecord->ExceptionCode);
476
477  // Allow dialog box to pop up allowing choice to start debugger.
478  if (OldFilter)
479    return (*OldFilter)(ep);
480  else
481    return EXCEPTION_CONTINUE_SEARCH;
482}
483
484static BOOL WINAPI LLVMConsoleCtrlHandler(DWORD dwCtrlType) {
485  // We are running in our very own thread, courtesy of Windows.
486  EnterCriticalSection(&CriticalSection);
487  Cleanup();
488
489  // If an interrupt function has been set, go and run one it; otherwise,
490  // the process dies.
491  void (*IF)() = InterruptFunction;
492  InterruptFunction = 0;      // Don't run it on another CTRL-C.
493
494  if (IF) {
495    // Note: if the interrupt function throws an exception, there is nothing
496    // to catch it in this thread so it will kill the process.
497    IF();                     // Run it now.
498    LeaveCriticalSection(&CriticalSection);
499    return TRUE;              // Don't kill the process.
500  }
501
502  // Allow normal processing to take place; i.e., the process dies.
503  LeaveCriticalSection(&CriticalSection);
504  return FALSE;
505}
506
507#if __MINGW32__
508 // We turned these warnings off for this file so that MinGW-g++ doesn't
509 // complain about the ll format specifiers used.  Now we are turning the
510 // warnings back on.  If MinGW starts to support diagnostic stacks, we can
511 // replace this with a pop.
512 #pragma GCC diagnostic warning "-Wformat"
513 #pragma GCC diagnostic warning "-Wformat-extra-args"
514#endif
515