Add AddSymbol() method to DynamicLibrary to work around Windows limitation
[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 #pragma comment(lib, "psapi.lib")
26 #pragma comment(lib, "dbghelp.lib")
27
28 // Forward declare.
29 static LONG WINAPI LLVMUnhandledExceptionFilter(LPEXCEPTION_POINTERS ep);
30 static BOOL WINAPI LLVMConsoleCtrlHandler(DWORD dwCtrlType);
31
32 // InterruptFunction - The function to call if ctrl-c is pressed.
33 static void (*InterruptFunction)() = 0;
34
35 static std::vector<llvm::sys::Path> *FilesToRemove = NULL;
36 static std::vector<llvm::sys::Path> *DirectoriesToRemove = NULL;
37 static bool RegisteredUnhandledExceptionFilter = false;
38 static bool CleanupExecuted = false;
39 static PTOP_LEVEL_EXCEPTION_FILTER OldFilter = NULL;
40
41 // Windows creates a new thread to execute the console handler when an event
42 // (such as CTRL/C) occurs.  This causes concurrency issues with the above
43 // globals which this critical section addresses.
44 static CRITICAL_SECTION CriticalSection;
45
46 namespace llvm {
47
48 //===----------------------------------------------------------------------===//
49 //=== WARNING: Implementation here must contain only Win32 specific code 
50 //===          and must not be UNIX code
51 //===----------------------------------------------------------------------===//
52
53
54 static void RegisterHandler() { 
55   if (RegisteredUnhandledExceptionFilter) {
56     EnterCriticalSection(&CriticalSection);
57     return;
58   }
59
60   // Now's the time to create the critical section.  This is the first time
61   // through here, and there's only one thread.
62   InitializeCriticalSection(&CriticalSection);
63
64   // Enter it immediately.  Now if someone hits CTRL/C, the console handler
65   // can't proceed until the globals are updated.
66   EnterCriticalSection(&CriticalSection);
67
68   RegisteredUnhandledExceptionFilter = true;
69   OldFilter = SetUnhandledExceptionFilter(LLVMUnhandledExceptionFilter);
70   SetConsoleCtrlHandler(LLVMConsoleCtrlHandler, TRUE);
71
72   // IMPORTANT NOTE: Caller must call LeaveCriticalSection(&CriticalSection) or
73   // else multi-threading problems will ensue.
74 }
75
76 // RemoveFileOnSignal - The public API
77 void sys::RemoveFileOnSignal(const sys::Path &Filename) {
78   RegisterHandler();
79
80   if (CleanupExecuted)
81     throw std::string("Process terminating -- cannot register for removal");
82
83   if (FilesToRemove == NULL)
84     FilesToRemove = new std::vector<sys::Path>;
85
86   FilesToRemove->push_back(Filename);
87
88   LeaveCriticalSection(&CriticalSection);
89 }
90
91 // RemoveDirectoryOnSignal - The public API
92 void sys::RemoveDirectoryOnSignal(const sys::Path& path) {
93   RegisterHandler();
94
95   if (CleanupExecuted)
96     throw std::string("Process terminating -- cannot register for removal");
97
98   if (path.isDirectory()) {
99     if (DirectoriesToRemove == NULL)
100       DirectoriesToRemove = new std::vector<sys::Path>;
101
102     DirectoriesToRemove->push_back(path);
103   }
104
105   LeaveCriticalSection(&CriticalSection);
106 }
107
108 /// PrintStackTraceOnErrorSignal - When an error signal (such as SIBABRT or
109 /// SIGSEGV) is delivered to the process, print a stack trace and then exit.
110 void sys::PrintStackTraceOnErrorSignal() {
111   RegisterHandler();
112   LeaveCriticalSection(&CriticalSection);
113 }
114
115
116 void sys::SetInterruptFunction(void (*IF)()) {
117   RegisterHandler();
118   InterruptFunction = IF;
119   LeaveCriticalSection(&CriticalSection);
120 }
121 }
122
123 static void Cleanup() {
124   EnterCriticalSection(&CriticalSection);
125
126   // Prevent other thread from registering new files and directories for
127   // removal, should we be executing because of the console handler callback.
128   CleanupExecuted = true;
129
130   // FIXME: open files cannot be deleted.
131
132   if (FilesToRemove != NULL)
133     while (!FilesToRemove->empty()) {
134       try {
135         FilesToRemove->back().eraseFromDisk();
136       } catch (...) {
137       }
138       FilesToRemove->pop_back();
139     }
140
141   if (DirectoriesToRemove != NULL)
142     while (!DirectoriesToRemove->empty()) {
143       try {
144         DirectoriesToRemove->back().eraseFromDisk(true);
145       } catch (...) {
146       }
147       DirectoriesToRemove->pop_back();
148     }
149
150   LeaveCriticalSection(&CriticalSection);
151 }
152
153 static LONG WINAPI LLVMUnhandledExceptionFilter(LPEXCEPTION_POINTERS ep) {
154   try {
155     Cleanup();
156
157     // Initialize the STACKFRAME structure.
158     STACKFRAME StackFrame;
159     memset(&StackFrame, 0, sizeof(StackFrame));
160
161     StackFrame.AddrPC.Offset = ep->ContextRecord->Eip;
162     StackFrame.AddrPC.Mode = AddrModeFlat;
163     StackFrame.AddrStack.Offset = ep->ContextRecord->Esp;
164     StackFrame.AddrStack.Mode = AddrModeFlat;
165     StackFrame.AddrFrame.Offset = ep->ContextRecord->Ebp;
166     StackFrame.AddrFrame.Mode = AddrModeFlat;
167
168     HANDLE hProcess = GetCurrentProcess();
169     HANDLE hThread = GetCurrentThread();
170
171     // Initialize the symbol handler.
172     SymSetOptions(SYMOPT_DEFERRED_LOADS|SYMOPT_LOAD_LINES);
173     SymInitialize(hProcess, NULL, TRUE);
174
175     while (true) {
176       if (!StackWalk(IMAGE_FILE_MACHINE_I386, hProcess, hThread, &StackFrame,
177                      ep->ContextRecord, NULL, SymFunctionTableAccess,
178                      SymGetModuleBase, NULL)) {
179         break;
180       }
181
182       if (StackFrame.AddrFrame.Offset == 0)
183         break;
184
185       // Print the PC in hexadecimal.
186       DWORD PC = StackFrame.AddrPC.Offset;
187       fprintf(stderr, "%08X", PC);
188
189       // Print the parameters.  Assume there are four.
190       fprintf(stderr, " (0x%08X 0x%08X 0x%08X 0x%08X)", StackFrame.Params[0],
191               StackFrame.Params[1], StackFrame.Params[2], StackFrame.Params[3]);
192
193       // Verify the PC belongs to a module in this process.
194       if (!SymGetModuleBase(hProcess, PC)) {
195         fputs(" <unknown module>\n", stderr);
196         continue;
197       }
198
199       // Print the symbol name.
200       char buffer[512];
201       IMAGEHLP_SYMBOL *symbol = reinterpret_cast<IMAGEHLP_SYMBOL *>(buffer);
202       memset(symbol, 0, sizeof(IMAGEHLP_SYMBOL));
203       symbol->SizeOfStruct = sizeof(IMAGEHLP_SYMBOL);
204       symbol->MaxNameLength = 512 - sizeof(IMAGEHLP_SYMBOL);
205
206       DWORD dwDisp;
207       if (!SymGetSymFromAddr(hProcess, PC, &dwDisp, symbol)) {
208         fputc('\n', stderr);
209         continue;
210       }
211
212       buffer[511] = 0;
213       if (dwDisp > 0)
214         fprintf(stderr, ", %s()+%04d bytes(s)", symbol->Name, dwDisp);
215       else
216         fprintf(stderr, ", %s", symbol->Name);
217
218       // Print the source file and line number information.
219       IMAGEHLP_LINE line;
220       memset(&line, 0, sizeof(line));
221       line.SizeOfStruct = sizeof(line);
222       if (SymGetLineFromAddr(hProcess, PC, &dwDisp, &line)) {
223         fprintf(stderr, ", %s, line %d", line.FileName, line.LineNumber);
224         if (dwDisp > 0)
225           fprintf(stderr, "+%04d byte(s)", dwDisp);
226       }
227
228       fputc('\n', stderr);
229     }
230   } catch (...) {
231       assert(!"Crashed in LLVMUnhandledExceptionFilter");
232   }
233
234   // Allow dialog box to pop up allowing choice to start debugger.
235   if (OldFilter)
236     return (*OldFilter)(ep);
237   else
238     return EXCEPTION_CONTINUE_SEARCH;
239 }
240
241 static BOOL WINAPI LLVMConsoleCtrlHandler(DWORD dwCtrlType) {
242   // We are running in our very own thread, courtesy of Windows.
243   EnterCriticalSection(&CriticalSection);
244   Cleanup();
245
246   // If an interrupt function has been set, go and run one it; otherwise,
247   // the process dies.
248   void (*IF)() = InterruptFunction;
249   InterruptFunction = 0;      // Don't run it on another CTRL-C.
250
251   if (IF) {
252     // Note: if the interrupt function throws an exception, there is nothing
253     // to catch it in this thread so it will kill the process.
254     IF();                     // Run it now.
255     LeaveCriticalSection(&CriticalSection);
256     return TRUE;              // Don't kill the process.
257   }
258
259   // Allow normal processing to take place; i.e., the process dies.
260   LeaveCriticalSection(&CriticalSection);
261   return FALSE;
262 }
263