Add llvm::sys::RunInterruptHandlers(), which runs the registered SIGINT cleanup
[oota-llvm.git] / lib / System / Win32 / Signals.inc
1 //===- Win32/Signals.cpp - Win32 Signals Implementation ---------*- C++ -*-===//
2 // 
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // 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 #include <algorithm>
18
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.
36 static LONG WINAPI LLVMUnhandledExceptionFilter(LPEXCEPTION_POINTERS ep);
37 static BOOL WINAPI LLVMConsoleCtrlHandler(DWORD dwCtrlType);
38
39 // InterruptFunction - The function to call if ctrl-c is pressed.
40 static void (*InterruptFunction)() = 0;
41
42 static std::vector<llvm::sys::Path> *FilesToRemove = NULL;
43 static std::vector<std::pair<void(*)(void*), void*> > *CallBacksToRun = 0;
44 static bool RegisteredUnhandledExceptionFilter = false;
45 static bool CleanupExecuted = false;
46 #ifdef _MSC_VER
47 static bool ExitOnUnhandledExceptions = false;
48 #endif
49 static PTOP_LEVEL_EXCEPTION_FILTER OldFilter = NULL;
50
51 // Windows creates a new thread to execute the console handler when an event
52 // (such as CTRL/C) occurs.  This causes concurrency issues with the above
53 // globals which this critical section addresses.
54 static CRITICAL_SECTION CriticalSection;
55
56 namespace llvm {
57
58 //===----------------------------------------------------------------------===//
59 //=== WARNING: Implementation here must contain only Win32 specific code 
60 //===          and must not be UNIX code
61 //===----------------------------------------------------------------------===//
62
63 #ifdef _MSC_VER
64 /// CRTReportHook - Function called on a CRT debugging event.
65 static int CRTReportHook(int ReportType, char *Message, int *Return) {
66   // Don't cause a DebugBreak() on return.
67   if (Return)
68     *Return = 0;
69
70   switch (ReportType) {
71   default:
72   case _CRT_ASSERT:
73     fprintf(stderr, "CRT assert: %s\n", Message);
74     // FIXME: Is there a way to just crash? Perhaps throw to the unhandled
75     // exception code? Perhaps SetErrorMode() handles this.
76     _exit(3);
77     break;
78   case _CRT_ERROR:
79     fprintf(stderr, "CRT error: %s\n", Message);
80     // FIXME: Is there a way to just crash? Perhaps throw to the unhandled
81     // exception code? Perhaps SetErrorMode() handles this.
82     _exit(3);
83     break;
84   case _CRT_WARN:
85     fprintf(stderr, "CRT warn: %s\n", Message);
86     break;
87   }
88
89   // Don't call _CrtDbgReport.
90   return TRUE;
91 }
92 #endif
93
94 static void RegisterHandler() {
95   if (RegisteredUnhandledExceptionFilter) {
96     EnterCriticalSection(&CriticalSection);
97     return;
98   }
99
100   // Now's the time to create the critical section.  This is the first time
101   // through here, and there's only one thread.
102   InitializeCriticalSection(&CriticalSection);
103
104   // Enter it immediately.  Now if someone hits CTRL/C, the console handler
105   // can't proceed until the globals are updated.
106   EnterCriticalSection(&CriticalSection);
107
108   RegisteredUnhandledExceptionFilter = true;
109   OldFilter = SetUnhandledExceptionFilter(LLVMUnhandledExceptionFilter);
110   SetConsoleCtrlHandler(LLVMConsoleCtrlHandler, TRUE);
111
112   // Environment variable to disable any kind of crash dialog.
113 #ifdef _MSC_VER
114   if (getenv("LLVM_DISABLE_CRT_DEBUG")) {
115     _CrtSetReportHook(CRTReportHook);
116     ExitOnUnhandledExceptions = true;
117   }
118 #endif
119
120   // IMPORTANT NOTE: Caller must call LeaveCriticalSection(&CriticalSection) or
121   // else multi-threading problems will ensue.
122 }
123
124 // RemoveFileOnSignal - The public API
125 bool sys::RemoveFileOnSignal(const sys::Path &Filename, std::string* ErrMsg) {
126   RegisterHandler();
127
128   if (CleanupExecuted) {
129     if (ErrMsg)
130       *ErrMsg = "Process terminating -- cannot register for removal";
131     return true;
132   }
133
134   if (FilesToRemove == NULL)
135     FilesToRemove = new std::vector<sys::Path>;
136
137   FilesToRemove->push_back(Filename);
138
139   LeaveCriticalSection(&CriticalSection);
140   return false;
141 }
142
143 /// PrintStackTraceOnErrorSignal - When an error signal (such as SIBABRT or
144 /// SIGSEGV) is delivered to the process, print a stack trace and then exit.
145 void sys::PrintStackTraceOnErrorSignal() {
146   RegisterHandler();
147   LeaveCriticalSection(&CriticalSection);
148 }
149
150
151 void sys::SetInterruptFunction(void (*IF)()) {
152   RegisterHandler();
153   InterruptFunction = IF;
154   LeaveCriticalSection(&CriticalSection);
155 }
156
157
158 /// AddSignalHandler - Add a function to be called when a signal is delivered
159 /// to the process.  The handler can have a cookie passed to it to identify
160 /// what instance of the handler it is.
161 void sys::AddSignalHandler(void (*FnPtr)(void *), void *Cookie) {
162   if (CallBacksToRun == 0)
163     CallBacksToRun = new std::vector<std::pair<void(*)(void*), void*> >();
164   CallBacksToRun->push_back(std::make_pair(FnPtr, Cookie));
165   RegisterHandler();
166   LeaveCriticalSection(&CriticalSection);
167 }
168 }
169
170 static void Cleanup() {
171   EnterCriticalSection(&CriticalSection);
172
173   // Prevent other thread from registering new files and directories for
174   // removal, should we be executing because of the console handler callback.
175   CleanupExecuted = true;
176
177   // FIXME: open files cannot be deleted.
178
179   if (FilesToRemove != NULL)
180     while (!FilesToRemove->empty()) {
181       FilesToRemove->back().eraseFromDisk();
182       FilesToRemove->pop_back();
183     }
184
185   if (CallBacksToRun)
186     for (unsigned i = 0, e = CallBacksToRun->size(); i != e; ++i)
187       (*CallBacksToRun)[i].first((*CallBacksToRun)[i].second);
188
189   LeaveCriticalSection(&CriticalSection);
190 }
191
192 void llvm::sys::RunInterruptHandlers() {
193   Cleanup();
194 }
195
196 static LONG WINAPI LLVMUnhandledExceptionFilter(LPEXCEPTION_POINTERS ep) {
197   try {
198     Cleanup();
199     
200 #ifdef _WIN64
201   // TODO: provide a x64 friendly version of the following
202 #else
203     
204     // Initialize the STACKFRAME structure.
205     STACKFRAME StackFrame;
206     memset(&StackFrame, 0, sizeof(StackFrame));
207
208     StackFrame.AddrPC.Offset = ep->ContextRecord->Eip;
209     StackFrame.AddrPC.Mode = AddrModeFlat;
210     StackFrame.AddrStack.Offset = ep->ContextRecord->Esp;
211     StackFrame.AddrStack.Mode = AddrModeFlat;
212     StackFrame.AddrFrame.Offset = ep->ContextRecord->Ebp;
213     StackFrame.AddrFrame.Mode = AddrModeFlat;
214
215     HANDLE hProcess = GetCurrentProcess();
216     HANDLE hThread = GetCurrentThread();
217
218     // Initialize the symbol handler.
219     SymSetOptions(SYMOPT_DEFERRED_LOADS|SYMOPT_LOAD_LINES);
220     SymInitialize(hProcess, NULL, TRUE);
221
222     while (true) {
223       if (!StackWalk(IMAGE_FILE_MACHINE_I386, hProcess, hThread, &StackFrame,
224                      ep->ContextRecord, NULL, SymFunctionTableAccess,
225                      SymGetModuleBase, NULL)) {
226         break;
227       }
228
229       if (StackFrame.AddrFrame.Offset == 0)
230         break;
231
232       // Print the PC in hexadecimal.
233       DWORD PC = StackFrame.AddrPC.Offset;
234       fprintf(stderr, "%08lX", PC);
235
236       // Print the parameters.  Assume there are four.
237       fprintf(stderr, " (0x%08lX 0x%08lX 0x%08lX 0x%08lX)", StackFrame.Params[0],
238               StackFrame.Params[1], StackFrame.Params[2], StackFrame.Params[3]);
239
240       // Verify the PC belongs to a module in this process.
241       if (!SymGetModuleBase(hProcess, PC)) {
242         fputs(" <unknown module>\n", stderr);
243         continue;
244       }
245
246       // Print the symbol name.
247       char buffer[512];
248       IMAGEHLP_SYMBOL *symbol = reinterpret_cast<IMAGEHLP_SYMBOL *>(buffer);
249       memset(symbol, 0, sizeof(IMAGEHLP_SYMBOL));
250       symbol->SizeOfStruct = sizeof(IMAGEHLP_SYMBOL);
251       symbol->MaxNameLength = 512 - sizeof(IMAGEHLP_SYMBOL);
252
253       DWORD dwDisp;
254       if (!SymGetSymFromAddr(hProcess, PC, &dwDisp, symbol)) {
255         fputc('\n', stderr);
256         continue;
257       }
258
259       buffer[511] = 0;
260       if (dwDisp > 0)
261         fprintf(stderr, ", %s()+%04lu bytes(s)", symbol->Name, dwDisp);
262       else
263         fprintf(stderr, ", %s", symbol->Name);
264
265       // Print the source file and line number information.
266       IMAGEHLP_LINE line;
267       memset(&line, 0, sizeof(line));
268       line.SizeOfStruct = sizeof(line);
269       if (SymGetLineFromAddr(hProcess, PC, &dwDisp, &line)) {
270         fprintf(stderr, ", %s, line %lu", line.FileName, line.LineNumber);
271         if (dwDisp > 0)
272           fprintf(stderr, "+%04lu byte(s)", dwDisp);
273       }
274
275       fputc('\n', stderr);
276     }
277
278 #endif
279
280   } catch (...) {
281       assert(0 && "Crashed in LLVMUnhandledExceptionFilter");
282   }
283
284 #ifdef _MSC_VER
285   if (ExitOnUnhandledExceptions)
286         _exit(-3);
287 #endif
288
289   // Allow dialog box to pop up allowing choice to start debugger.
290   if (OldFilter)
291     return (*OldFilter)(ep);
292   else
293     return EXCEPTION_CONTINUE_SEARCH;
294 }
295
296 static BOOL WINAPI LLVMConsoleCtrlHandler(DWORD dwCtrlType) {
297   // We are running in our very own thread, courtesy of Windows.
298   EnterCriticalSection(&CriticalSection);
299   Cleanup();
300
301   // If an interrupt function has been set, go and run one it; otherwise,
302   // the process dies.
303   void (*IF)() = InterruptFunction;
304   InterruptFunction = 0;      // Don't run it on another CTRL-C.
305
306   if (IF) {
307     // Note: if the interrupt function throws an exception, there is nothing
308     // to catch it in this thread so it will kill the process.
309     IF();                     // Run it now.
310     LeaveCriticalSection(&CriticalSection);
311     return TRUE;              // Don't kill the process.
312   }
313
314   // Allow normal processing to take place; i.e., the process dies.
315   LeaveCriticalSection(&CriticalSection);
316   return FALSE;
317 }
318