blob: 1ad176926716422d00efea00af981624e31eab26 [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
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 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
Daniel Dunbar3be2d122009-09-22 15:58:35 +0000115 ExitOnUnhandledExceptions = true;
Daniel Dunbardf338842009-09-22 09:50:28 +0000116 }
117
Reid Spencer90b54132004-09-16 15:53:16 +0000118 // IMPORTANT NOTE: Caller must call LeaveCriticalSection(&CriticalSection) or
119 // else multi-threading problems will ensue.
120}
121
Reid Spencer496c2772004-08-29 19:22:48 +0000122// RemoveFileOnSignal - The public API
Reid Spencer05545752006-08-25 21:37:17 +0000123bool sys::RemoveFileOnSignal(const sys::Path &Filename, std::string* ErrMsg) {
Reid Spencer90b54132004-09-16 15:53:16 +0000124 RegisterHandler();
125
Reid Spencer05545752006-08-25 21:37:17 +0000126 if (CleanupExecuted) {
127 if (ErrMsg)
128 *ErrMsg = "Process terminating -- cannot register for removal";
129 return true;
130 }
Reid Spencer7b60a152004-09-19 05:37:39 +0000131
Reid Spencer90b54132004-09-16 15:53:16 +0000132 if (FilesToRemove == NULL)
Reid Spencerced41102004-09-28 23:58:03 +0000133 FilesToRemove = new std::vector<sys::Path>;
Reid Spencer90b54132004-09-16 15:53:16 +0000134
Reid Spencer98601212004-11-16 06:59:53 +0000135 FilesToRemove->push_back(Filename);
Reid Spencer90b54132004-09-16 15:53:16 +0000136
137 LeaveCriticalSection(&CriticalSection);
Reid Spencer05545752006-08-25 21:37:17 +0000138 return false;
Reid Spencer496c2772004-08-29 19:22:48 +0000139}
140
Dan Gohman41154112010-09-01 14:17:34 +0000141// DontRemoveFileOnSignal - The public API
142void sys::DontRemoveFileOnSignal(const sys::Path &Filename) {
143 if (FilesToRemove == NULL)
144 return;
145
NAKAMURA Takumi2172f3c2010-10-22 01:23:50 +0000146 RegisterHandler();
147
Dan Gohman41154112010-09-01 14:17:34 +0000148 FilesToRemove->push_back(Filename);
149 std::vector<sys::Path>::reverse_iterator I =
150 std::find(FilesToRemove->rbegin(), FilesToRemove->rend(), Filename);
151 if (I != FilesToRemove->rend())
152 FilesToRemove->erase(I.base()-1);
153
154 LeaveCriticalSection(&CriticalSection);
155}
156
Reid Spencer496c2772004-08-29 19:22:48 +0000157/// PrintStackTraceOnErrorSignal - When an error signal (such as SIBABRT or
158/// SIGSEGV) is delivered to the process, print a stack trace and then exit.
Reid Spencer90b54132004-09-16 15:53:16 +0000159void sys::PrintStackTraceOnErrorSignal() {
160 RegisterHandler();
161 LeaveCriticalSection(&CriticalSection);
Reid Spencer496c2772004-08-29 19:22:48 +0000162}
163
Chris Lattnerfa8c2922005-08-02 02:14:22 +0000164
165void sys::SetInterruptFunction(void (*IF)()) {
Jeff Cohenee841a12005-08-02 03:04:47 +0000166 RegisterHandler();
Jeff Cohen64fe5842005-08-02 03:26:32 +0000167 InterruptFunction = IF;
Jeff Cohenee841a12005-08-02 03:04:47 +0000168 LeaveCriticalSection(&CriticalSection);
Chris Lattnerfa8c2922005-08-02 02:14:22 +0000169}
Sebastian Redl48fe6352009-03-19 23:26:52 +0000170
171
172/// AddSignalHandler - Add a function to be called when a signal is delivered
173/// to the process. The handler can have a cookie passed to it to identify
174/// what instance of the handler it is.
175void sys::AddSignalHandler(void (*FnPtr)(void *), void *Cookie) {
176 if (CallBacksToRun == 0)
177 CallBacksToRun = new std::vector<std::pair<void(*)(void*), void*> >();
178 CallBacksToRun->push_back(std::make_pair(FnPtr, Cookie));
179 RegisterHandler();
Torok Edwin61633362010-03-31 12:07:16 +0000180 LeaveCriticalSection(&CriticalSection);
Sebastian Redl48fe6352009-03-19 23:26:52 +0000181}
Reid Spencer496c2772004-08-29 19:22:48 +0000182}
183
Reid Spencer90b54132004-09-16 15:53:16 +0000184static void Cleanup() {
185 EnterCriticalSection(&CriticalSection);
186
Reid Spencer7b60a152004-09-19 05:37:39 +0000187 // Prevent other thread from registering new files and directories for
188 // removal, should we be executing because of the console handler callback.
189 CleanupExecuted = true;
190
191 // FIXME: open files cannot be deleted.
192
Reid Spencer90b54132004-09-16 15:53:16 +0000193 if (FilesToRemove != NULL)
194 while (!FilesToRemove->empty()) {
Chris Lattnerac356602009-07-09 16:17:28 +0000195 FilesToRemove->back().eraseFromDisk();
Reid Spencer90b54132004-09-16 15:53:16 +0000196 FilesToRemove->pop_back();
197 }
198
Chris Lattner35033a52009-03-04 21:21:36 +0000199 if (CallBacksToRun)
200 for (unsigned i = 0, e = CallBacksToRun->size(); i != e; ++i)
201 (*CallBacksToRun)[i].first((*CallBacksToRun)[i].second);
Reid Spencer90b54132004-09-16 15:53:16 +0000202
203 LeaveCriticalSection(&CriticalSection);
204}
205
Daniel Dunbarfb89e082010-05-08 02:10:34 +0000206void llvm::sys::RunInterruptHandlers() {
207 Cleanup();
208}
209
Reid Spencer90b54132004-09-16 15:53:16 +0000210static LONG WINAPI LLVMUnhandledExceptionFilter(LPEXCEPTION_POINTERS ep) {
Mikhail Glushenkov11d03f62010-10-27 09:09:04 +0000211 Cleanup();
Mikhail Glushenkov84ba14f2010-10-21 20:40:39 +0000212
Chuck Rose III0ccb9302007-11-21 00:37:56 +0000213#ifdef _WIN64
214 // TODO: provide a x64 friendly version of the following
215#else
Mikhail Glushenkov84ba14f2010-10-21 20:40:39 +0000216
Mikhail Glushenkov6d8ac5a2010-10-28 08:25:44 +0000217 // Initialize the STACKFRAME structure.
218 STACKFRAME StackFrame;
219 memset(&StackFrame, 0, sizeof(StackFrame));
Reid Spencer90b54132004-09-16 15:53:16 +0000220
Mikhail Glushenkov6d8ac5a2010-10-28 08:25:44 +0000221 StackFrame.AddrPC.Offset = ep->ContextRecord->Eip;
222 StackFrame.AddrPC.Mode = AddrModeFlat;
223 StackFrame.AddrStack.Offset = ep->ContextRecord->Esp;
224 StackFrame.AddrStack.Mode = AddrModeFlat;
225 StackFrame.AddrFrame.Offset = ep->ContextRecord->Ebp;
226 StackFrame.AddrFrame.Mode = AddrModeFlat;
Reid Spencer90b54132004-09-16 15:53:16 +0000227
Mikhail Glushenkov6d8ac5a2010-10-28 08:25:44 +0000228 HANDLE hProcess = GetCurrentProcess();
229 HANDLE hThread = GetCurrentThread();
Reid Spencer90b54132004-09-16 15:53:16 +0000230
Mikhail Glushenkov6d8ac5a2010-10-28 08:25:44 +0000231 // Initialize the symbol handler.
232 SymSetOptions(SYMOPT_DEFERRED_LOADS|SYMOPT_LOAD_LINES);
233 SymInitialize(hProcess, NULL, TRUE);
Reid Spencer90b54132004-09-16 15:53:16 +0000234
Mikhail Glushenkov6d8ac5a2010-10-28 08:25:44 +0000235 while (true) {
236 if (!StackWalk(IMAGE_FILE_MACHINE_I386, hProcess, hThread, &StackFrame,
237 ep->ContextRecord, NULL, SymFunctionTableAccess,
238 SymGetModuleBase, NULL)) {
239 break;
Reid Spencer90b54132004-09-16 15:53:16 +0000240 }
Chuck Rose III0ccb9302007-11-21 00:37:56 +0000241
Mikhail Glushenkov6d8ac5a2010-10-28 08:25:44 +0000242 if (StackFrame.AddrFrame.Offset == 0)
243 break;
244
245 // Print the PC in hexadecimal.
246 DWORD PC = StackFrame.AddrPC.Offset;
247 fprintf(stderr, "%08lX", PC);
248
249 // Print the parameters. Assume there are four.
250 fprintf(stderr, " (0x%08lX 0x%08lX 0x%08lX 0x%08lX)",
251 StackFrame.Params[0],
252 StackFrame.Params[1], StackFrame.Params[2], StackFrame.Params[3]);
253
254 // Verify the PC belongs to a module in this process.
255 if (!SymGetModuleBase(hProcess, PC)) {
256 fputs(" <unknown module>\n", stderr);
257 continue;
258 }
259
260 // Print the symbol name.
261 char buffer[512];
262 IMAGEHLP_SYMBOL *symbol = reinterpret_cast<IMAGEHLP_SYMBOL *>(buffer);
263 memset(symbol, 0, sizeof(IMAGEHLP_SYMBOL));
264 symbol->SizeOfStruct = sizeof(IMAGEHLP_SYMBOL);
265 symbol->MaxNameLength = 512 - sizeof(IMAGEHLP_SYMBOL);
266
267 DWORD dwDisp;
268 if (!SymGetSymFromAddr(hProcess, PC, &dwDisp, symbol)) {
269 fputc('\n', stderr);
270 continue;
271 }
272
273 buffer[511] = 0;
274 if (dwDisp > 0)
275 fprintf(stderr, ", %s()+%04lu bytes(s)", symbol->Name, dwDisp);
276 else
277 fprintf(stderr, ", %s", symbol->Name);
278
279 // Print the source file and line number information.
280 IMAGEHLP_LINE line;
281 memset(&line, 0, sizeof(line));
282 line.SizeOfStruct = sizeof(line);
283 if (SymGetLineFromAddr(hProcess, PC, &dwDisp, &line)) {
284 fprintf(stderr, ", %s, line %lu", line.FileName, line.LineNumber);
285 if (dwDisp > 0)
286 fprintf(stderr, "+%04lu byte(s)", dwDisp);
287 }
288
289 fputc('\n', stderr);
290 }
291
Chuck Rose III0ccb9302007-11-21 00:37:56 +0000292#endif
293
Daniel Dunbardf338842009-09-22 09:50:28 +0000294 if (ExitOnUnhandledExceptions)
Duncan Sands34727662010-07-12 08:16:59 +0000295 _exit(-3);
Daniel Dunbardf338842009-09-22 09:50:28 +0000296
Reid Spencer90b54132004-09-16 15:53:16 +0000297 // Allow dialog box to pop up allowing choice to start debugger.
Reid Spencer7b60a152004-09-19 05:37:39 +0000298 if (OldFilter)
299 return (*OldFilter)(ep);
300 else
301 return EXCEPTION_CONTINUE_SEARCH;
Reid Spencer90b54132004-09-16 15:53:16 +0000302}
303
304static BOOL WINAPI LLVMConsoleCtrlHandler(DWORD dwCtrlType) {
Jeff Cohen64fe5842005-08-02 03:26:32 +0000305 // We are running in our very own thread, courtesy of Windows.
Jeff Cohenee841a12005-08-02 03:04:47 +0000306 EnterCriticalSection(&CriticalSection);
Reid Spencer90b54132004-09-16 15:53:16 +0000307 Cleanup();
308
Jeff Cohenee841a12005-08-02 03:04:47 +0000309 // If an interrupt function has been set, go and run one it; otherwise,
310 // the process dies.
311 void (*IF)() = InterruptFunction;
312 InterruptFunction = 0; // Don't run it on another CTRL-C.
313
314 if (IF) {
Jeff Cohen64fe5842005-08-02 03:26:32 +0000315 // Note: if the interrupt function throws an exception, there is nothing
316 // to catch it in this thread so it will kill the process.
317 IF(); // Run it now.
Jeff Cohenee841a12005-08-02 03:04:47 +0000318 LeaveCriticalSection(&CriticalSection);
319 return TRUE; // Don't kill the process.
320 }
321
Reid Spencer298d6c12004-09-17 03:02:27 +0000322 // Allow normal processing to take place; i.e., the process dies.
Jeff Cohenee841a12005-08-02 03:04:47 +0000323 LeaveCriticalSection(&CriticalSection);
Reid Spencer90b54132004-09-16 15:53:16 +0000324 return FALSE;
325}
326