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