1 //===- KillTheDoctor - Prevent Dr. Watson from stopping tests ---*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This program provides an extremely hacky way to stop Dr. Watson from starting
11 // due to unhandled exceptions in child processes.
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).
18 // This also provides another really hacky method to prevent assert dialog boxes
19 // from poping 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.
26 // If the subprocess exits for any reason other than sucessful termination, -1
27 // is returned. If the process exits normally the value it returned is returned.
31 //===----------------------------------------------------------------------===//
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/System/Signals.h"
45 #include "system_error.h"
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."));
73 template <typename HandleType
>
75 typedef typename
HandleType::handle_type handle_type
;
81 : Handle(HandleType::GetInvalidHandle()) {}
83 explicit ScopedHandle(handle_type handle
)
87 HandleType::Destruct(Handle
);
90 ScopedHandle
& operator=(handle_type handle
) {
91 // Cleanup current handle.
92 if (!HandleType::isValid(Handle
))
93 HandleType::Destruct(Handle
);
98 operator bool() const {
99 return HandleType::isValid(Handle
);
102 operator handle_type() {
107 // This implements the most common handle in the Windows API.
108 struct CommonHandle
{
109 typedef HANDLE handle_type
;
111 static handle_type
GetInvalidHandle() {
112 return INVALID_HANDLE_VALUE
;
115 static void Destruct(handle_type Handle
) {
116 ::CloseHandle(Handle
);
119 static bool isValid(handle_type Handle
) {
120 return Handle
!= GetInvalidHandle();
124 struct FileMappingHandle
{
125 typedef HANDLE handle_type
;
127 static handle_type
GetInvalidHandle() {
131 static void Destruct(handle_type Handle
) {
132 ::CloseHandle(Handle
);
135 static bool isValid(handle_type Handle
) {
136 return Handle
!= GetInvalidHandle();
140 struct MappedViewOfFileHandle
{
141 typedef LPVOID handle_type
;
143 static handle_type
GetInvalidHandle() {
147 static void Destruct(handle_type Handle
) {
148 ::UnmapViewOfFile(Handle
);
151 static bool isValid(handle_type Handle
) {
152 return Handle
!= GetInvalidHandle();
156 struct ProcessHandle
: CommonHandle
{};
157 struct ThreadHandle
: CommonHandle
{};
158 struct TokenHandle
: CommonHandle
{};
159 struct FileHandle
: CommonHandle
{};
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
;
168 error_code
get_windows_last_error() {
169 return make_error_code(windows_error(::GetLastError()));
173 static error_code
GetFileNameFromHandle(HANDLE FileHandle
,
175 char Filename
[MAX_PATH
+1];
179 // Get the file size.
180 LARGE_INTEGER FileSize
;
181 Sucess
= ::GetFileSizeEx(FileHandle
, &FileSize
);
184 return get_windows_last_error();
186 // Create a file mapping object.
187 FileMappingScopedHandle
FileMapping(
188 ::CreateFileMappingA(FileHandle
,
196 return get_windows_last_error();
198 // Create a file mapping to get the file name.
199 MappedViewOfFileScopedHandle
MappedFile(
200 ::MapViewOfFile(FileMapping
, FILE_MAP_READ
, 0, 0, 1));
203 return get_windows_last_error();
205 Sucess
= ::GetMappedFileNameA(::GetCurrentProcess(),
208 array_lengthof(Filename
) - 1);
211 return get_windows_last_error();
214 return windows_error::success
;
218 static std::string
QuoteProgramPathIfNeeded(StringRef Command
) {
219 if (Command
.find_first_of(' ') == StringRef::npos
)
223 ret
.reserve(Command
.size() + 3);
225 ret
.append(Command
.begin(), Command
.end());
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
;
241 // Check for the program without an extension (in case it already has one).
242 pathext
.push_back("");
243 SplitString(std::getenv("PATHEXT"), pathext
, ";");
245 for (pathext_t::iterator i
= pathext
.begin(), e
= pathext
.end(); i
!= e
; ++i
){
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
,
255 array_lengthof(PathName
),
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
);
265 // We found the path! Return it.
266 ec
= windows_error::success
;
271 // Make sure PathName is valid.
272 PathName
[MAX_PATH
] = 0;
276 static error_code
EnableDebugPrivileges() {
278 BOOL success
= ::OpenProcessToken(::GetCurrentProcess(),
279 TOKEN_ADJUST_PRIVILEGES
| TOKEN_QUERY
,
282 return error_code(::GetLastError(), system_category());
284 TokenScopedHandle
Token(TokenHandle
);
285 TOKEN_PRIVILEGES TokenPrivileges
;
286 LUID LocallyUniqueID
;
288 success
= ::LookupPrivilegeValueA(NULL
,
292 return error_code(::GetLastError(), system_category());
294 TokenPrivileges
.PrivilegeCount
= 1;
295 TokenPrivileges
.Privileges
[0].Luid
= LocallyUniqueID
;
296 TokenPrivileges
.Privileges
[0].Attributes
= SE_PRIVILEGE_ENABLED
;
298 success
= ::AdjustTokenPrivileges(Token
,
301 sizeof(TOKEN_PRIVILEGES
),
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());
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>";
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.
347 cl::ParseCommandLineOptions(argc
, argv
, "Dr. Watson Assassin.\n");
348 if (ProgramToRun
.size() == 0) {
349 cl::PrintHelpMessage();
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
360 std::string
CommandLine(ProgramToRun
);
363 ProgramToRun
= FindProgram(ProgramToRun
, ec
);
365 errs() << ToolName
<< ": Failed to find program: '" << CommandLine
366 << "': " << ec
.message() << '\n';
371 errs() << ToolName
<< ": Found Program: " << ProgramToRun
<< '\n';
373 for (std::vector
<std::string
>::iterator i
= Argv
.begin(),
376 CommandLine
.push_back(' ');
377 CommandLine
.append(*i
);
381 errs() << ToolName
<< ": Program Image Path: " << ProgramToRun
<< '\n'
382 << ToolName
<< ": Command Line: " << CommandLine
<< '\n';
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
));
390 // Set error mode to not display any message boxes. The child process inherets
392 ::SetErrorMode(SEM_FAILCRITICALERRORS
| SEM_NOGPFAULTERRORBOX
);
393 ::_set_error_mode(_OUT_TO_STDERR
);
395 BOOL success
= ::CreateProcessA(ProgramToRun
.c_str(),
396 LPSTR(CommandLine
.c_str()),
406 errs() << ToolName
<< ": Failed to run program: '" << ProgramToRun
407 << "': " << error_code(::GetLastError(), system_category()).message()
412 // Make sure ::CloseHandle is called on exit.
413 std::map
<DWORD
, HANDLE
> ProcessIDToHandle
;
415 DEBUG_EVENT DebugEvent
;
416 std::memset(&DebugEvent
, 0, sizeof(DebugEvent
));
417 DWORD dwContinueStatus
= DBG_CONTINUE
;
419 // Run the program under the debugger until either it exits, or throws an
422 errs() << ToolName
<< ": Debugging...\n";
425 DWORD TimeLeft
= INFINITE
;
427 FILETIME CreationTime
, ExitTime
, KernelTime
, UserTime
;
429 success
= ::GetProcessTimes(ProcessInfo
.hProcess
,
435 ec
= error_code(::GetLastError(), system_category());
437 errs() << ToolName
<< ": Failed to get process times: "
438 << ec
.message() << '\n';
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 miliseconds.
446 uint64_t TotalTimeMiliseconds
= (a
.QuadPart
+ b
.QuadPart
) / 10000;
447 // Handle the case where the process has been running for more than 49
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";
455 // We check with > instead of using Timeleft because if
456 // TotalTimeMiliseconds is greater than Timeout * 1000, TimeLeft would
458 if (TotalTimeMiliseconds
> (Timeout
* 1000)) {
459 errs() << ToolName
<< ": Process timed out.\n";
460 ::TerminateProcess(ProcessInfo
.hProcess
, -1);
461 // Otherwise other stuff starts failing...
465 TimeLeft
= (Timeout
* 1000) - static_cast<uint32_t>(TotalTimeMiliseconds
);
467 success
= WaitForDebugEvent(&DebugEvent
, TimeLeft
);
470 ec
= error_code(::GetLastError(), system_category());
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...
479 errs() << ToolName
<< ": Failed to wait for debug event in program: '"
480 << ProgramToRun
<< "': " << ec
.message() << '\n';
484 switch(DebugEvent
.dwDebugEventCode
) {
485 case CREATE_PROCESS_DEBUG_EVENT
:
486 // Make sure we remove the handle on exit.
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
);
493 case EXIT_PROCESS_DEBUG_EVENT
: {
495 errs() << ToolName
<< ": Debug Event: EXIT_PROCESS_DEBUG_EVENT\n";
497 // If this is the process we origionally created, exit with its exit
499 if (DebugEvent
.dwProcessId
== ProcessInfo
.dwProcessId
)
500 return DebugEvent
.u
.ExitProcess
.dwExitCode
;
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";
509 ::CloseHandle(ExitingProcess
->second
);
510 ProcessIDToHandle
.erase(ExitingProcess
);
513 case CREATE_THREAD_DEBUG_EVENT
:
514 ::CloseHandle(DebugEvent
.u
.CreateThread
.hThread
);
516 case LOAD_DLL_DEBUG_EVENT
: {
517 // Cleanup the file handle.
518 FileScopedHandle
DLLFile(DebugEvent
.u
.LoadDll
.hFile
);
520 ec
= GetFileNameFromHandle(DLLFile
, DLLName
);
522 DLLName
= "<failed to get file name from file handle> : ";
523 DLLName
+= ec
.message();
525 if (TraceExecution
) {
526 errs() << ToolName
<< ": Debug Event: LOAD_DLL_DEBUG_EVENT\n";
527 errs().indent(ToolName
.size()) << ": DLL Name : " << DLLName
<< '\n';
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 poping up.\n";
538 dwContinueStatus
= DBG_CONTINUE
;
539 ::TerminateProcess(ProcessIDToHandle
[DebugEvent
.dwProcessId
], -1);
544 case EXCEPTION_DEBUG_EVENT
: {
545 // Close the application if this exception will not be handled by the
546 // child application.
548 errs() << ToolName
<< ": Debug Event: EXCEPTION_DEBUG_EVENT\n";
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";
561 dwContinueStatus
= DBG_EXCEPTION_NOT_HANDLED
;
563 errs() << ToolName
<< ": Unhandled exception in: " << ProgramToRun
565 errs().indent(ToolName
.size()) << ": location: ";
566 errs() << Exception
.ExceptionRecord
.ExceptionAddress
567 << ", exception code: "
568 << ExceptionCodeToString(
569 Exception
.ExceptionRecord
.ExceptionCode
)
570 << " (" << Exception
.ExceptionRecord
.ExceptionCode
572 dwContinueStatus
= DBG_CONTINUE
;
573 ::TerminateProcess(ProcessIDToHandle
[DebugEvent
.dwProcessId
], -1);
581 errs() << ToolName
<< ": Debug Event: <unknown>\n";
585 success
= ContinueDebugEvent(DebugEvent
.dwProcessId
,
586 DebugEvent
.dwThreadId
,
589 ec
= error_code(::GetLastError(), system_category());
590 errs() << ToolName
<< ": Failed to continue debugging program: '"
591 << ProgramToRun
<< "': " << ec
.message() << '\n';
595 dwContinueStatus
= DBG_CONTINUE
;
598 assert(0 && "Fell out of debug loop. This shouldn't be possible!");