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