Remove attribution from file headers, per discussion on llvmdev.
[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
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   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.
134 void sys::PrintStackTraceOnErrorSignal() {
135   RegisterHandler();
136   LeaveCriticalSection(&CriticalSection);
137 }
138
139
140 void sys::SetInterruptFunction(void (*IF)()) {
141   RegisterHandler();
142   InterruptFunction = IF;
143   LeaveCriticalSection(&CriticalSection);
144 }
145 }
146
147 static 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
177 static LONG WINAPI LLVMUnhandledExceptionFilter(LPEXCEPTION_POINTERS ep) {
178   try {
179     Cleanup();
180     
181 #ifdef _WIN64
182   // TODO: provide a x64 friendly version of the following
183 #else
184     
185     // Initialize the STACKFRAME structure.
186     STACKFRAME StackFrame;
187     memset(&StackFrame, 0, sizeof(StackFrame));
188
189     StackFrame.AddrPC.Offset = ep->ContextRecord->Eip;
190     StackFrame.AddrPC.Mode = AddrModeFlat;
191     StackFrame.AddrStack.Offset = ep->ContextRecord->Esp;
192     StackFrame.AddrStack.Mode = AddrModeFlat;
193     StackFrame.AddrFrame.Offset = ep->ContextRecord->Ebp;
194     StackFrame.AddrFrame.Mode = AddrModeFlat;
195
196     HANDLE hProcess = GetCurrentProcess();
197     HANDLE hThread = GetCurrentThread();
198
199     // Initialize the symbol handler.
200     SymSetOptions(SYMOPT_DEFERRED_LOADS|SYMOPT_LOAD_LINES);
201     SymInitialize(hProcess, NULL, TRUE);
202
203     while (true) {
204       if (!StackWalk(IMAGE_FILE_MACHINE_I386, hProcess, hThread, &StackFrame,
205                      ep->ContextRecord, NULL, SymFunctionTableAccess,
206                      SymGetModuleBase, NULL)) {
207         break;
208       }
209
210       if (StackFrame.AddrFrame.Offset == 0)
211         break;
212
213       // Print the PC in hexadecimal.
214       DWORD PC = StackFrame.AddrPC.Offset;
215       fprintf(stderr, "%08X", PC);
216
217       // Print the parameters.  Assume there are four.
218       fprintf(stderr, " (0x%08X 0x%08X 0x%08X 0x%08X)", StackFrame.Params[0],
219               StackFrame.Params[1], StackFrame.Params[2], StackFrame.Params[3]);
220
221       // Verify the PC belongs to a module in this process.
222       if (!SymGetModuleBase(hProcess, PC)) {
223         fputs(" <unknown module>\n", stderr);
224         continue;
225       }
226
227       // Print the symbol name.
228       char buffer[512];
229       IMAGEHLP_SYMBOL *symbol = reinterpret_cast<IMAGEHLP_SYMBOL *>(buffer);
230       memset(symbol, 0, sizeof(IMAGEHLP_SYMBOL));
231       symbol->SizeOfStruct = sizeof(IMAGEHLP_SYMBOL);
232       symbol->MaxNameLength = 512 - sizeof(IMAGEHLP_SYMBOL);
233
234       DWORD dwDisp;
235       if (!SymGetSymFromAddr(hProcess, PC, &dwDisp, symbol)) {
236         fputc('\n', stderr);
237         continue;
238       }
239
240       buffer[511] = 0;
241       if (dwDisp > 0)
242         fprintf(stderr, ", %s()+%04d bytes(s)", symbol->Name, dwDisp);
243       else
244         fprintf(stderr, ", %s", symbol->Name);
245
246       // Print the source file and line number information.
247       IMAGEHLP_LINE line;
248       memset(&line, 0, sizeof(line));
249       line.SizeOfStruct = sizeof(line);
250       if (SymGetLineFromAddr(hProcess, PC, &dwDisp, &line)) {
251         fprintf(stderr, ", %s, line %d", line.FileName, line.LineNumber);
252         if (dwDisp > 0)
253           fprintf(stderr, "+%04d byte(s)", dwDisp);
254       }
255
256       fputc('\n', stderr);
257     }
258
259 #endif
260
261   } catch (...) {
262       assert(!"Crashed in LLVMUnhandledExceptionFilter");
263   }
264
265   // Allow dialog box to pop up allowing choice to start debugger.
266   if (OldFilter)
267     return (*OldFilter)(ep);
268   else
269     return EXCEPTION_CONTINUE_SEARCH;
270 }
271
272 static BOOL WINAPI LLVMConsoleCtrlHandler(DWORD dwCtrlType) {
273   // We are running in our very own thread, courtesy of Windows.
274   EnterCriticalSection(&CriticalSection);
275   Cleanup();
276
277   // If an interrupt function has been set, go and run one it; otherwise,
278   // the process dies.
279   void (*IF)() = InterruptFunction;
280   InterruptFunction = 0;      // Don't run it on another CTRL-C.
281
282   if (IF) {
283     // Note: if the interrupt function throws an exception, there is nothing
284     // to catch it in this thread so it will kill the process.
285     IF();                     // Run it now.
286     LeaveCriticalSection(&CriticalSection);
287     return TRUE;              // Don't kill the process.
288   }
289
290   // Allow normal processing to take place; i.e., the process dies.
291   LeaveCriticalSection(&CriticalSection);
292   return FALSE;
293 }
294