31#include "llvm/ADT/STLExtras.h"
32#include "llvm/Support/ConvertUTF.h"
33#include "llvm/Support/Path.h"
34#include "llvm/Support/Threading.h"
35#include "llvm/Support/raw_ostream.h"
42#ifndef STATUS_WX86_BREAKPOINT
43#define STATUS_WX86_BREAKPOINT 0x4000001FL
58 L
"kernel32.dll",
"WaitForDebugEventEx"};
63 if (!s_wait_for_debug_event_ex) {
66 "WaitForDebugEventEx unavailable, using WaitForDebugEvent instead. "
67 "Unicode strings from OutputDebugStringW might show incorrectly.");
89 "lldb.plugin.process-windows.secondary[?]",
91 if (!secondary_thread) {
93 LLDB_LOG(log,
"couldn't launch debugger thread. {0}", result);
102 LLDB_LOG(log,
"attaching to '{0}'", pid);
106 "lldb.plugin.process-windows.secondary[?]", [
this, pid, attach_info] {
109 if (!secondary_thread) {
111 LLDB_LOG(log,
"couldn't attach to process '{0}'. {1}", pid, result);
121 std::shared_ptr<DebuggerThread> this_ref(shared_from_this());
124 LLDB_LOG(log,
"preparing to launch '{0}' on background thread.",
148 std::shared_ptr<DebuggerThread> this_ref(shared_from_this());
151 LLDB_LOG(log,
"preparing to attach to process '{0}' on background thread.",
154 if (!DebugActiveProcess(
static_cast<DWORD
>(pid))) {
174 LLDB_LOG(log,
"terminate = {0}, inferior={1}.", terminate, pid);
178 bool expected =
false;
193 BOOL terminate_succeeded = TerminateProcess(handle, 0);
195 "calling TerminateProcess({0}, 0) (inferior={1}), success={2}",
196 handle, pid, terminate_succeeded);
199 "NOT calling TerminateProcess because the inferior is not valid "
200 "({0}, 0) (inferior={1})",
210 LLDB_LOG(log,
"masking active exception");
222 if (!::DebugBreakProcess(
223 GetProcess().GetNativeProcess().GetSystemHandle())) {
228 LLDB_LOG(log,
"waiting for detach from process {0} to complete.", pid);
231 if (wait_result != WAIT_OBJECT_0) {
233 LLDB_LOG(log,
"error: WaitForSingleObject({0}, 5000) returned {1}",
236 LLDB_LOG(log,
"detach from process {0} completed successfully.", pid);
238 if (!
error.Success()) {
239 LLDB_LOG(log,
"encountered an error while trying to stop process {0}. {1}",
259 LLDB_LOG(log,
"broadcasting for inferior process {0}.",
280 DEBUG_EVENT dbe = {};
281 bool should_debug =
true;
283 while (should_debug) {
287 DWORD continue_status = DBG_CONTINUE;
289 HANDLE exited_process =
nullptr;
290 switch (dbe.dwDebugEventCode) {
292 llvm_unreachable(
"Unhandled debug event code!");
293 case EXCEPTION_DEBUG_EVENT: {
295 dbe.u.Exception, dbe.dwThreadId, shutting_down);
298 continue_status = DBG_CONTINUE;
300 continue_status = DBG_EXCEPTION_NOT_HANDLED;
304 case CREATE_THREAD_DEBUG_EVENT:
308 case CREATE_PROCESS_DEBUG_EVENT:
312 case EXIT_THREAD_DEBUG_EVENT:
316 case EXIT_PROCESS_DEBUG_EVENT:
317 if (!::DuplicateHandle(::GetCurrentProcess(),
318 m_process.GetNativeProcess().GetSystemHandle(),
319 ::GetCurrentProcess(), &exited_process,
320 SYNCHRONIZE, FALSE, 0))
321 exited_process =
nullptr;
322 should_debug =
false;
324 case LOAD_DLL_DEBUG_EVENT:
327 case UNLOAD_DLL_DEBUG_EVENT:
330 case OUTPUT_DEBUG_STRING_EVENT:
331 continue_status =
HandleODSEvent(dbe.u.DebugString, dbe.dwThreadId);
335 if (dbe.u.RipInfo.dwType == SLE_ERROR)
336 should_debug =
false;
341 log,
"calling ContinueDebugEvent({0}, {1}, {2}) on thread {3}.",
342 dbe.dwProcessId, dbe.dwThreadId, continue_status,
343 ::GetCurrentThreadId());
345 ::ContinueDebugEvent(dbe.dwProcessId, dbe.dwThreadId, continue_status);
347 if (dbe.dwDebugEventCode == EXIT_PROCESS_DEBUG_EVENT) {
348 if (exited_process) {
349 ::WaitForSingleObject(exited_process, INFINITE);
350 ::CloseHandle(exited_process);
362 (dbe.u.Exception.ExceptionRecord.ExceptionCode ==
363 EXCEPTION_BREAKPOINT ||
364 dbe.u.Exception.ExceptionRecord.ExceptionCode ==
367 "Breakpoint exception is cue to detach from process {0:x}",
376 continue_status = DBG_CONTINUE;
377 if (dbe.dwDebugEventCode == EXCEPTION_DEBUG_EVENT &&
378 !(dbe.u.Exception.ExceptionRecord.ExceptionCode ==
379 EXCEPTION_BREAKPOINT ||
380 dbe.u.Exception.ExceptionRecord.ExceptionCode ==
382 dbe.u.Exception.ExceptionRecord.ExceptionCode ==
383 EXCEPTION_SINGLE_STEP))
384 continue_status = DBG_EXCEPTION_NOT_HANDLED;
385 ::ContinueDebugEvent(dbe.dwProcessId, dbe.dwThreadId,
395 should_debug =
false;
397 LLDB_LOG(log,
"returned FALSE from WaitForDebugEventEx. Error = {0}",
400 should_debug =
false;
405 LLDB_LOG(log,
"WaitForDebugEventEx loop completed, exiting.");
411 DWORD thread_id,
bool shutting_down) {
415 (info.ExceptionRecord.ExceptionCode == EXCEPTION_BREAKPOINT ||
425 bool first_chance = (info.dwFirstChance != 0);
428 std::make_shared<ExceptionRecord>(info.ExceptionRecord, thread_id);
438 LLDB_LOG(log,
"encountered {0} chance exception {1:x} on thread {2:x}",
439 first_chance ?
"first" :
"second",
440 info.ExceptionRecord.ExceptionCode, thread_id);
451 LLDB_LOG(log,
"waiting for ExceptionPred != BreakInDebugger");
463 LLDB_LOG(log,
"Thread {0} spawned in process {1}", thread_id,
466 thread.GetNativeThread().SetOwnsHandle(
false);
479 static LazyImport<
decltype(&::NtQueryInformationProcess)>
480 s_query_information_process{L
"ntdll.dll",
"NtQueryInformationProcess"};
481 if (!s_query_information_process)
484 PROCESS_BASIC_INFORMATION pbi = {};
485 if ((*s_query_information_process)(process, ProcessBasicInformation, &pbi,
486 sizeof(pbi),
nullptr) < 0 ||
493 !peb.ProcessParameters)
496 RTL_USER_PROCESS_PARAMETERS params = {};
498 sizeof(params),
nullptr) ||
499 !params.ImagePathName.Buffer || params.ImagePathName.Length == 0)
502 std::wstring wpath(params.ImagePathName.Length /
sizeof(
wchar_t), L
'\0');
504 params.ImagePathName.Length,
nullptr))
508 if (!llvm::convertWideToUTF8(wpath, path))
518 uint32_t process_id = ::GetProcessId(info.hProcess);
520 LLDB_LOG(log,
"process {0} spawned", process_id);
522 std::string thread_name;
523 llvm::raw_string_ostream name_stream(thread_name);
524 name_stream <<
"lldb.plugin.process-windows.secondary[" << process_id <<
"]";
525 llvm::set_thread_name(thread_name);
547 LLDB_LOG(log,
"Thread {0} exited with code {1} in process {2}", thread_id,
548 info.dwExitCode,
m_process.GetProcessId());
565static std::optional<std::string>
569 llvm::SmallVector<wchar_t, MAX_PATH> vol_name(
MAX_PATH);
570 HANDLE vol_iter = ::FindFirstVolumeW(vol_name.data(), vol_name.size());
571 if (vol_iter == INVALID_HANDLE_VALUE) {
573 "ConvertNtDevicePathToDosPath: FindFirstVolumeW failed, "
578 llvm::scope_exit close_iter([&] { ::FindVolumeClose(vol_iter); });
583 size_t vol_len = ::wcsnlen(vol_name.data(), vol_name.size());
584 if (vol_len < 5 || vol_name[vol_len - 1] != L
'\\')
587 vol_name[vol_len - 1] = L
'\0';
588 llvm::SmallVector<wchar_t, MAX_PATH> dev_name(
MAX_PATH);
589 bool ok = ::QueryDosDeviceW(vol_name.data() + 4,
590 dev_name.data(), dev_name.size());
591 vol_name[vol_len - 1] = L
'\\';
596 size_t dev_len = ::wcsnlen(dev_name.data(), dev_name.size());
597 if (dev_len == 0 || dev_len >= nt_path.size())
599 if (_wcsnicmp(nt_path.data(), dev_name.data(), dev_len) != 0)
601 if (nt_path[dev_len] != L
'\\')
605 llvm::ArrayRef<wchar_t> mount(vol_name.data(), vol_len);
606 llvm::SmallVector<wchar_t> mount_names;
607 DWORD names_size = 0;
608 ::GetVolumePathNamesForVolumeNameW(vol_name.data(),
nullptr, 0,
610 if (names_size > 1) {
611 mount_names.resize(names_size);
613 if (::GetVolumePathNamesForVolumeNameW(
614 vol_name.data(), mount_names.data(), names_size, &written) &&
615 mount_names[0] != L
'\0') {
616 mount = llvm::ArrayRef<wchar_t>(
618 ::wcsnlen(mount_names.data(), mount_names.size()));
623 llvm::SmallVector<wchar_t> dos_wide(mount.begin(), mount.end());
624 if (!dos_wide.empty() && dos_wide.back() == L
'\\')
626 dos_wide.append(nt_path.begin() + dev_len, nt_path.end());
629 llvm::convertWideToUTF8(std::wstring_view(dos_wide.data(), dos_wide.size()),
632 }
while (::FindNextVolumeW(vol_iter, vol_name.data(), vol_name.size()));
634 LLDB_LOG(log,
"ConvertNtDevicePathToDosPath: no matching volume found");
642 std::vector<wchar_t> mapped_filename(
MAX_PATH + 1);
643 DWORD mapped_len = 0;
645 mapped_len = ::GetMappedFileNameW(process, addr, mapped_filename.data(),
646 mapped_filename.size());
649 if (mapped_len < mapped_filename.size())
651 mapped_filename.resize(mapped_filename.size() * 2);
654 llvm::ArrayRef<wchar_t>(mapped_filename.data(), mapped_len + 1));
659 DWORD dwFileSizeHi = 0;
660 DWORD dwFileSizeLo = ::GetFileSize(hFile, &dwFileSizeHi);
661 if (dwFileSizeLo == 0 && dwFileSizeHi == 0)
665 ::CreateFileMappingW(hFile,
nullptr, PAGE_READONLY, 0, 1,
nullptr),
670 auto view_deleter = [](
void *pMem) { ::UnmapViewOfFile(pMem); };
671 std::unique_ptr<void,
decltype(view_deleter)> pMem(
672 ::MapViewOfFile(filemap.
get(), FILE_MAP_READ, 0, 0, 1), view_deleter);
683 std::vector<wchar_t> module_filename(
MAX_PATH + 1);
686 ::GetModuleFileNameExW(process,
reinterpret_cast<HMODULE
>(base_addr),
687 module_filename.data(), module_filename.size());
690 if (len < module_filename.size()) {
691 std::string path_utf8;
692 llvm::convertWideToUTF8(std::wstring_view(module_filename.data(), len),
696 module_filename.resize(module_filename.size() * 2);
705 MEMORY_BASIC_INFORMATION mbi{};
706 if (!::VirtualQueryEx(process, addr, &mbi,
sizeof(mbi)))
708 if (mbi.State != MEM_COMMIT)
710 uintptr_t region_end =
711 reinterpret_cast<uintptr_t
>(mbi.BaseAddress) + mbi.RegionSize;
712 uintptr_t a =
reinterpret_cast<uintptr_t
>(addr);
713 assert(a < region_end);
714 return region_end - a;
721 std::vector<wchar_t> buf;
722 for (SIZE_T capacity =
MAX_PATH *
sizeof(
wchar_t);; capacity *= 2) {
723 SIZE_T to_read = std::min<SIZE_T>(capacity, limit);
724 to_read &= ~SIZE_T(1);
725 if (to_read <
sizeof(
wchar_t))
728 buf.resize(to_read /
sizeof(
wchar_t));
729 SIZE_T bytes_read = 0;
733 size_t max_chars = bytes_read /
sizeof(wchar_t);
734 size_t len = ::wcsnlen(buf.data(), max_chars);
735 if (len < max_chars) {
739 llvm::convertWideToUTF8(std::wstring_view(buf.data(), len), result);
742 if (to_read >= limit)
751 std::vector<char> buf;
752 for (SIZE_T capacity =
MAX_PATH;; capacity *= 2) {
753 SIZE_T to_read = std::min<SIZE_T>(capacity, limit);
758 SIZE_T bytes_read = 0;
762 size_t len = ::strnlen(buf.data(), bytes_read);
763 if (len < bytes_read) {
766 return std::string(buf.data(), len);
768 if (to_read >= limit)
774static std::optional<std::string>
776 if (info.lpImageName ==
nullptr)
779 LPVOID string_addr =
nullptr;
780 SIZE_T bytes_read = 0;
782 sizeof(string_addr), &bytes_read) ||
783 bytes_read !=
sizeof(string_addr))
797 auto on_load_dll = [&](llvm::StringRef path) {
802 LLDB_LOG(log,
"Inferior {0} - DLL '{1}' loaded at address {2:x}...",
803 m_process.GetProcessId(), path, info.lpBaseOfDll);
813 std::optional<std::string> loader_path =
815 if (loader_path && !llvm::sys::path::is_absolute(
816 *loader_path, llvm::sys::path::Style::windows))
824 std::optional<std::string> file_path;
825 if (info.hFile !=
nullptr) {
826 std::vector<wchar_t> buffer(1);
827 DWORD required_size =
828 GetFinalPathNameByHandleW(info.hFile, &buffer[0], 0, VOLUME_NAME_DOS);
829 if (required_size > 0) {
830 buffer.resize(required_size + 1);
831 GetFinalPathNameByHandleW(info.hFile, &buffer[0], required_size,
833 std::string path_str_utf8;
834 llvm::convertWideToUTF8(buffer.data(), path_str_utf8);
844 std::optional<std::string> resolved_path = loader_path;
845 if (!resolved_path ||
847 llvm::StringRef(*file_path).equals_insensitive(*resolved_path)))
848 resolved_path = file_path;
855 on_load_dll(*resolved_path);
858 "Inferior {0} - could not resolve path for LOAD_DLL_DEBUG_EVENT "
859 "(hFile={1}, base={2:x}, last error={3})",
860 m_process.GetProcessId(), info.hFile, info.lpBaseOfDll,
864 if (info.hFile !=
nullptr)
865 ::CloseHandle(info.hFile);
876 LLDB_LOG(log,
"process {0} unloading DLL at addr {1:x}.",
877 m_process.GetProcessId(), info.lpBaseOfDll);
881 reinterpret_cast<lldb::addr_t>(info.lpBaseOfDll), thread_id);
892 reinterpret_cast<uintptr_t
>(info.lpDebugStringData)),
893 info.fUnicode == TRUE, info.nDebugStringLength);
900 LLDB_LOG(log,
"encountered error {0} (type={1}) in process {2} thread {3}",
901 info.dwError, info.dwType,
m_process.GetProcessId(), thread_id);
static llvm::raw_ostream & error(Stream &strm)
static std::optional< std::string > GetLoaderModuleName(HANDLE process, LPVOID base_addr)
The path the loader recorded for the module at base_addr, or nullopt if the loader's module list has ...
static std::optional< std::string > GetMappedFileDosPath(HANDLE process, LPVOID addr)
static SIZE_T BytesReadableAt(HANDLE process, LPCVOID addr)
static std::optional< std::string > GetImagePathFromPEB(HANDLE process)
Read the path the process was created with from its process parameters (PEB::ProcessParameters->Image...
static WaitForDebugEventFn * g_wait_for_debug_event
static std::optional< std::string > GetFileNameFromImageNameField(HANDLE process, const LOAD_DLL_DEBUG_INFO &info)
static std::optional< std::string > GetFileNameFromHandleFallback(HANDLE hFile)
static std::optional< std::string > ConvertNtDevicePathToDosPath(llvm::ArrayRef< wchar_t > nt_path)
#define STATUS_WX86_BREAKPOINT
BOOL WINAPI WaitForDebugEventFn(LPDEBUG_EVENT, DWORD)
static std::optional< std::string > ReadRemotePathStringW(HANDLE process, LPCVOID addr)
static void InitializeWaitForDebugEvent()
WaitForDebugEventEx is only available on Windows 10+.
static std::optional< std::string > ReadRemotePathStringA(HANDLE process, LPCVOID addr)
static int ReadProcessMemory(uint8_t *buffer, size_t size, const pt_asid *, uint64_t pc, void *context)
Callback used by libipt for reading the process memory.
#define LLDB_LOG(log,...)
The LLDB_LOG* macros defined below are the way to emit log messages.
#define LLDB_LOG_VERBOSE(log,...)
std::atomic< bool > m_is_shutting_down
std::atomic< DWORD > m_pid_to_detach
void ContinueAsyncDllEvent()
Release a HandleLoadDllEvent / HandleUnloadDllEvent that is parked on m_dll_event_pred.
Predicate< bool > m_dll_event_pred
DWORD HandleExitThreadEvent(const EXIT_THREAD_DEBUG_INFO &info, DWORD thread_id)
DWORD HandleODSEvent(const OUTPUT_DEBUG_STRING_INFO &info, DWORD thread_id)
DWORD HandleLoadDllEvent(const LOAD_DLL_DEBUG_INFO &info, DWORD thread_id)
DWORD HandleExitProcessEvent(const EXIT_PROCESS_DEBUG_INFO &info, DWORD thread_id)
Status StopDebugging(bool terminate)
DWORD HandleRipEvent(const RIP_INFO &info, DWORD thread_id)
void ContinueAsyncException(ExceptionResult result)
HostProcess GetProcess() const
lldb::thread_result_t DebuggerThreadAttachRoutine(lldb::pid_t pid, const ProcessAttachInfo &launch_info)
DebuggerThread(DebugDelegateSP debug_delegate)
void FreeProcessHandles()
ExceptionRecordSP GetActiveException()
Returns the exception the debug loop is currently reporting, or null if there is none.
virtual ~DebuggerThread()
DWORD HandleCreateProcessEvent(const CREATE_PROCESS_DEBUG_INFO &info, DWORD thread_id)
ExceptionResult HandleExceptionEvent(const EXCEPTION_DEBUG_INFO &info, DWORD thread_id, bool shutting_down)
Status DebugAttach(lldb::pid_t pid, const ProcessAttachInfo &attach_info)
lldb::thread_result_t DebuggerThreadLaunchRoutine(const ProcessLaunchInfo &launch_info)
ExceptionRecordSP m_active_exception
Predicate< ExceptionResult > m_exception_pred
HANDLE m_debugging_ended_event
Status DebugLaunch(const ProcessLaunchInfo &launch_info)
DWORD HandleUnloadDllEvent(const UNLOAD_DLL_DEBUG_INFO &info, DWORD thread_id)
std::mutex m_active_exception_mutex
DebugDelegateSP m_debug_delegate
DWORD HandleCreateThreadEvent(const CREATE_THREAD_DEBUG_INFO &info, DWORD thread_id)
size_t GetPath(char *path, size_t max_path_length, bool denormalize=true) const
Extract the full path to the file.
void SetOwnsHandle(bool owns)
lldb::pid_t GetProcessId() const
FileSpec & GetExecutableFile()
HostProcess LaunchProcess(const ProcessLaunchInfo &launch_info, Status &error) override
static Status FromError(llvm::Error error)
Avoid using this in new code. Migrate APIs to llvm::Expected instead.
static llvm::Expected< HostThread > LaunchThread(llvm::StringRef name, std::function< lldb::thread_result_t()> thread_function, size_t min_stack_byte_size=0)
#define LLDB_INVALID_PROCESS
A class that represents a running process on the host machine.
Log * GetLog(Cat mask)
Retrieve the Log object for the channel associated with the given log enum.
std::string StripExtendedLengthPrefix(llvm::StringRef path)
Convert an extended-length path to a regular DOS path: "\\?\C:\a" becomes "C:\a" and "\\?...
std::shared_ptr< IDebugDelegate > DebugDelegateSP
std::shared_ptr< ExceptionRecord > ExceptionRecordSP
@ eBroadcastNever
No broadcast will be sent when the value is modified.
@ eBroadcastAlways
Always send a broadcast when the value is modified.
@ eErrorTypeWin32
Standard Win32 error codes.