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 PTOP_LEVEL_EXCEPTION_FILTER OldFilter = NULL;
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;
55 //===----------------------------------------------------------------------===//
56 //=== WARNING: Implementation here must contain only Win32 specific code
57 //=== and must not be UNIX code
58 //===----------------------------------------------------------------------===//
61 static void RegisterHandler() {
62 if (RegisteredUnhandledExceptionFilter) {
63 EnterCriticalSection(&CriticalSection);
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);
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);
75 RegisteredUnhandledExceptionFilter = true;
76 OldFilter = SetUnhandledExceptionFilter(LLVMUnhandledExceptionFilter);
77 SetConsoleCtrlHandler(LLVMConsoleCtrlHandler, TRUE);
79 // IMPORTANT NOTE: Caller must call LeaveCriticalSection(&CriticalSection) or
80 // else multi-threading problems will ensue.
83 // RemoveFileOnSignal - The public API
84 bool sys::RemoveFileOnSignal(const sys::Path &Filename, std::string* ErrMsg) {
87 if (CleanupExecuted) {
89 *ErrMsg = "Process terminating -- cannot register for removal";
93 if (FilesToRemove == NULL)
94 FilesToRemove = new std::vector<sys::Path>;
96 FilesToRemove->push_back(Filename);
98 LeaveCriticalSection(&CriticalSection);
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() {
106 LeaveCriticalSection(&CriticalSection);
110 void sys::SetInterruptFunction(void (*IF)()) {
112 InterruptFunction = IF;
113 LeaveCriticalSection(&CriticalSection);
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));
128 static void Cleanup() {
129 EnterCriticalSection(&CriticalSection);
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;
135 // FIXME: open files cannot be deleted.
137 if (FilesToRemove != NULL)
138 while (!FilesToRemove->empty()) {
139 FilesToRemove->back().eraseFromDisk();
140 FilesToRemove->pop_back();
144 for (unsigned i = 0, e = CallBacksToRun->size(); i != e; ++i)
145 (*CallBacksToRun)[i].first((*CallBacksToRun)[i].second);
147 LeaveCriticalSection(&CriticalSection);
150 static LONG WINAPI LLVMUnhandledExceptionFilter(LPEXCEPTION_POINTERS ep) {
155 // TODO: provide a x64 friendly version of the following
158 // Initialize the STACKFRAME structure.
159 STACKFRAME StackFrame;
160 memset(&StackFrame, 0, sizeof(StackFrame));
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;
169 HANDLE hProcess = GetCurrentProcess();
170 HANDLE hThread = GetCurrentThread();
172 // Initialize the symbol handler.
173 SymSetOptions(SYMOPT_DEFERRED_LOADS|SYMOPT_LOAD_LINES);
174 SymInitialize(hProcess, NULL, TRUE);
177 if (!StackWalk(IMAGE_FILE_MACHINE_I386, hProcess, hThread, &StackFrame,
178 ep->ContextRecord, NULL, SymFunctionTableAccess,
179 SymGetModuleBase, NULL)) {
183 if (StackFrame.AddrFrame.Offset == 0)
186 // Print the PC in hexadecimal.
187 DWORD PC = StackFrame.AddrPC.Offset;
188 fprintf(stderr, "%08lX", PC);
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]);
194 // Verify the PC belongs to a module in this process.
195 if (!SymGetModuleBase(hProcess, PC)) {
196 fputs(" <unknown module>\n", stderr);
200 // Print the symbol name.
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);
208 if (!SymGetSymFromAddr(hProcess, PC, &dwDisp, symbol)) {
215 fprintf(stderr, ", %s()+%04lu bytes(s)", symbol->Name, dwDisp);
217 fprintf(stderr, ", %s", symbol->Name);
219 // Print the source file and line number information.
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);
226 fprintf(stderr, "+%04lu byte(s)", dwDisp);
235 assert(0 && "Crashed in LLVMUnhandledExceptionFilter");
238 // Allow dialog box to pop up allowing choice to start debugger.
240 return (*OldFilter)(ep);
242 return EXCEPTION_CONTINUE_SEARCH;
245 static BOOL WINAPI LLVMConsoleCtrlHandler(DWORD dwCtrlType) {
246 // We are running in our very own thread, courtesy of Windows.
247 EnterCriticalSection(&CriticalSection);
250 // If an interrupt function has been set, go and run one it; otherwise,
252 void (*IF)() = InterruptFunction;
253 InterruptFunction = 0; // Don't run it on another CTRL-C.
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.
259 LeaveCriticalSection(&CriticalSection);
260 return TRUE; // Don't kill the process.
263 // Allow normal processing to take place; i.e., the process dies.
264 LeaveCriticalSection(&CriticalSection);