blob: 7da0c751136714965ded07d038353ea1a3ea3a57 [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//
5// This file was developed by Jeff Cohen and is distributed under the
6// University of Illinois Open Source License. See LICENSE.TXT for details.
7//
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;
42static std::vector<llvm::sys::Path> *DirectoriesToRemove = NULL;
43static 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
101// RemoveDirectoryOnSignal - The public API
102bool sys::RemoveDirectoryOnSignal(const sys::Path& path, std::string* ErrMsg) {
103 // Not a directory?
104 WIN32_FILE_ATTRIBUTE_DATA fi;
105 if (!GetFileAttributesEx(path.c_str(), GetFileExInfoStandard, &fi)) {
106 MakeErrMsg(ErrMsg, path.toString() + ": can't get status of file");
107 return true;
108 }
109
110 if (!(fi.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)) {
111 if (ErrMsg)
112 *ErrMsg = path.toString() + ": not a directory";
113 return true;
114 }
115
116 RegisterHandler();
117
118 if (CleanupExecuted) {
119 if (ErrMsg)
120 *ErrMsg = "Process terminating -- cannot register for removal";
121 return true;
122 }
123
124 if (DirectoriesToRemove == NULL)
125 DirectoriesToRemove = new std::vector<sys::Path>;
126 DirectoriesToRemove->push_back(path);
127
128 LeaveCriticalSection(&CriticalSection);
129 return false;
130}
131
132/// PrintStackTraceOnErrorSignal - When an error signal (such as SIBABRT or
133/// SIGSEGV) is delivered to the process, print a stack trace and then exit.
134void sys::PrintStackTraceOnErrorSignal() {
135 RegisterHandler();
136 LeaveCriticalSection(&CriticalSection);
137}
138
139
140void sys::SetInterruptFunction(void (*IF)()) {
141 RegisterHandler();
142 InterruptFunction = IF;
143 LeaveCriticalSection(&CriticalSection);
144}
145}
146
147static void Cleanup() {
148 EnterCriticalSection(&CriticalSection);
149
150 // Prevent other thread from registering new files and directories for
151 // removal, should we be executing because of the console handler callback.
152 CleanupExecuted = true;
153
154 // FIXME: open files cannot be deleted.
155
156 if (FilesToRemove != NULL)
157 while (!FilesToRemove->empty()) {
158 try {
159 FilesToRemove->back().eraseFromDisk();
160 } catch (...) {
161 }
162 FilesToRemove->pop_back();
163 }
164
165 if (DirectoriesToRemove != NULL)
166 while (!DirectoriesToRemove->empty()) {
167 try {
168 DirectoriesToRemove->back().eraseFromDisk(true);
169 } catch (...) {
170 }
171 DirectoriesToRemove->pop_back();
172 }
173
174 LeaveCriticalSection(&CriticalSection);
175}
176
177static LONG WINAPI LLVMUnhandledExceptionFilter(LPEXCEPTION_POINTERS ep) {
178 try {
179 Cleanup();
180
181 // Initialize the STACKFRAME structure.
182 STACKFRAME StackFrame;
183 memset(&StackFrame, 0, sizeof(StackFrame));
184
185 StackFrame.AddrPC.Offset = ep->ContextRecord->Eip;
186 StackFrame.AddrPC.Mode = AddrModeFlat;
187 StackFrame.AddrStack.Offset = ep->ContextRecord->Esp;
188 StackFrame.AddrStack.Mode = AddrModeFlat;
189 StackFrame.AddrFrame.Offset = ep->ContextRecord->Ebp;
190 StackFrame.AddrFrame.Mode = AddrModeFlat;
191
192 HANDLE hProcess = GetCurrentProcess();
193 HANDLE hThread = GetCurrentThread();
194
195 // Initialize the symbol handler.
196 SymSetOptions(SYMOPT_DEFERRED_LOADS|SYMOPT_LOAD_LINES);
197 SymInitialize(hProcess, NULL, TRUE);
198
199 while (true) {
200 if (!StackWalk(IMAGE_FILE_MACHINE_I386, hProcess, hThread, &StackFrame,
201 ep->ContextRecord, NULL, SymFunctionTableAccess,
202 SymGetModuleBase, NULL)) {
203 break;
204 }
205
206 if (StackFrame.AddrFrame.Offset == 0)
207 break;
208
209 // Print the PC in hexadecimal.
210 DWORD PC = StackFrame.AddrPC.Offset;
211 fprintf(stderr, "%08X", PC);
212
213 // Print the parameters. Assume there are four.
214 fprintf(stderr, " (0x%08X 0x%08X 0x%08X 0x%08X)", StackFrame.Params[0],
215 StackFrame.Params[1], StackFrame.Params[2], StackFrame.Params[3]);
216
217 // Verify the PC belongs to a module in this process.
218 if (!SymGetModuleBase(hProcess, PC)) {
219 fputs(" <unknown module>\n", stderr);
220 continue;
221 }
222
223 // Print the symbol name.
224 char buffer[512];
225 IMAGEHLP_SYMBOL *symbol = reinterpret_cast<IMAGEHLP_SYMBOL *>(buffer);
226 memset(symbol, 0, sizeof(IMAGEHLP_SYMBOL));
227 symbol->SizeOfStruct = sizeof(IMAGEHLP_SYMBOL);
228 symbol->MaxNameLength = 512 - sizeof(IMAGEHLP_SYMBOL);
229
230 DWORD dwDisp;
231 if (!SymGetSymFromAddr(hProcess, PC, &dwDisp, symbol)) {
232 fputc('\n', stderr);
233 continue;
234 }
235
236 buffer[511] = 0;
237 if (dwDisp > 0)
238 fprintf(stderr, ", %s()+%04d bytes(s)", symbol->Name, dwDisp);
239 else
240 fprintf(stderr, ", %s", symbol->Name);
241
242 // Print the source file and line number information.
243 IMAGEHLP_LINE line;
244 memset(&line, 0, sizeof(line));
245 line.SizeOfStruct = sizeof(line);
246 if (SymGetLineFromAddr(hProcess, PC, &dwDisp, &line)) {
247 fprintf(stderr, ", %s, line %d", line.FileName, line.LineNumber);
248 if (dwDisp > 0)
249 fprintf(stderr, "+%04d byte(s)", dwDisp);
250 }
251
252 fputc('\n', stderr);
253 }
254 } catch (...) {
255 assert(!"Crashed in LLVMUnhandledExceptionFilter");
256 }
257
258 // Allow dialog box to pop up allowing choice to start debugger.
259 if (OldFilter)
260 return (*OldFilter)(ep);
261 else
262 return EXCEPTION_CONTINUE_SEARCH;
263}
264
265static BOOL WINAPI LLVMConsoleCtrlHandler(DWORD dwCtrlType) {
266 // We are running in our very own thread, courtesy of Windows.
267 EnterCriticalSection(&CriticalSection);
268 Cleanup();
269
270 // If an interrupt function has been set, go and run one it; otherwise,
271 // the process dies.
272 void (*IF)() = InterruptFunction;
273 InterruptFunction = 0; // Don't run it on another CTRL-C.
274
275 if (IF) {
276 // Note: if the interrupt function throws an exception, there is nothing
277 // to catch it in this thread so it will kill the process.
278 IF(); // Run it now.
279 LeaveCriticalSection(&CriticalSection);
280 return TRUE; // Don't kill the process.
281 }
282
283 // Allow normal processing to take place; i.e., the process dies.
284 LeaveCriticalSection(&CriticalSection);
285 return FALSE;
286}
287