blob: 1e2fa4210df69b4ee70b49a9c600daf61606d3c9 [file] [log] [blame]
Reid Spencer3d7a6142004-08-29 19:22:48 +00001//===- Win32/Signals.cpp - Win32 Signals Implementation ---------*- C++ -*-===//
Mikhail Glushenkovf64d93d2010-10-21 20:40:39 +00002//
Reid Spencer3d7a6142004-08-29 19:22:48 +00003// The LLVM Compiler Infrastructure
4//
Chris Lattnerf3ebc3f2007-12-29 20:36:04 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Mikhail Glushenkovf64d93d2010-10-21 20:40:39 +00007//
Reid Spencer3d7a6142004-08-29 19:22:48 +00008//===----------------------------------------------------------------------===//
9//
10// This file provides the Win32 specific implementation of the Signals class.
11//
12//===----------------------------------------------------------------------===//
Rafael Espindola9aa3d5d2013-06-14 13:59:21 +000013#include "llvm/Support/FileSystem.h"
Leny Kholodov1b73e662016-05-04 16:56:51 +000014#include "llvm/Support/Path.h"
15#include "llvm/Support/Process.h"
16#include "llvm/Support/WindowsError.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000017#include <algorithm>
Leny Kholodov1b73e662016-05-04 16:56:51 +000018#include <io.h>
Michael J. Spencer89b0ad22015-01-29 17:20:29 +000019#include <signal.h>
Reid Spencer70b68352004-09-28 23:58:03 +000020#include <stdio.h>
Reid Spencer4aff78a2004-09-16 15:53:16 +000021
Zachary Turnercd132c92015-03-05 19:10:52 +000022#include "llvm/Support/Format.h"
23#include "llvm/Support/raw_ostream.h"
24
Chandler Carruth10b09152014-01-07 12:37:13 +000025// The Windows.h header must be after LLVM and standard headers.
Reid Klecknerd59e2fa2014-02-12 21:26:20 +000026#include "WindowsSupport.h"
Chandler Carruth10b09152014-01-07 12:37:13 +000027
Jeff Cohen07e22ba2005-02-19 03:01:13 +000028#ifdef __MINGW32__
Reid Spencer187b4ad2006-06-01 19:03:21 +000029 #include <imagehlp.h>
Reid Spencer99049282004-09-23 14:47:10 +000030#else
Reid Spencer187b4ad2006-06-01 19:03:21 +000031 #include <dbghelp.h>
Reid Spencer99049282004-09-23 14:47:10 +000032#endif
33#include <psapi.h>
Reid Spencer4aff78a2004-09-16 15:53:16 +000034
Michael J. Spencer44a36c82011-10-01 00:05:20 +000035#ifdef _MSC_VER
36 #pragma comment(lib, "psapi.lib")
Michael J. Spencer44a36c82011-10-01 00:05:20 +000037#elif __MINGW32__
Leny Kholodovbebb27b2015-07-02 14:34:57 +000038 #if (HAVE_LIBPSAPI != 1)
39 #error "libpsapi.a should be present"
Reid Spencer187b4ad2006-06-01 19:03:21 +000040 #endif
Michael J. Spencer44a36c82011-10-01 00:05:20 +000041 // The version of g++ that comes with MinGW does *not* properly understand
42 // the ll format specifier for printf. However, MinGW passes the format
43 // specifiers on to the MSVCRT entirely, and the CRT understands the ll
44 // specifier. So these warnings are spurious in this case. Since we compile
45 // with -Wall, this will generate these warnings which should be ignored. So
46 // we will turn off the warnings for this just file. However, MinGW also does
47 // not support push and pop for diagnostics, so we have to manually turn it
48 // back on at the end of the file.
49 #pragma GCC diagnostic ignored "-Wformat"
50 #pragma GCC diagnostic ignored "-Wformat-extra-args"
51
Anton Korobeynikovb27f11e2011-10-21 09:38:50 +000052 #if !defined(__MINGW64_VERSION_MAJOR)
53 // MinGW.org does not have updated support for the 64-bit versions of the
54 // DebugHlp APIs. So we will have to load them manually. The structures and
55 // method signatures were pulled from DbgHelp.h in the Windows Platform SDK,
56 // and adjusted for brevity.
Michael J. Spencer44a36c82011-10-01 00:05:20 +000057 typedef struct _IMAGEHLP_LINE64 {
58 DWORD SizeOfStruct;
59 PVOID Key;
60 DWORD LineNumber;
61 PCHAR FileName;
62 DWORD64 Address;
63 } IMAGEHLP_LINE64, *PIMAGEHLP_LINE64;
64
65 typedef struct _IMAGEHLP_SYMBOL64 {
66 DWORD SizeOfStruct;
67 DWORD64 Address;
68 DWORD Size;
69 DWORD Flags;
70 DWORD MaxNameLength;
71 CHAR Name[1];
72 } IMAGEHLP_SYMBOL64, *PIMAGEHLP_SYMBOL64;
73
74 typedef struct _tagADDRESS64 {
75 DWORD64 Offset;
76 WORD Segment;
77 ADDRESS_MODE Mode;
78 } ADDRESS64, *LPADDRESS64;
79
80 typedef struct _KDHELP64 {
81 DWORD64 Thread;
82 DWORD ThCallbackStack;
83 DWORD ThCallbackBStore;
84 DWORD NextCallback;
85 DWORD FramePointer;
86 DWORD64 KiCallUserMode;
87 DWORD64 KeUserCallbackDispatcher;
88 DWORD64 SystemRangeStart;
89 DWORD64 KiUserExceptionDispatcher;
90 DWORD64 StackBase;
91 DWORD64 StackLimit;
92 DWORD64 Reserved[5];
93 } KDHELP64, *PKDHELP64;
94
95 typedef struct _tagSTACKFRAME64 {
96 ADDRESS64 AddrPC;
97 ADDRESS64 AddrReturn;
98 ADDRESS64 AddrFrame;
99 ADDRESS64 AddrStack;
100 ADDRESS64 AddrBStore;
101 PVOID FuncTableEntry;
102 DWORD64 Params[4];
103 BOOL Far;
104 BOOL Virtual;
105 DWORD64 Reserved[3];
106 KDHELP64 KdHelp;
107 } STACKFRAME64, *LPSTACKFRAME64;
Leny Kholodovbebb27b2015-07-02 14:34:57 +0000108 #endif // !defined(__MINGW64_VERSION_MAJOR)
109#endif // __MINGW32__
Michael J. Spencer44a36c82011-10-01 00:05:20 +0000110
111typedef BOOL (__stdcall *PREAD_PROCESS_MEMORY_ROUTINE64)(HANDLE hProcess,
112 DWORD64 qwBaseAddress, PVOID lpBuffer, DWORD nSize,
113 LPDWORD lpNumberOfBytesRead);
114
115typedef PVOID (__stdcall *PFUNCTION_TABLE_ACCESS_ROUTINE64)( HANDLE ahProcess,
116 DWORD64 AddrBase);
117
118typedef DWORD64 (__stdcall *PGET_MODULE_BASE_ROUTINE64)(HANDLE hProcess,
119 DWORD64 Address);
120
121typedef DWORD64 (__stdcall *PTRANSLATE_ADDRESS_ROUTINE64)(HANDLE hProcess,
122 HANDLE hThread, LPADDRESS64 lpaddr);
123
Leny Kholodov1b73e662016-05-04 16:56:51 +0000124typedef BOOL(WINAPI *fpMiniDumpWriteDump)(HANDLE, DWORD, HANDLE, MINIDUMP_TYPE,
125 PMINIDUMP_EXCEPTION_INFORMATION,
126 PMINIDUMP_USER_STREAM_INFORMATION,
127 PMINIDUMP_CALLBACK_INFORMATION);
128static fpMiniDumpWriteDump fMiniDumpWriteDump;
129
Michael J. Spencer44a36c82011-10-01 00:05:20 +0000130typedef BOOL (WINAPI *fpStackWalk64)(DWORD, HANDLE, HANDLE, LPSTACKFRAME64,
131 PVOID, PREAD_PROCESS_MEMORY_ROUTINE64,
132 PFUNCTION_TABLE_ACCESS_ROUTINE64,
133 PGET_MODULE_BASE_ROUTINE64,
134 PTRANSLATE_ADDRESS_ROUTINE64);
Leny Kholodovbebb27b2015-07-02 14:34:57 +0000135static fpStackWalk64 fStackWalk64;
Michael J. Spencer44a36c82011-10-01 00:05:20 +0000136
137typedef DWORD64 (WINAPI *fpSymGetModuleBase64)(HANDLE, DWORD64);
Leny Kholodovbebb27b2015-07-02 14:34:57 +0000138static fpSymGetModuleBase64 fSymGetModuleBase64;
Michael J. Spencer44a36c82011-10-01 00:05:20 +0000139
140typedef BOOL (WINAPI *fpSymGetSymFromAddr64)(HANDLE, DWORD64,
141 PDWORD64, PIMAGEHLP_SYMBOL64);
Leny Kholodovbebb27b2015-07-02 14:34:57 +0000142static fpSymGetSymFromAddr64 fSymGetSymFromAddr64;
Michael J. Spencer44a36c82011-10-01 00:05:20 +0000143
144typedef BOOL (WINAPI *fpSymGetLineFromAddr64)(HANDLE, DWORD64,
145 PDWORD, PIMAGEHLP_LINE64);
Leny Kholodovbebb27b2015-07-02 14:34:57 +0000146static fpSymGetLineFromAddr64 fSymGetLineFromAddr64;
Michael J. Spencer44a36c82011-10-01 00:05:20 +0000147
Reid Klecknerba5757d2015-11-05 01:07:54 +0000148typedef BOOL(WINAPI *fpSymGetModuleInfo64)(HANDLE hProcess, DWORD64 dwAddr,
149 PIMAGEHLP_MODULE64 ModuleInfo);
150static fpSymGetModuleInfo64 fSymGetModuleInfo64;
151
Michael J. Spencer44a36c82011-10-01 00:05:20 +0000152typedef PVOID (WINAPI *fpSymFunctionTableAccess64)(HANDLE, DWORD64);
Leny Kholodovbebb27b2015-07-02 14:34:57 +0000153static fpSymFunctionTableAccess64 fSymFunctionTableAccess64;
154
155typedef DWORD (WINAPI *fpSymSetOptions)(DWORD);
156static fpSymSetOptions fSymSetOptions;
157
158typedef BOOL (WINAPI *fpSymInitialize)(HANDLE, PCSTR, BOOL);
159static fpSymInitialize fSymInitialize;
Michael J. Spencer44a36c82011-10-01 00:05:20 +0000160
Reid Klecknerba5757d2015-11-05 01:07:54 +0000161typedef BOOL (WINAPI *fpEnumerateLoadedModules)(HANDLE,PENUMLOADED_MODULES_CALLBACK64,PVOID);
162static fpEnumerateLoadedModules fEnumerateLoadedModules;
163
Michael J. Spencer44a36c82011-10-01 00:05:20 +0000164static bool load64BitDebugHelp(void) {
David Majnemer17a44962013-10-07 09:52:36 +0000165 HMODULE hLib = ::LoadLibraryW(L"Dbghelp.dll");
Michael J. Spencer44a36c82011-10-01 00:05:20 +0000166 if (hLib) {
Leny Kholodov1b73e662016-05-04 16:56:51 +0000167 fMiniDumpWriteDump = (fpMiniDumpWriteDump)
168 ::GetProcAddress(hLib, "MiniDumpWriteDump");
Leny Kholodovbebb27b2015-07-02 14:34:57 +0000169 fStackWalk64 = (fpStackWalk64)
Michael J. Spencer44a36c82011-10-01 00:05:20 +0000170 ::GetProcAddress(hLib, "StackWalk64");
Leny Kholodovbebb27b2015-07-02 14:34:57 +0000171 fSymGetModuleBase64 = (fpSymGetModuleBase64)
Michael J. Spencer44a36c82011-10-01 00:05:20 +0000172 ::GetProcAddress(hLib, "SymGetModuleBase64");
Leny Kholodovbebb27b2015-07-02 14:34:57 +0000173 fSymGetSymFromAddr64 = (fpSymGetSymFromAddr64)
Michael J. Spencer44a36c82011-10-01 00:05:20 +0000174 ::GetProcAddress(hLib, "SymGetSymFromAddr64");
Leny Kholodovbebb27b2015-07-02 14:34:57 +0000175 fSymGetLineFromAddr64 = (fpSymGetLineFromAddr64)
Michael J. Spencer44a36c82011-10-01 00:05:20 +0000176 ::GetProcAddress(hLib, "SymGetLineFromAddr64");
Reid Klecknerba5757d2015-11-05 01:07:54 +0000177 fSymGetModuleInfo64 = (fpSymGetModuleInfo64)
178 ::GetProcAddress(hLib, "SymGetModuleInfo64");
Leny Kholodovbebb27b2015-07-02 14:34:57 +0000179 fSymFunctionTableAccess64 = (fpSymFunctionTableAccess64)
Michael J. Spencer44a36c82011-10-01 00:05:20 +0000180 ::GetProcAddress(hLib, "SymFunctionTableAccess64");
Leny Kholodovbebb27b2015-07-02 14:34:57 +0000181 fSymSetOptions = (fpSymSetOptions)::GetProcAddress(hLib, "SymSetOptions");
182 fSymInitialize = (fpSymInitialize)::GetProcAddress(hLib, "SymInitialize");
Reid Klecknerba5757d2015-11-05 01:07:54 +0000183 fEnumerateLoadedModules = (fpEnumerateLoadedModules)
184 ::GetProcAddress(hLib, "EnumerateLoadedModules64");
Michael J. Spencer44a36c82011-10-01 00:05:20 +0000185 }
Leny Kholodov1b73e662016-05-04 16:56:51 +0000186 return fStackWalk64 && fSymInitialize && fSymSetOptions && fMiniDumpWriteDump;
Michael J. Spencer44a36c82011-10-01 00:05:20 +0000187}
Reid Spencer4aff78a2004-09-16 15:53:16 +0000188
Yaron Keren240bd9c2015-07-22 19:01:14 +0000189using namespace llvm;
190
Reid Spencer4aff78a2004-09-16 15:53:16 +0000191// Forward declare.
192static LONG WINAPI LLVMUnhandledExceptionFilter(LPEXCEPTION_POINTERS ep);
193static BOOL WINAPI LLVMConsoleCtrlHandler(DWORD dwCtrlType);
194
Jeff Cohenba7cc682005-08-02 03:04:47 +0000195// InterruptFunction - The function to call if ctrl-c is pressed.
196static void (*InterruptFunction)() = 0;
197
Rafael Espindola4f35da72013-06-13 21:16:58 +0000198static std::vector<std::string> *FilesToRemove = NULL;
Reid Spencer4aff78a2004-09-16 15:53:16 +0000199static bool RegisteredUnhandledExceptionFilter = false;
Reid Spencer1bdd0f02004-09-19 05:37:39 +0000200static bool CleanupExecuted = false;
201static PTOP_LEVEL_EXCEPTION_FILTER OldFilter = NULL;
Reid Spencer90debc52004-09-17 03:02:27 +0000202
203// Windows creates a new thread to execute the console handler when an event
204// (such as CTRL/C) occurs. This causes concurrency issues with the above
205// globals which this critical section addresses.
Reid Spencer4aff78a2004-09-16 15:53:16 +0000206static CRITICAL_SECTION CriticalSection;
Aaron Ballman50af8d42015-03-26 16:24:38 +0000207static bool CriticalSectionInitialized = false;
Reid Spencer4aff78a2004-09-16 15:53:16 +0000208
Richard Smith2ad6d482016-06-09 00:53:21 +0000209static StringRef Argv0;
210
Reid Klecknerba5757d2015-11-05 01:07:54 +0000211enum {
212#if defined(_M_X64)
213 NativeMachineType = IMAGE_FILE_MACHINE_AMD64
214#else
215 NativeMachineType = IMAGE_FILE_MACHINE_I386
216#endif
217};
218
219static bool printStackTraceWithLLVMSymbolizer(llvm::raw_ostream &OS,
220 HANDLE hProcess, HANDLE hThread,
221 STACKFRAME64 &StackFrameOrig,
222 CONTEXT *ContextOrig) {
223 // StackWalk64 modifies the incoming stack frame and context, so copy them.
224 STACKFRAME64 StackFrame = StackFrameOrig;
225
226 // Copy the register context so that we don't modify it while we unwind. We
227 // could use InitializeContext + CopyContext, but that's only required to get
228 // at AVX registers, which typically aren't needed by StackWalk64. Reduce the
229 // flag set to indicate that there's less data.
230 CONTEXT Context = *ContextOrig;
231 Context.ContextFlags = CONTEXT_CONTROL | CONTEXT_INTEGER;
232
233 static void *StackTrace[256];
Aaron Ballman3c44b422015-11-05 14:22:56 +0000234 size_t Depth = 0;
Reid Klecknerba5757d2015-11-05 01:07:54 +0000235 while (fStackWalk64(NativeMachineType, hProcess, hThread, &StackFrame,
236 &Context, 0, fSymFunctionTableAccess64,
237 fSymGetModuleBase64, 0)) {
238 if (StackFrame.AddrFrame.Offset == 0)
239 break;
240 StackTrace[Depth++] = (void *)(uintptr_t)StackFrame.AddrPC.Offset;
241 if (Depth >= array_lengthof(StackTrace))
242 break;
243 }
244
Richard Smith2ad6d482016-06-09 00:53:21 +0000245 return printSymbolizedStackTrace(Argv0, &StackTrace[0], Depth, OS);
Reid Klecknerba5757d2015-11-05 01:07:54 +0000246}
247
248namespace {
249struct FindModuleData {
250 void **StackTrace;
251 int Depth;
252 const char **Modules;
253 intptr_t *Offsets;
254 StringSaver *StrPool;
255};
256}
257
NAKAMURA Takumi2de1b322016-03-07 00:13:09 +0000258static BOOL CALLBACK findModuleCallback(PCSTR ModuleName,
Reid Klecknerba5757d2015-11-05 01:07:54 +0000259 DWORD64 ModuleBase, ULONG ModuleSize,
260 void *VoidData) {
261 FindModuleData *Data = (FindModuleData*)VoidData;
262 intptr_t Beg = ModuleBase;
263 intptr_t End = Beg + ModuleSize;
264 for (int I = 0; I < Data->Depth; I++) {
265 if (Data->Modules[I])
266 continue;
267 intptr_t Addr = (intptr_t)Data->StackTrace[I];
268 if (Beg <= Addr && Addr < End) {
269 Data->Modules[I] = Data->StrPool->save(ModuleName);
270 Data->Offsets[I] = Addr - Beg;
271 }
272 }
273 return TRUE;
274}
275
276static bool findModulesAndOffsets(void **StackTrace, int Depth,
277 const char **Modules, intptr_t *Offsets,
278 const char *MainExecutableName,
279 StringSaver &StrPool) {
280 if (!fEnumerateLoadedModules)
281 return false;
282 FindModuleData Data;
283 Data.StackTrace = StackTrace;
284 Data.Depth = Depth;
285 Data.Modules = Modules;
286 Data.Offsets = Offsets;
287 Data.StrPool = &StrPool;
288 fEnumerateLoadedModules(GetCurrentProcess(), findModuleCallback, &Data);
289 return true;
290}
291
Zachary Turnercd132c92015-03-05 19:10:52 +0000292static void PrintStackTraceForThread(llvm::raw_ostream &OS, HANDLE hProcess,
Zachary Turner62b7b612015-03-05 17:47:52 +0000293 HANDLE hThread, STACKFRAME64 &StackFrame,
294 CONTEXT *Context) {
Zachary Turner62b7b612015-03-05 17:47:52 +0000295 // Initialize the symbol handler.
Leny Kholodovbebb27b2015-07-02 14:34:57 +0000296 fSymSetOptions(SYMOPT_DEFERRED_LOADS | SYMOPT_LOAD_LINES);
297 fSymInitialize(hProcess, NULL, TRUE);
Zachary Turner62b7b612015-03-05 17:47:52 +0000298
Reid Klecknerba5757d2015-11-05 01:07:54 +0000299 // Try llvm-symbolizer first. llvm-symbolizer knows how to deal with both PDBs
300 // and DWARF, so it should do a good job regardless of what debug info or
301 // linker is in use.
302 if (printStackTraceWithLLVMSymbolizer(OS, hProcess, hThread, StackFrame,
303 Context)) {
304 return;
305 }
306
Zachary Turner62b7b612015-03-05 17:47:52 +0000307 while (true) {
Reid Klecknerba5757d2015-11-05 01:07:54 +0000308 if (!fStackWalk64(NativeMachineType, hProcess, hThread, &StackFrame,
309 Context, 0, fSymFunctionTableAccess64,
310 fSymGetModuleBase64, 0)) {
Zachary Turner62b7b612015-03-05 17:47:52 +0000311 break;
312 }
313
314 if (StackFrame.AddrFrame.Offset == 0)
315 break;
316
Zachary Turnercd132c92015-03-05 19:10:52 +0000317 using namespace llvm;
Zachary Turner62b7b612015-03-05 17:47:52 +0000318 // Print the PC in hexadecimal.
319 DWORD64 PC = StackFrame.AddrPC.Offset;
320#if defined(_M_X64)
Zachary Turnercd132c92015-03-05 19:10:52 +0000321 OS << format("0x%016llX", PC);
Zachary Turner62b7b612015-03-05 17:47:52 +0000322#elif defined(_M_IX86)
Zachary Turnercd132c92015-03-05 19:10:52 +0000323 OS << format("0x%08lX", static_cast<DWORD>(PC));
Zachary Turner62b7b612015-03-05 17:47:52 +0000324#endif
325
326// Print the parameters. Assume there are four.
327#if defined(_M_X64)
Zachary Turnercd132c92015-03-05 19:10:52 +0000328 OS << format(" (0x%016llX 0x%016llX 0x%016llX 0x%016llX)",
Zachary Turner62b7b612015-03-05 17:47:52 +0000329 StackFrame.Params[0], StackFrame.Params[1], StackFrame.Params[2],
330 StackFrame.Params[3]);
331#elif defined(_M_IX86)
Zachary Turnercd132c92015-03-05 19:10:52 +0000332 OS << format(" (0x%08lX 0x%08lX 0x%08lX 0x%08lX)",
Zachary Turner62b7b612015-03-05 17:47:52 +0000333 static_cast<DWORD>(StackFrame.Params[0]),
334 static_cast<DWORD>(StackFrame.Params[1]),
335 static_cast<DWORD>(StackFrame.Params[2]),
336 static_cast<DWORD>(StackFrame.Params[3]));
337#endif
338 // Verify the PC belongs to a module in this process.
Leny Kholodovbebb27b2015-07-02 14:34:57 +0000339 if (!fSymGetModuleBase64(hProcess, PC)) {
Zachary Turnercd132c92015-03-05 19:10:52 +0000340 OS << " <unknown module>\n";
Zachary Turner62b7b612015-03-05 17:47:52 +0000341 continue;
342 }
343
344 // Print the symbol name.
345 char buffer[512];
346 IMAGEHLP_SYMBOL64 *symbol = reinterpret_cast<IMAGEHLP_SYMBOL64 *>(buffer);
347 memset(symbol, 0, sizeof(IMAGEHLP_SYMBOL64));
348 symbol->SizeOfStruct = sizeof(IMAGEHLP_SYMBOL64);
349 symbol->MaxNameLength = 512 - sizeof(IMAGEHLP_SYMBOL64);
350
351 DWORD64 dwDisp;
Leny Kholodovbebb27b2015-07-02 14:34:57 +0000352 if (!fSymGetSymFromAddr64(hProcess, PC, &dwDisp, symbol)) {
Zachary Turnercd132c92015-03-05 19:10:52 +0000353 OS << '\n';
Zachary Turner62b7b612015-03-05 17:47:52 +0000354 continue;
355 }
356
357 buffer[511] = 0;
358 if (dwDisp > 0)
Zachary Turnercd132c92015-03-05 19:10:52 +0000359 OS << format(", %s() + 0x%llX bytes(s)", (const char*)symbol->Name,
360 dwDisp);
Zachary Turner62b7b612015-03-05 17:47:52 +0000361 else
Zachary Turnercd132c92015-03-05 19:10:52 +0000362 OS << format(", %s", (const char*)symbol->Name);
Zachary Turner62b7b612015-03-05 17:47:52 +0000363
364 // Print the source file and line number information.
Yaron Keren24a86df2015-04-24 15:39:47 +0000365 IMAGEHLP_LINE64 line = {};
Zachary Turner62b7b612015-03-05 17:47:52 +0000366 DWORD dwLineDisp;
Zachary Turner62b7b612015-03-05 17:47:52 +0000367 line.SizeOfStruct = sizeof(line);
Leny Kholodovbebb27b2015-07-02 14:34:57 +0000368 if (fSymGetLineFromAddr64(hProcess, PC, &dwLineDisp, &line)) {
Zachary Turnercd132c92015-03-05 19:10:52 +0000369 OS << format(", %s, line %lu", line.FileName, line.LineNumber);
Zachary Turner62b7b612015-03-05 17:47:52 +0000370 if (dwLineDisp > 0)
Zachary Turnercd132c92015-03-05 19:10:52 +0000371 OS << format(" + 0x%lX byte(s)", dwLineDisp);
Zachary Turner62b7b612015-03-05 17:47:52 +0000372 }
373
Zachary Turnercd132c92015-03-05 19:10:52 +0000374 OS << '\n';
Zachary Turner62b7b612015-03-05 17:47:52 +0000375 }
376}
377
Reid Spencer3d7a6142004-08-29 19:22:48 +0000378namespace llvm {
Reid Spencer3d7a6142004-08-29 19:22:48 +0000379
380//===----------------------------------------------------------------------===//
Mikhail Glushenkovf64d93d2010-10-21 20:40:39 +0000381//=== WARNING: Implementation here must contain only Win32 specific code
Reid Spencer4aff78a2004-09-16 15:53:16 +0000382//=== and must not be UNIX code
Reid Spencer3d7a6142004-08-29 19:22:48 +0000383//===----------------------------------------------------------------------===//
384
Daniel Dunbar1bdedd32009-09-22 15:58:35 +0000385#ifdef _MSC_VER
Reid Klecknerbd39f212013-04-05 16:18:03 +0000386/// AvoidMessageBoxHook - Emulates hitting "retry" from an "abort, retry,
387/// ignore" CRT debug report dialog. "retry" raises an exception which
388/// ultimately triggers our stack dumper.
Reid Kleckner542a4542015-02-26 21:08:21 +0000389static LLVM_ATTRIBUTE_UNUSED int
390AvoidMessageBoxHook(int ReportType, char *Message, int *Return) {
Reid Klecknerbd39f212013-04-05 16:18:03 +0000391 // Set *Return to the retry code for the return value of _CrtDbgReport:
392 // http://msdn.microsoft.com/en-us/library/8hyw4sy7(v=vs.71).aspx
393 // This may also trigger just-in-time debugging via DebugBreak().
394 if (Return)
395 *Return = 1;
396 // Don't call _CrtDbgReport.
397 return TRUE;
398}
399
Daniel Dunbar1bdedd32009-09-22 15:58:35 +0000400#endif
Daniel Dunbar4c7b0ca2009-09-22 09:50:28 +0000401
Aaron Ballman03b968e2015-01-29 20:48:34 +0000402extern "C" void HandleAbort(int Sig) {
Michael J. Spencer89b0ad22015-01-29 17:20:29 +0000403 if (Sig == SIGABRT) {
404 LLVM_BUILTIN_TRAP;
405 }
406}
407
Aaron Ballman50af8d42015-03-26 16:24:38 +0000408static void InitializeThreading() {
409 if (CriticalSectionInitialized)
410 return;
411
412 // Now's the time to create the critical section. This is the first time
413 // through here, and there's only one thread.
414 InitializeCriticalSection(&CriticalSection);
415 CriticalSectionInitialized = true;
416}
417
Daniel Dunbar4c7b0ca2009-09-22 09:50:28 +0000418static void RegisterHandler() {
Leny Kholodovbebb27b2015-07-02 14:34:57 +0000419 // If we cannot load up the APIs (which would be unexpected as they should
420 // exist on every version of Windows we support), we will bail out since
421 // there would be nothing to report.
Reid Kleckner6cdf8442016-01-11 21:07:48 +0000422 if (!load64BitDebugHelp()) {
423 assert(false && "These APIs should always be available");
424 return;
425 }
Michael J. Spencer44a36c82011-10-01 00:05:20 +0000426
Reid Spencer1bdd0f02004-09-19 05:37:39 +0000427 if (RegisteredUnhandledExceptionFilter) {
Reid Spencer90debc52004-09-17 03:02:27 +0000428 EnterCriticalSection(&CriticalSection);
Reid Spencer4aff78a2004-09-16 15:53:16 +0000429 return;
Reid Spencer90debc52004-09-17 03:02:27 +0000430 }
Reid Spencer4aff78a2004-09-16 15:53:16 +0000431
Aaron Ballman50af8d42015-03-26 16:24:38 +0000432 InitializeThreading();
Reid Spencer4aff78a2004-09-16 15:53:16 +0000433
434 // Enter it immediately. Now if someone hits CTRL/C, the console handler
435 // can't proceed until the globals are updated.
436 EnterCriticalSection(&CriticalSection);
437
438 RegisteredUnhandledExceptionFilter = true;
Reid Spencer1bdd0f02004-09-19 05:37:39 +0000439 OldFilter = SetUnhandledExceptionFilter(LLVMUnhandledExceptionFilter);
Reid Spencer4aff78a2004-09-16 15:53:16 +0000440 SetConsoleCtrlHandler(LLVMConsoleCtrlHandler, TRUE);
441
442 // IMPORTANT NOTE: Caller must call LeaveCriticalSection(&CriticalSection) or
443 // else multi-threading problems will ensue.
444}
445
Reid Spencer3d7a6142004-08-29 19:22:48 +0000446// RemoveFileOnSignal - The public API
Rafael Espindola4f35da72013-06-13 21:16:58 +0000447bool sys::RemoveFileOnSignal(StringRef Filename, std::string* ErrMsg) {
Reid Spencer4aff78a2004-09-16 15:53:16 +0000448 RegisterHandler();
449
Reid Spencer50eac3b2006-08-25 21:37:17 +0000450 if (CleanupExecuted) {
451 if (ErrMsg)
452 *ErrMsg = "Process terminating -- cannot register for removal";
453 return true;
454 }
Reid Spencer1bdd0f02004-09-19 05:37:39 +0000455
Reid Spencer4aff78a2004-09-16 15:53:16 +0000456 if (FilesToRemove == NULL)
Rafael Espindola4f35da72013-06-13 21:16:58 +0000457 FilesToRemove = new std::vector<std::string>;
Reid Spencer4aff78a2004-09-16 15:53:16 +0000458
Reid Spencerf070b6c2004-11-16 06:59:53 +0000459 FilesToRemove->push_back(Filename);
Reid Spencer4aff78a2004-09-16 15:53:16 +0000460
461 LeaveCriticalSection(&CriticalSection);
Reid Spencer50eac3b2006-08-25 21:37:17 +0000462 return false;
Reid Spencer3d7a6142004-08-29 19:22:48 +0000463}
464
Dan Gohmane201c072010-09-01 14:17:34 +0000465// DontRemoveFileOnSignal - The public API
Rafael Espindola4f35da72013-06-13 21:16:58 +0000466void sys::DontRemoveFileOnSignal(StringRef Filename) {
Dan Gohmane201c072010-09-01 14:17:34 +0000467 if (FilesToRemove == NULL)
468 return;
469
NAKAMURA Takumi3f688b92010-10-22 01:23:50 +0000470 RegisterHandler();
471
Rafael Espindola4f35da72013-06-13 21:16:58 +0000472 std::vector<std::string>::reverse_iterator I =
Dan Gohmane201c072010-09-01 14:17:34 +0000473 std::find(FilesToRemove->rbegin(), FilesToRemove->rend(), Filename);
474 if (I != FilesToRemove->rend())
475 FilesToRemove->erase(I.base()-1);
476
477 LeaveCriticalSection(&CriticalSection);
478}
479
Michael J. Spencer89b0ad22015-01-29 17:20:29 +0000480void sys::DisableSystemDialogsOnCrash() {
481 // Crash to stack trace handler on abort.
482 signal(SIGABRT, HandleAbort);
483
484 // The following functions are not reliably accessible on MinGW.
485#ifdef _MSC_VER
486 // We're already handling writing a "something went wrong" message.
487 _set_abort_behavior(0, _WRITE_ABORT_MSG);
488 // Disable Dr. Watson.
489 _set_abort_behavior(0, _CALL_REPORTFAULT);
490 _CrtSetReportHook(AvoidMessageBoxHook);
491#endif
492
493 // Disable standard error dialog box.
494 SetErrorMode(SEM_FAILCRITICALERRORS | SEM_NOGPFAULTERRORBOX |
495 SEM_NOOPENFILEERRORBOX);
496 _set_error_mode(_OUT_TO_STDERR);
497}
498
Reid Spencer3d7a6142004-08-29 19:22:48 +0000499/// PrintStackTraceOnErrorSignal - When an error signal (such as SIBABRT or
500/// SIGSEGV) is delivered to the process, print a stack trace and then exit.
Richard Smith2ad6d482016-06-09 00:53:21 +0000501void sys::PrintStackTraceOnErrorSignal(StringRef Argv0,
502 bool DisableCrashReporting) {
503 ::Argv0 = Argv0;
504
Leny Kholodov1b73e662016-05-04 16:56:51 +0000505 if (DisableCrashReporting || getenv("LLVM_DISABLE_CRASH_REPORT"))
506 Process::PreventCoreFiles();
507
Michael J. Spencer89b0ad22015-01-29 17:20:29 +0000508 DisableSystemDialogsOnCrash();
Reid Spencer4aff78a2004-09-16 15:53:16 +0000509 RegisterHandler();
510 LeaveCriticalSection(&CriticalSection);
Reid Spencer3d7a6142004-08-29 19:22:48 +0000511}
Benjamin Kramerf97eff62015-03-11 15:41:15 +0000512}
513
Yaron Kerenbdae8d62015-03-14 19:20:56 +0000514#if defined(__MINGW32__) && !defined(__MINGW64_VERSION_MAJOR)
515// Provide a prototype for RtlCaptureContext, mingw32 from mingw.org is
516// missing it but mingw-w64 has it.
Benjamin Kramerf97eff62015-03-11 15:41:15 +0000517extern "C" VOID WINAPI RtlCaptureContext(PCONTEXT ContextRecord);
Benjamin Kramerb47d5492015-03-11 16:09:02 +0000518#endif
Reid Spencer3d7a6142004-08-29 19:22:48 +0000519
Zachary Turnercd132c92015-03-05 19:10:52 +0000520void llvm::sys::PrintStackTrace(raw_ostream &OS) {
Reid Klecknere6580582015-03-05 18:26:58 +0000521 STACKFRAME64 StackFrame = {};
Yaron Keren24a86df2015-04-24 15:39:47 +0000522 CONTEXT Context = {};
Zachary Turner62b7b612015-03-05 17:47:52 +0000523 ::RtlCaptureContext(&Context);
524#if defined(_M_X64)
525 StackFrame.AddrPC.Offset = Context.Rip;
526 StackFrame.AddrStack.Offset = Context.Rsp;
527 StackFrame.AddrFrame.Offset = Context.Rbp;
528#else
529 StackFrame.AddrPC.Offset = Context.Eip;
530 StackFrame.AddrStack.Offset = Context.Esp;
531 StackFrame.AddrFrame.Offset = Context.Ebp;
532#endif
533 StackFrame.AddrPC.Mode = AddrModeFlat;
534 StackFrame.AddrStack.Mode = AddrModeFlat;
535 StackFrame.AddrFrame.Mode = AddrModeFlat;
Zachary Turnercd132c92015-03-05 19:10:52 +0000536 PrintStackTraceForThread(OS, GetCurrentProcess(), GetCurrentThread(),
Zachary Turner62b7b612015-03-05 17:47:52 +0000537 StackFrame, &Context);
Argyrios Kyrtzidiseb9ae762013-01-09 19:42:40 +0000538}
539
Chris Lattner6a5d6ec2005-08-02 02:14:22 +0000540
Benjamin Kramer90c2db22015-03-11 15:53:24 +0000541void llvm::sys::SetInterruptFunction(void (*IF)()) {
Jeff Cohenba7cc682005-08-02 03:04:47 +0000542 RegisterHandler();
Jeff Cohen9aafa062005-08-02 03:26:32 +0000543 InterruptFunction = IF;
Jeff Cohenba7cc682005-08-02 03:04:47 +0000544 LeaveCriticalSection(&CriticalSection);
Chris Lattner6a5d6ec2005-08-02 02:14:22 +0000545}
Sebastian Redl8d5baa02009-03-19 23:26:52 +0000546
547
548/// AddSignalHandler - Add a function to be called when a signal is delivered
549/// to the process. The handler can have a cookie passed to it to identify
550/// what instance of the handler it is.
Benjamin Kramerb47d5492015-03-11 16:09:02 +0000551void llvm::sys::AddSignalHandler(void (*FnPtr)(void *), void *Cookie) {
Sebastian Redl8d5baa02009-03-19 23:26:52 +0000552 CallBacksToRun->push_back(std::make_pair(FnPtr, Cookie));
553 RegisterHandler();
Torok Edwin6fb09562010-03-31 12:07:16 +0000554 LeaveCriticalSection(&CriticalSection);
Sebastian Redl8d5baa02009-03-19 23:26:52 +0000555}
Reid Spencer3d7a6142004-08-29 19:22:48 +0000556
Reid Spencer4aff78a2004-09-16 15:53:16 +0000557static void Cleanup() {
Yaron Keren356aa462015-05-19 13:31:25 +0000558 if (CleanupExecuted)
559 return;
560
Reid Spencer4aff78a2004-09-16 15:53:16 +0000561 EnterCriticalSection(&CriticalSection);
562
Reid Spencer1bdd0f02004-09-19 05:37:39 +0000563 // Prevent other thread from registering new files and directories for
564 // removal, should we be executing because of the console handler callback.
565 CleanupExecuted = true;
566
567 // FIXME: open files cannot be deleted.
Reid Spencer4aff78a2004-09-16 15:53:16 +0000568 if (FilesToRemove != NULL)
569 while (!FilesToRemove->empty()) {
Rafael Espindolad724c282014-02-23 13:37:37 +0000570 llvm::sys::fs::remove(FilesToRemove->back());
Reid Spencer4aff78a2004-09-16 15:53:16 +0000571 FilesToRemove->pop_back();
572 }
Yaron Keren28738102015-07-22 21:11:17 +0000573 llvm::sys::RunSignalHandlers();
Reid Spencer4aff78a2004-09-16 15:53:16 +0000574 LeaveCriticalSection(&CriticalSection);
575}
576
Daniel Dunbar68272562010-05-08 02:10:34 +0000577void llvm::sys::RunInterruptHandlers() {
Aaron Ballman50af8d42015-03-26 16:24:38 +0000578 // The interrupt handler may be called from an interrupt, but it may also be
579 // called manually (such as the case of report_fatal_error with no registered
580 // error handler). We must ensure that the critical section is properly
581 // initialized.
582 InitializeThreading();
Daniel Dunbar68272562010-05-08 02:10:34 +0000583 Cleanup();
584}
585
Leny Kholodov1b73e662016-05-04 16:56:51 +0000586/// \brief Find the Windows Registry Key for a given location.
587///
588/// \returns a valid HKEY if the location exists, else NULL.
589static HKEY FindWERKey(const llvm::Twine &RegistryLocation) {
590 HKEY Key;
Aaron Ballman0da8b2e2016-06-23 14:45:54 +0000591 if (ERROR_SUCCESS != ::RegOpenKeyExA(HKEY_LOCAL_MACHINE,
592 RegistryLocation.str().c_str(), 0,
593 KEY_QUERY_VALUE | KEY_READ, &Key))
Leny Kholodov1b73e662016-05-04 16:56:51 +0000594 return NULL;
595
596 return Key;
597}
598
599/// \brief Populate ResultDirectory with the value for "DumpFolder" for a given
600/// Windows Registry key.
601///
602/// \returns true if a valid value for DumpFolder exists, false otherwise.
603static bool GetDumpFolder(HKEY Key,
604 llvm::SmallVectorImpl<char> &ResultDirectory) {
605 using llvm::sys::windows::UTF16ToUTF8;
606
607 if (!Key)
608 return false;
609
610 DWORD BufferLengthBytes = 0;
611
612 if (ERROR_SUCCESS != ::RegGetValueW(Key, 0, L"DumpFolder", REG_EXPAND_SZ,
613 NULL, NULL, &BufferLengthBytes))
614 return false;
615
616 SmallVector<wchar_t, MAX_PATH> Buffer(BufferLengthBytes);
617
618 if (ERROR_SUCCESS != ::RegGetValueW(Key, 0, L"DumpFolder", REG_EXPAND_SZ,
619 NULL, Buffer.data(), &BufferLengthBytes))
620 return false;
621
622 DWORD ExpandBufferSize = ::ExpandEnvironmentStringsW(Buffer.data(), NULL, 0);
623
624 if (!ExpandBufferSize)
625 return false;
626
627 SmallVector<wchar_t, MAX_PATH> ExpandBuffer(ExpandBufferSize);
628
629 if (ExpandBufferSize != ::ExpandEnvironmentStringsW(Buffer.data(),
630 ExpandBuffer.data(),
631 ExpandBufferSize))
632 return false;
633
634 if (UTF16ToUTF8(ExpandBuffer.data(), ExpandBufferSize - 1, ResultDirectory))
635 return false;
636
637 return true;
638}
639
640/// \brief Populate ResultType with a valid MINIDUMP_TYPE based on the value of
641/// "DumpType" for a given Windows Registry key.
642///
643/// According to
644/// https://msdn.microsoft.com/en-us/library/windows/desktop/bb787181(v=vs.85).aspx
645/// valid values for DumpType are:
646/// * 0: Custom dump
647/// * 1: Mini dump
648/// * 2: Full dump
649/// If "Custom dump" is specified then the "CustomDumpFlags" field is read
650/// containing a bitwise combination of MINIDUMP_TYPE values.
651///
652/// \returns true if a valid value for ResultType can be set, false otherwise.
653static bool GetDumpType(HKEY Key, MINIDUMP_TYPE &ResultType) {
654 if (!Key)
655 return false;
656
657 DWORD DumpType;
658 DWORD TypeSize = sizeof(DumpType);
659 if (ERROR_SUCCESS != ::RegGetValueW(Key, NULL, L"DumpType", RRF_RT_REG_DWORD,
660 NULL, &DumpType,
661 &TypeSize))
662 return false;
663
664 switch (DumpType) {
665 case 0: {
666 DWORD Flags = 0;
667 if (ERROR_SUCCESS != ::RegGetValueW(Key, NULL, L"CustomDumpFlags",
668 RRF_RT_REG_DWORD, NULL, &Flags,
669 &TypeSize))
670 return false;
671
672 ResultType = static_cast<MINIDUMP_TYPE>(Flags);
673 break;
674 }
675 case 1:
676 ResultType = MiniDumpNormal;
677 break;
678 case 2:
679 ResultType = MiniDumpWithFullMemory;
680 break;
681 default:
682 return false;
683 }
684 return true;
685}
686
687/// \brief Write a Windows dump file containing process information that can be
688/// used for post-mortem debugging.
689///
690/// \returns zero error code if a mini dump created, actual error code
691/// otherwise.
692static std::error_code WINAPI
693WriteWindowsDumpFile(PMINIDUMP_EXCEPTION_INFORMATION ExceptionInfo) {
694 using namespace llvm;
695 using namespace llvm::sys;
696
697 std::string MainExecutableName = fs::getMainExecutable(nullptr, nullptr);
698 StringRef ProgramName;
699
700 if (MainExecutableName.empty()) {
701 // If we can't get the executable filename,
702 // things are in worse shape than we realize
703 // and we should just bail out.
704 return mapWindowsError(::GetLastError());
705 }
706
707 ProgramName = path::filename(MainExecutableName.c_str());
708
709 // The Windows Registry location as specified at
710 // https://msdn.microsoft.com/en-us/library/windows/desktop/bb787181%28v=vs.85%29.aspx
711 // "Collecting User-Mode Dumps" that may optionally be set to collect crash
712 // dumps in a specified location.
713 StringRef LocalDumpsRegistryLocation =
714 "SOFTWARE\\Microsoft\\Windows\\Windows Error Reporting\\LocalDumps";
715
716 // The key pointing to the Registry location that may contain global crash
717 // dump settings. This will be NULL if the location can not be found.
718 ScopedRegHandle DefaultLocalDumpsKey(FindWERKey(LocalDumpsRegistryLocation));
719
720 // The key pointing to the Registry location that may contain
721 // application-specific crash dump settings. This will be NULL if the
722 // location can not be found.
723 ScopedRegHandle AppSpecificKey(
724 FindWERKey(Twine(LocalDumpsRegistryLocation) + "\\" + ProgramName));
725
726 // Look to see if a dump type is specified in the registry; first with the
727 // app-specific key and failing that with the global key. If none are found
728 // default to a normal dump (GetDumpType will return false either if the key
729 // is NULL or if there is no valid DumpType value at its location).
730 MINIDUMP_TYPE DumpType;
731 if (!GetDumpType(AppSpecificKey, DumpType))
732 if (!GetDumpType(DefaultLocalDumpsKey, DumpType))
733 DumpType = MiniDumpNormal;
734
735 // Look to see if a dump location is specified in the registry; first with the
736 // app-specific key and failing that with the global key. If none are found
737 // we'll just create the dump file in the default temporary file location
738 // (GetDumpFolder will return false either if the key is NULL or if there is
739 // no valid DumpFolder value at its location).
740 bool ExplicitDumpDirectorySet = true;
741 SmallString<MAX_PATH> DumpDirectory;
742 if (!GetDumpFolder(AppSpecificKey, DumpDirectory))
743 if (!GetDumpFolder(DefaultLocalDumpsKey, DumpDirectory))
744 ExplicitDumpDirectorySet = false;
745
746 int FD;
747 SmallString<MAX_PATH> DumpPath;
748
749 if (ExplicitDumpDirectorySet) {
750 if (std::error_code EC = fs::create_directories(DumpDirectory))
751 return EC;
752 if (std::error_code EC = fs::createUniqueFile(
753 Twine(DumpDirectory) + "\\" + ProgramName + ".%%%%%%.dmp", FD,
754 DumpPath))
755 return EC;
756 } else if (std::error_code EC =
757 fs::createTemporaryFile(ProgramName, "dmp", FD, DumpPath))
758 return EC;
759
760 // Our support functions return a file descriptor but Windows wants a handle.
761 ScopedCommonHandle FileHandle(reinterpret_cast<HANDLE>(_get_osfhandle(FD)));
762
763 if (!fMiniDumpWriteDump(::GetCurrentProcess(), ::GetCurrentProcessId(),
764 FileHandle, DumpType, ExceptionInfo, NULL, NULL))
765 return mapWindowsError(::GetLastError());
766
767 llvm::errs() << "Wrote crash dump file \"" << DumpPath << "\"\n";
768 return std::error_code();
769}
770
Reid Spencer4aff78a2004-09-16 15:53:16 +0000771static LONG WINAPI LLVMUnhandledExceptionFilter(LPEXCEPTION_POINTERS ep) {
Mikhail Glushenkov32acd742010-10-27 09:09:04 +0000772 Cleanup();
Mikhail Glushenkovf64d93d2010-10-21 20:40:39 +0000773
Leny Kholodov1b73e662016-05-04 16:56:51 +0000774 // We'll automatically write a Minidump file here to help diagnose
775 // the nasty sorts of crashes that aren't 100% reproducible from a set of
776 // inputs (or in the event that the user is unable or unwilling to provide a
777 // reproducible case).
778 if (!llvm::Process::AreCoreFilesPrevented()) {
779 MINIDUMP_EXCEPTION_INFORMATION ExceptionInfo;
780 ExceptionInfo.ThreadId = ::GetCurrentThreadId();
781 ExceptionInfo.ExceptionPointers = ep;
782 ExceptionInfo.ClientPointers = FALSE;
783
784 if (std::error_code EC = WriteWindowsDumpFile(&ExceptionInfo))
785 llvm::errs() << "Could not write crash dump file: " << EC.message()
786 << "\n";
787 }
788
Mikhail Glushenkov080d86f2010-10-28 08:25:44 +0000789 // Initialize the STACKFRAME structure.
Yaron Keren24a86df2015-04-24 15:39:47 +0000790 STACKFRAME64 StackFrame = {};
Reid Spencer4aff78a2004-09-16 15:53:16 +0000791
Michael J. Spencer44a36c82011-10-01 00:05:20 +0000792#if defined(_M_X64)
Michael J. Spencer44a36c82011-10-01 00:05:20 +0000793 StackFrame.AddrPC.Offset = ep->ContextRecord->Rip;
794 StackFrame.AddrPC.Mode = AddrModeFlat;
795 StackFrame.AddrStack.Offset = ep->ContextRecord->Rsp;
796 StackFrame.AddrStack.Mode = AddrModeFlat;
797 StackFrame.AddrFrame.Offset = ep->ContextRecord->Rbp;
798 StackFrame.AddrFrame.Mode = AddrModeFlat;
799#elif defined(_M_IX86)
Mikhail Glushenkov080d86f2010-10-28 08:25:44 +0000800 StackFrame.AddrPC.Offset = ep->ContextRecord->Eip;
801 StackFrame.AddrPC.Mode = AddrModeFlat;
802 StackFrame.AddrStack.Offset = ep->ContextRecord->Esp;
803 StackFrame.AddrStack.Mode = AddrModeFlat;
804 StackFrame.AddrFrame.Offset = ep->ContextRecord->Ebp;
805 StackFrame.AddrFrame.Mode = AddrModeFlat;
Michael J. Spencer44a36c82011-10-01 00:05:20 +0000806#endif
Reid Spencer4aff78a2004-09-16 15:53:16 +0000807
Mikhail Glushenkov080d86f2010-10-28 08:25:44 +0000808 HANDLE hProcess = GetCurrentProcess();
809 HANDLE hThread = GetCurrentThread();
Zachary Turnercd132c92015-03-05 19:10:52 +0000810 PrintStackTraceForThread(llvm::errs(), hProcess, hThread, StackFrame,
Zachary Turner62b7b612015-03-05 17:47:52 +0000811 ep->ContextRecord);
Mikhail Glushenkov080d86f2010-10-28 08:25:44 +0000812
Michael J. Spencer89b0ad22015-01-29 17:20:29 +0000813 _exit(ep->ExceptionRecord->ExceptionCode);
Reid Spencer4aff78a2004-09-16 15:53:16 +0000814}
815
816static BOOL WINAPI LLVMConsoleCtrlHandler(DWORD dwCtrlType) {
Jeff Cohen9aafa062005-08-02 03:26:32 +0000817 // We are running in our very own thread, courtesy of Windows.
Jeff Cohenba7cc682005-08-02 03:04:47 +0000818 EnterCriticalSection(&CriticalSection);
Reid Spencer4aff78a2004-09-16 15:53:16 +0000819 Cleanup();
820
Jeff Cohenba7cc682005-08-02 03:04:47 +0000821 // If an interrupt function has been set, go and run one it; otherwise,
822 // the process dies.
823 void (*IF)() = InterruptFunction;
824 InterruptFunction = 0; // Don't run it on another CTRL-C.
825
826 if (IF) {
Jeff Cohen9aafa062005-08-02 03:26:32 +0000827 // Note: if the interrupt function throws an exception, there is nothing
828 // to catch it in this thread so it will kill the process.
829 IF(); // Run it now.
Jeff Cohenba7cc682005-08-02 03:04:47 +0000830 LeaveCriticalSection(&CriticalSection);
831 return TRUE; // Don't kill the process.
832 }
833
Reid Spencer90debc52004-09-17 03:02:27 +0000834 // Allow normal processing to take place; i.e., the process dies.
Jeff Cohenba7cc682005-08-02 03:04:47 +0000835 LeaveCriticalSection(&CriticalSection);
Reid Spencer4aff78a2004-09-16 15:53:16 +0000836 return FALSE;
837}
Michael J. Spencer44a36c82011-10-01 00:05:20 +0000838
839#if __MINGW32__
840 // We turned these warnings off for this file so that MinGW-g++ doesn't
841 // complain about the ll format specifiers used. Now we are turning the
842 // warnings back on. If MinGW starts to support diagnostic stacks, we can
843 // replace this with a pop.
844 #pragma GCC diagnostic warning "-Wformat"
845 #pragma GCC diagnostic warning "-Wformat-extra-args"
846#endif