Home | History | Annotate | Download | only in KillTheDoctor
      1 //===- KillTheDoctor - Prevent Dr. Watson from stopping tests ---*- C++ -*-===//
      2 //
      3 //                     The LLVM Compiler Infrastructure
      4 //
      5 // This file is distributed under the University of Illinois Open Source
      6 // License. See LICENSE.TXT for details.
      7 //
      8 //===----------------------------------------------------------------------===//
      9 //
     10 // This program provides an extremely hacky way to stop Dr. Watson from starting
     11 // due to unhandled exceptions in child processes.
     12 //
     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).
     17 //
     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.
     25 //
     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.
     28 //
     29 // I hate Windows.
     30 //
     31 //===----------------------------------------------------------------------===//
     32 
     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/Path.h"
     42 #include "llvm/Support/PrettyStackTrace.h"
     43 #include "llvm/Support/Signals.h"
     44 #include "llvm/Support/WindowsError.h"
     45 #include "llvm/Support/raw_ostream.h"
     46 #include "llvm/Support/type_traits.h"
     47 #include <algorithm>
     48 #include <cerrno>
     49 #include <cstdlib>
     50 #include <map>
     51 #include <string>
     52 #include <system_error>
     53 
     54 // These includes must be last.
     55 #include <Windows.h>
     56 #include <WinError.h>
     57 #include <Dbghelp.h>
     58 #include <psapi.h>
     59 
     60 using namespace llvm;
     61 
     62 #undef max
     63 
     64 namespace {
     65   cl::opt<std::string> ProgramToRun(cl::Positional,
     66     cl::desc("<program to run>"));
     67   cl::list<std::string>  Argv(cl::ConsumeAfter,
     68     cl::desc("<program arguments>..."));
     69   cl::opt<bool> TraceExecution("x",
     70     cl::desc("Print detailed output about what is being run to stderr."));
     71   cl::opt<unsigned> Timeout("t", cl::init(0),
     72     cl::desc("Set maximum runtime in seconds. Defaults to infinite."));
     73   cl::opt<bool> NoUser32("no-user32",
     74     cl::desc("Terminate process if it loads user32.dll."));
     75 
     76   StringRef ToolName;
     77 
     78   template <typename HandleType>
     79   class ScopedHandle {
     80     typedef typename HandleType::handle_type handle_type;
     81 
     82     handle_type Handle;
     83 
     84   public:
     85     ScopedHandle()
     86       : Handle(HandleType::GetInvalidHandle()) {}
     87 
     88     explicit ScopedHandle(handle_type handle)
     89       : Handle(handle) {}
     90 
     91     ~ScopedHandle() {
     92       HandleType::Destruct(Handle);
     93     }
     94 
     95     ScopedHandle& operator=(handle_type handle) {
     96       // Cleanup current handle.
     97       if (!HandleType::isValid(Handle))
     98         HandleType::Destruct(Handle);
     99       Handle = handle;
    100       return *this;
    101     }
    102 
    103     operator bool() const {
    104       return HandleType::isValid(Handle);
    105     }
    106 
    107     operator handle_type() {
    108       return Handle;
    109     }
    110   };
    111 
    112   // This implements the most common handle in the Windows API.
    113   struct CommonHandle {
    114     typedef HANDLE handle_type;
    115 
    116     static handle_type GetInvalidHandle() {
    117       return INVALID_HANDLE_VALUE;
    118     }
    119 
    120     static void Destruct(handle_type Handle) {
    121       ::CloseHandle(Handle);
    122     }
    123 
    124     static bool isValid(handle_type Handle) {
    125       return Handle != GetInvalidHandle();
    126     }
    127   };
    128 
    129   struct FileMappingHandle {
    130     typedef HANDLE handle_type;
    131 
    132     static handle_type GetInvalidHandle() {
    133       return NULL;
    134     }
    135 
    136     static void Destruct(handle_type Handle) {
    137       ::CloseHandle(Handle);
    138     }
    139 
    140     static bool isValid(handle_type Handle) {
    141       return Handle != GetInvalidHandle();
    142     }
    143   };
    144 
    145   struct MappedViewOfFileHandle {
    146     typedef LPVOID handle_type;
    147 
    148     static handle_type GetInvalidHandle() {
    149       return NULL;
    150     }
    151 
    152     static void Destruct(handle_type Handle) {
    153       ::UnmapViewOfFile(Handle);
    154     }
    155 
    156     static bool isValid(handle_type Handle) {
    157       return Handle != GetInvalidHandle();
    158     }
    159   };
    160 
    161   struct ProcessHandle : CommonHandle {};
    162   struct ThreadHandle  : CommonHandle {};
    163   struct TokenHandle   : CommonHandle {};
    164   struct FileHandle    : CommonHandle {};
    165 
    166   typedef ScopedHandle<FileMappingHandle>       FileMappingScopedHandle;
    167   typedef ScopedHandle<MappedViewOfFileHandle>  MappedViewOfFileScopedHandle;
    168   typedef ScopedHandle<ProcessHandle>           ProcessScopedHandle;
    169   typedef ScopedHandle<ThreadHandle>            ThreadScopedHandle;
    170   typedef ScopedHandle<TokenHandle>             TokenScopedHandle;
    171   typedef ScopedHandle<FileHandle>              FileScopedHandle;
    172 }
    173 
    174 static std::error_code windows_error(DWORD E) { return mapWindowsError(E); }
    175 
    176 static std::error_code GetFileNameFromHandle(HANDLE FileHandle,
    177                                              std::string &Name) {
    178   char Filename[MAX_PATH+1];
    179   bool Success = false;
    180   Name.clear();
    181 
    182   // Get the file size.
    183   LARGE_INTEGER FileSize;
    184   Success = ::GetFileSizeEx(FileHandle, &FileSize);
    185 
    186   if (!Success)
    187     return windows_error(::GetLastError());
    188 
    189   // Create a file mapping object.
    190   FileMappingScopedHandle FileMapping(
    191     ::CreateFileMappingA(FileHandle,
    192                          NULL,
    193                          PAGE_READONLY,
    194                          0,
    195                          1,
    196                          NULL));
    197 
    198   if (!FileMapping)
    199     return windows_error(::GetLastError());
    200 
    201   // Create a file mapping to get the file name.
    202   MappedViewOfFileScopedHandle MappedFile(
    203     ::MapViewOfFile(FileMapping, FILE_MAP_READ, 0, 0, 1));
    204 
    205   if (!MappedFile)
    206     return windows_error(::GetLastError());
    207 
    208   Success = ::GetMappedFileNameA(::GetCurrentProcess(),
    209                                 MappedFile,
    210                                 Filename,
    211                                 array_lengthof(Filename) - 1);
    212 
    213   if (!Success)
    214     return windows_error(::GetLastError());
    215   else {
    216     Name = Filename;
    217     return std::error_code();
    218   }
    219 }
    220 
    221 /// @brief Find program using shell lookup rules.
    222 /// @param Program This is either an absolute path, relative path, or simple a
    223 ///        program name. Look in PATH for any programs that match. If no
    224 ///        extension is present, try all extensions in PATHEXT.
    225 /// @return If ec == errc::success, The absolute path to the program. Otherwise
    226 ///         the return value is undefined.
    227 static std::string FindProgram(const std::string &Program,
    228                                std::error_code &ec) {
    229   char PathName[MAX_PATH + 1];
    230   typedef SmallVector<StringRef, 12> pathext_t;
    231   pathext_t pathext;
    232   // Check for the program without an extension (in case it already has one).
    233   pathext.push_back("");
    234   SplitString(std::getenv("PATHEXT"), pathext, ";");
    235 
    236   for (pathext_t::iterator i = pathext.begin(), e = pathext.end(); i != e; ++i){
    237     SmallString<5> ext;
    238     for (std::size_t ii = 0, e = i->size(); ii != e; ++ii)
    239       ext.push_back(::tolower((*i)[ii]));
    240     LPCSTR Extension = NULL;
    241     if (ext.size() && ext[0] == '.')
    242       Extension = ext.c_str();
    243     DWORD length = ::SearchPathA(NULL,
    244                                  Program.c_str(),
    245                                  Extension,
    246                                  array_lengthof(PathName),
    247                                  PathName,
    248                                  NULL);
    249     if (length == 0)
    250       ec = windows_error(::GetLastError());
    251     else if (length > array_lengthof(PathName)) {
    252       // This may have been the file, return with error.
    253       ec = windows_error(ERROR_BUFFER_OVERFLOW);
    254       break;
    255     } else {
    256       // We found the path! Return it.
    257       ec = std::error_code();
    258       break;
    259     }
    260   }
    261 
    262   // Make sure PathName is valid.
    263   PathName[MAX_PATH] = 0;
    264   return PathName;
    265 }
    266 
    267 static StringRef ExceptionCodeToString(DWORD ExceptionCode) {
    268   switch(ExceptionCode) {
    269   case EXCEPTION_ACCESS_VIOLATION: return "EXCEPTION_ACCESS_VIOLATION";
    270   case EXCEPTION_ARRAY_BOUNDS_EXCEEDED:
    271     return "EXCEPTION_ARRAY_BOUNDS_EXCEEDED";
    272   case EXCEPTION_BREAKPOINT: return "EXCEPTION_BREAKPOINT";
    273   case EXCEPTION_DATATYPE_MISALIGNMENT:
    274     return "EXCEPTION_DATATYPE_MISALIGNMENT";
    275   case EXCEPTION_FLT_DENORMAL_OPERAND: return "EXCEPTION_FLT_DENORMAL_OPERAND";
    276   case EXCEPTION_FLT_DIVIDE_BY_ZERO: return "EXCEPTION_FLT_DIVIDE_BY_ZERO";
    277   case EXCEPTION_FLT_INEXACT_RESULT: return "EXCEPTION_FLT_INEXACT_RESULT";
    278   case EXCEPTION_FLT_INVALID_OPERATION:
    279     return "EXCEPTION_FLT_INVALID_OPERATION";
    280   case EXCEPTION_FLT_OVERFLOW: return "EXCEPTION_FLT_OVERFLOW";
    281   case EXCEPTION_FLT_STACK_CHECK: return "EXCEPTION_FLT_STACK_CHECK";
    282   case EXCEPTION_FLT_UNDERFLOW: return "EXCEPTION_FLT_UNDERFLOW";
    283   case EXCEPTION_ILLEGAL_INSTRUCTION: return "EXCEPTION_ILLEGAL_INSTRUCTION";
    284   case EXCEPTION_IN_PAGE_ERROR: return "EXCEPTION_IN_PAGE_ERROR";
    285   case EXCEPTION_INT_DIVIDE_BY_ZERO: return "EXCEPTION_INT_DIVIDE_BY_ZERO";
    286   case EXCEPTION_INT_OVERFLOW: return "EXCEPTION_INT_OVERFLOW";
    287   case EXCEPTION_INVALID_DISPOSITION: return "EXCEPTION_INVALID_DISPOSITION";
    288   case EXCEPTION_NONCONTINUABLE_EXCEPTION:
    289     return "EXCEPTION_NONCONTINUABLE_EXCEPTION";
    290   case EXCEPTION_PRIV_INSTRUCTION: return "EXCEPTION_PRIV_INSTRUCTION";
    291   case EXCEPTION_SINGLE_STEP: return "EXCEPTION_SINGLE_STEP";
    292   case EXCEPTION_STACK_OVERFLOW: return "EXCEPTION_STACK_OVERFLOW";
    293   default: return "<unknown>";
    294   }
    295 }
    296 
    297 int main(int argc, char **argv) {
    298   // Print a stack trace if we signal out.
    299   sys::PrintStackTraceOnErrorSignal();
    300   PrettyStackTraceProgram X(argc, argv);
    301   llvm_shutdown_obj Y;  // Call llvm_shutdown() on exit.
    302 
    303   ToolName = argv[0];
    304 
    305   cl::ParseCommandLineOptions(argc, argv, "Dr. Watson Assassin.\n");
    306   if (ProgramToRun.size() == 0) {
    307     cl::PrintHelpMessage();
    308     return -1;
    309   }
    310 
    311   if (Timeout > std::numeric_limits<uint32_t>::max() / 1000) {
    312     errs() << ToolName << ": Timeout value too large, must be less than: "
    313                        << std::numeric_limits<uint32_t>::max() / 1000
    314                        << '\n';
    315     return -1;
    316   }
    317 
    318   std::string CommandLine(ProgramToRun);
    319 
    320   std::error_code ec;
    321   ProgramToRun = FindProgram(ProgramToRun, ec);
    322   if (ec) {
    323     errs() << ToolName << ": Failed to find program: '" << CommandLine
    324            << "': " << ec.message() << '\n';
    325     return -1;
    326   }
    327 
    328   if (TraceExecution)
    329     errs() << ToolName << ": Found Program: " << ProgramToRun << '\n';
    330 
    331   for (std::vector<std::string>::iterator i = Argv.begin(),
    332                                           e = Argv.end();
    333                                           i != e; ++i) {
    334     CommandLine.push_back(' ');
    335     CommandLine.append(*i);
    336   }
    337 
    338   if (TraceExecution)
    339     errs() << ToolName << ": Program Image Path: " << ProgramToRun << '\n'
    340            << ToolName << ": Command Line: " << CommandLine << '\n';
    341 
    342   STARTUPINFO StartupInfo;
    343   PROCESS_INFORMATION ProcessInfo;
    344   std::memset(&StartupInfo, 0, sizeof(StartupInfo));
    345   StartupInfo.cb = sizeof(StartupInfo);
    346   std::memset(&ProcessInfo, 0, sizeof(ProcessInfo));
    347 
    348   // Set error mode to not display any message boxes. The child process inherits
    349   // this.
    350   ::SetErrorMode(SEM_FAILCRITICALERRORS | SEM_NOGPFAULTERRORBOX);
    351   ::_set_error_mode(_OUT_TO_STDERR);
    352 
    353   BOOL success = ::CreateProcessA(ProgramToRun.c_str(),
    354                             LPSTR(CommandLine.c_str()),
    355                                   NULL,
    356                                   NULL,
    357                                   FALSE,
    358                                   DEBUG_PROCESS,
    359                                   NULL,
    360                                   NULL,
    361                                   &StartupInfo,
    362                                   &ProcessInfo);
    363   if (!success) {
    364     errs() << ToolName << ": Failed to run program: '" << ProgramToRun << "': "
    365            << std::error_code(windows_error(::GetLastError())).message()
    366            << '\n';
    367     return -1;
    368   }
    369 
    370   // Make sure ::CloseHandle is called on exit.
    371   std::map<DWORD, HANDLE> ProcessIDToHandle;
    372 
    373   DEBUG_EVENT DebugEvent;
    374   std::memset(&DebugEvent, 0, sizeof(DebugEvent));
    375   DWORD dwContinueStatus = DBG_CONTINUE;
    376 
    377   // Run the program under the debugger until either it exits, or throws an
    378   // exception.
    379   if (TraceExecution)
    380     errs() << ToolName << ": Debugging...\n";
    381 
    382   while(true) {
    383     DWORD TimeLeft = INFINITE;
    384     if (Timeout > 0) {
    385       FILETIME CreationTime, ExitTime, KernelTime, UserTime;
    386       ULARGE_INTEGER a, b;
    387       success = ::GetProcessTimes(ProcessInfo.hProcess,
    388                                   &CreationTime,
    389                                   &ExitTime,
    390                                   &KernelTime,
    391                                   &UserTime);
    392       if (!success) {
    393         ec = windows_error(::GetLastError());
    394 
    395         errs() << ToolName << ": Failed to get process times: "
    396                << ec.message() << '\n';
    397         return -1;
    398       }
    399       a.LowPart = KernelTime.dwLowDateTime;
    400       a.HighPart = KernelTime.dwHighDateTime;
    401       b.LowPart = UserTime.dwLowDateTime;
    402       b.HighPart = UserTime.dwHighDateTime;
    403       // Convert 100-nanosecond units to milliseconds.
    404       uint64_t TotalTimeMiliseconds = (a.QuadPart + b.QuadPart) / 10000;
    405       // Handle the case where the process has been running for more than 49
    406       // days.
    407       if (TotalTimeMiliseconds > std::numeric_limits<uint32_t>::max()) {
    408         errs() << ToolName << ": Timeout Failed: Process has been running for"
    409                               "more than 49 days.\n";
    410         return -1;
    411       }
    412 
    413       // We check with > instead of using Timeleft because if
    414       // TotalTimeMiliseconds is greater than Timeout * 1000, TimeLeft would
    415       // underflow.
    416       if (TotalTimeMiliseconds > (Timeout * 1000)) {
    417         errs() << ToolName << ": Process timed out.\n";
    418         ::TerminateProcess(ProcessInfo.hProcess, -1);
    419         // Otherwise other stuff starts failing...
    420         return -1;
    421       }
    422 
    423       TimeLeft = (Timeout * 1000) - static_cast<uint32_t>(TotalTimeMiliseconds);
    424     }
    425     success = WaitForDebugEvent(&DebugEvent, TimeLeft);
    426 
    427     if (!success) {
    428       DWORD LastError = ::GetLastError();
    429       ec = windows_error(LastError);
    430 
    431       if (LastError == ERROR_SEM_TIMEOUT || LastError == WSAETIMEDOUT) {
    432         errs() << ToolName << ": Process timed out.\n";
    433         ::TerminateProcess(ProcessInfo.hProcess, -1);
    434         // Otherwise other stuff starts failing...
    435         return -1;
    436       }
    437 
    438       errs() << ToolName << ": Failed to wait for debug event in program: '"
    439              << ProgramToRun << "': " << ec.message() << '\n';
    440       return -1;
    441     }
    442 
    443     switch(DebugEvent.dwDebugEventCode) {
    444     case CREATE_PROCESS_DEBUG_EVENT:
    445       // Make sure we remove the handle on exit.
    446       if (TraceExecution)
    447         errs() << ToolName << ": Debug Event: CREATE_PROCESS_DEBUG_EVENT\n";
    448       ProcessIDToHandle[DebugEvent.dwProcessId] =
    449         DebugEvent.u.CreateProcessInfo.hProcess;
    450       ::CloseHandle(DebugEvent.u.CreateProcessInfo.hFile);
    451       break;
    452     case EXIT_PROCESS_DEBUG_EVENT: {
    453         if (TraceExecution)
    454           errs() << ToolName << ": Debug Event: EXIT_PROCESS_DEBUG_EVENT\n";
    455 
    456         // If this is the process we originally created, exit with its exit
    457         // code.
    458         if (DebugEvent.dwProcessId == ProcessInfo.dwProcessId)
    459           return DebugEvent.u.ExitProcess.dwExitCode;
    460 
    461         // Otherwise cleanup any resources we have for it.
    462         std::map<DWORD, HANDLE>::iterator ExitingProcess =
    463           ProcessIDToHandle.find(DebugEvent.dwProcessId);
    464         if (ExitingProcess == ProcessIDToHandle.end()) {
    465           errs() << ToolName << ": Got unknown process id!\n";
    466           return -1;
    467         }
    468         ::CloseHandle(ExitingProcess->second);
    469         ProcessIDToHandle.erase(ExitingProcess);
    470       }
    471       break;
    472     case CREATE_THREAD_DEBUG_EVENT:
    473       ::CloseHandle(DebugEvent.u.CreateThread.hThread);
    474       break;
    475     case LOAD_DLL_DEBUG_EVENT: {
    476         // Cleanup the file handle.
    477         FileScopedHandle DLLFile(DebugEvent.u.LoadDll.hFile);
    478         std::string DLLName;
    479         ec = GetFileNameFromHandle(DLLFile, DLLName);
    480         if (ec) {
    481           DLLName = "<failed to get file name from file handle> : ";
    482           DLLName += ec.message();
    483         }
    484         if (TraceExecution) {
    485           errs() << ToolName << ": Debug Event: LOAD_DLL_DEBUG_EVENT\n";
    486           errs().indent(ToolName.size()) << ": DLL Name : " << DLLName << '\n';
    487         }
    488 
    489         if (NoUser32 && sys::path::stem(DLLName) == "user32") {
    490           // Program is loading user32.dll, in the applications we are testing,
    491           // this only happens if an assert has fired. By now the message has
    492           // already been printed, so simply close the program.
    493           errs() << ToolName << ": user32.dll loaded!\n";
    494           errs().indent(ToolName.size())
    495                  << ": This probably means that assert was called. Closing "
    496                     "program to prevent message box from popping up.\n";
    497           dwContinueStatus = DBG_CONTINUE;
    498           ::TerminateProcess(ProcessIDToHandle[DebugEvent.dwProcessId], -1);
    499           return -1;
    500         }
    501       }
    502       break;
    503     case EXCEPTION_DEBUG_EVENT: {
    504         // Close the application if this exception will not be handled by the
    505         // child application.
    506         if (TraceExecution)
    507           errs() << ToolName << ": Debug Event: EXCEPTION_DEBUG_EVENT\n";
    508 
    509         EXCEPTION_DEBUG_INFO  &Exception = DebugEvent.u.Exception;
    510         if (Exception.dwFirstChance > 0) {
    511           if (TraceExecution) {
    512             errs().indent(ToolName.size()) << ": Debug Info : ";
    513             errs() << "First chance exception at "
    514                    << Exception.ExceptionRecord.ExceptionAddress
    515                    << ", exception code: "
    516                    << ExceptionCodeToString(
    517                         Exception.ExceptionRecord.ExceptionCode)
    518                    << " (" << Exception.ExceptionRecord.ExceptionCode << ")\n";
    519           }
    520           dwContinueStatus = DBG_EXCEPTION_NOT_HANDLED;
    521         } else {
    522           errs() << ToolName << ": Unhandled exception in: " << ProgramToRun
    523                  << "!\n";
    524                  errs().indent(ToolName.size()) << ": location: ";
    525                  errs() << Exception.ExceptionRecord.ExceptionAddress
    526                         << ", exception code: "
    527                         << ExceptionCodeToString(
    528                             Exception.ExceptionRecord.ExceptionCode)
    529                         << " (" << Exception.ExceptionRecord.ExceptionCode
    530                         << ")\n";
    531           dwContinueStatus = DBG_CONTINUE;
    532           ::TerminateProcess(ProcessIDToHandle[DebugEvent.dwProcessId], -1);
    533           return -1;
    534         }
    535       }
    536       break;
    537     default:
    538       // Do nothing.
    539       if (TraceExecution)
    540         errs() << ToolName << ": Debug Event: <unknown>\n";
    541       break;
    542     }
    543 
    544     success = ContinueDebugEvent(DebugEvent.dwProcessId,
    545                                  DebugEvent.dwThreadId,
    546                                  dwContinueStatus);
    547     if (!success) {
    548       ec = windows_error(::GetLastError());
    549       errs() << ToolName << ": Failed to continue debugging program: '"
    550              << ProgramToRun << "': " << ec.message() << '\n';
    551       return -1;
    552     }
    553 
    554     dwContinueStatus = DBG_CONTINUE;
    555   }
    556 
    557   assert(0 && "Fell out of debug loop. This shouldn't be possible!");
    558   return -1;
    559 }
    560