blob: a3a393c76e456c0021888e2cbc0d6d1dd07b3051 [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>
Sebastian Redl48fe6352009-03-19 23:26:52 +000017#include <algorithm>
Reid Spencer90b54132004-09-16 15:53:16 +000018
Jeff Cohen23a1cf32005-02-19 03:01:13 +000019#ifdef __MINGW32__
Reid Spencer48fdf912006-06-01 19:03:21 +000020 #include <imagehlp.h>
Reid Spencerf6cbc0f2004-09-23 14:47:10 +000021#else
Reid Spencer48fdf912006-06-01 19:03:21 +000022 #include <dbghelp.h>
Reid Spencerf6cbc0f2004-09-23 14:47:10 +000023#endif
24#include <psapi.h>
Reid Spencer90b54132004-09-16 15:53:16 +000025
Reid Spencer48fdf912006-06-01 19:03:21 +000026#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
Reid Spencer90b54132004-09-16 15:53:16 +000034
35// Forward declare.
36static LONG WINAPI LLVMUnhandledExceptionFilter(LPEXCEPTION_POINTERS ep);
37static BOOL WINAPI LLVMConsoleCtrlHandler(DWORD dwCtrlType);
38
Jeff Cohenee841a12005-08-02 03:04:47 +000039// InterruptFunction - The function to call if ctrl-c is pressed.
40static void (*InterruptFunction)() = 0;
41
Reid Spencerced41102004-09-28 23:58:03 +000042static std::vector<llvm::sys::Path> *FilesToRemove = NULL;
Chris Lattner35033a52009-03-04 21:21:36 +000043static std::vector<std::pair<void(*)(void*), void*> > *CallBacksToRun = 0;
Reid Spencer90b54132004-09-16 15:53:16 +000044static bool RegisteredUnhandledExceptionFilter = false;
Reid Spencer7b60a152004-09-19 05:37:39 +000045static bool CleanupExecuted = false;
Daniel Dunbar43fa15b2009-09-22 16:10:35 +000046#ifdef _MSC_VER
Daniel Dunbardf338842009-09-22 09:50:28 +000047static bool ExitOnUnhandledExceptions = false;
Daniel Dunbar43fa15b2009-09-22 16:10:35 +000048#endif
Reid Spencer7b60a152004-09-19 05:37:39 +000049static PTOP_LEVEL_EXCEPTION_FILTER OldFilter = NULL;
Reid Spencer298d6c12004-09-17 03:02:27 +000050
51// Windows creates a new thread to execute the console handler when an event
52// (such as CTRL/C) occurs. This causes concurrency issues with the above
53// globals which this critical section addresses.
Reid Spencer90b54132004-09-16 15:53:16 +000054static CRITICAL_SECTION CriticalSection;
55
Reid Spencer496c2772004-08-29 19:22:48 +000056namespace llvm {
Reid Spencer496c2772004-08-29 19:22:48 +000057
58//===----------------------------------------------------------------------===//
59//=== WARNING: Implementation here must contain only Win32 specific code
Reid Spencer90b54132004-09-16 15:53:16 +000060//=== and must not be UNIX code
Reid Spencer496c2772004-08-29 19:22:48 +000061//===----------------------------------------------------------------------===//
62
Daniel Dunbar3be2d122009-09-22 15:58:35 +000063#ifdef _MSC_VER
Daniel Dunbardf338842009-09-22 09:50:28 +000064/// CRTReportHook - Function called on a CRT debugging event.
65static int CRTReportHook(int ReportType, char *Message, int *Return) {
66 // Don't cause a DebugBreak() on return.
67 if (Return)
68 *Return = 0;
Reid Spencer90b54132004-09-16 15:53:16 +000069
Daniel Dunbardf338842009-09-22 09:50:28 +000070 switch (ReportType) {
71 default:
72 case _CRT_ASSERT:
73 fprintf(stderr, "CRT assert: %s\n", Message);
74 // FIXME: Is there a way to just crash? Perhaps throw to the unhandled
75 // exception code? Perhaps SetErrorMode() handles this.
76 _exit(3);
77 break;
78 case _CRT_ERROR:
79 fprintf(stderr, "CRT error: %s\n", Message);
80 // FIXME: Is there a way to just crash? Perhaps throw to the unhandled
81 // exception code? Perhaps SetErrorMode() handles this.
82 _exit(3);
83 break;
84 case _CRT_WARN:
85 fprintf(stderr, "CRT warn: %s\n", Message);
86 break;
87 }
88
89 // Don't call _CrtDbgReport.
90 return TRUE;
91}
Daniel Dunbar3be2d122009-09-22 15:58:35 +000092#endif
Daniel Dunbardf338842009-09-22 09:50:28 +000093
94static void RegisterHandler() {
Reid Spencer7b60a152004-09-19 05:37:39 +000095 if (RegisteredUnhandledExceptionFilter) {
Reid Spencer298d6c12004-09-17 03:02:27 +000096 EnterCriticalSection(&CriticalSection);
Reid Spencer90b54132004-09-16 15:53:16 +000097 return;
Reid Spencer298d6c12004-09-17 03:02:27 +000098 }
Reid Spencer90b54132004-09-16 15:53:16 +000099
100 // Now's the time to create the critical section. This is the first time
101 // through here, and there's only one thread.
102 InitializeCriticalSection(&CriticalSection);
103
104 // Enter it immediately. Now if someone hits CTRL/C, the console handler
105 // can't proceed until the globals are updated.
106 EnterCriticalSection(&CriticalSection);
107
108 RegisteredUnhandledExceptionFilter = true;
Reid Spencer7b60a152004-09-19 05:37:39 +0000109 OldFilter = SetUnhandledExceptionFilter(LLVMUnhandledExceptionFilter);
Reid Spencer90b54132004-09-16 15:53:16 +0000110 SetConsoleCtrlHandler(LLVMConsoleCtrlHandler, TRUE);
111
Daniel Dunbardf338842009-09-22 09:50:28 +0000112 // Environment variable to disable any kind of crash dialog.
Daniel Dunbar3be2d122009-09-22 15:58:35 +0000113#ifdef _MSC_VER
Daniel Dunbardf338842009-09-22 09:50:28 +0000114 if (getenv("LLVM_DISABLE_CRT_DEBUG")) {
115 _CrtSetReportHook(CRTReportHook);
Daniel Dunbar3be2d122009-09-22 15:58:35 +0000116 ExitOnUnhandledExceptions = true;
Daniel Dunbardf338842009-09-22 09:50:28 +0000117 }
Daniel Dunbar3be2d122009-09-22 15:58:35 +0000118#endif
Daniel Dunbardf338842009-09-22 09:50:28 +0000119
Reid Spencer90b54132004-09-16 15:53:16 +0000120 // IMPORTANT NOTE: Caller must call LeaveCriticalSection(&CriticalSection) or
121 // else multi-threading problems will ensue.
122}
123
Reid Spencer496c2772004-08-29 19:22:48 +0000124// RemoveFileOnSignal - The public API
Reid Spencer05545752006-08-25 21:37:17 +0000125bool sys::RemoveFileOnSignal(const sys::Path &Filename, std::string* ErrMsg) {
Reid Spencer90b54132004-09-16 15:53:16 +0000126 RegisterHandler();
127
Reid Spencer05545752006-08-25 21:37:17 +0000128 if (CleanupExecuted) {
129 if (ErrMsg)
130 *ErrMsg = "Process terminating -- cannot register for removal";
131 return true;
132 }
Reid Spencer7b60a152004-09-19 05:37:39 +0000133
Reid Spencer90b54132004-09-16 15:53:16 +0000134 if (FilesToRemove == NULL)
Reid Spencerced41102004-09-28 23:58:03 +0000135 FilesToRemove = new std::vector<sys::Path>;
Reid Spencer90b54132004-09-16 15:53:16 +0000136
Reid Spencer98601212004-11-16 06:59:53 +0000137 FilesToRemove->push_back(Filename);
Reid Spencer90b54132004-09-16 15:53:16 +0000138
139 LeaveCriticalSection(&CriticalSection);
Reid Spencer05545752006-08-25 21:37:17 +0000140 return false;
Reid Spencer496c2772004-08-29 19:22:48 +0000141}
142
Reid Spencer496c2772004-08-29 19:22:48 +0000143/// PrintStackTraceOnErrorSignal - When an error signal (such as SIBABRT or
144/// SIGSEGV) is delivered to the process, print a stack trace and then exit.
Reid Spencer90b54132004-09-16 15:53:16 +0000145void sys::PrintStackTraceOnErrorSignal() {
146 RegisterHandler();
147 LeaveCriticalSection(&CriticalSection);
Reid Spencer496c2772004-08-29 19:22:48 +0000148}
149
Chris Lattnerfa8c2922005-08-02 02:14:22 +0000150
151void sys::SetInterruptFunction(void (*IF)()) {
Jeff Cohenee841a12005-08-02 03:04:47 +0000152 RegisterHandler();
Jeff Cohen64fe5842005-08-02 03:26:32 +0000153 InterruptFunction = IF;
Jeff Cohenee841a12005-08-02 03:04:47 +0000154 LeaveCriticalSection(&CriticalSection);
Chris Lattnerfa8c2922005-08-02 02:14:22 +0000155}
Sebastian Redl48fe6352009-03-19 23:26:52 +0000156
157
158/// AddSignalHandler - Add a function to be called when a signal is delivered
159/// to the process. The handler can have a cookie passed to it to identify
160/// what instance of the handler it is.
161void sys::AddSignalHandler(void (*FnPtr)(void *), void *Cookie) {
162 if (CallBacksToRun == 0)
163 CallBacksToRun = new std::vector<std::pair<void(*)(void*), void*> >();
164 CallBacksToRun->push_back(std::make_pair(FnPtr, Cookie));
165 RegisterHandler();
Torok Edwin61633362010-03-31 12:07:16 +0000166 LeaveCriticalSection(&CriticalSection);
Sebastian Redl48fe6352009-03-19 23:26:52 +0000167}
Reid Spencer496c2772004-08-29 19:22:48 +0000168}
169
Reid Spencer90b54132004-09-16 15:53:16 +0000170static void Cleanup() {
171 EnterCriticalSection(&CriticalSection);
172
Reid Spencer7b60a152004-09-19 05:37:39 +0000173 // Prevent other thread from registering new files and directories for
174 // removal, should we be executing because of the console handler callback.
175 CleanupExecuted = true;
176
177 // FIXME: open files cannot be deleted.
178
Reid Spencer90b54132004-09-16 15:53:16 +0000179 if (FilesToRemove != NULL)
180 while (!FilesToRemove->empty()) {
Chris Lattnerac356602009-07-09 16:17:28 +0000181 FilesToRemove->back().eraseFromDisk();
Reid Spencer90b54132004-09-16 15:53:16 +0000182 FilesToRemove->pop_back();
183 }
184
Chris Lattner35033a52009-03-04 21:21:36 +0000185 if (CallBacksToRun)
186 for (unsigned i = 0, e = CallBacksToRun->size(); i != e; ++i)
187 (*CallBacksToRun)[i].first((*CallBacksToRun)[i].second);
Reid Spencer90b54132004-09-16 15:53:16 +0000188
189 LeaveCriticalSection(&CriticalSection);
190}
191
Daniel Dunbarfb89e082010-05-08 02:10:34 +0000192void llvm::sys::RunInterruptHandlers() {
193 Cleanup();
194}
195
Reid Spencer90b54132004-09-16 15:53:16 +0000196static LONG WINAPI LLVMUnhandledExceptionFilter(LPEXCEPTION_POINTERS ep) {
197 try {
198 Cleanup();
Chuck Rose III0ccb9302007-11-21 00:37:56 +0000199
200#ifdef _WIN64
201 // TODO: provide a x64 friendly version of the following
202#else
203
Reid Spencer90b54132004-09-16 15:53:16 +0000204 // Initialize the STACKFRAME structure.
205 STACKFRAME StackFrame;
206 memset(&StackFrame, 0, sizeof(StackFrame));
207
208 StackFrame.AddrPC.Offset = ep->ContextRecord->Eip;
209 StackFrame.AddrPC.Mode = AddrModeFlat;
210 StackFrame.AddrStack.Offset = ep->ContextRecord->Esp;
211 StackFrame.AddrStack.Mode = AddrModeFlat;
212 StackFrame.AddrFrame.Offset = ep->ContextRecord->Ebp;
213 StackFrame.AddrFrame.Mode = AddrModeFlat;
214
215 HANDLE hProcess = GetCurrentProcess();
216 HANDLE hThread = GetCurrentThread();
217
218 // Initialize the symbol handler.
219 SymSetOptions(SYMOPT_DEFERRED_LOADS|SYMOPT_LOAD_LINES);
Reid Spencer7b60a152004-09-19 05:37:39 +0000220 SymInitialize(hProcess, NULL, TRUE);
Reid Spencer90b54132004-09-16 15:53:16 +0000221
222 while (true) {
223 if (!StackWalk(IMAGE_FILE_MACHINE_I386, hProcess, hThread, &StackFrame,
224 ep->ContextRecord, NULL, SymFunctionTableAccess,
225 SymGetModuleBase, NULL)) {
226 break;
227 }
228
229 if (StackFrame.AddrFrame.Offset == 0)
230 break;
231
232 // Print the PC in hexadecimal.
233 DWORD PC = StackFrame.AddrPC.Offset;
Anton Korobeynikov83985d72009-04-21 16:04:56 +0000234 fprintf(stderr, "%08lX", PC);
Reid Spencer90b54132004-09-16 15:53:16 +0000235
236 // Print the parameters. Assume there are four.
Anton Korobeynikov83985d72009-04-21 16:04:56 +0000237 fprintf(stderr, " (0x%08lX 0x%08lX 0x%08lX 0x%08lX)", StackFrame.Params[0],
Reid Spencer90b54132004-09-16 15:53:16 +0000238 StackFrame.Params[1], StackFrame.Params[2], StackFrame.Params[3]);
239
240 // Verify the PC belongs to a module in this process.
241 if (!SymGetModuleBase(hProcess, PC)) {
Reid Spencer7b60a152004-09-19 05:37:39 +0000242 fputs(" <unknown module>\n", stderr);
Reid Spencer90b54132004-09-16 15:53:16 +0000243 continue;
244 }
245
246 // Print the symbol name.
247 char buffer[512];
248 IMAGEHLP_SYMBOL *symbol = reinterpret_cast<IMAGEHLP_SYMBOL *>(buffer);
249 memset(symbol, 0, sizeof(IMAGEHLP_SYMBOL));
250 symbol->SizeOfStruct = sizeof(IMAGEHLP_SYMBOL);
251 symbol->MaxNameLength = 512 - sizeof(IMAGEHLP_SYMBOL);
252
253 DWORD dwDisp;
254 if (!SymGetSymFromAddr(hProcess, PC, &dwDisp, symbol)) {
255 fputc('\n', stderr);
256 continue;
257 }
258
259 buffer[511] = 0;
260 if (dwDisp > 0)
Anton Korobeynikov83985d72009-04-21 16:04:56 +0000261 fprintf(stderr, ", %s()+%04lu bytes(s)", symbol->Name, dwDisp);
Reid Spencer90b54132004-09-16 15:53:16 +0000262 else
263 fprintf(stderr, ", %s", symbol->Name);
264
265 // Print the source file and line number information.
266 IMAGEHLP_LINE line;
267 memset(&line, 0, sizeof(line));
268 line.SizeOfStruct = sizeof(line);
269 if (SymGetLineFromAddr(hProcess, PC, &dwDisp, &line)) {
Anton Korobeynikov83985d72009-04-21 16:04:56 +0000270 fprintf(stderr, ", %s, line %lu", line.FileName, line.LineNumber);
Reid Spencer90b54132004-09-16 15:53:16 +0000271 if (dwDisp > 0)
Anton Korobeynikov83985d72009-04-21 16:04:56 +0000272 fprintf(stderr, "+%04lu byte(s)", dwDisp);
Reid Spencer90b54132004-09-16 15:53:16 +0000273 }
274
275 fputc('\n', stderr);
276 }
Chuck Rose III0ccb9302007-11-21 00:37:56 +0000277
278#endif
279
Reid Spencer7b60a152004-09-19 05:37:39 +0000280 } catch (...) {
Chris Lattner35033a52009-03-04 21:21:36 +0000281 assert(0 && "Crashed in LLVMUnhandledExceptionFilter");
Reid Spencer90b54132004-09-16 15:53:16 +0000282 }
283
Daniel Dunbar3be2d122009-09-22 15:58:35 +0000284#ifdef _MSC_VER
Daniel Dunbardf338842009-09-22 09:50:28 +0000285 if (ExitOnUnhandledExceptions)
286 _exit(-3);
Daniel Dunbar3be2d122009-09-22 15:58:35 +0000287#endif
Daniel Dunbardf338842009-09-22 09:50:28 +0000288
Reid Spencer90b54132004-09-16 15:53:16 +0000289 // Allow dialog box to pop up allowing choice to start debugger.
Reid Spencer7b60a152004-09-19 05:37:39 +0000290 if (OldFilter)
291 return (*OldFilter)(ep);
292 else
293 return EXCEPTION_CONTINUE_SEARCH;
Reid Spencer90b54132004-09-16 15:53:16 +0000294}
295
296static BOOL WINAPI LLVMConsoleCtrlHandler(DWORD dwCtrlType) {
Jeff Cohen64fe5842005-08-02 03:26:32 +0000297 // We are running in our very own thread, courtesy of Windows.
Jeff Cohenee841a12005-08-02 03:04:47 +0000298 EnterCriticalSection(&CriticalSection);
Reid Spencer90b54132004-09-16 15:53:16 +0000299 Cleanup();
300
Jeff Cohenee841a12005-08-02 03:04:47 +0000301 // If an interrupt function has been set, go and run one it; otherwise,
302 // the process dies.
303 void (*IF)() = InterruptFunction;
304 InterruptFunction = 0; // Don't run it on another CTRL-C.
305
306 if (IF) {
Jeff Cohen64fe5842005-08-02 03:26:32 +0000307 // Note: if the interrupt function throws an exception, there is nothing
308 // to catch it in this thread so it will kill the process.
309 IF(); // Run it now.
Jeff Cohenee841a12005-08-02 03:04:47 +0000310 LeaveCriticalSection(&CriticalSection);
311 return TRUE; // Don't kill the process.
312 }
313
Reid Spencer298d6c12004-09-17 03:02:27 +0000314 // Allow normal processing to take place; i.e., the process dies.
Jeff Cohenee841a12005-08-02 03:04:47 +0000315 LeaveCriticalSection(&CriticalSection);
Reid Spencer90b54132004-09-16 15:53:16 +0000316 return FALSE;
317}
318