blob: 14f3f21f02a121b637139564ea94f6b1063f5721 [file] [log] [blame]
Reid Spencer496c2772004-08-29 19:22:48 +00001//===- Win32/Signals.cpp - Win32 Signals Implementation ---------*- C++ -*-===//
Mikhail Glushenkov84ba14f2010-10-21 20:40:39 +00002//
Reid Spencer496c2772004-08-29 19:22:48 +00003// 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.
Mikhail Glushenkov84ba14f2010-10-21 20:40:39 +00007//
Reid Spencer496c2772004-08-29 19:22:48 +00008//===----------------------------------------------------------------------===//
9//
10// This file provides the Win32 specific implementation of the Signals class.
11//
12//===----------------------------------------------------------------------===//
13
Michael J. Spencer1f6efa32010-11-29 18:16:10 +000014#include "Windows.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 Dunbardf338842009-09-22 09:50:28 +000046static bool ExitOnUnhandledExceptions = false;
Reid Spencer7b60a152004-09-19 05:37:39 +000047static PTOP_LEVEL_EXCEPTION_FILTER OldFilter = NULL;
Reid Spencer298d6c12004-09-17 03:02:27 +000048
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.
Reid Spencer90b54132004-09-16 15:53:16 +000052static CRITICAL_SECTION CriticalSection;
53
Reid Spencer496c2772004-08-29 19:22:48 +000054namespace llvm {
Reid Spencer496c2772004-08-29 19:22:48 +000055
56//===----------------------------------------------------------------------===//
Mikhail Glushenkov84ba14f2010-10-21 20:40:39 +000057//=== WARNING: Implementation here must contain only Win32 specific code
Reid Spencer90b54132004-09-16 15:53:16 +000058//=== and must not be UNIX code
Reid Spencer496c2772004-08-29 19:22:48 +000059//===----------------------------------------------------------------------===//
60
Daniel Dunbar3be2d122009-09-22 15:58:35 +000061#ifdef _MSC_VER
Daniel Dunbardf338842009-09-22 09:50:28 +000062/// 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;
Reid Spencer90b54132004-09-16 15:53:16 +000067
Daniel Dunbardf338842009-09-22 09:50:28 +000068 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}
Daniel Dunbar3be2d122009-09-22 15:58:35 +000090#endif
Daniel Dunbardf338842009-09-22 09:50:28 +000091
92static void RegisterHandler() {
Reid Spencer7b60a152004-09-19 05:37:39 +000093 if (RegisteredUnhandledExceptionFilter) {
Reid Spencer298d6c12004-09-17 03:02:27 +000094 EnterCriticalSection(&CriticalSection);
Reid Spencer90b54132004-09-16 15:53:16 +000095 return;
Reid Spencer298d6c12004-09-17 03:02:27 +000096 }
Reid Spencer90b54132004-09-16 15:53:16 +000097
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;
Reid Spencer7b60a152004-09-19 05:37:39 +0000107 OldFilter = SetUnhandledExceptionFilter(LLVMUnhandledExceptionFilter);
Reid Spencer90b54132004-09-16 15:53:16 +0000108 SetConsoleCtrlHandler(LLVMConsoleCtrlHandler, TRUE);
109
Daniel Dunbardf338842009-09-22 09:50:28 +0000110 // Environment variable to disable any kind of crash dialog.
111 if (getenv("LLVM_DISABLE_CRT_DEBUG")) {
NAKAMURA Takumia8bbe702010-10-06 02:15:22 +0000112#ifdef _MSC_VER
Daniel Dunbardf338842009-09-22 09:50:28 +0000113 _CrtSetReportHook(CRTReportHook);
NAKAMURA Takumia8bbe702010-10-06 02:15:22 +0000114#endif
NAKAMURA Takumiac25e442011-01-17 22:41:15 +0000115 SetErrorMode(SEM_FAILCRITICALERRORS |
116 SEM_NOGPFAULTERRORBOX |
117 SEM_NOOPENFILEERRORBOX);
Daniel Dunbar3be2d122009-09-22 15:58:35 +0000118 ExitOnUnhandledExceptions = true;
Daniel Dunbardf338842009-09-22 09:50:28 +0000119 }
120
Reid Spencer90b54132004-09-16 15:53:16 +0000121 // IMPORTANT NOTE: Caller must call LeaveCriticalSection(&CriticalSection) or
122 // else multi-threading problems will ensue.
123}
124
Reid Spencer496c2772004-08-29 19:22:48 +0000125// RemoveFileOnSignal - The public API
Reid Spencer05545752006-08-25 21:37:17 +0000126bool sys::RemoveFileOnSignal(const sys::Path &Filename, std::string* ErrMsg) {
Reid Spencer90b54132004-09-16 15:53:16 +0000127 RegisterHandler();
128
Reid Spencer05545752006-08-25 21:37:17 +0000129 if (CleanupExecuted) {
130 if (ErrMsg)
131 *ErrMsg = "Process terminating -- cannot register for removal";
132 return true;
133 }
Reid Spencer7b60a152004-09-19 05:37:39 +0000134
Reid Spencer90b54132004-09-16 15:53:16 +0000135 if (FilesToRemove == NULL)
Reid Spencerced41102004-09-28 23:58:03 +0000136 FilesToRemove = new std::vector<sys::Path>;
Reid Spencer90b54132004-09-16 15:53:16 +0000137
Reid Spencer98601212004-11-16 06:59:53 +0000138 FilesToRemove->push_back(Filename);
Reid Spencer90b54132004-09-16 15:53:16 +0000139
140 LeaveCriticalSection(&CriticalSection);
Reid Spencer05545752006-08-25 21:37:17 +0000141 return false;
Reid Spencer496c2772004-08-29 19:22:48 +0000142}
143
Dan Gohman41154112010-09-01 14:17:34 +0000144// DontRemoveFileOnSignal - The public API
145void sys::DontRemoveFileOnSignal(const sys::Path &Filename) {
146 if (FilesToRemove == NULL)
147 return;
148
NAKAMURA Takumi2172f3c2010-10-22 01:23:50 +0000149 RegisterHandler();
150
Dan Gohman41154112010-09-01 14:17:34 +0000151 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
Reid Spencer496c2772004-08-29 19:22:48 +0000160/// PrintStackTraceOnErrorSignal - When an error signal (such as SIBABRT or
161/// SIGSEGV) is delivered to the process, print a stack trace and then exit.
Reid Spencer90b54132004-09-16 15:53:16 +0000162void sys::PrintStackTraceOnErrorSignal() {
163 RegisterHandler();
164 LeaveCriticalSection(&CriticalSection);
Reid Spencer496c2772004-08-29 19:22:48 +0000165}
166
Chris Lattnerfa8c2922005-08-02 02:14:22 +0000167
168void sys::SetInterruptFunction(void (*IF)()) {
Jeff Cohenee841a12005-08-02 03:04:47 +0000169 RegisterHandler();
Jeff Cohen64fe5842005-08-02 03:26:32 +0000170 InterruptFunction = IF;
Jeff Cohenee841a12005-08-02 03:04:47 +0000171 LeaveCriticalSection(&CriticalSection);
Chris Lattnerfa8c2922005-08-02 02:14:22 +0000172}
Sebastian Redl48fe6352009-03-19 23:26:52 +0000173
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();
Torok Edwin61633362010-03-31 12:07:16 +0000183 LeaveCriticalSection(&CriticalSection);
Sebastian Redl48fe6352009-03-19 23:26:52 +0000184}
Reid Spencer496c2772004-08-29 19:22:48 +0000185}
186
Reid Spencer90b54132004-09-16 15:53:16 +0000187static void Cleanup() {
188 EnterCriticalSection(&CriticalSection);
189
Reid Spencer7b60a152004-09-19 05:37:39 +0000190 // 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
Reid Spencer90b54132004-09-16 15:53:16 +0000196 if (FilesToRemove != NULL)
197 while (!FilesToRemove->empty()) {
Chris Lattnerac356602009-07-09 16:17:28 +0000198 FilesToRemove->back().eraseFromDisk();
Reid Spencer90b54132004-09-16 15:53:16 +0000199 FilesToRemove->pop_back();
200 }
201
Chris Lattner35033a52009-03-04 21:21:36 +0000202 if (CallBacksToRun)
203 for (unsigned i = 0, e = CallBacksToRun->size(); i != e; ++i)
204 (*CallBacksToRun)[i].first((*CallBacksToRun)[i].second);
Reid Spencer90b54132004-09-16 15:53:16 +0000205
206 LeaveCriticalSection(&CriticalSection);
207}
208
Daniel Dunbarfb89e082010-05-08 02:10:34 +0000209void llvm::sys::RunInterruptHandlers() {
210 Cleanup();
211}
212
Reid Spencer90b54132004-09-16 15:53:16 +0000213static LONG WINAPI LLVMUnhandledExceptionFilter(LPEXCEPTION_POINTERS ep) {
Mikhail Glushenkov11d03f62010-10-27 09:09:04 +0000214 Cleanup();
Mikhail Glushenkov84ba14f2010-10-21 20:40:39 +0000215
Chuck Rose III0ccb9302007-11-21 00:37:56 +0000216#ifdef _WIN64
217 // TODO: provide a x64 friendly version of the following
218#else
Mikhail Glushenkov84ba14f2010-10-21 20:40:39 +0000219
Mikhail Glushenkov6d8ac5a2010-10-28 08:25:44 +0000220 // Initialize the STACKFRAME structure.
221 STACKFRAME StackFrame;
222 memset(&StackFrame, 0, sizeof(StackFrame));
Reid Spencer90b54132004-09-16 15:53:16 +0000223
Mikhail Glushenkov6d8ac5a2010-10-28 08:25:44 +0000224 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;
Reid Spencer90b54132004-09-16 15:53:16 +0000230
Mikhail Glushenkov6d8ac5a2010-10-28 08:25:44 +0000231 HANDLE hProcess = GetCurrentProcess();
232 HANDLE hThread = GetCurrentThread();
Reid Spencer90b54132004-09-16 15:53:16 +0000233
Mikhail Glushenkov6d8ac5a2010-10-28 08:25:44 +0000234 // Initialize the symbol handler.
235 SymSetOptions(SYMOPT_DEFERRED_LOADS|SYMOPT_LOAD_LINES);
236 SymInitialize(hProcess, NULL, TRUE);
Reid Spencer90b54132004-09-16 15:53:16 +0000237
Mikhail Glushenkov6d8ac5a2010-10-28 08:25:44 +0000238 while (true) {
239 if (!StackWalk(IMAGE_FILE_MACHINE_I386, hProcess, hThread, &StackFrame,
240 ep->ContextRecord, NULL, SymFunctionTableAccess,
241 SymGetModuleBase, NULL)) {
242 break;
Reid Spencer90b54132004-09-16 15:53:16 +0000243 }
Chuck Rose III0ccb9302007-11-21 00:37:56 +0000244
Mikhail Glushenkov6d8ac5a2010-10-28 08:25:44 +0000245 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
Chuck Rose III0ccb9302007-11-21 00:37:56 +0000295#endif
296
Daniel Dunbardf338842009-09-22 09:50:28 +0000297 if (ExitOnUnhandledExceptions)
Duncan Sands34727662010-07-12 08:16:59 +0000298 _exit(-3);
Daniel Dunbardf338842009-09-22 09:50:28 +0000299
Reid Spencer90b54132004-09-16 15:53:16 +0000300 // Allow dialog box to pop up allowing choice to start debugger.
Reid Spencer7b60a152004-09-19 05:37:39 +0000301 if (OldFilter)
302 return (*OldFilter)(ep);
303 else
304 return EXCEPTION_CONTINUE_SEARCH;
Reid Spencer90b54132004-09-16 15:53:16 +0000305}
306
307static BOOL WINAPI LLVMConsoleCtrlHandler(DWORD dwCtrlType) {
Jeff Cohen64fe5842005-08-02 03:26:32 +0000308 // We are running in our very own thread, courtesy of Windows.
Jeff Cohenee841a12005-08-02 03:04:47 +0000309 EnterCriticalSection(&CriticalSection);
Reid Spencer90b54132004-09-16 15:53:16 +0000310 Cleanup();
311
Jeff Cohenee841a12005-08-02 03:04:47 +0000312 // 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) {
Jeff Cohen64fe5842005-08-02 03:26:32 +0000318 // 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.
Jeff Cohenee841a12005-08-02 03:04:47 +0000321 LeaveCriticalSection(&CriticalSection);
322 return TRUE; // Don't kill the process.
323 }
324
Reid Spencer298d6c12004-09-17 03:02:27 +0000325 // Allow normal processing to take place; i.e., the process dies.
Jeff Cohenee841a12005-08-02 03:04:47 +0000326 LeaveCriticalSection(&CriticalSection);
Reid Spencer90b54132004-09-16 15:53:16 +0000327 return FALSE;
328}