1696bd635SAlexander Shaposhnikov //===-- DebuggerThread.cpp --------------------------------------*- C++ -*-===//
24ad5def9SAdrian McCarthy //
34ad5def9SAdrian McCarthy //                     The LLVM Compiler Infrastructure
44ad5def9SAdrian McCarthy //
54ad5def9SAdrian McCarthy // This file is distributed under the University of Illinois Open Source
64ad5def9SAdrian McCarthy // License. See LICENSE.TXT for details.
74ad5def9SAdrian McCarthy //
84ad5def9SAdrian McCarthy //===----------------------------------------------------------------------===//
94ad5def9SAdrian McCarthy 
104ad5def9SAdrian McCarthy #include "DebuggerThread.h"
114ad5def9SAdrian McCarthy #include "ExceptionRecord.h"
124ad5def9SAdrian McCarthy #include "IDebugDelegate.h"
134ad5def9SAdrian McCarthy 
144ad5def9SAdrian McCarthy #include "lldb/Core/ModuleSpec.h"
154ad5def9SAdrian McCarthy #include "lldb/Host/Predicate.h"
164ad5def9SAdrian McCarthy #include "lldb/Host/ThreadLauncher.h"
174ad5def9SAdrian McCarthy #include "lldb/Host/windows/HostProcessWindows.h"
184ad5def9SAdrian McCarthy #include "lldb/Host/windows/HostThreadWindows.h"
194ad5def9SAdrian McCarthy #include "lldb/Host/windows/ProcessLauncherWindows.h"
204ad5def9SAdrian McCarthy #include "lldb/Target/Process.h"
214ad5def9SAdrian McCarthy #include "lldb/Target/ProcessLaunchInfo.h"
225713a05bSZachary Turner #include "lldb/Utility/FileSpec.h"
236f9e6901SZachary Turner #include "lldb/Utility/Log.h"
2497206d57SZachary Turner #include "lldb/Utility/Status.h"
254ad5def9SAdrian McCarthy 
264ad5def9SAdrian McCarthy #include "Plugins/Process/Windows/Common/ProcessWindowsLog.h"
274ad5def9SAdrian McCarthy 
284ad5def9SAdrian McCarthy #include "llvm/ADT/STLExtras.h"
294ad5def9SAdrian McCarthy #include "llvm/Support/ConvertUTF.h"
30ed96be99SZachary Turner #include "llvm/Support/Threading.h"
314ad5def9SAdrian McCarthy #include "llvm/Support/raw_ostream.h"
324ad5def9SAdrian McCarthy 
334ad5def9SAdrian McCarthy using namespace lldb;
344ad5def9SAdrian McCarthy using namespace lldb_private;
354ad5def9SAdrian McCarthy 
364ad5def9SAdrian McCarthy namespace {
374ad5def9SAdrian McCarthy struct DebugLaunchContext {
384ad5def9SAdrian McCarthy   DebugLaunchContext(DebuggerThread *thread,
394ad5def9SAdrian McCarthy                      const ProcessLaunchInfo &launch_info)
404ad5def9SAdrian McCarthy       : m_thread(thread), m_launch_info(launch_info) {}
414ad5def9SAdrian McCarthy   DebuggerThread *m_thread;
424ad5def9SAdrian McCarthy   ProcessLaunchInfo m_launch_info;
434ad5def9SAdrian McCarthy };
444ad5def9SAdrian McCarthy 
454ad5def9SAdrian McCarthy struct DebugAttachContext {
464ad5def9SAdrian McCarthy   DebugAttachContext(DebuggerThread *thread, lldb::pid_t pid,
474ad5def9SAdrian McCarthy                      const ProcessAttachInfo &attach_info)
484ad5def9SAdrian McCarthy       : m_thread(thread), m_pid(pid), m_attach_info(attach_info) {}
494ad5def9SAdrian McCarthy   DebuggerThread *m_thread;
504ad5def9SAdrian McCarthy   lldb::pid_t m_pid;
514ad5def9SAdrian McCarthy   ProcessAttachInfo m_attach_info;
524ad5def9SAdrian McCarthy };
534ad5def9SAdrian McCarthy }
544ad5def9SAdrian McCarthy 
554ad5def9SAdrian McCarthy DebuggerThread::DebuggerThread(DebugDelegateSP debug_delegate)
564ad5def9SAdrian McCarthy     : m_debug_delegate(debug_delegate), m_pid_to_detach(0),
574ad5def9SAdrian McCarthy       m_is_shutting_down(false) {
584ad5def9SAdrian McCarthy   m_debugging_ended_event = ::CreateEvent(nullptr, TRUE, FALSE, nullptr);
594ad5def9SAdrian McCarthy }
604ad5def9SAdrian McCarthy 
614ad5def9SAdrian McCarthy DebuggerThread::~DebuggerThread() { ::CloseHandle(m_debugging_ended_event); }
624ad5def9SAdrian McCarthy 
6397206d57SZachary Turner Status DebuggerThread::DebugLaunch(const ProcessLaunchInfo &launch_info) {
64a385d2c1SPavel Labath   Log *log = ProcessWindowsLog::GetLogIfAny(WINDOWS_LOG_PROCESS);
65a385d2c1SPavel Labath   LLDB_LOG(log, "launching '{0}'", launch_info.GetExecutableFile().GetPath());
664ad5def9SAdrian McCarthy 
6797206d57SZachary Turner   Status error;
684ad5def9SAdrian McCarthy   DebugLaunchContext *context = new DebugLaunchContext(this, launch_info);
694ad5def9SAdrian McCarthy   HostThread slave_thread(ThreadLauncher::LaunchThread(
704ad5def9SAdrian McCarthy       "lldb.plugin.process-windows.slave[?]", DebuggerThreadLaunchRoutine,
714ad5def9SAdrian McCarthy       context, &error));
724ad5def9SAdrian McCarthy 
73a385d2c1SPavel Labath   if (!error.Success())
74a385d2c1SPavel Labath     LLDB_LOG(log, "couldn't launch debugger thread. {0}", error);
754ad5def9SAdrian McCarthy 
764ad5def9SAdrian McCarthy   return error;
774ad5def9SAdrian McCarthy }
784ad5def9SAdrian McCarthy 
7997206d57SZachary Turner Status DebuggerThread::DebugAttach(lldb::pid_t pid,
804ad5def9SAdrian McCarthy                                    const ProcessAttachInfo &attach_info) {
81a385d2c1SPavel Labath   Log *log = ProcessWindowsLog::GetLogIfAny(WINDOWS_LOG_PROCESS);
82a385d2c1SPavel Labath   LLDB_LOG(log, "attaching to '{0}'", pid);
834ad5def9SAdrian McCarthy 
8497206d57SZachary Turner   Status error;
854ad5def9SAdrian McCarthy   DebugAttachContext *context = new DebugAttachContext(this, pid, attach_info);
864ad5def9SAdrian McCarthy   HostThread slave_thread(ThreadLauncher::LaunchThread(
874ad5def9SAdrian McCarthy       "lldb.plugin.process-windows.slave[?]", DebuggerThreadAttachRoutine,
884ad5def9SAdrian McCarthy       context, &error));
894ad5def9SAdrian McCarthy 
90a385d2c1SPavel Labath   if (!error.Success())
91a385d2c1SPavel Labath     LLDB_LOG(log, "couldn't attach to process '{0}'. {1}", pid, error);
924ad5def9SAdrian McCarthy 
934ad5def9SAdrian McCarthy   return error;
944ad5def9SAdrian McCarthy }
954ad5def9SAdrian McCarthy 
964ad5def9SAdrian McCarthy lldb::thread_result_t DebuggerThread::DebuggerThreadLaunchRoutine(void *data) {
974ad5def9SAdrian McCarthy   DebugLaunchContext *context = static_cast<DebugLaunchContext *>(data);
984ad5def9SAdrian McCarthy   lldb::thread_result_t result =
994ad5def9SAdrian McCarthy       context->m_thread->DebuggerThreadLaunchRoutine(context->m_launch_info);
1004ad5def9SAdrian McCarthy   delete context;
1014ad5def9SAdrian McCarthy   return result;
1024ad5def9SAdrian McCarthy }
1034ad5def9SAdrian McCarthy 
1044ad5def9SAdrian McCarthy lldb::thread_result_t DebuggerThread::DebuggerThreadAttachRoutine(void *data) {
1054ad5def9SAdrian McCarthy   DebugAttachContext *context = static_cast<DebugAttachContext *>(data);
1064ad5def9SAdrian McCarthy   lldb::thread_result_t result = context->m_thread->DebuggerThreadAttachRoutine(
1074ad5def9SAdrian McCarthy       context->m_pid, context->m_attach_info);
1084ad5def9SAdrian McCarthy   delete context;
1094ad5def9SAdrian McCarthy   return result;
1104ad5def9SAdrian McCarthy }
1114ad5def9SAdrian McCarthy 
1124ad5def9SAdrian McCarthy lldb::thread_result_t DebuggerThread::DebuggerThreadLaunchRoutine(
1134ad5def9SAdrian McCarthy     const ProcessLaunchInfo &launch_info) {
1144ad5def9SAdrian McCarthy   // Grab a shared_ptr reference to this so that we know it won't get deleted
11505097246SAdrian Prantl   // until after the thread routine has exited.
1164ad5def9SAdrian McCarthy   std::shared_ptr<DebuggerThread> this_ref(shared_from_this());
1174ad5def9SAdrian McCarthy 
118a385d2c1SPavel Labath   Log *log = ProcessWindowsLog::GetLogIfAny(WINDOWS_LOG_PROCESS);
119a385d2c1SPavel Labath   LLDB_LOG(log, "preparing to launch '{0}' on background thread.",
120a385d2c1SPavel Labath            launch_info.GetExecutableFile().GetPath());
1214ad5def9SAdrian McCarthy 
12297206d57SZachary Turner   Status error;
1234ad5def9SAdrian McCarthy   ProcessLauncherWindows launcher;
1244ad5def9SAdrian McCarthy   HostProcess process(launcher.LaunchProcess(launch_info, error));
1254ad5def9SAdrian McCarthy   // If we couldn't create the process, notify waiters immediately.  Otherwise
12605097246SAdrian Prantl   // enter the debug loop and wait until we get the create process debug
12705097246SAdrian Prantl   // notification.  Note that if the process was created successfully, we can
12805097246SAdrian Prantl   // throw away the process handle we got from CreateProcess because Windows
12905097246SAdrian Prantl   // will give us another (potentially more useful?) handle when it sends us
13005097246SAdrian Prantl   // the CREATE_PROCESS_DEBUG_EVENT.
1314ad5def9SAdrian McCarthy   if (error.Success())
1324ad5def9SAdrian McCarthy     DebugLoop();
1334ad5def9SAdrian McCarthy   else
1344ad5def9SAdrian McCarthy     m_debug_delegate->OnDebuggerError(error, 0);
1354ad5def9SAdrian McCarthy 
1364ad5def9SAdrian McCarthy   return 0;
1374ad5def9SAdrian McCarthy }
1384ad5def9SAdrian McCarthy 
1394ad5def9SAdrian McCarthy lldb::thread_result_t DebuggerThread::DebuggerThreadAttachRoutine(
1404ad5def9SAdrian McCarthy     lldb::pid_t pid, const ProcessAttachInfo &attach_info) {
1414ad5def9SAdrian McCarthy   // Grab a shared_ptr reference to this so that we know it won't get deleted
14205097246SAdrian Prantl   // until after the thread routine has exited.
1434ad5def9SAdrian McCarthy   std::shared_ptr<DebuggerThread> this_ref(shared_from_this());
1444ad5def9SAdrian McCarthy 
145a385d2c1SPavel Labath   Log *log = ProcessWindowsLog::GetLogIfAny(WINDOWS_LOG_PROCESS);
146a385d2c1SPavel Labath   LLDB_LOG(log, "preparing to attach to process '{0}' on background thread.",
1474ad5def9SAdrian McCarthy            pid);
1484ad5def9SAdrian McCarthy 
1494ad5def9SAdrian McCarthy   if (!DebugActiveProcess((DWORD)pid)) {
15097206d57SZachary Turner     Status error(::GetLastError(), eErrorTypeWin32);
1514ad5def9SAdrian McCarthy     m_debug_delegate->OnDebuggerError(error, 0);
1524ad5def9SAdrian McCarthy     return 0;
1534ad5def9SAdrian McCarthy   }
1544ad5def9SAdrian McCarthy 
15505097246SAdrian Prantl   // The attach was successful, enter the debug loop.  From here on out, this
15605097246SAdrian Prantl   // is no different than a create process operation, so all the same comments
15705097246SAdrian Prantl   // in DebugLaunch should apply from this point out.
1584ad5def9SAdrian McCarthy   DebugLoop();
1594ad5def9SAdrian McCarthy 
1604ad5def9SAdrian McCarthy   return 0;
1614ad5def9SAdrian McCarthy }
1624ad5def9SAdrian McCarthy 
16397206d57SZachary Turner Status DebuggerThread::StopDebugging(bool terminate) {
16497206d57SZachary Turner   Status error;
1654ad5def9SAdrian McCarthy 
1664ad5def9SAdrian McCarthy   lldb::pid_t pid = m_process.GetProcessId();
1674ad5def9SAdrian McCarthy 
168a385d2c1SPavel Labath   Log *log = ProcessWindowsLog::GetLogIfAny(WINDOWS_LOG_PROCESS);
169a385d2c1SPavel Labath   LLDB_LOG(log, "terminate = {0}, inferior={1}.", terminate, pid);
1704ad5def9SAdrian McCarthy 
1714ad5def9SAdrian McCarthy   // Set m_is_shutting_down to true if it was false.  Return if it was already
1724ad5def9SAdrian McCarthy   // true.
1734ad5def9SAdrian McCarthy   bool expected = false;
1744ad5def9SAdrian McCarthy   if (!m_is_shutting_down.compare_exchange_strong(expected, true))
1754ad5def9SAdrian McCarthy     return error;
1764ad5def9SAdrian McCarthy 
1774ad5def9SAdrian McCarthy   // Make a copy of the process, since the termination sequence will reset
1784ad5def9SAdrian McCarthy   // DebuggerThread's internal copy and it needs to remain open for the Wait
1794ad5def9SAdrian McCarthy   // operation.
1804ad5def9SAdrian McCarthy   HostProcess process_copy = m_process;
1814ad5def9SAdrian McCarthy   lldb::process_t handle = m_process.GetNativeProcess().GetSystemHandle();
1824ad5def9SAdrian McCarthy 
1834ad5def9SAdrian McCarthy   if (terminate) {
1844ad5def9SAdrian McCarthy     // Initiate the termination before continuing the exception, so that the
18505097246SAdrian Prantl     // next debug event we get is the exit process event, and not some other
18605097246SAdrian Prantl     // event.
1874ad5def9SAdrian McCarthy     BOOL terminate_suceeded = TerminateProcess(handle, 0);
188a385d2c1SPavel Labath     LLDB_LOG(log,
189a385d2c1SPavel Labath              "calling TerminateProcess({0}, 0) (inferior={1}), success={2}",
190a385d2c1SPavel Labath              handle, pid, terminate_suceeded);
1914ad5def9SAdrian McCarthy   }
1924ad5def9SAdrian McCarthy 
1934ad5def9SAdrian McCarthy   // If we're stuck waiting for an exception to continue (e.g. the user is at a
19405097246SAdrian Prantl   // breakpoint messing around in the debugger), continue it now.  But only
19505097246SAdrian Prantl   // AFTER calling TerminateProcess to make sure that the very next call to
19605097246SAdrian Prantl   // WaitForDebugEvent is an exit process event.
1974ad5def9SAdrian McCarthy   if (m_active_exception.get()) {
198a385d2c1SPavel Labath     LLDB_LOG(log, "masking active exception");
1994ad5def9SAdrian McCarthy     ContinueAsyncException(ExceptionResult::MaskException);
2004ad5def9SAdrian McCarthy   }
2014ad5def9SAdrian McCarthy 
2024ad5def9SAdrian McCarthy   if (!terminate) {
2034ad5def9SAdrian McCarthy     // Indicate that we want to detach.
2044ad5def9SAdrian McCarthy     m_pid_to_detach = GetProcess().GetProcessId();
2054ad5def9SAdrian McCarthy 
2064ad5def9SAdrian McCarthy     // Force a fresh break so that the detach can happen from the debugger
2074ad5def9SAdrian McCarthy     // thread.
2084ad5def9SAdrian McCarthy     if (!::DebugBreakProcess(
2094ad5def9SAdrian McCarthy             GetProcess().GetNativeProcess().GetSystemHandle())) {
2104ad5def9SAdrian McCarthy       error.SetError(::GetLastError(), eErrorTypeWin32);
2114ad5def9SAdrian McCarthy     }
2124ad5def9SAdrian McCarthy   }
2134ad5def9SAdrian McCarthy 
214a385d2c1SPavel Labath   LLDB_LOG(log, "waiting for detach from process {0} to complete.", pid);
2154ad5def9SAdrian McCarthy 
2164ad5def9SAdrian McCarthy   DWORD wait_result = WaitForSingleObject(m_debugging_ended_event, 5000);
2174ad5def9SAdrian McCarthy   if (wait_result != WAIT_OBJECT_0) {
2184ad5def9SAdrian McCarthy     error.SetError(GetLastError(), eErrorTypeWin32);
219a385d2c1SPavel Labath     LLDB_LOG(log, "error: WaitForSingleObject({0}, 5000) returned {1}",
2204ad5def9SAdrian McCarthy              m_debugging_ended_event, wait_result);
221a385d2c1SPavel Labath   } else
222a385d2c1SPavel Labath     LLDB_LOG(log, "detach from process {0} completed successfully.", pid);
2234ad5def9SAdrian McCarthy 
2244ad5def9SAdrian McCarthy   if (!error.Success()) {
225a385d2c1SPavel Labath     LLDB_LOG(log, "encountered an error while trying to stop process {0}. {1}",
226a385d2c1SPavel Labath              pid, error);
2274ad5def9SAdrian McCarthy   }
2284ad5def9SAdrian McCarthy   return error;
2294ad5def9SAdrian McCarthy }
2304ad5def9SAdrian McCarthy 
2314ad5def9SAdrian McCarthy void DebuggerThread::ContinueAsyncException(ExceptionResult result) {
2324ad5def9SAdrian McCarthy   if (!m_active_exception.get())
2334ad5def9SAdrian McCarthy     return;
2344ad5def9SAdrian McCarthy 
235a385d2c1SPavel Labath   Log *log = ProcessWindowsLog::GetLogIfAny(WINDOWS_LOG_PROCESS |
236a385d2c1SPavel Labath                                             WINDOWS_LOG_EXCEPTION);
237a385d2c1SPavel Labath   LLDB_LOG(log, "broadcasting for inferior process {0}.",
2384ad5def9SAdrian McCarthy            m_process.GetProcessId());
2394ad5def9SAdrian McCarthy 
2404ad5def9SAdrian McCarthy   m_active_exception.reset();
2414ad5def9SAdrian McCarthy   m_exception_pred.SetValue(result, eBroadcastAlways);
2424ad5def9SAdrian McCarthy }
2434ad5def9SAdrian McCarthy 
2444ad5def9SAdrian McCarthy void DebuggerThread::FreeProcessHandles() {
2454ad5def9SAdrian McCarthy   m_process = HostProcess();
2464ad5def9SAdrian McCarthy   m_main_thread = HostThread();
2474ad5def9SAdrian McCarthy   if (m_image_file) {
2484ad5def9SAdrian McCarthy     ::CloseHandle(m_image_file);
2494ad5def9SAdrian McCarthy     m_image_file = nullptr;
2504ad5def9SAdrian McCarthy   }
2514ad5def9SAdrian McCarthy }
2524ad5def9SAdrian McCarthy 
2534ad5def9SAdrian McCarthy void DebuggerThread::DebugLoop() {
254a385d2c1SPavel Labath   Log *log = ProcessWindowsLog::GetLogIfAny(WINDOWS_LOG_EVENT);
2554ad5def9SAdrian McCarthy   DEBUG_EVENT dbe = {};
2564ad5def9SAdrian McCarthy   bool should_debug = true;
257a385d2c1SPavel Labath   LLDB_LOGV(log, "Entering WaitForDebugEvent loop");
2584ad5def9SAdrian McCarthy   while (should_debug) {
259a385d2c1SPavel Labath     LLDB_LOGV(log, "Calling WaitForDebugEvent");
2604ad5def9SAdrian McCarthy     BOOL wait_result = WaitForDebugEvent(&dbe, INFINITE);
2614ad5def9SAdrian McCarthy     if (wait_result) {
2624ad5def9SAdrian McCarthy       DWORD continue_status = DBG_CONTINUE;
2634ad5def9SAdrian McCarthy       switch (dbe.dwDebugEventCode) {
2644ad5def9SAdrian McCarthy       case EXCEPTION_DEBUG_EVENT: {
2654ad5def9SAdrian McCarthy         ExceptionResult status =
2664ad5def9SAdrian McCarthy             HandleExceptionEvent(dbe.u.Exception, dbe.dwThreadId);
2674ad5def9SAdrian McCarthy 
2684ad5def9SAdrian McCarthy         if (status == ExceptionResult::MaskException)
2694ad5def9SAdrian McCarthy           continue_status = DBG_CONTINUE;
2704ad5def9SAdrian McCarthy         else if (status == ExceptionResult::SendToApplication)
2714ad5def9SAdrian McCarthy           continue_status = DBG_EXCEPTION_NOT_HANDLED;
2724ad5def9SAdrian McCarthy 
2734ad5def9SAdrian McCarthy         break;
2744ad5def9SAdrian McCarthy       }
2754ad5def9SAdrian McCarthy       case CREATE_THREAD_DEBUG_EVENT:
2764ad5def9SAdrian McCarthy         continue_status =
2774ad5def9SAdrian McCarthy             HandleCreateThreadEvent(dbe.u.CreateThread, dbe.dwThreadId);
2784ad5def9SAdrian McCarthy         break;
2794ad5def9SAdrian McCarthy       case CREATE_PROCESS_DEBUG_EVENT:
2804ad5def9SAdrian McCarthy         continue_status =
2814ad5def9SAdrian McCarthy             HandleCreateProcessEvent(dbe.u.CreateProcessInfo, dbe.dwThreadId);
2824ad5def9SAdrian McCarthy         break;
2834ad5def9SAdrian McCarthy       case EXIT_THREAD_DEBUG_EVENT:
2844ad5def9SAdrian McCarthy         continue_status =
2854ad5def9SAdrian McCarthy             HandleExitThreadEvent(dbe.u.ExitThread, dbe.dwThreadId);
2864ad5def9SAdrian McCarthy         break;
2874ad5def9SAdrian McCarthy       case EXIT_PROCESS_DEBUG_EVENT:
2884ad5def9SAdrian McCarthy         continue_status =
2894ad5def9SAdrian McCarthy             HandleExitProcessEvent(dbe.u.ExitProcess, dbe.dwThreadId);
2904ad5def9SAdrian McCarthy         should_debug = false;
2914ad5def9SAdrian McCarthy         break;
2924ad5def9SAdrian McCarthy       case LOAD_DLL_DEBUG_EVENT:
2934ad5def9SAdrian McCarthy         continue_status = HandleLoadDllEvent(dbe.u.LoadDll, dbe.dwThreadId);
2944ad5def9SAdrian McCarthy         break;
2954ad5def9SAdrian McCarthy       case UNLOAD_DLL_DEBUG_EVENT:
2964ad5def9SAdrian McCarthy         continue_status = HandleUnloadDllEvent(dbe.u.UnloadDll, dbe.dwThreadId);
2974ad5def9SAdrian McCarthy         break;
2984ad5def9SAdrian McCarthy       case OUTPUT_DEBUG_STRING_EVENT:
2994ad5def9SAdrian McCarthy         continue_status = HandleODSEvent(dbe.u.DebugString, dbe.dwThreadId);
3004ad5def9SAdrian McCarthy         break;
3014ad5def9SAdrian McCarthy       case RIP_EVENT:
3024ad5def9SAdrian McCarthy         continue_status = HandleRipEvent(dbe.u.RipInfo, dbe.dwThreadId);
3034ad5def9SAdrian McCarthy         if (dbe.u.RipInfo.dwType == SLE_ERROR)
3044ad5def9SAdrian McCarthy           should_debug = false;
3054ad5def9SAdrian McCarthy         break;
3064ad5def9SAdrian McCarthy       }
3074ad5def9SAdrian McCarthy 
308a385d2c1SPavel Labath       LLDB_LOGV(log, "calling ContinueDebugEvent({0}, {1}, {2}) on thread {3}.",
3094ad5def9SAdrian McCarthy                 dbe.dwProcessId, dbe.dwThreadId, continue_status,
3104ad5def9SAdrian McCarthy                 ::GetCurrentThreadId());
3114ad5def9SAdrian McCarthy 
3124ad5def9SAdrian McCarthy       ::ContinueDebugEvent(dbe.dwProcessId, dbe.dwThreadId, continue_status);
3134ad5def9SAdrian McCarthy 
3144ad5def9SAdrian McCarthy       if (m_detached) {
3154ad5def9SAdrian McCarthy         should_debug = false;
3164ad5def9SAdrian McCarthy       }
3174ad5def9SAdrian McCarthy     } else {
318a385d2c1SPavel Labath       LLDB_LOG(log, "returned FALSE from WaitForDebugEvent.  Error = {0}",
3194ad5def9SAdrian McCarthy                ::GetLastError());
3204ad5def9SAdrian McCarthy 
3214ad5def9SAdrian McCarthy       should_debug = false;
3224ad5def9SAdrian McCarthy     }
3234ad5def9SAdrian McCarthy   }
3244ad5def9SAdrian McCarthy   FreeProcessHandles();
3254ad5def9SAdrian McCarthy 
326a385d2c1SPavel Labath   LLDB_LOG(log, "WaitForDebugEvent loop completed, exiting.");
3274ad5def9SAdrian McCarthy   SetEvent(m_debugging_ended_event);
3284ad5def9SAdrian McCarthy }
3294ad5def9SAdrian McCarthy 
3304ad5def9SAdrian McCarthy ExceptionResult
3314ad5def9SAdrian McCarthy DebuggerThread::HandleExceptionEvent(const EXCEPTION_DEBUG_INFO &info,
3324ad5def9SAdrian McCarthy                                      DWORD thread_id) {
333a385d2c1SPavel Labath   Log *log =
334a385d2c1SPavel Labath       ProcessWindowsLog::GetLogIfAny(WINDOWS_LOG_EVENT | WINDOWS_LOG_EXCEPTION);
3354ad5def9SAdrian McCarthy   if (m_is_shutting_down) {
3364ad5def9SAdrian McCarthy     // A breakpoint that occurs while `m_pid_to_detach` is non-zero is a magic
3374ad5def9SAdrian McCarthy     // exception that
3384ad5def9SAdrian McCarthy     // we use simply to wake up the DebuggerThread so that we can close out the
3394ad5def9SAdrian McCarthy     // debug loop.
3404ad5def9SAdrian McCarthy     if (m_pid_to_detach != 0 &&
3414ad5def9SAdrian McCarthy         info.ExceptionRecord.ExceptionCode == EXCEPTION_BREAKPOINT) {
342a385d2c1SPavel Labath       LLDB_LOG(log, "Breakpoint exception is cue to detach from process {0:x}",
3434ad5def9SAdrian McCarthy                m_pid_to_detach.load());
3444ad5def9SAdrian McCarthy       ::DebugActiveProcessStop(m_pid_to_detach);
3454ad5def9SAdrian McCarthy       m_detached = true;
3464ad5def9SAdrian McCarthy     }
3474ad5def9SAdrian McCarthy 
3484ad5def9SAdrian McCarthy     // Don't perform any blocking operations while we're shutting down.  That
34905097246SAdrian Prantl     // will cause TerminateProcess -> WaitForSingleObject to time out.
3504ad5def9SAdrian McCarthy     return ExceptionResult::SendToApplication;
3514ad5def9SAdrian McCarthy   }
3524ad5def9SAdrian McCarthy 
3534ad5def9SAdrian McCarthy   bool first_chance = (info.dwFirstChance != 0);
3544ad5def9SAdrian McCarthy 
3554ad5def9SAdrian McCarthy   m_active_exception.reset(
3564ad5def9SAdrian McCarthy       new ExceptionRecord(info.ExceptionRecord, thread_id));
357a385d2c1SPavel Labath   LLDB_LOG(log, "encountered {0} chance exception {1:x} on thread {2:x}",
3584ad5def9SAdrian McCarthy            first_chance ? "first" : "second",
3594ad5def9SAdrian McCarthy            info.ExceptionRecord.ExceptionCode, thread_id);
3604ad5def9SAdrian McCarthy 
3614ad5def9SAdrian McCarthy   ExceptionResult result =
3624ad5def9SAdrian McCarthy       m_debug_delegate->OnDebugException(first_chance, *m_active_exception);
3634ad5def9SAdrian McCarthy   m_exception_pred.SetValue(result, eBroadcastNever);
3644ad5def9SAdrian McCarthy 
365a385d2c1SPavel Labath   LLDB_LOG(log, "waiting for ExceptionPred != BreakInDebugger");
366*4b130331SPavel Labath   result = *m_exception_pred.WaitForValueNotEqualTo(
367*4b130331SPavel Labath       ExceptionResult::BreakInDebugger);
3684ad5def9SAdrian McCarthy 
369a385d2c1SPavel Labath   LLDB_LOG(log, "got ExceptionPred = {0}", (int)m_exception_pred.GetValue());
3704ad5def9SAdrian McCarthy   return result;
3714ad5def9SAdrian McCarthy }
3724ad5def9SAdrian McCarthy 
3734ad5def9SAdrian McCarthy DWORD
3744ad5def9SAdrian McCarthy DebuggerThread::HandleCreateThreadEvent(const CREATE_THREAD_DEBUG_INFO &info,
3754ad5def9SAdrian McCarthy                                         DWORD thread_id) {
376a385d2c1SPavel Labath   Log *log =
377a385d2c1SPavel Labath       ProcessWindowsLog::GetLogIfAny(WINDOWS_LOG_EVENT | WINDOWS_LOG_THREAD);
378a385d2c1SPavel Labath   LLDB_LOG(log, "Thread {0:x} spawned in process {1}", thread_id,
379a385d2c1SPavel Labath            m_process.GetProcessId());
3804ad5def9SAdrian McCarthy   HostThread thread(info.hThread);
3814ad5def9SAdrian McCarthy   thread.GetNativeThread().SetOwnsHandle(false);
3824ad5def9SAdrian McCarthy   m_debug_delegate->OnCreateThread(thread);
3834ad5def9SAdrian McCarthy   return DBG_CONTINUE;
3844ad5def9SAdrian McCarthy }
3854ad5def9SAdrian McCarthy 
3864ad5def9SAdrian McCarthy DWORD
3874ad5def9SAdrian McCarthy DebuggerThread::HandleCreateProcessEvent(const CREATE_PROCESS_DEBUG_INFO &info,
3884ad5def9SAdrian McCarthy                                          DWORD thread_id) {
389a385d2c1SPavel Labath   Log *log =
390a385d2c1SPavel Labath       ProcessWindowsLog::GetLogIfAny(WINDOWS_LOG_EVENT | WINDOWS_LOG_PROCESS);
3914ad5def9SAdrian McCarthy   uint32_t process_id = ::GetProcessId(info.hProcess);
3924ad5def9SAdrian McCarthy 
393a385d2c1SPavel Labath   LLDB_LOG(log, "process {0} spawned", process_id);
3944ad5def9SAdrian McCarthy 
3954ad5def9SAdrian McCarthy   std::string thread_name;
3964ad5def9SAdrian McCarthy   llvm::raw_string_ostream name_stream(thread_name);
3974ad5def9SAdrian McCarthy   name_stream << "lldb.plugin.process-windows.slave[" << process_id << "]";
3984ad5def9SAdrian McCarthy   name_stream.flush();
399ed96be99SZachary Turner   llvm::set_thread_name(thread_name);
4004ad5def9SAdrian McCarthy 
4014ad5def9SAdrian McCarthy   // info.hProcess and info.hThread are closed automatically by Windows when
4024ad5def9SAdrian McCarthy   // EXIT_PROCESS_DEBUG_EVENT is received.
4034ad5def9SAdrian McCarthy   m_process = HostProcess(info.hProcess);
4044ad5def9SAdrian McCarthy   ((HostProcessWindows &)m_process.GetNativeProcess()).SetOwnsHandle(false);
4054ad5def9SAdrian McCarthy   m_main_thread = HostThread(info.hThread);
4064ad5def9SAdrian McCarthy   m_main_thread.GetNativeThread().SetOwnsHandle(false);
4074ad5def9SAdrian McCarthy   m_image_file = info.hFile;
4084ad5def9SAdrian McCarthy 
4094ad5def9SAdrian McCarthy   lldb::addr_t load_addr = reinterpret_cast<lldb::addr_t>(info.lpBaseOfImage);
4104ad5def9SAdrian McCarthy   m_debug_delegate->OnDebuggerConnected(load_addr);
4114ad5def9SAdrian McCarthy 
4124ad5def9SAdrian McCarthy   return DBG_CONTINUE;
4134ad5def9SAdrian McCarthy }
4144ad5def9SAdrian McCarthy 
4154ad5def9SAdrian McCarthy DWORD
4164ad5def9SAdrian McCarthy DebuggerThread::HandleExitThreadEvent(const EXIT_THREAD_DEBUG_INFO &info,
4174ad5def9SAdrian McCarthy                                       DWORD thread_id) {
418a385d2c1SPavel Labath   Log *log =
419a385d2c1SPavel Labath       ProcessWindowsLog::GetLogIfAny(WINDOWS_LOG_EVENT | WINDOWS_LOG_THREAD);
420a385d2c1SPavel Labath   LLDB_LOG(log, "Thread {0} exited with code {1} in process {2}", thread_id,
421a385d2c1SPavel Labath            info.dwExitCode, m_process.GetProcessId());
4224ad5def9SAdrian McCarthy   m_debug_delegate->OnExitThread(thread_id, info.dwExitCode);
4234ad5def9SAdrian McCarthy   return DBG_CONTINUE;
4244ad5def9SAdrian McCarthy }
4254ad5def9SAdrian McCarthy 
4264ad5def9SAdrian McCarthy DWORD
4274ad5def9SAdrian McCarthy DebuggerThread::HandleExitProcessEvent(const EXIT_PROCESS_DEBUG_INFO &info,
4284ad5def9SAdrian McCarthy                                        DWORD thread_id) {
429a385d2c1SPavel Labath   Log *log =
430a385d2c1SPavel Labath       ProcessWindowsLog::GetLogIfAny(WINDOWS_LOG_EVENT | WINDOWS_LOG_THREAD);
431a385d2c1SPavel Labath   LLDB_LOG(log, "process {0} exited with code {1}", m_process.GetProcessId(),
432a385d2c1SPavel Labath            info.dwExitCode);
4334ad5def9SAdrian McCarthy 
4344ad5def9SAdrian McCarthy   m_debug_delegate->OnExitProcess(info.dwExitCode);
4354ad5def9SAdrian McCarthy 
4364ad5def9SAdrian McCarthy   FreeProcessHandles();
4374ad5def9SAdrian McCarthy   return DBG_CONTINUE;
4384ad5def9SAdrian McCarthy }
4394ad5def9SAdrian McCarthy 
4404ad5def9SAdrian McCarthy DWORD
4414ad5def9SAdrian McCarthy DebuggerThread::HandleLoadDllEvent(const LOAD_DLL_DEBUG_INFO &info,
4424ad5def9SAdrian McCarthy                                    DWORD thread_id) {
443a385d2c1SPavel Labath   Log *log = ProcessWindowsLog::GetLogIfAny(WINDOWS_LOG_EVENT);
4444ad5def9SAdrian McCarthy   if (info.hFile == nullptr) {
4454ad5def9SAdrian McCarthy     // Not sure what this is, so just ignore it.
446a385d2c1SPavel Labath     LLDB_LOG(log, "Warning: Inferior {0} has a NULL file handle, returning...",
4474ad5def9SAdrian McCarthy              m_process.GetProcessId());
4484ad5def9SAdrian McCarthy     return DBG_CONTINUE;
4494ad5def9SAdrian McCarthy   }
4504ad5def9SAdrian McCarthy 
4514ad5def9SAdrian McCarthy   std::vector<wchar_t> buffer(1);
4524ad5def9SAdrian McCarthy   DWORD required_size =
4534ad5def9SAdrian McCarthy       GetFinalPathNameByHandleW(info.hFile, &buffer[0], 0, VOLUME_NAME_DOS);
4544ad5def9SAdrian McCarthy   if (required_size > 0) {
4554ad5def9SAdrian McCarthy     buffer.resize(required_size + 1);
4564ad5def9SAdrian McCarthy     required_size = GetFinalPathNameByHandleW(info.hFile, &buffer[0],
4574ad5def9SAdrian McCarthy                                               required_size, VOLUME_NAME_DOS);
4584ad5def9SAdrian McCarthy     std::string path_str_utf8;
4594ad5def9SAdrian McCarthy     llvm::convertWideToUTF8(buffer.data(), path_str_utf8);
4604ad5def9SAdrian McCarthy     llvm::StringRef path_str = path_str_utf8;
4614ad5def9SAdrian McCarthy     const char *path = path_str.data();
4624ad5def9SAdrian McCarthy     if (path_str.startswith("\\\\?\\"))
4634ad5def9SAdrian McCarthy       path += 4;
4644ad5def9SAdrian McCarthy 
4654ad5def9SAdrian McCarthy     FileSpec file_spec(path, false);
4664ad5def9SAdrian McCarthy     ModuleSpec module_spec(file_spec);
4674ad5def9SAdrian McCarthy     lldb::addr_t load_addr = reinterpret_cast<lldb::addr_t>(info.lpBaseOfDll);
4684ad5def9SAdrian McCarthy 
469a385d2c1SPavel Labath     LLDB_LOG(log, "Inferior {0} - DLL '{1}' loaded at address {2:x}...",
4704ad5def9SAdrian McCarthy              m_process.GetProcessId(), path, info.lpBaseOfDll);
4714ad5def9SAdrian McCarthy 
4724ad5def9SAdrian McCarthy     m_debug_delegate->OnLoadDll(module_spec, load_addr);
4734ad5def9SAdrian McCarthy   } else {
474a385d2c1SPavel Labath     LLDB_LOG(
475a385d2c1SPavel Labath         log,
476a385d2c1SPavel Labath         "Inferior {0} - Error {1} occurred calling GetFinalPathNameByHandle",
4774ad5def9SAdrian McCarthy         m_process.GetProcessId(), ::GetLastError());
4784ad5def9SAdrian McCarthy   }
4794ad5def9SAdrian McCarthy   // Windows does not automatically close info.hFile, so we need to do it.
4804ad5def9SAdrian McCarthy   ::CloseHandle(info.hFile);
4814ad5def9SAdrian McCarthy   return DBG_CONTINUE;
4824ad5def9SAdrian McCarthy }
4834ad5def9SAdrian McCarthy 
4844ad5def9SAdrian McCarthy DWORD
4854ad5def9SAdrian McCarthy DebuggerThread::HandleUnloadDllEvent(const UNLOAD_DLL_DEBUG_INFO &info,
4864ad5def9SAdrian McCarthy                                      DWORD thread_id) {
487a385d2c1SPavel Labath   Log *log = ProcessWindowsLog::GetLogIfAny(WINDOWS_LOG_EVENT);
488a385d2c1SPavel Labath   LLDB_LOG(log, "process {0} unloading DLL at addr {1:x}.",
4894ad5def9SAdrian McCarthy            m_process.GetProcessId(), info.lpBaseOfDll);
4904ad5def9SAdrian McCarthy 
4914ad5def9SAdrian McCarthy   m_debug_delegate->OnUnloadDll(
4924ad5def9SAdrian McCarthy       reinterpret_cast<lldb::addr_t>(info.lpBaseOfDll));
4934ad5def9SAdrian McCarthy   return DBG_CONTINUE;
4944ad5def9SAdrian McCarthy }
4954ad5def9SAdrian McCarthy 
4964ad5def9SAdrian McCarthy DWORD
4974ad5def9SAdrian McCarthy DebuggerThread::HandleODSEvent(const OUTPUT_DEBUG_STRING_INFO &info,
4984ad5def9SAdrian McCarthy                                DWORD thread_id) {
4994ad5def9SAdrian McCarthy   return DBG_CONTINUE;
5004ad5def9SAdrian McCarthy }
5014ad5def9SAdrian McCarthy 
5024ad5def9SAdrian McCarthy DWORD
5034ad5def9SAdrian McCarthy DebuggerThread::HandleRipEvent(const RIP_INFO &info, DWORD thread_id) {
504a385d2c1SPavel Labath   Log *log = ProcessWindowsLog::GetLogIfAny(WINDOWS_LOG_EVENT);
505a385d2c1SPavel Labath   LLDB_LOG(log, "encountered error {0} (type={1}) in process {2} thread {3}",
5064ad5def9SAdrian McCarthy            info.dwError, info.dwType, m_process.GetProcessId(), thread_id);
5074ad5def9SAdrian McCarthy 
50897206d57SZachary Turner   Status error(info.dwError, eErrorTypeWin32);
5094ad5def9SAdrian McCarthy   m_debug_delegate->OnDebuggerError(error, info.dwType);
5104ad5def9SAdrian McCarthy 
5114ad5def9SAdrian McCarthy   return DBG_CONTINUE;
5124ad5def9SAdrian McCarthy }
513