blob: 3a8f77e3cdb9d8a97503c71f0f0da0b1ef1a1998 [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()) {
139 try {
140 FilesToRemove->back().eraseFromDisk();
141 } catch (...) {
142 }
143 FilesToRemove->pop_back();
144 }
145
Chris Lattner199997b2009-03-04 21:21:36 +0000146 if (CallBacksToRun)
147 for (unsigned i = 0, e = CallBacksToRun->size(); i != e; ++i)
148 (*CallBacksToRun)[i].first((*CallBacksToRun)[i].second);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000149
150 LeaveCriticalSection(&CriticalSection);
151}
152
153static LONG WINAPI LLVMUnhandledExceptionFilter(LPEXCEPTION_POINTERS ep) {
154 try {
155 Cleanup();
Chuck Rose III57c33da2007-11-21 00:37:56 +0000156
157#ifdef _WIN64
158 // TODO: provide a x64 friendly version of the following
159#else
160
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000161 // Initialize the STACKFRAME structure.
162 STACKFRAME StackFrame;
163 memset(&StackFrame, 0, sizeof(StackFrame));
164
165 StackFrame.AddrPC.Offset = ep->ContextRecord->Eip;
166 StackFrame.AddrPC.Mode = AddrModeFlat;
167 StackFrame.AddrStack.Offset = ep->ContextRecord->Esp;
168 StackFrame.AddrStack.Mode = AddrModeFlat;
169 StackFrame.AddrFrame.Offset = ep->ContextRecord->Ebp;
170 StackFrame.AddrFrame.Mode = AddrModeFlat;
171
172 HANDLE hProcess = GetCurrentProcess();
173 HANDLE hThread = GetCurrentThread();
174
175 // Initialize the symbol handler.
176 SymSetOptions(SYMOPT_DEFERRED_LOADS|SYMOPT_LOAD_LINES);
177 SymInitialize(hProcess, NULL, TRUE);
178
179 while (true) {
180 if (!StackWalk(IMAGE_FILE_MACHINE_I386, hProcess, hThread, &StackFrame,
181 ep->ContextRecord, NULL, SymFunctionTableAccess,
182 SymGetModuleBase, NULL)) {
183 break;
184 }
185
186 if (StackFrame.AddrFrame.Offset == 0)
187 break;
188
189 // Print the PC in hexadecimal.
190 DWORD PC = StackFrame.AddrPC.Offset;
Anton Korobeynikov77a60b92009-04-21 16:04:56 +0000191 fprintf(stderr, "%08lX", PC);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000192
193 // Print the parameters. Assume there are four.
Anton Korobeynikov77a60b92009-04-21 16:04:56 +0000194 fprintf(stderr, " (0x%08lX 0x%08lX 0x%08lX 0x%08lX)", StackFrame.Params[0],
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000195 StackFrame.Params[1], StackFrame.Params[2], StackFrame.Params[3]);
196
197 // Verify the PC belongs to a module in this process.
198 if (!SymGetModuleBase(hProcess, PC)) {
199 fputs(" <unknown module>\n", stderr);
200 continue;
201 }
202
203 // Print the symbol name.
204 char buffer[512];
205 IMAGEHLP_SYMBOL *symbol = reinterpret_cast<IMAGEHLP_SYMBOL *>(buffer);
206 memset(symbol, 0, sizeof(IMAGEHLP_SYMBOL));
207 symbol->SizeOfStruct = sizeof(IMAGEHLP_SYMBOL);
208 symbol->MaxNameLength = 512 - sizeof(IMAGEHLP_SYMBOL);
209
210 DWORD dwDisp;
211 if (!SymGetSymFromAddr(hProcess, PC, &dwDisp, symbol)) {
212 fputc('\n', stderr);
213 continue;
214 }
215
216 buffer[511] = 0;
217 if (dwDisp > 0)
Anton Korobeynikov77a60b92009-04-21 16:04:56 +0000218 fprintf(stderr, ", %s()+%04lu bytes(s)", symbol->Name, dwDisp);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000219 else
220 fprintf(stderr, ", %s", symbol->Name);
221
222 // Print the source file and line number information.
223 IMAGEHLP_LINE line;
224 memset(&line, 0, sizeof(line));
225 line.SizeOfStruct = sizeof(line);
226 if (SymGetLineFromAddr(hProcess, PC, &dwDisp, &line)) {
Anton Korobeynikov77a60b92009-04-21 16:04:56 +0000227 fprintf(stderr, ", %s, line %lu", line.FileName, line.LineNumber);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000228 if (dwDisp > 0)
Anton Korobeynikov77a60b92009-04-21 16:04:56 +0000229 fprintf(stderr, "+%04lu byte(s)", dwDisp);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000230 }
231
232 fputc('\n', stderr);
233 }
Chuck Rose III57c33da2007-11-21 00:37:56 +0000234
235#endif
236
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000237 } catch (...) {
Chris Lattner199997b2009-03-04 21:21:36 +0000238 assert(0 && "Crashed in LLVMUnhandledExceptionFilter");
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000239 }
240
241 // Allow dialog box to pop up allowing choice to start debugger.
242 if (OldFilter)
243 return (*OldFilter)(ep);
244 else
245 return EXCEPTION_CONTINUE_SEARCH;
246}
247
248static BOOL WINAPI LLVMConsoleCtrlHandler(DWORD dwCtrlType) {
249 // We are running in our very own thread, courtesy of Windows.
250 EnterCriticalSection(&CriticalSection);
251 Cleanup();
252
253 // If an interrupt function has been set, go and run one it; otherwise,
254 // the process dies.
255 void (*IF)() = InterruptFunction;
256 InterruptFunction = 0; // Don't run it on another CTRL-C.
257
258 if (IF) {
259 // Note: if the interrupt function throws an exception, there is nothing
260 // to catch it in this thread so it will kill the process.
261 IF(); // Run it now.
262 LeaveCriticalSection(&CriticalSection);
263 return TRUE; // Don't kill the process.
264 }
265
266 // Allow normal processing to take place; i.e., the process dies.
267 LeaveCriticalSection(&CriticalSection);
268 return FALSE;
269}
270