1 //===- KillTheDoctor - Prevent Dr. Watson from stopping tests ---*- 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 program provides an extremely hacky way to stop Dr. Watson from starting
11 // due to unhandled exceptions in child processes.
13 // This simply starts the program named in the first positional argument with
14 // the arguments following it under a debugger. All this debugger does is catch
15 // any unhandled exceptions thrown in the child process and close the program
16 // (and hopefully tells someone about it).
18 // This also provides another really hacky method to prevent assert dialog boxes
19 // from popping up. When --no-user32 is passed, if any process loads user32.dll,
20 // we assume it is trying to call MessageBoxEx and terminate it. The proper way
21 // to do this would be to actually set a break point, but there's quite a bit
22 // of code involved to get the address of MessageBoxEx in the remote process's
23 // address space due to Address space layout randomization (ASLR). This can be
24 // added if it's ever actually needed.
26 // If the subprocess exits for any reason other than successful termination, -1
27 // is returned. If the process exits normally the value it returned is returned.
31 //===----------------------------------------------------------------------===//
33 #include "llvm/ADT/STLExtras.h"
34 #include "llvm/ADT/SmallString.h"
35 #include "llvm/ADT/SmallVector.h"
36 #include "llvm/ADT/StringExtras.h"
37 #include "llvm/ADT/StringRef.h"
38 #include "llvm/ADT/Twine.h"
39 #include "llvm/Support/CommandLine.h"
40 #include "llvm/Support/ManagedStatic.h"
41 #include "llvm/Support/PrettyStackTrace.h"
42 #include "llvm/Support/Signals.h"
43 #include "llvm/Support/WindowsError.h"
44 #include "llvm/Support/raw_ostream.h"
45 #include "llvm/Support/type_traits.h"
51 #include <system_error>
53 // These includes must be last.
64 cl::opt<std::string> ProgramToRun(cl::Positional,
65 cl::desc("<program to run>"));
66 cl::list<std::string> Argv(cl::ConsumeAfter,
67 cl::desc("<program arguments>..."));
68 cl::opt<bool> TraceExecution("x",
69 cl::desc("Print detailed output about what is being run to stderr."));
70 cl::opt<unsigned> Timeout("t", cl::init(0),
71 cl::desc("Set maximum runtime in seconds. Defaults to infinite."));
72 cl::opt<bool> NoUser32("no-user32",
73 cl::desc("Terminate process if it loads user32.dll."));
77 template <typename HandleType>
79 typedef typename HandleType::handle_type handle_type;
85 : Handle(HandleType::GetInvalidHandle()) {}
87 explicit ScopedHandle(handle_type handle)
91 HandleType::Destruct(Handle);
94 ScopedHandle& operator=(handle_type handle) {
95 // Cleanup current handle.
96 if (!HandleType::isValid(Handle))
97 HandleType::Destruct(Handle);
102 operator bool() const {
103 return HandleType::isValid(Handle);
106 operator handle_type() {
111 // This implements the most common handle in the Windows API.
112 struct CommonHandle {
113 typedef HANDLE handle_type;
115 static handle_type GetInvalidHandle() {
116 return INVALID_HANDLE_VALUE;
119 static void Destruct(handle_type Handle) {
120 ::CloseHandle(Handle);
123 static bool isValid(handle_type Handle) {
124 return Handle != GetInvalidHandle();
128 struct FileMappingHandle {
129 typedef HANDLE handle_type;
131 static handle_type GetInvalidHandle() {
135 static void Destruct(handle_type Handle) {
136 ::CloseHandle(Handle);
139 static bool isValid(handle_type Handle) {
140 return Handle != GetInvalidHandle();
144 struct MappedViewOfFileHandle {
145 typedef LPVOID handle_type;
147 static handle_type GetInvalidHandle() {
151 static void Destruct(handle_type Handle) {
152 ::UnmapViewOfFile(Handle);
155 static bool isValid(handle_type Handle) {
156 return Handle != GetInvalidHandle();
160 struct ProcessHandle : CommonHandle {};
161 struct ThreadHandle : CommonHandle {};
162 struct TokenHandle : CommonHandle {};
163 struct FileHandle : CommonHandle {};
165 typedef ScopedHandle<FileMappingHandle> FileMappingScopedHandle;
166 typedef ScopedHandle<MappedViewOfFileHandle> MappedViewOfFileScopedHandle;
167 typedef ScopedHandle<ProcessHandle> ProcessScopedHandle;
168 typedef ScopedHandle<ThreadHandle> ThreadScopedHandle;
169 typedef ScopedHandle<TokenHandle> TokenScopedHandle;
170 typedef ScopedHandle<FileHandle> FileScopedHandle;
173 static std::error_code windows_error(DWORD E) { return mapWindowsError(E); }
175 static std::error_code GetFileNameFromHandle(HANDLE FileHandle,
177 char Filename[MAX_PATH+1];
178 bool Success = false;
181 // Get the file size.
182 LARGE_INTEGER FileSize;
183 Success = ::GetFileSizeEx(FileHandle, &FileSize);
186 return windows_error(::GetLastError());
188 // Create a file mapping object.
189 FileMappingScopedHandle FileMapping(
190 ::CreateFileMappingA(FileHandle,
198 return windows_error(::GetLastError());
200 // Create a file mapping to get the file name.
201 MappedViewOfFileScopedHandle MappedFile(
202 ::MapViewOfFile(FileMapping, FILE_MAP_READ, 0, 0, 1));
205 return windows_error(::GetLastError());
207 Success = ::GetMappedFileNameA(::GetCurrentProcess(),
210 array_lengthof(Filename) - 1);
213 return windows_error(::GetLastError());
216 return std::error_code();
220 /// @brief Find program using shell lookup rules.
221 /// @param Program This is either an absolute path, relative path, or simple a
222 /// program name. Look in PATH for any programs that match. If no
223 /// extension is present, try all extensions in PATHEXT.
224 /// @return If ec == errc::success, The absolute path to the program. Otherwise
225 /// the return value is undefined.
226 static std::string FindProgram(const std::string &Program,
227 std::error_code &ec) {
228 char PathName[MAX_PATH + 1];
229 typedef SmallVector<StringRef, 12> pathext_t;
231 // Check for the program without an extension (in case it already has one).
232 pathext.push_back("");
233 SplitString(std::getenv("PATHEXT"), pathext, ";");
235 for (pathext_t::iterator i = pathext.begin(), e = pathext.end(); i != e; ++i){
237 for (std::size_t ii = 0, e = i->size(); ii != e; ++ii)
238 ext.push_back(::tolower((*i)[ii]));
239 LPCSTR Extension = NULL;
240 if (ext.size() && ext[0] == '.')
241 Extension = ext.c_str();
242 DWORD length = ::SearchPathA(NULL,
245 array_lengthof(PathName),
249 ec = windows_error(::GetLastError());
250 else if (length > array_lengthof(PathName)) {
251 // This may have been the file, return with error.
252 ec = windows_error(ERROR_BUFFER_OVERFLOW);
255 // We found the path! Return it.
256 ec = std::error_code();
261 // Make sure PathName is valid.
262 PathName[MAX_PATH] = 0;
266 static StringRef ExceptionCodeToString(DWORD ExceptionCode) {
267 switch(ExceptionCode) {
268 case EXCEPTION_ACCESS_VIOLATION: return "EXCEPTION_ACCESS_VIOLATION";
269 case EXCEPTION_ARRAY_BOUNDS_EXCEEDED:
270 return "EXCEPTION_ARRAY_BOUNDS_EXCEEDED";
271 case EXCEPTION_BREAKPOINT: return "EXCEPTION_BREAKPOINT";
272 case EXCEPTION_DATATYPE_MISALIGNMENT:
273 return "EXCEPTION_DATATYPE_MISALIGNMENT";
274 case EXCEPTION_FLT_DENORMAL_OPERAND: return "EXCEPTION_FLT_DENORMAL_OPERAND";
275 case EXCEPTION_FLT_DIVIDE_BY_ZERO: return "EXCEPTION_FLT_DIVIDE_BY_ZERO";
276 case EXCEPTION_FLT_INEXACT_RESULT: return "EXCEPTION_FLT_INEXACT_RESULT";
277 case EXCEPTION_FLT_INVALID_OPERATION:
278 return "EXCEPTION_FLT_INVALID_OPERATION";
279 case EXCEPTION_FLT_OVERFLOW: return "EXCEPTION_FLT_OVERFLOW";
280 case EXCEPTION_FLT_STACK_CHECK: return "EXCEPTION_FLT_STACK_CHECK";
281 case EXCEPTION_FLT_UNDERFLOW: return "EXCEPTION_FLT_UNDERFLOW";
282 case EXCEPTION_ILLEGAL_INSTRUCTION: return "EXCEPTION_ILLEGAL_INSTRUCTION";
283 case EXCEPTION_IN_PAGE_ERROR: return "EXCEPTION_IN_PAGE_ERROR";
284 case EXCEPTION_INT_DIVIDE_BY_ZERO: return "EXCEPTION_INT_DIVIDE_BY_ZERO";
285 case EXCEPTION_INT_OVERFLOW: return "EXCEPTION_INT_OVERFLOW";
286 case EXCEPTION_INVALID_DISPOSITION: return "EXCEPTION_INVALID_DISPOSITION";
287 case EXCEPTION_NONCONTINUABLE_EXCEPTION:
288 return "EXCEPTION_NONCONTINUABLE_EXCEPTION";
289 case EXCEPTION_PRIV_INSTRUCTION: return "EXCEPTION_PRIV_INSTRUCTION";
290 case EXCEPTION_SINGLE_STEP: return "EXCEPTION_SINGLE_STEP";
291 case EXCEPTION_STACK_OVERFLOW: return "EXCEPTION_STACK_OVERFLOW";
292 default: return "<unknown>";
296 int main(int argc, char **argv) {
297 // Print a stack trace if we signal out.
298 sys::PrintStackTraceOnErrorSignal();
299 PrettyStackTraceProgram X(argc, argv);
300 llvm_shutdown_obj Y; // Call llvm_shutdown() on exit.
304 cl::ParseCommandLineOptions(argc, argv, "Dr. Watson Assassin.\n");
305 if (ProgramToRun.size() == 0) {
306 cl::PrintHelpMessage();
310 if (Timeout > std::numeric_limits<uint32_t>::max() / 1000) {
311 errs() << ToolName << ": Timeout value too large, must be less than: "
312 << std::numeric_limits<uint32_t>::max() / 1000
317 std::string CommandLine(ProgramToRun);
320 ProgramToRun = FindProgram(ProgramToRun, ec);
322 errs() << ToolName << ": Failed to find program: '" << CommandLine
323 << "': " << ec.message() << '\n';
328 errs() << ToolName << ": Found Program: " << ProgramToRun << '\n';
330 for (std::vector<std::string>::iterator i = Argv.begin(),
333 CommandLine.push_back(' ');
334 CommandLine.append(*i);
338 errs() << ToolName << ": Program Image Path: " << ProgramToRun << '\n'
339 << ToolName << ": Command Line: " << CommandLine << '\n';
341 STARTUPINFO StartupInfo;
342 PROCESS_INFORMATION ProcessInfo;
343 std::memset(&StartupInfo, 0, sizeof(StartupInfo));
344 StartupInfo.cb = sizeof(StartupInfo);
345 std::memset(&ProcessInfo, 0, sizeof(ProcessInfo));
347 // Set error mode to not display any message boxes. The child process inherits
349 ::SetErrorMode(SEM_FAILCRITICALERRORS | SEM_NOGPFAULTERRORBOX);
350 ::_set_error_mode(_OUT_TO_STDERR);
352 BOOL success = ::CreateProcessA(ProgramToRun.c_str(),
353 LPSTR(CommandLine.c_str()),
363 errs() << ToolName << ": Failed to run program: '" << ProgramToRun << "': "
364 << std::error_code(windows_error(::GetLastError())).message()
369 // Make sure ::CloseHandle is called on exit.
370 std::map<DWORD, HANDLE> ProcessIDToHandle;
372 DEBUG_EVENT DebugEvent;
373 std::memset(&DebugEvent, 0, sizeof(DebugEvent));
374 DWORD dwContinueStatus = DBG_CONTINUE;
376 // Run the program under the debugger until either it exits, or throws an
379 errs() << ToolName << ": Debugging...\n";
382 DWORD TimeLeft = INFINITE;
384 FILETIME CreationTime, ExitTime, KernelTime, UserTime;
386 success = ::GetProcessTimes(ProcessInfo.hProcess,
392 ec = windows_error(::GetLastError());
394 errs() << ToolName << ": Failed to get process times: "
395 << ec.message() << '\n';
398 a.LowPart = KernelTime.dwLowDateTime;
399 a.HighPart = KernelTime.dwHighDateTime;
400 b.LowPart = UserTime.dwLowDateTime;
401 b.HighPart = UserTime.dwHighDateTime;
402 // Convert 100-nanosecond units to milliseconds.
403 uint64_t TotalTimeMiliseconds = (a.QuadPart + b.QuadPart) / 10000;
404 // Handle the case where the process has been running for more than 49
406 if (TotalTimeMiliseconds > std::numeric_limits<uint32_t>::max()) {
407 errs() << ToolName << ": Timeout Failed: Process has been running for"
408 "more than 49 days.\n";
412 // We check with > instead of using Timeleft because if
413 // TotalTimeMiliseconds is greater than Timeout * 1000, TimeLeft would
415 if (TotalTimeMiliseconds > (Timeout * 1000)) {
416 errs() << ToolName << ": Process timed out.\n";
417 ::TerminateProcess(ProcessInfo.hProcess, -1);
418 // Otherwise other stuff starts failing...
422 TimeLeft = (Timeout * 1000) - static_cast<uint32_t>(TotalTimeMiliseconds);
424 success = WaitForDebugEvent(&DebugEvent, TimeLeft);
427 DWORD LastError = ::GetLastError();
428 ec = windows_error(LastError);
430 if (LastError == ERROR_SEM_TIMEOUT || LastError == WSAETIMEDOUT) {
431 errs() << ToolName << ": Process timed out.\n";
432 ::TerminateProcess(ProcessInfo.hProcess, -1);
433 // Otherwise other stuff starts failing...
437 errs() << ToolName << ": Failed to wait for debug event in program: '"
438 << ProgramToRun << "': " << ec.message() << '\n';
442 switch(DebugEvent.dwDebugEventCode) {
443 case CREATE_PROCESS_DEBUG_EVENT:
444 // Make sure we remove the handle on exit.
446 errs() << ToolName << ": Debug Event: CREATE_PROCESS_DEBUG_EVENT\n";
447 ProcessIDToHandle[DebugEvent.dwProcessId] =
448 DebugEvent.u.CreateProcessInfo.hProcess;
449 ::CloseHandle(DebugEvent.u.CreateProcessInfo.hFile);
451 case EXIT_PROCESS_DEBUG_EVENT: {
453 errs() << ToolName << ": Debug Event: EXIT_PROCESS_DEBUG_EVENT\n";
455 // If this is the process we originally created, exit with its exit
457 if (DebugEvent.dwProcessId == ProcessInfo.dwProcessId)
458 return DebugEvent.u.ExitProcess.dwExitCode;
460 // Otherwise cleanup any resources we have for it.
461 std::map<DWORD, HANDLE>::iterator ExitingProcess =
462 ProcessIDToHandle.find(DebugEvent.dwProcessId);
463 if (ExitingProcess == ProcessIDToHandle.end()) {
464 errs() << ToolName << ": Got unknown process id!\n";
467 ::CloseHandle(ExitingProcess->second);
468 ProcessIDToHandle.erase(ExitingProcess);
471 case CREATE_THREAD_DEBUG_EVENT:
472 ::CloseHandle(DebugEvent.u.CreateThread.hThread);
474 case LOAD_DLL_DEBUG_EVENT: {
475 // Cleanup the file handle.
476 FileScopedHandle DLLFile(DebugEvent.u.LoadDll.hFile);
478 ec = GetFileNameFromHandle(DLLFile, DLLName);
480 DLLName = "<failed to get file name from file handle> : ";
481 DLLName += ec.message();
483 if (TraceExecution) {
484 errs() << ToolName << ": Debug Event: LOAD_DLL_DEBUG_EVENT\n";
485 errs().indent(ToolName.size()) << ": DLL Name : " << DLLName << '\n';
488 if (NoUser32 && sys::path::stem(DLLName) == "user32") {
489 // Program is loading user32.dll, in the applications we are testing,
490 // this only happens if an assert has fired. By now the message has
491 // already been printed, so simply close the program.
492 errs() << ToolName << ": user32.dll loaded!\n";
493 errs().indent(ToolName.size())
494 << ": This probably means that assert was called. Closing "
495 "program to prevent message box from popping up.\n";
496 dwContinueStatus = DBG_CONTINUE;
497 ::TerminateProcess(ProcessIDToHandle[DebugEvent.dwProcessId], -1);
502 case EXCEPTION_DEBUG_EVENT: {
503 // Close the application if this exception will not be handled by the
504 // child application.
506 errs() << ToolName << ": Debug Event: EXCEPTION_DEBUG_EVENT\n";
508 EXCEPTION_DEBUG_INFO &Exception = DebugEvent.u.Exception;
509 if (Exception.dwFirstChance > 0) {
510 if (TraceExecution) {
511 errs().indent(ToolName.size()) << ": Debug Info : ";
512 errs() << "First chance exception at "
513 << Exception.ExceptionRecord.ExceptionAddress
514 << ", exception code: "
515 << ExceptionCodeToString(
516 Exception.ExceptionRecord.ExceptionCode)
517 << " (" << Exception.ExceptionRecord.ExceptionCode << ")\n";
519 dwContinueStatus = DBG_EXCEPTION_NOT_HANDLED;
521 errs() << ToolName << ": Unhandled exception in: " << ProgramToRun
523 errs().indent(ToolName.size()) << ": location: ";
524 errs() << Exception.ExceptionRecord.ExceptionAddress
525 << ", exception code: "
526 << ExceptionCodeToString(
527 Exception.ExceptionRecord.ExceptionCode)
528 << " (" << Exception.ExceptionRecord.ExceptionCode
530 dwContinueStatus = DBG_CONTINUE;
531 ::TerminateProcess(ProcessIDToHandle[DebugEvent.dwProcessId], -1);
539 errs() << ToolName << ": Debug Event: <unknown>\n";
543 success = ContinueDebugEvent(DebugEvent.dwProcessId,
544 DebugEvent.dwThreadId,
547 ec = windows_error(::GetLastError());
548 errs() << ToolName << ": Failed to continue debugging program: '"
549 << ProgramToRun << "': " << ec.message() << '\n';
553 dwContinueStatus = DBG_CONTINUE;
556 assert(0 && "Fell out of debug loop. This shouldn't be possible!");