Signals.inc revision 249423
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
14#include "Windows.h"
15#include <algorithm>
16#include <stdio.h>
17#include <vector>
18
19#ifdef __MINGW32__
20 #include <imagehlp.h>
21#else
22 #include <dbghelp.h>
23#endif
24#include <psapi.h>
25
26#ifdef _MSC_VER
27 #pragma comment(lib, "psapi.lib")
28 #pragma comment(lib, "dbghelp.lib")
29#elif __MINGW32__
30 #if ((HAVE_LIBIMAGEHLP != 1) || (HAVE_LIBPSAPI != 1))
31  #error "libimagehlp.a & libpsapi.a should be present"
32 #endif
33 // The version of g++ that comes with MinGW does *not* properly understand
34 // the ll format specifier for printf. However, MinGW passes the format
35 // specifiers on to the MSVCRT entirely, and the CRT understands the ll
36 // specifier. So these warnings are spurious in this case. Since we compile
37 // with -Wall, this will generate these warnings which should be ignored. So
38 // we will turn off the warnings for this just file. However, MinGW also does
39 // not support push and pop for diagnostics, so we have to manually turn it
40 // back on at the end of the file.
41 #pragma GCC diagnostic ignored "-Wformat"
42 #pragma GCC diagnostic ignored "-Wformat-extra-args"
43
44 #if !defined(__MINGW64_VERSION_MAJOR)
45 // MinGW.org does not have updated support for the 64-bit versions of the
46 // DebugHlp APIs. So we will have to load them manually. The structures and
47 // method signatures were pulled from DbgHelp.h in the Windows Platform SDK,
48 // and adjusted for brevity.
49 typedef struct _IMAGEHLP_LINE64 {
50   DWORD    SizeOfStruct;
51   PVOID    Key;
52   DWORD    LineNumber;
53   PCHAR    FileName;
54   DWORD64  Address;
55 } IMAGEHLP_LINE64, *PIMAGEHLP_LINE64;
56
57 typedef struct _IMAGEHLP_SYMBOL64 {
58   DWORD   SizeOfStruct;
59   DWORD64 Address;
60   DWORD   Size;
61   DWORD   Flags;
62   DWORD   MaxNameLength;
63   CHAR    Name[1];
64 } IMAGEHLP_SYMBOL64, *PIMAGEHLP_SYMBOL64;
65
66 typedef struct _tagADDRESS64 {
67   DWORD64       Offset;
68   WORD          Segment;
69   ADDRESS_MODE  Mode;
70 } ADDRESS64, *LPADDRESS64;
71
72 typedef struct _KDHELP64 {
73   DWORD64   Thread;
74   DWORD   ThCallbackStack;
75   DWORD   ThCallbackBStore;
76   DWORD   NextCallback;
77   DWORD   FramePointer;
78   DWORD64   KiCallUserMode;
79   DWORD64   KeUserCallbackDispatcher;
80   DWORD64   SystemRangeStart;
81   DWORD64   KiUserExceptionDispatcher;
82   DWORD64   StackBase;
83   DWORD64   StackLimit;
84   DWORD64   Reserved[5];
85 } KDHELP64, *PKDHELP64;
86
87 typedef struct _tagSTACKFRAME64 {
88   ADDRESS64   AddrPC;
89   ADDRESS64   AddrReturn;
90   ADDRESS64   AddrFrame;
91   ADDRESS64   AddrStack;
92   ADDRESS64   AddrBStore;
93   PVOID       FuncTableEntry;
94   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/// CRTReportHook - Function called on a CRT debugging event.
182static int CRTReportHook(int ReportType, char *Message, int *Return) {
183  // Don't cause a DebugBreak() on return.
184  if (Return)
185    *Return = 0;
186
187  switch (ReportType) {
188  default:
189  case _CRT_ASSERT:
190    fprintf(stderr, "CRT assert: %s\n", Message);
191    // FIXME: Is there a way to just crash? Perhaps throw to the unhandled
192    // exception code? Perhaps SetErrorMode() handles this.
193    _exit(3);
194    break;
195  case _CRT_ERROR:
196    fprintf(stderr, "CRT error: %s\n", Message);
197    // FIXME: Is there a way to just crash? Perhaps throw to the unhandled
198    // exception code? Perhaps SetErrorMode() handles this.
199    _exit(3);
200    break;
201  case _CRT_WARN:
202    fprintf(stderr, "CRT warn: %s\n", Message);
203    break;
204  }
205
206  // Don't call _CrtDbgReport.
207  return TRUE;
208}
209#endif
210
211static void RegisterHandler() {
212#if __MINGW32__ && !defined(__MINGW64_VERSION_MAJOR)
213  // On MinGW.org, we need to load up the symbols explicitly, because the
214  // Win32 framework they include does not have support for the 64-bit
215  // versions of the APIs we need.  If we cannot load up the APIs (which
216  // would be unexpected as they should exist on every version of Windows
217  // we support), we will bail out since there would be nothing to report.
218  if (!load64BitDebugHelp()) {
219    assert(false && "These APIs should always be available");
220    return;
221  }
222#endif
223
224  if (RegisteredUnhandledExceptionFilter) {
225    EnterCriticalSection(&CriticalSection);
226    return;
227  }
228
229  // Now's the time to create the critical section.  This is the first time
230  // through here, and there's only one thread.
231  InitializeCriticalSection(&CriticalSection);
232
233  // Enter it immediately.  Now if someone hits CTRL/C, the console handler
234  // can't proceed until the globals are updated.
235  EnterCriticalSection(&CriticalSection);
236
237  RegisteredUnhandledExceptionFilter = true;
238  OldFilter = SetUnhandledExceptionFilter(LLVMUnhandledExceptionFilter);
239  SetConsoleCtrlHandler(LLVMConsoleCtrlHandler, TRUE);
240
241  // Environment variable to disable any kind of crash dialog.
242  if (getenv("LLVM_DISABLE_CRASH_REPORT")) {
243#ifdef _MSC_VER
244    _CrtSetReportHook(CRTReportHook);
245#endif
246    SetErrorMode(SEM_FAILCRITICALERRORS |
247                 SEM_NOGPFAULTERRORBOX |
248                 SEM_NOOPENFILEERRORBOX);
249    ExitOnUnhandledExceptions = true;
250  }
251
252  // IMPORTANT NOTE: Caller must call LeaveCriticalSection(&CriticalSection) or
253  // else multi-threading problems will ensue.
254}
255
256// RemoveFileOnSignal - The public API
257bool sys::RemoveFileOnSignal(const sys::Path &Filename, std::string* ErrMsg) {
258  RegisterHandler();
259
260  if (CleanupExecuted) {
261    if (ErrMsg)
262      *ErrMsg = "Process terminating -- cannot register for removal";
263    return true;
264  }
265
266  if (FilesToRemove == NULL)
267    FilesToRemove = new std::vector<sys::Path>;
268
269  FilesToRemove->push_back(Filename);
270
271  LeaveCriticalSection(&CriticalSection);
272  return false;
273}
274
275// DontRemoveFileOnSignal - The public API
276void sys::DontRemoveFileOnSignal(const sys::Path &Filename) {
277  if (FilesToRemove == NULL)
278    return;
279
280  RegisterHandler();
281
282  FilesToRemove->push_back(Filename);
283  std::vector<sys::Path>::reverse_iterator I =
284  std::find(FilesToRemove->rbegin(), FilesToRemove->rend(), Filename);
285  if (I != FilesToRemove->rend())
286    FilesToRemove->erase(I.base()-1);
287
288  LeaveCriticalSection(&CriticalSection);
289}
290
291/// PrintStackTraceOnErrorSignal - When an error signal (such as SIBABRT or
292/// SIGSEGV) is delivered to the process, print a stack trace and then exit.
293void sys::PrintStackTraceOnErrorSignal() {
294  RegisterHandler();
295  LeaveCriticalSection(&CriticalSection);
296}
297
298void llvm::sys::PrintStackTrace(FILE *) {
299  // FIXME: Implement.
300}
301
302
303void sys::SetInterruptFunction(void (*IF)()) {
304  RegisterHandler();
305  InterruptFunction = IF;
306  LeaveCriticalSection(&CriticalSection);
307}
308
309
310/// AddSignalHandler - Add a function to be called when a signal is delivered
311/// to the process.  The handler can have a cookie passed to it to identify
312/// what instance of the handler it is.
313void sys::AddSignalHandler(void (*FnPtr)(void *), void *Cookie) {
314  if (CallBacksToRun == 0)
315    CallBacksToRun = new std::vector<std::pair<void(*)(void*), void*> >();
316  CallBacksToRun->push_back(std::make_pair(FnPtr, Cookie));
317  RegisterHandler();
318  LeaveCriticalSection(&CriticalSection);
319}
320}
321
322static void Cleanup() {
323  EnterCriticalSection(&CriticalSection);
324
325  // Prevent other thread from registering new files and directories for
326  // removal, should we be executing because of the console handler callback.
327  CleanupExecuted = true;
328
329  // FIXME: open files cannot be deleted.
330
331  if (FilesToRemove != NULL)
332    while (!FilesToRemove->empty()) {
333      FilesToRemove->back().eraseFromDisk();
334      FilesToRemove->pop_back();
335    }
336
337  if (CallBacksToRun)
338    for (unsigned i = 0, e = CallBacksToRun->size(); i != e; ++i)
339      (*CallBacksToRun)[i].first((*CallBacksToRun)[i].second);
340
341  LeaveCriticalSection(&CriticalSection);
342}
343
344void llvm::sys::RunInterruptHandlers() {
345  Cleanup();
346}
347
348static LONG WINAPI LLVMUnhandledExceptionFilter(LPEXCEPTION_POINTERS ep) {
349  Cleanup();
350
351  // Initialize the STACKFRAME structure.
352  STACKFRAME64 StackFrame;
353  memset(&StackFrame, 0, sizeof(StackFrame));
354
355  DWORD machineType;
356#if defined(_M_X64)
357  machineType = IMAGE_FILE_MACHINE_AMD64;
358  StackFrame.AddrPC.Offset = ep->ContextRecord->Rip;
359  StackFrame.AddrPC.Mode = AddrModeFlat;
360  StackFrame.AddrStack.Offset = ep->ContextRecord->Rsp;
361  StackFrame.AddrStack.Mode = AddrModeFlat;
362  StackFrame.AddrFrame.Offset = ep->ContextRecord->Rbp;
363  StackFrame.AddrFrame.Mode = AddrModeFlat;
364#elif defined(_M_IX86)
365  machineType = IMAGE_FILE_MACHINE_I386;
366  StackFrame.AddrPC.Offset = ep->ContextRecord->Eip;
367  StackFrame.AddrPC.Mode = AddrModeFlat;
368  StackFrame.AddrStack.Offset = ep->ContextRecord->Esp;
369  StackFrame.AddrStack.Mode = AddrModeFlat;
370  StackFrame.AddrFrame.Offset = ep->ContextRecord->Ebp;
371  StackFrame.AddrFrame.Mode = AddrModeFlat;
372#endif
373
374  HANDLE hProcess = GetCurrentProcess();
375  HANDLE hThread = GetCurrentThread();
376
377  // Initialize the symbol handler.
378  SymSetOptions(SYMOPT_DEFERRED_LOADS|SYMOPT_LOAD_LINES);
379  SymInitialize(hProcess, NULL, TRUE);
380
381  while (true) {
382    if (!StackWalk64(machineType, hProcess, hThread, &StackFrame,
383                   ep->ContextRecord, NULL, SymFunctionTableAccess64,
384                   SymGetModuleBase64, NULL)) {
385      break;
386    }
387
388    if (StackFrame.AddrFrame.Offset == 0)
389      break;
390
391    // Print the PC in hexadecimal.
392    DWORD64 PC = StackFrame.AddrPC.Offset;
393#if defined(_M_X64)
394    fprintf(stderr, "0x%016llX", PC);
395#elif defined(_M_IX86)
396    fprintf(stderr, "0x%08lX", static_cast<DWORD>(PC));
397#endif
398
399    // Print the parameters.  Assume there are four.
400#if defined(_M_X64)
401    fprintf(stderr, " (0x%016llX 0x%016llX 0x%016llX 0x%016llX)",
402                StackFrame.Params[0],
403                StackFrame.Params[1],
404                StackFrame.Params[2],
405                StackFrame.Params[3]);
406#elif defined(_M_IX86)
407    fprintf(stderr, " (0x%08lX 0x%08lX 0x%08lX 0x%08lX)",
408                static_cast<DWORD>(StackFrame.Params[0]),
409                static_cast<DWORD>(StackFrame.Params[1]),
410                static_cast<DWORD>(StackFrame.Params[2]),
411                static_cast<DWORD>(StackFrame.Params[3]));
412#endif
413    // Verify the PC belongs to a module in this process.
414    if (!SymGetModuleBase64(hProcess, PC)) {
415      fputs(" <unknown module>\n", stderr);
416      continue;
417    }
418
419    // Print the symbol name.
420    char buffer[512];
421    IMAGEHLP_SYMBOL64 *symbol = reinterpret_cast<IMAGEHLP_SYMBOL64 *>(buffer);
422    memset(symbol, 0, sizeof(IMAGEHLP_SYMBOL64));
423    symbol->SizeOfStruct = sizeof(IMAGEHLP_SYMBOL64);
424    symbol->MaxNameLength = 512 - sizeof(IMAGEHLP_SYMBOL64);
425
426    DWORD64 dwDisp;
427    if (!SymGetSymFromAddr64(hProcess, PC, &dwDisp, symbol)) {
428      fputc('\n', stderr);
429      continue;
430    }
431
432    buffer[511] = 0;
433    if (dwDisp > 0)
434      fprintf(stderr, ", %s() + 0x%llX bytes(s)", symbol->Name, dwDisp);
435    else
436      fprintf(stderr, ", %s", symbol->Name);
437
438    // Print the source file and line number information.
439    IMAGEHLP_LINE64 line;
440    DWORD dwLineDisp;
441    memset(&line, 0, sizeof(line));
442    line.SizeOfStruct = sizeof(line);
443    if (SymGetLineFromAddr64(hProcess, PC, &dwLineDisp, &line)) {
444      fprintf(stderr, ", %s, line %lu", line.FileName, line.LineNumber);
445      if (dwLineDisp > 0)
446        fprintf(stderr, " + 0x%lX byte(s)", dwLineDisp);
447    }
448
449    fputc('\n', stderr);
450  }
451
452  if (ExitOnUnhandledExceptions)
453    _exit(ep->ExceptionRecord->ExceptionCode);
454
455  // Allow dialog box to pop up allowing choice to start debugger.
456  if (OldFilter)
457    return (*OldFilter)(ep);
458  else
459    return EXCEPTION_CONTINUE_SEARCH;
460}
461
462static BOOL WINAPI LLVMConsoleCtrlHandler(DWORD dwCtrlType) {
463  // We are running in our very own thread, courtesy of Windows.
464  EnterCriticalSection(&CriticalSection);
465  Cleanup();
466
467  // If an interrupt function has been set, go and run one it; otherwise,
468  // the process dies.
469  void (*IF)() = InterruptFunction;
470  InterruptFunction = 0;      // Don't run it on another CTRL-C.
471
472  if (IF) {
473    // Note: if the interrupt function throws an exception, there is nothing
474    // to catch it in this thread so it will kill the process.
475    IF();                     // Run it now.
476    LeaveCriticalSection(&CriticalSection);
477    return TRUE;              // Don't kill the process.
478  }
479
480  // Allow normal processing to take place; i.e., the process dies.
481  LeaveCriticalSection(&CriticalSection);
482  return FALSE;
483}
484
485#if __MINGW32__
486 // We turned these warnings off for this file so that MinGW-g++ doesn't
487 // complain about the ll format specifiers used.  Now we are turning the
488 // warnings back on.  If MinGW starts to support diagnostic stacks, we can
489 // replace this with a pop.
490 #pragma GCC diagnostic warning "-Wformat"
491 #pragma GCC diagnostic warning "-Wformat-extra-args"
492#endif
493