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 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.
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.
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/Support/Signals.h"
45 #include "llvm/Support/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
;
169 static error_code
GetFileNameFromHandle(HANDLE FileHandle
,
171 char Filename
[MAX_PATH
+1];
175 // Get the file size.
176 LARGE_INTEGER FileSize
;
177 Sucess
= ::GetFileSizeEx(FileHandle
, &FileSize
);
180 return windows_error(::GetLastError());
182 // Create a file mapping object.
183 FileMappingScopedHandle
FileMapping(
184 ::CreateFileMappingA(FileHandle
,
192 return windows_error(::GetLastError());
194 // Create a file mapping to get the file name.
195 MappedViewOfFileScopedHandle
MappedFile(
196 ::MapViewOfFile(FileMapping
, FILE_MAP_READ
, 0, 0, 1));
199 return windows_error(::GetLastError());
201 Sucess
= ::GetMappedFileNameA(::GetCurrentProcess(),
204 array_lengthof(Filename
) - 1);
207 return windows_error(::GetLastError());
210 return windows_error::success
;
214 static std::string
QuoteProgramPathIfNeeded(StringRef Command
) {
215 if (Command
.find_first_of(' ') == StringRef::npos
)
219 ret
.reserve(Command
.size() + 3);
221 ret
.append(Command
.begin(), Command
.end());
227 /// @brief Find program using shell lookup rules.
228 /// @param Program This is either an absolute path, relative path, or simple a
229 /// program name. Look in PATH for any programs that match. If no
230 /// extension is present, try all extensions in PATHEXT.
231 /// @return If ec == errc::success, The absolute path to the program. Otherwise
232 /// the return value is undefined.
233 static std::string
FindProgram(const std::string
&Program
, error_code
&ec
) {
234 char PathName
[MAX_PATH
+ 1];
235 typedef SmallVector
<StringRef
, 12> pathext_t
;
237 // Check for the program without an extension (in case it already has one).
238 pathext
.push_back("");
239 SplitString(std::getenv("PATHEXT"), pathext
, ";");
241 for (pathext_t::iterator i
= pathext
.begin(), e
= pathext
.end(); i
!= e
; ++i
){
243 for (std::size_t ii
= 0, e
= i
->size(); ii
!= e
; ++ii
)
244 ext
.push_back(::tolower((*i
)[ii
]));
245 LPCSTR Extension
= NULL
;
246 if (ext
.size() && ext
[0] == '.')
247 Extension
= ext
.c_str();
248 DWORD length
= ::SearchPathA(NULL
,
251 array_lengthof(PathName
),
255 ec
= windows_error(::GetLastError());
256 else if (length
> array_lengthof(PathName
)) {
257 // This may have been the file, return with error.
258 ec
= windows_error::buffer_overflow
;
261 // We found the path! Return it.
262 ec
= windows_error::success
;
267 // Make sure PathName is valid.
268 PathName
[MAX_PATH
] = 0;
272 static error_code
EnableDebugPrivileges() {
274 BOOL success
= ::OpenProcessToken(::GetCurrentProcess(),
275 TOKEN_ADJUST_PRIVILEGES
| TOKEN_QUERY
,
278 return windows_error(::GetLastError());
280 TokenScopedHandle
Token(TokenHandle
);
281 TOKEN_PRIVILEGES TokenPrivileges
;
282 LUID LocallyUniqueID
;
284 success
= ::LookupPrivilegeValueA(NULL
,
288 return windows_error(::GetLastError());
290 TokenPrivileges
.PrivilegeCount
= 1;
291 TokenPrivileges
.Privileges
[0].Luid
= LocallyUniqueID
;
292 TokenPrivileges
.Privileges
[0].Attributes
= SE_PRIVILEGE_ENABLED
;
294 success
= ::AdjustTokenPrivileges(Token
,
297 sizeof(TOKEN_PRIVILEGES
),
300 // The value of success is basically useless. Either way we are just returning
301 // the value of ::GetLastError().
302 return windows_error(::GetLastError());
305 static StringRef
ExceptionCodeToString(DWORD ExceptionCode
) {
306 switch(ExceptionCode
) {
307 case EXCEPTION_ACCESS_VIOLATION
: return "EXCEPTION_ACCESS_VIOLATION";
308 case EXCEPTION_ARRAY_BOUNDS_EXCEEDED
:
309 return "EXCEPTION_ARRAY_BOUNDS_EXCEEDED";
310 case EXCEPTION_BREAKPOINT
: return "EXCEPTION_BREAKPOINT";
311 case EXCEPTION_DATATYPE_MISALIGNMENT
:
312 return "EXCEPTION_DATATYPE_MISALIGNMENT";
313 case EXCEPTION_FLT_DENORMAL_OPERAND
: return "EXCEPTION_FLT_DENORMAL_OPERAND";
314 case EXCEPTION_FLT_DIVIDE_BY_ZERO
: return "EXCEPTION_FLT_DIVIDE_BY_ZERO";
315 case EXCEPTION_FLT_INEXACT_RESULT
: return "EXCEPTION_FLT_INEXACT_RESULT";
316 case EXCEPTION_FLT_INVALID_OPERATION
:
317 return "EXCEPTION_FLT_INVALID_OPERATION";
318 case EXCEPTION_FLT_OVERFLOW
: return "EXCEPTION_FLT_OVERFLOW";
319 case EXCEPTION_FLT_STACK_CHECK
: return "EXCEPTION_FLT_STACK_CHECK";
320 case EXCEPTION_FLT_UNDERFLOW
: return "EXCEPTION_FLT_UNDERFLOW";
321 case EXCEPTION_ILLEGAL_INSTRUCTION
: return "EXCEPTION_ILLEGAL_INSTRUCTION";
322 case EXCEPTION_IN_PAGE_ERROR
: return "EXCEPTION_IN_PAGE_ERROR";
323 case EXCEPTION_INT_DIVIDE_BY_ZERO
: return "EXCEPTION_INT_DIVIDE_BY_ZERO";
324 case EXCEPTION_INT_OVERFLOW
: return "EXCEPTION_INT_OVERFLOW";
325 case EXCEPTION_INVALID_DISPOSITION
: return "EXCEPTION_INVALID_DISPOSITION";
326 case EXCEPTION_NONCONTINUABLE_EXCEPTION
:
327 return "EXCEPTION_NONCONTINUABLE_EXCEPTION";
328 case EXCEPTION_PRIV_INSTRUCTION
: return "EXCEPTION_PRIV_INSTRUCTION";
329 case EXCEPTION_SINGLE_STEP
: return "EXCEPTION_SINGLE_STEP";
330 case EXCEPTION_STACK_OVERFLOW
: return "EXCEPTION_STACK_OVERFLOW";
331 default: return "<unknown>";
335 int main(int argc
, char **argv
) {
336 // Print a stack trace if we signal out.
337 sys::PrintStackTraceOnErrorSignal();
338 PrettyStackTraceProgram
X(argc
, argv
);
339 llvm_shutdown_obj Y
; // Call llvm_shutdown() on exit.
343 cl::ParseCommandLineOptions(argc
, argv
, "Dr. Watson Assassin.\n");
344 if (ProgramToRun
.size() == 0) {
345 cl::PrintHelpMessage();
349 if (Timeout
> std::numeric_limits
<uint32_t>::max() / 1000) {
350 errs() << ToolName
<< ": Timeout value too large, must be less than: "
351 << std::numeric_limits
<uint32_t>::max() / 1000
356 std::string
CommandLine(ProgramToRun
);
359 ProgramToRun
= FindProgram(ProgramToRun
, ec
);
361 errs() << ToolName
<< ": Failed to find program: '" << CommandLine
362 << "': " << ec
.message() << '\n';
367 errs() << ToolName
<< ": Found Program: " << ProgramToRun
<< '\n';
369 for (std::vector
<std::string
>::iterator i
= Argv
.begin(),
372 CommandLine
.push_back(' ');
373 CommandLine
.append(*i
);
377 errs() << ToolName
<< ": Program Image Path: " << ProgramToRun
<< '\n'
378 << ToolName
<< ": Command Line: " << CommandLine
<< '\n';
380 STARTUPINFO StartupInfo
;
381 PROCESS_INFORMATION ProcessInfo
;
382 std::memset(&StartupInfo
, 0, sizeof(StartupInfo
));
383 StartupInfo
.cb
= sizeof(StartupInfo
);
384 std::memset(&ProcessInfo
, 0, sizeof(ProcessInfo
));
386 // Set error mode to not display any message boxes. The child process inherits
388 ::SetErrorMode(SEM_FAILCRITICALERRORS
| SEM_NOGPFAULTERRORBOX
);
389 ::_set_error_mode(_OUT_TO_STDERR
);
391 BOOL success
= ::CreateProcessA(ProgramToRun
.c_str(),
392 LPSTR(CommandLine
.c_str()),
402 errs() << ToolName
<< ": Failed to run program: '" << ProgramToRun
403 << "': " << error_code(windows_error(::GetLastError())).message()
408 // Make sure ::CloseHandle is called on exit.
409 std::map
<DWORD
, HANDLE
> ProcessIDToHandle
;
411 DEBUG_EVENT DebugEvent
;
412 std::memset(&DebugEvent
, 0, sizeof(DebugEvent
));
413 DWORD dwContinueStatus
= DBG_CONTINUE
;
415 // Run the program under the debugger until either it exits, or throws an
418 errs() << ToolName
<< ": Debugging...\n";
421 DWORD TimeLeft
= INFINITE
;
423 FILETIME CreationTime
, ExitTime
, KernelTime
, UserTime
;
425 success
= ::GetProcessTimes(ProcessInfo
.hProcess
,
431 ec
= windows_error(::GetLastError());
433 errs() << ToolName
<< ": Failed to get process times: "
434 << ec
.message() << '\n';
437 a
.LowPart
= KernelTime
.dwLowDateTime
;
438 a
.HighPart
= KernelTime
.dwHighDateTime
;
439 b
.LowPart
= UserTime
.dwLowDateTime
;
440 b
.HighPart
= UserTime
.dwHighDateTime
;
441 // Convert 100-nanosecond units to milliseconds.
442 uint64_t TotalTimeMiliseconds
= (a
.QuadPart
+ b
.QuadPart
) / 10000;
443 // Handle the case where the process has been running for more than 49
445 if (TotalTimeMiliseconds
> std::numeric_limits
<uint32_t>::max()) {
446 errs() << ToolName
<< ": Timeout Failed: Process has been running for"
447 "more than 49 days.\n";
451 // We check with > instead of using Timeleft because if
452 // TotalTimeMiliseconds is greater than Timeout * 1000, TimeLeft would
454 if (TotalTimeMiliseconds
> (Timeout
* 1000)) {
455 errs() << ToolName
<< ": Process timed out.\n";
456 ::TerminateProcess(ProcessInfo
.hProcess
, -1);
457 // Otherwise other stuff starts failing...
461 TimeLeft
= (Timeout
* 1000) - static_cast<uint32_t>(TotalTimeMiliseconds
);
463 success
= WaitForDebugEvent(&DebugEvent
, TimeLeft
);
466 ec
= windows_error(::GetLastError());
468 if (ec
== errc::timed_out
) {
469 errs() << ToolName
<< ": Process timed out.\n";
470 ::TerminateProcess(ProcessInfo
.hProcess
, -1);
471 // Otherwise other stuff starts failing...
475 errs() << ToolName
<< ": Failed to wait for debug event in program: '"
476 << ProgramToRun
<< "': " << ec
.message() << '\n';
480 switch(DebugEvent
.dwDebugEventCode
) {
481 case CREATE_PROCESS_DEBUG_EVENT
:
482 // Make sure we remove the handle on exit.
484 errs() << ToolName
<< ": Debug Event: CREATE_PROCESS_DEBUG_EVENT\n";
485 ProcessIDToHandle
[DebugEvent
.dwProcessId
] =
486 DebugEvent
.u
.CreateProcessInfo
.hProcess
;
487 ::CloseHandle(DebugEvent
.u
.CreateProcessInfo
.hFile
);
489 case EXIT_PROCESS_DEBUG_EVENT
: {
491 errs() << ToolName
<< ": Debug Event: EXIT_PROCESS_DEBUG_EVENT\n";
493 // If this is the process we originally created, exit with its exit
495 if (DebugEvent
.dwProcessId
== ProcessInfo
.dwProcessId
)
496 return DebugEvent
.u
.ExitProcess
.dwExitCode
;
498 // Otherwise cleanup any resources we have for it.
499 std::map
<DWORD
, HANDLE
>::iterator ExitingProcess
=
500 ProcessIDToHandle
.find(DebugEvent
.dwProcessId
);
501 if (ExitingProcess
== ProcessIDToHandle
.end()) {
502 errs() << ToolName
<< ": Got unknown process id!\n";
505 ::CloseHandle(ExitingProcess
->second
);
506 ProcessIDToHandle
.erase(ExitingProcess
);
509 case CREATE_THREAD_DEBUG_EVENT
:
510 ::CloseHandle(DebugEvent
.u
.CreateThread
.hThread
);
512 case LOAD_DLL_DEBUG_EVENT
: {
513 // Cleanup the file handle.
514 FileScopedHandle
DLLFile(DebugEvent
.u
.LoadDll
.hFile
);
516 ec
= GetFileNameFromHandle(DLLFile
, DLLName
);
518 DLLName
= "<failed to get file name from file handle> : ";
519 DLLName
+= ec
.message();
521 if (TraceExecution
) {
522 errs() << ToolName
<< ": Debug Event: LOAD_DLL_DEBUG_EVENT\n";
523 errs().indent(ToolName
.size()) << ": DLL Name : " << DLLName
<< '\n';
526 if (NoUser32
&& sys::path::stem(DLLName
) == "user32") {
527 // Program is loading user32.dll, in the applications we are testing,
528 // this only happens if an assert has fired. By now the message has
529 // already been printed, so simply close the program.
530 errs() << ToolName
<< ": user32.dll loaded!\n";
531 errs().indent(ToolName
.size())
532 << ": This probably means that assert was called. Closing "
533 "program to prevent message box from popping up.\n";
534 dwContinueStatus
= DBG_CONTINUE
;
535 ::TerminateProcess(ProcessIDToHandle
[DebugEvent
.dwProcessId
], -1);
540 case EXCEPTION_DEBUG_EVENT
: {
541 // Close the application if this exception will not be handled by the
542 // child application.
544 errs() << ToolName
<< ": Debug Event: EXCEPTION_DEBUG_EVENT\n";
546 EXCEPTION_DEBUG_INFO
&Exception
= DebugEvent
.u
.Exception
;
547 if (Exception
.dwFirstChance
> 0) {
548 if (TraceExecution
) {
549 errs().indent(ToolName
.size()) << ": Debug Info : ";
550 errs() << "First chance exception at "
551 << Exception
.ExceptionRecord
.ExceptionAddress
552 << ", exception code: "
553 << ExceptionCodeToString(
554 Exception
.ExceptionRecord
.ExceptionCode
)
555 << " (" << Exception
.ExceptionRecord
.ExceptionCode
<< ")\n";
557 dwContinueStatus
= DBG_EXCEPTION_NOT_HANDLED
;
559 errs() << ToolName
<< ": Unhandled exception in: " << ProgramToRun
561 errs().indent(ToolName
.size()) << ": location: ";
562 errs() << Exception
.ExceptionRecord
.ExceptionAddress
563 << ", exception code: "
564 << ExceptionCodeToString(
565 Exception
.ExceptionRecord
.ExceptionCode
)
566 << " (" << Exception
.ExceptionRecord
.ExceptionCode
568 dwContinueStatus
= DBG_CONTINUE
;
569 ::TerminateProcess(ProcessIDToHandle
[DebugEvent
.dwProcessId
], -1);
577 errs() << ToolName
<< ": Debug Event: <unknown>\n";
581 success
= ContinueDebugEvent(DebugEvent
.dwProcessId
,
582 DebugEvent
.dwThreadId
,
585 ec
= windows_error(::GetLastError());
586 errs() << ToolName
<< ": Failed to continue debugging program: '"
587 << ProgramToRun
<< "': " << ec
.message() << '\n';
591 dwContinueStatus
= DBG_CONTINUE
;
594 assert(0 && "Fell out of debug loop. This shouldn't be possible!");