blob: dba22185ac7f0b44feeb46fdfa5cdcfc2625452b [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 Dunbarf54515d2009-09-22 16:10:35 +000046#ifdef _MSC_VER
Daniel Dunbar1e57bc82009-09-22 09:50:28 +000047static bool ExitOnUnhandledExceptions = false;
Daniel Dunbarf54515d2009-09-22 16:10:35 +000048#endif
Dan Gohmanf17a25c2007-07-18 16:29:46 +000049static PTOP_LEVEL_EXCEPTION_FILTER OldFilter = NULL;
50
51// Windows creates a new thread to execute the console handler when an event
52// (such as CTRL/C) occurs. This causes concurrency issues with the above
53// globals which this critical section addresses.
54static CRITICAL_SECTION CriticalSection;
55
56namespace llvm {
57
58//===----------------------------------------------------------------------===//
59//=== WARNING: Implementation here must contain only Win32 specific code
60//=== and must not be UNIX code
61//===----------------------------------------------------------------------===//
62
Daniel Dunbar441722f2009-09-22 15:58:35 +000063#ifdef _MSC_VER
Daniel Dunbar1e57bc82009-09-22 09:50:28 +000064/// CRTReportHook - Function called on a CRT debugging event.
65static int CRTReportHook(int ReportType, char *Message, int *Return) {
66 // Don't cause a DebugBreak() on return.
67 if (Return)
68 *Return = 0;
Dan Gohmanf17a25c2007-07-18 16:29:46 +000069
Daniel Dunbar1e57bc82009-09-22 09:50:28 +000070 switch (ReportType) {
71 default:
72 case _CRT_ASSERT:
73 fprintf(stderr, "CRT assert: %s\n", Message);
74 // FIXME: Is there a way to just crash? Perhaps throw to the unhandled
75 // exception code? Perhaps SetErrorMode() handles this.
76 _exit(3);
77 break;
78 case _CRT_ERROR:
79 fprintf(stderr, "CRT error: %s\n", Message);
80 // FIXME: Is there a way to just crash? Perhaps throw to the unhandled
81 // exception code? Perhaps SetErrorMode() handles this.
82 _exit(3);
83 break;
84 case _CRT_WARN:
85 fprintf(stderr, "CRT warn: %s\n", Message);
86 break;
87 }
88
89 // Don't call _CrtDbgReport.
90 return TRUE;
91}
Daniel Dunbar441722f2009-09-22 15:58:35 +000092#endif
Daniel Dunbar1e57bc82009-09-22 09:50:28 +000093
94static void RegisterHandler() {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000095 if (RegisteredUnhandledExceptionFilter) {
96 EnterCriticalSection(&CriticalSection);
97 return;
98 }
99
100 // Now's the time to create the critical section. This is the first time
101 // through here, and there's only one thread.
102 InitializeCriticalSection(&CriticalSection);
103
104 // Enter it immediately. Now if someone hits CTRL/C, the console handler
105 // can't proceed until the globals are updated.
106 EnterCriticalSection(&CriticalSection);
107
108 RegisteredUnhandledExceptionFilter = true;
109 OldFilter = SetUnhandledExceptionFilter(LLVMUnhandledExceptionFilter);
110 SetConsoleCtrlHandler(LLVMConsoleCtrlHandler, TRUE);
111
Daniel Dunbar1e57bc82009-09-22 09:50:28 +0000112 // Environment variable to disable any kind of crash dialog.
Daniel Dunbar441722f2009-09-22 15:58:35 +0000113#ifdef _MSC_VER
Daniel Dunbar1e57bc82009-09-22 09:50:28 +0000114 if (getenv("LLVM_DISABLE_CRT_DEBUG")) {
115 _CrtSetReportHook(CRTReportHook);
Daniel Dunbar441722f2009-09-22 15:58:35 +0000116 ExitOnUnhandledExceptions = true;
Daniel Dunbar1e57bc82009-09-22 09:50:28 +0000117 }
Daniel Dunbar441722f2009-09-22 15:58:35 +0000118#endif
Daniel Dunbar1e57bc82009-09-22 09:50:28 +0000119
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000120 // IMPORTANT NOTE: Caller must call LeaveCriticalSection(&CriticalSection) or
121 // else multi-threading problems will ensue.
122}
123
124// RemoveFileOnSignal - The public API
125bool sys::RemoveFileOnSignal(const sys::Path &Filename, std::string* ErrMsg) {
126 RegisterHandler();
127
128 if (CleanupExecuted) {
129 if (ErrMsg)
130 *ErrMsg = "Process terminating -- cannot register for removal";
131 return true;
132 }
133
134 if (FilesToRemove == NULL)
135 FilesToRemove = new std::vector<sys::Path>;
136
137 FilesToRemove->push_back(Filename);
138
139 LeaveCriticalSection(&CriticalSection);
140 return false;
141}
142
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000143/// PrintStackTraceOnErrorSignal - When an error signal (such as SIBABRT or
144/// SIGSEGV) is delivered to the process, print a stack trace and then exit.
145void sys::PrintStackTraceOnErrorSignal() {
146 RegisterHandler();
147 LeaveCriticalSection(&CriticalSection);
148}
149
150
151void sys::SetInterruptFunction(void (*IF)()) {
152 RegisterHandler();
153 InterruptFunction = IF;
154 LeaveCriticalSection(&CriticalSection);
155}
Sebastian Redl2aa4c4e2009-03-19 23:26:52 +0000156
157
158/// AddSignalHandler - Add a function to be called when a signal is delivered
159/// to the process. The handler can have a cookie passed to it to identify
160/// what instance of the handler it is.
161void sys::AddSignalHandler(void (*FnPtr)(void *), void *Cookie) {
162 if (CallBacksToRun == 0)
163 CallBacksToRun = new std::vector<std::pair<void(*)(void*), void*> >();
164 CallBacksToRun->push_back(std::make_pair(FnPtr, Cookie));
165 RegisterHandler();
166}
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000167}
168
169static void Cleanup() {
170 EnterCriticalSection(&CriticalSection);
171
172 // Prevent other thread from registering new files and directories for
173 // removal, should we be executing because of the console handler callback.
174 CleanupExecuted = true;
175
176 // FIXME: open files cannot be deleted.
177
178 if (FilesToRemove != NULL)
179 while (!FilesToRemove->empty()) {
Chris Lattnerfeadf1b2009-07-09 16:17:28 +0000180 FilesToRemove->back().eraseFromDisk();
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000181 FilesToRemove->pop_back();
182 }
183
Chris Lattner199997b2009-03-04 21:21:36 +0000184 if (CallBacksToRun)
185 for (unsigned i = 0, e = CallBacksToRun->size(); i != e; ++i)
186 (*CallBacksToRun)[i].first((*CallBacksToRun)[i].second);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000187
188 LeaveCriticalSection(&CriticalSection);
189}
190
191static LONG WINAPI LLVMUnhandledExceptionFilter(LPEXCEPTION_POINTERS ep) {
192 try {
193 Cleanup();
Chuck Rose III57c33da2007-11-21 00:37:56 +0000194
195#ifdef _WIN64
196 // TODO: provide a x64 friendly version of the following
197#else
198
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000199 // Initialize the STACKFRAME structure.
200 STACKFRAME StackFrame;
201 memset(&StackFrame, 0, sizeof(StackFrame));
202
203 StackFrame.AddrPC.Offset = ep->ContextRecord->Eip;
204 StackFrame.AddrPC.Mode = AddrModeFlat;
205 StackFrame.AddrStack.Offset = ep->ContextRecord->Esp;
206 StackFrame.AddrStack.Mode = AddrModeFlat;
207 StackFrame.AddrFrame.Offset = ep->ContextRecord->Ebp;
208 StackFrame.AddrFrame.Mode = AddrModeFlat;
209
210 HANDLE hProcess = GetCurrentProcess();
211 HANDLE hThread = GetCurrentThread();
212
213 // Initialize the symbol handler.
214 SymSetOptions(SYMOPT_DEFERRED_LOADS|SYMOPT_LOAD_LINES);
215 SymInitialize(hProcess, NULL, TRUE);
216
217 while (true) {
218 if (!StackWalk(IMAGE_FILE_MACHINE_I386, hProcess, hThread, &StackFrame,
219 ep->ContextRecord, NULL, SymFunctionTableAccess,
220 SymGetModuleBase, NULL)) {
221 break;
222 }
223
224 if (StackFrame.AddrFrame.Offset == 0)
225 break;
226
227 // Print the PC in hexadecimal.
228 DWORD PC = StackFrame.AddrPC.Offset;
Anton Korobeynikov77a60b92009-04-21 16:04:56 +0000229 fprintf(stderr, "%08lX", PC);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000230
231 // Print the parameters. Assume there are four.
Anton Korobeynikov77a60b92009-04-21 16:04:56 +0000232 fprintf(stderr, " (0x%08lX 0x%08lX 0x%08lX 0x%08lX)", StackFrame.Params[0],
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000233 StackFrame.Params[1], StackFrame.Params[2], StackFrame.Params[3]);
234
235 // Verify the PC belongs to a module in this process.
236 if (!SymGetModuleBase(hProcess, PC)) {
237 fputs(" <unknown module>\n", stderr);
238 continue;
239 }
240
241 // Print the symbol name.
242 char buffer[512];
243 IMAGEHLP_SYMBOL *symbol = reinterpret_cast<IMAGEHLP_SYMBOL *>(buffer);
244 memset(symbol, 0, sizeof(IMAGEHLP_SYMBOL));
245 symbol->SizeOfStruct = sizeof(IMAGEHLP_SYMBOL);
246 symbol->MaxNameLength = 512 - sizeof(IMAGEHLP_SYMBOL);
247
248 DWORD dwDisp;
249 if (!SymGetSymFromAddr(hProcess, PC, &dwDisp, symbol)) {
250 fputc('\n', stderr);
251 continue;
252 }
253
254 buffer[511] = 0;
255 if (dwDisp > 0)
Anton Korobeynikov77a60b92009-04-21 16:04:56 +0000256 fprintf(stderr, ", %s()+%04lu bytes(s)", symbol->Name, dwDisp);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000257 else
258 fprintf(stderr, ", %s", symbol->Name);
259
260 // Print the source file and line number information.
261 IMAGEHLP_LINE line;
262 memset(&line, 0, sizeof(line));
263 line.SizeOfStruct = sizeof(line);
264 if (SymGetLineFromAddr(hProcess, PC, &dwDisp, &line)) {
Anton Korobeynikov77a60b92009-04-21 16:04:56 +0000265 fprintf(stderr, ", %s, line %lu", line.FileName, line.LineNumber);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000266 if (dwDisp > 0)
Anton Korobeynikov77a60b92009-04-21 16:04:56 +0000267 fprintf(stderr, "+%04lu byte(s)", dwDisp);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000268 }
269
270 fputc('\n', stderr);
271 }
Chuck Rose III57c33da2007-11-21 00:37:56 +0000272
273#endif
274
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000275 } catch (...) {
Chris Lattner199997b2009-03-04 21:21:36 +0000276 assert(0 && "Crashed in LLVMUnhandledExceptionFilter");
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000277 }
278
Daniel Dunbar441722f2009-09-22 15:58:35 +0000279#ifdef _MSC_VER
Daniel Dunbar1e57bc82009-09-22 09:50:28 +0000280 if (ExitOnUnhandledExceptions)
281 _exit(-3);
Daniel Dunbar441722f2009-09-22 15:58:35 +0000282#endif
Daniel Dunbar1e57bc82009-09-22 09:50:28 +0000283
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000284 // Allow dialog box to pop up allowing choice to start debugger.
285 if (OldFilter)
286 return (*OldFilter)(ep);
287 else
288 return EXCEPTION_CONTINUE_SEARCH;
289}
290
291static BOOL WINAPI LLVMConsoleCtrlHandler(DWORD dwCtrlType) {
292 // We are running in our very own thread, courtesy of Windows.
293 EnterCriticalSection(&CriticalSection);
294 Cleanup();
295
296 // If an interrupt function has been set, go and run one it; otherwise,
297 // the process dies.
298 void (*IF)() = InterruptFunction;
299 InterruptFunction = 0; // Don't run it on another CTRL-C.
300
301 if (IF) {
302 // Note: if the interrupt function throws an exception, there is nothing
303 // to catch it in this thread so it will kill the process.
304 IF(); // Run it now.
305 LeaveCriticalSection(&CriticalSection);
306 return TRUE; // Don't kill the process.
307 }
308
309 // Allow normal processing to take place; i.e., the process dies.
310 LeaveCriticalSection(&CriticalSection);
311 return FALSE;
312}
313