blob: b18b4d1dacacd1f32275e435fc0c52d2af844202 [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//===----------------------------------------------------------------------===//
13
Michael J. Spencer447762d2010-11-29 18:16:10 +000014#include "Windows.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000015#include <algorithm>
Reid Spencer70b68352004-09-28 23:58:03 +000016#include <stdio.h>
Reid Spencer4aff78a2004-09-16 15:53:16 +000017#include <vector>
18
Jeff Cohen07e22ba2005-02-19 03:01:13 +000019#ifdef __MINGW32__
Reid Spencer187b4ad2006-06-01 19:03:21 +000020 #include <imagehlp.h>
Reid Spencer99049282004-09-23 14:47:10 +000021#else
Reid Spencer187b4ad2006-06-01 19:03:21 +000022 #include <dbghelp.h>
Reid Spencer99049282004-09-23 14:47:10 +000023#endif
24#include <psapi.h>
Reid Spencer4aff78a2004-09-16 15:53:16 +000025
Michael J. Spencer44a36c82011-10-01 00:05:20 +000026#ifdef _MSC_VER
27 #pragma comment(lib, "psapi.lib")
28 #pragma comment(lib, "dbghelp.lib")
29#elif __MINGW32__
Reid Spencer187b4ad2006-06-01 19:03:21 +000030 #if ((HAVE_LIBIMAGEHLP != 1) || (HAVE_LIBPSAPI != 1))
31 #error "libimagehlp.a & libpsapi.a should be present"
32 #endif
Michael J. Spencer44a36c82011-10-01 00:05:20 +000033 // The version of g++ that comes with MinGW does *not* properly understand
34 // the ll format specifier for printf. However, MinGW passes the format
35 // specifiers on to the MSVCRT entirely, and the CRT understands the ll
36 // specifier. So these warnings are spurious in this case. Since we compile
37 // with -Wall, this will generate these warnings which should be ignored. So
38 // we will turn off the warnings for this just file. However, MinGW also does
39 // not support push and pop for diagnostics, so we have to manually turn it
40 // back on at the end of the file.
41 #pragma GCC diagnostic ignored "-Wformat"
42 #pragma GCC diagnostic ignored "-Wformat-extra-args"
43
Anton Korobeynikovb27f11e2011-10-21 09:38:50 +000044 #if !defined(__MINGW64_VERSION_MAJOR)
45 // MinGW.org does not have updated support for the 64-bit versions of the
46 // DebugHlp APIs. So we will have to load them manually. The structures and
47 // method signatures were pulled from DbgHelp.h in the Windows Platform SDK,
48 // and adjusted for brevity.
Michael J. Spencer44a36c82011-10-01 00:05:20 +000049 typedef struct _IMAGEHLP_LINE64 {
50 DWORD SizeOfStruct;
51 PVOID Key;
52 DWORD LineNumber;
53 PCHAR FileName;
54 DWORD64 Address;
55 } IMAGEHLP_LINE64, *PIMAGEHLP_LINE64;
56
57 typedef struct _IMAGEHLP_SYMBOL64 {
58 DWORD SizeOfStruct;
59 DWORD64 Address;
60 DWORD Size;
61 DWORD Flags;
62 DWORD MaxNameLength;
63 CHAR Name[1];
64 } IMAGEHLP_SYMBOL64, *PIMAGEHLP_SYMBOL64;
65
66 typedef struct _tagADDRESS64 {
67 DWORD64 Offset;
68 WORD Segment;
69 ADDRESS_MODE Mode;
70 } ADDRESS64, *LPADDRESS64;
71
72 typedef struct _KDHELP64 {
73 DWORD64 Thread;
74 DWORD ThCallbackStack;
75 DWORD ThCallbackBStore;
76 DWORD NextCallback;
77 DWORD FramePointer;
78 DWORD64 KiCallUserMode;
79 DWORD64 KeUserCallbackDispatcher;
80 DWORD64 SystemRangeStart;
81 DWORD64 KiUserExceptionDispatcher;
82 DWORD64 StackBase;
83 DWORD64 StackLimit;
84 DWORD64 Reserved[5];
85 } KDHELP64, *PKDHELP64;
86
87 typedef struct _tagSTACKFRAME64 {
88 ADDRESS64 AddrPC;
89 ADDRESS64 AddrReturn;
90 ADDRESS64 AddrFrame;
91 ADDRESS64 AddrStack;
92 ADDRESS64 AddrBStore;
93 PVOID FuncTableEntry;
94 DWORD64 Params[4];
95 BOOL Far;
96 BOOL Virtual;
97 DWORD64 Reserved[3];
98 KDHELP64 KdHelp;
99 } STACKFRAME64, *LPSTACKFRAME64;
100
101typedef BOOL (__stdcall *PREAD_PROCESS_MEMORY_ROUTINE64)(HANDLE hProcess,
102 DWORD64 qwBaseAddress, PVOID lpBuffer, DWORD nSize,
103 LPDWORD lpNumberOfBytesRead);
104
105typedef PVOID (__stdcall *PFUNCTION_TABLE_ACCESS_ROUTINE64)( HANDLE ahProcess,
106 DWORD64 AddrBase);
107
108typedef DWORD64 (__stdcall *PGET_MODULE_BASE_ROUTINE64)(HANDLE hProcess,
109 DWORD64 Address);
110
111typedef DWORD64 (__stdcall *PTRANSLATE_ADDRESS_ROUTINE64)(HANDLE hProcess,
112 HANDLE hThread, LPADDRESS64 lpaddr);
113
114typedef BOOL (WINAPI *fpStackWalk64)(DWORD, HANDLE, HANDLE, LPSTACKFRAME64,
115 PVOID, PREAD_PROCESS_MEMORY_ROUTINE64,
116 PFUNCTION_TABLE_ACCESS_ROUTINE64,
117 PGET_MODULE_BASE_ROUTINE64,
118 PTRANSLATE_ADDRESS_ROUTINE64);
119static fpStackWalk64 StackWalk64;
120
121typedef DWORD64 (WINAPI *fpSymGetModuleBase64)(HANDLE, DWORD64);
122static fpSymGetModuleBase64 SymGetModuleBase64;
123
124typedef BOOL (WINAPI *fpSymGetSymFromAddr64)(HANDLE, DWORD64,
125 PDWORD64, PIMAGEHLP_SYMBOL64);
126static fpSymGetSymFromAddr64 SymGetSymFromAddr64;
127
128typedef BOOL (WINAPI *fpSymGetLineFromAddr64)(HANDLE, DWORD64,
129 PDWORD, PIMAGEHLP_LINE64);
130static fpSymGetLineFromAddr64 SymGetLineFromAddr64;
131
132typedef PVOID (WINAPI *fpSymFunctionTableAccess64)(HANDLE, DWORD64);
133static fpSymFunctionTableAccess64 SymFunctionTableAccess64;
134
135static bool load64BitDebugHelp(void) {
136 HMODULE hLib = ::LoadLibrary("Dbghelp.dll");
137 if (hLib) {
138 StackWalk64 = (fpStackWalk64)
139 ::GetProcAddress(hLib, "StackWalk64");
140 SymGetModuleBase64 = (fpSymGetModuleBase64)
141 ::GetProcAddress(hLib, "SymGetModuleBase64");
142 SymGetSymFromAddr64 = (fpSymGetSymFromAddr64)
143 ::GetProcAddress(hLib, "SymGetSymFromAddr64");
144 SymGetLineFromAddr64 = (fpSymGetLineFromAddr64)
145 ::GetProcAddress(hLib, "SymGetLineFromAddr64");
146 SymFunctionTableAccess64 = (fpSymFunctionTableAccess64)
147 ::GetProcAddress(hLib, "SymFunctionTableAccess64");
148 }
149 return StackWalk64 != NULL;
150}
Anton Korobeynikovb27f11e2011-10-21 09:38:50 +0000151 #endif // !defined(__MINGW64_VERSION_MAJOR)
Michael J. Spencer44a36c82011-10-01 00:05:20 +0000152#endif // __MINGW32__
Reid Spencer4aff78a2004-09-16 15:53:16 +0000153
154// Forward declare.
155static LONG WINAPI LLVMUnhandledExceptionFilter(LPEXCEPTION_POINTERS ep);
156static BOOL WINAPI LLVMConsoleCtrlHandler(DWORD dwCtrlType);
157
Jeff Cohenba7cc682005-08-02 03:04:47 +0000158// InterruptFunction - The function to call if ctrl-c is pressed.
159static void (*InterruptFunction)() = 0;
160
Reid Spencer70b68352004-09-28 23:58:03 +0000161static std::vector<llvm::sys::Path> *FilesToRemove = NULL;
Chris Lattner4fdd0422009-03-04 21:21:36 +0000162static std::vector<std::pair<void(*)(void*), void*> > *CallBacksToRun = 0;
Reid Spencer4aff78a2004-09-16 15:53:16 +0000163static bool RegisteredUnhandledExceptionFilter = false;
Reid Spencer1bdd0f02004-09-19 05:37:39 +0000164static bool CleanupExecuted = false;
Daniel Dunbar4c7b0ca2009-09-22 09:50:28 +0000165static bool ExitOnUnhandledExceptions = false;
Reid Spencer1bdd0f02004-09-19 05:37:39 +0000166static PTOP_LEVEL_EXCEPTION_FILTER OldFilter = NULL;
Reid Spencer90debc52004-09-17 03:02:27 +0000167
168// Windows creates a new thread to execute the console handler when an event
169// (such as CTRL/C) occurs. This causes concurrency issues with the above
170// globals which this critical section addresses.
Reid Spencer4aff78a2004-09-16 15:53:16 +0000171static CRITICAL_SECTION CriticalSection;
172
Reid Spencer3d7a6142004-08-29 19:22:48 +0000173namespace llvm {
Reid Spencer3d7a6142004-08-29 19:22:48 +0000174
175//===----------------------------------------------------------------------===//
Mikhail Glushenkovf64d93d2010-10-21 20:40:39 +0000176//=== WARNING: Implementation here must contain only Win32 specific code
Reid Spencer4aff78a2004-09-16 15:53:16 +0000177//=== and must not be UNIX code
Reid Spencer3d7a6142004-08-29 19:22:48 +0000178//===----------------------------------------------------------------------===//
179
Daniel Dunbar1bdedd32009-09-22 15:58:35 +0000180#ifdef _MSC_VER
Reid Klecknerbd39f212013-04-05 16:18:03 +0000181/// AvoidMessageBoxHook - Emulates hitting "retry" from an "abort, retry,
182/// ignore" CRT debug report dialog. "retry" raises an exception which
183/// ultimately triggers our stack dumper.
184static int AvoidMessageBoxHook(int ReportType, char *Message, int *Return) {
185 // Set *Return to the retry code for the return value of _CrtDbgReport:
186 // http://msdn.microsoft.com/en-us/library/8hyw4sy7(v=vs.71).aspx
187 // This may also trigger just-in-time debugging via DebugBreak().
188 if (Return)
189 *Return = 1;
190 // Don't call _CrtDbgReport.
191 return TRUE;
192}
193
Daniel Dunbar4c7b0ca2009-09-22 09:50:28 +0000194/// CRTReportHook - Function called on a CRT debugging event.
195static int CRTReportHook(int ReportType, char *Message, int *Return) {
196 // Don't cause a DebugBreak() on return.
197 if (Return)
198 *Return = 0;
Reid Spencer4aff78a2004-09-16 15:53:16 +0000199
Daniel Dunbar4c7b0ca2009-09-22 09:50:28 +0000200 switch (ReportType) {
201 default:
202 case _CRT_ASSERT:
203 fprintf(stderr, "CRT assert: %s\n", Message);
204 // FIXME: Is there a way to just crash? Perhaps throw to the unhandled
205 // exception code? Perhaps SetErrorMode() handles this.
206 _exit(3);
207 break;
208 case _CRT_ERROR:
209 fprintf(stderr, "CRT error: %s\n", Message);
210 // FIXME: Is there a way to just crash? Perhaps throw to the unhandled
211 // exception code? Perhaps SetErrorMode() handles this.
212 _exit(3);
213 break;
214 case _CRT_WARN:
215 fprintf(stderr, "CRT warn: %s\n", Message);
216 break;
217 }
218
219 // Don't call _CrtDbgReport.
220 return TRUE;
221}
Daniel Dunbar1bdedd32009-09-22 15:58:35 +0000222#endif
Daniel Dunbar4c7b0ca2009-09-22 09:50:28 +0000223
224static void RegisterHandler() {
Anton Korobeynikovb27f11e2011-10-21 09:38:50 +0000225#if __MINGW32__ && !defined(__MINGW64_VERSION_MAJOR)
226 // On MinGW.org, we need to load up the symbols explicitly, because the
Michael J. Spencer44a36c82011-10-01 00:05:20 +0000227 // Win32 framework they include does not have support for the 64-bit
228 // versions of the APIs we need. If we cannot load up the APIs (which
229 // would be unexpected as they should exist on every version of Windows
230 // we support), we will bail out since there would be nothing to report.
231 if (!load64BitDebugHelp()) {
232 assert(false && "These APIs should always be available");
233 return;
234 }
235#endif
236
Reid Spencer1bdd0f02004-09-19 05:37:39 +0000237 if (RegisteredUnhandledExceptionFilter) {
Reid Spencer90debc52004-09-17 03:02:27 +0000238 EnterCriticalSection(&CriticalSection);
Reid Spencer4aff78a2004-09-16 15:53:16 +0000239 return;
Reid Spencer90debc52004-09-17 03:02:27 +0000240 }
Reid Spencer4aff78a2004-09-16 15:53:16 +0000241
242 // Now's the time to create the critical section. This is the first time
243 // through here, and there's only one thread.
244 InitializeCriticalSection(&CriticalSection);
245
246 // Enter it immediately. Now if someone hits CTRL/C, the console handler
247 // can't proceed until the globals are updated.
248 EnterCriticalSection(&CriticalSection);
249
250 RegisteredUnhandledExceptionFilter = true;
Reid Spencer1bdd0f02004-09-19 05:37:39 +0000251 OldFilter = SetUnhandledExceptionFilter(LLVMUnhandledExceptionFilter);
Reid Spencer4aff78a2004-09-16 15:53:16 +0000252 SetConsoleCtrlHandler(LLVMConsoleCtrlHandler, TRUE);
253
Reid Klecknerbd39f212013-04-05 16:18:03 +0000254#ifdef _MSC_VER
255 const char *EnableMsgbox = getenv("LLVM_ENABLE_CRT_REPORT");
256 if (!EnableMsgbox || strcmp("0", EnableMsgbox) == 0) {
257 // Setting a report hook overrides the default behavior of popping an "abort,
258 // retry, or ignore" dialog.
259 _CrtSetReportHook(AvoidMessageBoxHook);
260 }
261#endif
262
Daniel Dunbar4c7b0ca2009-09-22 09:50:28 +0000263 // Environment variable to disable any kind of crash dialog.
Argyrios Kyrtzidiscd8fe082012-01-11 20:53:25 +0000264 if (getenv("LLVM_DISABLE_CRASH_REPORT")) {
NAKAMURA Takumiad205572010-10-06 02:15:22 +0000265#ifdef _MSC_VER
Daniel Dunbar4c7b0ca2009-09-22 09:50:28 +0000266 _CrtSetReportHook(CRTReportHook);
NAKAMURA Takumiad205572010-10-06 02:15:22 +0000267#endif
NAKAMURA Takumibb4ea1f2011-01-17 22:41:15 +0000268 SetErrorMode(SEM_FAILCRITICALERRORS |
269 SEM_NOGPFAULTERRORBOX |
270 SEM_NOOPENFILEERRORBOX);
Daniel Dunbar1bdedd32009-09-22 15:58:35 +0000271 ExitOnUnhandledExceptions = true;
Daniel Dunbar4c7b0ca2009-09-22 09:50:28 +0000272 }
273
Reid Spencer4aff78a2004-09-16 15:53:16 +0000274 // IMPORTANT NOTE: Caller must call LeaveCriticalSection(&CriticalSection) or
275 // else multi-threading problems will ensue.
276}
277
Reid Spencer3d7a6142004-08-29 19:22:48 +0000278// RemoveFileOnSignal - The public API
Reid Spencer50eac3b2006-08-25 21:37:17 +0000279bool sys::RemoveFileOnSignal(const sys::Path &Filename, std::string* ErrMsg) {
Reid Spencer4aff78a2004-09-16 15:53:16 +0000280 RegisterHandler();
281
Reid Spencer50eac3b2006-08-25 21:37:17 +0000282 if (CleanupExecuted) {
283 if (ErrMsg)
284 *ErrMsg = "Process terminating -- cannot register for removal";
285 return true;
286 }
Reid Spencer1bdd0f02004-09-19 05:37:39 +0000287
Reid Spencer4aff78a2004-09-16 15:53:16 +0000288 if (FilesToRemove == NULL)
Reid Spencer70b68352004-09-28 23:58:03 +0000289 FilesToRemove = new std::vector<sys::Path>;
Reid Spencer4aff78a2004-09-16 15:53:16 +0000290
Reid Spencerf070b6c2004-11-16 06:59:53 +0000291 FilesToRemove->push_back(Filename);
Reid Spencer4aff78a2004-09-16 15:53:16 +0000292
293 LeaveCriticalSection(&CriticalSection);
Reid Spencer50eac3b2006-08-25 21:37:17 +0000294 return false;
Reid Spencer3d7a6142004-08-29 19:22:48 +0000295}
296
Dan Gohmane201c072010-09-01 14:17:34 +0000297// DontRemoveFileOnSignal - The public API
298void sys::DontRemoveFileOnSignal(const sys::Path &Filename) {
299 if (FilesToRemove == NULL)
300 return;
301
NAKAMURA Takumi3f688b92010-10-22 01:23:50 +0000302 RegisterHandler();
303
Dan Gohmane201c072010-09-01 14:17:34 +0000304 FilesToRemove->push_back(Filename);
305 std::vector<sys::Path>::reverse_iterator I =
306 std::find(FilesToRemove->rbegin(), FilesToRemove->rend(), Filename);
307 if (I != FilesToRemove->rend())
308 FilesToRemove->erase(I.base()-1);
309
310 LeaveCriticalSection(&CriticalSection);
311}
312
Reid Spencer3d7a6142004-08-29 19:22:48 +0000313/// PrintStackTraceOnErrorSignal - When an error signal (such as SIBABRT or
314/// SIGSEGV) is delivered to the process, print a stack trace and then exit.
Reid Spencer4aff78a2004-09-16 15:53:16 +0000315void sys::PrintStackTraceOnErrorSignal() {
316 RegisterHandler();
317 LeaveCriticalSection(&CriticalSection);
Reid Spencer3d7a6142004-08-29 19:22:48 +0000318}
319
Argyrios Kyrtzidiseb9ae762013-01-09 19:42:40 +0000320void llvm::sys::PrintStackTrace(FILE *) {
321 // FIXME: Implement.
322}
323
Chris Lattner6a5d6ec2005-08-02 02:14:22 +0000324
325void sys::SetInterruptFunction(void (*IF)()) {
Jeff Cohenba7cc682005-08-02 03:04:47 +0000326 RegisterHandler();
Jeff Cohen9aafa062005-08-02 03:26:32 +0000327 InterruptFunction = IF;
Jeff Cohenba7cc682005-08-02 03:04:47 +0000328 LeaveCriticalSection(&CriticalSection);
Chris Lattner6a5d6ec2005-08-02 02:14:22 +0000329}
Sebastian Redl8d5baa02009-03-19 23:26:52 +0000330
331
332/// AddSignalHandler - Add a function to be called when a signal is delivered
333/// to the process. The handler can have a cookie passed to it to identify
334/// what instance of the handler it is.
335void sys::AddSignalHandler(void (*FnPtr)(void *), void *Cookie) {
336 if (CallBacksToRun == 0)
337 CallBacksToRun = new std::vector<std::pair<void(*)(void*), void*> >();
338 CallBacksToRun->push_back(std::make_pair(FnPtr, Cookie));
339 RegisterHandler();
Torok Edwin6fb09562010-03-31 12:07:16 +0000340 LeaveCriticalSection(&CriticalSection);
Sebastian Redl8d5baa02009-03-19 23:26:52 +0000341}
Reid Spencer3d7a6142004-08-29 19:22:48 +0000342}
343
Reid Spencer4aff78a2004-09-16 15:53:16 +0000344static void Cleanup() {
345 EnterCriticalSection(&CriticalSection);
346
Reid Spencer1bdd0f02004-09-19 05:37:39 +0000347 // Prevent other thread from registering new files and directories for
348 // removal, should we be executing because of the console handler callback.
349 CleanupExecuted = true;
350
351 // FIXME: open files cannot be deleted.
352
Reid Spencer4aff78a2004-09-16 15:53:16 +0000353 if (FilesToRemove != NULL)
354 while (!FilesToRemove->empty()) {
Chris Lattner433cf712009-07-09 16:17:28 +0000355 FilesToRemove->back().eraseFromDisk();
Reid Spencer4aff78a2004-09-16 15:53:16 +0000356 FilesToRemove->pop_back();
357 }
358
Chris Lattner4fdd0422009-03-04 21:21:36 +0000359 if (CallBacksToRun)
360 for (unsigned i = 0, e = CallBacksToRun->size(); i != e; ++i)
361 (*CallBacksToRun)[i].first((*CallBacksToRun)[i].second);
Reid Spencer4aff78a2004-09-16 15:53:16 +0000362
363 LeaveCriticalSection(&CriticalSection);
364}
365
Daniel Dunbar68272562010-05-08 02:10:34 +0000366void llvm::sys::RunInterruptHandlers() {
367 Cleanup();
368}
369
Reid Spencer4aff78a2004-09-16 15:53:16 +0000370static LONG WINAPI LLVMUnhandledExceptionFilter(LPEXCEPTION_POINTERS ep) {
Mikhail Glushenkov32acd742010-10-27 09:09:04 +0000371 Cleanup();
Mikhail Glushenkovf64d93d2010-10-21 20:40:39 +0000372
Mikhail Glushenkov080d86f2010-10-28 08:25:44 +0000373 // Initialize the STACKFRAME structure.
Michael J. Spencer44a36c82011-10-01 00:05:20 +0000374 STACKFRAME64 StackFrame;
Mikhail Glushenkov080d86f2010-10-28 08:25:44 +0000375 memset(&StackFrame, 0, sizeof(StackFrame));
Reid Spencer4aff78a2004-09-16 15:53:16 +0000376
Michael J. Spencer44a36c82011-10-01 00:05:20 +0000377 DWORD machineType;
378#if defined(_M_X64)
379 machineType = IMAGE_FILE_MACHINE_AMD64;
380 StackFrame.AddrPC.Offset = ep->ContextRecord->Rip;
381 StackFrame.AddrPC.Mode = AddrModeFlat;
382 StackFrame.AddrStack.Offset = ep->ContextRecord->Rsp;
383 StackFrame.AddrStack.Mode = AddrModeFlat;
384 StackFrame.AddrFrame.Offset = ep->ContextRecord->Rbp;
385 StackFrame.AddrFrame.Mode = AddrModeFlat;
386#elif defined(_M_IX86)
387 machineType = IMAGE_FILE_MACHINE_I386;
Mikhail Glushenkov080d86f2010-10-28 08:25:44 +0000388 StackFrame.AddrPC.Offset = ep->ContextRecord->Eip;
389 StackFrame.AddrPC.Mode = AddrModeFlat;
390 StackFrame.AddrStack.Offset = ep->ContextRecord->Esp;
391 StackFrame.AddrStack.Mode = AddrModeFlat;
392 StackFrame.AddrFrame.Offset = ep->ContextRecord->Ebp;
393 StackFrame.AddrFrame.Mode = AddrModeFlat;
Michael J. Spencer44a36c82011-10-01 00:05:20 +0000394#endif
Reid Spencer4aff78a2004-09-16 15:53:16 +0000395
Mikhail Glushenkov080d86f2010-10-28 08:25:44 +0000396 HANDLE hProcess = GetCurrentProcess();
397 HANDLE hThread = GetCurrentThread();
Reid Spencer4aff78a2004-09-16 15:53:16 +0000398
Mikhail Glushenkov080d86f2010-10-28 08:25:44 +0000399 // Initialize the symbol handler.
400 SymSetOptions(SYMOPT_DEFERRED_LOADS|SYMOPT_LOAD_LINES);
401 SymInitialize(hProcess, NULL, TRUE);
Reid Spencer4aff78a2004-09-16 15:53:16 +0000402
Mikhail Glushenkov080d86f2010-10-28 08:25:44 +0000403 while (true) {
Michael J. Spencer44a36c82011-10-01 00:05:20 +0000404 if (!StackWalk64(machineType, hProcess, hThread, &StackFrame,
405 ep->ContextRecord, NULL, SymFunctionTableAccess64,
406 SymGetModuleBase64, NULL)) {
Mikhail Glushenkov080d86f2010-10-28 08:25:44 +0000407 break;
Reid Spencer4aff78a2004-09-16 15:53:16 +0000408 }
Chuck Rose III07b57d22007-11-21 00:37:56 +0000409
Mikhail Glushenkov080d86f2010-10-28 08:25:44 +0000410 if (StackFrame.AddrFrame.Offset == 0)
411 break;
412
413 // Print the PC in hexadecimal.
Michael J. Spencer44a36c82011-10-01 00:05:20 +0000414 DWORD64 PC = StackFrame.AddrPC.Offset;
415#if defined(_M_X64)
416 fprintf(stderr, "0x%016llX", PC);
417#elif defined(_M_IX86)
418 fprintf(stderr, "0x%08lX", static_cast<DWORD>(PC));
419#endif
Mikhail Glushenkov080d86f2010-10-28 08:25:44 +0000420
421 // Print the parameters. Assume there are four.
Michael J. Spencer44a36c82011-10-01 00:05:20 +0000422#if defined(_M_X64)
423 fprintf(stderr, " (0x%016llX 0x%016llX 0x%016llX 0x%016llX)",
424 StackFrame.Params[0],
425 StackFrame.Params[1],
426 StackFrame.Params[2],
427 StackFrame.Params[3]);
428#elif defined(_M_IX86)
Mikhail Glushenkov080d86f2010-10-28 08:25:44 +0000429 fprintf(stderr, " (0x%08lX 0x%08lX 0x%08lX 0x%08lX)",
Michael J. Spencer44a36c82011-10-01 00:05:20 +0000430 static_cast<DWORD>(StackFrame.Params[0]),
431 static_cast<DWORD>(StackFrame.Params[1]),
432 static_cast<DWORD>(StackFrame.Params[2]),
433 static_cast<DWORD>(StackFrame.Params[3]));
434#endif
Mikhail Glushenkov080d86f2010-10-28 08:25:44 +0000435 // Verify the PC belongs to a module in this process.
Michael J. Spencer44a36c82011-10-01 00:05:20 +0000436 if (!SymGetModuleBase64(hProcess, PC)) {
Mikhail Glushenkov080d86f2010-10-28 08:25:44 +0000437 fputs(" <unknown module>\n", stderr);
438 continue;
439 }
440
441 // Print the symbol name.
442 char buffer[512];
Michael J. Spencer44a36c82011-10-01 00:05:20 +0000443 IMAGEHLP_SYMBOL64 *symbol = reinterpret_cast<IMAGEHLP_SYMBOL64 *>(buffer);
444 memset(symbol, 0, sizeof(IMAGEHLP_SYMBOL64));
445 symbol->SizeOfStruct = sizeof(IMAGEHLP_SYMBOL64);
446 symbol->MaxNameLength = 512 - sizeof(IMAGEHLP_SYMBOL64);
Mikhail Glushenkov080d86f2010-10-28 08:25:44 +0000447
Michael J. Spencer44a36c82011-10-01 00:05:20 +0000448 DWORD64 dwDisp;
449 if (!SymGetSymFromAddr64(hProcess, PC, &dwDisp, symbol)) {
Mikhail Glushenkov080d86f2010-10-28 08:25:44 +0000450 fputc('\n', stderr);
451 continue;
452 }
453
454 buffer[511] = 0;
455 if (dwDisp > 0)
Michael J. Spencer44a36c82011-10-01 00:05:20 +0000456 fprintf(stderr, ", %s() + 0x%llX bytes(s)", symbol->Name, dwDisp);
Mikhail Glushenkov080d86f2010-10-28 08:25:44 +0000457 else
458 fprintf(stderr, ", %s", symbol->Name);
459
460 // Print the source file and line number information.
Michael J. Spencer44a36c82011-10-01 00:05:20 +0000461 IMAGEHLP_LINE64 line;
462 DWORD dwLineDisp;
Mikhail Glushenkov080d86f2010-10-28 08:25:44 +0000463 memset(&line, 0, sizeof(line));
464 line.SizeOfStruct = sizeof(line);
Michael J. Spencer44a36c82011-10-01 00:05:20 +0000465 if (SymGetLineFromAddr64(hProcess, PC, &dwLineDisp, &line)) {
Mikhail Glushenkov080d86f2010-10-28 08:25:44 +0000466 fprintf(stderr, ", %s, line %lu", line.FileName, line.LineNumber);
Michael J. Spencer44a36c82011-10-01 00:05:20 +0000467 if (dwLineDisp > 0)
468 fprintf(stderr, " + 0x%lX byte(s)", dwLineDisp);
Mikhail Glushenkov080d86f2010-10-28 08:25:44 +0000469 }
470
471 fputc('\n', stderr);
472 }
473
Daniel Dunbar4c7b0ca2009-09-22 09:50:28 +0000474 if (ExitOnUnhandledExceptions)
NAKAMURA Takumi64404a32011-11-29 07:47:04 +0000475 _exit(ep->ExceptionRecord->ExceptionCode);
Daniel Dunbar4c7b0ca2009-09-22 09:50:28 +0000476
Reid Spencer4aff78a2004-09-16 15:53:16 +0000477 // Allow dialog box to pop up allowing choice to start debugger.
Reid Spencer1bdd0f02004-09-19 05:37:39 +0000478 if (OldFilter)
479 return (*OldFilter)(ep);
480 else
481 return EXCEPTION_CONTINUE_SEARCH;
Reid Spencer4aff78a2004-09-16 15:53:16 +0000482}
483
484static BOOL WINAPI LLVMConsoleCtrlHandler(DWORD dwCtrlType) {
Jeff Cohen9aafa062005-08-02 03:26:32 +0000485 // We are running in our very own thread, courtesy of Windows.
Jeff Cohenba7cc682005-08-02 03:04:47 +0000486 EnterCriticalSection(&CriticalSection);
Reid Spencer4aff78a2004-09-16 15:53:16 +0000487 Cleanup();
488
Jeff Cohenba7cc682005-08-02 03:04:47 +0000489 // If an interrupt function has been set, go and run one it; otherwise,
490 // the process dies.
491 void (*IF)() = InterruptFunction;
492 InterruptFunction = 0; // Don't run it on another CTRL-C.
493
494 if (IF) {
Jeff Cohen9aafa062005-08-02 03:26:32 +0000495 // Note: if the interrupt function throws an exception, there is nothing
496 // to catch it in this thread so it will kill the process.
497 IF(); // Run it now.
Jeff Cohenba7cc682005-08-02 03:04:47 +0000498 LeaveCriticalSection(&CriticalSection);
499 return TRUE; // Don't kill the process.
500 }
501
Reid Spencer90debc52004-09-17 03:02:27 +0000502 // Allow normal processing to take place; i.e., the process dies.
Jeff Cohenba7cc682005-08-02 03:04:47 +0000503 LeaveCriticalSection(&CriticalSection);
Reid Spencer4aff78a2004-09-16 15:53:16 +0000504 return FALSE;
505}
Michael J. Spencer44a36c82011-10-01 00:05:20 +0000506
507#if __MINGW32__
508 // We turned these warnings off for this file so that MinGW-g++ doesn't
509 // complain about the ll format specifiers used. Now we are turning the
510 // warnings back on. If MinGW starts to support diagnostic stacks, we can
511 // replace this with a pop.
512 #pragma GCC diagnostic warning "-Wformat"
513 #pragma GCC diagnostic warning "-Wformat-extra-args"
514#endif