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