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}",
256 LLDB_LOG(log,
"broadcasting for inferior process {0}.",
277 DEBUG_EVENT dbe = {};
278 bool should_debug =
true;
280 while (should_debug) {
284 DWORD continue_status = DBG_CONTINUE;
286 switch (dbe.dwDebugEventCode) {
288 llvm_unreachable(
"Unhandled debug event code!");
289 case EXCEPTION_DEBUG_EVENT: {
291 dbe.u.Exception, dbe.dwThreadId, shutting_down);
294 continue_status = DBG_CONTINUE;
296 continue_status = DBG_EXCEPTION_NOT_HANDLED;
300 case CREATE_THREAD_DEBUG_EVENT:
304 case CREATE_PROCESS_DEBUG_EVENT:
308 case EXIT_THREAD_DEBUG_EVENT:
312 case EXIT_PROCESS_DEBUG_EVENT:
315 should_debug =
false;
317 case LOAD_DLL_DEBUG_EVENT:
320 case UNLOAD_DLL_DEBUG_EVENT:
323 case OUTPUT_DEBUG_STRING_EVENT:
324 continue_status =
HandleODSEvent(dbe.u.DebugString, dbe.dwThreadId);
328 if (dbe.u.RipInfo.dwType == SLE_ERROR)
329 should_debug =
false;
334 log,
"calling ContinueDebugEvent({0}, {1}, {2}) on thread {3}.",
335 dbe.dwProcessId, dbe.dwThreadId, continue_status,
336 ::GetCurrentThreadId());
338 ::ContinueDebugEvent(dbe.dwProcessId, dbe.dwThreadId, continue_status);
347 (dbe.u.Exception.ExceptionRecord.ExceptionCode ==
348 EXCEPTION_BREAKPOINT ||
349 dbe.u.Exception.ExceptionRecord.ExceptionCode ==
352 "Breakpoint exception is cue to detach from process {0:x}",
361 continue_status = DBG_CONTINUE;
362 if (dbe.dwDebugEventCode == EXCEPTION_DEBUG_EVENT &&
363 !(dbe.u.Exception.ExceptionRecord.ExceptionCode ==
364 EXCEPTION_BREAKPOINT ||
365 dbe.u.Exception.ExceptionRecord.ExceptionCode ==
367 dbe.u.Exception.ExceptionRecord.ExceptionCode ==
368 EXCEPTION_SINGLE_STEP))
369 continue_status = DBG_EXCEPTION_NOT_HANDLED;
370 ::ContinueDebugEvent(dbe.dwProcessId, dbe.dwThreadId,
380 should_debug =
false;
382 LLDB_LOG(log,
"returned FALSE from WaitForDebugEventEx. Error = {0}",
385 should_debug =
false;
390 LLDB_LOG(log,
"WaitForDebugEventEx loop completed, exiting.");
396 DWORD thread_id,
bool shutting_down) {
400 (info.ExceptionRecord.ExceptionCode == EXCEPTION_BREAKPOINT ||
410 bool first_chance = (info.dwFirstChance != 0);
413 std::make_shared<ExceptionRecord>(info.ExceptionRecord, thread_id);
423 LLDB_LOG(log,
"encountered {0} chance exception {1:x} on thread {2:x}",
424 first_chance ?
"first" :
"second",
425 info.ExceptionRecord.ExceptionCode, thread_id);
436 LLDB_LOG(log,
"waiting for ExceptionPred != BreakInDebugger");
448 LLDB_LOG(log,
"Thread {0} spawned in process {1}", thread_id,
451 thread.GetNativeThread().SetOwnsHandle(
false);
460 uint32_t process_id = ::GetProcessId(info.hProcess);
462 LLDB_LOG(log,
"process {0} spawned", process_id);
464 std::string thread_name;
465 llvm::raw_string_ostream name_stream(thread_name);
466 name_stream <<
"lldb.plugin.process-windows.secondary[" << process_id <<
"]";
467 llvm::set_thread_name(thread_name);
488 LLDB_LOG(log,
"Thread {0} exited with code {1} in process {2}", thread_id,
489 info.dwExitCode,
m_process.GetProcessId());
506static std::optional<std::string>
510 llvm::SmallVector<wchar_t, MAX_PATH> vol_name(
MAX_PATH);
511 HANDLE vol_iter = ::FindFirstVolumeW(vol_name.data(), vol_name.size());
512 if (vol_iter == INVALID_HANDLE_VALUE) {
514 "ConvertNtDevicePathToDosPath: FindFirstVolumeW failed, "
519 llvm::scope_exit close_iter([&] { ::FindVolumeClose(vol_iter); });
524 size_t vol_len = ::wcsnlen(vol_name.data(), vol_name.size());
525 if (vol_len < 5 || vol_name[vol_len - 1] != L
'\\')
528 vol_name[vol_len - 1] = L
'\0';
529 llvm::SmallVector<wchar_t, MAX_PATH> dev_name(
MAX_PATH);
530 bool ok = ::QueryDosDeviceW(vol_name.data() + 4,
531 dev_name.data(), dev_name.size());
532 vol_name[vol_len - 1] = L
'\\';
537 size_t dev_len = ::wcsnlen(dev_name.data(), dev_name.size());
538 if (dev_len == 0 || dev_len >= nt_path.size())
540 if (_wcsnicmp(nt_path.data(), dev_name.data(), dev_len) != 0)
542 if (nt_path[dev_len] != L
'\\')
546 llvm::ArrayRef<wchar_t> mount(vol_name.data(), vol_len);
547 llvm::SmallVector<wchar_t> mount_names;
548 DWORD names_size = 0;
549 ::GetVolumePathNamesForVolumeNameW(vol_name.data(),
nullptr, 0,
551 if (names_size > 1) {
552 mount_names.resize(names_size);
554 if (::GetVolumePathNamesForVolumeNameW(
555 vol_name.data(), mount_names.data(), names_size, &written) &&
556 mount_names[0] != L
'\0') {
557 mount = llvm::ArrayRef<wchar_t>(
559 ::wcsnlen(mount_names.data(), mount_names.size()));
564 llvm::SmallVector<wchar_t> dos_wide(mount.begin(), mount.end());
565 if (!dos_wide.empty() && dos_wide.back() == L
'\\')
567 dos_wide.append(nt_path.begin() + dev_len, nt_path.end());
570 llvm::convertWideToUTF8(std::wstring_view(dos_wide.data(), dos_wide.size()),
573 }
while (::FindNextVolumeW(vol_iter, vol_name.data(), vol_name.size()));
575 LLDB_LOG(log,
"ConvertNtDevicePathToDosPath: no matching volume found");
583 std::vector<wchar_t> mapped_filename(
MAX_PATH + 1);
584 DWORD mapped_len = 0;
586 mapped_len = ::GetMappedFileNameW(process, addr, mapped_filename.data(),
587 mapped_filename.size());
590 if (mapped_len < mapped_filename.size())
592 mapped_filename.resize(mapped_filename.size() * 2);
595 llvm::ArrayRef<wchar_t>(mapped_filename.data(), mapped_len + 1));
600 DWORD dwFileSizeHi = 0;
601 DWORD dwFileSizeLo = ::GetFileSize(hFile, &dwFileSizeHi);
602 if (dwFileSizeLo == 0 && dwFileSizeHi == 0)
606 ::CreateFileMappingW(hFile,
nullptr, PAGE_READONLY, 0, 1,
nullptr),
611 auto view_deleter = [](
void *pMem) { ::UnmapViewOfFile(pMem); };
612 std::unique_ptr<void,
decltype(view_deleter)> pMem(
613 ::MapViewOfFile(filemap.
get(), FILE_MAP_READ, 0, 0, 1), view_deleter);
622 std::vector<wchar_t> module_filename(
MAX_PATH + 1);
625 ::GetModuleFileNameExW(process,
reinterpret_cast<HMODULE
>(base_addr),
626 module_filename.data(), module_filename.size());
629 if (len < module_filename.size()) {
630 std::string path_utf8;
631 llvm::convertWideToUTF8(std::wstring_view(module_filename.data(), len),
635 module_filename.resize(module_filename.size() * 2);
646 MEMORY_BASIC_INFORMATION mbi{};
647 if (!::VirtualQueryEx(process, addr, &mbi,
sizeof(mbi)))
649 if (mbi.State != MEM_COMMIT)
651 uintptr_t region_end =
652 reinterpret_cast<uintptr_t
>(mbi.BaseAddress) + mbi.RegionSize;
653 uintptr_t a =
reinterpret_cast<uintptr_t
>(addr);
654 assert(a < region_end);
655 return region_end - a;
662 std::vector<wchar_t> buf;
663 for (SIZE_T capacity =
MAX_PATH *
sizeof(
wchar_t);; capacity *= 2) {
664 SIZE_T to_read = std::min<SIZE_T>(capacity, limit);
665 to_read &= ~SIZE_T(1);
666 if (to_read <
sizeof(
wchar_t))
669 buf.resize(to_read /
sizeof(
wchar_t));
670 SIZE_T bytes_read = 0;
674 size_t max_chars = bytes_read /
sizeof(wchar_t);
675 size_t len = ::wcsnlen(buf.data(), max_chars);
676 if (len < max_chars) {
680 llvm::convertWideToUTF8(std::wstring_view(buf.data(), len), result);
683 if (to_read >= limit)
692 std::vector<char> buf;
693 for (SIZE_T capacity =
MAX_PATH;; capacity *= 2) {
694 SIZE_T to_read = std::min<SIZE_T>(capacity, limit);
699 SIZE_T bytes_read = 0;
703 size_t len = ::strnlen(buf.data(), bytes_read);
704 if (len < bytes_read) {
707 return std::string(buf.data(), len);
709 if (to_read >= limit)
715static std::optional<std::string>
717 if (info.lpImageName ==
nullptr)
720 LPVOID string_addr =
nullptr;
721 SIZE_T bytes_read = 0;
723 sizeof(string_addr), &bytes_read) ||
724 bytes_read !=
sizeof(string_addr))
738 auto on_load_dll = [&](llvm::StringRef path) {
743 LLDB_LOG(log,
"Inferior {0} - DLL '{1}' loaded at address {2:x}...",
744 m_process.GetProcessId(), path, info.lpBaseOfDll);
750 std::optional<std::string> resolved_path;
751 if (info.hFile !=
nullptr) {
752 std::vector<wchar_t> buffer(1);
753 DWORD required_size =
754 GetFinalPathNameByHandleW(info.hFile, &buffer[0], 0, VOLUME_NAME_DOS);
755 if (required_size > 0) {
756 buffer.resize(required_size + 1);
757 GetFinalPathNameByHandleW(info.hFile, &buffer[0], required_size,
759 std::string path_str_utf8;
760 llvm::convertWideToUTF8(buffer.data(), path_str_utf8);
761 llvm::StringRef path_str = path_str_utf8;
762 path_str.consume_front(
"\\\\?\\");
763 resolved_path = path_str.str();
776 on_load_dll(*resolved_path);
779 "Inferior {0} - could not resolve path for LOAD_DLL_DEBUG_EVENT "
780 "(hFile={1}, base={2:x}, last error={3})",
781 m_process.GetProcessId(), info.hFile, info.lpBaseOfDll,
785 if (info.hFile !=
nullptr)
786 ::CloseHandle(info.hFile);
797 LLDB_LOG(log,
"process {0} unloading DLL at addr {1:x}.",
798 m_process.GetProcessId(), info.lpBaseOfDll);
802 reinterpret_cast<lldb::addr_t>(info.lpBaseOfDll), thread_id);
813 reinterpret_cast<uintptr_t
>(info.lpDebugStringData)),
814 info.fUnicode == TRUE, info.nDebugStringLength);
821 LLDB_LOG(log,
"encountered error {0} (type={1}) in process {2} thread {3}",
822 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()
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::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.