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/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"
     46 #include <algorithm>
     47 #include <cerrno>
     48 #include <cstdlib>
     49 #include <map>
     50 #include <string>
     51 
     52 // These includes must be last.
     53 #include <Windows.h>
     54 #include <WinError.h>
     55 #include <Dbghelp.h>
     56 #include <psapi.h>
     57 
     58 using namespace llvm;
     59 
     60 #undef max
     61 
     62 namespace {
     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."));
     73 
     74   StringRef ToolName;
     75 
     76   template <typename HandleType>
     77   class ScopedHandle {
     78     typedef typename HandleType::handle_type handle_type;
     79 
     80     handle_type Handle;
     81 
     82   public:
     83     ScopedHandle()
     84       : Handle(HandleType::GetInvalidHandle()) {}
     85 
     86     explicit ScopedHandle(handle_type handle)
     87       : Handle(handle) {}
     88 
     89     ~ScopedHandle() {
     90       HandleType::Destruct(Handle);
     91     }
     92 
     93     ScopedHandle& operator=(handle_type handle) {
     94       // Cleanup current handle.
     95       if (!HandleType::isValid(Handle))
     96         HandleType::Destruct(Handle);
     97       Handle = handle;
     98       return *this;
     99     }
    100 
    101     operator bool() const {
    102       return HandleType::isValid(Handle);
    103     }
    104 
    105     operator handle_type() {
    106       return Handle;
    107     }
    108   };
    109 
    110   // This implements the most common handle in the Windows API.
    111   struct CommonHandle {
    112     typedef HANDLE handle_type;
    113 
    114     static handle_type GetInvalidHandle() {
    115       return INVALID_HANDLE_VALUE;
    116     }
    117 
    118     static void Destruct(handle_type Handle) {
    119       ::CloseHandle(Handle);
    120     }
    121 
    122     static bool isValid(handle_type Handle) {
    123       return Handle != GetInvalidHandle();
    124     }
    125   };
    126 
    127   struct FileMappingHandle {
    128     typedef HANDLE handle_type;
    129 
    130     static handle_type GetInvalidHandle() {
    131       return NULL;
    132     }
    133 
    134     static void Destruct(handle_type Handle) {
    135       ::CloseHandle(Handle);
    136     }
    137 
    138     static bool isValid(handle_type Handle) {
    139       return Handle != GetInvalidHandle();
    140     }
    141   };
    142 
    143   struct MappedViewOfFileHandle {
    144     typedef LPVOID handle_type;
    145 
    146     static handle_type GetInvalidHandle() {
    147       return NULL;
    148     }
    149 
    150     static void Destruct(handle_type Handle) {
    151       ::UnmapViewOfFile(Handle);
    152     }
    153 
    154     static bool isValid(handle_type Handle) {
    155       return Handle != GetInvalidHandle();
    156     }
    157   };
    158 
    159   struct ProcessHandle : CommonHandle {};
    160   struct ThreadHandle  : CommonHandle {};
    161   struct TokenHandle   : CommonHandle {};
    162   struct FileHandle    : CommonHandle {};
    163 
    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;
    170 }
    171 
    172 static error_code GetFileNameFromHandle(HANDLE FileHandle,
    173                                         std::string& Name) {
    174   char Filename[MAX_PATH+1];
    175   bool Success = false;
    176   Name.clear();
    177 
    178   // Get the file size.
    179   LARGE_INTEGER FileSize;
    180   Success = ::GetFileSizeEx(FileHandle, &FileSize);
    181 
    182   if (!Success)
    183     return windows_error(::GetLastError());
    184 
    185   // Create a file mapping object.
    186   FileMappingScopedHandle FileMapping(
    187     ::CreateFileMappingA(FileHandle,
    188                          NULL,
    189                          PAGE_READONLY,
    190                          0,
    191                          1,
    192                          NULL));
    193 
    194   if (!FileMapping)
    195     return windows_error(::GetLastError());
    196 
    197   // Create a file mapping to get the file name.
    198   MappedViewOfFileScopedHandle MappedFile(
    199     ::MapViewOfFile(FileMapping, FILE_MAP_READ, 0, 0, 1));
    200 
    201   if (!MappedFile)
    202     return windows_error(::GetLastError());
    203 
    204   Success = ::GetMappedFileNameA(::GetCurrentProcess(),
    205                                 MappedFile,
    206                                 Filename,
    207                                 array_lengthof(Filename) - 1);
    208 
    209   if (!Success)
    210     return windows_error(::GetLastError());
    211   else {
    212     Name = Filename;
    213     return windows_error::success;
    214   }
    215 }
    216 
    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;
    226   pathext_t pathext;
    227   // Check for the program without an extension (in case it already has one).
    228   pathext.push_back("");
    229   SplitString(std::getenv("PATHEXT"), pathext, ";");
    230 
    231   for (pathext_t::iterator i = pathext.begin(), e = pathext.end(); i != e; ++i){
    232     SmallString<5> ext;
    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,
    239                                  Program.c_str(),
    240                                  Extension,
    241                                  array_lengthof(PathName),
    242                                  PathName,
    243                                  NULL);
    244     if (length == 0)
    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;
    249       break;
    250     } else {
    251       // We found the path! Return it.
    252       ec = windows_error::success;
    253       break;
    254     }
    255   }
    256 
    257   // Make sure PathName is valid.
    258   PathName[MAX_PATH] = 0;
    259   return PathName;
    260 }
    261 
    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>";
    289   }
    290 }
    291 
    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.
    297 
    298   ToolName = argv[0];
    299 
    300   cl::ParseCommandLineOptions(argc, argv, "Dr. Watson Assassin.\n");
    301   if (ProgramToRun.size() == 0) {
    302     cl::PrintHelpMessage();
    303     return -1;
    304   }
    305 
    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
    309                        << '\n';
    310     return -1;
    311   }
    312 
    313   std::string CommandLine(ProgramToRun);
    314 
    315   error_code ec;
    316   ProgramToRun = FindProgram(ProgramToRun, ec);
    317   if (ec) {
    318     errs() << ToolName << ": Failed to find program: '" << CommandLine
    319            << "': " << ec.message() << '\n';
    320     return -1;
    321   }
    322 
    323   if (TraceExecution)
    324     errs() << ToolName << ": Found Program: " << ProgramToRun << '\n';
    325 
    326   for (std::vector<std::string>::iterator i = Argv.begin(),
    327                                           e = Argv.end();
    328                                           i != e; ++i) {
    329     CommandLine.push_back(' ');
    330     CommandLine.append(*i);
    331   }
    332 
    333   if (TraceExecution)
    334     errs() << ToolName << ": Program Image Path: " << ProgramToRun << '\n'
    335            << ToolName << ": Command Line: " << CommandLine << '\n';
    336 
    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));
    342 
    343   // Set error mode to not display any message boxes. The child process inherits
    344   // this.
    345   ::SetErrorMode(SEM_FAILCRITICALERRORS | SEM_NOGPFAULTERRORBOX);
    346   ::_set_error_mode(_OUT_TO_STDERR);
    347 
    348   BOOL success = ::CreateProcessA(ProgramToRun.c_str(),
    349                             LPSTR(CommandLine.c_str()),
    350                                   NULL,
    351                                   NULL,
    352                                   FALSE,
    353                                   DEBUG_PROCESS,
    354                                   NULL,
    355                                   NULL,
    356                                   &StartupInfo,
    357                                   &ProcessInfo);
    358   if (!success) {
    359     errs() << ToolName << ": Failed to run program: '" << ProgramToRun
    360            << "': " << error_code(windows_error(::GetLastError())).message()
    361            << '\n';
    362     return -1;
    363   }
    364 
    365   // Make sure ::CloseHandle is called on exit.
    366   std::map<DWORD, HANDLE> ProcessIDToHandle;
    367 
    368   DEBUG_EVENT DebugEvent;
    369   std::memset(&DebugEvent, 0, sizeof(DebugEvent));
    370   DWORD dwContinueStatus = DBG_CONTINUE;
    371 
    372   // Run the program under the debugger until either it exits, or throws an
    373   // exception.
    374   if (TraceExecution)
    375     errs() << ToolName << ": Debugging...\n";
    376 
    377   while(true) {
    378     DWORD TimeLeft = INFINITE;
    379     if (Timeout > 0) {
    380       FILETIME CreationTime, ExitTime, KernelTime, UserTime;
    381       ULARGE_INTEGER a, b;
    382       success = ::GetProcessTimes(ProcessInfo.hProcess,
    383                                   &CreationTime,
    384                                   &ExitTime,
    385                                   &KernelTime,
    386                                   &UserTime);
    387       if (!success) {
    388         ec = windows_error(::GetLastError());
    389 
    390         errs() << ToolName << ": Failed to get process times: "
    391                << ec.message() << '\n';
    392         return -1;
    393       }
    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
    401       // days.
    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";
    405         return -1;
    406       }
    407 
    408       // We check with > instead of using Timeleft because if
    409       // TotalTimeMiliseconds is greater than Timeout * 1000, TimeLeft would
    410       // underflow.
    411       if (TotalTimeMiliseconds > (Timeout * 1000)) {
    412         errs() << ToolName << ": Process timed out.\n";
    413         ::TerminateProcess(ProcessInfo.hProcess, -1);
    414         // Otherwise other stuff starts failing...
    415         return -1;
    416       }
    417 
    418       TimeLeft = (Timeout * 1000) - static_cast<uint32_t>(TotalTimeMiliseconds);
    419     }
    420     success = WaitForDebugEvent(&DebugEvent, TimeLeft);
    421 
    422     if (!success) {
    423       ec = windows_error(::GetLastError());
    424 
    425       if (ec == errc::timed_out) {
    426         errs() << ToolName << ": Process timed out.\n";
    427         ::TerminateProcess(ProcessInfo.hProcess, -1);
    428         // Otherwise other stuff starts failing...
    429         return -1;
    430       }
    431 
    432       errs() << ToolName << ": Failed to wait for debug event in program: '"
    433              << ProgramToRun << "': " << ec.message() << '\n';
    434       return -1;
    435     }
    436 
    437     switch(DebugEvent.dwDebugEventCode) {
    438     case CREATE_PROCESS_DEBUG_EVENT:
    439       // Make sure we remove the handle on exit.
    440       if (TraceExecution)
    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);
    445       break;
    446     case EXIT_PROCESS_DEBUG_EVENT: {
    447         if (TraceExecution)
    448           errs() << ToolName << ": Debug Event: EXIT_PROCESS_DEBUG_EVENT\n";
    449 
    450         // If this is the process we originally created, exit with its exit
    451         // code.
    452         if (DebugEvent.dwProcessId == ProcessInfo.dwProcessId)
    453           return DebugEvent.u.ExitProcess.dwExitCode;
    454 
    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";
    460           return -1;
    461         }
    462         ::CloseHandle(ExitingProcess->second);
    463         ProcessIDToHandle.erase(ExitingProcess);
    464       }
    465       break;
    466     case CREATE_THREAD_DEBUG_EVENT:
    467       ::CloseHandle(DebugEvent.u.CreateThread.hThread);
    468       break;
    469     case LOAD_DLL_DEBUG_EVENT: {
    470         // Cleanup the file handle.
    471         FileScopedHandle DLLFile(DebugEvent.u.LoadDll.hFile);
    472         std::string DLLName;
    473         ec = GetFileNameFromHandle(DLLFile, DLLName);
    474         if (ec) {
    475           DLLName = "<failed to get file name from file handle> : ";
    476           DLLName += ec.message();
    477         }
    478         if (TraceExecution) {
    479           errs() << ToolName << ": Debug Event: LOAD_DLL_DEBUG_EVENT\n";
    480           errs().indent(ToolName.size()) << ": DLL Name : " << DLLName << '\n';
    481         }
    482 
    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);
    493           return -1;
    494         }
    495       }
    496       break;
    497     case EXCEPTION_DEBUG_EVENT: {
    498         // Close the application if this exception will not be handled by the
    499         // child application.
    500         if (TraceExecution)
    501           errs() << ToolName << ": Debug Event: EXCEPTION_DEBUG_EVENT\n";
    502 
    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";
    513           }
    514           dwContinueStatus = DBG_EXCEPTION_NOT_HANDLED;
    515         } else {
    516           errs() << ToolName << ": Unhandled exception in: " << ProgramToRun
    517                  << "!\n";
    518                  errs().indent(ToolName.size()) << ": location: ";
    519                  errs() << Exception.ExceptionRecord.ExceptionAddress
    520                         << ", exception code: "
    521                         << ExceptionCodeToString(
    522                             Exception.ExceptionRecord.ExceptionCode)
    523                         << " (" << Exception.ExceptionRecord.ExceptionCode
    524                         << ")\n";
    525           dwContinueStatus = DBG_CONTINUE;
    526           ::TerminateProcess(ProcessIDToHandle[DebugEvent.dwProcessId], -1);
    527           return -1;
    528         }
    529       }
    530       break;
    531     default:
    532       // Do nothing.
    533       if (TraceExecution)
    534         errs() << ToolName << ": Debug Event: <unknown>\n";
    535       break;
    536     }
    537 
    538     success = ContinueDebugEvent(DebugEvent.dwProcessId,
    539                                  DebugEvent.dwThreadId,
    540                                  dwContinueStatus);
    541     if (!success) {
    542       ec = windows_error(::GetLastError());
    543       errs() << ToolName << ": Failed to continue debugging program: '"
    544              << ProgramToRun << "': " << ec.message() << '\n';
    545       return -1;
    546     }
    547 
    548     dwContinueStatus = DBG_CONTINUE;
    549   }
    550 
    551   assert(0 && "Fell out of debug loop. This shouldn't be possible!");
    552   return -1;
    553 }
    554