Signals.inc revision ac25e44d8905e88f91f998ce27a82cea641f5ff9
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 "Windows.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. 36static LONG WINAPI LLVMUnhandledExceptionFilter(LPEXCEPTION_POINTERS ep); 37static BOOL WINAPI LLVMConsoleCtrlHandler(DWORD dwCtrlType); 38 39// InterruptFunction - The function to call if ctrl-c is pressed. 40static void (*InterruptFunction)() = 0; 41 42static std::vector<llvm::sys::Path> *FilesToRemove = NULL; 43static std::vector<std::pair<void(*)(void*), void*> > *CallBacksToRun = 0; 44static bool RegisteredUnhandledExceptionFilter = false; 45static bool CleanupExecuted = false; 46static bool ExitOnUnhandledExceptions = false; 47static PTOP_LEVEL_EXCEPTION_FILTER OldFilter = NULL; 48 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. 52static CRITICAL_SECTION CriticalSection; 53 54namespace llvm { 55 56//===----------------------------------------------------------------------===// 57//=== WARNING: Implementation here must contain only Win32 specific code 58//=== and must not be UNIX code 59//===----------------------------------------------------------------------===// 60 61#ifdef _MSC_VER 62/// CRTReportHook - Function called on a CRT debugging event. 63static int CRTReportHook(int ReportType, char *Message, int *Return) { 64 // Don't cause a DebugBreak() on return. 65 if (Return) 66 *Return = 0; 67 68 switch (ReportType) { 69 default: 70 case _CRT_ASSERT: 71 fprintf(stderr, "CRT assert: %s\n", Message); 72 // FIXME: Is there a way to just crash? Perhaps throw to the unhandled 73 // exception code? Perhaps SetErrorMode() handles this. 74 _exit(3); 75 break; 76 case _CRT_ERROR: 77 fprintf(stderr, "CRT error: %s\n", Message); 78 // FIXME: Is there a way to just crash? Perhaps throw to the unhandled 79 // exception code? Perhaps SetErrorMode() handles this. 80 _exit(3); 81 break; 82 case _CRT_WARN: 83 fprintf(stderr, "CRT warn: %s\n", Message); 84 break; 85 } 86 87 // Don't call _CrtDbgReport. 88 return TRUE; 89} 90#endif 91 92static void RegisterHandler() { 93 if (RegisteredUnhandledExceptionFilter) { 94 EnterCriticalSection(&CriticalSection); 95 return; 96 } 97 98 // Now's the time to create the critical section. This is the first time 99 // through here, and there's only one thread. 100 InitializeCriticalSection(&CriticalSection); 101 102 // Enter it immediately. Now if someone hits CTRL/C, the console handler 103 // can't proceed until the globals are updated. 104 EnterCriticalSection(&CriticalSection); 105 106 RegisteredUnhandledExceptionFilter = true; 107 OldFilter = SetUnhandledExceptionFilter(LLVMUnhandledExceptionFilter); 108 SetConsoleCtrlHandler(LLVMConsoleCtrlHandler, TRUE); 109 110 // Environment variable to disable any kind of crash dialog. 111 if (getenv("LLVM_DISABLE_CRT_DEBUG")) { 112#ifdef _MSC_VER 113 _CrtSetReportHook(CRTReportHook); 114#endif 115 SetErrorMode(SEM_FAILCRITICALERRORS | 116 SEM_NOGPFAULTERRORBOX | 117 SEM_NOOPENFILEERRORBOX); 118 ExitOnUnhandledExceptions = true; 119 } 120 121 // IMPORTANT NOTE: Caller must call LeaveCriticalSection(&CriticalSection) or 122 // else multi-threading problems will ensue. 123} 124 125// RemoveFileOnSignal - The public API 126bool sys::RemoveFileOnSignal(const sys::Path &Filename, std::string* ErrMsg) { 127 RegisterHandler(); 128 129 if (CleanupExecuted) { 130 if (ErrMsg) 131 *ErrMsg = "Process terminating -- cannot register for removal"; 132 return true; 133 } 134 135 if (FilesToRemove == NULL) 136 FilesToRemove = new std::vector<sys::Path>; 137 138 FilesToRemove->push_back(Filename); 139 140 LeaveCriticalSection(&CriticalSection); 141 return false; 142} 143 144// DontRemoveFileOnSignal - The public API 145void sys::DontRemoveFileOnSignal(const sys::Path &Filename) { 146 if (FilesToRemove == NULL) 147 return; 148 149 RegisterHandler(); 150 151 FilesToRemove->push_back(Filename); 152 std::vector<sys::Path>::reverse_iterator I = 153 std::find(FilesToRemove->rbegin(), FilesToRemove->rend(), Filename); 154 if (I != FilesToRemove->rend()) 155 FilesToRemove->erase(I.base()-1); 156 157 LeaveCriticalSection(&CriticalSection); 158} 159 160/// PrintStackTraceOnErrorSignal - When an error signal (such as SIBABRT or 161/// SIGSEGV) is delivered to the process, print a stack trace and then exit. 162void sys::PrintStackTraceOnErrorSignal() { 163 RegisterHandler(); 164 LeaveCriticalSection(&CriticalSection); 165} 166 167 168void sys::SetInterruptFunction(void (*IF)()) { 169 RegisterHandler(); 170 InterruptFunction = IF; 171 LeaveCriticalSection(&CriticalSection); 172} 173 174 175/// AddSignalHandler - Add a function to be called when a signal is delivered 176/// to the process. The handler can have a cookie passed to it to identify 177/// what instance of the handler it is. 178void sys::AddSignalHandler(void (*FnPtr)(void *), void *Cookie) { 179 if (CallBacksToRun == 0) 180 CallBacksToRun = new std::vector<std::pair<void(*)(void*), void*> >(); 181 CallBacksToRun->push_back(std::make_pair(FnPtr, Cookie)); 182 RegisterHandler(); 183 LeaveCriticalSection(&CriticalSection); 184} 185} 186 187static void Cleanup() { 188 EnterCriticalSection(&CriticalSection); 189 190 // Prevent other thread from registering new files and directories for 191 // removal, should we be executing because of the console handler callback. 192 CleanupExecuted = true; 193 194 // FIXME: open files cannot be deleted. 195 196 if (FilesToRemove != NULL) 197 while (!FilesToRemove->empty()) { 198 FilesToRemove->back().eraseFromDisk(); 199 FilesToRemove->pop_back(); 200 } 201 202 if (CallBacksToRun) 203 for (unsigned i = 0, e = CallBacksToRun->size(); i != e; ++i) 204 (*CallBacksToRun)[i].first((*CallBacksToRun)[i].second); 205 206 LeaveCriticalSection(&CriticalSection); 207} 208 209void llvm::sys::RunInterruptHandlers() { 210 Cleanup(); 211} 212 213static LONG WINAPI LLVMUnhandledExceptionFilter(LPEXCEPTION_POINTERS ep) { 214 Cleanup(); 215 216#ifdef _WIN64 217 // TODO: provide a x64 friendly version of the following 218#else 219 220 // Initialize the STACKFRAME structure. 221 STACKFRAME StackFrame; 222 memset(&StackFrame, 0, sizeof(StackFrame)); 223 224 StackFrame.AddrPC.Offset = ep->ContextRecord->Eip; 225 StackFrame.AddrPC.Mode = AddrModeFlat; 226 StackFrame.AddrStack.Offset = ep->ContextRecord->Esp; 227 StackFrame.AddrStack.Mode = AddrModeFlat; 228 StackFrame.AddrFrame.Offset = ep->ContextRecord->Ebp; 229 StackFrame.AddrFrame.Mode = AddrModeFlat; 230 231 HANDLE hProcess = GetCurrentProcess(); 232 HANDLE hThread = GetCurrentThread(); 233 234 // Initialize the symbol handler. 235 SymSetOptions(SYMOPT_DEFERRED_LOADS|SYMOPT_LOAD_LINES); 236 SymInitialize(hProcess, NULL, TRUE); 237 238 while (true) { 239 if (!StackWalk(IMAGE_FILE_MACHINE_I386, hProcess, hThread, &StackFrame, 240 ep->ContextRecord, NULL, SymFunctionTableAccess, 241 SymGetModuleBase, NULL)) { 242 break; 243 } 244 245 if (StackFrame.AddrFrame.Offset == 0) 246 break; 247 248 // Print the PC in hexadecimal. 249 DWORD PC = StackFrame.AddrPC.Offset; 250 fprintf(stderr, "%08lX", PC); 251 252 // Print the parameters. Assume there are four. 253 fprintf(stderr, " (0x%08lX 0x%08lX 0x%08lX 0x%08lX)", 254 StackFrame.Params[0], 255 StackFrame.Params[1], StackFrame.Params[2], StackFrame.Params[3]); 256 257 // Verify the PC belongs to a module in this process. 258 if (!SymGetModuleBase(hProcess, PC)) { 259 fputs(" <unknown module>\n", stderr); 260 continue; 261 } 262 263 // Print the symbol name. 264 char buffer[512]; 265 IMAGEHLP_SYMBOL *symbol = reinterpret_cast<IMAGEHLP_SYMBOL *>(buffer); 266 memset(symbol, 0, sizeof(IMAGEHLP_SYMBOL)); 267 symbol->SizeOfStruct = sizeof(IMAGEHLP_SYMBOL); 268 symbol->MaxNameLength = 512 - sizeof(IMAGEHLP_SYMBOL); 269 270 DWORD dwDisp; 271 if (!SymGetSymFromAddr(hProcess, PC, &dwDisp, symbol)) { 272 fputc('\n', stderr); 273 continue; 274 } 275 276 buffer[511] = 0; 277 if (dwDisp > 0) 278 fprintf(stderr, ", %s()+%04lu bytes(s)", symbol->Name, dwDisp); 279 else 280 fprintf(stderr, ", %s", symbol->Name); 281 282 // Print the source file and line number information. 283 IMAGEHLP_LINE line; 284 memset(&line, 0, sizeof(line)); 285 line.SizeOfStruct = sizeof(line); 286 if (SymGetLineFromAddr(hProcess, PC, &dwDisp, &line)) { 287 fprintf(stderr, ", %s, line %lu", line.FileName, line.LineNumber); 288 if (dwDisp > 0) 289 fprintf(stderr, "+%04lu byte(s)", dwDisp); 290 } 291 292 fputc('\n', stderr); 293 } 294 295#endif 296 297 if (ExitOnUnhandledExceptions) 298 _exit(-3); 299 300 // Allow dialog box to pop up allowing choice to start debugger. 301 if (OldFilter) 302 return (*OldFilter)(ep); 303 else 304 return EXCEPTION_CONTINUE_SEARCH; 305} 306 307static BOOL WINAPI LLVMConsoleCtrlHandler(DWORD dwCtrlType) { 308 // We are running in our very own thread, courtesy of Windows. 309 EnterCriticalSection(&CriticalSection); 310 Cleanup(); 311 312 // If an interrupt function has been set, go and run one it; otherwise, 313 // the process dies. 314 void (*IF)() = InterruptFunction; 315 InterruptFunction = 0; // Don't run it on another CTRL-C. 316 317 if (IF) { 318 // Note: if the interrupt function throws an exception, there is nothing 319 // to catch it in this thread so it will kill the process. 320 IF(); // Run it now. 321 LeaveCriticalSection(&CriticalSection); 322 return TRUE; // Don't kill the process. 323 } 324 325 // Allow normal processing to take place; i.e., the process dies. 326 LeaveCriticalSection(&CriticalSection); 327 return FALSE; 328} 329