30#include "llvm/ADT/STLExtras.h"
31#include "llvm/Support/ConvertUTF.h"
32#include "llvm/Support/Threading.h"
33#include "llvm/Support/raw_ostream.h"
39#ifndef STATUS_WX86_BREAKPOINT
40#define STATUS_WX86_BREAKPOINT 0x4000001FL
55 L
"kernel32.dll",
"WaitForDebugEventEx"};
60 if (!s_wait_for_debug_event_ex) {
63 "WaitForDebugEventEx unavailable, using WaitForDebugEvent instead. "
64 "Unicode strings from OutputDebugStringW might show incorrectly.");
86 "lldb.plugin.process-windows.secondary[?]",
88 if (!secondary_thread) {
90 LLDB_LOG(log,
"couldn't launch debugger thread. {0}", result);
99 LLDB_LOG(log,
"attaching to '{0}'", pid);
103 "lldb.plugin.process-windows.secondary[?]", [
this, pid, attach_info] {
106 if (!secondary_thread) {
108 LLDB_LOG(log,
"couldn't attach to process '{0}'. {1}", pid, result);
118 std::shared_ptr<DebuggerThread> this_ref(shared_from_this());
121 LLDB_LOG(log,
"preparing to launch '{0}' on background thread.",
145 std::shared_ptr<DebuggerThread> this_ref(shared_from_this());
148 LLDB_LOG(log,
"preparing to attach to process '{0}' on background thread.",
151 if (!DebugActiveProcess(
static_cast<DWORD
>(pid))) {
171 LLDB_LOG(log,
"terminate = {0}, inferior={1}.", terminate, pid);
175 bool expected =
false;
190 BOOL terminate_succeeded = TerminateProcess(handle, 0);
192 "calling TerminateProcess({0}, 0) (inferior={1}), success={2}",
193 handle, pid, terminate_succeeded);
196 "NOT calling TerminateProcess because the inferior is not valid "
197 "({0}, 0) (inferior={1})",
207 LLDB_LOG(log,
"masking active exception");
219 if (!::DebugBreakProcess(
220 GetProcess().GetNativeProcess().GetSystemHandle())) {
225 LLDB_LOG(log,
"waiting for detach from process {0} to complete.", pid);
228 if (wait_result != WAIT_OBJECT_0) {
230 LLDB_LOG(log,
"error: WaitForSingleObject({0}, 5000) returned {1}",
233 LLDB_LOG(log,
"detach from process {0} completed successfully.", pid);
235 if (!
error.Success()) {
236 LLDB_LOG(log,
"encountered an error while trying to stop process {0}. {1}",
247 LLDB_LOG(log,
"broadcasting for inferior process {0}.",
269 DEBUG_EVENT dbe = {};
270 bool should_debug =
true;
272 while (should_debug) {
276 DWORD continue_status = DBG_CONTINUE;
278 switch (dbe.dwDebugEventCode) {
280 llvm_unreachable(
"Unhandled debug event code!");
281 case EXCEPTION_DEBUG_EVENT: {
283 dbe.u.Exception, dbe.dwThreadId, shutting_down);
286 continue_status = DBG_CONTINUE;
288 continue_status = DBG_EXCEPTION_NOT_HANDLED;
292 case CREATE_THREAD_DEBUG_EVENT:
296 case CREATE_PROCESS_DEBUG_EVENT:
300 case EXIT_THREAD_DEBUG_EVENT:
304 case EXIT_PROCESS_DEBUG_EVENT:
307 should_debug =
false;
309 case LOAD_DLL_DEBUG_EVENT:
312 case UNLOAD_DLL_DEBUG_EVENT:
315 case OUTPUT_DEBUG_STRING_EVENT:
316 continue_status =
HandleODSEvent(dbe.u.DebugString, dbe.dwThreadId);
320 if (dbe.u.RipInfo.dwType == SLE_ERROR)
321 should_debug =
false;
326 log,
"calling ContinueDebugEvent({0}, {1}, {2}) on thread {3}.",
327 dbe.dwProcessId, dbe.dwThreadId, continue_status,
328 ::GetCurrentThreadId());
330 ::ContinueDebugEvent(dbe.dwProcessId, dbe.dwThreadId, continue_status);
339 (dbe.u.Exception.ExceptionRecord.ExceptionCode ==
340 EXCEPTION_BREAKPOINT ||
341 dbe.u.Exception.ExceptionRecord.ExceptionCode ==
344 "Breakpoint exception is cue to detach from process {0:x}",
353 continue_status = DBG_CONTINUE;
354 if (dbe.dwDebugEventCode == EXCEPTION_DEBUG_EVENT &&
355 !(dbe.u.Exception.ExceptionRecord.ExceptionCode ==
356 EXCEPTION_BREAKPOINT ||
357 dbe.u.Exception.ExceptionRecord.ExceptionCode ==
359 dbe.u.Exception.ExceptionRecord.ExceptionCode ==
360 EXCEPTION_SINGLE_STEP))
361 continue_status = DBG_EXCEPTION_NOT_HANDLED;
362 ::ContinueDebugEvent(dbe.dwProcessId, dbe.dwThreadId,
372 should_debug =
false;
374 LLDB_LOG(log,
"returned FALSE from WaitForDebugEventEx. Error = {0}",
377 should_debug =
false;
382 LLDB_LOG(log,
"WaitForDebugEventEx loop completed, exiting.");
388 DWORD thread_id,
bool shutting_down) {
392 (info.ExceptionRecord.ExceptionCode == EXCEPTION_BREAKPOINT ||
402 bool first_chance = (info.dwFirstChance != 0);
406 LLDB_LOG(log,
"encountered {0} chance exception {1:x} on thread {2:x}",
407 first_chance ?
"first" :
"second",
408 info.ExceptionRecord.ExceptionCode, thread_id);
414 LLDB_LOG(log,
"waiting for ExceptionPred != BreakInDebugger");
426 LLDB_LOG(log,
"Thread {0} spawned in process {1}", thread_id,
429 thread.GetNativeThread().SetOwnsHandle(
false);
438 uint32_t process_id = ::GetProcessId(info.hProcess);
440 LLDB_LOG(log,
"process {0} spawned", process_id);
442 std::string thread_name;
443 llvm::raw_string_ostream name_stream(thread_name);
444 name_stream <<
"lldb.plugin.process-windows.secondary[" << process_id <<
"]";
445 llvm::set_thread_name(thread_name);
466 LLDB_LOG(log,
"Thread {0} exited with code {1} in process {2}", thread_id,
467 info.dwExitCode,
m_process.GetProcessId());
484static std::optional<std::string>
488 llvm::SmallVector<wchar_t, MAX_PATH> vol_name(
MAX_PATH);
489 HANDLE vol_iter = ::FindFirstVolumeW(vol_name.data(), vol_name.size());
490 if (vol_iter == INVALID_HANDLE_VALUE) {
492 "ConvertNtDevicePathToDosPath: FindFirstVolumeW failed, "
497 llvm::scope_exit close_iter([&] { ::FindVolumeClose(vol_iter); });
502 size_t vol_len = ::wcsnlen(vol_name.data(), vol_name.size());
503 if (vol_len < 5 || vol_name[vol_len - 1] != L
'\\')
506 vol_name[vol_len - 1] = L
'\0';
507 llvm::SmallVector<wchar_t, MAX_PATH> dev_name(
MAX_PATH);
508 bool ok = ::QueryDosDeviceW(vol_name.data() + 4,
509 dev_name.data(), dev_name.size());
510 vol_name[vol_len - 1] = L
'\\';
515 size_t dev_len = ::wcsnlen(dev_name.data(), dev_name.size());
516 if (dev_len == 0 || dev_len >= nt_path.size())
518 if (_wcsnicmp(nt_path.data(), dev_name.data(), dev_len) != 0)
520 if (nt_path[dev_len] != L
'\\')
524 llvm::ArrayRef<wchar_t> mount(vol_name.data(), vol_len);
525 llvm::SmallVector<wchar_t> mount_names;
526 DWORD names_size = 0;
527 ::GetVolumePathNamesForVolumeNameW(vol_name.data(),
nullptr, 0,
529 if (names_size > 1) {
530 mount_names.resize(names_size);
532 if (::GetVolumePathNamesForVolumeNameW(
533 vol_name.data(), mount_names.data(), names_size, &written) &&
534 mount_names[0] != L
'\0') {
535 mount = llvm::ArrayRef<wchar_t>(
537 ::wcsnlen(mount_names.data(), mount_names.size()));
542 llvm::SmallVector<wchar_t> dos_wide(mount.begin(), mount.end());
543 if (!dos_wide.empty() && dos_wide.back() == L
'\\')
545 dos_wide.append(nt_path.begin() + dev_len, nt_path.end());
548 llvm::convertWideToUTF8(std::wstring_view(dos_wide.data(), dos_wide.size()),
551 }
while (::FindNextVolumeW(vol_iter, vol_name.data(), vol_name.size()));
553 LLDB_LOG(log,
"ConvertNtDevicePathToDosPath: no matching volume found");
561 std::vector<wchar_t> mapped_filename(
MAX_PATH + 1);
562 DWORD mapped_len = 0;
564 mapped_len = ::GetMappedFileNameW(process, addr, mapped_filename.data(),
565 mapped_filename.size());
568 if (mapped_len < mapped_filename.size())
570 mapped_filename.resize(mapped_filename.size() * 2);
573 llvm::ArrayRef<wchar_t>(mapped_filename.data(), mapped_len + 1));
578 DWORD dwFileSizeHi = 0;
579 DWORD dwFileSizeLo = ::GetFileSize(hFile, &dwFileSizeHi);
580 if (dwFileSizeLo == 0 && dwFileSizeHi == 0)
584 ::CreateFileMappingW(hFile,
nullptr, PAGE_READONLY, 0, 1,
nullptr),
589 auto view_deleter = [](
void *pMem) { ::UnmapViewOfFile(pMem); };
590 std::unique_ptr<void,
decltype(view_deleter)> pMem(
591 ::MapViewOfFile(filemap.
get(), FILE_MAP_READ, 0, 0, 1), view_deleter);
600 std::vector<wchar_t> module_filename(
MAX_PATH + 1);
603 ::GetModuleFileNameExW(process,
reinterpret_cast<HMODULE
>(base_addr),
604 module_filename.data(), module_filename.size());
607 if (len < module_filename.size()) {
608 std::string path_utf8;
609 llvm::convertWideToUTF8(std::wstring_view(module_filename.data(), len),
613 module_filename.resize(module_filename.size() * 2);
624 MEMORY_BASIC_INFORMATION mbi{};
625 if (!::VirtualQueryEx(process, addr, &mbi,
sizeof(mbi)))
627 if (mbi.State != MEM_COMMIT)
629 uintptr_t region_end =
630 reinterpret_cast<uintptr_t
>(mbi.BaseAddress) + mbi.RegionSize;
631 uintptr_t a =
reinterpret_cast<uintptr_t
>(addr);
632 assert(a < region_end);
633 return region_end - a;
640 std::vector<wchar_t> buf;
641 for (SIZE_T capacity =
MAX_PATH *
sizeof(
wchar_t);; capacity *= 2) {
642 SIZE_T to_read = std::min<SIZE_T>(capacity, limit);
643 to_read &= ~SIZE_T(1);
644 if (to_read <
sizeof(
wchar_t))
647 buf.resize(to_read /
sizeof(
wchar_t));
648 SIZE_T bytes_read = 0;
652 size_t max_chars = bytes_read /
sizeof(wchar_t);
653 size_t len = ::wcsnlen(buf.data(), max_chars);
654 if (len < max_chars) {
658 llvm::convertWideToUTF8(std::wstring_view(buf.data(), len), result);
661 if (to_read >= limit)
670 std::vector<char> buf;
671 for (SIZE_T capacity =
MAX_PATH;; capacity *= 2) {
672 SIZE_T to_read = std::min<SIZE_T>(capacity, limit);
677 SIZE_T bytes_read = 0;
681 size_t len = ::strnlen(buf.data(), bytes_read);
682 if (len < bytes_read) {
685 return std::string(buf.data(), len);
687 if (to_read >= limit)
693static std::optional<std::string>
695 if (info.lpImageName ==
nullptr)
698 LPVOID string_addr =
nullptr;
699 SIZE_T bytes_read = 0;
701 sizeof(string_addr), &bytes_read) ||
702 bytes_read !=
sizeof(string_addr))
716 auto on_load_dll = [&](llvm::StringRef path) {
721 LLDB_LOG(log,
"Inferior {0} - DLL '{1}' loaded at address {2:x}...",
722 m_process.GetProcessId(), path, info.lpBaseOfDll);
728 std::optional<std::string> resolved_path;
729 if (info.hFile !=
nullptr) {
730 std::vector<wchar_t> buffer(1);
731 DWORD required_size =
732 GetFinalPathNameByHandleW(info.hFile, &buffer[0], 0, VOLUME_NAME_DOS);
733 if (required_size > 0) {
734 buffer.resize(required_size + 1);
735 GetFinalPathNameByHandleW(info.hFile, &buffer[0], required_size,
737 std::string path_str_utf8;
738 llvm::convertWideToUTF8(buffer.data(), path_str_utf8);
739 llvm::StringRef path_str = path_str_utf8;
740 path_str.consume_front(
"\\\\?\\");
741 resolved_path = path_str.str();
754 on_load_dll(*resolved_path);
757 "Inferior {0} - could not resolve path for LOAD_DLL_DEBUG_EVENT "
758 "(hFile={1}, base={2:x}, last error={3})",
759 m_process.GetProcessId(), info.hFile, info.lpBaseOfDll,
763 if (info.hFile !=
nullptr)
764 ::CloseHandle(info.hFile);
775 LLDB_LOG(log,
"process {0} unloading DLL at addr {1:x}.",
776 m_process.GetProcessId(), info.lpBaseOfDll);
780 reinterpret_cast<lldb::addr_t>(info.lpBaseOfDll), thread_id);
791 reinterpret_cast<uintptr_t
>(info.lpDebugStringData)),
792 info.fUnicode == TRUE, info.nDebugStringLength);
799 LLDB_LOG(log,
"encountered error {0} (type={1}) in process {2} thread {3}",
800 info.dwError, info.dwType,
m_process.GetProcessId(), thread_id);
static llvm::raw_ostream & error(Stream &strm)
static std::optional< std::string > GetMappedFileDosPath(HANDLE process, LPVOID addr)
static SIZE_T BytesReadableAt(HANDLE process, LPCVOID addr)
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 > GetFileNameByLoadAddress(HANDLE process, LPVOID base_addr)
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()
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)
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::shared_ptr< IDebugDelegate > DebugDelegateSP
@ 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.