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