blob: 23fc72ec10e2c80ee40c1995e4ff5fd5e8ec66fd [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
Zachary Turnerab266cf2016-12-21 18:50:52 +000031 #include <crtdbg.h>
Reid Spencer187b4ad2006-06-01 19:03:21 +000032 #include <dbghelp.h>
Reid Spencer99049282004-09-23 14:47:10 +000033#endif
34#include <psapi.h>
Reid Spencer4aff78a2004-09-16 15:53:16 +000035
Michael J. Spencer44a36c82011-10-01 00:05:20 +000036#ifdef _MSC_VER
37 #pragma comment(lib, "psapi.lib")
Michael J. Spencer44a36c82011-10-01 00:05:20 +000038#elif __MINGW32__
Leny Kholodovbebb27b2015-07-02 14:34:57 +000039 #if (HAVE_LIBPSAPI != 1)
40 #error "libpsapi.a should be present"
Reid Spencer187b4ad2006-06-01 19:03:21 +000041 #endif
Michael J. Spencer44a36c82011-10-01 00:05:20 +000042 // The version of g++ that comes with MinGW does *not* properly understand
43 // the ll format specifier for printf. However, MinGW passes the format
44 // specifiers on to the MSVCRT entirely, and the CRT understands the ll
45 // specifier. So these warnings are spurious in this case. Since we compile
46 // with -Wall, this will generate these warnings which should be ignored. So
47 // we will turn off the warnings for this just file. However, MinGW also does
48 // not support push and pop for diagnostics, so we have to manually turn it
49 // back on at the end of the file.
50 #pragma GCC diagnostic ignored "-Wformat"
51 #pragma GCC diagnostic ignored "-Wformat-extra-args"
52
Anton Korobeynikovb27f11e2011-10-21 09:38:50 +000053 #if !defined(__MINGW64_VERSION_MAJOR)
54 // MinGW.org does not have updated support for the 64-bit versions of the
55 // DebugHlp APIs. So we will have to load them manually. The structures and
56 // method signatures were pulled from DbgHelp.h in the Windows Platform SDK,
57 // and adjusted for brevity.
Michael J. Spencer44a36c82011-10-01 00:05:20 +000058 typedef struct _IMAGEHLP_LINE64 {
59 DWORD SizeOfStruct;
60 PVOID Key;
61 DWORD LineNumber;
62 PCHAR FileName;
63 DWORD64 Address;
64 } IMAGEHLP_LINE64, *PIMAGEHLP_LINE64;
65
66 typedef struct _IMAGEHLP_SYMBOL64 {
67 DWORD SizeOfStruct;
68 DWORD64 Address;
69 DWORD Size;
70 DWORD Flags;
71 DWORD MaxNameLength;
72 CHAR Name[1];
73 } IMAGEHLP_SYMBOL64, *PIMAGEHLP_SYMBOL64;
74
75 typedef struct _tagADDRESS64 {
76 DWORD64 Offset;
77 WORD Segment;
78 ADDRESS_MODE Mode;
79 } ADDRESS64, *LPADDRESS64;
80
81 typedef struct _KDHELP64 {
82 DWORD64 Thread;
83 DWORD ThCallbackStack;
84 DWORD ThCallbackBStore;
85 DWORD NextCallback;
86 DWORD FramePointer;
87 DWORD64 KiCallUserMode;
88 DWORD64 KeUserCallbackDispatcher;
89 DWORD64 SystemRangeStart;
90 DWORD64 KiUserExceptionDispatcher;
91 DWORD64 StackBase;
92 DWORD64 StackLimit;
93 DWORD64 Reserved[5];
94 } KDHELP64, *PKDHELP64;
95
96 typedef struct _tagSTACKFRAME64 {
97 ADDRESS64 AddrPC;
98 ADDRESS64 AddrReturn;
99 ADDRESS64 AddrFrame;
100 ADDRESS64 AddrStack;
101 ADDRESS64 AddrBStore;
102 PVOID FuncTableEntry;
103 DWORD64 Params[4];
104 BOOL Far;
105 BOOL Virtual;
106 DWORD64 Reserved[3];
107 KDHELP64 KdHelp;
108 } STACKFRAME64, *LPSTACKFRAME64;
Leny Kholodovbebb27b2015-07-02 14:34:57 +0000109 #endif // !defined(__MINGW64_VERSION_MAJOR)
110#endif // __MINGW32__
Michael J. Spencer44a36c82011-10-01 00:05:20 +0000111
112typedef BOOL (__stdcall *PREAD_PROCESS_MEMORY_ROUTINE64)(HANDLE hProcess,
113 DWORD64 qwBaseAddress, PVOID lpBuffer, DWORD nSize,
114 LPDWORD lpNumberOfBytesRead);
115
116typedef PVOID (__stdcall *PFUNCTION_TABLE_ACCESS_ROUTINE64)( HANDLE ahProcess,
117 DWORD64 AddrBase);
118
119typedef DWORD64 (__stdcall *PGET_MODULE_BASE_ROUTINE64)(HANDLE hProcess,
120 DWORD64 Address);
121
122typedef DWORD64 (__stdcall *PTRANSLATE_ADDRESS_ROUTINE64)(HANDLE hProcess,
123 HANDLE hThread, LPADDRESS64 lpaddr);
124
Leny Kholodov1b73e662016-05-04 16:56:51 +0000125typedef BOOL(WINAPI *fpMiniDumpWriteDump)(HANDLE, DWORD, HANDLE, MINIDUMP_TYPE,
126 PMINIDUMP_EXCEPTION_INFORMATION,
127 PMINIDUMP_USER_STREAM_INFORMATION,
128 PMINIDUMP_CALLBACK_INFORMATION);
129static fpMiniDumpWriteDump fMiniDumpWriteDump;
130
Michael J. Spencer44a36c82011-10-01 00:05:20 +0000131typedef BOOL (WINAPI *fpStackWalk64)(DWORD, HANDLE, HANDLE, LPSTACKFRAME64,
132 PVOID, PREAD_PROCESS_MEMORY_ROUTINE64,
133 PFUNCTION_TABLE_ACCESS_ROUTINE64,
134 PGET_MODULE_BASE_ROUTINE64,
135 PTRANSLATE_ADDRESS_ROUTINE64);
Leny Kholodovbebb27b2015-07-02 14:34:57 +0000136static fpStackWalk64 fStackWalk64;
Michael J. Spencer44a36c82011-10-01 00:05:20 +0000137
138typedef DWORD64 (WINAPI *fpSymGetModuleBase64)(HANDLE, DWORD64);
Leny Kholodovbebb27b2015-07-02 14:34:57 +0000139static fpSymGetModuleBase64 fSymGetModuleBase64;
Michael J. Spencer44a36c82011-10-01 00:05:20 +0000140
141typedef BOOL (WINAPI *fpSymGetSymFromAddr64)(HANDLE, DWORD64,
142 PDWORD64, PIMAGEHLP_SYMBOL64);
Leny Kholodovbebb27b2015-07-02 14:34:57 +0000143static fpSymGetSymFromAddr64 fSymGetSymFromAddr64;
Michael J. Spencer44a36c82011-10-01 00:05:20 +0000144
145typedef BOOL (WINAPI *fpSymGetLineFromAddr64)(HANDLE, DWORD64,
146 PDWORD, PIMAGEHLP_LINE64);
Leny Kholodovbebb27b2015-07-02 14:34:57 +0000147static fpSymGetLineFromAddr64 fSymGetLineFromAddr64;
Michael J. Spencer44a36c82011-10-01 00:05:20 +0000148
Reid Klecknerba5757d2015-11-05 01:07:54 +0000149typedef BOOL(WINAPI *fpSymGetModuleInfo64)(HANDLE hProcess, DWORD64 dwAddr,
150 PIMAGEHLP_MODULE64 ModuleInfo);
151static fpSymGetModuleInfo64 fSymGetModuleInfo64;
152
Michael J. Spencer44a36c82011-10-01 00:05:20 +0000153typedef PVOID (WINAPI *fpSymFunctionTableAccess64)(HANDLE, DWORD64);
Leny Kholodovbebb27b2015-07-02 14:34:57 +0000154static fpSymFunctionTableAccess64 fSymFunctionTableAccess64;
155
156typedef DWORD (WINAPI *fpSymSetOptions)(DWORD);
157static fpSymSetOptions fSymSetOptions;
158
159typedef BOOL (WINAPI *fpSymInitialize)(HANDLE, PCSTR, BOOL);
160static fpSymInitialize fSymInitialize;
Michael J. Spencer44a36c82011-10-01 00:05:20 +0000161
Reid Klecknerba5757d2015-11-05 01:07:54 +0000162typedef BOOL (WINAPI *fpEnumerateLoadedModules)(HANDLE,PENUMLOADED_MODULES_CALLBACK64,PVOID);
163static fpEnumerateLoadedModules fEnumerateLoadedModules;
164
Michael J. Spencer44a36c82011-10-01 00:05:20 +0000165static bool load64BitDebugHelp(void) {
David Majnemer17a44962013-10-07 09:52:36 +0000166 HMODULE hLib = ::LoadLibraryW(L"Dbghelp.dll");
Michael J. Spencer44a36c82011-10-01 00:05:20 +0000167 if (hLib) {
Leny Kholodov1b73e662016-05-04 16:56:51 +0000168 fMiniDumpWriteDump = (fpMiniDumpWriteDump)
169 ::GetProcAddress(hLib, "MiniDumpWriteDump");
Leny Kholodovbebb27b2015-07-02 14:34:57 +0000170 fStackWalk64 = (fpStackWalk64)
Michael J. Spencer44a36c82011-10-01 00:05:20 +0000171 ::GetProcAddress(hLib, "StackWalk64");
Leny Kholodovbebb27b2015-07-02 14:34:57 +0000172 fSymGetModuleBase64 = (fpSymGetModuleBase64)
Michael J. Spencer44a36c82011-10-01 00:05:20 +0000173 ::GetProcAddress(hLib, "SymGetModuleBase64");
Leny Kholodovbebb27b2015-07-02 14:34:57 +0000174 fSymGetSymFromAddr64 = (fpSymGetSymFromAddr64)
Michael J. Spencer44a36c82011-10-01 00:05:20 +0000175 ::GetProcAddress(hLib, "SymGetSymFromAddr64");
Leny Kholodovbebb27b2015-07-02 14:34:57 +0000176 fSymGetLineFromAddr64 = (fpSymGetLineFromAddr64)
Michael J. Spencer44a36c82011-10-01 00:05:20 +0000177 ::GetProcAddress(hLib, "SymGetLineFromAddr64");
Reid Klecknerba5757d2015-11-05 01:07:54 +0000178 fSymGetModuleInfo64 = (fpSymGetModuleInfo64)
179 ::GetProcAddress(hLib, "SymGetModuleInfo64");
Leny Kholodovbebb27b2015-07-02 14:34:57 +0000180 fSymFunctionTableAccess64 = (fpSymFunctionTableAccess64)
Michael J. Spencer44a36c82011-10-01 00:05:20 +0000181 ::GetProcAddress(hLib, "SymFunctionTableAccess64");
Leny Kholodovbebb27b2015-07-02 14:34:57 +0000182 fSymSetOptions = (fpSymSetOptions)::GetProcAddress(hLib, "SymSetOptions");
183 fSymInitialize = (fpSymInitialize)::GetProcAddress(hLib, "SymInitialize");
Reid Klecknerba5757d2015-11-05 01:07:54 +0000184 fEnumerateLoadedModules = (fpEnumerateLoadedModules)
185 ::GetProcAddress(hLib, "EnumerateLoadedModules64");
Michael J. Spencer44a36c82011-10-01 00:05:20 +0000186 }
Leny Kholodov1b73e662016-05-04 16:56:51 +0000187 return fStackWalk64 && fSymInitialize && fSymSetOptions && fMiniDumpWriteDump;
Michael J. Spencer44a36c82011-10-01 00:05:20 +0000188}
Reid Spencer4aff78a2004-09-16 15:53:16 +0000189
Yaron Keren240bd9c2015-07-22 19:01:14 +0000190using namespace llvm;
191
Reid Spencer4aff78a2004-09-16 15:53:16 +0000192// Forward declare.
193static LONG WINAPI LLVMUnhandledExceptionFilter(LPEXCEPTION_POINTERS ep);
194static BOOL WINAPI LLVMConsoleCtrlHandler(DWORD dwCtrlType);
195
Jeff Cohenba7cc682005-08-02 03:04:47 +0000196// InterruptFunction - The function to call if ctrl-c is pressed.
197static void (*InterruptFunction)() = 0;
198
Rafael Espindola4f35da72013-06-13 21:16:58 +0000199static std::vector<std::string> *FilesToRemove = NULL;
Reid Spencer4aff78a2004-09-16 15:53:16 +0000200static bool RegisteredUnhandledExceptionFilter = false;
Reid Spencer1bdd0f02004-09-19 05:37:39 +0000201static bool CleanupExecuted = false;
202static PTOP_LEVEL_EXCEPTION_FILTER OldFilter = NULL;
Reid Spencer90debc52004-09-17 03:02:27 +0000203
204// Windows creates a new thread to execute the console handler when an event
205// (such as CTRL/C) occurs. This causes concurrency issues with the above
206// globals which this critical section addresses.
Reid Spencer4aff78a2004-09-16 15:53:16 +0000207static CRITICAL_SECTION CriticalSection;
Aaron Ballman50af8d42015-03-26 16:24:38 +0000208static bool CriticalSectionInitialized = false;
Reid Spencer4aff78a2004-09-16 15:53:16 +0000209
Richard Smith2ad6d482016-06-09 00:53:21 +0000210static StringRef Argv0;
211
Reid Klecknerba5757d2015-11-05 01:07:54 +0000212enum {
213#if defined(_M_X64)
214 NativeMachineType = IMAGE_FILE_MACHINE_AMD64
Martell Malone346a5fd2017-08-03 23:12:33 +0000215#elif defined(_M_ARM64)
216 NativeMachineType = IMAGE_FILE_MACHINE_ARM64
217#elif defined(_M_IX86)
Reid Klecknerba5757d2015-11-05 01:07:54 +0000218 NativeMachineType = IMAGE_FILE_MACHINE_I386
Martell Malone346a5fd2017-08-03 23:12:33 +0000219#elif defined(_M_ARM)
220 NativeMachineType = IMAGE_FILE_MACHINE_ARMNT
221#else
222 NativeMachineType = IMAGE_FILE_MACHINE_UNKNOWN
Reid Klecknerba5757d2015-11-05 01:07:54 +0000223#endif
224};
225
226static bool printStackTraceWithLLVMSymbolizer(llvm::raw_ostream &OS,
227 HANDLE hProcess, HANDLE hThread,
228 STACKFRAME64 &StackFrameOrig,
229 CONTEXT *ContextOrig) {
230 // StackWalk64 modifies the incoming stack frame and context, so copy them.
231 STACKFRAME64 StackFrame = StackFrameOrig;
232
233 // Copy the register context so that we don't modify it while we unwind. We
234 // could use InitializeContext + CopyContext, but that's only required to get
235 // at AVX registers, which typically aren't needed by StackWalk64. Reduce the
236 // flag set to indicate that there's less data.
237 CONTEXT Context = *ContextOrig;
238 Context.ContextFlags = CONTEXT_CONTROL | CONTEXT_INTEGER;
239
240 static void *StackTrace[256];
Aaron Ballman3c44b422015-11-05 14:22:56 +0000241 size_t Depth = 0;
Reid Klecknerba5757d2015-11-05 01:07:54 +0000242 while (fStackWalk64(NativeMachineType, hProcess, hThread, &StackFrame,
243 &Context, 0, fSymFunctionTableAccess64,
244 fSymGetModuleBase64, 0)) {
245 if (StackFrame.AddrFrame.Offset == 0)
246 break;
247 StackTrace[Depth++] = (void *)(uintptr_t)StackFrame.AddrPC.Offset;
248 if (Depth >= array_lengthof(StackTrace))
249 break;
250 }
251
Richard Smith2ad6d482016-06-09 00:53:21 +0000252 return printSymbolizedStackTrace(Argv0, &StackTrace[0], Depth, OS);
Reid Klecknerba5757d2015-11-05 01:07:54 +0000253}
254
255namespace {
256struct FindModuleData {
257 void **StackTrace;
258 int Depth;
259 const char **Modules;
260 intptr_t *Offsets;
261 StringSaver *StrPool;
262};
263}
264
NAKAMURA Takumi2de1b322016-03-07 00:13:09 +0000265static BOOL CALLBACK findModuleCallback(PCSTR ModuleName,
Reid Klecknerba5757d2015-11-05 01:07:54 +0000266 DWORD64 ModuleBase, ULONG ModuleSize,
267 void *VoidData) {
268 FindModuleData *Data = (FindModuleData*)VoidData;
269 intptr_t Beg = ModuleBase;
270 intptr_t End = Beg + ModuleSize;
271 for (int I = 0; I < Data->Depth; I++) {
272 if (Data->Modules[I])
273 continue;
274 intptr_t Addr = (intptr_t)Data->StackTrace[I];
275 if (Beg <= Addr && Addr < End) {
Mehdi Aminie4f0b752016-10-05 01:41:11 +0000276 Data->Modules[I] = Data->StrPool->save(ModuleName).data();
Reid Klecknerba5757d2015-11-05 01:07:54 +0000277 Data->Offsets[I] = Addr - Beg;
278 }
279 }
280 return TRUE;
281}
282
283static bool findModulesAndOffsets(void **StackTrace, int Depth,
284 const char **Modules, intptr_t *Offsets,
285 const char *MainExecutableName,
286 StringSaver &StrPool) {
287 if (!fEnumerateLoadedModules)
288 return false;
289 FindModuleData Data;
290 Data.StackTrace = StackTrace;
291 Data.Depth = Depth;
292 Data.Modules = Modules;
293 Data.Offsets = Offsets;
294 Data.StrPool = &StrPool;
295 fEnumerateLoadedModules(GetCurrentProcess(), findModuleCallback, &Data);
296 return true;
297}
298
Zachary Turnercd132c92015-03-05 19:10:52 +0000299static void PrintStackTraceForThread(llvm::raw_ostream &OS, HANDLE hProcess,
Zachary Turner62b7b612015-03-05 17:47:52 +0000300 HANDLE hThread, STACKFRAME64 &StackFrame,
301 CONTEXT *Context) {
Zachary Turner62b7b612015-03-05 17:47:52 +0000302 // Initialize the symbol handler.
Leny Kholodovbebb27b2015-07-02 14:34:57 +0000303 fSymSetOptions(SYMOPT_DEFERRED_LOADS | SYMOPT_LOAD_LINES);
304 fSymInitialize(hProcess, NULL, TRUE);
Zachary Turner62b7b612015-03-05 17:47:52 +0000305
Reid Klecknerba5757d2015-11-05 01:07:54 +0000306 // Try llvm-symbolizer first. llvm-symbolizer knows how to deal with both PDBs
307 // and DWARF, so it should do a good job regardless of what debug info or
308 // linker is in use.
309 if (printStackTraceWithLLVMSymbolizer(OS, hProcess, hThread, StackFrame,
310 Context)) {
311 return;
312 }
313
Zachary Turner62b7b612015-03-05 17:47:52 +0000314 while (true) {
Reid Klecknerba5757d2015-11-05 01:07:54 +0000315 if (!fStackWalk64(NativeMachineType, hProcess, hThread, &StackFrame,
316 Context, 0, fSymFunctionTableAccess64,
317 fSymGetModuleBase64, 0)) {
Zachary Turner62b7b612015-03-05 17:47:52 +0000318 break;
319 }
320
321 if (StackFrame.AddrFrame.Offset == 0)
322 break;
323
Zachary Turnercd132c92015-03-05 19:10:52 +0000324 using namespace llvm;
Zachary Turner62b7b612015-03-05 17:47:52 +0000325 // Print the PC in hexadecimal.
326 DWORD64 PC = StackFrame.AddrPC.Offset;
Martell Malone346a5fd2017-08-03 23:12:33 +0000327#if defined(_M_X64) || defined(_M_ARM64)
Zachary Turnercd132c92015-03-05 19:10:52 +0000328 OS << format("0x%016llX", PC);
Martell Malone346a5fd2017-08-03 23:12:33 +0000329#elif defined(_M_IX86) || defined(_M_ARM)
Zachary Turnercd132c92015-03-05 19:10:52 +0000330 OS << format("0x%08lX", static_cast<DWORD>(PC));
Zachary Turner62b7b612015-03-05 17:47:52 +0000331#endif
332
333// Print the parameters. Assume there are four.
Martell Malone346a5fd2017-08-03 23:12:33 +0000334#if defined(_M_X64) || defined(_M_ARM64)
Zachary Turnercd132c92015-03-05 19:10:52 +0000335 OS << format(" (0x%016llX 0x%016llX 0x%016llX 0x%016llX)",
Zachary Turner62b7b612015-03-05 17:47:52 +0000336 StackFrame.Params[0], StackFrame.Params[1], StackFrame.Params[2],
337 StackFrame.Params[3]);
Martell Malone346a5fd2017-08-03 23:12:33 +0000338#elif defined(_M_IX86) || defined(_M_ARM)
Zachary Turnercd132c92015-03-05 19:10:52 +0000339 OS << format(" (0x%08lX 0x%08lX 0x%08lX 0x%08lX)",
Zachary Turner62b7b612015-03-05 17:47:52 +0000340 static_cast<DWORD>(StackFrame.Params[0]),
341 static_cast<DWORD>(StackFrame.Params[1]),
342 static_cast<DWORD>(StackFrame.Params[2]),
343 static_cast<DWORD>(StackFrame.Params[3]));
344#endif
345 // Verify the PC belongs to a module in this process.
Leny Kholodovbebb27b2015-07-02 14:34:57 +0000346 if (!fSymGetModuleBase64(hProcess, PC)) {
Zachary Turnercd132c92015-03-05 19:10:52 +0000347 OS << " <unknown module>\n";
Zachary Turner62b7b612015-03-05 17:47:52 +0000348 continue;
349 }
350
351 // Print the symbol name.
352 char buffer[512];
353 IMAGEHLP_SYMBOL64 *symbol = reinterpret_cast<IMAGEHLP_SYMBOL64 *>(buffer);
354 memset(symbol, 0, sizeof(IMAGEHLP_SYMBOL64));
355 symbol->SizeOfStruct = sizeof(IMAGEHLP_SYMBOL64);
356 symbol->MaxNameLength = 512 - sizeof(IMAGEHLP_SYMBOL64);
357
358 DWORD64 dwDisp;
Leny Kholodovbebb27b2015-07-02 14:34:57 +0000359 if (!fSymGetSymFromAddr64(hProcess, PC, &dwDisp, symbol)) {
Zachary Turnercd132c92015-03-05 19:10:52 +0000360 OS << '\n';
Zachary Turner62b7b612015-03-05 17:47:52 +0000361 continue;
362 }
363
364 buffer[511] = 0;
365 if (dwDisp > 0)
Zachary Turnercd132c92015-03-05 19:10:52 +0000366 OS << format(", %s() + 0x%llX bytes(s)", (const char*)symbol->Name,
367 dwDisp);
Zachary Turner62b7b612015-03-05 17:47:52 +0000368 else
Zachary Turnercd132c92015-03-05 19:10:52 +0000369 OS << format(", %s", (const char*)symbol->Name);
Zachary Turner62b7b612015-03-05 17:47:52 +0000370
371 // Print the source file and line number information.
Yaron Keren24a86df2015-04-24 15:39:47 +0000372 IMAGEHLP_LINE64 line = {};
Zachary Turner62b7b612015-03-05 17:47:52 +0000373 DWORD dwLineDisp;
Zachary Turner62b7b612015-03-05 17:47:52 +0000374 line.SizeOfStruct = sizeof(line);
Leny Kholodovbebb27b2015-07-02 14:34:57 +0000375 if (fSymGetLineFromAddr64(hProcess, PC, &dwLineDisp, &line)) {
Zachary Turnercd132c92015-03-05 19:10:52 +0000376 OS << format(", %s, line %lu", line.FileName, line.LineNumber);
Zachary Turner62b7b612015-03-05 17:47:52 +0000377 if (dwLineDisp > 0)
Zachary Turnercd132c92015-03-05 19:10:52 +0000378 OS << format(" + 0x%lX byte(s)", dwLineDisp);
Zachary Turner62b7b612015-03-05 17:47:52 +0000379 }
380
Zachary Turnercd132c92015-03-05 19:10:52 +0000381 OS << '\n';
Zachary Turner62b7b612015-03-05 17:47:52 +0000382 }
383}
384
Reid Spencer3d7a6142004-08-29 19:22:48 +0000385namespace llvm {
Reid Spencer3d7a6142004-08-29 19:22:48 +0000386
387//===----------------------------------------------------------------------===//
Mikhail Glushenkovf64d93d2010-10-21 20:40:39 +0000388//=== WARNING: Implementation here must contain only Win32 specific code
Reid Spencer4aff78a2004-09-16 15:53:16 +0000389//=== and must not be UNIX code
Reid Spencer3d7a6142004-08-29 19:22:48 +0000390//===----------------------------------------------------------------------===//
391
Daniel Dunbar1bdedd32009-09-22 15:58:35 +0000392#ifdef _MSC_VER
Reid Klecknerbd39f212013-04-05 16:18:03 +0000393/// AvoidMessageBoxHook - Emulates hitting "retry" from an "abort, retry,
394/// ignore" CRT debug report dialog. "retry" raises an exception which
395/// ultimately triggers our stack dumper.
Reid Kleckner542a4542015-02-26 21:08:21 +0000396static LLVM_ATTRIBUTE_UNUSED int
397AvoidMessageBoxHook(int ReportType, char *Message, int *Return) {
Reid Klecknerbd39f212013-04-05 16:18:03 +0000398 // Set *Return to the retry code for the return value of _CrtDbgReport:
399 // http://msdn.microsoft.com/en-us/library/8hyw4sy7(v=vs.71).aspx
400 // This may also trigger just-in-time debugging via DebugBreak().
401 if (Return)
402 *Return = 1;
403 // Don't call _CrtDbgReport.
404 return TRUE;
405}
406
Daniel Dunbar1bdedd32009-09-22 15:58:35 +0000407#endif
Daniel Dunbar4c7b0ca2009-09-22 09:50:28 +0000408
Aaron Ballman03b968e2015-01-29 20:48:34 +0000409extern "C" void HandleAbort(int Sig) {
Michael J. Spencer89b0ad22015-01-29 17:20:29 +0000410 if (Sig == SIGABRT) {
411 LLVM_BUILTIN_TRAP;
412 }
413}
414
Aaron Ballman50af8d42015-03-26 16:24:38 +0000415static void InitializeThreading() {
416 if (CriticalSectionInitialized)
417 return;
418
419 // Now's the time to create the critical section. This is the first time
420 // through here, and there's only one thread.
421 InitializeCriticalSection(&CriticalSection);
422 CriticalSectionInitialized = true;
423}
424
Daniel Dunbar4c7b0ca2009-09-22 09:50:28 +0000425static void RegisterHandler() {
Leny Kholodovbebb27b2015-07-02 14:34:57 +0000426 // If we cannot load up the APIs (which would be unexpected as they should
427 // exist on every version of Windows we support), we will bail out since
428 // there would be nothing to report.
Reid Kleckner6cdf8442016-01-11 21:07:48 +0000429 if (!load64BitDebugHelp()) {
430 assert(false && "These APIs should always be available");
431 return;
432 }
Michael J. Spencer44a36c82011-10-01 00:05:20 +0000433
Reid Spencer1bdd0f02004-09-19 05:37:39 +0000434 if (RegisteredUnhandledExceptionFilter) {
Reid Spencer90debc52004-09-17 03:02:27 +0000435 EnterCriticalSection(&CriticalSection);
Reid Spencer4aff78a2004-09-16 15:53:16 +0000436 return;
Reid Spencer90debc52004-09-17 03:02:27 +0000437 }
Reid Spencer4aff78a2004-09-16 15:53:16 +0000438
Aaron Ballman50af8d42015-03-26 16:24:38 +0000439 InitializeThreading();
Reid Spencer4aff78a2004-09-16 15:53:16 +0000440
441 // Enter it immediately. Now if someone hits CTRL/C, the console handler
442 // can't proceed until the globals are updated.
443 EnterCriticalSection(&CriticalSection);
444
445 RegisteredUnhandledExceptionFilter = true;
Reid Spencer1bdd0f02004-09-19 05:37:39 +0000446 OldFilter = SetUnhandledExceptionFilter(LLVMUnhandledExceptionFilter);
Reid Spencer4aff78a2004-09-16 15:53:16 +0000447 SetConsoleCtrlHandler(LLVMConsoleCtrlHandler, TRUE);
448
449 // IMPORTANT NOTE: Caller must call LeaveCriticalSection(&CriticalSection) or
450 // else multi-threading problems will ensue.
451}
452
Reid Spencer3d7a6142004-08-29 19:22:48 +0000453// RemoveFileOnSignal - The public API
Rafael Espindola4f35da72013-06-13 21:16:58 +0000454bool sys::RemoveFileOnSignal(StringRef Filename, std::string* ErrMsg) {
Reid Spencer4aff78a2004-09-16 15:53:16 +0000455 RegisterHandler();
456
Reid Spencer50eac3b2006-08-25 21:37:17 +0000457 if (CleanupExecuted) {
458 if (ErrMsg)
459 *ErrMsg = "Process terminating -- cannot register for removal";
460 return true;
461 }
Reid Spencer1bdd0f02004-09-19 05:37:39 +0000462
Reid Spencer4aff78a2004-09-16 15:53:16 +0000463 if (FilesToRemove == NULL)
Rafael Espindola4f35da72013-06-13 21:16:58 +0000464 FilesToRemove = new std::vector<std::string>;
Reid Spencer4aff78a2004-09-16 15:53:16 +0000465
Reid Spencerf070b6c2004-11-16 06:59:53 +0000466 FilesToRemove->push_back(Filename);
Reid Spencer4aff78a2004-09-16 15:53:16 +0000467
468 LeaveCriticalSection(&CriticalSection);
Reid Spencer50eac3b2006-08-25 21:37:17 +0000469 return false;
Reid Spencer3d7a6142004-08-29 19:22:48 +0000470}
471
Dan Gohmane201c072010-09-01 14:17:34 +0000472// DontRemoveFileOnSignal - The public API
Rafael Espindola4f35da72013-06-13 21:16:58 +0000473void sys::DontRemoveFileOnSignal(StringRef Filename) {
Dan Gohmane201c072010-09-01 14:17:34 +0000474 if (FilesToRemove == NULL)
475 return;
476
NAKAMURA Takumi3f688b92010-10-22 01:23:50 +0000477 RegisterHandler();
478
Rafael Espindola4f35da72013-06-13 21:16:58 +0000479 std::vector<std::string>::reverse_iterator I =
David Majnemer42531262016-08-12 03:55:06 +0000480 find(reverse(*FilesToRemove), Filename);
Dan Gohmane201c072010-09-01 14:17:34 +0000481 if (I != FilesToRemove->rend())
482 FilesToRemove->erase(I.base()-1);
483
484 LeaveCriticalSection(&CriticalSection);
485}
486
Michael J. Spencer89b0ad22015-01-29 17:20:29 +0000487void sys::DisableSystemDialogsOnCrash() {
488 // Crash to stack trace handler on abort.
489 signal(SIGABRT, HandleAbort);
490
491 // The following functions are not reliably accessible on MinGW.
492#ifdef _MSC_VER
493 // We're already handling writing a "something went wrong" message.
494 _set_abort_behavior(0, _WRITE_ABORT_MSG);
495 // Disable Dr. Watson.
496 _set_abort_behavior(0, _CALL_REPORTFAULT);
497 _CrtSetReportHook(AvoidMessageBoxHook);
498#endif
499
500 // Disable standard error dialog box.
501 SetErrorMode(SEM_FAILCRITICALERRORS | SEM_NOGPFAULTERRORBOX |
502 SEM_NOOPENFILEERRORBOX);
503 _set_error_mode(_OUT_TO_STDERR);
504}
505
Eric Christopher668e6b42018-01-18 21:45:51 +0000506/// PrintStackTraceOnErrorSignal - When an error signal (such as SIGABRT or
Reid Spencer3d7a6142004-08-29 19:22:48 +0000507/// SIGSEGV) is delivered to the process, print a stack trace and then exit.
Richard Smith2ad6d482016-06-09 00:53:21 +0000508void sys::PrintStackTraceOnErrorSignal(StringRef Argv0,
509 bool DisableCrashReporting) {
510 ::Argv0 = Argv0;
511
Leny Kholodov1b73e662016-05-04 16:56:51 +0000512 if (DisableCrashReporting || getenv("LLVM_DISABLE_CRASH_REPORT"))
513 Process::PreventCoreFiles();
514
Michael J. Spencer89b0ad22015-01-29 17:20:29 +0000515 DisableSystemDialogsOnCrash();
Reid Spencer4aff78a2004-09-16 15:53:16 +0000516 RegisterHandler();
517 LeaveCriticalSection(&CriticalSection);
Reid Spencer3d7a6142004-08-29 19:22:48 +0000518}
Benjamin Kramerf97eff62015-03-11 15:41:15 +0000519}
520
Yaron Kerenbdae8d62015-03-14 19:20:56 +0000521#if defined(__MINGW32__) && !defined(__MINGW64_VERSION_MAJOR)
522// Provide a prototype for RtlCaptureContext, mingw32 from mingw.org is
523// missing it but mingw-w64 has it.
Benjamin Kramerf97eff62015-03-11 15:41:15 +0000524extern "C" VOID WINAPI RtlCaptureContext(PCONTEXT ContextRecord);
Benjamin Kramerb47d5492015-03-11 16:09:02 +0000525#endif
Reid Spencer3d7a6142004-08-29 19:22:48 +0000526
Zachary Turnercd132c92015-03-05 19:10:52 +0000527void llvm::sys::PrintStackTrace(raw_ostream &OS) {
Reid Klecknere6580582015-03-05 18:26:58 +0000528 STACKFRAME64 StackFrame = {};
Yaron Keren24a86df2015-04-24 15:39:47 +0000529 CONTEXT Context = {};
Zachary Turner62b7b612015-03-05 17:47:52 +0000530 ::RtlCaptureContext(&Context);
531#if defined(_M_X64)
532 StackFrame.AddrPC.Offset = Context.Rip;
533 StackFrame.AddrStack.Offset = Context.Rsp;
534 StackFrame.AddrFrame.Offset = Context.Rbp;
Martell Malone346a5fd2017-08-03 23:12:33 +0000535#elif defined(_M_IX86)
Zachary Turner62b7b612015-03-05 17:47:52 +0000536 StackFrame.AddrPC.Offset = Context.Eip;
537 StackFrame.AddrStack.Offset = Context.Esp;
538 StackFrame.AddrFrame.Offset = Context.Ebp;
Martell Malone346a5fd2017-08-03 23:12:33 +0000539#elif defined(_M_ARM64) || defined(_M_ARM)
540 StackFrame.AddrPC.Offset = Context.Pc;
541 StackFrame.AddrStack.Offset = Context.Sp;
542 StackFrame.AddrFrame.Offset = Context.Fp;
Zachary Turner62b7b612015-03-05 17:47:52 +0000543#endif
544 StackFrame.AddrPC.Mode = AddrModeFlat;
545 StackFrame.AddrStack.Mode = AddrModeFlat;
546 StackFrame.AddrFrame.Mode = AddrModeFlat;
Zachary Turnercd132c92015-03-05 19:10:52 +0000547 PrintStackTraceForThread(OS, GetCurrentProcess(), GetCurrentThread(),
Zachary Turner62b7b612015-03-05 17:47:52 +0000548 StackFrame, &Context);
Argyrios Kyrtzidiseb9ae762013-01-09 19:42:40 +0000549}
550
Chris Lattner6a5d6ec2005-08-02 02:14:22 +0000551
Benjamin Kramer90c2db22015-03-11 15:53:24 +0000552void llvm::sys::SetInterruptFunction(void (*IF)()) {
Jeff Cohenba7cc682005-08-02 03:04:47 +0000553 RegisterHandler();
Jeff Cohen9aafa062005-08-02 03:26:32 +0000554 InterruptFunction = IF;
Jeff Cohenba7cc682005-08-02 03:04:47 +0000555 LeaveCriticalSection(&CriticalSection);
Chris Lattner6a5d6ec2005-08-02 02:14:22 +0000556}
Sebastian Redl8d5baa02009-03-19 23:26:52 +0000557
558
559/// AddSignalHandler - Add a function to be called when a signal is delivered
560/// to the process. The handler can have a cookie passed to it to identify
561/// what instance of the handler it is.
Benjamin Kramerb47d5492015-03-11 16:09:02 +0000562void llvm::sys::AddSignalHandler(void (*FnPtr)(void *), void *Cookie) {
Sebastian Redl8d5baa02009-03-19 23:26:52 +0000563 CallBacksToRun->push_back(std::make_pair(FnPtr, Cookie));
564 RegisterHandler();
Torok Edwin6fb09562010-03-31 12:07:16 +0000565 LeaveCriticalSection(&CriticalSection);
Sebastian Redl8d5baa02009-03-19 23:26:52 +0000566}
Reid Spencer3d7a6142004-08-29 19:22:48 +0000567
Reid Spencer4aff78a2004-09-16 15:53:16 +0000568static void Cleanup() {
Yaron Keren356aa462015-05-19 13:31:25 +0000569 if (CleanupExecuted)
570 return;
571
Reid Spencer4aff78a2004-09-16 15:53:16 +0000572 EnterCriticalSection(&CriticalSection);
573
Reid Spencer1bdd0f02004-09-19 05:37:39 +0000574 // Prevent other thread from registering new files and directories for
575 // removal, should we be executing because of the console handler callback.
576 CleanupExecuted = true;
577
578 // FIXME: open files cannot be deleted.
Reid Spencer4aff78a2004-09-16 15:53:16 +0000579 if (FilesToRemove != NULL)
580 while (!FilesToRemove->empty()) {
Rafael Espindolad724c282014-02-23 13:37:37 +0000581 llvm::sys::fs::remove(FilesToRemove->back());
Reid Spencer4aff78a2004-09-16 15:53:16 +0000582 FilesToRemove->pop_back();
583 }
Yaron Keren28738102015-07-22 21:11:17 +0000584 llvm::sys::RunSignalHandlers();
Reid Spencer4aff78a2004-09-16 15:53:16 +0000585 LeaveCriticalSection(&CriticalSection);
586}
587
Daniel Dunbar68272562010-05-08 02:10:34 +0000588void llvm::sys::RunInterruptHandlers() {
Aaron Ballman50af8d42015-03-26 16:24:38 +0000589 // The interrupt handler may be called from an interrupt, but it may also be
590 // called manually (such as the case of report_fatal_error with no registered
591 // error handler). We must ensure that the critical section is properly
592 // initialized.
593 InitializeThreading();
Daniel Dunbar68272562010-05-08 02:10:34 +0000594 Cleanup();
595}
596
Leny Kholodov1b73e662016-05-04 16:56:51 +0000597/// \brief Find the Windows Registry Key for a given location.
598///
599/// \returns a valid HKEY if the location exists, else NULL.
600static HKEY FindWERKey(const llvm::Twine &RegistryLocation) {
601 HKEY Key;
Aaron Ballman0da8b2e2016-06-23 14:45:54 +0000602 if (ERROR_SUCCESS != ::RegOpenKeyExA(HKEY_LOCAL_MACHINE,
603 RegistryLocation.str().c_str(), 0,
604 KEY_QUERY_VALUE | KEY_READ, &Key))
Leny Kholodov1b73e662016-05-04 16:56:51 +0000605 return NULL;
606
607 return Key;
608}
609
610/// \brief Populate ResultDirectory with the value for "DumpFolder" for a given
611/// Windows Registry key.
612///
613/// \returns true if a valid value for DumpFolder exists, false otherwise.
614static bool GetDumpFolder(HKEY Key,
615 llvm::SmallVectorImpl<char> &ResultDirectory) {
616 using llvm::sys::windows::UTF16ToUTF8;
617
618 if (!Key)
619 return false;
620
621 DWORD BufferLengthBytes = 0;
622
623 if (ERROR_SUCCESS != ::RegGetValueW(Key, 0, L"DumpFolder", REG_EXPAND_SZ,
624 NULL, NULL, &BufferLengthBytes))
625 return false;
626
627 SmallVector<wchar_t, MAX_PATH> Buffer(BufferLengthBytes);
628
629 if (ERROR_SUCCESS != ::RegGetValueW(Key, 0, L"DumpFolder", REG_EXPAND_SZ,
630 NULL, Buffer.data(), &BufferLengthBytes))
631 return false;
632
633 DWORD ExpandBufferSize = ::ExpandEnvironmentStringsW(Buffer.data(), NULL, 0);
634
635 if (!ExpandBufferSize)
636 return false;
637
638 SmallVector<wchar_t, MAX_PATH> ExpandBuffer(ExpandBufferSize);
639
640 if (ExpandBufferSize != ::ExpandEnvironmentStringsW(Buffer.data(),
641 ExpandBuffer.data(),
642 ExpandBufferSize))
643 return false;
644
645 if (UTF16ToUTF8(ExpandBuffer.data(), ExpandBufferSize - 1, ResultDirectory))
646 return false;
647
648 return true;
649}
650
651/// \brief Populate ResultType with a valid MINIDUMP_TYPE based on the value of
652/// "DumpType" for a given Windows Registry key.
653///
654/// According to
655/// https://msdn.microsoft.com/en-us/library/windows/desktop/bb787181(v=vs.85).aspx
656/// valid values for DumpType are:
657/// * 0: Custom dump
658/// * 1: Mini dump
659/// * 2: Full dump
660/// If "Custom dump" is specified then the "CustomDumpFlags" field is read
661/// containing a bitwise combination of MINIDUMP_TYPE values.
662///
663/// \returns true if a valid value for ResultType can be set, false otherwise.
664static bool GetDumpType(HKEY Key, MINIDUMP_TYPE &ResultType) {
665 if (!Key)
666 return false;
667
668 DWORD DumpType;
669 DWORD TypeSize = sizeof(DumpType);
670 if (ERROR_SUCCESS != ::RegGetValueW(Key, NULL, L"DumpType", RRF_RT_REG_DWORD,
671 NULL, &DumpType,
672 &TypeSize))
673 return false;
674
675 switch (DumpType) {
676 case 0: {
677 DWORD Flags = 0;
678 if (ERROR_SUCCESS != ::RegGetValueW(Key, NULL, L"CustomDumpFlags",
679 RRF_RT_REG_DWORD, NULL, &Flags,
680 &TypeSize))
681 return false;
682
683 ResultType = static_cast<MINIDUMP_TYPE>(Flags);
684 break;
685 }
686 case 1:
687 ResultType = MiniDumpNormal;
688 break;
689 case 2:
690 ResultType = MiniDumpWithFullMemory;
691 break;
692 default:
693 return false;
694 }
695 return true;
696}
697
698/// \brief Write a Windows dump file containing process information that can be
699/// used for post-mortem debugging.
700///
701/// \returns zero error code if a mini dump created, actual error code
702/// otherwise.
703static std::error_code WINAPI
704WriteWindowsDumpFile(PMINIDUMP_EXCEPTION_INFORMATION ExceptionInfo) {
705 using namespace llvm;
706 using namespace llvm::sys;
707
708 std::string MainExecutableName = fs::getMainExecutable(nullptr, nullptr);
709 StringRef ProgramName;
710
711 if (MainExecutableName.empty()) {
712 // If we can't get the executable filename,
713 // things are in worse shape than we realize
714 // and we should just bail out.
715 return mapWindowsError(::GetLastError());
716 }
717
718 ProgramName = path::filename(MainExecutableName.c_str());
719
720 // The Windows Registry location as specified at
721 // https://msdn.microsoft.com/en-us/library/windows/desktop/bb787181%28v=vs.85%29.aspx
722 // "Collecting User-Mode Dumps" that may optionally be set to collect crash
723 // dumps in a specified location.
724 StringRef LocalDumpsRegistryLocation =
725 "SOFTWARE\\Microsoft\\Windows\\Windows Error Reporting\\LocalDumps";
726
727 // The key pointing to the Registry location that may contain global crash
728 // dump settings. This will be NULL if the location can not be found.
729 ScopedRegHandle DefaultLocalDumpsKey(FindWERKey(LocalDumpsRegistryLocation));
730
731 // The key pointing to the Registry location that may contain
732 // application-specific crash dump settings. This will be NULL if the
733 // location can not be found.
734 ScopedRegHandle AppSpecificKey(
735 FindWERKey(Twine(LocalDumpsRegistryLocation) + "\\" + ProgramName));
736
737 // Look to see if a dump type is specified in the registry; first with the
738 // app-specific key and failing that with the global key. If none are found
739 // default to a normal dump (GetDumpType will return false either if the key
740 // is NULL or if there is no valid DumpType value at its location).
741 MINIDUMP_TYPE DumpType;
742 if (!GetDumpType(AppSpecificKey, DumpType))
743 if (!GetDumpType(DefaultLocalDumpsKey, DumpType))
744 DumpType = MiniDumpNormal;
745
746 // Look to see if a dump location is specified in the registry; first with the
747 // app-specific key and failing that with the global key. If none are found
748 // we'll just create the dump file in the default temporary file location
749 // (GetDumpFolder will return false either if the key is NULL or if there is
750 // no valid DumpFolder value at its location).
751 bool ExplicitDumpDirectorySet = true;
752 SmallString<MAX_PATH> DumpDirectory;
753 if (!GetDumpFolder(AppSpecificKey, DumpDirectory))
754 if (!GetDumpFolder(DefaultLocalDumpsKey, DumpDirectory))
755 ExplicitDumpDirectorySet = false;
756
757 int FD;
758 SmallString<MAX_PATH> DumpPath;
759
760 if (ExplicitDumpDirectorySet) {
761 if (std::error_code EC = fs::create_directories(DumpDirectory))
762 return EC;
763 if (std::error_code EC = fs::createUniqueFile(
764 Twine(DumpDirectory) + "\\" + ProgramName + ".%%%%%%.dmp", FD,
765 DumpPath))
766 return EC;
767 } else if (std::error_code EC =
768 fs::createTemporaryFile(ProgramName, "dmp", FD, DumpPath))
769 return EC;
770
771 // Our support functions return a file descriptor but Windows wants a handle.
772 ScopedCommonHandle FileHandle(reinterpret_cast<HANDLE>(_get_osfhandle(FD)));
773
774 if (!fMiniDumpWriteDump(::GetCurrentProcess(), ::GetCurrentProcessId(),
775 FileHandle, DumpType, ExceptionInfo, NULL, NULL))
776 return mapWindowsError(::GetLastError());
777
778 llvm::errs() << "Wrote crash dump file \"" << DumpPath << "\"\n";
779 return std::error_code();
780}
781
Reid Spencer4aff78a2004-09-16 15:53:16 +0000782static LONG WINAPI LLVMUnhandledExceptionFilter(LPEXCEPTION_POINTERS ep) {
Mikhail Glushenkov32acd742010-10-27 09:09:04 +0000783 Cleanup();
Mikhail Glushenkovf64d93d2010-10-21 20:40:39 +0000784
Leny Kholodov1b73e662016-05-04 16:56:51 +0000785 // We'll automatically write a Minidump file here to help diagnose
786 // the nasty sorts of crashes that aren't 100% reproducible from a set of
787 // inputs (or in the event that the user is unable or unwilling to provide a
788 // reproducible case).
Kristof Beyls7adf8c52017-03-31 14:58:52 +0000789 if (!llvm::sys::Process::AreCoreFilesPrevented()) {
Leny Kholodov1b73e662016-05-04 16:56:51 +0000790 MINIDUMP_EXCEPTION_INFORMATION ExceptionInfo;
791 ExceptionInfo.ThreadId = ::GetCurrentThreadId();
792 ExceptionInfo.ExceptionPointers = ep;
793 ExceptionInfo.ClientPointers = FALSE;
794
795 if (std::error_code EC = WriteWindowsDumpFile(&ExceptionInfo))
796 llvm::errs() << "Could not write crash dump file: " << EC.message()
797 << "\n";
798 }
799
Mikhail Glushenkov080d86f2010-10-28 08:25:44 +0000800 // Initialize the STACKFRAME structure.
Yaron Keren24a86df2015-04-24 15:39:47 +0000801 STACKFRAME64 StackFrame = {};
Reid Spencer4aff78a2004-09-16 15:53:16 +0000802
Michael J. Spencer44a36c82011-10-01 00:05:20 +0000803#if defined(_M_X64)
Michael J. Spencer44a36c82011-10-01 00:05:20 +0000804 StackFrame.AddrPC.Offset = ep->ContextRecord->Rip;
805 StackFrame.AddrPC.Mode = AddrModeFlat;
806 StackFrame.AddrStack.Offset = ep->ContextRecord->Rsp;
807 StackFrame.AddrStack.Mode = AddrModeFlat;
808 StackFrame.AddrFrame.Offset = ep->ContextRecord->Rbp;
809 StackFrame.AddrFrame.Mode = AddrModeFlat;
810#elif defined(_M_IX86)
Mikhail Glushenkov080d86f2010-10-28 08:25:44 +0000811 StackFrame.AddrPC.Offset = ep->ContextRecord->Eip;
812 StackFrame.AddrPC.Mode = AddrModeFlat;
813 StackFrame.AddrStack.Offset = ep->ContextRecord->Esp;
814 StackFrame.AddrStack.Mode = AddrModeFlat;
815 StackFrame.AddrFrame.Offset = ep->ContextRecord->Ebp;
816 StackFrame.AddrFrame.Mode = AddrModeFlat;
Martell Malone346a5fd2017-08-03 23:12:33 +0000817#elif defined(_M_ARM64) || defined(_M_ARM)
818 StackFrame.AddrPC.Offset = ep->ContextRecord->Pc;
819 StackFrame.AddrPC.Mode = AddrModeFlat;
820 StackFrame.AddrStack.Offset = ep->ContextRecord->Sp;
821 StackFrame.AddrStack.Mode = AddrModeFlat;
822 StackFrame.AddrFrame.Offset = ep->ContextRecord->Fp;
823 StackFrame.AddrFrame.Mode = AddrModeFlat;
Michael J. Spencer44a36c82011-10-01 00:05:20 +0000824#endif
Reid Spencer4aff78a2004-09-16 15:53:16 +0000825
Mikhail Glushenkov080d86f2010-10-28 08:25:44 +0000826 HANDLE hProcess = GetCurrentProcess();
827 HANDLE hThread = GetCurrentThread();
Zachary Turnercd132c92015-03-05 19:10:52 +0000828 PrintStackTraceForThread(llvm::errs(), hProcess, hThread, StackFrame,
Zachary Turner62b7b612015-03-05 17:47:52 +0000829 ep->ContextRecord);
Mikhail Glushenkov080d86f2010-10-28 08:25:44 +0000830
Michael J. Spencer89b0ad22015-01-29 17:20:29 +0000831 _exit(ep->ExceptionRecord->ExceptionCode);
Reid Spencer4aff78a2004-09-16 15:53:16 +0000832}
833
834static BOOL WINAPI LLVMConsoleCtrlHandler(DWORD dwCtrlType) {
Jeff Cohen9aafa062005-08-02 03:26:32 +0000835 // We are running in our very own thread, courtesy of Windows.
Jeff Cohenba7cc682005-08-02 03:04:47 +0000836 EnterCriticalSection(&CriticalSection);
Reid Spencer4aff78a2004-09-16 15:53:16 +0000837 Cleanup();
838
Jeff Cohenba7cc682005-08-02 03:04:47 +0000839 // If an interrupt function has been set, go and run one it; otherwise,
840 // the process dies.
841 void (*IF)() = InterruptFunction;
842 InterruptFunction = 0; // Don't run it on another CTRL-C.
843
844 if (IF) {
Jeff Cohen9aafa062005-08-02 03:26:32 +0000845 // Note: if the interrupt function throws an exception, there is nothing
846 // to catch it in this thread so it will kill the process.
847 IF(); // Run it now.
Jeff Cohenba7cc682005-08-02 03:04:47 +0000848 LeaveCriticalSection(&CriticalSection);
849 return TRUE; // Don't kill the process.
850 }
851
Reid Spencer90debc52004-09-17 03:02:27 +0000852 // Allow normal processing to take place; i.e., the process dies.
Jeff Cohenba7cc682005-08-02 03:04:47 +0000853 LeaveCriticalSection(&CriticalSection);
Reid Spencer4aff78a2004-09-16 15:53:16 +0000854 return FALSE;
855}
Michael J. Spencer44a36c82011-10-01 00:05:20 +0000856
857#if __MINGW32__
858 // We turned these warnings off for this file so that MinGW-g++ doesn't
859 // complain about the ll format specifiers used. Now we are turning the
860 // warnings back on. If MinGW starts to support diagnostic stacks, we can
861 // replace this with a pop.
862 #pragma GCC diagnostic warning "-Wformat"
863 #pragma GCC diagnostic warning "-Wformat-extra-args"
864#endif