1 //===- Win32/Signals.cpp - Win32 Signals Implementation ---------*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file provides the Win32 specific implementation of the Signals class.
12 //===----------------------------------------------------------------------===//
27 #if ((HAVE_LIBIMAGEHLP != 1) || (HAVE_LIBPSAPI != 1))
28 #error "libimagehlp.a & libpsapi.a should be present"
31 #pragma comment(lib, "psapi.lib")
32 #pragma comment(lib, "dbghelp.lib")
36 static LONG WINAPI LLVMUnhandledExceptionFilter(LPEXCEPTION_POINTERS ep);
37 static BOOL WINAPI LLVMConsoleCtrlHandler(DWORD dwCtrlType);
39 // InterruptFunction - The function to call if ctrl-c is pressed.
40 static void (*InterruptFunction)() = 0;
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 bool ExitOnUnhandledExceptions = false;
47 static PTOP_LEVEL_EXCEPTION_FILTER OldFilter = NULL;
49 // Windows creates a new thread to execute the console handler when an event
50 // (such as CTRL/C) occurs. This causes concurrency issues with the above
51 // globals which this critical section addresses.
52 static CRITICAL_SECTION CriticalSection;
56 //===----------------------------------------------------------------------===//
57 //=== WARNING: Implementation here must contain only Win32 specific code
58 //=== and must not be UNIX code
59 //===----------------------------------------------------------------------===//
61 /// CRTReportHook - Function called on a CRT debugging event.
62 static int CRTReportHook(int ReportType, char *Message, int *Return) {
63 // Don't cause a DebugBreak() on return.
70 fprintf(stderr, "CRT assert: %s\n", Message);
71 // FIXME: Is there a way to just crash? Perhaps throw to the unhandled
72 // exception code? Perhaps SetErrorMode() handles this.
76 fprintf(stderr, "CRT error: %s\n", Message);
77 // FIXME: Is there a way to just crash? Perhaps throw to the unhandled
78 // exception code? Perhaps SetErrorMode() handles this.
82 fprintf(stderr, "CRT warn: %s\n", Message);
86 // Don't call _CrtDbgReport.
90 static void RegisterHandler() {
91 if (RegisteredUnhandledExceptionFilter) {
92 EnterCriticalSection(&CriticalSection);
96 // Now's the time to create the critical section. This is the first time
97 // through here, and there's only one thread.
98 InitializeCriticalSection(&CriticalSection);
100 // Enter it immediately. Now if someone hits CTRL/C, the console handler
101 // can't proceed until the globals are updated.
102 EnterCriticalSection(&CriticalSection);
104 RegisteredUnhandledExceptionFilter = true;
105 OldFilter = SetUnhandledExceptionFilter(LLVMUnhandledExceptionFilter);
106 SetConsoleCtrlHandler(LLVMConsoleCtrlHandler, TRUE);
108 // Environment variable to disable any kind of crash dialog.
109 if (getenv("LLVM_DISABLE_CRT_DEBUG")) {
110 _CrtSetReportHook(CRTReportHook);
111 ExitOnUnhandledExceptions = true;
114 // IMPORTANT NOTE: Caller must call LeaveCriticalSection(&CriticalSection) or
115 // else multi-threading problems will ensue.
118 // RemoveFileOnSignal - The public API
119 bool sys::RemoveFileOnSignal(const sys::Path &Filename, std::string* ErrMsg) {
122 if (CleanupExecuted) {
124 *ErrMsg = "Process terminating -- cannot register for removal";
128 if (FilesToRemove == NULL)
129 FilesToRemove = new std::vector<sys::Path>;
131 FilesToRemove->push_back(Filename);
133 LeaveCriticalSection(&CriticalSection);
137 /// PrintStackTraceOnErrorSignal - When an error signal (such as SIBABRT or
138 /// SIGSEGV) is delivered to the process, print a stack trace and then exit.
139 void sys::PrintStackTraceOnErrorSignal() {
141 LeaveCriticalSection(&CriticalSection);
145 void sys::SetInterruptFunction(void (*IF)()) {
147 InterruptFunction = IF;
148 LeaveCriticalSection(&CriticalSection);
152 /// AddSignalHandler - Add a function to be called when a signal is delivered
153 /// to the process. The handler can have a cookie passed to it to identify
154 /// what instance of the handler it is.
155 void sys::AddSignalHandler(void (*FnPtr)(void *), void *Cookie) {
156 if (CallBacksToRun == 0)
157 CallBacksToRun = new std::vector<std::pair<void(*)(void*), void*> >();
158 CallBacksToRun->push_back(std::make_pair(FnPtr, Cookie));
163 static void Cleanup() {
164 EnterCriticalSection(&CriticalSection);
166 // Prevent other thread from registering new files and directories for
167 // removal, should we be executing because of the console handler callback.
168 CleanupExecuted = true;
170 // FIXME: open files cannot be deleted.
172 if (FilesToRemove != NULL)
173 while (!FilesToRemove->empty()) {
174 FilesToRemove->back().eraseFromDisk();
175 FilesToRemove->pop_back();
179 for (unsigned i = 0, e = CallBacksToRun->size(); i != e; ++i)
180 (*CallBacksToRun)[i].first((*CallBacksToRun)[i].second);
182 LeaveCriticalSection(&CriticalSection);
185 static LONG WINAPI LLVMUnhandledExceptionFilter(LPEXCEPTION_POINTERS ep) {
190 // TODO: provide a x64 friendly version of the following
193 // Initialize the STACKFRAME structure.
194 STACKFRAME StackFrame;
195 memset(&StackFrame, 0, sizeof(StackFrame));
197 StackFrame.AddrPC.Offset = ep->ContextRecord->Eip;
198 StackFrame.AddrPC.Mode = AddrModeFlat;
199 StackFrame.AddrStack.Offset = ep->ContextRecord->Esp;
200 StackFrame.AddrStack.Mode = AddrModeFlat;
201 StackFrame.AddrFrame.Offset = ep->ContextRecord->Ebp;
202 StackFrame.AddrFrame.Mode = AddrModeFlat;
204 HANDLE hProcess = GetCurrentProcess();
205 HANDLE hThread = GetCurrentThread();
207 // Initialize the symbol handler.
208 SymSetOptions(SYMOPT_DEFERRED_LOADS|SYMOPT_LOAD_LINES);
209 SymInitialize(hProcess, NULL, TRUE);
212 if (!StackWalk(IMAGE_FILE_MACHINE_I386, hProcess, hThread, &StackFrame,
213 ep->ContextRecord, NULL, SymFunctionTableAccess,
214 SymGetModuleBase, NULL)) {
218 if (StackFrame.AddrFrame.Offset == 0)
221 // Print the PC in hexadecimal.
222 DWORD PC = StackFrame.AddrPC.Offset;
223 fprintf(stderr, "%08lX", PC);
225 // Print the parameters. Assume there are four.
226 fprintf(stderr, " (0x%08lX 0x%08lX 0x%08lX 0x%08lX)", StackFrame.Params[0],
227 StackFrame.Params[1], StackFrame.Params[2], StackFrame.Params[3]);
229 // Verify the PC belongs to a module in this process.
230 if (!SymGetModuleBase(hProcess, PC)) {
231 fputs(" <unknown module>\n", stderr);
235 // Print the symbol name.
237 IMAGEHLP_SYMBOL *symbol = reinterpret_cast<IMAGEHLP_SYMBOL *>(buffer);
238 memset(symbol, 0, sizeof(IMAGEHLP_SYMBOL));
239 symbol->SizeOfStruct = sizeof(IMAGEHLP_SYMBOL);
240 symbol->MaxNameLength = 512 - sizeof(IMAGEHLP_SYMBOL);
243 if (!SymGetSymFromAddr(hProcess, PC, &dwDisp, symbol)) {
250 fprintf(stderr, ", %s()+%04lu bytes(s)", symbol->Name, dwDisp);
252 fprintf(stderr, ", %s", symbol->Name);
254 // Print the source file and line number information.
256 memset(&line, 0, sizeof(line));
257 line.SizeOfStruct = sizeof(line);
258 if (SymGetLineFromAddr(hProcess, PC, &dwDisp, &line)) {
259 fprintf(stderr, ", %s, line %lu", line.FileName, line.LineNumber);
261 fprintf(stderr, "+%04lu byte(s)", dwDisp);
270 assert(0 && "Crashed in LLVMUnhandledExceptionFilter");
273 if (ExitOnUnhandledExceptions)
276 // Allow dialog box to pop up allowing choice to start debugger.
278 return (*OldFilter)(ep);
280 return EXCEPTION_CONTINUE_SEARCH;
283 static BOOL WINAPI LLVMConsoleCtrlHandler(DWORD dwCtrlType) {
284 // We are running in our very own thread, courtesy of Windows.
285 EnterCriticalSection(&CriticalSection);
288 // If an interrupt function has been set, go and run one it; otherwise,
290 void (*IF)() = InterruptFunction;
291 InterruptFunction = 0; // Don't run it on another CTRL-C.
294 // Note: if the interrupt function throws an exception, there is nothing
295 // to catch it in this thread so it will kill the process.
297 LeaveCriticalSection(&CriticalSection);
298 return TRUE; // Don't kill the process.
301 // Allow normal processing to take place; i.e., the process dies.
302 LeaveCriticalSection(&CriticalSection);