blob: 699df769f9b992d9c9e960f8023ea6662a8b563c [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 Dunbar1e57bc82009-09-22 09:50:28 +000061/// CRTReportHook - Function called on a CRT debugging event.
62static int CRTReportHook(int ReportType, char *Message, int *Return) {
63 // Don't cause a DebugBreak() on return.
64 if (Return)
65 *Return = 0;
Dan Gohmanf17a25c2007-07-18 16:29:46 +000066
Daniel Dunbar1e57bc82009-09-22 09:50:28 +000067 switch (ReportType) {
68 default:
69 case _CRT_ASSERT:
70 fprintf(stderr, "CRT assert: %s\n", Message);
71 // FIXME: Is there a way to just crash? Perhaps throw to the unhandled
72 // exception code? Perhaps SetErrorMode() handles this.
73 _exit(3);
74 break;
75 case _CRT_ERROR:
76 fprintf(stderr, "CRT error: %s\n", Message);
77 // FIXME: Is there a way to just crash? Perhaps throw to the unhandled
78 // exception code? Perhaps SetErrorMode() handles this.
79 _exit(3);
80 break;
81 case _CRT_WARN:
82 fprintf(stderr, "CRT warn: %s\n", Message);
83 break;
84 }
85
86 // Don't call _CrtDbgReport.
87 return TRUE;
88}
89
90static void RegisterHandler() {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000091 if (RegisteredUnhandledExceptionFilter) {
92 EnterCriticalSection(&CriticalSection);
93 return;
94 }
95
96 // Now's the time to create the critical section. This is the first time
97 // through here, and there's only one thread.
98 InitializeCriticalSection(&CriticalSection);
99
100 // Enter it immediately. Now if someone hits CTRL/C, the console handler
101 // can't proceed until the globals are updated.
102 EnterCriticalSection(&CriticalSection);
103
104 RegisteredUnhandledExceptionFilter = true;
105 OldFilter = SetUnhandledExceptionFilter(LLVMUnhandledExceptionFilter);
106 SetConsoleCtrlHandler(LLVMConsoleCtrlHandler, TRUE);
107
Daniel Dunbar1e57bc82009-09-22 09:50:28 +0000108 // Environment variable to disable any kind of crash dialog.
109 if (getenv("LLVM_DISABLE_CRT_DEBUG")) {
110 _CrtSetReportHook(CRTReportHook);
111 ExitOnUnhandledExceptions = true;
112 }
113
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000114 // IMPORTANT NOTE: Caller must call LeaveCriticalSection(&CriticalSection) or
115 // else multi-threading problems will ensue.
116}
117
118// RemoveFileOnSignal - The public API
119bool sys::RemoveFileOnSignal(const sys::Path &Filename, std::string* ErrMsg) {
120 RegisterHandler();
121
122 if (CleanupExecuted) {
123 if (ErrMsg)
124 *ErrMsg = "Process terminating -- cannot register for removal";
125 return true;
126 }
127
128 if (FilesToRemove == NULL)
129 FilesToRemove = new std::vector<sys::Path>;
130
131 FilesToRemove->push_back(Filename);
132
133 LeaveCriticalSection(&CriticalSection);
134 return false;
135}
136
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000137/// PrintStackTraceOnErrorSignal - When an error signal (such as SIBABRT or
138/// SIGSEGV) is delivered to the process, print a stack trace and then exit.
139void sys::PrintStackTraceOnErrorSignal() {
140 RegisterHandler();
141 LeaveCriticalSection(&CriticalSection);
142}
143
144
145void sys::SetInterruptFunction(void (*IF)()) {
146 RegisterHandler();
147 InterruptFunction = IF;
148 LeaveCriticalSection(&CriticalSection);
149}
Sebastian Redl2aa4c4e2009-03-19 23:26:52 +0000150
151
152/// AddSignalHandler - Add a function to be called when a signal is delivered
153/// to the process. The handler can have a cookie passed to it to identify
154/// what instance of the handler it is.
155void sys::AddSignalHandler(void (*FnPtr)(void *), void *Cookie) {
156 if (CallBacksToRun == 0)
157 CallBacksToRun = new std::vector<std::pair<void(*)(void*), void*> >();
158 CallBacksToRun->push_back(std::make_pair(FnPtr, Cookie));
159 RegisterHandler();
160}
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000161}
162
163static void Cleanup() {
164 EnterCriticalSection(&CriticalSection);
165
166 // Prevent other thread from registering new files and directories for
167 // removal, should we be executing because of the console handler callback.
168 CleanupExecuted = true;
169
170 // FIXME: open files cannot be deleted.
171
172 if (FilesToRemove != NULL)
173 while (!FilesToRemove->empty()) {
Chris Lattnerfeadf1b2009-07-09 16:17:28 +0000174 FilesToRemove->back().eraseFromDisk();
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000175 FilesToRemove->pop_back();
176 }
177
Chris Lattner199997b2009-03-04 21:21:36 +0000178 if (CallBacksToRun)
179 for (unsigned i = 0, e = CallBacksToRun->size(); i != e; ++i)
180 (*CallBacksToRun)[i].first((*CallBacksToRun)[i].second);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000181
182 LeaveCriticalSection(&CriticalSection);
183}
184
185static LONG WINAPI LLVMUnhandledExceptionFilter(LPEXCEPTION_POINTERS ep) {
186 try {
187 Cleanup();
Chuck Rose III57c33da2007-11-21 00:37:56 +0000188
189#ifdef _WIN64
190 // TODO: provide a x64 friendly version of the following
191#else
192
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000193 // Initialize the STACKFRAME structure.
194 STACKFRAME StackFrame;
195 memset(&StackFrame, 0, sizeof(StackFrame));
196
197 StackFrame.AddrPC.Offset = ep->ContextRecord->Eip;
198 StackFrame.AddrPC.Mode = AddrModeFlat;
199 StackFrame.AddrStack.Offset = ep->ContextRecord->Esp;
200 StackFrame.AddrStack.Mode = AddrModeFlat;
201 StackFrame.AddrFrame.Offset = ep->ContextRecord->Ebp;
202 StackFrame.AddrFrame.Mode = AddrModeFlat;
203
204 HANDLE hProcess = GetCurrentProcess();
205 HANDLE hThread = GetCurrentThread();
206
207 // Initialize the symbol handler.
208 SymSetOptions(SYMOPT_DEFERRED_LOADS|SYMOPT_LOAD_LINES);
209 SymInitialize(hProcess, NULL, TRUE);
210
211 while (true) {
212 if (!StackWalk(IMAGE_FILE_MACHINE_I386, hProcess, hThread, &StackFrame,
213 ep->ContextRecord, NULL, SymFunctionTableAccess,
214 SymGetModuleBase, NULL)) {
215 break;
216 }
217
218 if (StackFrame.AddrFrame.Offset == 0)
219 break;
220
221 // Print the PC in hexadecimal.
222 DWORD PC = StackFrame.AddrPC.Offset;
Anton Korobeynikov77a60b92009-04-21 16:04:56 +0000223 fprintf(stderr, "%08lX", PC);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000224
225 // Print the parameters. Assume there are four.
Anton Korobeynikov77a60b92009-04-21 16:04:56 +0000226 fprintf(stderr, " (0x%08lX 0x%08lX 0x%08lX 0x%08lX)", StackFrame.Params[0],
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000227 StackFrame.Params[1], StackFrame.Params[2], StackFrame.Params[3]);
228
229 // Verify the PC belongs to a module in this process.
230 if (!SymGetModuleBase(hProcess, PC)) {
231 fputs(" <unknown module>\n", stderr);
232 continue;
233 }
234
235 // Print the symbol name.
236 char buffer[512];
237 IMAGEHLP_SYMBOL *symbol = reinterpret_cast<IMAGEHLP_SYMBOL *>(buffer);
238 memset(symbol, 0, sizeof(IMAGEHLP_SYMBOL));
239 symbol->SizeOfStruct = sizeof(IMAGEHLP_SYMBOL);
240 symbol->MaxNameLength = 512 - sizeof(IMAGEHLP_SYMBOL);
241
242 DWORD dwDisp;
243 if (!SymGetSymFromAddr(hProcess, PC, &dwDisp, symbol)) {
244 fputc('\n', stderr);
245 continue;
246 }
247
248 buffer[511] = 0;
249 if (dwDisp > 0)
Anton Korobeynikov77a60b92009-04-21 16:04:56 +0000250 fprintf(stderr, ", %s()+%04lu bytes(s)", symbol->Name, dwDisp);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000251 else
252 fprintf(stderr, ", %s", symbol->Name);
253
254 // Print the source file and line number information.
255 IMAGEHLP_LINE line;
256 memset(&line, 0, sizeof(line));
257 line.SizeOfStruct = sizeof(line);
258 if (SymGetLineFromAddr(hProcess, PC, &dwDisp, &line)) {
Anton Korobeynikov77a60b92009-04-21 16:04:56 +0000259 fprintf(stderr, ", %s, line %lu", line.FileName, line.LineNumber);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000260 if (dwDisp > 0)
Anton Korobeynikov77a60b92009-04-21 16:04:56 +0000261 fprintf(stderr, "+%04lu byte(s)", dwDisp);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000262 }
263
264 fputc('\n', stderr);
265 }
Chuck Rose III57c33da2007-11-21 00:37:56 +0000266
267#endif
268
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000269 } catch (...) {
Chris Lattner199997b2009-03-04 21:21:36 +0000270 assert(0 && "Crashed in LLVMUnhandledExceptionFilter");
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000271 }
272
Daniel Dunbar1e57bc82009-09-22 09:50:28 +0000273 if (ExitOnUnhandledExceptions)
274 _exit(-3);
275
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000276 // Allow dialog box to pop up allowing choice to start debugger.
277 if (OldFilter)
278 return (*OldFilter)(ep);
279 else
280 return EXCEPTION_CONTINUE_SEARCH;
281}
282
283static BOOL WINAPI LLVMConsoleCtrlHandler(DWORD dwCtrlType) {
284 // We are running in our very own thread, courtesy of Windows.
285 EnterCriticalSection(&CriticalSection);
286 Cleanup();
287
288 // If an interrupt function has been set, go and run one it; otherwise,
289 // the process dies.
290 void (*IF)() = InterruptFunction;
291 InterruptFunction = 0; // Don't run it on another CTRL-C.
292
293 if (IF) {
294 // Note: if the interrupt function throws an exception, there is nothing
295 // to catch it in this thread so it will kill the process.
296 IF(); // Run it now.
297 LeaveCriticalSection(&CriticalSection);
298 return TRUE; // Don't kill the process.
299 }
300
301 // Allow normal processing to take place; i.e., the process dies.
302 LeaveCriticalSection(&CriticalSection);
303 return FALSE;
304}
305