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