blob: 41eb5e593aa5ca5a404a0143b5a51aba52ed3f7f [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//===----------------------------------------------------------------------===//
Zachary Turnerb44d7a02018-06-01 22:23:46 +000013#include "llvm/Support/ConvertUTF.h"
Rafael Espindola9aa3d5d2013-06-14 13:59:21 +000014#include "llvm/Support/FileSystem.h"
Leny Kholodov1b73e662016-05-04 16:56:51 +000015#include "llvm/Support/Path.h"
16#include "llvm/Support/Process.h"
17#include "llvm/Support/WindowsError.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000018#include <algorithm>
Leny Kholodov1b73e662016-05-04 16:56:51 +000019#include <io.h>
Michael J. Spencer89b0ad22015-01-29 17:20:29 +000020#include <signal.h>
Reid Spencer70b68352004-09-28 23:58:03 +000021#include <stdio.h>
Reid Spencer4aff78a2004-09-16 15:53:16 +000022
Zachary Turnercd132c92015-03-05 19:10:52 +000023#include "llvm/Support/Format.h"
24#include "llvm/Support/raw_ostream.h"
25
Chandler Carruth10b09152014-01-07 12:37:13 +000026// The Windows.h header must be after LLVM and standard headers.
Reid Klecknerd59e2fa2014-02-12 21:26:20 +000027#include "WindowsSupport.h"
Chandler Carruth10b09152014-01-07 12:37:13 +000028
Jeff Cohen07e22ba2005-02-19 03:01:13 +000029#ifdef __MINGW32__
Reid Spencer187b4ad2006-06-01 19:03:21 +000030 #include <imagehlp.h>
Reid Spencer99049282004-09-23 14:47:10 +000031#else
Zachary Turnerab266cf2016-12-21 18:50:52 +000032 #include <crtdbg.h>
Reid Spencer187b4ad2006-06-01 19:03:21 +000033 #include <dbghelp.h>
Reid Spencer99049282004-09-23 14:47:10 +000034#endif
35#include <psapi.h>
Reid Spencer4aff78a2004-09-16 15:53:16 +000036
Michael J. Spencer44a36c82011-10-01 00:05:20 +000037#ifdef _MSC_VER
38 #pragma comment(lib, "psapi.lib")
Michael J. Spencer44a36c82011-10-01 00:05:20 +000039#elif __MINGW32__
Michael J. Spencer44a36c82011-10-01 00:05:20 +000040 // The version of g++ that comes with MinGW does *not* properly understand
41 // the ll format specifier for printf. However, MinGW passes the format
42 // specifiers on to the MSVCRT entirely, and the CRT understands the ll
43 // specifier. So these warnings are spurious in this case. Since we compile
44 // with -Wall, this will generate these warnings which should be ignored. So
45 // we will turn off the warnings for this just file. However, MinGW also does
46 // not support push and pop for diagnostics, so we have to manually turn it
47 // back on at the end of the file.
48 #pragma GCC diagnostic ignored "-Wformat"
49 #pragma GCC diagnostic ignored "-Wformat-extra-args"
50
Anton Korobeynikovb27f11e2011-10-21 09:38:50 +000051 #if !defined(__MINGW64_VERSION_MAJOR)
52 // MinGW.org does not have updated support for the 64-bit versions of the
53 // DebugHlp APIs. So we will have to load them manually. The structures and
54 // method signatures were pulled from DbgHelp.h in the Windows Platform SDK,
55 // and adjusted for brevity.
Michael J. Spencer44a36c82011-10-01 00:05:20 +000056 typedef struct _IMAGEHLP_LINE64 {
57 DWORD SizeOfStruct;
58 PVOID Key;
59 DWORD LineNumber;
60 PCHAR FileName;
61 DWORD64 Address;
62 } IMAGEHLP_LINE64, *PIMAGEHLP_LINE64;
63
64 typedef struct _IMAGEHLP_SYMBOL64 {
65 DWORD SizeOfStruct;
66 DWORD64 Address;
67 DWORD Size;
68 DWORD Flags;
69 DWORD MaxNameLength;
70 CHAR Name[1];
71 } IMAGEHLP_SYMBOL64, *PIMAGEHLP_SYMBOL64;
72
73 typedef struct _tagADDRESS64 {
74 DWORD64 Offset;
75 WORD Segment;
76 ADDRESS_MODE Mode;
77 } ADDRESS64, *LPADDRESS64;
78
79 typedef struct _KDHELP64 {
80 DWORD64 Thread;
81 DWORD ThCallbackStack;
82 DWORD ThCallbackBStore;
83 DWORD NextCallback;
84 DWORD FramePointer;
85 DWORD64 KiCallUserMode;
86 DWORD64 KeUserCallbackDispatcher;
87 DWORD64 SystemRangeStart;
88 DWORD64 KiUserExceptionDispatcher;
89 DWORD64 StackBase;
90 DWORD64 StackLimit;
91 DWORD64 Reserved[5];
92 } KDHELP64, *PKDHELP64;
93
94 typedef struct _tagSTACKFRAME64 {
95 ADDRESS64 AddrPC;
96 ADDRESS64 AddrReturn;
97 ADDRESS64 AddrFrame;
98 ADDRESS64 AddrStack;
99 ADDRESS64 AddrBStore;
100 PVOID FuncTableEntry;
101 DWORD64 Params[4];
102 BOOL Far;
103 BOOL Virtual;
104 DWORD64 Reserved[3];
105 KDHELP64 KdHelp;
106 } STACKFRAME64, *LPSTACKFRAME64;
Leny Kholodovbebb27b2015-07-02 14:34:57 +0000107 #endif // !defined(__MINGW64_VERSION_MAJOR)
108#endif // __MINGW32__
Michael J. Spencer44a36c82011-10-01 00:05:20 +0000109
110typedef BOOL (__stdcall *PREAD_PROCESS_MEMORY_ROUTINE64)(HANDLE hProcess,
111 DWORD64 qwBaseAddress, PVOID lpBuffer, DWORD nSize,
112 LPDWORD lpNumberOfBytesRead);
113
114typedef PVOID (__stdcall *PFUNCTION_TABLE_ACCESS_ROUTINE64)( HANDLE ahProcess,
115 DWORD64 AddrBase);
116
117typedef DWORD64 (__stdcall *PGET_MODULE_BASE_ROUTINE64)(HANDLE hProcess,
118 DWORD64 Address);
119
120typedef DWORD64 (__stdcall *PTRANSLATE_ADDRESS_ROUTINE64)(HANDLE hProcess,
121 HANDLE hThread, LPADDRESS64 lpaddr);
122
Leny Kholodov1b73e662016-05-04 16:56:51 +0000123typedef BOOL(WINAPI *fpMiniDumpWriteDump)(HANDLE, DWORD, HANDLE, MINIDUMP_TYPE,
124 PMINIDUMP_EXCEPTION_INFORMATION,
125 PMINIDUMP_USER_STREAM_INFORMATION,
126 PMINIDUMP_CALLBACK_INFORMATION);
127static fpMiniDumpWriteDump fMiniDumpWriteDump;
128
Michael J. Spencer44a36c82011-10-01 00:05:20 +0000129typedef BOOL (WINAPI *fpStackWalk64)(DWORD, HANDLE, HANDLE, LPSTACKFRAME64,
130 PVOID, PREAD_PROCESS_MEMORY_ROUTINE64,
131 PFUNCTION_TABLE_ACCESS_ROUTINE64,
132 PGET_MODULE_BASE_ROUTINE64,
133 PTRANSLATE_ADDRESS_ROUTINE64);
Leny Kholodovbebb27b2015-07-02 14:34:57 +0000134static fpStackWalk64 fStackWalk64;
Michael J. Spencer44a36c82011-10-01 00:05:20 +0000135
136typedef DWORD64 (WINAPI *fpSymGetModuleBase64)(HANDLE, DWORD64);
Leny Kholodovbebb27b2015-07-02 14:34:57 +0000137static fpSymGetModuleBase64 fSymGetModuleBase64;
Michael J. Spencer44a36c82011-10-01 00:05:20 +0000138
139typedef BOOL (WINAPI *fpSymGetSymFromAddr64)(HANDLE, DWORD64,
140 PDWORD64, PIMAGEHLP_SYMBOL64);
Leny Kholodovbebb27b2015-07-02 14:34:57 +0000141static fpSymGetSymFromAddr64 fSymGetSymFromAddr64;
Michael J. Spencer44a36c82011-10-01 00:05:20 +0000142
143typedef BOOL (WINAPI *fpSymGetLineFromAddr64)(HANDLE, DWORD64,
144 PDWORD, PIMAGEHLP_LINE64);
Leny Kholodovbebb27b2015-07-02 14:34:57 +0000145static fpSymGetLineFromAddr64 fSymGetLineFromAddr64;
Michael J. Spencer44a36c82011-10-01 00:05:20 +0000146
Reid Klecknerba5757d2015-11-05 01:07:54 +0000147typedef BOOL(WINAPI *fpSymGetModuleInfo64)(HANDLE hProcess, DWORD64 dwAddr,
148 PIMAGEHLP_MODULE64 ModuleInfo);
149static fpSymGetModuleInfo64 fSymGetModuleInfo64;
150
Michael J. Spencer44a36c82011-10-01 00:05:20 +0000151typedef PVOID (WINAPI *fpSymFunctionTableAccess64)(HANDLE, DWORD64);
Leny Kholodovbebb27b2015-07-02 14:34:57 +0000152static fpSymFunctionTableAccess64 fSymFunctionTableAccess64;
153
154typedef DWORD (WINAPI *fpSymSetOptions)(DWORD);
155static fpSymSetOptions fSymSetOptions;
156
157typedef BOOL (WINAPI *fpSymInitialize)(HANDLE, PCSTR, BOOL);
158static fpSymInitialize fSymInitialize;
Michael J. Spencer44a36c82011-10-01 00:05:20 +0000159
Reid Klecknerba5757d2015-11-05 01:07:54 +0000160typedef BOOL (WINAPI *fpEnumerateLoadedModules)(HANDLE,PENUMLOADED_MODULES_CALLBACK64,PVOID);
161static fpEnumerateLoadedModules fEnumerateLoadedModules;
162
Michael J. Spencer44a36c82011-10-01 00:05:20 +0000163static bool load64BitDebugHelp(void) {
David Majnemer17a44962013-10-07 09:52:36 +0000164 HMODULE hLib = ::LoadLibraryW(L"Dbghelp.dll");
Michael J. Spencer44a36c82011-10-01 00:05:20 +0000165 if (hLib) {
Leny Kholodov1b73e662016-05-04 16:56:51 +0000166 fMiniDumpWriteDump = (fpMiniDumpWriteDump)
167 ::GetProcAddress(hLib, "MiniDumpWriteDump");
Leny Kholodovbebb27b2015-07-02 14:34:57 +0000168 fStackWalk64 = (fpStackWalk64)
Michael J. Spencer44a36c82011-10-01 00:05:20 +0000169 ::GetProcAddress(hLib, "StackWalk64");
Leny Kholodovbebb27b2015-07-02 14:34:57 +0000170 fSymGetModuleBase64 = (fpSymGetModuleBase64)
Michael J. Spencer44a36c82011-10-01 00:05:20 +0000171 ::GetProcAddress(hLib, "SymGetModuleBase64");
Leny Kholodovbebb27b2015-07-02 14:34:57 +0000172 fSymGetSymFromAddr64 = (fpSymGetSymFromAddr64)
Michael J. Spencer44a36c82011-10-01 00:05:20 +0000173 ::GetProcAddress(hLib, "SymGetSymFromAddr64");
Leny Kholodovbebb27b2015-07-02 14:34:57 +0000174 fSymGetLineFromAddr64 = (fpSymGetLineFromAddr64)
Michael J. Spencer44a36c82011-10-01 00:05:20 +0000175 ::GetProcAddress(hLib, "SymGetLineFromAddr64");
Reid Klecknerba5757d2015-11-05 01:07:54 +0000176 fSymGetModuleInfo64 = (fpSymGetModuleInfo64)
177 ::GetProcAddress(hLib, "SymGetModuleInfo64");
Leny Kholodovbebb27b2015-07-02 14:34:57 +0000178 fSymFunctionTableAccess64 = (fpSymFunctionTableAccess64)
Michael J. Spencer44a36c82011-10-01 00:05:20 +0000179 ::GetProcAddress(hLib, "SymFunctionTableAccess64");
Leny Kholodovbebb27b2015-07-02 14:34:57 +0000180 fSymSetOptions = (fpSymSetOptions)::GetProcAddress(hLib, "SymSetOptions");
181 fSymInitialize = (fpSymInitialize)::GetProcAddress(hLib, "SymInitialize");
Reid Klecknerba5757d2015-11-05 01:07:54 +0000182 fEnumerateLoadedModules = (fpEnumerateLoadedModules)
183 ::GetProcAddress(hLib, "EnumerateLoadedModules64");
Michael J. Spencer44a36c82011-10-01 00:05:20 +0000184 }
Leny Kholodov1b73e662016-05-04 16:56:51 +0000185 return fStackWalk64 && fSymInitialize && fSymSetOptions && fMiniDumpWriteDump;
Michael J. Spencer44a36c82011-10-01 00:05:20 +0000186}
Reid Spencer4aff78a2004-09-16 15:53:16 +0000187
Yaron Keren240bd9c2015-07-22 19:01:14 +0000188using namespace llvm;
189
Reid Spencer4aff78a2004-09-16 15:53:16 +0000190// Forward declare.
191static LONG WINAPI LLVMUnhandledExceptionFilter(LPEXCEPTION_POINTERS ep);
192static BOOL WINAPI LLVMConsoleCtrlHandler(DWORD dwCtrlType);
193
JF Bastien93bce512018-05-15 04:06:28 +0000194// The function to call if ctrl-c is pressed.
Jeff Cohenba7cc682005-08-02 03:04:47 +0000195static void (*InterruptFunction)() = 0;
196
Rafael Espindola4f35da72013-06-13 21:16:58 +0000197static std::vector<std::string> *FilesToRemove = NULL;
Reid Spencer4aff78a2004-09-16 15:53:16 +0000198static bool RegisteredUnhandledExceptionFilter = false;
Reid Spencer1bdd0f02004-09-19 05:37:39 +0000199static bool CleanupExecuted = false;
200static PTOP_LEVEL_EXCEPTION_FILTER OldFilter = NULL;
Reid Spencer90debc52004-09-17 03:02:27 +0000201
202// Windows creates a new thread to execute the console handler when an event
203// (such as CTRL/C) occurs. This causes concurrency issues with the above
204// globals which this critical section addresses.
Reid Spencer4aff78a2004-09-16 15:53:16 +0000205static CRITICAL_SECTION CriticalSection;
Aaron Ballman50af8d42015-03-26 16:24:38 +0000206static bool CriticalSectionInitialized = false;
Reid Spencer4aff78a2004-09-16 15:53:16 +0000207
Richard Smith2ad6d482016-06-09 00:53:21 +0000208static StringRef Argv0;
209
Reid Klecknerba5757d2015-11-05 01:07:54 +0000210enum {
211#if defined(_M_X64)
212 NativeMachineType = IMAGE_FILE_MACHINE_AMD64
Martell Malone346a5fd2017-08-03 23:12:33 +0000213#elif defined(_M_ARM64)
214 NativeMachineType = IMAGE_FILE_MACHINE_ARM64
215#elif defined(_M_IX86)
Reid Klecknerba5757d2015-11-05 01:07:54 +0000216 NativeMachineType = IMAGE_FILE_MACHINE_I386
Martell Malone346a5fd2017-08-03 23:12:33 +0000217#elif defined(_M_ARM)
218 NativeMachineType = IMAGE_FILE_MACHINE_ARMNT
219#else
220 NativeMachineType = IMAGE_FILE_MACHINE_UNKNOWN
Reid Klecknerba5757d2015-11-05 01:07:54 +0000221#endif
222};
223
224static bool printStackTraceWithLLVMSymbolizer(llvm::raw_ostream &OS,
225 HANDLE hProcess, HANDLE hThread,
226 STACKFRAME64 &StackFrameOrig,
227 CONTEXT *ContextOrig) {
228 // StackWalk64 modifies the incoming stack frame and context, so copy them.
229 STACKFRAME64 StackFrame = StackFrameOrig;
230
231 // Copy the register context so that we don't modify it while we unwind. We
232 // could use InitializeContext + CopyContext, but that's only required to get
233 // at AVX registers, which typically aren't needed by StackWalk64. Reduce the
234 // flag set to indicate that there's less data.
235 CONTEXT Context = *ContextOrig;
236 Context.ContextFlags = CONTEXT_CONTROL | CONTEXT_INTEGER;
237
238 static void *StackTrace[256];
Aaron Ballman3c44b422015-11-05 14:22:56 +0000239 size_t Depth = 0;
Reid Klecknerba5757d2015-11-05 01:07:54 +0000240 while (fStackWalk64(NativeMachineType, hProcess, hThread, &StackFrame,
241 &Context, 0, fSymFunctionTableAccess64,
242 fSymGetModuleBase64, 0)) {
243 if (StackFrame.AddrFrame.Offset == 0)
244 break;
245 StackTrace[Depth++] = (void *)(uintptr_t)StackFrame.AddrPC.Offset;
246 if (Depth >= array_lengthof(StackTrace))
247 break;
248 }
249
Richard Smith2ad6d482016-06-09 00:53:21 +0000250 return printSymbolizedStackTrace(Argv0, &StackTrace[0], Depth, OS);
Reid Klecknerba5757d2015-11-05 01:07:54 +0000251}
252
253namespace {
254struct FindModuleData {
255 void **StackTrace;
256 int Depth;
257 const char **Modules;
258 intptr_t *Offsets;
259 StringSaver *StrPool;
260};
261}
262
NAKAMURA Takumi2de1b322016-03-07 00:13:09 +0000263static BOOL CALLBACK findModuleCallback(PCSTR ModuleName,
Reid Klecknerba5757d2015-11-05 01:07:54 +0000264 DWORD64 ModuleBase, ULONG ModuleSize,
265 void *VoidData) {
266 FindModuleData *Data = (FindModuleData*)VoidData;
267 intptr_t Beg = ModuleBase;
268 intptr_t End = Beg + ModuleSize;
269 for (int I = 0; I < Data->Depth; I++) {
270 if (Data->Modules[I])
271 continue;
272 intptr_t Addr = (intptr_t)Data->StackTrace[I];
273 if (Beg <= Addr && Addr < End) {
Mehdi Aminie4f0b752016-10-05 01:41:11 +0000274 Data->Modules[I] = Data->StrPool->save(ModuleName).data();
Reid Klecknerba5757d2015-11-05 01:07:54 +0000275 Data->Offsets[I] = Addr - Beg;
276 }
277 }
278 return TRUE;
279}
280
281static bool findModulesAndOffsets(void **StackTrace, int Depth,
282 const char **Modules, intptr_t *Offsets,
283 const char *MainExecutableName,
284 StringSaver &StrPool) {
285 if (!fEnumerateLoadedModules)
286 return false;
287 FindModuleData Data;
288 Data.StackTrace = StackTrace;
289 Data.Depth = Depth;
290 Data.Modules = Modules;
291 Data.Offsets = Offsets;
292 Data.StrPool = &StrPool;
293 fEnumerateLoadedModules(GetCurrentProcess(), findModuleCallback, &Data);
294 return true;
295}
296
Zachary Turnercd132c92015-03-05 19:10:52 +0000297static void PrintStackTraceForThread(llvm::raw_ostream &OS, HANDLE hProcess,
Zachary Turner62b7b612015-03-05 17:47:52 +0000298 HANDLE hThread, STACKFRAME64 &StackFrame,
299 CONTEXT *Context) {
Zachary Turner62b7b612015-03-05 17:47:52 +0000300 // Initialize the symbol handler.
Leny Kholodovbebb27b2015-07-02 14:34:57 +0000301 fSymSetOptions(SYMOPT_DEFERRED_LOADS | SYMOPT_LOAD_LINES);
302 fSymInitialize(hProcess, NULL, TRUE);
Zachary Turner62b7b612015-03-05 17:47:52 +0000303
Reid Klecknerba5757d2015-11-05 01:07:54 +0000304 // Try llvm-symbolizer first. llvm-symbolizer knows how to deal with both PDBs
305 // and DWARF, so it should do a good job regardless of what debug info or
306 // linker is in use.
307 if (printStackTraceWithLLVMSymbolizer(OS, hProcess, hThread, StackFrame,
308 Context)) {
309 return;
310 }
311
Zachary Turner62b7b612015-03-05 17:47:52 +0000312 while (true) {
Reid Klecknerba5757d2015-11-05 01:07:54 +0000313 if (!fStackWalk64(NativeMachineType, hProcess, hThread, &StackFrame,
314 Context, 0, fSymFunctionTableAccess64,
315 fSymGetModuleBase64, 0)) {
Zachary Turner62b7b612015-03-05 17:47:52 +0000316 break;
317 }
318
319 if (StackFrame.AddrFrame.Offset == 0)
320 break;
321
Zachary Turnercd132c92015-03-05 19:10:52 +0000322 using namespace llvm;
Zachary Turner62b7b612015-03-05 17:47:52 +0000323 // Print the PC in hexadecimal.
324 DWORD64 PC = StackFrame.AddrPC.Offset;
Martell Malone346a5fd2017-08-03 23:12:33 +0000325#if defined(_M_X64) || defined(_M_ARM64)
Zachary Turnercd132c92015-03-05 19:10:52 +0000326 OS << format("0x%016llX", PC);
Martell Malone346a5fd2017-08-03 23:12:33 +0000327#elif defined(_M_IX86) || defined(_M_ARM)
Zachary Turnercd132c92015-03-05 19:10:52 +0000328 OS << format("0x%08lX", static_cast<DWORD>(PC));
Zachary Turner62b7b612015-03-05 17:47:52 +0000329#endif
330
331// Print the parameters. Assume there are four.
Martell Malone346a5fd2017-08-03 23:12:33 +0000332#if defined(_M_X64) || defined(_M_ARM64)
Zachary Turnercd132c92015-03-05 19:10:52 +0000333 OS << format(" (0x%016llX 0x%016llX 0x%016llX 0x%016llX)",
Zachary Turner62b7b612015-03-05 17:47:52 +0000334 StackFrame.Params[0], StackFrame.Params[1], StackFrame.Params[2],
335 StackFrame.Params[3]);
Martell Malone346a5fd2017-08-03 23:12:33 +0000336#elif defined(_M_IX86) || defined(_M_ARM)
Zachary Turnercd132c92015-03-05 19:10:52 +0000337 OS << format(" (0x%08lX 0x%08lX 0x%08lX 0x%08lX)",
Zachary Turner62b7b612015-03-05 17:47:52 +0000338 static_cast<DWORD>(StackFrame.Params[0]),
339 static_cast<DWORD>(StackFrame.Params[1]),
340 static_cast<DWORD>(StackFrame.Params[2]),
341 static_cast<DWORD>(StackFrame.Params[3]));
342#endif
343 // Verify the PC belongs to a module in this process.
Leny Kholodovbebb27b2015-07-02 14:34:57 +0000344 if (!fSymGetModuleBase64(hProcess, PC)) {
Zachary Turnercd132c92015-03-05 19:10:52 +0000345 OS << " <unknown module>\n";
Zachary Turner62b7b612015-03-05 17:47:52 +0000346 continue;
347 }
348
349 // Print the symbol name.
350 char buffer[512];
351 IMAGEHLP_SYMBOL64 *symbol = reinterpret_cast<IMAGEHLP_SYMBOL64 *>(buffer);
352 memset(symbol, 0, sizeof(IMAGEHLP_SYMBOL64));
353 symbol->SizeOfStruct = sizeof(IMAGEHLP_SYMBOL64);
354 symbol->MaxNameLength = 512 - sizeof(IMAGEHLP_SYMBOL64);
355
356 DWORD64 dwDisp;
Leny Kholodovbebb27b2015-07-02 14:34:57 +0000357 if (!fSymGetSymFromAddr64(hProcess, PC, &dwDisp, symbol)) {
Zachary Turnercd132c92015-03-05 19:10:52 +0000358 OS << '\n';
Zachary Turner62b7b612015-03-05 17:47:52 +0000359 continue;
360 }
361
362 buffer[511] = 0;
363 if (dwDisp > 0)
Zachary Turnercd132c92015-03-05 19:10:52 +0000364 OS << format(", %s() + 0x%llX bytes(s)", (const char*)symbol->Name,
365 dwDisp);
Zachary Turner62b7b612015-03-05 17:47:52 +0000366 else
Zachary Turnercd132c92015-03-05 19:10:52 +0000367 OS << format(", %s", (const char*)symbol->Name);
Zachary Turner62b7b612015-03-05 17:47:52 +0000368
369 // Print the source file and line number information.
Yaron Keren24a86df2015-04-24 15:39:47 +0000370 IMAGEHLP_LINE64 line = {};
Zachary Turner62b7b612015-03-05 17:47:52 +0000371 DWORD dwLineDisp;
Zachary Turner62b7b612015-03-05 17:47:52 +0000372 line.SizeOfStruct = sizeof(line);
Leny Kholodovbebb27b2015-07-02 14:34:57 +0000373 if (fSymGetLineFromAddr64(hProcess, PC, &dwLineDisp, &line)) {
Zachary Turnercd132c92015-03-05 19:10:52 +0000374 OS << format(", %s, line %lu", line.FileName, line.LineNumber);
Zachary Turner62b7b612015-03-05 17:47:52 +0000375 if (dwLineDisp > 0)
Zachary Turnercd132c92015-03-05 19:10:52 +0000376 OS << format(" + 0x%lX byte(s)", dwLineDisp);
Zachary Turner62b7b612015-03-05 17:47:52 +0000377 }
378
Zachary Turnercd132c92015-03-05 19:10:52 +0000379 OS << '\n';
Zachary Turner62b7b612015-03-05 17:47:52 +0000380 }
381}
382
Reid Spencer3d7a6142004-08-29 19:22:48 +0000383namespace llvm {
Reid Spencer3d7a6142004-08-29 19:22:48 +0000384
385//===----------------------------------------------------------------------===//
Mikhail Glushenkovf64d93d2010-10-21 20:40:39 +0000386//=== WARNING: Implementation here must contain only Win32 specific code
Reid Spencer4aff78a2004-09-16 15:53:16 +0000387//=== and must not be UNIX code
Reid Spencer3d7a6142004-08-29 19:22:48 +0000388//===----------------------------------------------------------------------===//
389
Daniel Dunbar1bdedd32009-09-22 15:58:35 +0000390#ifdef _MSC_VER
JF Bastien93bce512018-05-15 04:06:28 +0000391/// Emulates hitting "retry" from an "abort, retry, ignore" CRT debug report
392/// dialog. "retry" raises an exception which ultimately triggers our stack
393/// dumper.
Reid Kleckner542a4542015-02-26 21:08:21 +0000394static LLVM_ATTRIBUTE_UNUSED int
395AvoidMessageBoxHook(int ReportType, char *Message, int *Return) {
Reid Klecknerbd39f212013-04-05 16:18:03 +0000396 // Set *Return to the retry code for the return value of _CrtDbgReport:
397 // http://msdn.microsoft.com/en-us/library/8hyw4sy7(v=vs.71).aspx
398 // This may also trigger just-in-time debugging via DebugBreak().
399 if (Return)
400 *Return = 1;
401 // Don't call _CrtDbgReport.
402 return TRUE;
403}
404
Daniel Dunbar1bdedd32009-09-22 15:58:35 +0000405#endif
Daniel Dunbar4c7b0ca2009-09-22 09:50:28 +0000406
Aaron Ballman03b968e2015-01-29 20:48:34 +0000407extern "C" void HandleAbort(int Sig) {
Michael J. Spencer89b0ad22015-01-29 17:20:29 +0000408 if (Sig == SIGABRT) {
409 LLVM_BUILTIN_TRAP;
410 }
411}
412
Aaron Ballman50af8d42015-03-26 16:24:38 +0000413static void InitializeThreading() {
414 if (CriticalSectionInitialized)
415 return;
416
417 // Now's the time to create the critical section. This is the first time
418 // through here, and there's only one thread.
419 InitializeCriticalSection(&CriticalSection);
420 CriticalSectionInitialized = true;
421}
422
Daniel Dunbar4c7b0ca2009-09-22 09:50:28 +0000423static void RegisterHandler() {
Leny Kholodovbebb27b2015-07-02 14:34:57 +0000424 // If we cannot load up the APIs (which would be unexpected as they should
425 // exist on every version of Windows we support), we will bail out since
426 // there would be nothing to report.
Reid Kleckner6cdf8442016-01-11 21:07:48 +0000427 if (!load64BitDebugHelp()) {
428 assert(false && "These APIs should always be available");
429 return;
430 }
Michael J. Spencer44a36c82011-10-01 00:05:20 +0000431
Reid Spencer1bdd0f02004-09-19 05:37:39 +0000432 if (RegisteredUnhandledExceptionFilter) {
Reid Spencer90debc52004-09-17 03:02:27 +0000433 EnterCriticalSection(&CriticalSection);
Reid Spencer4aff78a2004-09-16 15:53:16 +0000434 return;
Reid Spencer90debc52004-09-17 03:02:27 +0000435 }
Reid Spencer4aff78a2004-09-16 15:53:16 +0000436
Aaron Ballman50af8d42015-03-26 16:24:38 +0000437 InitializeThreading();
Reid Spencer4aff78a2004-09-16 15:53:16 +0000438
439 // Enter it immediately. Now if someone hits CTRL/C, the console handler
440 // can't proceed until the globals are updated.
441 EnterCriticalSection(&CriticalSection);
442
443 RegisteredUnhandledExceptionFilter = true;
Reid Spencer1bdd0f02004-09-19 05:37:39 +0000444 OldFilter = SetUnhandledExceptionFilter(LLVMUnhandledExceptionFilter);
Reid Spencer4aff78a2004-09-16 15:53:16 +0000445 SetConsoleCtrlHandler(LLVMConsoleCtrlHandler, TRUE);
446
447 // IMPORTANT NOTE: Caller must call LeaveCriticalSection(&CriticalSection) or
448 // else multi-threading problems will ensue.
449}
450
JF Bastien93bce512018-05-15 04:06:28 +0000451// The public API
Rafael Espindola4f35da72013-06-13 21:16:58 +0000452bool sys::RemoveFileOnSignal(StringRef Filename, std::string* ErrMsg) {
Reid Spencer4aff78a2004-09-16 15:53:16 +0000453 RegisterHandler();
454
Reid Spencer50eac3b2006-08-25 21:37:17 +0000455 if (CleanupExecuted) {
456 if (ErrMsg)
457 *ErrMsg = "Process terminating -- cannot register for removal";
458 return true;
459 }
Reid Spencer1bdd0f02004-09-19 05:37:39 +0000460
Reid Spencer4aff78a2004-09-16 15:53:16 +0000461 if (FilesToRemove == NULL)
Rafael Espindola4f35da72013-06-13 21:16:58 +0000462 FilesToRemove = new std::vector<std::string>;
Reid Spencer4aff78a2004-09-16 15:53:16 +0000463
Reid Spencerf070b6c2004-11-16 06:59:53 +0000464 FilesToRemove->push_back(Filename);
Reid Spencer4aff78a2004-09-16 15:53:16 +0000465
466 LeaveCriticalSection(&CriticalSection);
Reid Spencer50eac3b2006-08-25 21:37:17 +0000467 return false;
Reid Spencer3d7a6142004-08-29 19:22:48 +0000468}
469
JF Bastien93bce512018-05-15 04:06:28 +0000470// The public API
Rafael Espindola4f35da72013-06-13 21:16:58 +0000471void sys::DontRemoveFileOnSignal(StringRef Filename) {
Dan Gohmane201c072010-09-01 14:17:34 +0000472 if (FilesToRemove == NULL)
473 return;
474
NAKAMURA Takumi3f688b92010-10-22 01:23:50 +0000475 RegisterHandler();
476
Rafael Espindola4f35da72013-06-13 21:16:58 +0000477 std::vector<std::string>::reverse_iterator I =
David Majnemer42531262016-08-12 03:55:06 +0000478 find(reverse(*FilesToRemove), Filename);
Dan Gohmane201c072010-09-01 14:17:34 +0000479 if (I != FilesToRemove->rend())
480 FilesToRemove->erase(I.base()-1);
481
482 LeaveCriticalSection(&CriticalSection);
483}
484
Michael J. Spencer89b0ad22015-01-29 17:20:29 +0000485void sys::DisableSystemDialogsOnCrash() {
486 // Crash to stack trace handler on abort.
487 signal(SIGABRT, HandleAbort);
488
489 // The following functions are not reliably accessible on MinGW.
490#ifdef _MSC_VER
491 // We're already handling writing a "something went wrong" message.
492 _set_abort_behavior(0, _WRITE_ABORT_MSG);
493 // Disable Dr. Watson.
494 _set_abort_behavior(0, _CALL_REPORTFAULT);
495 _CrtSetReportHook(AvoidMessageBoxHook);
496#endif
497
498 // Disable standard error dialog box.
499 SetErrorMode(SEM_FAILCRITICALERRORS | SEM_NOGPFAULTERRORBOX |
500 SEM_NOOPENFILEERRORBOX);
501 _set_error_mode(_OUT_TO_STDERR);
502}
503
JF Bastien93bce512018-05-15 04:06:28 +0000504/// When an error signal (such as SIGABRT or SIGSEGV) is delivered to the
505/// process, print a stack trace and then exit.
Richard Smith2ad6d482016-06-09 00:53:21 +0000506void sys::PrintStackTraceOnErrorSignal(StringRef Argv0,
507 bool DisableCrashReporting) {
508 ::Argv0 = Argv0;
509
Leny Kholodov1b73e662016-05-04 16:56:51 +0000510 if (DisableCrashReporting || getenv("LLVM_DISABLE_CRASH_REPORT"))
511 Process::PreventCoreFiles();
512
Michael J. Spencer89b0ad22015-01-29 17:20:29 +0000513 DisableSystemDialogsOnCrash();
Reid Spencer4aff78a2004-09-16 15:53:16 +0000514 RegisterHandler();
515 LeaveCriticalSection(&CriticalSection);
Reid Spencer3d7a6142004-08-29 19:22:48 +0000516}
Benjamin Kramerf97eff62015-03-11 15:41:15 +0000517}
518
Yaron Kerenbdae8d62015-03-14 19:20:56 +0000519#if defined(__MINGW32__) && !defined(__MINGW64_VERSION_MAJOR)
520// Provide a prototype for RtlCaptureContext, mingw32 from mingw.org is
521// missing it but mingw-w64 has it.
Benjamin Kramerf97eff62015-03-11 15:41:15 +0000522extern "C" VOID WINAPI RtlCaptureContext(PCONTEXT ContextRecord);
Benjamin Kramerb47d5492015-03-11 16:09:02 +0000523#endif
Reid Spencer3d7a6142004-08-29 19:22:48 +0000524
Zachary Turnercd132c92015-03-05 19:10:52 +0000525void llvm::sys::PrintStackTrace(raw_ostream &OS) {
Reid Klecknere6580582015-03-05 18:26:58 +0000526 STACKFRAME64 StackFrame = {};
Yaron Keren24a86df2015-04-24 15:39:47 +0000527 CONTEXT Context = {};
Zachary Turner62b7b612015-03-05 17:47:52 +0000528 ::RtlCaptureContext(&Context);
529#if defined(_M_X64)
530 StackFrame.AddrPC.Offset = Context.Rip;
531 StackFrame.AddrStack.Offset = Context.Rsp;
532 StackFrame.AddrFrame.Offset = Context.Rbp;
Martell Malone346a5fd2017-08-03 23:12:33 +0000533#elif defined(_M_IX86)
Zachary Turner62b7b612015-03-05 17:47:52 +0000534 StackFrame.AddrPC.Offset = Context.Eip;
535 StackFrame.AddrStack.Offset = Context.Esp;
536 StackFrame.AddrFrame.Offset = Context.Ebp;
Martin Storsjo82931612018-04-13 06:38:02 +0000537#elif defined(_M_ARM64)
Martell Malone346a5fd2017-08-03 23:12:33 +0000538 StackFrame.AddrPC.Offset = Context.Pc;
539 StackFrame.AddrStack.Offset = Context.Sp;
540 StackFrame.AddrFrame.Offset = Context.Fp;
Martin Storsjo82931612018-04-13 06:38:02 +0000541#elif defined(_M_ARM)
542 StackFrame.AddrPC.Offset = Context.Pc;
543 StackFrame.AddrStack.Offset = Context.Sp;
544 StackFrame.AddrFrame.Offset = Context.R11;
Zachary Turner62b7b612015-03-05 17:47:52 +0000545#endif
546 StackFrame.AddrPC.Mode = AddrModeFlat;
547 StackFrame.AddrStack.Mode = AddrModeFlat;
548 StackFrame.AddrFrame.Mode = AddrModeFlat;
Zachary Turnercd132c92015-03-05 19:10:52 +0000549 PrintStackTraceForThread(OS, GetCurrentProcess(), GetCurrentThread(),
Zachary Turner62b7b612015-03-05 17:47:52 +0000550 StackFrame, &Context);
Argyrios Kyrtzidiseb9ae762013-01-09 19:42:40 +0000551}
552
Chris Lattner6a5d6ec2005-08-02 02:14:22 +0000553
Benjamin Kramer90c2db22015-03-11 15:53:24 +0000554void llvm::sys::SetInterruptFunction(void (*IF)()) {
Jeff Cohenba7cc682005-08-02 03:04:47 +0000555 RegisterHandler();
Jeff Cohen9aafa062005-08-02 03:26:32 +0000556 InterruptFunction = IF;
Jeff Cohenba7cc682005-08-02 03:04:47 +0000557 LeaveCriticalSection(&CriticalSection);
Chris Lattner6a5d6ec2005-08-02 02:14:22 +0000558}
Sebastian Redl8d5baa02009-03-19 23:26:52 +0000559
560
JF Bastien93bce512018-05-15 04:06:28 +0000561/// Add a function to be called when a signal is delivered to the process. The
562/// handler can have a cookie passed to it to identify what instance of the
563/// handler it is.
JF Bastienaa1333a2018-05-16 17:25:35 +0000564void llvm::sys::AddSignalHandler(sys::SignalHandlerCallback FnPtr,
565 void *Cookie) {
566 insertSignalHandler(FnPtr, Cookie);
Sebastian Redl8d5baa02009-03-19 23:26:52 +0000567 RegisterHandler();
Torok Edwin6fb09562010-03-31 12:07:16 +0000568 LeaveCriticalSection(&CriticalSection);
Sebastian Redl8d5baa02009-03-19 23:26:52 +0000569}
Reid Spencer3d7a6142004-08-29 19:22:48 +0000570
Reid Spencer4aff78a2004-09-16 15:53:16 +0000571static void Cleanup() {
Yaron Keren356aa462015-05-19 13:31:25 +0000572 if (CleanupExecuted)
573 return;
574
Reid Spencer4aff78a2004-09-16 15:53:16 +0000575 EnterCriticalSection(&CriticalSection);
576
Reid Spencer1bdd0f02004-09-19 05:37:39 +0000577 // Prevent other thread from registering new files and directories for
578 // removal, should we be executing because of the console handler callback.
579 CleanupExecuted = true;
580
581 // FIXME: open files cannot be deleted.
Reid Spencer4aff78a2004-09-16 15:53:16 +0000582 if (FilesToRemove != NULL)
583 while (!FilesToRemove->empty()) {
Rafael Espindolad724c282014-02-23 13:37:37 +0000584 llvm::sys::fs::remove(FilesToRemove->back());
Reid Spencer4aff78a2004-09-16 15:53:16 +0000585 FilesToRemove->pop_back();
586 }
Yaron Keren28738102015-07-22 21:11:17 +0000587 llvm::sys::RunSignalHandlers();
Reid Spencer4aff78a2004-09-16 15:53:16 +0000588 LeaveCriticalSection(&CriticalSection);
589}
590
Daniel Dunbar68272562010-05-08 02:10:34 +0000591void llvm::sys::RunInterruptHandlers() {
Aaron Ballman50af8d42015-03-26 16:24:38 +0000592 // The interrupt handler may be called from an interrupt, but it may also be
593 // called manually (such as the case of report_fatal_error with no registered
594 // error handler). We must ensure that the critical section is properly
595 // initialized.
596 InitializeThreading();
Daniel Dunbar68272562010-05-08 02:10:34 +0000597 Cleanup();
598}
599
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000600/// Find the Windows Registry Key for a given location.
Leny Kholodov1b73e662016-05-04 16:56:51 +0000601///
602/// \returns a valid HKEY if the location exists, else NULL.
603static HKEY FindWERKey(const llvm::Twine &RegistryLocation) {
604 HKEY Key;
Aaron Ballman0da8b2e2016-06-23 14:45:54 +0000605 if (ERROR_SUCCESS != ::RegOpenKeyExA(HKEY_LOCAL_MACHINE,
606 RegistryLocation.str().c_str(), 0,
607 KEY_QUERY_VALUE | KEY_READ, &Key))
Leny Kholodov1b73e662016-05-04 16:56:51 +0000608 return NULL;
609
610 return Key;
611}
612
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000613/// Populate ResultDirectory with the value for "DumpFolder" for a given
Leny Kholodov1b73e662016-05-04 16:56:51 +0000614/// Windows Registry key.
615///
616/// \returns true if a valid value for DumpFolder exists, false otherwise.
617static bool GetDumpFolder(HKEY Key,
618 llvm::SmallVectorImpl<char> &ResultDirectory) {
619 using llvm::sys::windows::UTF16ToUTF8;
620
621 if (!Key)
622 return false;
623
624 DWORD BufferLengthBytes = 0;
625
626 if (ERROR_SUCCESS != ::RegGetValueW(Key, 0, L"DumpFolder", REG_EXPAND_SZ,
627 NULL, NULL, &BufferLengthBytes))
628 return false;
629
630 SmallVector<wchar_t, MAX_PATH> Buffer(BufferLengthBytes);
631
632 if (ERROR_SUCCESS != ::RegGetValueW(Key, 0, L"DumpFolder", REG_EXPAND_SZ,
633 NULL, Buffer.data(), &BufferLengthBytes))
634 return false;
635
636 DWORD ExpandBufferSize = ::ExpandEnvironmentStringsW(Buffer.data(), NULL, 0);
637
638 if (!ExpandBufferSize)
639 return false;
640
641 SmallVector<wchar_t, MAX_PATH> ExpandBuffer(ExpandBufferSize);
642
643 if (ExpandBufferSize != ::ExpandEnvironmentStringsW(Buffer.data(),
644 ExpandBuffer.data(),
645 ExpandBufferSize))
646 return false;
647
648 if (UTF16ToUTF8(ExpandBuffer.data(), ExpandBufferSize - 1, ResultDirectory))
649 return false;
650
651 return true;
652}
653
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000654/// Populate ResultType with a valid MINIDUMP_TYPE based on the value of
Leny Kholodov1b73e662016-05-04 16:56:51 +0000655/// "DumpType" for a given Windows Registry key.
656///
657/// According to
658/// https://msdn.microsoft.com/en-us/library/windows/desktop/bb787181(v=vs.85).aspx
659/// valid values for DumpType are:
660/// * 0: Custom dump
661/// * 1: Mini dump
662/// * 2: Full dump
663/// If "Custom dump" is specified then the "CustomDumpFlags" field is read
664/// containing a bitwise combination of MINIDUMP_TYPE values.
665///
666/// \returns true if a valid value for ResultType can be set, false otherwise.
667static bool GetDumpType(HKEY Key, MINIDUMP_TYPE &ResultType) {
668 if (!Key)
669 return false;
670
671 DWORD DumpType;
672 DWORD TypeSize = sizeof(DumpType);
673 if (ERROR_SUCCESS != ::RegGetValueW(Key, NULL, L"DumpType", RRF_RT_REG_DWORD,
674 NULL, &DumpType,
675 &TypeSize))
676 return false;
677
678 switch (DumpType) {
679 case 0: {
680 DWORD Flags = 0;
681 if (ERROR_SUCCESS != ::RegGetValueW(Key, NULL, L"CustomDumpFlags",
682 RRF_RT_REG_DWORD, NULL, &Flags,
683 &TypeSize))
684 return false;
685
686 ResultType = static_cast<MINIDUMP_TYPE>(Flags);
687 break;
688 }
689 case 1:
690 ResultType = MiniDumpNormal;
691 break;
692 case 2:
693 ResultType = MiniDumpWithFullMemory;
694 break;
695 default:
696 return false;
697 }
698 return true;
699}
700
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000701/// Write a Windows dump file containing process information that can be
Leny Kholodov1b73e662016-05-04 16:56:51 +0000702/// used for post-mortem debugging.
703///
704/// \returns zero error code if a mini dump created, actual error code
705/// otherwise.
706static std::error_code WINAPI
707WriteWindowsDumpFile(PMINIDUMP_EXCEPTION_INFORMATION ExceptionInfo) {
708 using namespace llvm;
709 using namespace llvm::sys;
710
711 std::string MainExecutableName = fs::getMainExecutable(nullptr, nullptr);
712 StringRef ProgramName;
713
714 if (MainExecutableName.empty()) {
715 // If we can't get the executable filename,
716 // things are in worse shape than we realize
717 // and we should just bail out.
718 return mapWindowsError(::GetLastError());
719 }
720
721 ProgramName = path::filename(MainExecutableName.c_str());
722
723 // The Windows Registry location as specified at
724 // https://msdn.microsoft.com/en-us/library/windows/desktop/bb787181%28v=vs.85%29.aspx
725 // "Collecting User-Mode Dumps" that may optionally be set to collect crash
726 // dumps in a specified location.
727 StringRef LocalDumpsRegistryLocation =
728 "SOFTWARE\\Microsoft\\Windows\\Windows Error Reporting\\LocalDumps";
729
730 // The key pointing to the Registry location that may contain global crash
731 // dump settings. This will be NULL if the location can not be found.
732 ScopedRegHandle DefaultLocalDumpsKey(FindWERKey(LocalDumpsRegistryLocation));
733
734 // The key pointing to the Registry location that may contain
735 // application-specific crash dump settings. This will be NULL if the
736 // location can not be found.
737 ScopedRegHandle AppSpecificKey(
738 FindWERKey(Twine(LocalDumpsRegistryLocation) + "\\" + ProgramName));
739
740 // Look to see if a dump type is specified in the registry; first with the
741 // app-specific key and failing that with the global key. If none are found
742 // default to a normal dump (GetDumpType will return false either if the key
743 // is NULL or if there is no valid DumpType value at its location).
744 MINIDUMP_TYPE DumpType;
745 if (!GetDumpType(AppSpecificKey, DumpType))
746 if (!GetDumpType(DefaultLocalDumpsKey, DumpType))
747 DumpType = MiniDumpNormal;
748
749 // Look to see if a dump location is specified in the registry; first with the
750 // app-specific key and failing that with the global key. If none are found
751 // we'll just create the dump file in the default temporary file location
752 // (GetDumpFolder will return false either if the key is NULL or if there is
753 // no valid DumpFolder value at its location).
754 bool ExplicitDumpDirectorySet = true;
755 SmallString<MAX_PATH> DumpDirectory;
756 if (!GetDumpFolder(AppSpecificKey, DumpDirectory))
757 if (!GetDumpFolder(DefaultLocalDumpsKey, DumpDirectory))
758 ExplicitDumpDirectorySet = false;
759
760 int FD;
761 SmallString<MAX_PATH> DumpPath;
762
763 if (ExplicitDumpDirectorySet) {
764 if (std::error_code EC = fs::create_directories(DumpDirectory))
765 return EC;
766 if (std::error_code EC = fs::createUniqueFile(
767 Twine(DumpDirectory) + "\\" + ProgramName + ".%%%%%%.dmp", FD,
768 DumpPath))
769 return EC;
770 } else if (std::error_code EC =
771 fs::createTemporaryFile(ProgramName, "dmp", FD, DumpPath))
772 return EC;
773
774 // Our support functions return a file descriptor but Windows wants a handle.
775 ScopedCommonHandle FileHandle(reinterpret_cast<HANDLE>(_get_osfhandle(FD)));
776
777 if (!fMiniDumpWriteDump(::GetCurrentProcess(), ::GetCurrentProcessId(),
778 FileHandle, DumpType, ExceptionInfo, NULL, NULL))
779 return mapWindowsError(::GetLastError());
780
781 llvm::errs() << "Wrote crash dump file \"" << DumpPath << "\"\n";
782 return std::error_code();
783}
784
Reid Spencer4aff78a2004-09-16 15:53:16 +0000785static LONG WINAPI LLVMUnhandledExceptionFilter(LPEXCEPTION_POINTERS ep) {
Mikhail Glushenkov32acd742010-10-27 09:09:04 +0000786 Cleanup();
Mikhail Glushenkovf64d93d2010-10-21 20:40:39 +0000787
Leny Kholodov1b73e662016-05-04 16:56:51 +0000788 // We'll automatically write a Minidump file here to help diagnose
789 // the nasty sorts of crashes that aren't 100% reproducible from a set of
790 // inputs (or in the event that the user is unable or unwilling to provide a
791 // reproducible case).
Kristof Beyls7adf8c52017-03-31 14:58:52 +0000792 if (!llvm::sys::Process::AreCoreFilesPrevented()) {
Leny Kholodov1b73e662016-05-04 16:56:51 +0000793 MINIDUMP_EXCEPTION_INFORMATION ExceptionInfo;
794 ExceptionInfo.ThreadId = ::GetCurrentThreadId();
795 ExceptionInfo.ExceptionPointers = ep;
796 ExceptionInfo.ClientPointers = FALSE;
797
798 if (std::error_code EC = WriteWindowsDumpFile(&ExceptionInfo))
799 llvm::errs() << "Could not write crash dump file: " << EC.message()
800 << "\n";
801 }
802
Mikhail Glushenkov080d86f2010-10-28 08:25:44 +0000803 // Initialize the STACKFRAME structure.
Yaron Keren24a86df2015-04-24 15:39:47 +0000804 STACKFRAME64 StackFrame = {};
Reid Spencer4aff78a2004-09-16 15:53:16 +0000805
Michael J. Spencer44a36c82011-10-01 00:05:20 +0000806#if defined(_M_X64)
Michael J. Spencer44a36c82011-10-01 00:05:20 +0000807 StackFrame.AddrPC.Offset = ep->ContextRecord->Rip;
808 StackFrame.AddrPC.Mode = AddrModeFlat;
809 StackFrame.AddrStack.Offset = ep->ContextRecord->Rsp;
810 StackFrame.AddrStack.Mode = AddrModeFlat;
811 StackFrame.AddrFrame.Offset = ep->ContextRecord->Rbp;
812 StackFrame.AddrFrame.Mode = AddrModeFlat;
813#elif defined(_M_IX86)
Mikhail Glushenkov080d86f2010-10-28 08:25:44 +0000814 StackFrame.AddrPC.Offset = ep->ContextRecord->Eip;
815 StackFrame.AddrPC.Mode = AddrModeFlat;
816 StackFrame.AddrStack.Offset = ep->ContextRecord->Esp;
817 StackFrame.AddrStack.Mode = AddrModeFlat;
818 StackFrame.AddrFrame.Offset = ep->ContextRecord->Ebp;
819 StackFrame.AddrFrame.Mode = AddrModeFlat;
Martell Malone346a5fd2017-08-03 23:12:33 +0000820#elif defined(_M_ARM64) || defined(_M_ARM)
821 StackFrame.AddrPC.Offset = ep->ContextRecord->Pc;
822 StackFrame.AddrPC.Mode = AddrModeFlat;
823 StackFrame.AddrStack.Offset = ep->ContextRecord->Sp;
824 StackFrame.AddrStack.Mode = AddrModeFlat;
Martin Storsjo82931612018-04-13 06:38:02 +0000825#if defined(_M_ARM64)
Martell Malone346a5fd2017-08-03 23:12:33 +0000826 StackFrame.AddrFrame.Offset = ep->ContextRecord->Fp;
Martin Storsjo82931612018-04-13 06:38:02 +0000827#else
828 StackFrame.AddrFrame.Offset = ep->ContextRecord->R11;
829#endif
Martell Malone346a5fd2017-08-03 23:12:33 +0000830 StackFrame.AddrFrame.Mode = AddrModeFlat;
Michael J. Spencer44a36c82011-10-01 00:05:20 +0000831#endif
Reid Spencer4aff78a2004-09-16 15:53:16 +0000832
Mikhail Glushenkov080d86f2010-10-28 08:25:44 +0000833 HANDLE hProcess = GetCurrentProcess();
834 HANDLE hThread = GetCurrentThread();
Zachary Turnercd132c92015-03-05 19:10:52 +0000835 PrintStackTraceForThread(llvm::errs(), hProcess, hThread, StackFrame,
Zachary Turner62b7b612015-03-05 17:47:52 +0000836 ep->ContextRecord);
Mikhail Glushenkov080d86f2010-10-28 08:25:44 +0000837
Michael J. Spencer89b0ad22015-01-29 17:20:29 +0000838 _exit(ep->ExceptionRecord->ExceptionCode);
Reid Spencer4aff78a2004-09-16 15:53:16 +0000839}
840
841static BOOL WINAPI LLVMConsoleCtrlHandler(DWORD dwCtrlType) {
Jeff Cohen9aafa062005-08-02 03:26:32 +0000842 // We are running in our very own thread, courtesy of Windows.
Jeff Cohenba7cc682005-08-02 03:04:47 +0000843 EnterCriticalSection(&CriticalSection);
Reid Spencer4aff78a2004-09-16 15:53:16 +0000844 Cleanup();
845
Jeff Cohenba7cc682005-08-02 03:04:47 +0000846 // If an interrupt function has been set, go and run one it; otherwise,
847 // the process dies.
848 void (*IF)() = InterruptFunction;
849 InterruptFunction = 0; // Don't run it on another CTRL-C.
850
851 if (IF) {
Jeff Cohen9aafa062005-08-02 03:26:32 +0000852 // Note: if the interrupt function throws an exception, there is nothing
853 // to catch it in this thread so it will kill the process.
854 IF(); // Run it now.
Jeff Cohenba7cc682005-08-02 03:04:47 +0000855 LeaveCriticalSection(&CriticalSection);
856 return TRUE; // Don't kill the process.
857 }
858
Reid Spencer90debc52004-09-17 03:02:27 +0000859 // Allow normal processing to take place; i.e., the process dies.
Jeff Cohenba7cc682005-08-02 03:04:47 +0000860 LeaveCriticalSection(&CriticalSection);
Reid Spencer4aff78a2004-09-16 15:53:16 +0000861 return FALSE;
862}
Michael J. Spencer44a36c82011-10-01 00:05:20 +0000863
864#if __MINGW32__
865 // We turned these warnings off for this file so that MinGW-g++ doesn't
866 // complain about the ll format specifiers used. Now we are turning the
867 // warnings back on. If MinGW starts to support diagnostic stacks, we can
868 // replace this with a pop.
869 #pragma GCC diagnostic warning "-Wformat"
870 #pragma GCC diagnostic warning "-Wformat-extra-args"
871#endif