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