LLDB mainline
DebuggerThread.cpp
Go to the documentation of this file.
1//===-- DebuggerThread.cpp ------------------------------------------------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8
9#include "DebuggerThread.h"
10#include "ExceptionRecord.h"
11#include "IDebugDelegate.h"
12
21#include "lldb/Target/Process.h"
23#include "lldb/Utility/Log.h"
25#include "lldb/Utility/Status.h"
26
28
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"
34
35#include <optional>
36#include <pathcch.h>
37#include <psapi.h>
38
39#ifndef STATUS_WX86_BREAKPOINT
40#define STATUS_WX86_BREAKPOINT 0x4000001FL // For WOW64
41#endif
42
43using namespace lldb;
44using namespace lldb_private;
45
46typedef BOOL WINAPI WaitForDebugEventFn(LPDEBUG_EVENT, DWORD);
48
49/// WaitForDebugEventEx is only available on Windows 10+. This lazily checks if
50/// the function is available and falls back to WaitForDebugEvent if
51/// unavailable. The -Ex version ensures correct forwarding of
52/// OutputDebugStringW events.
54 static LazyImport<WaitForDebugEventFn *> s_wait_for_debug_event_ex = {
55 L"kernel32.dll", "WaitForDebugEventEx"};
56
58 return;
59
60 if (!s_wait_for_debug_event_ex) {
63 "WaitForDebugEventEx unavailable, using WaitForDebugEvent instead. "
64 "Unicode strings from OutputDebugStringW might show incorrectly.");
65 g_wait_for_debug_event = &WaitForDebugEvent;
66 } else {
67 g_wait_for_debug_event = *s_wait_for_debug_event_ex;
68 }
69}
70
72 : m_debug_delegate(debug_delegate), m_pid_to_detach(0),
73 m_is_shutting_down(false) {
75 m_debugging_ended_event = ::CreateEvent(nullptr, TRUE, FALSE, nullptr);
76}
77
79
82 LLDB_LOG(log, "launching '{0}'", launch_info.GetExecutableFile().GetPath());
83
84 Status result;
85 llvm::Expected<HostThread> secondary_thread = ThreadLauncher::LaunchThread(
86 "lldb.plugin.process-windows.secondary[?]",
87 [this, launch_info] { return DebuggerThreadLaunchRoutine(launch_info); });
88 if (!secondary_thread) {
89 result = Status::FromError(secondary_thread.takeError());
90 LLDB_LOG(log, "couldn't launch debugger thread. {0}", result);
91 }
92
93 return result;
94}
95
97 const ProcessAttachInfo &attach_info) {
99 LLDB_LOG(log, "attaching to '{0}'", pid);
100
101 Status result;
102 llvm::Expected<HostThread> secondary_thread = ThreadLauncher::LaunchThread(
103 "lldb.plugin.process-windows.secondary[?]", [this, pid, attach_info] {
104 return DebuggerThreadAttachRoutine(pid, attach_info);
105 });
106 if (!secondary_thread) {
107 result = Status::FromError(secondary_thread.takeError());
108 LLDB_LOG(log, "couldn't attach to process '{0}'. {1}", pid, result);
109 }
110
111 return result;
112}
113
115 const ProcessLaunchInfo &launch_info) {
116 // Grab a shared_ptr reference to this so that we know it won't get deleted
117 // until after the thread routine has exited.
118 std::shared_ptr<DebuggerThread> this_ref(shared_from_this());
119
121 LLDB_LOG(log, "preparing to launch '{0}' on background thread.",
122 launch_info.GetExecutableFile().GetPath());
123
125 ProcessLauncherWindows launcher;
126 HostProcess process(launcher.LaunchProcess(launch_info, error));
127 // If we couldn't create the process, notify waiters immediately. Otherwise
128 // enter the debug loop and wait until we get the create process debug
129 // notification. Note that if the process was created successfully, we can
130 // throw away the process handle we got from CreateProcess because Windows
131 // will give us another (potentially more useful?) handle when it sends us
132 // the CREATE_PROCESS_DEBUG_EVENT.
133 if (error.Success())
134 DebugLoop();
135 else
136 m_debug_delegate->OnDebuggerError(error, 0);
137
138 return {};
139}
140
142 lldb::pid_t pid, const ProcessAttachInfo &attach_info) {
143 // Grab a shared_ptr reference to this so that we know it won't get deleted
144 // until after the thread routine has exited.
145 std::shared_ptr<DebuggerThread> this_ref(shared_from_this());
146
148 LLDB_LOG(log, "preparing to attach to process '{0}' on background thread.",
149 pid);
150
151 if (!DebugActiveProcess(static_cast<DWORD>(pid))) {
152 Status error(::GetLastError(), eErrorTypeWin32);
153 m_debug_delegate->OnDebuggerError(error, 0);
154 return {};
155 }
156
157 // The attach was successful, enter the debug loop. From here on out, this
158 // is no different than a create process operation, so all the same comments
159 // in DebugLaunch should apply from this point out.
160 DebugLoop();
161
162 return {};
163}
164
167
168 lldb::pid_t pid = m_process.GetProcessId();
169
171 LLDB_LOG(log, "terminate = {0}, inferior={1}.", terminate, pid);
172
173 // Set m_is_shutting_down to true if it was false. Return if it was already
174 // true.
175 bool expected = false;
176 if (!m_is_shutting_down.compare_exchange_strong(expected, true))
177 return error;
178
179 // Make a copy of the process, since the termination sequence will reset
180 // DebuggerThread's internal copy and it needs to remain open for the Wait
181 // operation.
182 HostProcess process_copy = m_process;
183 lldb::process_t handle = m_process.GetNativeProcess().GetSystemHandle();
184
185 if (terminate) {
186 if (handle != nullptr && handle != LLDB_INVALID_PROCESS) {
187 // Initiate the termination before continuing the exception, so that the
188 // next debug event we get is the exit process event, and not some other
189 // event.
190 BOOL terminate_succeeded = TerminateProcess(handle, 0);
191 LLDB_LOG(log,
192 "calling TerminateProcess({0}, 0) (inferior={1}), success={2}",
193 handle, pid, terminate_succeeded);
194 } else {
195 LLDB_LOG(log,
196 "NOT calling TerminateProcess because the inferior is not valid "
197 "({0}, 0) (inferior={1})",
198 handle, pid);
199 }
200 }
201
202 // If we're stuck waiting for an exception to continue (e.g. the user is at a
203 // breakpoint messing around in the debugger), continue it now. But only
204 // AFTER calling TerminateProcess to make sure that the very next call to
205 // WaitForDebugEventEx is an exit process event.
206 if (m_active_exception.get()) {
207 LLDB_LOG(log, "masking active exception");
209 }
210
212
213 if (!terminate) {
214 // Indicate that we want to detach.
216
217 // Force a fresh break so that the detach can happen from the debugger
218 // thread.
219 if (!::DebugBreakProcess(
220 GetProcess().GetNativeProcess().GetSystemHandle())) {
221 error = Status(::GetLastError(), eErrorTypeWin32);
222 }
223 }
224
225 LLDB_LOG(log, "waiting for detach from process {0} to complete.", pid);
226
227 DWORD wait_result = WaitForSingleObject(m_debugging_ended_event, 5000);
228 if (wait_result != WAIT_OBJECT_0) {
229 error = Status(GetLastError(), eErrorTypeWin32);
230 LLDB_LOG(log, "error: WaitForSingleObject({0}, 5000) returned {1}",
231 m_debugging_ended_event, wait_result);
232 } else
233 LLDB_LOG(log, "detach from process {0} completed successfully.", pid);
234
235 if (!error.Success()) {
236 LLDB_LOG(log, "encountered an error while trying to stop process {0}. {1}",
237 pid, error);
238 }
239 return error;
240}
241
243 if (!m_active_exception.get())
244 return;
245
247 LLDB_LOG(log, "broadcasting for inferior process {0}.",
248 m_process.GetProcessId());
249
250 m_active_exception.reset();
251 m_exception_pred.SetValue(result, eBroadcastAlways);
252}
253
257
261 if (m_image_file) {
262 ::CloseHandle(m_image_file);
263 m_image_file = nullptr;
264 }
265}
266
269 DEBUG_EVENT dbe = {};
270 bool should_debug = true;
271 LLDB_LOG_VERBOSE(log, "Entering WaitForDebugEventEx loop");
272 while (should_debug) {
273 LLDB_LOG_VERBOSE(log, "Calling WaitForDebugEvent");
274 BOOL wait_result = g_wait_for_debug_event(&dbe, INFINITE);
275 if (wait_result) {
276 DWORD continue_status = DBG_CONTINUE;
277 bool shutting_down = m_is_shutting_down;
278 switch (dbe.dwDebugEventCode) {
279 default:
280 llvm_unreachable("Unhandled debug event code!");
281 case EXCEPTION_DEBUG_EVENT: {
283 dbe.u.Exception, dbe.dwThreadId, shutting_down);
284
285 if (status == ExceptionResult::MaskException)
286 continue_status = DBG_CONTINUE;
287 else if (status == ExceptionResult::SendToApplication)
288 continue_status = DBG_EXCEPTION_NOT_HANDLED;
289
290 break;
291 }
292 case CREATE_THREAD_DEBUG_EVENT:
293 continue_status =
294 HandleCreateThreadEvent(dbe.u.CreateThread, dbe.dwThreadId);
295 break;
296 case CREATE_PROCESS_DEBUG_EVENT:
297 continue_status =
298 HandleCreateProcessEvent(dbe.u.CreateProcessInfo, dbe.dwThreadId);
299 break;
300 case EXIT_THREAD_DEBUG_EVENT:
301 continue_status =
302 HandleExitThreadEvent(dbe.u.ExitThread, dbe.dwThreadId);
303 break;
304 case EXIT_PROCESS_DEBUG_EVENT:
305 continue_status =
306 HandleExitProcessEvent(dbe.u.ExitProcess, dbe.dwThreadId);
307 should_debug = false;
308 break;
309 case LOAD_DLL_DEBUG_EVENT:
310 continue_status = HandleLoadDllEvent(dbe.u.LoadDll, dbe.dwThreadId);
311 break;
312 case UNLOAD_DLL_DEBUG_EVENT:
313 continue_status = HandleUnloadDllEvent(dbe.u.UnloadDll, dbe.dwThreadId);
314 break;
315 case OUTPUT_DEBUG_STRING_EVENT:
316 continue_status = HandleODSEvent(dbe.u.DebugString, dbe.dwThreadId);
317 break;
318 case RIP_EVENT:
319 continue_status = HandleRipEvent(dbe.u.RipInfo, dbe.dwThreadId);
320 if (dbe.u.RipInfo.dwType == SLE_ERROR)
321 should_debug = false;
322 break;
323 }
324
326 log, "calling ContinueDebugEvent({0}, {1}, {2}) on thread {3}.",
327 dbe.dwProcessId, dbe.dwThreadId, continue_status,
328 ::GetCurrentThreadId());
329
330 ::ContinueDebugEvent(dbe.dwProcessId, dbe.dwThreadId, continue_status);
331
332 // We have to DebugActiveProcessStop after ContinueDebugEvent, otherwise
333 // the target process will crash
334 if (shutting_down) {
335 // A breakpoint that occurs while `m_pid_to_detach` is non-zero is a
336 // magic exception that we use simply to wake up the DebuggerThread so
337 // that we can close out the debug loop.
338 if (m_pid_to_detach != 0 &&
339 (dbe.u.Exception.ExceptionRecord.ExceptionCode ==
340 EXCEPTION_BREAKPOINT ||
341 dbe.u.Exception.ExceptionRecord.ExceptionCode ==
343 LLDB_LOG(log,
344 "Breakpoint exception is cue to detach from process {0:x}",
345 m_pid_to_detach.load());
346
347 // detaching with leaving breakpoint exception event on the queue may
348 // cause target process to crash so process events as possible since
349 // target threads are running at this time, there is possibility to
350 // have some breakpoint exception between last WaitForDebugEventEx and
351 // DebugActiveProcessStop but ignore for now.
352 while (g_wait_for_debug_event(&dbe, 0)) {
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,
363 continue_status);
364 }
365
366 ::DebugActiveProcessStop(m_pid_to_detach);
367 m_detached = true;
368 }
369 }
370
371 if (m_detached)
372 should_debug = false;
373 } else {
374 LLDB_LOG(log, "returned FALSE from WaitForDebugEventEx. Error = {0}",
375 ::GetLastError());
376
377 should_debug = false;
378 }
379 }
381
382 LLDB_LOG(log, "WaitForDebugEventEx loop completed, exiting.");
383 ::SetEvent(m_debugging_ended_event);
384}
385
387DebuggerThread::HandleExceptionEvent(const EXCEPTION_DEBUG_INFO &info,
388 DWORD thread_id, bool shutting_down) {
390 if (shutting_down) {
391 bool is_breakpoint =
392 (info.ExceptionRecord.ExceptionCode == EXCEPTION_BREAKPOINT ||
393 info.ExceptionRecord.ExceptionCode == STATUS_WX86_BREAKPOINT);
394
395 // Don't perform any blocking operations while we're shutting down. That
396 // will cause TerminateProcess -> WaitForSingleObject to time out.
397 // We should not send breakpoint exceptions to the application.
398 return is_breakpoint ? ExceptionResult::MaskException
400 }
401
402 bool first_chance = (info.dwFirstChance != 0);
403
404 m_active_exception.reset(
405 new ExceptionRecord(info.ExceptionRecord, thread_id));
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);
409
410 ExceptionResult result =
411 m_debug_delegate->OnDebugException(first_chance, *m_active_exception);
412 m_exception_pred.SetValue(result, eBroadcastNever);
413
414 LLDB_LOG(log, "waiting for ExceptionPred != BreakInDebugger");
415 result = *m_exception_pred.WaitForValueNotEqualTo(
417
418 LLDB_LOG(log, "got ExceptionPred = {0}", (int)m_exception_pred.GetValue());
419 return result;
420}
421
422DWORD
423DebuggerThread::HandleCreateThreadEvent(const CREATE_THREAD_DEBUG_INFO &info,
424 DWORD thread_id) {
426 LLDB_LOG(log, "Thread {0} spawned in process {1}", thread_id,
427 m_process.GetProcessId());
428 HostThread thread(info.hThread);
429 thread.GetNativeThread().SetOwnsHandle(false);
430 m_debug_delegate->OnCreateThread(thread);
431 return DBG_CONTINUE;
432}
433
434DWORD
435DebuggerThread::HandleCreateProcessEvent(const CREATE_PROCESS_DEBUG_INFO &info,
436 DWORD thread_id) {
438 uint32_t process_id = ::GetProcessId(info.hProcess);
439
440 LLDB_LOG(log, "process {0} spawned", process_id);
441
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);
446
447 // info.hProcess and info.hThread are closed automatically by Windows when
448 // EXIT_PROCESS_DEBUG_EVENT is received.
449 m_process = HostProcess(info.hProcess);
450 static_cast<HostProcessWindows &>(m_process.GetNativeProcess())
451 .SetOwnsHandle(false);
452 m_main_thread = HostThread(info.hThread);
453 m_main_thread.GetNativeThread().SetOwnsHandle(false);
454 m_image_file = info.hFile;
455
456 lldb::addr_t load_addr = reinterpret_cast<lldb::addr_t>(info.lpBaseOfImage);
457 m_debug_delegate->OnDebuggerConnected(load_addr);
458
459 return DBG_CONTINUE;
460}
461
462DWORD
463DebuggerThread::HandleExitThreadEvent(const EXIT_THREAD_DEBUG_INFO &info,
464 DWORD thread_id) {
466 LLDB_LOG(log, "Thread {0} exited with code {1} in process {2}", thread_id,
467 info.dwExitCode, m_process.GetProcessId());
468 m_debug_delegate->OnExitThread(thread_id, info.dwExitCode);
469 return DBG_CONTINUE;
470}
471
472DWORD
473DebuggerThread::HandleExitProcessEvent(const EXIT_PROCESS_DEBUG_INFO &info,
474 DWORD thread_id) {
476 LLDB_LOG(log, "process {0} exited with code {1}", m_process.GetProcessId(),
477 info.dwExitCode);
478
479 m_debug_delegate->OnExitProcess(info.dwExitCode);
480
481 return DBG_CONTINUE;
482}
483
484static std::optional<std::string>
485ConvertNtDevicePathToDosPath(llvm::ArrayRef<wchar_t> nt_path) {
487
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) {
491 LLDB_LOG(log,
492 "ConvertNtDevicePathToDosPath: FindFirstVolumeW failed, "
493 "error={0}",
494 ::GetLastError());
495 return std::nullopt;
496 }
497 llvm::scope_exit close_iter([&] { ::FindVolumeClose(vol_iter); });
498
499 do {
500 // FindFirstVolumeW yields "\\?\Volume{GUID}\".
501 // QueryDosDeviceW expects "Volume{GUID}".
502 size_t vol_len = ::wcsnlen(vol_name.data(), vol_name.size());
503 if (vol_len < 5 || vol_name[vol_len - 1] != L'\\')
504 continue;
505
506 vol_name[vol_len - 1] = L'\0'; // strip trailing '\' for QueryDosDeviceW
507 llvm::SmallVector<wchar_t, MAX_PATH> dev_name(MAX_PATH);
508 bool ok = ::QueryDosDeviceW(vol_name.data() + 4, // skip "\\?\"
509 dev_name.data(), dev_name.size());
510 vol_name[vol_len - 1] = L'\\'; // restore
511 if (!ok)
512 continue;
513
514 // Check that nt_path begins with this device name followed by '\'.
515 size_t dev_len = ::wcsnlen(dev_name.data(), dev_name.size());
516 if (dev_len == 0 || dev_len >= nt_path.size())
517 continue;
518 if (_wcsnicmp(nt_path.data(), dev_name.data(), dev_len) != 0)
519 continue;
520 if (nt_path[dev_len] != L'\\')
521 continue;
522
523 // Prefer a drive-letter/mount-point over the raw volume GUID path.
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,
528 &names_size);
529 if (names_size > 1) {
530 mount_names.resize(names_size);
531 DWORD written = 0;
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>(
536 mount_names.data(),
537 ::wcsnlen(mount_names.data(), mount_names.size()));
538 }
539 }
540
541 // Build the final path: mount point + rest of nt_path.
542 llvm::SmallVector<wchar_t> dos_wide(mount.begin(), mount.end());
543 if (!dos_wide.empty() && dos_wide.back() == L'\\')
544 dos_wide.pop_back();
545 dos_wide.append(nt_path.begin() + dev_len, nt_path.end());
546
547 std::string result;
548 llvm::convertWideToUTF8(std::wstring_view(dos_wide.data(), dos_wide.size()),
549 result);
550 return result;
551 } while (::FindNextVolumeW(vol_iter, vol_name.data(), vol_name.size()));
552
553 LLDB_LOG(log, "ConvertNtDevicePathToDosPath: no matching volume found");
554 return std::nullopt;
555}
556
557// Query the file name backing the mapping at `addr` in `process` and convert
558// the resulting NT device path to a DOS path.
559static std::optional<std::string> GetMappedFileDosPath(HANDLE process,
560 LPVOID addr) {
561 std::vector<wchar_t> mapped_filename(MAX_PATH + 1);
562 DWORD mapped_len = 0;
563 while (mapped_filename.size() <= PATHCCH_MAX_CCH) {
564 mapped_len = ::GetMappedFileNameW(process, addr, mapped_filename.data(),
565 mapped_filename.size());
566 if (mapped_len == 0)
567 return std::nullopt;
568 if (mapped_len < mapped_filename.size())
569 break;
570 mapped_filename.resize(mapped_filename.size() * 2);
571 }
573 llvm::ArrayRef<wchar_t>(mapped_filename.data(), mapped_len + 1));
574}
575
576static std::optional<std::string> GetFileNameFromHandleFallback(HANDLE hFile) {
577 // Check that file is not empty as we cannot map a file with zero length.
578 DWORD dwFileSizeHi = 0;
579 DWORD dwFileSizeLo = ::GetFileSize(hFile, &dwFileSizeHi);
580 if (dwFileSizeLo == 0 && dwFileSizeHi == 0)
581 return std::nullopt;
582
583 AutoHandle filemap(
584 ::CreateFileMappingW(hFile, nullptr, PAGE_READONLY, 0, 1, nullptr),
585 nullptr);
586 if (!filemap.IsValid())
587 return std::nullopt;
588
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);
592 if (!pMem)
593 return std::nullopt;
594
595 return GetMappedFileDosPath(::GetCurrentProcess(), pMem.get());
596}
597
598static std::optional<std::string> GetFileNameByLoadAddress(HANDLE process,
599 LPVOID base_addr) {
600 std::vector<wchar_t> module_filename(MAX_PATH + 1);
601 while (module_filename.size() <= PATHCCH_MAX_CCH) {
602 DWORD len =
603 ::GetModuleFileNameExW(process, reinterpret_cast<HMODULE>(base_addr),
604 module_filename.data(), module_filename.size());
605 if (len == 0)
606 break; // Not loaded as a module; fall back to the mapped-file query.
607 if (len < module_filename.size()) {
608 std::string path_utf8;
609 llvm::convertWideToUTF8(std::wstring_view(module_filename.data(), len),
610 path_utf8);
611 return path_utf8;
612 }
613 module_filename.resize(module_filename.size() * 2);
614 }
615
616 // Fallback: ask the kernel for the file backing the mapping at this address.
617 return GetMappedFileDosPath(process, base_addr);
618}
619
620// Determine how many bytes can be read at `addr` in `process` before crossing
621// out of the committed memory region containing it. Returns 0 if the address is
622// not within a committed region.
623static SIZE_T BytesReadableAt(HANDLE process, LPCVOID addr) {
624 MEMORY_BASIC_INFORMATION mbi{};
625 if (!::VirtualQueryEx(process, addr, &mbi, sizeof(mbi)))
626 return 0;
627 if (mbi.State != MEM_COMMIT)
628 return 0;
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;
634}
635
636static std::optional<std::string> ReadRemotePathStringW(HANDLE process,
637 LPCVOID addr) {
638 SIZE_T limit = std::min<SIZE_T>(PATHCCH_MAX_CCH * sizeof(wchar_t),
639 BytesReadableAt(process, addr));
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); // round down to a wchar_t boundary
644 if (to_read < sizeof(wchar_t))
645 return std::nullopt;
646
647 buf.resize(to_read / sizeof(wchar_t));
648 SIZE_T bytes_read = 0;
649 if (!::ReadProcessMemory(process, addr, buf.data(), to_read, &bytes_read))
650 return std::nullopt;
651
652 size_t max_chars = bytes_read / sizeof(wchar_t);
653 size_t len = ::wcsnlen(buf.data(), max_chars);
654 if (len < max_chars) { // found the null terminator
655 if (len == 0) // empty string
656 return std::nullopt;
657 std::string result;
658 llvm::convertWideToUTF8(std::wstring_view(buf.data(), len), result);
659 return result;
660 }
661 if (to_read >= limit) // read everything available without a terminator
662 return std::nullopt;
663 }
664}
665
666static std::optional<std::string> ReadRemotePathStringA(HANDLE process,
667 LPCVOID addr) {
668 SIZE_T limit =
669 std::min<SIZE_T>(PATHCCH_MAX_CCH, BytesReadableAt(process, addr));
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);
673 if (to_read == 0)
674 return std::nullopt;
675
676 buf.resize(to_read);
677 SIZE_T bytes_read = 0;
678 if (!::ReadProcessMemory(process, addr, buf.data(), to_read, &bytes_read))
679 return std::nullopt;
680
681 size_t len = ::strnlen(buf.data(), bytes_read);
682 if (len < bytes_read) { // found the null terminator
683 if (len == 0) // empty string
684 return std::nullopt;
685 return std::string(buf.data(), len);
686 }
687 if (to_read >= limit) // read everything available without a terminator
688 return std::nullopt;
689 }
690}
691
692// Resolve the LOAD_DLL_DEBUG_INFO::lpImageName field.
693static std::optional<std::string>
694GetFileNameFromImageNameField(HANDLE process, const LOAD_DLL_DEBUG_INFO &info) {
695 if (info.lpImageName == nullptr)
696 return std::nullopt;
697
698 LPVOID string_addr = nullptr;
699 SIZE_T bytes_read = 0;
700 if (!::ReadProcessMemory(process, info.lpImageName, &string_addr,
701 sizeof(string_addr), &bytes_read) ||
702 bytes_read != sizeof(string_addr))
703 return std::nullopt;
704
705 if (info.fUnicode)
706 return ReadRemotePathStringW(process, string_addr);
707 return ReadRemotePathStringA(process, string_addr);
708}
709
710DWORD
711DebuggerThread::HandleLoadDllEvent(const LOAD_DLL_DEBUG_INFO &info,
712 DWORD thread_id) {
714
716 auto on_load_dll = [&](llvm::StringRef path) {
717 FileSpec file_spec(path);
718 ModuleSpec module_spec(file_spec);
719 lldb::addr_t load_addr = reinterpret_cast<lldb::addr_t>(info.lpBaseOfDll);
720
721 LLDB_LOG(log, "Inferior {0} - DLL '{1}' loaded at address {2:x}...",
722 m_process.GetProcessId(), path, info.lpBaseOfDll);
723
724 m_dll_event_pred.SetValue(false, eBroadcastNever);
725 action = m_debug_delegate->OnLoadDll(module_spec, load_addr, thread_id);
726 };
727
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,
736 VOLUME_NAME_DOS);
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();
742 } else {
743 resolved_path = GetFileNameFromHandleFallback(info.hFile);
744 }
745 }
746
747 HANDLE process = m_process.GetNativeProcess().GetSystemHandle();
748 if (!resolved_path)
749 resolved_path = GetFileNameFromImageNameField(process, info);
750 if (!resolved_path)
751 resolved_path = GetFileNameByLoadAddress(process, info.lpBaseOfDll);
752
753 if (resolved_path)
754 on_load_dll(*resolved_path);
755 else
756 LLDB_LOG(log,
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,
760 ::GetLastError());
761
762 // Windows does not automatically close info.hFile, so we need to do it.
763 if (info.hFile != nullptr)
764 ::CloseHandle(info.hFile);
765
766 if (action == DllEventAction::ParkDebugLoop && !m_is_shutting_down.load())
767 m_dll_event_pred.WaitForValueEqualTo(true);
768 return DBG_CONTINUE;
769}
770
771DWORD
772DebuggerThread::HandleUnloadDllEvent(const UNLOAD_DLL_DEBUG_INFO &info,
773 DWORD thread_id) {
775 LLDB_LOG(log, "process {0} unloading DLL at addr {1:x}.",
776 m_process.GetProcessId(), info.lpBaseOfDll);
777
778 m_dll_event_pred.SetValue(false, eBroadcastNever);
779 DllEventAction action = m_debug_delegate->OnUnloadDll(
780 reinterpret_cast<lldb::addr_t>(info.lpBaseOfDll), thread_id);
781 if (action == DllEventAction::ParkDebugLoop && !m_is_shutting_down.load())
782 m_dll_event_pred.WaitForValueEqualTo(true);
783 return DBG_CONTINUE;
784}
785
786DWORD
787DebuggerThread::HandleODSEvent(const OUTPUT_DEBUG_STRING_INFO &info,
788 DWORD thread_id) {
789 m_debug_delegate->OnDebugString(
790 static_cast<lldb::addr_t>(
791 reinterpret_cast<uintptr_t>(info.lpDebugStringData)),
792 info.fUnicode == TRUE, info.nDebugStringLength);
793 return DBG_CONTINUE;
794}
795
796DWORD
797DebuggerThread::HandleRipEvent(const RIP_INFO &info, DWORD thread_id) {
799 LLDB_LOG(log, "encountered error {0} (type={1}) in process {2} thread {3}",
800 info.dwError, info.dwType, m_process.GetProcessId(), thread_id);
801
802 Status error(info.dwError, eErrorTypeWin32);
803 m_debug_delegate->OnDebuggerError(error, info.dwType);
804
805 return DBG_CONTINUE;
806}
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)
DllEventAction
Definition ForwardDecl.h:29
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.
Definition Log.h:376
#define LLDB_LOG_VERBOSE(log,...)
Definition Log.h:383
#define PATHCCH_MAX_CCH
#define MAX_PATH
void * HANDLE
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)
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
Status DebugLaunch(const ProcessLaunchInfo &launch_info)
DWORD HandleUnloadDllEvent(const UNLOAD_DLL_DEBUG_INFO &info, DWORD thread_id)
DWORD HandleCreateThreadEvent(const CREATE_THREAD_DEBUG_INFO &info, DWORD thread_id)
A file utility class.
Definition FileSpec.h:57
size_t GetPath(char *path, size_t max_path_length, bool denormalize=true) const
Extract the full path to the file.
Definition FileSpec.cpp:376
lldb::pid_t GetProcessId() const
FileSpec & GetExecutableFile()
Definition ProcessInfo.h:41
HostProcess LaunchProcess(const ProcessLaunchInfo &launch_info, Status &error) override
An error handling class.
Definition Status.h:118
static Status FromError(llvm::Error error)
Avoid using this in new code. Migrate APIs to llvm::Expected instead.
Definition Status.cpp:136
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
Definition lldb-types.h:68
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.
Definition Log.h:339
std::shared_ptr< IDebugDelegate > DebugDelegateSP
Definition ForwardDecl.h:45
@ eBroadcastNever
No broadcast will be sent when the value is modified.
Definition Predicate.h:28
@ eBroadcastAlways
Always send a broadcast when the value is modified.
Definition Predicate.h:29
void * thread_result_t
Definition lldb-types.h:62
@ eErrorTypeWin32
Standard Win32 error codes.
uint64_t pid_t
Definition lldb-types.h:83
uint64_t addr_t
Definition lldb-types.h:80
uint64_t process_t
Definition lldb-types.h:57