blob: 3a0e5569f933efbce328288db174672c4d3fe5a6 [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
Reid Klecknerba5757d2015-11-05 01:07:54 +0000209enum {
210#if defined(_M_X64)
211 NativeMachineType = IMAGE_FILE_MACHINE_AMD64
212#else
213 NativeMachineType = IMAGE_FILE_MACHINE_I386
214#endif
215};
216
217static bool printStackTraceWithLLVMSymbolizer(llvm::raw_ostream &OS,
218 HANDLE hProcess, HANDLE hThread,
219 STACKFRAME64 &StackFrameOrig,
220 CONTEXT *ContextOrig) {
221 // StackWalk64 modifies the incoming stack frame and context, so copy them.
222 STACKFRAME64 StackFrame = StackFrameOrig;
223
224 // Copy the register context so that we don't modify it while we unwind. We
225 // could use InitializeContext + CopyContext, but that's only required to get
226 // at AVX registers, which typically aren't needed by StackWalk64. Reduce the
227 // flag set to indicate that there's less data.
228 CONTEXT Context = *ContextOrig;
229 Context.ContextFlags = CONTEXT_CONTROL | CONTEXT_INTEGER;
230
231 static void *StackTrace[256];
Aaron Ballman3c44b422015-11-05 14:22:56 +0000232 size_t Depth = 0;
Reid Klecknerba5757d2015-11-05 01:07:54 +0000233 while (fStackWalk64(NativeMachineType, hProcess, hThread, &StackFrame,
234 &Context, 0, fSymFunctionTableAccess64,
235 fSymGetModuleBase64, 0)) {
236 if (StackFrame.AddrFrame.Offset == 0)
237 break;
238 StackTrace[Depth++] = (void *)(uintptr_t)StackFrame.AddrPC.Offset;
239 if (Depth >= array_lengthof(StackTrace))
240 break;
241 }
242
243 return printSymbolizedStackTrace(&StackTrace[0], Depth, OS);
244}
245
246namespace {
247struct FindModuleData {
248 void **StackTrace;
249 int Depth;
250 const char **Modules;
251 intptr_t *Offsets;
252 StringSaver *StrPool;
253};
254}
255
NAKAMURA Takumi2de1b322016-03-07 00:13:09 +0000256static BOOL CALLBACK findModuleCallback(PCSTR ModuleName,
Reid Klecknerba5757d2015-11-05 01:07:54 +0000257 DWORD64 ModuleBase, ULONG ModuleSize,
258 void *VoidData) {
259 FindModuleData *Data = (FindModuleData*)VoidData;
260 intptr_t Beg = ModuleBase;
261 intptr_t End = Beg + ModuleSize;
262 for (int I = 0; I < Data->Depth; I++) {
263 if (Data->Modules[I])
264 continue;
265 intptr_t Addr = (intptr_t)Data->StackTrace[I];
266 if (Beg <= Addr && Addr < End) {
267 Data->Modules[I] = Data->StrPool->save(ModuleName);
268 Data->Offsets[I] = Addr - Beg;
269 }
270 }
271 return TRUE;
272}
273
274static bool findModulesAndOffsets(void **StackTrace, int Depth,
275 const char **Modules, intptr_t *Offsets,
276 const char *MainExecutableName,
277 StringSaver &StrPool) {
278 if (!fEnumerateLoadedModules)
279 return false;
280 FindModuleData Data;
281 Data.StackTrace = StackTrace;
282 Data.Depth = Depth;
283 Data.Modules = Modules;
284 Data.Offsets = Offsets;
285 Data.StrPool = &StrPool;
286 fEnumerateLoadedModules(GetCurrentProcess(), findModuleCallback, &Data);
287 return true;
288}
289
Zachary Turnercd132c92015-03-05 19:10:52 +0000290static void PrintStackTraceForThread(llvm::raw_ostream &OS, HANDLE hProcess,
Zachary Turner62b7b612015-03-05 17:47:52 +0000291 HANDLE hThread, STACKFRAME64 &StackFrame,
292 CONTEXT *Context) {
Zachary Turner62b7b612015-03-05 17:47:52 +0000293 // Initialize the symbol handler.
Leny Kholodovbebb27b2015-07-02 14:34:57 +0000294 fSymSetOptions(SYMOPT_DEFERRED_LOADS | SYMOPT_LOAD_LINES);
295 fSymInitialize(hProcess, NULL, TRUE);
Zachary Turner62b7b612015-03-05 17:47:52 +0000296
Reid Klecknerba5757d2015-11-05 01:07:54 +0000297 // Try llvm-symbolizer first. llvm-symbolizer knows how to deal with both PDBs
298 // and DWARF, so it should do a good job regardless of what debug info or
299 // linker is in use.
300 if (printStackTraceWithLLVMSymbolizer(OS, hProcess, hThread, StackFrame,
301 Context)) {
302 return;
303 }
304
Zachary Turner62b7b612015-03-05 17:47:52 +0000305 while (true) {
Reid Klecknerba5757d2015-11-05 01:07:54 +0000306 if (!fStackWalk64(NativeMachineType, hProcess, hThread, &StackFrame,
307 Context, 0, fSymFunctionTableAccess64,
308 fSymGetModuleBase64, 0)) {
Zachary Turner62b7b612015-03-05 17:47:52 +0000309 break;
310 }
311
312 if (StackFrame.AddrFrame.Offset == 0)
313 break;
314
Zachary Turnercd132c92015-03-05 19:10:52 +0000315 using namespace llvm;
Zachary Turner62b7b612015-03-05 17:47:52 +0000316 // Print the PC in hexadecimal.
317 DWORD64 PC = StackFrame.AddrPC.Offset;
318#if defined(_M_X64)
Zachary Turnercd132c92015-03-05 19:10:52 +0000319 OS << format("0x%016llX", PC);
Zachary Turner62b7b612015-03-05 17:47:52 +0000320#elif defined(_M_IX86)
Zachary Turnercd132c92015-03-05 19:10:52 +0000321 OS << format("0x%08lX", static_cast<DWORD>(PC));
Zachary Turner62b7b612015-03-05 17:47:52 +0000322#endif
323
324// Print the parameters. Assume there are four.
325#if defined(_M_X64)
Zachary Turnercd132c92015-03-05 19:10:52 +0000326 OS << format(" (0x%016llX 0x%016llX 0x%016llX 0x%016llX)",
Zachary Turner62b7b612015-03-05 17:47:52 +0000327 StackFrame.Params[0], StackFrame.Params[1], StackFrame.Params[2],
328 StackFrame.Params[3]);
329#elif defined(_M_IX86)
Zachary Turnercd132c92015-03-05 19:10:52 +0000330 OS << format(" (0x%08lX 0x%08lX 0x%08lX 0x%08lX)",
Zachary Turner62b7b612015-03-05 17:47:52 +0000331 static_cast<DWORD>(StackFrame.Params[0]),
332 static_cast<DWORD>(StackFrame.Params[1]),
333 static_cast<DWORD>(StackFrame.Params[2]),
334 static_cast<DWORD>(StackFrame.Params[3]));
335#endif
336 // Verify the PC belongs to a module in this process.
Leny Kholodovbebb27b2015-07-02 14:34:57 +0000337 if (!fSymGetModuleBase64(hProcess, PC)) {
Zachary Turnercd132c92015-03-05 19:10:52 +0000338 OS << " <unknown module>\n";
Zachary Turner62b7b612015-03-05 17:47:52 +0000339 continue;
340 }
341
342 // Print the symbol name.
343 char buffer[512];
344 IMAGEHLP_SYMBOL64 *symbol = reinterpret_cast<IMAGEHLP_SYMBOL64 *>(buffer);
345 memset(symbol, 0, sizeof(IMAGEHLP_SYMBOL64));
346 symbol->SizeOfStruct = sizeof(IMAGEHLP_SYMBOL64);
347 symbol->MaxNameLength = 512 - sizeof(IMAGEHLP_SYMBOL64);
348
349 DWORD64 dwDisp;
Leny Kholodovbebb27b2015-07-02 14:34:57 +0000350 if (!fSymGetSymFromAddr64(hProcess, PC, &dwDisp, symbol)) {
Zachary Turnercd132c92015-03-05 19:10:52 +0000351 OS << '\n';
Zachary Turner62b7b612015-03-05 17:47:52 +0000352 continue;
353 }
354
355 buffer[511] = 0;
356 if (dwDisp > 0)
Zachary Turnercd132c92015-03-05 19:10:52 +0000357 OS << format(", %s() + 0x%llX bytes(s)", (const char*)symbol->Name,
358 dwDisp);
Zachary Turner62b7b612015-03-05 17:47:52 +0000359 else
Zachary Turnercd132c92015-03-05 19:10:52 +0000360 OS << format(", %s", (const char*)symbol->Name);
Zachary Turner62b7b612015-03-05 17:47:52 +0000361
362 // Print the source file and line number information.
Yaron Keren24a86df2015-04-24 15:39:47 +0000363 IMAGEHLP_LINE64 line = {};
Zachary Turner62b7b612015-03-05 17:47:52 +0000364 DWORD dwLineDisp;
Zachary Turner62b7b612015-03-05 17:47:52 +0000365 line.SizeOfStruct = sizeof(line);
Leny Kholodovbebb27b2015-07-02 14:34:57 +0000366 if (fSymGetLineFromAddr64(hProcess, PC, &dwLineDisp, &line)) {
Zachary Turnercd132c92015-03-05 19:10:52 +0000367 OS << format(", %s, line %lu", line.FileName, line.LineNumber);
Zachary Turner62b7b612015-03-05 17:47:52 +0000368 if (dwLineDisp > 0)
Zachary Turnercd132c92015-03-05 19:10:52 +0000369 OS << format(" + 0x%lX byte(s)", dwLineDisp);
Zachary Turner62b7b612015-03-05 17:47:52 +0000370 }
371
Zachary Turnercd132c92015-03-05 19:10:52 +0000372 OS << '\n';
Zachary Turner62b7b612015-03-05 17:47:52 +0000373 }
374}
375
Reid Spencer3d7a6142004-08-29 19:22:48 +0000376namespace llvm {
Reid Spencer3d7a6142004-08-29 19:22:48 +0000377
378//===----------------------------------------------------------------------===//
Mikhail Glushenkovf64d93d2010-10-21 20:40:39 +0000379//=== WARNING: Implementation here must contain only Win32 specific code
Reid Spencer4aff78a2004-09-16 15:53:16 +0000380//=== and must not be UNIX code
Reid Spencer3d7a6142004-08-29 19:22:48 +0000381//===----------------------------------------------------------------------===//
382
Daniel Dunbar1bdedd32009-09-22 15:58:35 +0000383#ifdef _MSC_VER
Reid Klecknerbd39f212013-04-05 16:18:03 +0000384/// AvoidMessageBoxHook - Emulates hitting "retry" from an "abort, retry,
385/// ignore" CRT debug report dialog. "retry" raises an exception which
386/// ultimately triggers our stack dumper.
Reid Kleckner542a4542015-02-26 21:08:21 +0000387static LLVM_ATTRIBUTE_UNUSED int
388AvoidMessageBoxHook(int ReportType, char *Message, int *Return) {
Reid Klecknerbd39f212013-04-05 16:18:03 +0000389 // Set *Return to the retry code for the return value of _CrtDbgReport:
390 // http://msdn.microsoft.com/en-us/library/8hyw4sy7(v=vs.71).aspx
391 // This may also trigger just-in-time debugging via DebugBreak().
392 if (Return)
393 *Return = 1;
394 // Don't call _CrtDbgReport.
395 return TRUE;
396}
397
Daniel Dunbar1bdedd32009-09-22 15:58:35 +0000398#endif
Daniel Dunbar4c7b0ca2009-09-22 09:50:28 +0000399
Aaron Ballman03b968e2015-01-29 20:48:34 +0000400extern "C" void HandleAbort(int Sig) {
Michael J. Spencer89b0ad22015-01-29 17:20:29 +0000401 if (Sig == SIGABRT) {
402 LLVM_BUILTIN_TRAP;
403 }
404}
405
Aaron Ballman50af8d42015-03-26 16:24:38 +0000406static void InitializeThreading() {
407 if (CriticalSectionInitialized)
408 return;
409
410 // Now's the time to create the critical section. This is the first time
411 // through here, and there's only one thread.
412 InitializeCriticalSection(&CriticalSection);
413 CriticalSectionInitialized = true;
414}
415
Daniel Dunbar4c7b0ca2009-09-22 09:50:28 +0000416static void RegisterHandler() {
Leny Kholodovbebb27b2015-07-02 14:34:57 +0000417 // If we cannot load up the APIs (which would be unexpected as they should
418 // exist on every version of Windows we support), we will bail out since
419 // there would be nothing to report.
Reid Kleckner6cdf8442016-01-11 21:07:48 +0000420 if (!load64BitDebugHelp()) {
421 assert(false && "These APIs should always be available");
422 return;
423 }
Michael J. Spencer44a36c82011-10-01 00:05:20 +0000424
Reid Spencer1bdd0f02004-09-19 05:37:39 +0000425 if (RegisteredUnhandledExceptionFilter) {
Reid Spencer90debc52004-09-17 03:02:27 +0000426 EnterCriticalSection(&CriticalSection);
Reid Spencer4aff78a2004-09-16 15:53:16 +0000427 return;
Reid Spencer90debc52004-09-17 03:02:27 +0000428 }
Reid Spencer4aff78a2004-09-16 15:53:16 +0000429
Aaron Ballman50af8d42015-03-26 16:24:38 +0000430 InitializeThreading();
Reid Spencer4aff78a2004-09-16 15:53:16 +0000431
432 // Enter it immediately. Now if someone hits CTRL/C, the console handler
433 // can't proceed until the globals are updated.
434 EnterCriticalSection(&CriticalSection);
435
436 RegisteredUnhandledExceptionFilter = true;
Reid Spencer1bdd0f02004-09-19 05:37:39 +0000437 OldFilter = SetUnhandledExceptionFilter(LLVMUnhandledExceptionFilter);
Reid Spencer4aff78a2004-09-16 15:53:16 +0000438 SetConsoleCtrlHandler(LLVMConsoleCtrlHandler, TRUE);
439
440 // IMPORTANT NOTE: Caller must call LeaveCriticalSection(&CriticalSection) or
441 // else multi-threading problems will ensue.
442}
443
Reid Spencer3d7a6142004-08-29 19:22:48 +0000444// RemoveFileOnSignal - The public API
Rafael Espindola4f35da72013-06-13 21:16:58 +0000445bool sys::RemoveFileOnSignal(StringRef Filename, std::string* ErrMsg) {
Reid Spencer4aff78a2004-09-16 15:53:16 +0000446 RegisterHandler();
447
Reid Spencer50eac3b2006-08-25 21:37:17 +0000448 if (CleanupExecuted) {
449 if (ErrMsg)
450 *ErrMsg = "Process terminating -- cannot register for removal";
451 return true;
452 }
Reid Spencer1bdd0f02004-09-19 05:37:39 +0000453
Reid Spencer4aff78a2004-09-16 15:53:16 +0000454 if (FilesToRemove == NULL)
Rafael Espindola4f35da72013-06-13 21:16:58 +0000455 FilesToRemove = new std::vector<std::string>;
Reid Spencer4aff78a2004-09-16 15:53:16 +0000456
Reid Spencerf070b6c2004-11-16 06:59:53 +0000457 FilesToRemove->push_back(Filename);
Reid Spencer4aff78a2004-09-16 15:53:16 +0000458
459 LeaveCriticalSection(&CriticalSection);
Reid Spencer50eac3b2006-08-25 21:37:17 +0000460 return false;
Reid Spencer3d7a6142004-08-29 19:22:48 +0000461}
462
Dan Gohmane201c072010-09-01 14:17:34 +0000463// DontRemoveFileOnSignal - The public API
Rafael Espindola4f35da72013-06-13 21:16:58 +0000464void sys::DontRemoveFileOnSignal(StringRef Filename) {
Dan Gohmane201c072010-09-01 14:17:34 +0000465 if (FilesToRemove == NULL)
466 return;
467
NAKAMURA Takumi3f688b92010-10-22 01:23:50 +0000468 RegisterHandler();
469
Rafael Espindola4f35da72013-06-13 21:16:58 +0000470 std::vector<std::string>::reverse_iterator I =
Dan Gohmane201c072010-09-01 14:17:34 +0000471 std::find(FilesToRemove->rbegin(), FilesToRemove->rend(), Filename);
472 if (I != FilesToRemove->rend())
473 FilesToRemove->erase(I.base()-1);
474
475 LeaveCriticalSection(&CriticalSection);
476}
477
Michael J. Spencer89b0ad22015-01-29 17:20:29 +0000478void sys::DisableSystemDialogsOnCrash() {
479 // Crash to stack trace handler on abort.
480 signal(SIGABRT, HandleAbort);
481
482 // The following functions are not reliably accessible on MinGW.
483#ifdef _MSC_VER
484 // We're already handling writing a "something went wrong" message.
485 _set_abort_behavior(0, _WRITE_ABORT_MSG);
486 // Disable Dr. Watson.
487 _set_abort_behavior(0, _CALL_REPORTFAULT);
488 _CrtSetReportHook(AvoidMessageBoxHook);
489#endif
490
491 // Disable standard error dialog box.
492 SetErrorMode(SEM_FAILCRITICALERRORS | SEM_NOGPFAULTERRORBOX |
493 SEM_NOOPENFILEERRORBOX);
494 _set_error_mode(_OUT_TO_STDERR);
495}
496
Reid Spencer3d7a6142004-08-29 19:22:48 +0000497/// PrintStackTraceOnErrorSignal - When an error signal (such as SIBABRT or
498/// SIGSEGV) is delivered to the process, print a stack trace and then exit.
Pete Cooper6bea2f42015-04-07 20:43:23 +0000499void sys::PrintStackTraceOnErrorSignal(bool DisableCrashReporting) {
Leny Kholodov1b73e662016-05-04 16:56:51 +0000500 if (DisableCrashReporting || getenv("LLVM_DISABLE_CRASH_REPORT"))
501 Process::PreventCoreFiles();
502
Michael J. Spencer89b0ad22015-01-29 17:20:29 +0000503 DisableSystemDialogsOnCrash();
Reid Spencer4aff78a2004-09-16 15:53:16 +0000504 RegisterHandler();
505 LeaveCriticalSection(&CriticalSection);
Reid Spencer3d7a6142004-08-29 19:22:48 +0000506}
Benjamin Kramerf97eff62015-03-11 15:41:15 +0000507}
508
Yaron Kerenbdae8d62015-03-14 19:20:56 +0000509#if defined(__MINGW32__) && !defined(__MINGW64_VERSION_MAJOR)
510// Provide a prototype for RtlCaptureContext, mingw32 from mingw.org is
511// missing it but mingw-w64 has it.
Benjamin Kramerf97eff62015-03-11 15:41:15 +0000512extern "C" VOID WINAPI RtlCaptureContext(PCONTEXT ContextRecord);
Benjamin Kramerb47d5492015-03-11 16:09:02 +0000513#endif
Reid Spencer3d7a6142004-08-29 19:22:48 +0000514
Zachary Turnercd132c92015-03-05 19:10:52 +0000515void llvm::sys::PrintStackTrace(raw_ostream &OS) {
Reid Klecknere6580582015-03-05 18:26:58 +0000516 STACKFRAME64 StackFrame = {};
Yaron Keren24a86df2015-04-24 15:39:47 +0000517 CONTEXT Context = {};
Zachary Turner62b7b612015-03-05 17:47:52 +0000518 ::RtlCaptureContext(&Context);
519#if defined(_M_X64)
520 StackFrame.AddrPC.Offset = Context.Rip;
521 StackFrame.AddrStack.Offset = Context.Rsp;
522 StackFrame.AddrFrame.Offset = Context.Rbp;
523#else
524 StackFrame.AddrPC.Offset = Context.Eip;
525 StackFrame.AddrStack.Offset = Context.Esp;
526 StackFrame.AddrFrame.Offset = Context.Ebp;
527#endif
528 StackFrame.AddrPC.Mode = AddrModeFlat;
529 StackFrame.AddrStack.Mode = AddrModeFlat;
530 StackFrame.AddrFrame.Mode = AddrModeFlat;
Zachary Turnercd132c92015-03-05 19:10:52 +0000531 PrintStackTraceForThread(OS, GetCurrentProcess(), GetCurrentThread(),
Zachary Turner62b7b612015-03-05 17:47:52 +0000532 StackFrame, &Context);
Argyrios Kyrtzidiseb9ae762013-01-09 19:42:40 +0000533}
534
Chris Lattner6a5d6ec2005-08-02 02:14:22 +0000535
Benjamin Kramer90c2db22015-03-11 15:53:24 +0000536void llvm::sys::SetInterruptFunction(void (*IF)()) {
Jeff Cohenba7cc682005-08-02 03:04:47 +0000537 RegisterHandler();
Jeff Cohen9aafa062005-08-02 03:26:32 +0000538 InterruptFunction = IF;
Jeff Cohenba7cc682005-08-02 03:04:47 +0000539 LeaveCriticalSection(&CriticalSection);
Chris Lattner6a5d6ec2005-08-02 02:14:22 +0000540}
Sebastian Redl8d5baa02009-03-19 23:26:52 +0000541
542
543/// AddSignalHandler - Add a function to be called when a signal is delivered
544/// to the process. The handler can have a cookie passed to it to identify
545/// what instance of the handler it is.
Benjamin Kramerb47d5492015-03-11 16:09:02 +0000546void llvm::sys::AddSignalHandler(void (*FnPtr)(void *), void *Cookie) {
Sebastian Redl8d5baa02009-03-19 23:26:52 +0000547 CallBacksToRun->push_back(std::make_pair(FnPtr, Cookie));
548 RegisterHandler();
Torok Edwin6fb09562010-03-31 12:07:16 +0000549 LeaveCriticalSection(&CriticalSection);
Sebastian Redl8d5baa02009-03-19 23:26:52 +0000550}
Reid Spencer3d7a6142004-08-29 19:22:48 +0000551
Reid Spencer4aff78a2004-09-16 15:53:16 +0000552static void Cleanup() {
Yaron Keren356aa462015-05-19 13:31:25 +0000553 if (CleanupExecuted)
554 return;
555
Reid Spencer4aff78a2004-09-16 15:53:16 +0000556 EnterCriticalSection(&CriticalSection);
557
Reid Spencer1bdd0f02004-09-19 05:37:39 +0000558 // Prevent other thread from registering new files and directories for
559 // removal, should we be executing because of the console handler callback.
560 CleanupExecuted = true;
561
562 // FIXME: open files cannot be deleted.
Reid Spencer4aff78a2004-09-16 15:53:16 +0000563 if (FilesToRemove != NULL)
564 while (!FilesToRemove->empty()) {
Rafael Espindolad724c282014-02-23 13:37:37 +0000565 llvm::sys::fs::remove(FilesToRemove->back());
Reid Spencer4aff78a2004-09-16 15:53:16 +0000566 FilesToRemove->pop_back();
567 }
Yaron Keren28738102015-07-22 21:11:17 +0000568 llvm::sys::RunSignalHandlers();
Reid Spencer4aff78a2004-09-16 15:53:16 +0000569 LeaveCriticalSection(&CriticalSection);
570}
571
Daniel Dunbar68272562010-05-08 02:10:34 +0000572void llvm::sys::RunInterruptHandlers() {
Aaron Ballman50af8d42015-03-26 16:24:38 +0000573 // The interrupt handler may be called from an interrupt, but it may also be
574 // called manually (such as the case of report_fatal_error with no registered
575 // error handler). We must ensure that the critical section is properly
576 // initialized.
577 InitializeThreading();
Daniel Dunbar68272562010-05-08 02:10:34 +0000578 Cleanup();
579}
580
Leny Kholodov1b73e662016-05-04 16:56:51 +0000581/// \brief Find the Windows Registry Key for a given location.
582///
583/// \returns a valid HKEY if the location exists, else NULL.
584static HKEY FindWERKey(const llvm::Twine &RegistryLocation) {
585 HKEY Key;
586 if (ERROR_SUCCESS != ::RegOpenKeyEx(HKEY_LOCAL_MACHINE,
587 RegistryLocation.str().c_str(), 0,
588 KEY_QUERY_VALUE | KEY_READ, &Key))
589 return NULL;
590
591 return Key;
592}
593
594/// \brief Populate ResultDirectory with the value for "DumpFolder" for a given
595/// Windows Registry key.
596///
597/// \returns true if a valid value for DumpFolder exists, false otherwise.
598static bool GetDumpFolder(HKEY Key,
599 llvm::SmallVectorImpl<char> &ResultDirectory) {
600 using llvm::sys::windows::UTF16ToUTF8;
601
602 if (!Key)
603 return false;
604
605 DWORD BufferLengthBytes = 0;
606
607 if (ERROR_SUCCESS != ::RegGetValueW(Key, 0, L"DumpFolder", REG_EXPAND_SZ,
608 NULL, NULL, &BufferLengthBytes))
609 return false;
610
611 SmallVector<wchar_t, MAX_PATH> Buffer(BufferLengthBytes);
612
613 if (ERROR_SUCCESS != ::RegGetValueW(Key, 0, L"DumpFolder", REG_EXPAND_SZ,
614 NULL, Buffer.data(), &BufferLengthBytes))
615 return false;
616
617 DWORD ExpandBufferSize = ::ExpandEnvironmentStringsW(Buffer.data(), NULL, 0);
618
619 if (!ExpandBufferSize)
620 return false;
621
622 SmallVector<wchar_t, MAX_PATH> ExpandBuffer(ExpandBufferSize);
623
624 if (ExpandBufferSize != ::ExpandEnvironmentStringsW(Buffer.data(),
625 ExpandBuffer.data(),
626 ExpandBufferSize))
627 return false;
628
629 if (UTF16ToUTF8(ExpandBuffer.data(), ExpandBufferSize - 1, ResultDirectory))
630 return false;
631
632 return true;
633}
634
635/// \brief Populate ResultType with a valid MINIDUMP_TYPE based on the value of
636/// "DumpType" for a given Windows Registry key.
637///
638/// According to
639/// https://msdn.microsoft.com/en-us/library/windows/desktop/bb787181(v=vs.85).aspx
640/// valid values for DumpType are:
641/// * 0: Custom dump
642/// * 1: Mini dump
643/// * 2: Full dump
644/// If "Custom dump" is specified then the "CustomDumpFlags" field is read
645/// containing a bitwise combination of MINIDUMP_TYPE values.
646///
647/// \returns true if a valid value for ResultType can be set, false otherwise.
648static bool GetDumpType(HKEY Key, MINIDUMP_TYPE &ResultType) {
649 if (!Key)
650 return false;
651
652 DWORD DumpType;
653 DWORD TypeSize = sizeof(DumpType);
654 if (ERROR_SUCCESS != ::RegGetValueW(Key, NULL, L"DumpType", RRF_RT_REG_DWORD,
655 NULL, &DumpType,
656 &TypeSize))
657 return false;
658
659 switch (DumpType) {
660 case 0: {
661 DWORD Flags = 0;
662 if (ERROR_SUCCESS != ::RegGetValueW(Key, NULL, L"CustomDumpFlags",
663 RRF_RT_REG_DWORD, NULL, &Flags,
664 &TypeSize))
665 return false;
666
667 ResultType = static_cast<MINIDUMP_TYPE>(Flags);
668 break;
669 }
670 case 1:
671 ResultType = MiniDumpNormal;
672 break;
673 case 2:
674 ResultType = MiniDumpWithFullMemory;
675 break;
676 default:
677 return false;
678 }
679 return true;
680}
681
682/// \brief Write a Windows dump file containing process information that can be
683/// used for post-mortem debugging.
684///
685/// \returns zero error code if a mini dump created, actual error code
686/// otherwise.
687static std::error_code WINAPI
688WriteWindowsDumpFile(PMINIDUMP_EXCEPTION_INFORMATION ExceptionInfo) {
689 using namespace llvm;
690 using namespace llvm::sys;
691
692 std::string MainExecutableName = fs::getMainExecutable(nullptr, nullptr);
693 StringRef ProgramName;
694
695 if (MainExecutableName.empty()) {
696 // If we can't get the executable filename,
697 // things are in worse shape than we realize
698 // and we should just bail out.
699 return mapWindowsError(::GetLastError());
700 }
701
702 ProgramName = path::filename(MainExecutableName.c_str());
703
704 // The Windows Registry location as specified at
705 // https://msdn.microsoft.com/en-us/library/windows/desktop/bb787181%28v=vs.85%29.aspx
706 // "Collecting User-Mode Dumps" that may optionally be set to collect crash
707 // dumps in a specified location.
708 StringRef LocalDumpsRegistryLocation =
709 "SOFTWARE\\Microsoft\\Windows\\Windows Error Reporting\\LocalDumps";
710
711 // The key pointing to the Registry location that may contain global crash
712 // dump settings. This will be NULL if the location can not be found.
713 ScopedRegHandle DefaultLocalDumpsKey(FindWERKey(LocalDumpsRegistryLocation));
714
715 // The key pointing to the Registry location that may contain
716 // application-specific crash dump settings. This will be NULL if the
717 // location can not be found.
718 ScopedRegHandle AppSpecificKey(
719 FindWERKey(Twine(LocalDumpsRegistryLocation) + "\\" + ProgramName));
720
721 // Look to see if a dump type is specified in the registry; first with the
722 // app-specific key and failing that with the global key. If none are found
723 // default to a normal dump (GetDumpType will return false either if the key
724 // is NULL or if there is no valid DumpType value at its location).
725 MINIDUMP_TYPE DumpType;
726 if (!GetDumpType(AppSpecificKey, DumpType))
727 if (!GetDumpType(DefaultLocalDumpsKey, DumpType))
728 DumpType = MiniDumpNormal;
729
730 // Look to see if a dump location is specified in the registry; first with the
731 // app-specific key and failing that with the global key. If none are found
732 // we'll just create the dump file in the default temporary file location
733 // (GetDumpFolder will return false either if the key is NULL or if there is
734 // no valid DumpFolder value at its location).
735 bool ExplicitDumpDirectorySet = true;
736 SmallString<MAX_PATH> DumpDirectory;
737 if (!GetDumpFolder(AppSpecificKey, DumpDirectory))
738 if (!GetDumpFolder(DefaultLocalDumpsKey, DumpDirectory))
739 ExplicitDumpDirectorySet = false;
740
741 int FD;
742 SmallString<MAX_PATH> DumpPath;
743
744 if (ExplicitDumpDirectorySet) {
745 if (std::error_code EC = fs::create_directories(DumpDirectory))
746 return EC;
747 if (std::error_code EC = fs::createUniqueFile(
748 Twine(DumpDirectory) + "\\" + ProgramName + ".%%%%%%.dmp", FD,
749 DumpPath))
750 return EC;
751 } else if (std::error_code EC =
752 fs::createTemporaryFile(ProgramName, "dmp", FD, DumpPath))
753 return EC;
754
755 // Our support functions return a file descriptor but Windows wants a handle.
756 ScopedCommonHandle FileHandle(reinterpret_cast<HANDLE>(_get_osfhandle(FD)));
757
758 if (!fMiniDumpWriteDump(::GetCurrentProcess(), ::GetCurrentProcessId(),
759 FileHandle, DumpType, ExceptionInfo, NULL, NULL))
760 return mapWindowsError(::GetLastError());
761
762 llvm::errs() << "Wrote crash dump file \"" << DumpPath << "\"\n";
763 return std::error_code();
764}
765
Reid Spencer4aff78a2004-09-16 15:53:16 +0000766static LONG WINAPI LLVMUnhandledExceptionFilter(LPEXCEPTION_POINTERS ep) {
Mikhail Glushenkov32acd742010-10-27 09:09:04 +0000767 Cleanup();
Mikhail Glushenkovf64d93d2010-10-21 20:40:39 +0000768
Leny Kholodov1b73e662016-05-04 16:56:51 +0000769 // We'll automatically write a Minidump file here to help diagnose
770 // the nasty sorts of crashes that aren't 100% reproducible from a set of
771 // inputs (or in the event that the user is unable or unwilling to provide a
772 // reproducible case).
773 if (!llvm::Process::AreCoreFilesPrevented()) {
774 MINIDUMP_EXCEPTION_INFORMATION ExceptionInfo;
775 ExceptionInfo.ThreadId = ::GetCurrentThreadId();
776 ExceptionInfo.ExceptionPointers = ep;
777 ExceptionInfo.ClientPointers = FALSE;
778
779 if (std::error_code EC = WriteWindowsDumpFile(&ExceptionInfo))
780 llvm::errs() << "Could not write crash dump file: " << EC.message()
781 << "\n";
782 }
783
Mikhail Glushenkov080d86f2010-10-28 08:25:44 +0000784 // Initialize the STACKFRAME structure.
Yaron Keren24a86df2015-04-24 15:39:47 +0000785 STACKFRAME64 StackFrame = {};
Reid Spencer4aff78a2004-09-16 15:53:16 +0000786
Michael J. Spencer44a36c82011-10-01 00:05:20 +0000787#if defined(_M_X64)
Michael J. Spencer44a36c82011-10-01 00:05:20 +0000788 StackFrame.AddrPC.Offset = ep->ContextRecord->Rip;
789 StackFrame.AddrPC.Mode = AddrModeFlat;
790 StackFrame.AddrStack.Offset = ep->ContextRecord->Rsp;
791 StackFrame.AddrStack.Mode = AddrModeFlat;
792 StackFrame.AddrFrame.Offset = ep->ContextRecord->Rbp;
793 StackFrame.AddrFrame.Mode = AddrModeFlat;
794#elif defined(_M_IX86)
Mikhail Glushenkov080d86f2010-10-28 08:25:44 +0000795 StackFrame.AddrPC.Offset = ep->ContextRecord->Eip;
796 StackFrame.AddrPC.Mode = AddrModeFlat;
797 StackFrame.AddrStack.Offset = ep->ContextRecord->Esp;
798 StackFrame.AddrStack.Mode = AddrModeFlat;
799 StackFrame.AddrFrame.Offset = ep->ContextRecord->Ebp;
800 StackFrame.AddrFrame.Mode = AddrModeFlat;
Michael J. Spencer44a36c82011-10-01 00:05:20 +0000801#endif
Reid Spencer4aff78a2004-09-16 15:53:16 +0000802
Mikhail Glushenkov080d86f2010-10-28 08:25:44 +0000803 HANDLE hProcess = GetCurrentProcess();
804 HANDLE hThread = GetCurrentThread();
Zachary Turnercd132c92015-03-05 19:10:52 +0000805 PrintStackTraceForThread(llvm::errs(), hProcess, hThread, StackFrame,
Zachary Turner62b7b612015-03-05 17:47:52 +0000806 ep->ContextRecord);
Mikhail Glushenkov080d86f2010-10-28 08:25:44 +0000807
Michael J. Spencer89b0ad22015-01-29 17:20:29 +0000808 _exit(ep->ExceptionRecord->ExceptionCode);
Reid Spencer4aff78a2004-09-16 15:53:16 +0000809}
810
811static BOOL WINAPI LLVMConsoleCtrlHandler(DWORD dwCtrlType) {
Jeff Cohen9aafa062005-08-02 03:26:32 +0000812 // We are running in our very own thread, courtesy of Windows.
Jeff Cohenba7cc682005-08-02 03:04:47 +0000813 EnterCriticalSection(&CriticalSection);
Reid Spencer4aff78a2004-09-16 15:53:16 +0000814 Cleanup();
815
Jeff Cohenba7cc682005-08-02 03:04:47 +0000816 // If an interrupt function has been set, go and run one it; otherwise,
817 // the process dies.
818 void (*IF)() = InterruptFunction;
819 InterruptFunction = 0; // Don't run it on another CTRL-C.
820
821 if (IF) {
Jeff Cohen9aafa062005-08-02 03:26:32 +0000822 // Note: if the interrupt function throws an exception, there is nothing
823 // to catch it in this thread so it will kill the process.
824 IF(); // Run it now.
Jeff Cohenba7cc682005-08-02 03:04:47 +0000825 LeaveCriticalSection(&CriticalSection);
826 return TRUE; // Don't kill the process.
827 }
828
Reid Spencer90debc52004-09-17 03:02:27 +0000829 // Allow normal processing to take place; i.e., the process dies.
Jeff Cohenba7cc682005-08-02 03:04:47 +0000830 LeaveCriticalSection(&CriticalSection);
Reid Spencer4aff78a2004-09-16 15:53:16 +0000831 return FALSE;
832}
Michael J. Spencer44a36c82011-10-01 00:05:20 +0000833
834#if __MINGW32__
835 // We turned these warnings off for this file so that MinGW-g++ doesn't
836 // complain about the ll format specifiers used. Now we are turning the
837 // warnings back on. If MinGW starts to support diagnostic stacks, we can
838 // replace this with a pop.
839 #pragma GCC diagnostic warning "-Wformat"
840 #pragma GCC diagnostic warning "-Wformat-extra-args"
841#endif