blob: ca43bbf5972a627680c20e4c8f629f91b1fa9e84 [file] [log] [blame]
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001//===- Win32/Signals.cpp - Win32 Signals Implementation ---------*- C++ -*-===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner081ce942007-12-29 20:36:04 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This file provides the Win32 specific implementation of the Signals class.
11//
12//===----------------------------------------------------------------------===//
13
14#include "Win32.h"
15#include <stdio.h>
16#include <vector>
Sebastian Redl2aa4c4e2009-03-19 23:26:52 +000017#include <algorithm>
Dan Gohmanf17a25c2007-07-18 16:29:46 +000018
19#ifdef __MINGW32__
20 #include <imagehlp.h>
21#else
22 #include <dbghelp.h>
23#endif
24#include <psapi.h>
25
26#ifdef __MINGW32__
27 #if ((HAVE_LIBIMAGEHLP != 1) || (HAVE_LIBPSAPI != 1))
28 #error "libimagehlp.a & libpsapi.a should be present"
29 #endif
30#else
31 #pragma comment(lib, "psapi.lib")
32 #pragma comment(lib, "dbghelp.lib")
33#endif
34
35// Forward declare.
36static LONG WINAPI LLVMUnhandledExceptionFilter(LPEXCEPTION_POINTERS ep);
37static BOOL WINAPI LLVMConsoleCtrlHandler(DWORD dwCtrlType);
38
39// InterruptFunction - The function to call if ctrl-c is pressed.
40static void (*InterruptFunction)() = 0;
41
42static std::vector<llvm::sys::Path> *FilesToRemove = NULL;
Chris Lattner199997b2009-03-04 21:21:36 +000043static std::vector<std::pair<void(*)(void*), void*> > *CallBacksToRun = 0;
Dan Gohmanf17a25c2007-07-18 16:29:46 +000044static bool RegisteredUnhandledExceptionFilter = false;
45static bool CleanupExecuted = false;
Daniel Dunbar1e57bc82009-09-22 09:50:28 +000046static bool ExitOnUnhandledExceptions = false;
Dan Gohmanf17a25c2007-07-18 16:29:46 +000047static PTOP_LEVEL_EXCEPTION_FILTER OldFilter = NULL;
48
49// Windows creates a new thread to execute the console handler when an event
50// (such as CTRL/C) occurs. This causes concurrency issues with the above
51// globals which this critical section addresses.
52static CRITICAL_SECTION CriticalSection;
53
54namespace llvm {
55
56//===----------------------------------------------------------------------===//
57//=== WARNING: Implementation here must contain only Win32 specific code
58//=== and must not be UNIX code
59//===----------------------------------------------------------------------===//
60
Daniel Dunbar441722f2009-09-22 15:58:35 +000061#ifdef _MSC_VER
Daniel Dunbar1e57bc82009-09-22 09:50:28 +000062/// CRTReportHook - Function called on a CRT debugging event.
63static int CRTReportHook(int ReportType, char *Message, int *Return) {
64 // Don't cause a DebugBreak() on return.
65 if (Return)
66 *Return = 0;
Dan Gohmanf17a25c2007-07-18 16:29:46 +000067
Daniel Dunbar1e57bc82009-09-22 09:50:28 +000068 switch (ReportType) {
69 default:
70 case _CRT_ASSERT:
71 fprintf(stderr, "CRT assert: %s\n", Message);
72 // FIXME: Is there a way to just crash? Perhaps throw to the unhandled
73 // exception code? Perhaps SetErrorMode() handles this.
74 _exit(3);
75 break;
76 case _CRT_ERROR:
77 fprintf(stderr, "CRT error: %s\n", Message);
78 // FIXME: Is there a way to just crash? Perhaps throw to the unhandled
79 // exception code? Perhaps SetErrorMode() handles this.
80 _exit(3);
81 break;
82 case _CRT_WARN:
83 fprintf(stderr, "CRT warn: %s\n", Message);
84 break;
85 }
86
87 // Don't call _CrtDbgReport.
88 return TRUE;
89}
Daniel Dunbar441722f2009-09-22 15:58:35 +000090#endif
Daniel Dunbar1e57bc82009-09-22 09:50:28 +000091
92static void RegisterHandler() {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000093 if (RegisteredUnhandledExceptionFilter) {
94 EnterCriticalSection(&CriticalSection);
95 return;
96 }
97
98 // Now's the time to create the critical section. This is the first time
99 // through here, and there's only one thread.
100 InitializeCriticalSection(&CriticalSection);
101
102 // Enter it immediately. Now if someone hits CTRL/C, the console handler
103 // can't proceed until the globals are updated.
104 EnterCriticalSection(&CriticalSection);
105
106 RegisteredUnhandledExceptionFilter = true;
107 OldFilter = SetUnhandledExceptionFilter(LLVMUnhandledExceptionFilter);
108 SetConsoleCtrlHandler(LLVMConsoleCtrlHandler, TRUE);
109
Daniel Dunbar1e57bc82009-09-22 09:50:28 +0000110 // Environment variable to disable any kind of crash dialog.
Daniel Dunbar441722f2009-09-22 15:58:35 +0000111#ifdef _MSC_VER
Daniel Dunbar1e57bc82009-09-22 09:50:28 +0000112 if (getenv("LLVM_DISABLE_CRT_DEBUG")) {
113 _CrtSetReportHook(CRTReportHook);
Daniel Dunbar441722f2009-09-22 15:58:35 +0000114 ExitOnUnhandledExceptions = true;
Daniel Dunbar1e57bc82009-09-22 09:50:28 +0000115 }
Daniel Dunbar441722f2009-09-22 15:58:35 +0000116#endif
Daniel Dunbar1e57bc82009-09-22 09:50:28 +0000117
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000118 // IMPORTANT NOTE: Caller must call LeaveCriticalSection(&CriticalSection) or
119 // else multi-threading problems will ensue.
120}
121
122// RemoveFileOnSignal - The public API
123bool sys::RemoveFileOnSignal(const sys::Path &Filename, std::string* ErrMsg) {
124 RegisterHandler();
125
126 if (CleanupExecuted) {
127 if (ErrMsg)
128 *ErrMsg = "Process terminating -- cannot register for removal";
129 return true;
130 }
131
132 if (FilesToRemove == NULL)
133 FilesToRemove = new std::vector<sys::Path>;
134
135 FilesToRemove->push_back(Filename);
136
137 LeaveCriticalSection(&CriticalSection);
138 return false;
139}
140
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000141/// PrintStackTraceOnErrorSignal - When an error signal (such as SIBABRT or
142/// SIGSEGV) is delivered to the process, print a stack trace and then exit.
143void sys::PrintStackTraceOnErrorSignal() {
144 RegisterHandler();
145 LeaveCriticalSection(&CriticalSection);
146}
147
148
149void sys::SetInterruptFunction(void (*IF)()) {
150 RegisterHandler();
151 InterruptFunction = IF;
152 LeaveCriticalSection(&CriticalSection);
153}
Sebastian Redl2aa4c4e2009-03-19 23:26:52 +0000154
155
156/// AddSignalHandler - Add a function to be called when a signal is delivered
157/// to the process. The handler can have a cookie passed to it to identify
158/// what instance of the handler it is.
159void sys::AddSignalHandler(void (*FnPtr)(void *), void *Cookie) {
160 if (CallBacksToRun == 0)
161 CallBacksToRun = new std::vector<std::pair<void(*)(void*), void*> >();
162 CallBacksToRun->push_back(std::make_pair(FnPtr, Cookie));
163 RegisterHandler();
164}
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000165}
166
167static void Cleanup() {
168 EnterCriticalSection(&CriticalSection);
169
170 // Prevent other thread from registering new files and directories for
171 // removal, should we be executing because of the console handler callback.
172 CleanupExecuted = true;
173
174 // FIXME: open files cannot be deleted.
175
176 if (FilesToRemove != NULL)
177 while (!FilesToRemove->empty()) {
Chris Lattnerfeadf1b2009-07-09 16:17:28 +0000178 FilesToRemove->back().eraseFromDisk();
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000179 FilesToRemove->pop_back();
180 }
181
Chris Lattner199997b2009-03-04 21:21:36 +0000182 if (CallBacksToRun)
183 for (unsigned i = 0, e = CallBacksToRun->size(); i != e; ++i)
184 (*CallBacksToRun)[i].first((*CallBacksToRun)[i].second);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000185
186 LeaveCriticalSection(&CriticalSection);
187}
188
189static LONG WINAPI LLVMUnhandledExceptionFilter(LPEXCEPTION_POINTERS ep) {
190 try {
191 Cleanup();
Chuck Rose III57c33da2007-11-21 00:37:56 +0000192
193#ifdef _WIN64
194 // TODO: provide a x64 friendly version of the following
195#else
196
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000197 // Initialize the STACKFRAME structure.
198 STACKFRAME StackFrame;
199 memset(&StackFrame, 0, sizeof(StackFrame));
200
201 StackFrame.AddrPC.Offset = ep->ContextRecord->Eip;
202 StackFrame.AddrPC.Mode = AddrModeFlat;
203 StackFrame.AddrStack.Offset = ep->ContextRecord->Esp;
204 StackFrame.AddrStack.Mode = AddrModeFlat;
205 StackFrame.AddrFrame.Offset = ep->ContextRecord->Ebp;
206 StackFrame.AddrFrame.Mode = AddrModeFlat;
207
208 HANDLE hProcess = GetCurrentProcess();
209 HANDLE hThread = GetCurrentThread();
210
211 // Initialize the symbol handler.
212 SymSetOptions(SYMOPT_DEFERRED_LOADS|SYMOPT_LOAD_LINES);
213 SymInitialize(hProcess, NULL, TRUE);
214
215 while (true) {
216 if (!StackWalk(IMAGE_FILE_MACHINE_I386, hProcess, hThread, &StackFrame,
217 ep->ContextRecord, NULL, SymFunctionTableAccess,
218 SymGetModuleBase, NULL)) {
219 break;
220 }
221
222 if (StackFrame.AddrFrame.Offset == 0)
223 break;
224
225 // Print the PC in hexadecimal.
226 DWORD PC = StackFrame.AddrPC.Offset;
Anton Korobeynikov77a60b92009-04-21 16:04:56 +0000227 fprintf(stderr, "%08lX", PC);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000228
229 // Print the parameters. Assume there are four.
Anton Korobeynikov77a60b92009-04-21 16:04:56 +0000230 fprintf(stderr, " (0x%08lX 0x%08lX 0x%08lX 0x%08lX)", StackFrame.Params[0],
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000231 StackFrame.Params[1], StackFrame.Params[2], StackFrame.Params[3]);
232
233 // Verify the PC belongs to a module in this process.
234 if (!SymGetModuleBase(hProcess, PC)) {
235 fputs(" <unknown module>\n", stderr);
236 continue;
237 }
238
239 // Print the symbol name.
240 char buffer[512];
241 IMAGEHLP_SYMBOL *symbol = reinterpret_cast<IMAGEHLP_SYMBOL *>(buffer);
242 memset(symbol, 0, sizeof(IMAGEHLP_SYMBOL));
243 symbol->SizeOfStruct = sizeof(IMAGEHLP_SYMBOL);
244 symbol->MaxNameLength = 512 - sizeof(IMAGEHLP_SYMBOL);
245
246 DWORD dwDisp;
247 if (!SymGetSymFromAddr(hProcess, PC, &dwDisp, symbol)) {
248 fputc('\n', stderr);
249 continue;
250 }
251
252 buffer[511] = 0;
253 if (dwDisp > 0)
Anton Korobeynikov77a60b92009-04-21 16:04:56 +0000254 fprintf(stderr, ", %s()+%04lu bytes(s)", symbol->Name, dwDisp);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000255 else
256 fprintf(stderr, ", %s", symbol->Name);
257
258 // Print the source file and line number information.
259 IMAGEHLP_LINE line;
260 memset(&line, 0, sizeof(line));
261 line.SizeOfStruct = sizeof(line);
262 if (SymGetLineFromAddr(hProcess, PC, &dwDisp, &line)) {
Anton Korobeynikov77a60b92009-04-21 16:04:56 +0000263 fprintf(stderr, ", %s, line %lu", line.FileName, line.LineNumber);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000264 if (dwDisp > 0)
Anton Korobeynikov77a60b92009-04-21 16:04:56 +0000265 fprintf(stderr, "+%04lu byte(s)", dwDisp);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000266 }
267
268 fputc('\n', stderr);
269 }
Chuck Rose III57c33da2007-11-21 00:37:56 +0000270
271#endif
272
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000273 } catch (...) {
Chris Lattner199997b2009-03-04 21:21:36 +0000274 assert(0 && "Crashed in LLVMUnhandledExceptionFilter");
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000275 }
276
Daniel Dunbar441722f2009-09-22 15:58:35 +0000277#ifdef _MSC_VER
Daniel Dunbar1e57bc82009-09-22 09:50:28 +0000278 if (ExitOnUnhandledExceptions)
279 _exit(-3);
Daniel Dunbar441722f2009-09-22 15:58:35 +0000280#endif
Daniel Dunbar1e57bc82009-09-22 09:50:28 +0000281
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000282 // Allow dialog box to pop up allowing choice to start debugger.
283 if (OldFilter)
284 return (*OldFilter)(ep);
285 else
286 return EXCEPTION_CONTINUE_SEARCH;
287}
288
289static BOOL WINAPI LLVMConsoleCtrlHandler(DWORD dwCtrlType) {
290 // We are running in our very own thread, courtesy of Windows.
291 EnterCriticalSection(&CriticalSection);
292 Cleanup();
293
294 // If an interrupt function has been set, go and run one it; otherwise,
295 // the process dies.
296 void (*IF)() = InterruptFunction;
297 InterruptFunction = 0; // Don't run it on another CTRL-C.
298
299 if (IF) {
300 // Note: if the interrupt function throws an exception, there is nothing
301 // to catch it in this thread so it will kill the process.
302 IF(); // Run it now.
303 LeaveCriticalSection(&CriticalSection);
304 return TRUE; // Don't kill the process.
305 }
306
307 // Allow normal processing to take place; i.e., the process dies.
308 LeaveCriticalSection(&CriticalSection);
309 return FALSE;
310}
311