LLVM API Documentation
00001 //===- Win32/Signals.cpp - Win32 Signals Implementation ---------*- C++ -*-===// 00002 // 00003 // The LLVM Compiler Infrastructure 00004 // 00005 // This file is distributed under the University of Illinois Open Source 00006 // License. See LICENSE.TXT for details. 00007 // 00008 //===----------------------------------------------------------------------===// 00009 // 00010 // This file provides the Win32 specific implementation of the Signals class. 00011 // 00012 //===----------------------------------------------------------------------===// 00013 00014 #include "Win32.h" 00015 #include <stdio.h> 00016 #include <vector> 00017 #include <algorithm> 00018 00019 #ifdef __MINGW32__ 00020 #include <imagehlp.h> 00021 #else 00022 #include <dbghelp.h> 00023 #endif 00024 #include <psapi.h> 00025 00026 #ifdef __MINGW32__ 00027 #if ((HAVE_LIBIMAGEHLP != 1) || (HAVE_LIBPSAPI != 1)) 00028 #error "libimagehlp.a & libpsapi.a should be present" 00029 #endif 00030 #else 00031 #pragma comment(lib, "psapi.lib") 00032 #pragma comment(lib, "dbghelp.lib") 00033 #endif 00034 00035 // Forward declare. 00036 static LONG WINAPI LLVMUnhandledExceptionFilter(LPEXCEPTION_POINTERS ep); 00037 static BOOL WINAPI LLVMConsoleCtrlHandler(DWORD dwCtrlType); 00038 00039 // InterruptFunction - The function to call if ctrl-c is pressed. 00040 static void (*InterruptFunction)() = 0; 00041 00042 static std::vector<llvm::sys::Path> *FilesToRemove = NULL; 00043 static std::vector<std::pair<void(*)(void*), void*> > *CallBacksToRun = 0; 00044 static bool RegisteredUnhandledExceptionFilter = false; 00045 static bool CleanupExecuted = false; 00046 static PTOP_LEVEL_EXCEPTION_FILTER OldFilter = NULL; 00047 00048 // Windows creates a new thread to execute the console handler when an event 00049 // (such as CTRL/C) occurs. This causes concurrency issues with the above 00050 // globals which this critical section addresses. 00051 static CRITICAL_SECTION CriticalSection; 00052 00053 namespace llvm { 00054 00055 //===----------------------------------------------------------------------===// 00056 //=== WARNING: Implementation here must contain only Win32 specific code 00057 //=== and must not be UNIX code 00058 //===----------------------------------------------------------------------===// 00059 00060 00061 static void RegisterHandler() { 00062 if (RegisteredUnhandledExceptionFilter) { 00063 EnterCriticalSection(&CriticalSection); 00064 return; 00065 } 00066 00067 // Now's the time to create the critical section. This is the first time 00068 // through here, and there's only one thread. 00069 InitializeCriticalSection(&CriticalSection); 00070 00071 // Enter it immediately. Now if someone hits CTRL/C, the console handler 00072 // can't proceed until the globals are updated. 00073 EnterCriticalSection(&CriticalSection); 00074 00075 RegisteredUnhandledExceptionFilter = true; 00076 OldFilter = SetUnhandledExceptionFilter(LLVMUnhandledExceptionFilter); 00077 SetConsoleCtrlHandler(LLVMConsoleCtrlHandler, TRUE); 00078 00079 // IMPORTANT NOTE: Caller must call LeaveCriticalSection(&CriticalSection) or 00080 // else multi-threading problems will ensue. 00081 } 00082 00083 // RemoveFileOnSignal - The public API 00084 bool sys::RemoveFileOnSignal(const sys::Path &Filename, std::string* ErrMsg) { 00085 RegisterHandler(); 00086 00087 if (CleanupExecuted) { 00088 if (ErrMsg) 00089 *ErrMsg = "Process terminating -- cannot register for removal"; 00090 return true; 00091 } 00092 00093 if (FilesToRemove == NULL) 00094 FilesToRemove = new std::vector<sys::Path>; 00095 00096 FilesToRemove->push_back(Filename); 00097 00098 LeaveCriticalSection(&CriticalSection); 00099 return false; 00100 } 00101 00102 /// PrintStackTraceOnErrorSignal - When an error signal (such as SIBABRT or 00103 /// SIGSEGV) is delivered to the process, print a stack trace and then exit. 00104 void sys::PrintStackTraceOnErrorSignal() { 00105 RegisterHandler(); 00106 LeaveCriticalSection(&CriticalSection); 00107 } 00108 00109 00110 void sys::SetInterruptFunction(void (*IF)()) { 00111 RegisterHandler(); 00112 InterruptFunction = IF; 00113 LeaveCriticalSection(&CriticalSection); 00114 } 00115 00116 00117 /// AddSignalHandler - Add a function to be called when a signal is delivered 00118 /// to the process. The handler can have a cookie passed to it to identify 00119 /// what instance of the handler it is. 00120 void sys::AddSignalHandler(void (*FnPtr)(void *), void *Cookie) { 00121 if (CallBacksToRun == 0) 00122 CallBacksToRun = new std::vector<std::pair<void(*)(void*), void*> >(); 00123 CallBacksToRun->push_back(std::make_pair(FnPtr, Cookie)); 00124 RegisterHandler(); 00125 } 00126 } 00127 00128 static void Cleanup() { 00129 EnterCriticalSection(&CriticalSection); 00130 00131 // Prevent other thread from registering new files and directories for 00132 // removal, should we be executing because of the console handler callback. 00133 CleanupExecuted = true; 00134 00135 // FIXME: open files cannot be deleted. 00136 00137 if (FilesToRemove != NULL) 00138 while (!FilesToRemove->empty()) { 00139 FilesToRemove->back().eraseFromDisk(); 00140 FilesToRemove->pop_back(); 00141 } 00142 00143 if (CallBacksToRun) 00144 for (unsigned i = 0, e = CallBacksToRun->size(); i != e; ++i) 00145 (*CallBacksToRun)[i].first((*CallBacksToRun)[i].second); 00146 00147 LeaveCriticalSection(&CriticalSection); 00148 } 00149 00150 static LONG WINAPI LLVMUnhandledExceptionFilter(LPEXCEPTION_POINTERS ep) { 00151 try { 00152 Cleanup(); 00153 00154 #ifdef _WIN64 00155 // TODO: provide a x64 friendly version of the following 00156 #else 00157 00158 // Initialize the STACKFRAME structure. 00159 STACKFRAME StackFrame; 00160 memset(&StackFrame, 0, sizeof(StackFrame)); 00161 00162 StackFrame.AddrPC.Offset = ep->ContextRecord->Eip; 00163 StackFrame.AddrPC.Mode = AddrModeFlat; 00164 StackFrame.AddrStack.Offset = ep->ContextRecord->Esp; 00165 StackFrame.AddrStack.Mode = AddrModeFlat; 00166 StackFrame.AddrFrame.Offset = ep->ContextRecord->Ebp; 00167 StackFrame.AddrFrame.Mode = AddrModeFlat; 00168 00169 HANDLE hProcess = GetCurrentProcess(); 00170 HANDLE hThread = GetCurrentThread(); 00171 00172 // Initialize the symbol handler. 00173 SymSetOptions(SYMOPT_DEFERRED_LOADS|SYMOPT_LOAD_LINES); 00174 SymInitialize(hProcess, NULL, TRUE); 00175 00176 while (true) { 00177 if (!StackWalk(IMAGE_FILE_MACHINE_I386, hProcess, hThread, &StackFrame, 00178 ep->ContextRecord, NULL, SymFunctionTableAccess, 00179 SymGetModuleBase, NULL)) { 00180 break; 00181 } 00182 00183 if (StackFrame.AddrFrame.Offset == 0) 00184 break; 00185 00186 // Print the PC in hexadecimal. 00187 DWORD PC = StackFrame.AddrPC.Offset; 00188 fprintf(stderr, "%08lX", PC); 00189 00190 // Print the parameters. Assume there are four. 00191 fprintf(stderr, " (0x%08lX 0x%08lX 0x%08lX 0x%08lX)", StackFrame.Params[0], 00192 StackFrame.Params[1], StackFrame.Params[2], StackFrame.Params[3]); 00193 00194 // Verify the PC belongs to a module in this process. 00195 if (!SymGetModuleBase(hProcess, PC)) { 00196 fputs(" <unknown module>\n", stderr); 00197 continue; 00198 } 00199 00200 // Print the symbol name. 00201 char buffer[512]; 00202 IMAGEHLP_SYMBOL *symbol = reinterpret_cast<IMAGEHLP_SYMBOL *>(buffer); 00203 memset(symbol, 0, sizeof(IMAGEHLP_SYMBOL)); 00204 symbol->SizeOfStruct = sizeof(IMAGEHLP_SYMBOL); 00205 symbol->MaxNameLength = 512 - sizeof(IMAGEHLP_SYMBOL); 00206 00207 DWORD dwDisp; 00208 if (!SymGetSymFromAddr(hProcess, PC, &dwDisp, symbol)) { 00209 fputc('\n', stderr); 00210 continue; 00211 } 00212 00213 buffer[511] = 0; 00214 if (dwDisp > 0) 00215 fprintf(stderr, ", %s()+%04lu bytes(s)", symbol->Name, dwDisp); 00216 else 00217 fprintf(stderr, ", %s", symbol->Name); 00218 00219 // Print the source file and line number information. 00220 IMAGEHLP_LINE line; 00221 memset(&line, 0, sizeof(line)); 00222 line.SizeOfStruct = sizeof(line); 00223 if (SymGetLineFromAddr(hProcess, PC, &dwDisp, &line)) { 00224 fprintf(stderr, ", %s, line %lu", line.FileName, line.LineNumber); 00225 if (dwDisp > 0) 00226 fprintf(stderr, "+%04lu byte(s)", dwDisp); 00227 } 00228 00229 fputc('\n', stderr); 00230 } 00231 00232 #endif 00233 00234 } catch (...) { 00235 assert(0 && "Crashed in LLVMUnhandledExceptionFilter"); 00236 } 00237 00238 // Allow dialog box to pop up allowing choice to start debugger. 00239 if (OldFilter) 00240 return (*OldFilter)(ep); 00241 else 00242 return EXCEPTION_CONTINUE_SEARCH; 00243 } 00244 00245 static BOOL WINAPI LLVMConsoleCtrlHandler(DWORD dwCtrlType) { 00246 // We are running in our very own thread, courtesy of Windows. 00247 EnterCriticalSection(&CriticalSection); 00248 Cleanup(); 00249 00250 // If an interrupt function has been set, go and run one it; otherwise, 00251 // the process dies. 00252 void (*IF)() = InterruptFunction; 00253 InterruptFunction = 0; // Don't run it on another CTRL-C. 00254 00255 if (IF) { 00256 // Note: if the interrupt function throws an exception, there is nothing 00257 // to catch it in this thread so it will kill the process. 00258 IF(); // Run it now. 00259 LeaveCriticalSection(&CriticalSection); 00260 return TRUE; // Don't kill the process. 00261 } 00262 00263 // Allow normal processing to take place; i.e., the process dies. 00264 LeaveCriticalSection(&CriticalSection); 00265 return FALSE; 00266 } 00267