blob: 4a1a4cc074d22ddd23c261f79069b4cdb46b693e [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;
46static PTOP_LEVEL_EXCEPTION_FILTER OldFilter = NULL;
47
48// Windows creates a new thread to execute the console handler when an event
49// (such as CTRL/C) occurs. This causes concurrency issues with the above
50// globals which this critical section addresses.
51static CRITICAL_SECTION CriticalSection;
52
53namespace llvm {
54
55//===----------------------------------------------------------------------===//
56//=== WARNING: Implementation here must contain only Win32 specific code
57//=== and must not be UNIX code
58//===----------------------------------------------------------------------===//
59
60
61static void RegisterHandler() {
62 if (RegisteredUnhandledExceptionFilter) {
63 EnterCriticalSection(&CriticalSection);
64 return;
65 }
66
67 // Now's the time to create the critical section. This is the first time
68 // through here, and there's only one thread.
69 InitializeCriticalSection(&CriticalSection);
70
71 // Enter it immediately. Now if someone hits CTRL/C, the console handler
72 // can't proceed until the globals are updated.
73 EnterCriticalSection(&CriticalSection);
74
75 RegisteredUnhandledExceptionFilter = true;
76 OldFilter = SetUnhandledExceptionFilter(LLVMUnhandledExceptionFilter);
77 SetConsoleCtrlHandler(LLVMConsoleCtrlHandler, TRUE);
78
79 // IMPORTANT NOTE: Caller must call LeaveCriticalSection(&CriticalSection) or
80 // else multi-threading problems will ensue.
81}
82
83// RemoveFileOnSignal - The public API
84bool sys::RemoveFileOnSignal(const sys::Path &Filename, std::string* ErrMsg) {
85 RegisterHandler();
86
87 if (CleanupExecuted) {
88 if (ErrMsg)
89 *ErrMsg = "Process terminating -- cannot register for removal";
90 return true;
91 }
92
93 if (FilesToRemove == NULL)
94 FilesToRemove = new std::vector<sys::Path>;
95
96 FilesToRemove->push_back(Filename);
97
98 LeaveCriticalSection(&CriticalSection);
99 return false;
100}
101
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000102/// PrintStackTraceOnErrorSignal - When an error signal (such as SIBABRT or
103/// SIGSEGV) is delivered to the process, print a stack trace and then exit.
104void sys::PrintStackTraceOnErrorSignal() {
105 RegisterHandler();
106 LeaveCriticalSection(&CriticalSection);
107}
108
109
110void sys::SetInterruptFunction(void (*IF)()) {
111 RegisterHandler();
112 InterruptFunction = IF;
113 LeaveCriticalSection(&CriticalSection);
114}
Sebastian Redl2aa4c4e2009-03-19 23:26:52 +0000115
116
117/// AddSignalHandler - Add a function to be called when a signal is delivered
118/// to the process. The handler can have a cookie passed to it to identify
119/// what instance of the handler it is.
120void sys::AddSignalHandler(void (*FnPtr)(void *), void *Cookie) {
121 if (CallBacksToRun == 0)
122 CallBacksToRun = new std::vector<std::pair<void(*)(void*), void*> >();
123 CallBacksToRun->push_back(std::make_pair(FnPtr, Cookie));
124 RegisterHandler();
125}
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000126}
127
128static void Cleanup() {
129 EnterCriticalSection(&CriticalSection);
130
131 // Prevent other thread from registering new files and directories for
132 // removal, should we be executing because of the console handler callback.
133 CleanupExecuted = true;
134
135 // FIXME: open files cannot be deleted.
136
137 if (FilesToRemove != NULL)
138 while (!FilesToRemove->empty()) {
Chris Lattnerfeadf1b2009-07-09 16:17:28 +0000139 FilesToRemove->back().eraseFromDisk();
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000140 FilesToRemove->pop_back();
141 }
142
Chris Lattner199997b2009-03-04 21:21:36 +0000143 if (CallBacksToRun)
144 for (unsigned i = 0, e = CallBacksToRun->size(); i != e; ++i)
145 (*CallBacksToRun)[i].first((*CallBacksToRun)[i].second);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000146
147 LeaveCriticalSection(&CriticalSection);
148}
149
150static LONG WINAPI LLVMUnhandledExceptionFilter(LPEXCEPTION_POINTERS ep) {
151 try {
152 Cleanup();
Chuck Rose III57c33da2007-11-21 00:37:56 +0000153
154#ifdef _WIN64
155 // TODO: provide a x64 friendly version of the following
156#else
157
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000158 // Initialize the STACKFRAME structure.
159 STACKFRAME StackFrame;
160 memset(&StackFrame, 0, sizeof(StackFrame));
161
162 StackFrame.AddrPC.Offset = ep->ContextRecord->Eip;
163 StackFrame.AddrPC.Mode = AddrModeFlat;
164 StackFrame.AddrStack.Offset = ep->ContextRecord->Esp;
165 StackFrame.AddrStack.Mode = AddrModeFlat;
166 StackFrame.AddrFrame.Offset = ep->ContextRecord->Ebp;
167 StackFrame.AddrFrame.Mode = AddrModeFlat;
168
169 HANDLE hProcess = GetCurrentProcess();
170 HANDLE hThread = GetCurrentThread();
171
172 // Initialize the symbol handler.
173 SymSetOptions(SYMOPT_DEFERRED_LOADS|SYMOPT_LOAD_LINES);
174 SymInitialize(hProcess, NULL, TRUE);
175
176 while (true) {
177 if (!StackWalk(IMAGE_FILE_MACHINE_I386, hProcess, hThread, &StackFrame,
178 ep->ContextRecord, NULL, SymFunctionTableAccess,
179 SymGetModuleBase, NULL)) {
180 break;
181 }
182
183 if (StackFrame.AddrFrame.Offset == 0)
184 break;
185
186 // Print the PC in hexadecimal.
187 DWORD PC = StackFrame.AddrPC.Offset;
Anton Korobeynikov77a60b92009-04-21 16:04:56 +0000188 fprintf(stderr, "%08lX", PC);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000189
190 // Print the parameters. Assume there are four.
Anton Korobeynikov77a60b92009-04-21 16:04:56 +0000191 fprintf(stderr, " (0x%08lX 0x%08lX 0x%08lX 0x%08lX)", StackFrame.Params[0],
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000192 StackFrame.Params[1], StackFrame.Params[2], StackFrame.Params[3]);
193
194 // Verify the PC belongs to a module in this process.
195 if (!SymGetModuleBase(hProcess, PC)) {
196 fputs(" <unknown module>\n", stderr);
197 continue;
198 }
199
200 // Print the symbol name.
201 char buffer[512];
202 IMAGEHLP_SYMBOL *symbol = reinterpret_cast<IMAGEHLP_SYMBOL *>(buffer);
203 memset(symbol, 0, sizeof(IMAGEHLP_SYMBOL));
204 symbol->SizeOfStruct = sizeof(IMAGEHLP_SYMBOL);
205 symbol->MaxNameLength = 512 - sizeof(IMAGEHLP_SYMBOL);
206
207 DWORD dwDisp;
208 if (!SymGetSymFromAddr(hProcess, PC, &dwDisp, symbol)) {
209 fputc('\n', stderr);
210 continue;
211 }
212
213 buffer[511] = 0;
214 if (dwDisp > 0)
Anton Korobeynikov77a60b92009-04-21 16:04:56 +0000215 fprintf(stderr, ", %s()+%04lu bytes(s)", symbol->Name, dwDisp);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000216 else
217 fprintf(stderr, ", %s", symbol->Name);
218
219 // Print the source file and line number information.
220 IMAGEHLP_LINE line;
221 memset(&line, 0, sizeof(line));
222 line.SizeOfStruct = sizeof(line);
223 if (SymGetLineFromAddr(hProcess, PC, &dwDisp, &line)) {
Anton Korobeynikov77a60b92009-04-21 16:04:56 +0000224 fprintf(stderr, ", %s, line %lu", line.FileName, line.LineNumber);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000225 if (dwDisp > 0)
Anton Korobeynikov77a60b92009-04-21 16:04:56 +0000226 fprintf(stderr, "+%04lu byte(s)", dwDisp);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000227 }
228
229 fputc('\n', stderr);
230 }
Chuck Rose III57c33da2007-11-21 00:37:56 +0000231
232#endif
233
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000234 } catch (...) {
Chris Lattner199997b2009-03-04 21:21:36 +0000235 assert(0 && "Crashed in LLVMUnhandledExceptionFilter");
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000236 }
237
238 // Allow dialog box to pop up allowing choice to start debugger.
239 if (OldFilter)
240 return (*OldFilter)(ep);
241 else
242 return EXCEPTION_CONTINUE_SEARCH;
243}
244
245static BOOL WINAPI LLVMConsoleCtrlHandler(DWORD dwCtrlType) {
246 // We are running in our very own thread, courtesy of Windows.
247 EnterCriticalSection(&CriticalSection);
248 Cleanup();
249
250 // If an interrupt function has been set, go and run one it; otherwise,
251 // the process dies.
252 void (*IF)() = InterruptFunction;
253 InterruptFunction = 0; // Don't run it on another CTRL-C.
254
255 if (IF) {
256 // Note: if the interrupt function throws an exception, there is nothing
257 // to catch it in this thread so it will kill the process.
258 IF(); // Run it now.
259 LeaveCriticalSection(&CriticalSection);
260 return TRUE; // Don't kill the process.
261 }
262
263 // Allow normal processing to take place; i.e., the process dies.
264 LeaveCriticalSection(&CriticalSection);
265 return FALSE;
266}
267