[Go to site: main page, start]

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 (GetActiveException()) {
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 std::lock_guard<std::mutex> guard(m_active_exception_mutex);
244 return m_active_exception;
245}
246
248 {
249 std::lock_guard<std::mutex> guard(m_active_exception_mutex);
251 return;
252 m_active_exception.reset();
253 }
254
256 LLDB_LOG(log, "broadcasting for inferior process {0}.",
257 m_process.GetProcessId());
258
259 m_exception_pred.SetValue(result, eBroadcastAlways);
260}
261
265
269 if (m_image_file) {
270 ::CloseHandle(m_image_file);
271 m_image_file = nullptr;
272 }
273}
274
277 DEBUG_EVENT dbe = {};
278 bool should_debug = true;
279 LLDB_LOG_VERBOSE(log, "Entering WaitForDebugEventEx loop");
280 while (should_debug) {
281 LLDB_LOG_VERBOSE(log, "Calling WaitForDebugEvent");
282 BOOL wait_result = g_wait_for_debug_event(&dbe, INFINITE);
283 if (wait_result) {
284 DWORD continue_status = DBG_CONTINUE;
285 bool shutting_down = m_is_shutting_down;
286 switch (dbe.dwDebugEventCode) {
287 default:
288 llvm_unreachable("Unhandled debug event code!");
289 case EXCEPTION_DEBUG_EVENT: {
291 dbe.u.Exception, dbe.dwThreadId, shutting_down);
292
293 if (status == ExceptionResult::MaskException)
294 continue_status = DBG_CONTINUE;
295 else if (status == ExceptionResult::SendToApplication)
296 continue_status = DBG_EXCEPTION_NOT_HANDLED;
297
298 break;
299 }
300 case CREATE_THREAD_DEBUG_EVENT:
301 continue_status =
302 HandleCreateThreadEvent(dbe.u.CreateThread, dbe.dwThreadId);
303 break;
304 case CREATE_PROCESS_DEBUG_EVENT:
305 continue_status =
306 HandleCreateProcessEvent(dbe.u.CreateProcessInfo, dbe.dwThreadId);
307 break;
308 case EXIT_THREAD_DEBUG_EVENT:
309 continue_status =
310 HandleExitThreadEvent(dbe.u.ExitThread, dbe.dwThreadId);
311 break;
312 case EXIT_PROCESS_DEBUG_EVENT:
313 continue_status =
314 HandleExitProcessEvent(dbe.u.ExitProcess, dbe.dwThreadId);
315 should_debug = false;
316 break;
317 case LOAD_DLL_DEBUG_EVENT:
318 continue_status = HandleLoadDllEvent(dbe.u.LoadDll, dbe.dwThreadId);
319 break;
320 case UNLOAD_DLL_DEBUG_EVENT:
321 continue_status = HandleUnloadDllEvent(dbe.u.UnloadDll, dbe.dwThreadId);
322 break;
323 case OUTPUT_DEBUG_STRING_EVENT:
324 continue_status = HandleODSEvent(dbe.u.DebugString, dbe.dwThreadId);
325 break;
326 case RIP_EVENT:
327 continue_status = HandleRipEvent(dbe.u.RipInfo, dbe.dwThreadId);
328 if (dbe.u.RipInfo.dwType == SLE_ERROR)
329 should_debug = false;
330 break;
331 }
332
334 log, "calling ContinueDebugEvent({0}, {1}, {2}) on thread {3}.",
335 dbe.dwProcessId, dbe.dwThreadId, continue_status,
336 ::GetCurrentThreadId());
337
338 ::ContinueDebugEvent(dbe.dwProcessId, dbe.dwThreadId, continue_status);
339
340 // We have to DebugActiveProcessStop after ContinueDebugEvent, otherwise
341 // the target process will crash
342 if (shutting_down) {
343 // A breakpoint that occurs while `m_pid_to_detach` is non-zero is a
344 // magic exception that we use simply to wake up the DebuggerThread so
345 // that we can close out the debug loop.
346 if (m_pid_to_detach != 0 &&
347 (dbe.u.Exception.ExceptionRecord.ExceptionCode ==
348 EXCEPTION_BREAKPOINT ||
349 dbe.u.Exception.ExceptionRecord.ExceptionCode ==
351 LLDB_LOG(log,
352 "Breakpoint exception is cue to detach from process {0:x}",
353 m_pid_to_detach.load());
354
355 // detaching with leaving breakpoint exception event on the queue may
356 // cause target process to crash so process events as possible since
357 // target threads are running at this time, there is possibility to
358 // have some breakpoint exception between last WaitForDebugEventEx and
359 // DebugActiveProcessStop but ignore for now.
360 while (g_wait_for_debug_event(&dbe, 0)) {
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,
371 continue_status);
372 }
373
374 ::DebugActiveProcessStop(m_pid_to_detach);
375 m_detached = true;
376 }
377 }
378
379 if (m_detached)
380 should_debug = false;
381 } else {
382 LLDB_LOG(log, "returned FALSE from WaitForDebugEventEx. Error = {0}",
383 ::GetLastError());
384
385 should_debug = false;
386 }
387 }
389
390 LLDB_LOG(log, "WaitForDebugEventEx loop completed, exiting.");
391 ::SetEvent(m_debugging_ended_event);
392}
393
395DebuggerThread::HandleExceptionEvent(const EXCEPTION_DEBUG_INFO &info,
396 DWORD thread_id, bool shutting_down) {
398 if (shutting_down) {
399 bool is_breakpoint =
400 (info.ExceptionRecord.ExceptionCode == EXCEPTION_BREAKPOINT ||
401 info.ExceptionRecord.ExceptionCode == STATUS_WX86_BREAKPOINT);
402
403 // Don't perform any blocking operations while we're shutting down. That
404 // will cause TerminateProcess -> WaitForSingleObject to time out.
405 // We should not send breakpoint exceptions to the application.
406 return is_breakpoint ? ExceptionResult::MaskException
408 }
409
410 bool first_chance = (info.dwFirstChance != 0);
411
412 ExceptionRecordSP active_exception =
413 std::make_shared<ExceptionRecord>(info.ExceptionRecord, thread_id);
414 {
415 std::lock_guard<std::mutex> guard(m_active_exception_mutex);
416 m_active_exception = active_exception;
417 }
418 // Set this before calling the delegate. The delegate can wake up the thread
419 // driving the debugger, and that thread can call ContinueAsyncException
420 // before OnDebugException returns.
422
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);
426
427 ExceptionResult result =
428 m_debug_delegate->OnDebugException(first_chance, *active_exception);
429 // The delegate only says what to do, it never continues the exception. If the
430 // result is not BreakInDebugger, continue it here, or the wait below never
431 // ends. If the other thread already continued it, this does nothing and its
432 // result is what the wait below returns.
435
436 LLDB_LOG(log, "waiting for ExceptionPred != BreakInDebugger");
437 result = *m_exception_pred.WaitForValueNotEqualTo(
439
440 LLDB_LOG(log, "got ExceptionPred = {0}", (int)m_exception_pred.GetValue());
441 return result;
442}
443
444DWORD
445DebuggerThread::HandleCreateThreadEvent(const CREATE_THREAD_DEBUG_INFO &info,
446 DWORD thread_id) {
448 LLDB_LOG(log, "Thread {0} spawned in process {1}", thread_id,
449 m_process.GetProcessId());
450 HostThread thread(info.hThread);
451 thread.GetNativeThread().SetOwnsHandle(false);
452 m_debug_delegate->OnCreateThread(thread);
453 return DBG_CONTINUE;
454}
455
456DWORD
457DebuggerThread::HandleCreateProcessEvent(const CREATE_PROCESS_DEBUG_INFO &info,
458 DWORD thread_id) {
460 uint32_t process_id = ::GetProcessId(info.hProcess);
461
462 LLDB_LOG(log, "process {0} spawned", process_id);
463
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);
468
469 // info.hProcess and info.hThread are closed automatically by Windows when
470 // EXIT_PROCESS_DEBUG_EVENT is received.
471 m_process = HostProcess(info.hProcess);
472 static_cast<HostProcessWindows &>(m_process.GetNativeProcess())
473 .SetOwnsHandle(false);
474 m_main_thread = HostThread(info.hThread);
475 m_main_thread.GetNativeThread().SetOwnsHandle(false);
476 m_image_file = info.hFile;
477
478 lldb::addr_t load_addr = reinterpret_cast<lldb::addr_t>(info.lpBaseOfImage);
479 m_debug_delegate->OnDebuggerConnected(load_addr);
480
481 return DBG_CONTINUE;
482}
483
484DWORD
485DebuggerThread::HandleExitThreadEvent(const EXIT_THREAD_DEBUG_INFO &info,
486 DWORD thread_id) {
488 LLDB_LOG(log, "Thread {0} exited with code {1} in process {2}", thread_id,
489 info.dwExitCode, m_process.GetProcessId());
490 m_debug_delegate->OnExitThread(thread_id, info.dwExitCode);
491 return DBG_CONTINUE;
492}
493
494DWORD
495DebuggerThread::HandleExitProcessEvent(const EXIT_PROCESS_DEBUG_INFO &info,
496 DWORD thread_id) {
498 LLDB_LOG(log, "process {0} exited with code {1}", m_process.GetProcessId(),
499 info.dwExitCode);
500
501 m_debug_delegate->OnExitProcess(info.dwExitCode);
502
503 return DBG_CONTINUE;
504}
505
506static std::optional<std::string>
507ConvertNtDevicePathToDosPath(llvm::ArrayRef<wchar_t> nt_path) {
509
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) {
513 LLDB_LOG(log,
514 "ConvertNtDevicePathToDosPath: FindFirstVolumeW failed, "
515 "error={0}",
516 ::GetLastError());
517 return std::nullopt;
518 }
519 llvm::scope_exit close_iter([&] { ::FindVolumeClose(vol_iter); });
520
521 do {
522 // FindFirstVolumeW yields "\\?\Volume{GUID}\".
523 // QueryDosDeviceW expects "Volume{GUID}".
524 size_t vol_len = ::wcsnlen(vol_name.data(), vol_name.size());
525 if (vol_len < 5 || vol_name[vol_len - 1] != L'\\')
526 continue;
527
528 vol_name[vol_len - 1] = L'\0'; // strip trailing '\' for QueryDosDeviceW
529 llvm::SmallVector<wchar_t, MAX_PATH> dev_name(MAX_PATH);
530 bool ok = ::QueryDosDeviceW(vol_name.data() + 4, // skip "\\?\"
531 dev_name.data(), dev_name.size());
532 vol_name[vol_len - 1] = L'\\'; // restore
533 if (!ok)
534 continue;
535
536 // Check that nt_path begins with this device name followed by '\'.
537 size_t dev_len = ::wcsnlen(dev_name.data(), dev_name.size());
538 if (dev_len == 0 || dev_len >= nt_path.size())
539 continue;
540 if (_wcsnicmp(nt_path.data(), dev_name.data(), dev_len) != 0)
541 continue;
542 if (nt_path[dev_len] != L'\\')
543 continue;
544
545 // Prefer a drive-letter/mount-point over the raw volume GUID path.
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,
550 &names_size);
551 if (names_size > 1) {
552 mount_names.resize(names_size);
553 DWORD written = 0;
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>(
558 mount_names.data(),
559 ::wcsnlen(mount_names.data(), mount_names.size()));
560 }
561 }
562
563 // Build the final path: mount point + rest of nt_path.
564 llvm::SmallVector<wchar_t> dos_wide(mount.begin(), mount.end());
565 if (!dos_wide.empty() && dos_wide.back() == L'\\')
566 dos_wide.pop_back();
567 dos_wide.append(nt_path.begin() + dev_len, nt_path.end());
568
569 std::string result;
570 llvm::convertWideToUTF8(std::wstring_view(dos_wide.data(), dos_wide.size()),
571 result);
572 return result;
573 } while (::FindNextVolumeW(vol_iter, vol_name.data(), vol_name.size()));
574
575 LLDB_LOG(log, "ConvertNtDevicePathToDosPath: no matching volume found");
576 return std::nullopt;
577}
578
579// Query the file name backing the mapping at `addr` in `process` and convert
580// the resulting NT device path to a DOS path.
581static std::optional<std::string> GetMappedFileDosPath(HANDLE process,
582 LPVOID addr) {
583 std::vector<wchar_t> mapped_filename(MAX_PATH + 1);
584 DWORD mapped_len = 0;
585 while (mapped_filename.size() <= PATHCCH_MAX_CCH) {
586 mapped_len = ::GetMappedFileNameW(process, addr, mapped_filename.data(),
587 mapped_filename.size());
588 if (mapped_len == 0)
589 return std::nullopt;
590 if (mapped_len < mapped_filename.size())
591 break;
592 mapped_filename.resize(mapped_filename.size() * 2);
593 }
595 llvm::ArrayRef<wchar_t>(mapped_filename.data(), mapped_len + 1));
596}
597
598static std::optional<std::string> GetFileNameFromHandleFallback(HANDLE hFile) {
599 // Check that file is not empty as we cannot map a file with zero length.
600 DWORD dwFileSizeHi = 0;
601 DWORD dwFileSizeLo = ::GetFileSize(hFile, &dwFileSizeHi);
602 if (dwFileSizeLo == 0 && dwFileSizeHi == 0)
603 return std::nullopt;
604
605 AutoHandle filemap(
606 ::CreateFileMappingW(hFile, nullptr, PAGE_READONLY, 0, 1, nullptr),
607 nullptr);
608 if (!filemap.IsValid())
609 return std::nullopt;
610
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);
614 if (!pMem)
615 return std::nullopt;
616
617 return GetMappedFileDosPath(::GetCurrentProcess(), pMem.get());
618}
619
620static std::optional<std::string> GetFileNameByLoadAddress(HANDLE process,
621 LPVOID base_addr) {
622 std::vector<wchar_t> module_filename(MAX_PATH + 1);
623 while (module_filename.size() <= PATHCCH_MAX_CCH) {
624 DWORD len =
625 ::GetModuleFileNameExW(process, reinterpret_cast<HMODULE>(base_addr),
626 module_filename.data(), module_filename.size());
627 if (len == 0)
628 break; // Not loaded as a module; fall back to the mapped-file query.
629 if (len < module_filename.size()) {
630 std::string path_utf8;
631 llvm::convertWideToUTF8(std::wstring_view(module_filename.data(), len),
632 path_utf8);
633 return path_utf8;
634 }
635 module_filename.resize(module_filename.size() * 2);
636 }
637
638 // Fallback: ask the kernel for the file backing the mapping at this address.
639 return GetMappedFileDosPath(process, base_addr);
640}
641
642// Determine how many bytes can be read at `addr` in `process` before crossing
643// out of the committed memory region containing it. Returns 0 if the address is
644// not within a committed region.
645static SIZE_T BytesReadableAt(HANDLE process, LPCVOID addr) {
646 MEMORY_BASIC_INFORMATION mbi{};
647 if (!::VirtualQueryEx(process, addr, &mbi, sizeof(mbi)))
648 return 0;
649 if (mbi.State != MEM_COMMIT)
650 return 0;
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;
656}
657
658static std::optional<std::string> ReadRemotePathStringW(HANDLE process,
659 LPCVOID addr) {
660 SIZE_T limit = std::min<SIZE_T>(PATHCCH_MAX_CCH * sizeof(wchar_t),
661 BytesReadableAt(process, addr));
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); // round down to a wchar_t boundary
666 if (to_read < sizeof(wchar_t))
667 return std::nullopt;
668
669 buf.resize(to_read / sizeof(wchar_t));
670 SIZE_T bytes_read = 0;
671 if (!::ReadProcessMemory(process, addr, buf.data(), to_read, &bytes_read))
672 return std::nullopt;
673
674 size_t max_chars = bytes_read / sizeof(wchar_t);
675 size_t len = ::wcsnlen(buf.data(), max_chars);
676 if (len < max_chars) { // found the null terminator
677 if (len == 0) // empty string
678 return std::nullopt;
679 std::string result;
680 llvm::convertWideToUTF8(std::wstring_view(buf.data(), len), result);
681 return result;
682 }
683 if (to_read >= limit) // read everything available without a terminator
684 return std::nullopt;
685 }
686}
687
688static std::optional<std::string> ReadRemotePathStringA(HANDLE process,
689 LPCVOID addr) {
690 SIZE_T limit =
691 std::min<SIZE_T>(PATHCCH_MAX_CCH, BytesReadableAt(process, addr));
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);
695 if (to_read == 0)
696 return std::nullopt;
697
698 buf.resize(to_read);
699 SIZE_T bytes_read = 0;
700 if (!::ReadProcessMemory(process, addr, buf.data(), to_read, &bytes_read))
701 return std::nullopt;
702
703 size_t len = ::strnlen(buf.data(), bytes_read);
704 if (len < bytes_read) { // found the null terminator
705 if (len == 0) // empty string
706 return std::nullopt;
707 return std::string(buf.data(), len);
708 }
709 if (to_read >= limit) // read everything available without a terminator
710 return std::nullopt;
711 }
712}
713
714// Resolve the LOAD_DLL_DEBUG_INFO::lpImageName field.
715static std::optional<std::string>
716GetFileNameFromImageNameField(HANDLE process, const LOAD_DLL_DEBUG_INFO &info) {
717 if (info.lpImageName == nullptr)
718 return std::nullopt;
719
720 LPVOID string_addr = nullptr;
721 SIZE_T bytes_read = 0;
722 if (!::ReadProcessMemory(process, info.lpImageName, &string_addr,
723 sizeof(string_addr), &bytes_read) ||
724 bytes_read != sizeof(string_addr))
725 return std::nullopt;
726
727 if (info.fUnicode)
728 return ReadRemotePathStringW(process, string_addr);
729 return ReadRemotePathStringA(process, string_addr);
730}
731
732DWORD
733DebuggerThread::HandleLoadDllEvent(const LOAD_DLL_DEBUG_INFO &info,
734 DWORD thread_id) {
736
738 auto on_load_dll = [&](llvm::StringRef path) {
739 FileSpec file_spec(path);
740 ModuleSpec module_spec(file_spec);
741 lldb::addr_t load_addr = reinterpret_cast<lldb::addr_t>(info.lpBaseOfDll);
742
743 LLDB_LOG(log, "Inferior {0} - DLL '{1}' loaded at address {2:x}...",
744 m_process.GetProcessId(), path, info.lpBaseOfDll);
745
746 m_dll_event_pred.SetValue(false, eBroadcastNever);
747 action = m_debug_delegate->OnLoadDll(module_spec, load_addr, thread_id);
748 };
749
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,
758 VOLUME_NAME_DOS);
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();
764 } else {
765 resolved_path = GetFileNameFromHandleFallback(info.hFile);
766 }
767 }
768
769 HANDLE process = m_process.GetNativeProcess().GetSystemHandle();
770 if (!resolved_path)
771 resolved_path = GetFileNameFromImageNameField(process, info);
772 if (!resolved_path)
773 resolved_path = GetFileNameByLoadAddress(process, info.lpBaseOfDll);
774
775 if (resolved_path)
776 on_load_dll(*resolved_path);
777 else
778 LLDB_LOG(log,
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,
782 ::GetLastError());
783
784 // Windows does not automatically close info.hFile, so we need to do it.
785 if (info.hFile != nullptr)
786 ::CloseHandle(info.hFile);
787
788 if (action == DllEventAction::ParkDebugLoop && !m_is_shutting_down.load())
789 m_dll_event_pred.WaitForValueEqualTo(true);
790 return DBG_CONTINUE;
791}
792
793DWORD
794DebuggerThread::HandleUnloadDllEvent(const UNLOAD_DLL_DEBUG_INFO &info,
795 DWORD thread_id) {
797 LLDB_LOG(log, "process {0} unloading DLL at addr {1:x}.",
798 m_process.GetProcessId(), info.lpBaseOfDll);
799
800 m_dll_event_pred.SetValue(false, eBroadcastNever);
801 DllEventAction action = m_debug_delegate->OnUnloadDll(
802 reinterpret_cast<lldb::addr_t>(info.lpBaseOfDll), thread_id);
803 if (action == DllEventAction::ParkDebugLoop && !m_is_shutting_down.load())
804 m_dll_event_pred.WaitForValueEqualTo(true);
805 return DBG_CONTINUE;
806}
807
808DWORD
809DebuggerThread::HandleODSEvent(const OUTPUT_DEBUG_STRING_INFO &info,
810 DWORD thread_id) {
811 m_debug_delegate->OnDebugString(
812 static_cast<lldb::addr_t>(
813 reinterpret_cast<uintptr_t>(info.lpDebugStringData)),
814 info.fUnicode == TRUE, info.nDebugStringLength);
815 return DBG_CONTINUE;
816}
817
818DWORD
819DebuggerThread::HandleRipEvent(const RIP_INFO &info, DWORD thread_id) {
821 LLDB_LOG(log, "encountered error {0} (type={1}) in process {2} thread {3}",
822 info.dwError, info.dwType, m_process.GetProcessId(), thread_id);
823
824 Status error(info.dwError, eErrorTypeWin32);
825 m_debug_delegate->OnDebuggerError(error, info.dwType);
826
827 return DBG_CONTINUE;
828}
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:375
#define LLDB_LOG_VERBOSE(log,...)
Definition Log.h:382
#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)
ExceptionRecordSP GetActiveException()
Returns the exception the debug loop is currently reporting, or null if there is none.
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:56
size_t GetPath(char *path, size_t max_path_length, bool denormalize=true) const
Extract the full path to the file.
Definition FileSpec.cpp:380
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:338
std::shared_ptr< IDebugDelegate > DebugDelegateSP
Definition ForwardDecl.h:45
std::shared_ptr< ExceptionRecord > ExceptionRecordSP
Definition ForwardDecl.h:47
@ 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:84
uint64_t addr_t
Definition lldb-types.h:80
uint64_t process_t
Definition lldb-types.h:57