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