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/raw_ostream.h"
44 #include "llvm/Support/system_error.h"
45 #include "llvm/Support/type_traits.h"
53 // This includes must be last.
63 cl::opt<std::string> ProgramToRun(cl::Positional,
64 cl::desc("<program to run>"));
65 cl::list<std::string> Argv(cl::ConsumeAfter,
66 cl::desc("<program arguments>..."));
67 cl::opt<bool> TraceExecution("x",
68 cl::desc("Print detailed output about what is being run to stderr."));
69 cl::opt<unsigned> Timeout("t", cl::init(0),
70 cl::desc("Set maximum runtime in seconds. Defaults to infinite."));
71 cl::opt<bool> NoUser32("no-user32",
72 cl::desc("Terminate process if it loads user32.dll."));
76 template <typename HandleType>
78 typedef typename HandleType::handle_type handle_type;
84 : Handle(HandleType::GetInvalidHandle()) {}
86 explicit ScopedHandle(handle_type handle)
90 HandleType::Destruct(Handle);
93 ScopedHandle& operator=(handle_type handle) {
94 // Cleanup current handle.
95 if (!HandleType::isValid(Handle))
96 HandleType::Destruct(Handle);
101 operator bool() const {
102 return HandleType::isValid(Handle);
105 operator handle_type() {
110 // This implements the most common handle in the Windows API.
111 struct CommonHandle {
112 typedef HANDLE handle_type;
114 static handle_type GetInvalidHandle() {
115 return INVALID_HANDLE_VALUE;
118 static void Destruct(handle_type Handle) {
119 ::CloseHandle(Handle);
122 static bool isValid(handle_type Handle) {
123 return Handle != GetInvalidHandle();
127 struct FileMappingHandle {
128 typedef HANDLE handle_type;
130 static handle_type GetInvalidHandle() {
134 static void Destruct(handle_type Handle) {
135 ::CloseHandle(Handle);
138 static bool isValid(handle_type Handle) {
139 return Handle != GetInvalidHandle();
143 struct MappedViewOfFileHandle {
144 typedef LPVOID handle_type;
146 static handle_type GetInvalidHandle() {
150 static void Destruct(handle_type Handle) {
151 ::UnmapViewOfFile(Handle);
154 static bool isValid(handle_type Handle) {
155 return Handle != GetInvalidHandle();
159 struct ProcessHandle : CommonHandle {};
160 struct ThreadHandle : CommonHandle {};
161 struct TokenHandle : CommonHandle {};
162 struct FileHandle : CommonHandle {};
164 typedef ScopedHandle<FileMappingHandle> FileMappingScopedHandle;
165 typedef ScopedHandle<MappedViewOfFileHandle> MappedViewOfFileScopedHandle;
166 typedef ScopedHandle<ProcessHandle> ProcessScopedHandle;
167 typedef ScopedHandle<ThreadHandle> ThreadScopedHandle;
168 typedef ScopedHandle<TokenHandle> TokenScopedHandle;
169 typedef ScopedHandle<FileHandle> FileScopedHandle;
172 static error_code GetFileNameFromHandle(HANDLE FileHandle,
174 char Filename[MAX_PATH+1];
175 bool Success = false;
178 // Get the file size.
179 LARGE_INTEGER FileSize;
180 Success = ::GetFileSizeEx(FileHandle, &FileSize);
183 return windows_error(::GetLastError());
185 // Create a file mapping object.
186 FileMappingScopedHandle FileMapping(
187 ::CreateFileMappingA(FileHandle,
195 return windows_error(::GetLastError());
197 // Create a file mapping to get the file name.
198 MappedViewOfFileScopedHandle MappedFile(
199 ::MapViewOfFile(FileMapping, FILE_MAP_READ, 0, 0, 1));
202 return windows_error(::GetLastError());
204 Success = ::GetMappedFileNameA(::GetCurrentProcess(),
207 array_lengthof(Filename) - 1);
210 return windows_error(::GetLastError());
213 return windows_error::success;
217 /// @brief Find program using shell lookup rules.
218 /// @param Program This is either an absolute path, relative path, or simple a
219 /// program name. Look in PATH for any programs that match. If no
220 /// extension is present, try all extensions in PATHEXT.
221 /// @return If ec == errc::success, The absolute path to the program. Otherwise
222 /// the return value is undefined.
223 static std::string FindProgram(const std::string &Program, error_code &ec) {
224 char PathName[MAX_PATH + 1];
225 typedef SmallVector<StringRef, 12> pathext_t;
227 // Check for the program without an extension (in case it already has one).
228 pathext.push_back("");
229 SplitString(std::getenv("PATHEXT"), pathext, ";");
231 for (pathext_t::iterator i = pathext.begin(), e = pathext.end(); i != e; ++i){
233 for (std::size_t ii = 0, e = i->size(); ii != e; ++ii)
234 ext.push_back(::tolower((*i)[ii]));
235 LPCSTR Extension = NULL;
236 if (ext.size() && ext[0] == '.')
237 Extension = ext.c_str();
238 DWORD length = ::SearchPathA(NULL,
241 array_lengthof(PathName),
245 ec = windows_error(::GetLastError());
246 else if (length > array_lengthof(PathName)) {
247 // This may have been the file, return with error.
248 ec = windows_error::buffer_overflow;
251 // We found the path! Return it.
252 ec = windows_error::success;
257 // Make sure PathName is valid.
258 PathName[MAX_PATH] = 0;
262 static StringRef ExceptionCodeToString(DWORD ExceptionCode) {
263 switch(ExceptionCode) {
264 case EXCEPTION_ACCESS_VIOLATION: return "EXCEPTION_ACCESS_VIOLATION";
265 case EXCEPTION_ARRAY_BOUNDS_EXCEEDED:
266 return "EXCEPTION_ARRAY_BOUNDS_EXCEEDED";
267 case EXCEPTION_BREAKPOINT: return "EXCEPTION_BREAKPOINT";
268 case EXCEPTION_DATATYPE_MISALIGNMENT:
269 return "EXCEPTION_DATATYPE_MISALIGNMENT";
270 case EXCEPTION_FLT_DENORMAL_OPERAND: return "EXCEPTION_FLT_DENORMAL_OPERAND";
271 case EXCEPTION_FLT_DIVIDE_BY_ZERO: return "EXCEPTION_FLT_DIVIDE_BY_ZERO";
272 case EXCEPTION_FLT_INEXACT_RESULT: return "EXCEPTION_FLT_INEXACT_RESULT";
273 case EXCEPTION_FLT_INVALID_OPERATION:
274 return "EXCEPTION_FLT_INVALID_OPERATION";
275 case EXCEPTION_FLT_OVERFLOW: return "EXCEPTION_FLT_OVERFLOW";
276 case EXCEPTION_FLT_STACK_CHECK: return "EXCEPTION_FLT_STACK_CHECK";
277 case EXCEPTION_FLT_UNDERFLOW: return "EXCEPTION_FLT_UNDERFLOW";
278 case EXCEPTION_ILLEGAL_INSTRUCTION: return "EXCEPTION_ILLEGAL_INSTRUCTION";
279 case EXCEPTION_IN_PAGE_ERROR: return "EXCEPTION_IN_PAGE_ERROR";
280 case EXCEPTION_INT_DIVIDE_BY_ZERO: return "EXCEPTION_INT_DIVIDE_BY_ZERO";
281 case EXCEPTION_INT_OVERFLOW: return "EXCEPTION_INT_OVERFLOW";
282 case EXCEPTION_INVALID_DISPOSITION: return "EXCEPTION_INVALID_DISPOSITION";
283 case EXCEPTION_NONCONTINUABLE_EXCEPTION:
284 return "EXCEPTION_NONCONTINUABLE_EXCEPTION";
285 case EXCEPTION_PRIV_INSTRUCTION: return "EXCEPTION_PRIV_INSTRUCTION";
286 case EXCEPTION_SINGLE_STEP: return "EXCEPTION_SINGLE_STEP";
287 case EXCEPTION_STACK_OVERFLOW: return "EXCEPTION_STACK_OVERFLOW";
288 default: return "<unknown>";
292 int main(int argc, char **argv) {
293 // Print a stack trace if we signal out.
294 sys::PrintStackTraceOnErrorSignal();
295 PrettyStackTraceProgram X(argc, argv);
296 llvm_shutdown_obj Y; // Call llvm_shutdown() on exit.
300 cl::ParseCommandLineOptions(argc, argv, "Dr. Watson Assassin.\n");
301 if (ProgramToRun.size() == 0) {
302 cl::PrintHelpMessage();
306 if (Timeout > std::numeric_limits<uint32_t>::max() / 1000) {
307 errs() << ToolName << ": Timeout value too large, must be less than: "
308 << std::numeric_limits<uint32_t>::max() / 1000
313 std::string CommandLine(ProgramToRun);
316 ProgramToRun = FindProgram(ProgramToRun, ec);
318 errs() << ToolName << ": Failed to find program: '" << CommandLine
319 << "': " << ec.message() << '\n';
324 errs() << ToolName << ": Found Program: " << ProgramToRun << '\n';
326 for (std::vector<std::string>::iterator i = Argv.begin(),
329 CommandLine.push_back(' ');
330 CommandLine.append(*i);
334 errs() << ToolName << ": Program Image Path: " << ProgramToRun << '\n'
335 << ToolName << ": Command Line: " << CommandLine << '\n';
337 STARTUPINFO StartupInfo;
338 PROCESS_INFORMATION ProcessInfo;
339 std::memset(&StartupInfo, 0, sizeof(StartupInfo));
340 StartupInfo.cb = sizeof(StartupInfo);
341 std::memset(&ProcessInfo, 0, sizeof(ProcessInfo));
343 // Set error mode to not display any message boxes. The child process inherits
345 ::SetErrorMode(SEM_FAILCRITICALERRORS | SEM_NOGPFAULTERRORBOX);
346 ::_set_error_mode(_OUT_TO_STDERR);
348 BOOL success = ::CreateProcessA(ProgramToRun.c_str(),
349 LPSTR(CommandLine.c_str()),
359 errs() << ToolName << ": Failed to run program: '" << ProgramToRun
360 << "': " << error_code(windows_error(::GetLastError())).message()
365 // Make sure ::CloseHandle is called on exit.
366 std::map<DWORD, HANDLE> ProcessIDToHandle;
368 DEBUG_EVENT DebugEvent;
369 std::memset(&DebugEvent, 0, sizeof(DebugEvent));
370 DWORD dwContinueStatus = DBG_CONTINUE;
372 // Run the program under the debugger until either it exits, or throws an
375 errs() << ToolName << ": Debugging...\n";
378 DWORD TimeLeft = INFINITE;
380 FILETIME CreationTime, ExitTime, KernelTime, UserTime;
382 success = ::GetProcessTimes(ProcessInfo.hProcess,
388 ec = windows_error(::GetLastError());
390 errs() << ToolName << ": Failed to get process times: "
391 << ec.message() << '\n';
394 a.LowPart = KernelTime.dwLowDateTime;
395 a.HighPart = KernelTime.dwHighDateTime;
396 b.LowPart = UserTime.dwLowDateTime;
397 b.HighPart = UserTime.dwHighDateTime;
398 // Convert 100-nanosecond units to milliseconds.
399 uint64_t TotalTimeMiliseconds = (a.QuadPart + b.QuadPart) / 10000;
400 // Handle the case where the process has been running for more than 49
402 if (TotalTimeMiliseconds > std::numeric_limits<uint32_t>::max()) {
403 errs() << ToolName << ": Timeout Failed: Process has been running for"
404 "more than 49 days.\n";
408 // We check with > instead of using Timeleft because if
409 // TotalTimeMiliseconds is greater than Timeout * 1000, TimeLeft would
411 if (TotalTimeMiliseconds > (Timeout * 1000)) {
412 errs() << ToolName << ": Process timed out.\n";
413 ::TerminateProcess(ProcessInfo.hProcess, -1);
414 // Otherwise other stuff starts failing...
418 TimeLeft = (Timeout * 1000) - static_cast<uint32_t>(TotalTimeMiliseconds);
420 success = WaitForDebugEvent(&DebugEvent, TimeLeft);
423 ec = windows_error(::GetLastError());
425 if (ec == errc::timed_out) {
426 errs() << ToolName << ": Process timed out.\n";
427 ::TerminateProcess(ProcessInfo.hProcess, -1);
428 // Otherwise other stuff starts failing...
432 errs() << ToolName << ": Failed to wait for debug event in program: '"
433 << ProgramToRun << "': " << ec.message() << '\n';
437 switch(DebugEvent.dwDebugEventCode) {
438 case CREATE_PROCESS_DEBUG_EVENT:
439 // Make sure we remove the handle on exit.
441 errs() << ToolName << ": Debug Event: CREATE_PROCESS_DEBUG_EVENT\n";
442 ProcessIDToHandle[DebugEvent.dwProcessId] =
443 DebugEvent.u.CreateProcessInfo.hProcess;
444 ::CloseHandle(DebugEvent.u.CreateProcessInfo.hFile);
446 case EXIT_PROCESS_DEBUG_EVENT: {
448 errs() << ToolName << ": Debug Event: EXIT_PROCESS_DEBUG_EVENT\n";
450 // If this is the process we originally created, exit with its exit
452 if (DebugEvent.dwProcessId == ProcessInfo.dwProcessId)
453 return DebugEvent.u.ExitProcess.dwExitCode;
455 // Otherwise cleanup any resources we have for it.
456 std::map<DWORD, HANDLE>::iterator ExitingProcess =
457 ProcessIDToHandle.find(DebugEvent.dwProcessId);
458 if (ExitingProcess == ProcessIDToHandle.end()) {
459 errs() << ToolName << ": Got unknown process id!\n";
462 ::CloseHandle(ExitingProcess->second);
463 ProcessIDToHandle.erase(ExitingProcess);
466 case CREATE_THREAD_DEBUG_EVENT:
467 ::CloseHandle(DebugEvent.u.CreateThread.hThread);
469 case LOAD_DLL_DEBUG_EVENT: {
470 // Cleanup the file handle.
471 FileScopedHandle DLLFile(DebugEvent.u.LoadDll.hFile);
473 ec = GetFileNameFromHandle(DLLFile, DLLName);
475 DLLName = "<failed to get file name from file handle> : ";
476 DLLName += ec.message();
478 if (TraceExecution) {
479 errs() << ToolName << ": Debug Event: LOAD_DLL_DEBUG_EVENT\n";
480 errs().indent(ToolName.size()) << ": DLL Name : " << DLLName << '\n';
483 if (NoUser32 && sys::path::stem(DLLName) == "user32") {
484 // Program is loading user32.dll, in the applications we are testing,
485 // this only happens if an assert has fired. By now the message has
486 // already been printed, so simply close the program.
487 errs() << ToolName << ": user32.dll loaded!\n";
488 errs().indent(ToolName.size())
489 << ": This probably means that assert was called. Closing "
490 "program to prevent message box from popping up.\n";
491 dwContinueStatus = DBG_CONTINUE;
492 ::TerminateProcess(ProcessIDToHandle[DebugEvent.dwProcessId], -1);
497 case EXCEPTION_DEBUG_EVENT: {
498 // Close the application if this exception will not be handled by the
499 // child application.
501 errs() << ToolName << ": Debug Event: EXCEPTION_DEBUG_EVENT\n";
503 EXCEPTION_DEBUG_INFO &Exception = DebugEvent.u.Exception;
504 if (Exception.dwFirstChance > 0) {
505 if (TraceExecution) {
506 errs().indent(ToolName.size()) << ": Debug Info : ";
507 errs() << "First chance exception at "
508 << Exception.ExceptionRecord.ExceptionAddress
509 << ", exception code: "
510 << ExceptionCodeToString(
511 Exception.ExceptionRecord.ExceptionCode)
512 << " (" << Exception.ExceptionRecord.ExceptionCode << ")\n";
514 dwContinueStatus = DBG_EXCEPTION_NOT_HANDLED;
516 errs() << ToolName << ": Unhandled exception in: " << ProgramToRun
518 errs().indent(ToolName.size()) << ": location: ";
519 errs() << Exception.ExceptionRecord.ExceptionAddress
520 << ", exception code: "
521 << ExceptionCodeToString(
522 Exception.ExceptionRecord.ExceptionCode)
523 << " (" << Exception.ExceptionRecord.ExceptionCode
525 dwContinueStatus = DBG_CONTINUE;
526 ::TerminateProcess(ProcessIDToHandle[DebugEvent.dwProcessId], -1);
534 errs() << ToolName << ": Debug Event: <unknown>\n";
538 success = ContinueDebugEvent(DebugEvent.dwProcessId,
539 DebugEvent.dwThreadId,
542 ec = windows_error(::GetLastError());
543 errs() << ToolName << ": Failed to continue debugging program: '"
544 << ProgramToRun << "': " << ec.message() << '\n';
548 dwContinueStatus = DBG_CONTINUE;
551 assert(0 && "Fell out of debug loop. This shouldn't be possible!");