blob: 02dab86f22d8494426fe7adee1208a86b2b7f03d [file] [log] [blame]
Reid Spencer496c2772004-08-29 19:22:48 +00001//===- Win32/Signals.cpp - Win32 Signals Implementation ---------*- C++ -*-===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner4ee451d2007-12-29 20:36:04 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Reid Spencer496c2772004-08-29 19:22:48 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This file provides the Win32 specific implementation of the Signals class.
11//
12//===----------------------------------------------------------------------===//
13
Reid Spencer90b54132004-09-16 15:53:16 +000014#include "Win32.h"
Reid Spencerced41102004-09-28 23:58:03 +000015#include <stdio.h>
Reid Spencer90b54132004-09-16 15:53:16 +000016#include <vector>
17
Jeff Cohen23a1cf32005-02-19 03:01:13 +000018#ifdef __MINGW32__
Reid Spencer48fdf912006-06-01 19:03:21 +000019 #include <imagehlp.h>
Reid Spencerf6cbc0f2004-09-23 14:47:10 +000020#else
Reid Spencer48fdf912006-06-01 19:03:21 +000021 #include <dbghelp.h>
Reid Spencerf6cbc0f2004-09-23 14:47:10 +000022#endif
23#include <psapi.h>
Reid Spencer90b54132004-09-16 15:53:16 +000024
Reid Spencer48fdf912006-06-01 19:03:21 +000025#ifdef __MINGW32__
26 #if ((HAVE_LIBIMAGEHLP != 1) || (HAVE_LIBPSAPI != 1))
27 #error "libimagehlp.a & libpsapi.a should be present"
28 #endif
29#else
30 #pragma comment(lib, "psapi.lib")
31 #pragma comment(lib, "dbghelp.lib")
32#endif
Reid Spencer90b54132004-09-16 15:53:16 +000033
34// Forward declare.
35static LONG WINAPI LLVMUnhandledExceptionFilter(LPEXCEPTION_POINTERS ep);
36static BOOL WINAPI LLVMConsoleCtrlHandler(DWORD dwCtrlType);
37
Jeff Cohenee841a12005-08-02 03:04:47 +000038// InterruptFunction - The function to call if ctrl-c is pressed.
39static void (*InterruptFunction)() = 0;
40
Reid Spencerced41102004-09-28 23:58:03 +000041static std::vector<llvm::sys::Path> *FilesToRemove = NULL;
Reid Spencer90b54132004-09-16 15:53:16 +000042static std::vector<llvm::sys::Path> *DirectoriesToRemove = NULL;
43static bool RegisteredUnhandledExceptionFilter = false;
Reid Spencer7b60a152004-09-19 05:37:39 +000044static bool CleanupExecuted = false;
45static PTOP_LEVEL_EXCEPTION_FILTER OldFilter = NULL;
Reid Spencer298d6c12004-09-17 03:02:27 +000046
47// Windows creates a new thread to execute the console handler when an event
48// (such as CTRL/C) occurs. This causes concurrency issues with the above
49// globals which this critical section addresses.
Reid Spencer90b54132004-09-16 15:53:16 +000050static CRITICAL_SECTION CriticalSection;
51
Reid Spencer496c2772004-08-29 19:22:48 +000052namespace llvm {
Reid Spencer496c2772004-08-29 19:22:48 +000053
54//===----------------------------------------------------------------------===//
55//=== WARNING: Implementation here must contain only Win32 specific code
Reid Spencer90b54132004-09-16 15:53:16 +000056//=== and must not be UNIX code
Reid Spencer496c2772004-08-29 19:22:48 +000057//===----------------------------------------------------------------------===//
58
Reid Spencer90b54132004-09-16 15:53:16 +000059
60static void RegisterHandler() {
Reid Spencer7b60a152004-09-19 05:37:39 +000061 if (RegisteredUnhandledExceptionFilter) {
Reid Spencer298d6c12004-09-17 03:02:27 +000062 EnterCriticalSection(&CriticalSection);
Reid Spencer90b54132004-09-16 15:53:16 +000063 return;
Reid Spencer298d6c12004-09-17 03:02:27 +000064 }
Reid Spencer90b54132004-09-16 15:53:16 +000065
66 // Now's the time to create the critical section. This is the first time
67 // through here, and there's only one thread.
68 InitializeCriticalSection(&CriticalSection);
69
70 // Enter it immediately. Now if someone hits CTRL/C, the console handler
71 // can't proceed until the globals are updated.
72 EnterCriticalSection(&CriticalSection);
73
74 RegisteredUnhandledExceptionFilter = true;
Reid Spencer7b60a152004-09-19 05:37:39 +000075 OldFilter = SetUnhandledExceptionFilter(LLVMUnhandledExceptionFilter);
Reid Spencer90b54132004-09-16 15:53:16 +000076 SetConsoleCtrlHandler(LLVMConsoleCtrlHandler, TRUE);
77
78 // IMPORTANT NOTE: Caller must call LeaveCriticalSection(&CriticalSection) or
79 // else multi-threading problems will ensue.
80}
81
Reid Spencer496c2772004-08-29 19:22:48 +000082// RemoveFileOnSignal - The public API
Reid Spencer05545752006-08-25 21:37:17 +000083bool sys::RemoveFileOnSignal(const sys::Path &Filename, std::string* ErrMsg) {
Reid Spencer90b54132004-09-16 15:53:16 +000084 RegisterHandler();
85
Reid Spencer05545752006-08-25 21:37:17 +000086 if (CleanupExecuted) {
87 if (ErrMsg)
88 *ErrMsg = "Process terminating -- cannot register for removal";
89 return true;
90 }
Reid Spencer7b60a152004-09-19 05:37:39 +000091
Reid Spencer90b54132004-09-16 15:53:16 +000092 if (FilesToRemove == NULL)
Reid Spencerced41102004-09-28 23:58:03 +000093 FilesToRemove = new std::vector<sys::Path>;
Reid Spencer90b54132004-09-16 15:53:16 +000094
Reid Spencer98601212004-11-16 06:59:53 +000095 FilesToRemove->push_back(Filename);
Reid Spencer90b54132004-09-16 15:53:16 +000096
97 LeaveCriticalSection(&CriticalSection);
Reid Spencer05545752006-08-25 21:37:17 +000098 return false;
Reid Spencer496c2772004-08-29 19:22:48 +000099}
100
101// RemoveDirectoryOnSignal - The public API
Reid Spencer05545752006-08-25 21:37:17 +0000102bool sys::RemoveDirectoryOnSignal(const sys::Path& path, std::string* ErrMsg) {
Chris Lattner89615012006-08-01 17:59:14 +0000103 // Not a directory?
Jeff Cohen31102892007-04-07 20:47:27 +0000104 WIN32_FILE_ATTRIBUTE_DATA fi;
105 if (!GetFileAttributesEx(path.c_str(), GetFileExInfoStandard, &fi)) {
106 MakeErrMsg(ErrMsg, path.toString() + ": can't get status of file");
Reid Spencer8475ec02007-03-29 19:05:44 +0000107 return true;
Jeff Cohen31102892007-04-07 20:47:27 +0000108 }
109
110 if (!(fi.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)) {
Reid Spencer05545752006-08-25 21:37:17 +0000111 if (ErrMsg)
Jeff Cohen31102892007-04-07 20:47:27 +0000112 *ErrMsg = path.toString() + ": not a directory";
Reid Spencer05545752006-08-25 21:37:17 +0000113 return true;
114 }
Chris Lattner89615012006-08-01 17:59:14 +0000115
Reid Spencer90b54132004-09-16 15:53:16 +0000116 RegisterHandler();
117
Reid Spencer05545752006-08-25 21:37:17 +0000118 if (CleanupExecuted) {
119 if (ErrMsg)
120 *ErrMsg = "Process terminating -- cannot register for removal";
121 return true;
122 }
Reid Spencer7b60a152004-09-19 05:37:39 +0000123
Chris Lattner89615012006-08-01 17:59:14 +0000124 if (DirectoriesToRemove == NULL)
125 DirectoriesToRemove = new std::vector<sys::Path>;
126 DirectoriesToRemove->push_back(path);
Reid Spencer90b54132004-09-16 15:53:16 +0000127
128 LeaveCriticalSection(&CriticalSection);
Reid Spencer05545752006-08-25 21:37:17 +0000129 return false;
Reid Spencer496c2772004-08-29 19:22:48 +0000130}
131
132/// PrintStackTraceOnErrorSignal - When an error signal (such as SIBABRT or
133/// SIGSEGV) is delivered to the process, print a stack trace and then exit.
Reid Spencer90b54132004-09-16 15:53:16 +0000134void sys::PrintStackTraceOnErrorSignal() {
135 RegisterHandler();
136 LeaveCriticalSection(&CriticalSection);
Reid Spencer496c2772004-08-29 19:22:48 +0000137}
138
Chris Lattnerfa8c2922005-08-02 02:14:22 +0000139
140void sys::SetInterruptFunction(void (*IF)()) {
Jeff Cohenee841a12005-08-02 03:04:47 +0000141 RegisterHandler();
Jeff Cohen64fe5842005-08-02 03:26:32 +0000142 InterruptFunction = IF;
Jeff Cohenee841a12005-08-02 03:04:47 +0000143 LeaveCriticalSection(&CriticalSection);
Chris Lattnerfa8c2922005-08-02 02:14:22 +0000144}
Reid Spencer496c2772004-08-29 19:22:48 +0000145}
146
Reid Spencer90b54132004-09-16 15:53:16 +0000147static void Cleanup() {
148 EnterCriticalSection(&CriticalSection);
149
Reid Spencer7b60a152004-09-19 05:37:39 +0000150 // Prevent other thread from registering new files and directories for
151 // removal, should we be executing because of the console handler callback.
152 CleanupExecuted = true;
153
154 // FIXME: open files cannot be deleted.
155
Reid Spencer90b54132004-09-16 15:53:16 +0000156 if (FilesToRemove != NULL)
157 while (!FilesToRemove->empty()) {
158 try {
Jeff Cohen8f0e8f22005-07-08 04:50:08 +0000159 FilesToRemove->back().eraseFromDisk();
Reid Spencer90b54132004-09-16 15:53:16 +0000160 } catch (...) {
161 }
162 FilesToRemove->pop_back();
163 }
164
165 if (DirectoriesToRemove != NULL)
166 while (!DirectoriesToRemove->empty()) {
167 try {
Jeff Cohen8f0e8f22005-07-08 04:50:08 +0000168 DirectoriesToRemove->back().eraseFromDisk(true);
Reid Spencer90b54132004-09-16 15:53:16 +0000169 } catch (...) {
170 }
171 DirectoriesToRemove->pop_back();
172 }
173
174 LeaveCriticalSection(&CriticalSection);
175}
176
177static LONG WINAPI LLVMUnhandledExceptionFilter(LPEXCEPTION_POINTERS ep) {
178 try {
179 Cleanup();
Chuck Rose III0ccb9302007-11-21 00:37:56 +0000180
181#ifdef _WIN64
182 // TODO: provide a x64 friendly version of the following
183#else
184
Reid Spencer90b54132004-09-16 15:53:16 +0000185 // Initialize the STACKFRAME structure.
186 STACKFRAME StackFrame;
187 memset(&StackFrame, 0, sizeof(StackFrame));
188
189 StackFrame.AddrPC.Offset = ep->ContextRecord->Eip;
190 StackFrame.AddrPC.Mode = AddrModeFlat;
191 StackFrame.AddrStack.Offset = ep->ContextRecord->Esp;
192 StackFrame.AddrStack.Mode = AddrModeFlat;
193 StackFrame.AddrFrame.Offset = ep->ContextRecord->Ebp;
194 StackFrame.AddrFrame.Mode = AddrModeFlat;
195
196 HANDLE hProcess = GetCurrentProcess();
197 HANDLE hThread = GetCurrentThread();
198
199 // Initialize the symbol handler.
200 SymSetOptions(SYMOPT_DEFERRED_LOADS|SYMOPT_LOAD_LINES);
Reid Spencer7b60a152004-09-19 05:37:39 +0000201 SymInitialize(hProcess, NULL, TRUE);
Reid Spencer90b54132004-09-16 15:53:16 +0000202
203 while (true) {
204 if (!StackWalk(IMAGE_FILE_MACHINE_I386, hProcess, hThread, &StackFrame,
205 ep->ContextRecord, NULL, SymFunctionTableAccess,
206 SymGetModuleBase, NULL)) {
207 break;
208 }
209
210 if (StackFrame.AddrFrame.Offset == 0)
211 break;
212
213 // Print the PC in hexadecimal.
214 DWORD PC = StackFrame.AddrPC.Offset;
Reid Spencer7b60a152004-09-19 05:37:39 +0000215 fprintf(stderr, "%08X", PC);
Reid Spencer90b54132004-09-16 15:53:16 +0000216
217 // Print the parameters. Assume there are four.
218 fprintf(stderr, " (0x%08X 0x%08X 0x%08X 0x%08X)", StackFrame.Params[0],
219 StackFrame.Params[1], StackFrame.Params[2], StackFrame.Params[3]);
220
221 // Verify the PC belongs to a module in this process.
222 if (!SymGetModuleBase(hProcess, PC)) {
Reid Spencer7b60a152004-09-19 05:37:39 +0000223 fputs(" <unknown module>\n", stderr);
Reid Spencer90b54132004-09-16 15:53:16 +0000224 continue;
225 }
226
227 // Print the symbol name.
228 char buffer[512];
229 IMAGEHLP_SYMBOL *symbol = reinterpret_cast<IMAGEHLP_SYMBOL *>(buffer);
230 memset(symbol, 0, sizeof(IMAGEHLP_SYMBOL));
231 symbol->SizeOfStruct = sizeof(IMAGEHLP_SYMBOL);
232 symbol->MaxNameLength = 512 - sizeof(IMAGEHLP_SYMBOL);
233
234 DWORD dwDisp;
235 if (!SymGetSymFromAddr(hProcess, PC, &dwDisp, symbol)) {
236 fputc('\n', stderr);
237 continue;
238 }
239
240 buffer[511] = 0;
241 if (dwDisp > 0)
242 fprintf(stderr, ", %s()+%04d bytes(s)", symbol->Name, dwDisp);
243 else
244 fprintf(stderr, ", %s", symbol->Name);
245
246 // Print the source file and line number information.
247 IMAGEHLP_LINE line;
248 memset(&line, 0, sizeof(line));
249 line.SizeOfStruct = sizeof(line);
250 if (SymGetLineFromAddr(hProcess, PC, &dwDisp, &line)) {
251 fprintf(stderr, ", %s, line %d", line.FileName, line.LineNumber);
252 if (dwDisp > 0)
253 fprintf(stderr, "+%04d byte(s)", dwDisp);
254 }
255
256 fputc('\n', stderr);
257 }
Chuck Rose III0ccb9302007-11-21 00:37:56 +0000258
259#endif
260
Reid Spencer7b60a152004-09-19 05:37:39 +0000261 } catch (...) {
Reid Spencer90b54132004-09-16 15:53:16 +0000262 assert(!"Crashed in LLVMUnhandledExceptionFilter");
263 }
264
265 // Allow dialog box to pop up allowing choice to start debugger.
Reid Spencer7b60a152004-09-19 05:37:39 +0000266 if (OldFilter)
267 return (*OldFilter)(ep);
268 else
269 return EXCEPTION_CONTINUE_SEARCH;
Reid Spencer90b54132004-09-16 15:53:16 +0000270}
271
272static BOOL WINAPI LLVMConsoleCtrlHandler(DWORD dwCtrlType) {
Jeff Cohen64fe5842005-08-02 03:26:32 +0000273 // We are running in our very own thread, courtesy of Windows.
Jeff Cohenee841a12005-08-02 03:04:47 +0000274 EnterCriticalSection(&CriticalSection);
Reid Spencer90b54132004-09-16 15:53:16 +0000275 Cleanup();
276
Jeff Cohenee841a12005-08-02 03:04:47 +0000277 // If an interrupt function has been set, go and run one it; otherwise,
278 // the process dies.
279 void (*IF)() = InterruptFunction;
280 InterruptFunction = 0; // Don't run it on another CTRL-C.
281
282 if (IF) {
Jeff Cohen64fe5842005-08-02 03:26:32 +0000283 // Note: if the interrupt function throws an exception, there is nothing
284 // to catch it in this thread so it will kill the process.
285 IF(); // Run it now.
Jeff Cohenee841a12005-08-02 03:04:47 +0000286 LeaveCriticalSection(&CriticalSection);
287 return TRUE; // Don't kill the process.
288 }
289
Reid Spencer298d6c12004-09-17 03:02:27 +0000290 // Allow normal processing to take place; i.e., the process dies.
Jeff Cohenee841a12005-08-02 03:04:47 +0000291 LeaveCriticalSection(&CriticalSection);
Reid Spencer90b54132004-09-16 15:53:16 +0000292 return FALSE;
293}
294