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