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