180814287SRaphael Isemann //===-- DebuggerThread.cpp ------------------------------------------------===//
24ad5def9SAdrian McCarthy //
32946cd70SChandler Carruth // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
42946cd70SChandler Carruth // See https://llvm.org/LICENSE.txt for license information.
52946cd70SChandler Carruth // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
64ad5def9SAdrian McCarthy //
74ad5def9SAdrian McCarthy //===----------------------------------------------------------------------===//
84ad5def9SAdrian McCarthy 
94ad5def9SAdrian McCarthy #include "DebuggerThread.h"
104ad5def9SAdrian McCarthy #include "ExceptionRecord.h"
114ad5def9SAdrian McCarthy #include "IDebugDelegate.h"
124ad5def9SAdrian McCarthy 
134ad5def9SAdrian McCarthy #include "lldb/Core/ModuleSpec.h"
14e7404d99SPavel Labath #include "lldb/Host/ProcessLaunchInfo.h"
154ad5def9SAdrian McCarthy #include "lldb/Host/ThreadLauncher.h"
16*87a2dba1SAlvin Wong #include "lldb/Host/windows/AutoHandle.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"
215713a05bSZachary Turner #include "lldb/Utility/FileSpec.h"
226f9e6901SZachary Turner #include "lldb/Utility/Log.h"
237fae4932SRaphael Isemann #include "lldb/Utility/Predicate.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 
33*87a2dba1SAlvin Wong #include <psapi.h>
34*87a2dba1SAlvin Wong 
355146a9eaSAaron Smith #ifndef STATUS_WX86_BREAKPOINT
365146a9eaSAaron Smith #define STATUS_WX86_BREAKPOINT 0x4000001FL // For WOW64
375146a9eaSAaron Smith #endif
385146a9eaSAaron Smith 
394ad5def9SAdrian McCarthy using namespace lldb;
404ad5def9SAdrian McCarthy using namespace lldb_private;
414ad5def9SAdrian McCarthy 
DebuggerThread(DebugDelegateSP debug_delegate)424ad5def9SAdrian McCarthy DebuggerThread::DebuggerThread(DebugDelegateSP debug_delegate)
434ad5def9SAdrian McCarthy     : m_debug_delegate(debug_delegate), m_pid_to_detach(0),
444ad5def9SAdrian McCarthy       m_is_shutting_down(false) {
454ad5def9SAdrian McCarthy   m_debugging_ended_event = ::CreateEvent(nullptr, TRUE, FALSE, nullptr);
464ad5def9SAdrian McCarthy }
474ad5def9SAdrian McCarthy 
~DebuggerThread()484ad5def9SAdrian McCarthy DebuggerThread::~DebuggerThread() { ::CloseHandle(m_debugging_ended_event); }
494ad5def9SAdrian McCarthy 
DebugLaunch(const ProcessLaunchInfo & launch_info)5097206d57SZachary Turner Status DebuggerThread::DebugLaunch(const ProcessLaunchInfo &launch_info) {
516730df47SPavel Labath   Log *log = GetLog(WindowsLog::Process);
52a385d2c1SPavel Labath   LLDB_LOG(log, "launching '{0}'", launch_info.GetExecutableFile().GetPath());
534ad5def9SAdrian McCarthy 
54631b5f7dSStella Stamenova   Status result;
55d0810779SPavel Labath   llvm::Expected<HostThread> secondary_thread = ThreadLauncher::LaunchThread(
56d0810779SPavel Labath       "lldb.plugin.process-windows.secondary[?]",
57d0810779SPavel Labath       [this, launch_info] { return DebuggerThreadLaunchRoutine(launch_info); });
5864ec505dSJonas Devlieghere   if (!secondary_thread) {
5964ec505dSJonas Devlieghere     result = Status(secondary_thread.takeError());
60631b5f7dSStella Stamenova     LLDB_LOG(log, "couldn't launch debugger thread. {0}", result);
61631b5f7dSStella Stamenova   }
624ad5def9SAdrian McCarthy 
63631b5f7dSStella Stamenova   return result;
644ad5def9SAdrian McCarthy }
654ad5def9SAdrian McCarthy 
DebugAttach(lldb::pid_t pid,const ProcessAttachInfo & attach_info)6697206d57SZachary Turner Status DebuggerThread::DebugAttach(lldb::pid_t pid,
674ad5def9SAdrian McCarthy                                    const ProcessAttachInfo &attach_info) {
686730df47SPavel Labath   Log *log = GetLog(WindowsLog::Process);
69a385d2c1SPavel Labath   LLDB_LOG(log, "attaching to '{0}'", pid);
704ad5def9SAdrian McCarthy 
71631b5f7dSStella Stamenova   Status result;
72d0810779SPavel Labath   llvm::Expected<HostThread> secondary_thread = ThreadLauncher::LaunchThread(
73d0810779SPavel Labath       "lldb.plugin.process-windows.secondary[?]", [this, pid, attach_info] {
74d0810779SPavel Labath         return DebuggerThreadAttachRoutine(pid, attach_info);
75d0810779SPavel Labath       });
7664ec505dSJonas Devlieghere   if (!secondary_thread) {
7764ec505dSJonas Devlieghere     result = Status(secondary_thread.takeError());
78631b5f7dSStella Stamenova     LLDB_LOG(log, "couldn't attach to process '{0}'. {1}", pid, result);
79631b5f7dSStella Stamenova   }
804ad5def9SAdrian McCarthy 
81631b5f7dSStella Stamenova   return result;
824ad5def9SAdrian McCarthy }
834ad5def9SAdrian McCarthy 
DebuggerThreadLaunchRoutine(const ProcessLaunchInfo & launch_info)844ad5def9SAdrian McCarthy lldb::thread_result_t DebuggerThread::DebuggerThreadLaunchRoutine(
854ad5def9SAdrian McCarthy     const ProcessLaunchInfo &launch_info) {
864ad5def9SAdrian McCarthy   // Grab a shared_ptr reference to this so that we know it won't get deleted
8705097246SAdrian Prantl   // until after the thread routine has exited.
884ad5def9SAdrian McCarthy   std::shared_ptr<DebuggerThread> this_ref(shared_from_this());
894ad5def9SAdrian McCarthy 
906730df47SPavel Labath   Log *log = GetLog(WindowsLog::Process);
91a385d2c1SPavel Labath   LLDB_LOG(log, "preparing to launch '{0}' on background thread.",
92a385d2c1SPavel Labath            launch_info.GetExecutableFile().GetPath());
934ad5def9SAdrian McCarthy 
9497206d57SZachary Turner   Status error;
954ad5def9SAdrian McCarthy   ProcessLauncherWindows launcher;
964ad5def9SAdrian McCarthy   HostProcess process(launcher.LaunchProcess(launch_info, error));
974ad5def9SAdrian McCarthy   // If we couldn't create the process, notify waiters immediately.  Otherwise
9805097246SAdrian Prantl   // enter the debug loop and wait until we get the create process debug
9905097246SAdrian Prantl   // notification.  Note that if the process was created successfully, we can
10005097246SAdrian Prantl   // throw away the process handle we got from CreateProcess because Windows
10105097246SAdrian Prantl   // will give us another (potentially more useful?) handle when it sends us
10205097246SAdrian Prantl   // the CREATE_PROCESS_DEBUG_EVENT.
1034ad5def9SAdrian McCarthy   if (error.Success())
1044ad5def9SAdrian McCarthy     DebugLoop();
1054ad5def9SAdrian McCarthy   else
1064ad5def9SAdrian McCarthy     m_debug_delegate->OnDebuggerError(error, 0);
1074ad5def9SAdrian McCarthy 
10885200645SKonrad Kleine   return {};
1094ad5def9SAdrian McCarthy }
1104ad5def9SAdrian McCarthy 
DebuggerThreadAttachRoutine(lldb::pid_t pid,const ProcessAttachInfo & attach_info)1114ad5def9SAdrian McCarthy lldb::thread_result_t DebuggerThread::DebuggerThreadAttachRoutine(
1124ad5def9SAdrian McCarthy     lldb::pid_t pid, const ProcessAttachInfo &attach_info) {
1134ad5def9SAdrian McCarthy   // Grab a shared_ptr reference to this so that we know it won't get deleted
11405097246SAdrian Prantl   // until after the thread routine has exited.
1154ad5def9SAdrian McCarthy   std::shared_ptr<DebuggerThread> this_ref(shared_from_this());
1164ad5def9SAdrian McCarthy 
1176730df47SPavel Labath   Log *log = GetLog(WindowsLog::Process);
118a385d2c1SPavel Labath   LLDB_LOG(log, "preparing to attach to process '{0}' on background thread.",
1194ad5def9SAdrian McCarthy            pid);
1204ad5def9SAdrian McCarthy 
1214ad5def9SAdrian McCarthy   if (!DebugActiveProcess((DWORD)pid)) {
12297206d57SZachary Turner     Status error(::GetLastError(), eErrorTypeWin32);
1234ad5def9SAdrian McCarthy     m_debug_delegate->OnDebuggerError(error, 0);
12485200645SKonrad Kleine     return {};
1254ad5def9SAdrian McCarthy   }
1264ad5def9SAdrian McCarthy 
12705097246SAdrian Prantl   // The attach was successful, enter the debug loop.  From here on out, this
12805097246SAdrian Prantl   // is no different than a create process operation, so all the same comments
12905097246SAdrian Prantl   // in DebugLaunch should apply from this point out.
1304ad5def9SAdrian McCarthy   DebugLoop();
1314ad5def9SAdrian McCarthy 
13285200645SKonrad Kleine   return {};
1334ad5def9SAdrian McCarthy }
1344ad5def9SAdrian McCarthy 
StopDebugging(bool terminate)13597206d57SZachary Turner Status DebuggerThread::StopDebugging(bool terminate) {
13697206d57SZachary Turner   Status error;
1374ad5def9SAdrian McCarthy 
1384ad5def9SAdrian McCarthy   lldb::pid_t pid = m_process.GetProcessId();
1394ad5def9SAdrian McCarthy 
1406730df47SPavel Labath   Log *log = GetLog(WindowsLog::Process);
141a385d2c1SPavel Labath   LLDB_LOG(log, "terminate = {0}, inferior={1}.", terminate, pid);
1424ad5def9SAdrian McCarthy 
1434ad5def9SAdrian McCarthy   // Set m_is_shutting_down to true if it was false.  Return if it was already
1444ad5def9SAdrian McCarthy   // true.
1454ad5def9SAdrian McCarthy   bool expected = false;
1464ad5def9SAdrian McCarthy   if (!m_is_shutting_down.compare_exchange_strong(expected, true))
1474ad5def9SAdrian McCarthy     return error;
1484ad5def9SAdrian McCarthy 
1494ad5def9SAdrian McCarthy   // Make a copy of the process, since the termination sequence will reset
1504ad5def9SAdrian McCarthy   // DebuggerThread's internal copy and it needs to remain open for the Wait
1514ad5def9SAdrian McCarthy   // operation.
1524ad5def9SAdrian McCarthy   HostProcess process_copy = m_process;
1534ad5def9SAdrian McCarthy   lldb::process_t handle = m_process.GetNativeProcess().GetSystemHandle();
1544ad5def9SAdrian McCarthy 
1554ad5def9SAdrian McCarthy   if (terminate) {
1569d6fabf9SStella Stamenova     if (handle != nullptr && handle != LLDB_INVALID_PROCESS) {
1574ad5def9SAdrian McCarthy       // Initiate the termination before continuing the exception, so that the
15805097246SAdrian Prantl       // next debug event we get is the exit process event, and not some other
15905097246SAdrian Prantl       // event.
1604ad5def9SAdrian McCarthy       BOOL terminate_suceeded = TerminateProcess(handle, 0);
161a385d2c1SPavel Labath       LLDB_LOG(log,
162a385d2c1SPavel Labath                "calling TerminateProcess({0}, 0) (inferior={1}), success={2}",
163a385d2c1SPavel Labath                handle, pid, terminate_suceeded);
1649d6fabf9SStella Stamenova     } else {
1659d6fabf9SStella Stamenova       LLDB_LOG(log,
166e3037904SAaron Smith                "NOT calling TerminateProcess because the inferior is not valid "
167e3037904SAaron Smith                "({0}, 0) (inferior={1})",
1689d6fabf9SStella Stamenova                handle, pid);
1699d6fabf9SStella Stamenova     }
1704ad5def9SAdrian McCarthy   }
1714ad5def9SAdrian McCarthy 
1724ad5def9SAdrian McCarthy   // If we're stuck waiting for an exception to continue (e.g. the user is at a
17305097246SAdrian Prantl   // breakpoint messing around in the debugger), continue it now.  But only
17405097246SAdrian Prantl   // AFTER calling TerminateProcess to make sure that the very next call to
17505097246SAdrian Prantl   // WaitForDebugEvent is an exit process event.
1764ad5def9SAdrian McCarthy   if (m_active_exception.get()) {
177a385d2c1SPavel Labath     LLDB_LOG(log, "masking active exception");
1784ad5def9SAdrian McCarthy     ContinueAsyncException(ExceptionResult::MaskException);
1794ad5def9SAdrian McCarthy   }
1804ad5def9SAdrian McCarthy 
1814ad5def9SAdrian McCarthy   if (!terminate) {
1824ad5def9SAdrian McCarthy     // Indicate that we want to detach.
1834ad5def9SAdrian McCarthy     m_pid_to_detach = GetProcess().GetProcessId();
1844ad5def9SAdrian McCarthy 
1854ad5def9SAdrian McCarthy     // Force a fresh break so that the detach can happen from the debugger
1864ad5def9SAdrian McCarthy     // thread.
1874ad5def9SAdrian McCarthy     if (!::DebugBreakProcess(
1884ad5def9SAdrian McCarthy             GetProcess().GetNativeProcess().GetSystemHandle())) {
1894ad5def9SAdrian McCarthy       error.SetError(::GetLastError(), eErrorTypeWin32);
1904ad5def9SAdrian McCarthy     }
1914ad5def9SAdrian McCarthy   }
1924ad5def9SAdrian McCarthy 
193a385d2c1SPavel Labath   LLDB_LOG(log, "waiting for detach from process {0} to complete.", pid);
1944ad5def9SAdrian McCarthy 
1954ad5def9SAdrian McCarthy   DWORD wait_result = WaitForSingleObject(m_debugging_ended_event, 5000);
1964ad5def9SAdrian McCarthy   if (wait_result != WAIT_OBJECT_0) {
1974ad5def9SAdrian McCarthy     error.SetError(GetLastError(), eErrorTypeWin32);
198a385d2c1SPavel Labath     LLDB_LOG(log, "error: WaitForSingleObject({0}, 5000) returned {1}",
1994ad5def9SAdrian McCarthy              m_debugging_ended_event, wait_result);
200a385d2c1SPavel Labath   } else
201a385d2c1SPavel Labath     LLDB_LOG(log, "detach from process {0} completed successfully.", pid);
2024ad5def9SAdrian McCarthy 
2034ad5def9SAdrian McCarthy   if (!error.Success()) {
204a385d2c1SPavel Labath     LLDB_LOG(log, "encountered an error while trying to stop process {0}. {1}",
205a385d2c1SPavel Labath              pid, error);
2064ad5def9SAdrian McCarthy   }
2074ad5def9SAdrian McCarthy   return error;
2084ad5def9SAdrian McCarthy }
2094ad5def9SAdrian McCarthy 
ContinueAsyncException(ExceptionResult result)2104ad5def9SAdrian McCarthy void DebuggerThread::ContinueAsyncException(ExceptionResult result) {
2114ad5def9SAdrian McCarthy   if (!m_active_exception.get())
2124ad5def9SAdrian McCarthy     return;
2134ad5def9SAdrian McCarthy 
2146730df47SPavel Labath   Log *log = GetLog(WindowsLog::Process | WindowsLog::Exception);
215a385d2c1SPavel Labath   LLDB_LOG(log, "broadcasting for inferior process {0}.",
2164ad5def9SAdrian McCarthy            m_process.GetProcessId());
2174ad5def9SAdrian McCarthy 
2184ad5def9SAdrian McCarthy   m_active_exception.reset();
2194ad5def9SAdrian McCarthy   m_exception_pred.SetValue(result, eBroadcastAlways);
2204ad5def9SAdrian McCarthy }
2214ad5def9SAdrian McCarthy 
FreeProcessHandles()2224ad5def9SAdrian McCarthy void DebuggerThread::FreeProcessHandles() {
2234ad5def9SAdrian McCarthy   m_process = HostProcess();
2244ad5def9SAdrian McCarthy   m_main_thread = HostThread();
2254ad5def9SAdrian McCarthy   if (m_image_file) {
2264ad5def9SAdrian McCarthy     ::CloseHandle(m_image_file);
2274ad5def9SAdrian McCarthy     m_image_file = nullptr;
2284ad5def9SAdrian McCarthy   }
2294ad5def9SAdrian McCarthy }
2304ad5def9SAdrian McCarthy 
DebugLoop()2314ad5def9SAdrian McCarthy void DebuggerThread::DebugLoop() {
2326730df47SPavel Labath   Log *log = GetLog(WindowsLog::Event);
2334ad5def9SAdrian McCarthy   DEBUG_EVENT dbe = {};
2344ad5def9SAdrian McCarthy   bool should_debug = true;
235a385d2c1SPavel Labath   LLDB_LOGV(log, "Entering WaitForDebugEvent loop");
2364ad5def9SAdrian McCarthy   while (should_debug) {
237a385d2c1SPavel Labath     LLDB_LOGV(log, "Calling WaitForDebugEvent");
2384ad5def9SAdrian McCarthy     BOOL wait_result = WaitForDebugEvent(&dbe, INFINITE);
2394ad5def9SAdrian McCarthy     if (wait_result) {
2404ad5def9SAdrian McCarthy       DWORD continue_status = DBG_CONTINUE;
2414ad5def9SAdrian McCarthy       switch (dbe.dwDebugEventCode) {
242e3037904SAaron Smith       default:
243e3037904SAaron Smith         llvm_unreachable("Unhandle debug event code!");
2444ad5def9SAdrian McCarthy       case EXCEPTION_DEBUG_EVENT: {
2454ad5def9SAdrian McCarthy         ExceptionResult status =
2464ad5def9SAdrian McCarthy             HandleExceptionEvent(dbe.u.Exception, dbe.dwThreadId);
2474ad5def9SAdrian McCarthy 
2484ad5def9SAdrian McCarthy         if (status == ExceptionResult::MaskException)
2494ad5def9SAdrian McCarthy           continue_status = DBG_CONTINUE;
2504ad5def9SAdrian McCarthy         else if (status == ExceptionResult::SendToApplication)
2514ad5def9SAdrian McCarthy           continue_status = DBG_EXCEPTION_NOT_HANDLED;
2524ad5def9SAdrian McCarthy 
2534ad5def9SAdrian McCarthy         break;
2544ad5def9SAdrian McCarthy       }
2554ad5def9SAdrian McCarthy       case CREATE_THREAD_DEBUG_EVENT:
2564ad5def9SAdrian McCarthy         continue_status =
2574ad5def9SAdrian McCarthy             HandleCreateThreadEvent(dbe.u.CreateThread, dbe.dwThreadId);
2584ad5def9SAdrian McCarthy         break;
2594ad5def9SAdrian McCarthy       case CREATE_PROCESS_DEBUG_EVENT:
2604ad5def9SAdrian McCarthy         continue_status =
2614ad5def9SAdrian McCarthy             HandleCreateProcessEvent(dbe.u.CreateProcessInfo, dbe.dwThreadId);
2624ad5def9SAdrian McCarthy         break;
2634ad5def9SAdrian McCarthy       case EXIT_THREAD_DEBUG_EVENT:
2644ad5def9SAdrian McCarthy         continue_status =
2654ad5def9SAdrian McCarthy             HandleExitThreadEvent(dbe.u.ExitThread, dbe.dwThreadId);
2664ad5def9SAdrian McCarthy         break;
2674ad5def9SAdrian McCarthy       case EXIT_PROCESS_DEBUG_EVENT:
2684ad5def9SAdrian McCarthy         continue_status =
2694ad5def9SAdrian McCarthy             HandleExitProcessEvent(dbe.u.ExitProcess, dbe.dwThreadId);
2704ad5def9SAdrian McCarthy         should_debug = false;
2714ad5def9SAdrian McCarthy         break;
2724ad5def9SAdrian McCarthy       case LOAD_DLL_DEBUG_EVENT:
2734ad5def9SAdrian McCarthy         continue_status = HandleLoadDllEvent(dbe.u.LoadDll, dbe.dwThreadId);
2744ad5def9SAdrian McCarthy         break;
2754ad5def9SAdrian McCarthy       case UNLOAD_DLL_DEBUG_EVENT:
2764ad5def9SAdrian McCarthy         continue_status = HandleUnloadDllEvent(dbe.u.UnloadDll, dbe.dwThreadId);
2774ad5def9SAdrian McCarthy         break;
2784ad5def9SAdrian McCarthy       case OUTPUT_DEBUG_STRING_EVENT:
2794ad5def9SAdrian McCarthy         continue_status = HandleODSEvent(dbe.u.DebugString, dbe.dwThreadId);
2804ad5def9SAdrian McCarthy         break;
2814ad5def9SAdrian McCarthy       case RIP_EVENT:
2824ad5def9SAdrian McCarthy         continue_status = HandleRipEvent(dbe.u.RipInfo, dbe.dwThreadId);
2834ad5def9SAdrian McCarthy         if (dbe.u.RipInfo.dwType == SLE_ERROR)
2844ad5def9SAdrian McCarthy           should_debug = false;
2854ad5def9SAdrian McCarthy         break;
2864ad5def9SAdrian McCarthy       }
2874ad5def9SAdrian McCarthy 
288a385d2c1SPavel Labath       LLDB_LOGV(log, "calling ContinueDebugEvent({0}, {1}, {2}) on thread {3}.",
2894ad5def9SAdrian McCarthy                 dbe.dwProcessId, dbe.dwThreadId, continue_status,
2904ad5def9SAdrian McCarthy                 ::GetCurrentThreadId());
2914ad5def9SAdrian McCarthy 
2924ad5def9SAdrian McCarthy       ::ContinueDebugEvent(dbe.dwProcessId, dbe.dwThreadId, continue_status);
2934ad5def9SAdrian McCarthy 
2944ad5def9SAdrian McCarthy       if (m_detached) {
2954ad5def9SAdrian McCarthy         should_debug = false;
2964ad5def9SAdrian McCarthy       }
2974ad5def9SAdrian McCarthy     } else {
298a385d2c1SPavel Labath       LLDB_LOG(log, "returned FALSE from WaitForDebugEvent.  Error = {0}",
2994ad5def9SAdrian McCarthy                ::GetLastError());
3004ad5def9SAdrian McCarthy 
3014ad5def9SAdrian McCarthy       should_debug = false;
3024ad5def9SAdrian McCarthy     }
3034ad5def9SAdrian McCarthy   }
3044ad5def9SAdrian McCarthy   FreeProcessHandles();
3054ad5def9SAdrian McCarthy 
306a385d2c1SPavel Labath   LLDB_LOG(log, "WaitForDebugEvent loop completed, exiting.");
307e3037904SAaron Smith   ::SetEvent(m_debugging_ended_event);
3084ad5def9SAdrian McCarthy }
3094ad5def9SAdrian McCarthy 
3104ad5def9SAdrian McCarthy ExceptionResult
HandleExceptionEvent(const EXCEPTION_DEBUG_INFO & info,DWORD thread_id)3114ad5def9SAdrian McCarthy DebuggerThread::HandleExceptionEvent(const EXCEPTION_DEBUG_INFO &info,
3124ad5def9SAdrian McCarthy                                      DWORD thread_id) {
3136730df47SPavel Labath   Log *log = GetLog(WindowsLog::Event | WindowsLog::Exception);
3144ad5def9SAdrian McCarthy   if (m_is_shutting_down) {
3154ad5def9SAdrian McCarthy     // A breakpoint that occurs while `m_pid_to_detach` is non-zero is a magic
3164ad5def9SAdrian McCarthy     // exception that
3174ad5def9SAdrian McCarthy     // we use simply to wake up the DebuggerThread so that we can close out the
3184ad5def9SAdrian McCarthy     // debug loop.
3194ad5def9SAdrian McCarthy     if (m_pid_to_detach != 0 &&
3205146a9eaSAaron Smith         (info.ExceptionRecord.ExceptionCode == EXCEPTION_BREAKPOINT ||
3215146a9eaSAaron Smith          info.ExceptionRecord.ExceptionCode == STATUS_WX86_BREAKPOINT)) {
322a385d2c1SPavel Labath       LLDB_LOG(log, "Breakpoint exception is cue to detach from process {0:x}",
3234ad5def9SAdrian McCarthy                m_pid_to_detach.load());
3244ad5def9SAdrian McCarthy       ::DebugActiveProcessStop(m_pid_to_detach);
3254ad5def9SAdrian McCarthy       m_detached = true;
3264ad5def9SAdrian McCarthy     }
3274ad5def9SAdrian McCarthy 
3284ad5def9SAdrian McCarthy     // Don't perform any blocking operations while we're shutting down.  That
32905097246SAdrian Prantl     // will cause TerminateProcess -> WaitForSingleObject to time out.
3304ad5def9SAdrian McCarthy     return ExceptionResult::SendToApplication;
3314ad5def9SAdrian McCarthy   }
3324ad5def9SAdrian McCarthy 
3334ad5def9SAdrian McCarthy   bool first_chance = (info.dwFirstChance != 0);
3344ad5def9SAdrian McCarthy 
3354ad5def9SAdrian McCarthy   m_active_exception.reset(
3364ad5def9SAdrian McCarthy       new ExceptionRecord(info.ExceptionRecord, thread_id));
337a385d2c1SPavel Labath   LLDB_LOG(log, "encountered {0} chance exception {1:x} on thread {2:x}",
3384ad5def9SAdrian McCarthy            first_chance ? "first" : "second",
3394ad5def9SAdrian McCarthy            info.ExceptionRecord.ExceptionCode, thread_id);
3404ad5def9SAdrian McCarthy 
3414ad5def9SAdrian McCarthy   ExceptionResult result =
3424ad5def9SAdrian McCarthy       m_debug_delegate->OnDebugException(first_chance, *m_active_exception);
3434ad5def9SAdrian McCarthy   m_exception_pred.SetValue(result, eBroadcastNever);
3444ad5def9SAdrian McCarthy 
345a385d2c1SPavel Labath   LLDB_LOG(log, "waiting for ExceptionPred != BreakInDebugger");
3464b130331SPavel Labath   result = *m_exception_pred.WaitForValueNotEqualTo(
3474b130331SPavel Labath       ExceptionResult::BreakInDebugger);
3484ad5def9SAdrian McCarthy 
349a385d2c1SPavel Labath   LLDB_LOG(log, "got ExceptionPred = {0}", (int)m_exception_pred.GetValue());
3504ad5def9SAdrian McCarthy   return result;
3514ad5def9SAdrian McCarthy }
3524ad5def9SAdrian McCarthy 
3534ad5def9SAdrian McCarthy DWORD
HandleCreateThreadEvent(const CREATE_THREAD_DEBUG_INFO & info,DWORD thread_id)3544ad5def9SAdrian McCarthy DebuggerThread::HandleCreateThreadEvent(const CREATE_THREAD_DEBUG_INFO &info,
3554ad5def9SAdrian McCarthy                                         DWORD thread_id) {
3566730df47SPavel Labath   Log *log = GetLog(WindowsLog::Event | WindowsLog::Thread);
357e3037904SAaron Smith   LLDB_LOG(log, "Thread {0} spawned in process {1}", thread_id,
358a385d2c1SPavel Labath            m_process.GetProcessId());
3594ad5def9SAdrian McCarthy   HostThread thread(info.hThread);
3604ad5def9SAdrian McCarthy   thread.GetNativeThread().SetOwnsHandle(false);
3614ad5def9SAdrian McCarthy   m_debug_delegate->OnCreateThread(thread);
3624ad5def9SAdrian McCarthy   return DBG_CONTINUE;
3634ad5def9SAdrian McCarthy }
3644ad5def9SAdrian McCarthy 
3654ad5def9SAdrian McCarthy DWORD
HandleCreateProcessEvent(const CREATE_PROCESS_DEBUG_INFO & info,DWORD thread_id)3664ad5def9SAdrian McCarthy DebuggerThread::HandleCreateProcessEvent(const CREATE_PROCESS_DEBUG_INFO &info,
3674ad5def9SAdrian McCarthy                                          DWORD thread_id) {
3686730df47SPavel Labath   Log *log = GetLog(WindowsLog::Event | WindowsLog::Process);
3694ad5def9SAdrian McCarthy   uint32_t process_id = ::GetProcessId(info.hProcess);
3704ad5def9SAdrian McCarthy 
371a385d2c1SPavel Labath   LLDB_LOG(log, "process {0} spawned", process_id);
3724ad5def9SAdrian McCarthy 
3734ad5def9SAdrian McCarthy   std::string thread_name;
3744ad5def9SAdrian McCarthy   llvm::raw_string_ostream name_stream(thread_name);
37564ec505dSJonas Devlieghere   name_stream << "lldb.plugin.process-windows.secondary[" << process_id << "]";
3764ad5def9SAdrian McCarthy   name_stream.flush();
377ed96be99SZachary Turner   llvm::set_thread_name(thread_name);
3784ad5def9SAdrian McCarthy 
3794ad5def9SAdrian McCarthy   // info.hProcess and info.hThread are closed automatically by Windows when
3804ad5def9SAdrian McCarthy   // EXIT_PROCESS_DEBUG_EVENT is received.
3814ad5def9SAdrian McCarthy   m_process = HostProcess(info.hProcess);
3824ad5def9SAdrian McCarthy   ((HostProcessWindows &)m_process.GetNativeProcess()).SetOwnsHandle(false);
3834ad5def9SAdrian McCarthy   m_main_thread = HostThread(info.hThread);
3844ad5def9SAdrian McCarthy   m_main_thread.GetNativeThread().SetOwnsHandle(false);
3854ad5def9SAdrian McCarthy   m_image_file = info.hFile;
3864ad5def9SAdrian McCarthy 
3874ad5def9SAdrian McCarthy   lldb::addr_t load_addr = reinterpret_cast<lldb::addr_t>(info.lpBaseOfImage);
3884ad5def9SAdrian McCarthy   m_debug_delegate->OnDebuggerConnected(load_addr);
3894ad5def9SAdrian McCarthy 
3904ad5def9SAdrian McCarthy   return DBG_CONTINUE;
3914ad5def9SAdrian McCarthy }
3924ad5def9SAdrian McCarthy 
3934ad5def9SAdrian McCarthy DWORD
HandleExitThreadEvent(const EXIT_THREAD_DEBUG_INFO & info,DWORD thread_id)3944ad5def9SAdrian McCarthy DebuggerThread::HandleExitThreadEvent(const EXIT_THREAD_DEBUG_INFO &info,
3954ad5def9SAdrian McCarthy                                       DWORD thread_id) {
3966730df47SPavel Labath   Log *log = GetLog(WindowsLog::Event | WindowsLog::Thread);
397a385d2c1SPavel Labath   LLDB_LOG(log, "Thread {0} exited with code {1} in process {2}", thread_id,
398a385d2c1SPavel Labath            info.dwExitCode, m_process.GetProcessId());
3994ad5def9SAdrian McCarthy   m_debug_delegate->OnExitThread(thread_id, info.dwExitCode);
4004ad5def9SAdrian McCarthy   return DBG_CONTINUE;
4014ad5def9SAdrian McCarthy }
4024ad5def9SAdrian McCarthy 
4034ad5def9SAdrian McCarthy DWORD
HandleExitProcessEvent(const EXIT_PROCESS_DEBUG_INFO & info,DWORD thread_id)4044ad5def9SAdrian McCarthy DebuggerThread::HandleExitProcessEvent(const EXIT_PROCESS_DEBUG_INFO &info,
4054ad5def9SAdrian McCarthy                                        DWORD thread_id) {
4066730df47SPavel Labath   Log *log = GetLog(WindowsLog::Event | WindowsLog::Thread);
407a385d2c1SPavel Labath   LLDB_LOG(log, "process {0} exited with code {1}", m_process.GetProcessId(),
408a385d2c1SPavel Labath            info.dwExitCode);
4094ad5def9SAdrian McCarthy 
4104ad5def9SAdrian McCarthy   m_debug_delegate->OnExitProcess(info.dwExitCode);
4114ad5def9SAdrian McCarthy 
4124ad5def9SAdrian McCarthy   return DBG_CONTINUE;
4134ad5def9SAdrian McCarthy }
4144ad5def9SAdrian McCarthy 
GetFileNameFromHandleFallback(HANDLE hFile)415*87a2dba1SAlvin Wong static llvm::Optional<std::string> GetFileNameFromHandleFallback(HANDLE hFile) {
416*87a2dba1SAlvin Wong   // Check that file is not empty as we cannot map a file with zero length.
417*87a2dba1SAlvin Wong   DWORD dwFileSizeHi = 0;
418*87a2dba1SAlvin Wong   DWORD dwFileSizeLo = ::GetFileSize(hFile, &dwFileSizeHi);
419*87a2dba1SAlvin Wong   if (dwFileSizeLo == 0 && dwFileSizeHi == 0)
420*87a2dba1SAlvin Wong     return llvm::None;
421*87a2dba1SAlvin Wong 
422*87a2dba1SAlvin Wong   AutoHandle filemap(
423*87a2dba1SAlvin Wong       ::CreateFileMappingW(hFile, nullptr, PAGE_READONLY, 0, 1, NULL), nullptr);
424*87a2dba1SAlvin Wong   if (!filemap.IsValid())
425*87a2dba1SAlvin Wong     return llvm::None;
426*87a2dba1SAlvin Wong 
427*87a2dba1SAlvin Wong   auto view_deleter = [](void *pMem) { ::UnmapViewOfFile(pMem); };
428*87a2dba1SAlvin Wong   std::unique_ptr<void, decltype(view_deleter)> pMem(
429*87a2dba1SAlvin Wong       ::MapViewOfFile(filemap.get(), FILE_MAP_READ, 0, 0, 1), view_deleter);
430*87a2dba1SAlvin Wong   if (!pMem)
431*87a2dba1SAlvin Wong     return llvm::None;
432*87a2dba1SAlvin Wong 
433*87a2dba1SAlvin Wong   std::array<wchar_t, MAX_PATH + 1> mapped_filename;
434*87a2dba1SAlvin Wong   if (!::GetMappedFileNameW(::GetCurrentProcess(), pMem.get(),
435*87a2dba1SAlvin Wong                             mapped_filename.data(), mapped_filename.size()))
436*87a2dba1SAlvin Wong     return llvm::None;
437*87a2dba1SAlvin Wong 
438*87a2dba1SAlvin Wong   // A series of null-terminated strings, plus an additional null character
439*87a2dba1SAlvin Wong   std::array<wchar_t, 512> drive_strings;
440*87a2dba1SAlvin Wong   drive_strings[0] = L'\0';
441*87a2dba1SAlvin Wong   if (!::GetLogicalDriveStringsW(drive_strings.size(), drive_strings.data()))
442*87a2dba1SAlvin Wong     return llvm::None;
443*87a2dba1SAlvin Wong 
444*87a2dba1SAlvin Wong   std::array<wchar_t, 3> drive = {L"_:"};
445*87a2dba1SAlvin Wong   for (const wchar_t *it = drive_strings.data(); *it != L'\0';
446*87a2dba1SAlvin Wong        it += wcslen(it) + 1) {
447*87a2dba1SAlvin Wong     // Copy the drive letter to the template string
448*87a2dba1SAlvin Wong     drive[0] = it[0];
449*87a2dba1SAlvin Wong     std::array<wchar_t, MAX_PATH> device_name;
450*87a2dba1SAlvin Wong     if (::QueryDosDeviceW(drive.data(), device_name.data(),
451*87a2dba1SAlvin Wong                           device_name.size())) {
452*87a2dba1SAlvin Wong       size_t device_name_len = wcslen(device_name.data());
453*87a2dba1SAlvin Wong       if (device_name_len < mapped_filename.size()) {
454*87a2dba1SAlvin Wong         bool match = _wcsnicmp(mapped_filename.data(), device_name.data(),
455*87a2dba1SAlvin Wong                                device_name_len) == 0;
456*87a2dba1SAlvin Wong         if (match && mapped_filename[device_name_len] == L'\\') {
457*87a2dba1SAlvin Wong           // Replace device path with its drive letter
458*87a2dba1SAlvin Wong           std::wstring rebuilt_path(drive.data());
459*87a2dba1SAlvin Wong           rebuilt_path.append(&mapped_filename[device_name_len]);
460*87a2dba1SAlvin Wong           std::string path_utf8;
461*87a2dba1SAlvin Wong           llvm::convertWideToUTF8(rebuilt_path, path_utf8);
462*87a2dba1SAlvin Wong           return path_utf8;
463*87a2dba1SAlvin Wong         }
464*87a2dba1SAlvin Wong       }
465*87a2dba1SAlvin Wong     }
466*87a2dba1SAlvin Wong   }
467*87a2dba1SAlvin Wong   return llvm::None;
468*87a2dba1SAlvin Wong }
469*87a2dba1SAlvin Wong 
4704ad5def9SAdrian McCarthy DWORD
HandleLoadDllEvent(const LOAD_DLL_DEBUG_INFO & info,DWORD thread_id)4714ad5def9SAdrian McCarthy DebuggerThread::HandleLoadDllEvent(const LOAD_DLL_DEBUG_INFO &info,
4724ad5def9SAdrian McCarthy                                    DWORD thread_id) {
4736730df47SPavel Labath   Log *log = GetLog(WindowsLog::Event);
4744ad5def9SAdrian McCarthy   if (info.hFile == nullptr) {
4754ad5def9SAdrian McCarthy     // Not sure what this is, so just ignore it.
476a385d2c1SPavel Labath     LLDB_LOG(log, "Warning: Inferior {0} has a NULL file handle, returning...",
4774ad5def9SAdrian McCarthy              m_process.GetProcessId());
4784ad5def9SAdrian McCarthy     return DBG_CONTINUE;
4794ad5def9SAdrian McCarthy   }
4804ad5def9SAdrian McCarthy 
481*87a2dba1SAlvin Wong   auto on_load_dll = [&](llvm::StringRef path) {
482*87a2dba1SAlvin Wong     FileSpec file_spec(path);
483*87a2dba1SAlvin Wong     ModuleSpec module_spec(file_spec);
484*87a2dba1SAlvin Wong     lldb::addr_t load_addr = reinterpret_cast<lldb::addr_t>(info.lpBaseOfDll);
485*87a2dba1SAlvin Wong 
486*87a2dba1SAlvin Wong     LLDB_LOG(log, "Inferior {0} - DLL '{1}' loaded at address {2:x}...",
487*87a2dba1SAlvin Wong              m_process.GetProcessId(), path, info.lpBaseOfDll);
488*87a2dba1SAlvin Wong 
489*87a2dba1SAlvin Wong     m_debug_delegate->OnLoadDll(module_spec, load_addr);
490*87a2dba1SAlvin Wong   };
491*87a2dba1SAlvin Wong 
4924ad5def9SAdrian McCarthy   std::vector<wchar_t> buffer(1);
4934ad5def9SAdrian McCarthy   DWORD required_size =
4944ad5def9SAdrian McCarthy       GetFinalPathNameByHandleW(info.hFile, &buffer[0], 0, VOLUME_NAME_DOS);
4954ad5def9SAdrian McCarthy   if (required_size > 0) {
4964ad5def9SAdrian McCarthy     buffer.resize(required_size + 1);
4974ad5def9SAdrian McCarthy     required_size = GetFinalPathNameByHandleW(info.hFile, &buffer[0],
4984ad5def9SAdrian McCarthy                                               required_size, VOLUME_NAME_DOS);
4994ad5def9SAdrian McCarthy     std::string path_str_utf8;
5004ad5def9SAdrian McCarthy     llvm::convertWideToUTF8(buffer.data(), path_str_utf8);
5014ad5def9SAdrian McCarthy     llvm::StringRef path_str = path_str_utf8;
5024ad5def9SAdrian McCarthy     const char *path = path_str.data();
5034ad5def9SAdrian McCarthy     if (path_str.startswith("\\\\?\\"))
5044ad5def9SAdrian McCarthy       path += 4;
5054ad5def9SAdrian McCarthy 
506*87a2dba1SAlvin Wong     on_load_dll(path);
507*87a2dba1SAlvin Wong   } else if (llvm::Optional<std::string> path =
508*87a2dba1SAlvin Wong                  GetFileNameFromHandleFallback(info.hFile)) {
509*87a2dba1SAlvin Wong     on_load_dll(*path);
5104ad5def9SAdrian McCarthy   } else {
511a385d2c1SPavel Labath     LLDB_LOG(
512a385d2c1SPavel Labath         log,
513a385d2c1SPavel Labath         "Inferior {0} - Error {1} occurred calling GetFinalPathNameByHandle",
5144ad5def9SAdrian McCarthy         m_process.GetProcessId(), ::GetLastError());
5154ad5def9SAdrian McCarthy   }
5164ad5def9SAdrian McCarthy   // Windows does not automatically close info.hFile, so we need to do it.
5174ad5def9SAdrian McCarthy   ::CloseHandle(info.hFile);
5184ad5def9SAdrian McCarthy   return DBG_CONTINUE;
5194ad5def9SAdrian McCarthy }
5204ad5def9SAdrian McCarthy 
5214ad5def9SAdrian McCarthy DWORD
HandleUnloadDllEvent(const UNLOAD_DLL_DEBUG_INFO & info,DWORD thread_id)5224ad5def9SAdrian McCarthy DebuggerThread::HandleUnloadDllEvent(const UNLOAD_DLL_DEBUG_INFO &info,
5234ad5def9SAdrian McCarthy                                      DWORD thread_id) {
5246730df47SPavel Labath   Log *log = GetLog(WindowsLog::Event);
525a385d2c1SPavel Labath   LLDB_LOG(log, "process {0} unloading DLL at addr {1:x}.",
5264ad5def9SAdrian McCarthy            m_process.GetProcessId(), info.lpBaseOfDll);
5274ad5def9SAdrian McCarthy 
5284ad5def9SAdrian McCarthy   m_debug_delegate->OnUnloadDll(
5294ad5def9SAdrian McCarthy       reinterpret_cast<lldb::addr_t>(info.lpBaseOfDll));
5304ad5def9SAdrian McCarthy   return DBG_CONTINUE;
5314ad5def9SAdrian McCarthy }
5324ad5def9SAdrian McCarthy 
5334ad5def9SAdrian McCarthy DWORD
HandleODSEvent(const OUTPUT_DEBUG_STRING_INFO & info,DWORD thread_id)5344ad5def9SAdrian McCarthy DebuggerThread::HandleODSEvent(const OUTPUT_DEBUG_STRING_INFO &info,
5354ad5def9SAdrian McCarthy                                DWORD thread_id) {
5364ad5def9SAdrian McCarthy   return DBG_CONTINUE;
5374ad5def9SAdrian McCarthy }
5384ad5def9SAdrian McCarthy 
5394ad5def9SAdrian McCarthy DWORD
HandleRipEvent(const RIP_INFO & info,DWORD thread_id)5404ad5def9SAdrian McCarthy DebuggerThread::HandleRipEvent(const RIP_INFO &info, DWORD thread_id) {
5416730df47SPavel Labath   Log *log = GetLog(WindowsLog::Event);
542a385d2c1SPavel Labath   LLDB_LOG(log, "encountered error {0} (type={1}) in process {2} thread {3}",
5434ad5def9SAdrian McCarthy            info.dwError, info.dwType, m_process.GetProcessId(), thread_id);
5444ad5def9SAdrian McCarthy 
54597206d57SZachary Turner   Status error(info.dwError, eErrorTypeWin32);
5464ad5def9SAdrian McCarthy   m_debug_delegate->OnDebuggerError(error, info.dwType);
5474ad5def9SAdrian McCarthy 
5484ad5def9SAdrian McCarthy   return DBG_CONTINUE;
5494ad5def9SAdrian McCarthy }
550