KillTheDoctor.cpp 19 KB

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