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