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
22#include "lldb/Target/Process.h"
24#include "lldb/Utility/Log.h"
26#include "lldb/Utility/Status.h"
27
29
31#include "llvm/ADT/STLExtras.h"
32#include "llvm/Support/ConvertUTF.h"
33#include "llvm/Support/Path.h"
34#include "llvm/Support/Threading.h"
35#include "llvm/Support/raw_ostream.h"
36
37#include <optional>
38#include <pathcch.h>
39#include <psapi.h>
40#include <winternl.h>
41
42#ifndef STATUS_WX86_BREAKPOINT
43#define STATUS_WX86_BREAKPOINT 0x4000001FL // For WOW64
44#endif
45
46using namespace lldb;
47using namespace lldb_private;
48
49typedef BOOL WINAPI WaitForDebugEventFn(LPDEBUG_EVENT, DWORD);
51
52/// WaitForDebugEventEx is only available on Windows 10+. This lazily checks if
53/// the function is available and falls back to WaitForDebugEvent if
54/// unavailable. The -Ex version ensures correct forwarding of
55/// OutputDebugStringW events.
57 static LazyImport<WaitForDebugEventFn *> s_wait_for_debug_event_ex = {
58 L"kernel32.dll", "WaitForDebugEventEx"};
59
61 return;
62
63 if (!s_wait_for_debug_event_ex) {
66 "WaitForDebugEventEx unavailable, using WaitForDebugEvent instead. "
67 "Unicode strings from OutputDebugStringW might show incorrectly.");
68 g_wait_for_debug_event = &WaitForDebugEvent;
69 } else {
70 g_wait_for_debug_event = *s_wait_for_debug_event_ex;
71 }
72}
73
75 : m_debug_delegate(debug_delegate), m_pid_to_detach(0),
76 m_is_shutting_down(false) {
78 m_debugging_ended_event = ::CreateEvent(nullptr, TRUE, FALSE, nullptr);
79}
80
82
85 LLDB_LOG(log, "launching '{0}'", launch_info.GetExecutableFile().GetPath());
86
87 Status result;
88 llvm::Expected<HostThread> secondary_thread = ThreadLauncher::LaunchThread(
89 "lldb.plugin.process-windows.secondary[?]",
90 [this, launch_info] { return DebuggerThreadLaunchRoutine(launch_info); });
91 if (!secondary_thread) {
92 result = Status::FromError(secondary_thread.takeError());
93 LLDB_LOG(log, "couldn't launch debugger thread. {0}", result);
94 }
95
96 return result;
97}
98
100 const ProcessAttachInfo &attach_info) {
102 LLDB_LOG(log, "attaching to '{0}'", pid);
103
104 Status result;
105 llvm::Expected<HostThread> secondary_thread = ThreadLauncher::LaunchThread(
106 "lldb.plugin.process-windows.secondary[?]", [this, pid, attach_info] {
107 return DebuggerThreadAttachRoutine(pid, attach_info);
108 });
109 if (!secondary_thread) {
110 result = Status::FromError(secondary_thread.takeError());
111 LLDB_LOG(log, "couldn't attach to process '{0}'. {1}", pid, result);
112 }
113
114 return result;
115}
116
118 const ProcessLaunchInfo &launch_info) {
119 // Grab a shared_ptr reference to this so that we know it won't get deleted
120 // until after the thread routine has exited.
121 std::shared_ptr<DebuggerThread> this_ref(shared_from_this());
122
124 LLDB_LOG(log, "preparing to launch '{0}' on background thread.",
125 launch_info.GetExecutableFile().GetPath());
126
128 ProcessLauncherWindows launcher;
129 HostProcess process(launcher.LaunchProcess(launch_info, error));
130 // If we couldn't create the process, notify waiters immediately. Otherwise
131 // enter the debug loop and wait until we get the create process debug
132 // notification. Note that if the process was created successfully, we can
133 // throw away the process handle we got from CreateProcess because Windows
134 // will give us another (potentially more useful?) handle when it sends us
135 // the CREATE_PROCESS_DEBUG_EVENT.
136 if (error.Success())
137 DebugLoop();
138 else
139 m_debug_delegate->OnDebuggerError(error, 0);
140
141 return {};
142}
143
145 lldb::pid_t pid, const ProcessAttachInfo &attach_info) {
146 // Grab a shared_ptr reference to this so that we know it won't get deleted
147 // until after the thread routine has exited.
148 std::shared_ptr<DebuggerThread> this_ref(shared_from_this());
149
151 LLDB_LOG(log, "preparing to attach to process '{0}' on background thread.",
152 pid);
153
154 if (!DebugActiveProcess(static_cast<DWORD>(pid))) {
155 Status error(::GetLastError(), eErrorTypeWin32);
156 m_debug_delegate->OnDebuggerError(error, 0);
157 return {};
158 }
159
160 // The attach was successful, enter the debug loop. From here on out, this
161 // is no different than a create process operation, so all the same comments
162 // in DebugLaunch should apply from this point out.
163 DebugLoop();
164
165 return {};
166}
167
170
171 lldb::pid_t pid = m_process.GetProcessId();
172
174 LLDB_LOG(log, "terminate = {0}, inferior={1}.", terminate, pid);
175
176 // Set m_is_shutting_down to true if it was false. Return if it was already
177 // true.
178 bool expected = false;
179 if (!m_is_shutting_down.compare_exchange_strong(expected, true))
180 return error;
181
182 // Make a copy of the process, since the termination sequence will reset
183 // DebuggerThread's internal copy and it needs to remain open for the Wait
184 // operation.
185 HostProcess process_copy = m_process;
186 lldb::process_t handle = m_process.GetNativeProcess().GetSystemHandle();
187
188 if (terminate) {
189 if (handle != nullptr && handle != LLDB_INVALID_PROCESS) {
190 // Initiate the termination before continuing the exception, so that the
191 // next debug event we get is the exit process event, and not some other
192 // event.
193 BOOL terminate_succeeded = TerminateProcess(handle, 0);
194 LLDB_LOG(log,
195 "calling TerminateProcess({0}, 0) (inferior={1}), success={2}",
196 handle, pid, terminate_succeeded);
197 } else {
198 LLDB_LOG(log,
199 "NOT calling TerminateProcess because the inferior is not valid "
200 "({0}, 0) (inferior={1})",
201 handle, pid);
202 }
203 }
204
205 // If we're stuck waiting for an exception to continue (e.g. the user is at a
206 // breakpoint messing around in the debugger), continue it now. But only
207 // AFTER calling TerminateProcess to make sure that the very next call to
208 // WaitForDebugEventEx is an exit process event.
209 if (GetActiveException()) {
210 LLDB_LOG(log, "masking active exception");
212 }
213
215
216 if (!terminate) {
217 // Indicate that we want to detach.
219
220 // Force a fresh break so that the detach can happen from the debugger
221 // thread.
222 if (!::DebugBreakProcess(
223 GetProcess().GetNativeProcess().GetSystemHandle())) {
224 error = Status(::GetLastError(), eErrorTypeWin32);
225 }
226 }
227
228 LLDB_LOG(log, "waiting for detach from process {0} to complete.", pid);
229
230 DWORD wait_result = WaitForSingleObject(m_debugging_ended_event, 5000);
231 if (wait_result != WAIT_OBJECT_0) {
232 error = Status(GetLastError(), eErrorTypeWin32);
233 LLDB_LOG(log, "error: WaitForSingleObject({0}, 5000) returned {1}",
234 m_debugging_ended_event, wait_result);
235 } else
236 LLDB_LOG(log, "detach from process {0} completed successfully.", pid);
237
238 if (!error.Success()) {
239 LLDB_LOG(log, "encountered an error while trying to stop process {0}. {1}",
240 pid, error);
241 }
242 return error;
243}
244
246 std::lock_guard<std::mutex> guard(m_active_exception_mutex);
247 return m_active_exception;
248}
249
251 {
252 std::lock_guard<std::mutex> guard(m_active_exception_mutex);
254 return;
255 m_active_exception.reset();
256 }
257
259 LLDB_LOG(log, "broadcasting for inferior process {0}.",
260 m_process.GetProcessId());
261
262 m_exception_pred.SetValue(result, eBroadcastAlways);
263}
264
268
272 if (m_image_file) {
273 ::CloseHandle(m_image_file);
274 m_image_file = nullptr;
275 }
276}
277
280 DEBUG_EVENT dbe = {};
281 bool should_debug = true;
282 LLDB_LOG_VERBOSE(log, "Entering WaitForDebugEventEx loop");
283 while (should_debug) {
284 LLDB_LOG_VERBOSE(log, "Calling WaitForDebugEvent");
285 BOOL wait_result = g_wait_for_debug_event(&dbe, INFINITE);
286 if (wait_result) {
287 DWORD continue_status = DBG_CONTINUE;
288 bool shutting_down = m_is_shutting_down;
289 HANDLE exited_process = nullptr;
290 switch (dbe.dwDebugEventCode) {
291 default:
292 llvm_unreachable("Unhandled debug event code!");
293 case EXCEPTION_DEBUG_EVENT: {
295 dbe.u.Exception, dbe.dwThreadId, shutting_down);
296
297 if (status == ExceptionResult::MaskException)
298 continue_status = DBG_CONTINUE;
299 else if (status == ExceptionResult::SendToApplication)
300 continue_status = DBG_EXCEPTION_NOT_HANDLED;
301
302 break;
303 }
304 case CREATE_THREAD_DEBUG_EVENT:
305 continue_status =
306 HandleCreateThreadEvent(dbe.u.CreateThread, dbe.dwThreadId);
307 break;
308 case CREATE_PROCESS_DEBUG_EVENT:
309 continue_status =
310 HandleCreateProcessEvent(dbe.u.CreateProcessInfo, dbe.dwThreadId);
311 break;
312 case EXIT_THREAD_DEBUG_EVENT:
313 continue_status =
314 HandleExitThreadEvent(dbe.u.ExitThread, dbe.dwThreadId);
315 break;
316 case EXIT_PROCESS_DEBUG_EVENT:
317 if (!::DuplicateHandle(::GetCurrentProcess(),
318 m_process.GetNativeProcess().GetSystemHandle(),
319 ::GetCurrentProcess(), &exited_process,
320 SYNCHRONIZE, FALSE, 0))
321 exited_process = nullptr;
322 should_debug = false;
323 break;
324 case LOAD_DLL_DEBUG_EVENT:
325 continue_status = HandleLoadDllEvent(dbe.u.LoadDll, dbe.dwThreadId);
326 break;
327 case UNLOAD_DLL_DEBUG_EVENT:
328 continue_status = HandleUnloadDllEvent(dbe.u.UnloadDll, dbe.dwThreadId);
329 break;
330 case OUTPUT_DEBUG_STRING_EVENT:
331 continue_status = HandleODSEvent(dbe.u.DebugString, dbe.dwThreadId);
332 break;
333 case RIP_EVENT:
334 continue_status = HandleRipEvent(dbe.u.RipInfo, dbe.dwThreadId);
335 if (dbe.u.RipInfo.dwType == SLE_ERROR)
336 should_debug = false;
337 break;
338 }
339
341 log, "calling ContinueDebugEvent({0}, {1}, {2}) on thread {3}.",
342 dbe.dwProcessId, dbe.dwThreadId, continue_status,
343 ::GetCurrentThreadId());
344
345 ::ContinueDebugEvent(dbe.dwProcessId, dbe.dwThreadId, continue_status);
346
347 if (dbe.dwDebugEventCode == EXIT_PROCESS_DEBUG_EVENT) {
348 if (exited_process) {
349 ::WaitForSingleObject(exited_process, INFINITE);
350 ::CloseHandle(exited_process);
351 }
352 HandleExitProcessEvent(dbe.u.ExitProcess, dbe.dwThreadId);
353 }
354
355 // We have to DebugActiveProcessStop after ContinueDebugEvent, otherwise
356 // the target process will crash
357 if (shutting_down) {
358 // A breakpoint that occurs while `m_pid_to_detach` is non-zero is a
359 // magic exception that we use simply to wake up the DebuggerThread so
360 // that we can close out the debug loop.
361 if (m_pid_to_detach != 0 &&
362 (dbe.u.Exception.ExceptionRecord.ExceptionCode ==
363 EXCEPTION_BREAKPOINT ||
364 dbe.u.Exception.ExceptionRecord.ExceptionCode ==
366 LLDB_LOG(log,
367 "Breakpoint exception is cue to detach from process {0:x}",
368 m_pid_to_detach.load());
369
370 // detaching with leaving breakpoint exception event on the queue may
371 // cause target process to crash so process events as possible since
372 // target threads are running at this time, there is possibility to
373 // have some breakpoint exception between last WaitForDebugEventEx and
374 // DebugActiveProcessStop but ignore for now.
375 while (g_wait_for_debug_event(&dbe, 0)) {
376 continue_status = DBG_CONTINUE;
377 if (dbe.dwDebugEventCode == EXCEPTION_DEBUG_EVENT &&
378 !(dbe.u.Exception.ExceptionRecord.ExceptionCode ==
379 EXCEPTION_BREAKPOINT ||
380 dbe.u.Exception.ExceptionRecord.ExceptionCode ==
382 dbe.u.Exception.ExceptionRecord.ExceptionCode ==
383 EXCEPTION_SINGLE_STEP))
384 continue_status = DBG_EXCEPTION_NOT_HANDLED;
385 ::ContinueDebugEvent(dbe.dwProcessId, dbe.dwThreadId,
386 continue_status);
387 }
388
389 ::DebugActiveProcessStop(m_pid_to_detach);
390 m_detached = true;
391 }
392 }
393
394 if (m_detached)
395 should_debug = false;
396 } else {
397 LLDB_LOG(log, "returned FALSE from WaitForDebugEventEx. Error = {0}",
398 ::GetLastError());
399
400 should_debug = false;
401 }
402 }
404
405 LLDB_LOG(log, "WaitForDebugEventEx loop completed, exiting.");
406 ::SetEvent(m_debugging_ended_event);
407}
408
410DebuggerThread::HandleExceptionEvent(const EXCEPTION_DEBUG_INFO &info,
411 DWORD thread_id, bool shutting_down) {
413 if (shutting_down) {
414 bool is_breakpoint =
415 (info.ExceptionRecord.ExceptionCode == EXCEPTION_BREAKPOINT ||
416 info.ExceptionRecord.ExceptionCode == STATUS_WX86_BREAKPOINT);
417
418 // Don't perform any blocking operations while we're shutting down. That
419 // will cause TerminateProcess -> WaitForSingleObject to time out.
420 // We should not send breakpoint exceptions to the application.
421 return is_breakpoint ? ExceptionResult::MaskException
423 }
424
425 bool first_chance = (info.dwFirstChance != 0);
426
427 ExceptionRecordSP active_exception =
428 std::make_shared<ExceptionRecord>(info.ExceptionRecord, thread_id);
429 {
430 std::lock_guard<std::mutex> guard(m_active_exception_mutex);
431 m_active_exception = active_exception;
432 }
433 // Set this before calling the delegate. The delegate can wake up the thread
434 // driving the debugger, and that thread can call ContinueAsyncException
435 // before OnDebugException returns.
437
438 LLDB_LOG(log, "encountered {0} chance exception {1:x} on thread {2:x}",
439 first_chance ? "first" : "second",
440 info.ExceptionRecord.ExceptionCode, thread_id);
441
442 ExceptionResult result =
443 m_debug_delegate->OnDebugException(first_chance, *active_exception);
444 // The delegate only says what to do, it never continues the exception. If the
445 // result is not BreakInDebugger, continue it here, or the wait below never
446 // ends. If the other thread already continued it, this does nothing and its
447 // result is what the wait below returns.
450
451 LLDB_LOG(log, "waiting for ExceptionPred != BreakInDebugger");
452 result = *m_exception_pred.WaitForValueNotEqualTo(
454
455 LLDB_LOG(log, "got ExceptionPred = {0}", (int)m_exception_pred.GetValue());
456 return result;
457}
458
459DWORD
460DebuggerThread::HandleCreateThreadEvent(const CREATE_THREAD_DEBUG_INFO &info,
461 DWORD thread_id) {
463 LLDB_LOG(log, "Thread {0} spawned in process {1}", thread_id,
464 m_process.GetProcessId());
465 HostThread thread(info.hThread);
466 thread.GetNativeThread().SetOwnsHandle(false);
467 m_debug_delegate->OnCreateThread(thread);
468 return DBG_CONTINUE;
469}
470
471/// Read the path the process was created with from its process parameters
472/// (PEB::ProcessParameters->ImagePathName).
473///
474/// This keeps the subst drive, junction or symbolic link the process was
475/// launched through.
476static std::optional<std::string> GetImagePathFromPEB(HANDLE process) {
477 // winternl.h declares NtQueryInformationProcess, but there is no import
478 // library for it.
479 static LazyImport<decltype(&::NtQueryInformationProcess)>
480 s_query_information_process{L"ntdll.dll", "NtQueryInformationProcess"};
481 if (!s_query_information_process)
482 return std::nullopt;
483
484 PROCESS_BASIC_INFORMATION pbi = {};
485 if ((*s_query_information_process)(process, ProcessBasicInformation, &pbi,
486 sizeof(pbi), nullptr) < 0 ||
487 !pbi.PebBaseAddress)
488 return std::nullopt;
489
490 PEB peb = {};
491 if (!::ReadProcessMemory(process, pbi.PebBaseAddress, &peb, sizeof(peb),
492 nullptr) ||
493 !peb.ProcessParameters)
494 return std::nullopt;
495
496 RTL_USER_PROCESS_PARAMETERS params = {};
497 if (!::ReadProcessMemory(process, peb.ProcessParameters, &params,
498 sizeof(params), nullptr) ||
499 !params.ImagePathName.Buffer || params.ImagePathName.Length == 0)
500 return std::nullopt;
501
502 std::wstring wpath(params.ImagePathName.Length / sizeof(wchar_t), L'\0');
503 if (!::ReadProcessMemory(process, params.ImagePathName.Buffer, wpath.data(),
504 params.ImagePathName.Length, nullptr))
505 return std::nullopt;
506
507 std::string path;
508 if (!llvm::convertWideToUTF8(wpath, path))
509 return std::nullopt;
510 // A process launched through an extended-length path has the "\\?\" prefix.
511 return StripExtendedLengthPrefix(path);
512}
513
514DWORD
515DebuggerThread::HandleCreateProcessEvent(const CREATE_PROCESS_DEBUG_INFO &info,
516 DWORD thread_id) {
518 uint32_t process_id = ::GetProcessId(info.hProcess);
519
520 LLDB_LOG(log, "process {0} spawned", process_id);
521
522 std::string thread_name;
523 llvm::raw_string_ostream name_stream(thread_name);
524 name_stream << "lldb.plugin.process-windows.secondary[" << process_id << "]";
525 llvm::set_thread_name(thread_name);
526
527 // info.hProcess and info.hThread are closed automatically by Windows when
528 // EXIT_PROCESS_DEBUG_EVENT is received.
529 m_process = HostProcess(info.hProcess);
530 static_cast<HostProcessWindows &>(m_process.GetNativeProcess())
531 .SetOwnsHandle(false);
532 m_main_thread = HostThread(info.hThread);
533 m_main_thread.GetNativeThread().SetOwnsHandle(false);
534 m_image_file = info.hFile;
535
536 lldb::addr_t load_addr = reinterpret_cast<lldb::addr_t>(info.lpBaseOfImage);
537 m_image_path = GetImagePathFromPEB(info.hProcess).value_or("");
538 m_debug_delegate->OnDebuggerConnected(load_addr);
539
540 return DBG_CONTINUE;
541}
542
543DWORD
544DebuggerThread::HandleExitThreadEvent(const EXIT_THREAD_DEBUG_INFO &info,
545 DWORD thread_id) {
547 LLDB_LOG(log, "Thread {0} exited with code {1} in process {2}", thread_id,
548 info.dwExitCode, m_process.GetProcessId());
549 m_debug_delegate->OnExitThread(thread_id, info.dwExitCode);
550 return DBG_CONTINUE;
551}
552
553DWORD
554DebuggerThread::HandleExitProcessEvent(const EXIT_PROCESS_DEBUG_INFO &info,
555 DWORD thread_id) {
557 LLDB_LOG(log, "process {0} exited with code {1}", m_process.GetProcessId(),
558 info.dwExitCode);
559
560 m_debug_delegate->OnExitProcess(info.dwExitCode);
561
562 return DBG_CONTINUE;
563}
564
565static std::optional<std::string>
566ConvertNtDevicePathToDosPath(llvm::ArrayRef<wchar_t> nt_path) {
568
569 llvm::SmallVector<wchar_t, MAX_PATH> vol_name(MAX_PATH);
570 HANDLE vol_iter = ::FindFirstVolumeW(vol_name.data(), vol_name.size());
571 if (vol_iter == INVALID_HANDLE_VALUE) {
572 LLDB_LOG(log,
573 "ConvertNtDevicePathToDosPath: FindFirstVolumeW failed, "
574 "error={0}",
575 ::GetLastError());
576 return std::nullopt;
577 }
578 llvm::scope_exit close_iter([&] { ::FindVolumeClose(vol_iter); });
579
580 do {
581 // FindFirstVolumeW yields "\\?\Volume{GUID}\".
582 // QueryDosDeviceW expects "Volume{GUID}".
583 size_t vol_len = ::wcsnlen(vol_name.data(), vol_name.size());
584 if (vol_len < 5 || vol_name[vol_len - 1] != L'\\')
585 continue;
586
587 vol_name[vol_len - 1] = L'\0'; // strip trailing '\' for QueryDosDeviceW
588 llvm::SmallVector<wchar_t, MAX_PATH> dev_name(MAX_PATH);
589 bool ok = ::QueryDosDeviceW(vol_name.data() + 4, // skip "\\?\"
590 dev_name.data(), dev_name.size());
591 vol_name[vol_len - 1] = L'\\'; // restore
592 if (!ok)
593 continue;
594
595 // Check that nt_path begins with this device name followed by '\'.
596 size_t dev_len = ::wcsnlen(dev_name.data(), dev_name.size());
597 if (dev_len == 0 || dev_len >= nt_path.size())
598 continue;
599 if (_wcsnicmp(nt_path.data(), dev_name.data(), dev_len) != 0)
600 continue;
601 if (nt_path[dev_len] != L'\\')
602 continue;
603
604 // Prefer a drive-letter/mount-point over the raw volume GUID path.
605 llvm::ArrayRef<wchar_t> mount(vol_name.data(), vol_len);
606 llvm::SmallVector<wchar_t> mount_names;
607 DWORD names_size = 0;
608 ::GetVolumePathNamesForVolumeNameW(vol_name.data(), nullptr, 0,
609 &names_size);
610 if (names_size > 1) {
611 mount_names.resize(names_size);
612 DWORD written = 0;
613 if (::GetVolumePathNamesForVolumeNameW(
614 vol_name.data(), mount_names.data(), names_size, &written) &&
615 mount_names[0] != L'\0') {
616 mount = llvm::ArrayRef<wchar_t>(
617 mount_names.data(),
618 ::wcsnlen(mount_names.data(), mount_names.size()));
619 }
620 }
621
622 // Build the final path: mount point + rest of nt_path.
623 llvm::SmallVector<wchar_t> dos_wide(mount.begin(), mount.end());
624 if (!dos_wide.empty() && dos_wide.back() == L'\\')
625 dos_wide.pop_back();
626 dos_wide.append(nt_path.begin() + dev_len, nt_path.end());
627
628 std::string result;
629 llvm::convertWideToUTF8(std::wstring_view(dos_wide.data(), dos_wide.size()),
630 result);
631 return result;
632 } while (::FindNextVolumeW(vol_iter, vol_name.data(), vol_name.size()));
633
634 LLDB_LOG(log, "ConvertNtDevicePathToDosPath: no matching volume found");
635 return std::nullopt;
636}
637
638// Query the file name backing the mapping at `addr` in `process` and convert
639// the resulting NT device path to a DOS path.
640static std::optional<std::string> GetMappedFileDosPath(HANDLE process,
641 LPVOID addr) {
642 std::vector<wchar_t> mapped_filename(MAX_PATH + 1);
643 DWORD mapped_len = 0;
644 while (mapped_filename.size() <= PATHCCH_MAX_CCH) {
645 mapped_len = ::GetMappedFileNameW(process, addr, mapped_filename.data(),
646 mapped_filename.size());
647 if (mapped_len == 0)
648 return std::nullopt;
649 if (mapped_len < mapped_filename.size())
650 break;
651 mapped_filename.resize(mapped_filename.size() * 2);
652 }
654 llvm::ArrayRef<wchar_t>(mapped_filename.data(), mapped_len + 1));
655}
656
657static std::optional<std::string> GetFileNameFromHandleFallback(HANDLE hFile) {
658 // Check that file is not empty as we cannot map a file with zero length.
659 DWORD dwFileSizeHi = 0;
660 DWORD dwFileSizeLo = ::GetFileSize(hFile, &dwFileSizeHi);
661 if (dwFileSizeLo == 0 && dwFileSizeHi == 0)
662 return std::nullopt;
663
664 AutoHandle filemap(
665 ::CreateFileMappingW(hFile, nullptr, PAGE_READONLY, 0, 1, nullptr),
666 nullptr);
667 if (!filemap.IsValid())
668 return std::nullopt;
669
670 auto view_deleter = [](void *pMem) { ::UnmapViewOfFile(pMem); };
671 std::unique_ptr<void, decltype(view_deleter)> pMem(
672 ::MapViewOfFile(filemap.get(), FILE_MAP_READ, 0, 0, 1), view_deleter);
673 if (!pMem)
674 return std::nullopt;
675
676 return GetMappedFileDosPath(::GetCurrentProcess(), pMem.get());
677}
678
679/// The path the loader recorded for the module at \p base_addr, or nullopt if
680/// the loader's module list has no entry for it yet.
681static std::optional<std::string> GetLoaderModuleName(HANDLE process,
682 LPVOID base_addr) {
683 std::vector<wchar_t> module_filename(MAX_PATH + 1);
684 while (module_filename.size() <= PATHCCH_MAX_CCH) {
685 DWORD len =
686 ::GetModuleFileNameExW(process, reinterpret_cast<HMODULE>(base_addr),
687 module_filename.data(), module_filename.size());
688 if (len == 0)
689 return std::nullopt;
690 if (len < module_filename.size()) {
691 std::string path_utf8;
692 llvm::convertWideToUTF8(std::wstring_view(module_filename.data(), len),
693 path_utf8);
694 return path_utf8;
695 }
696 module_filename.resize(module_filename.size() * 2);
697 }
698 return std::nullopt;
699}
700
701// Determine how many bytes can be read at `addr` in `process` before crossing
702// out of the committed memory region containing it. Returns 0 if the address is
703// not within a committed region.
704static SIZE_T BytesReadableAt(HANDLE process, LPCVOID addr) {
705 MEMORY_BASIC_INFORMATION mbi{};
706 if (!::VirtualQueryEx(process, addr, &mbi, sizeof(mbi)))
707 return 0;
708 if (mbi.State != MEM_COMMIT)
709 return 0;
710 uintptr_t region_end =
711 reinterpret_cast<uintptr_t>(mbi.BaseAddress) + mbi.RegionSize;
712 uintptr_t a = reinterpret_cast<uintptr_t>(addr);
713 assert(a < region_end);
714 return region_end - a;
715}
716
717static std::optional<std::string> ReadRemotePathStringW(HANDLE process,
718 LPCVOID addr) {
719 SIZE_T limit = std::min<SIZE_T>(PATHCCH_MAX_CCH * sizeof(wchar_t),
720 BytesReadableAt(process, addr));
721 std::vector<wchar_t> buf;
722 for (SIZE_T capacity = MAX_PATH * sizeof(wchar_t);; capacity *= 2) {
723 SIZE_T to_read = std::min<SIZE_T>(capacity, limit);
724 to_read &= ~SIZE_T(1); // round down to a wchar_t boundary
725 if (to_read < sizeof(wchar_t))
726 return std::nullopt;
727
728 buf.resize(to_read / sizeof(wchar_t));
729 SIZE_T bytes_read = 0;
730 if (!::ReadProcessMemory(process, addr, buf.data(), to_read, &bytes_read))
731 return std::nullopt;
732
733 size_t max_chars = bytes_read / sizeof(wchar_t);
734 size_t len = ::wcsnlen(buf.data(), max_chars);
735 if (len < max_chars) { // found the null terminator
736 if (len == 0) // empty string
737 return std::nullopt;
738 std::string result;
739 llvm::convertWideToUTF8(std::wstring_view(buf.data(), len), result);
740 return result;
741 }
742 if (to_read >= limit) // read everything available without a terminator
743 return std::nullopt;
744 }
745}
746
747static std::optional<std::string> ReadRemotePathStringA(HANDLE process,
748 LPCVOID addr) {
749 SIZE_T limit =
750 std::min<SIZE_T>(PATHCCH_MAX_CCH, BytesReadableAt(process, addr));
751 std::vector<char> buf;
752 for (SIZE_T capacity = MAX_PATH;; capacity *= 2) {
753 SIZE_T to_read = std::min<SIZE_T>(capacity, limit);
754 if (to_read == 0)
755 return std::nullopt;
756
757 buf.resize(to_read);
758 SIZE_T bytes_read = 0;
759 if (!::ReadProcessMemory(process, addr, buf.data(), to_read, &bytes_read))
760 return std::nullopt;
761
762 size_t len = ::strnlen(buf.data(), bytes_read);
763 if (len < bytes_read) { // found the null terminator
764 if (len == 0) // empty string
765 return std::nullopt;
766 return std::string(buf.data(), len);
767 }
768 if (to_read >= limit) // read everything available without a terminator
769 return std::nullopt;
770 }
771}
772
773// Resolve the LOAD_DLL_DEBUG_INFO::lpImageName field.
774static std::optional<std::string>
775GetFileNameFromImageNameField(HANDLE process, const LOAD_DLL_DEBUG_INFO &info) {
776 if (info.lpImageName == nullptr)
777 return std::nullopt;
778
779 LPVOID string_addr = nullptr;
780 SIZE_T bytes_read = 0;
781 if (!::ReadProcessMemory(process, info.lpImageName, &string_addr,
782 sizeof(string_addr), &bytes_read) ||
783 bytes_read != sizeof(string_addr))
784 return std::nullopt;
785
786 if (info.fUnicode)
787 return ReadRemotePathStringW(process, string_addr);
788 return ReadRemotePathStringA(process, string_addr);
789}
790
791DWORD
792DebuggerThread::HandleLoadDllEvent(const LOAD_DLL_DEBUG_INFO &info,
793 DWORD thread_id) {
795
797 auto on_load_dll = [&](llvm::StringRef path) {
798 FileSpec file_spec(path);
799 ModuleSpec module_spec(file_spec);
800 lldb::addr_t load_addr = reinterpret_cast<lldb::addr_t>(info.lpBaseOfDll);
801
802 LLDB_LOG(log, "Inferior {0} - DLL '{1}' loaded at address {2:x}...",
803 m_process.GetProcessId(), path, info.lpBaseOfDll);
804
805 m_dll_event_pred.SetValue(false, eBroadcastNever);
806 action = m_debug_delegate->OnLoadDll(module_spec, load_addr, thread_id);
807 };
808
809 HANDLE process = m_process.GetNativeProcess().GetSystemHandle();
810
811 // Prefer the path the loader used for the DLL, which keeps the subst drive,
812 // junction or symbolic link it was reached through.
813 std::optional<std::string> loader_path =
814 GetFileNameFromImageNameField(process, info);
815 if (loader_path && !llvm::sys::path::is_absolute(
816 *loader_path, llvm::sys::path::Style::windows))
817 loader_path.reset();
818 if (!loader_path)
819 loader_path = GetLoaderModuleName(process, info.lpBaseOfDll);
820 if (loader_path)
821 loader_path = StripExtendedLengthPrefix(*loader_path);
822
823 // The file handle gives the resolved path, with the on-disk case.
824 std::optional<std::string> file_path;
825 if (info.hFile != nullptr) {
826 std::vector<wchar_t> buffer(1);
827 DWORD required_size =
828 GetFinalPathNameByHandleW(info.hFile, &buffer[0], 0, VOLUME_NAME_DOS);
829 if (required_size > 0) {
830 buffer.resize(required_size + 1);
831 GetFinalPathNameByHandleW(info.hFile, &buffer[0], required_size,
832 VOLUME_NAME_DOS);
833 std::string path_str_utf8;
834 llvm::convertWideToUTF8(buffer.data(), path_str_utf8);
835 file_path = StripExtendedLengthPrefix(path_str_utf8);
836 } else {
837 file_path = GetFileNameFromHandleFallback(info.hFile);
838 }
839 }
840
841 // The loader's path often differs from the on-disk one only in case (e.g.
842 // C:\windows\System32\KERNEL32.DLL). If that's the case, keep the on disk
843 // spelling.
844 std::optional<std::string> resolved_path = loader_path;
845 if (!resolved_path ||
846 (file_path &&
847 llvm::StringRef(*file_path).equals_insensitive(*resolved_path)))
848 resolved_path = file_path;
849 if (!resolved_path)
850 resolved_path = GetFileNameFromImageNameField(process, info);
851 if (!resolved_path)
852 resolved_path = GetMappedFileDosPath(process, info.lpBaseOfDll);
853
854 if (resolved_path)
855 on_load_dll(*resolved_path);
856 else
857 LLDB_LOG(log,
858 "Inferior {0} - could not resolve path for LOAD_DLL_DEBUG_EVENT "
859 "(hFile={1}, base={2:x}, last error={3})",
860 m_process.GetProcessId(), info.hFile, info.lpBaseOfDll,
861 ::GetLastError());
862
863 // Windows does not automatically close info.hFile, so we need to do it.
864 if (info.hFile != nullptr)
865 ::CloseHandle(info.hFile);
866
867 if (action == DllEventAction::ParkDebugLoop && !m_is_shutting_down.load())
868 m_dll_event_pred.WaitForValueEqualTo(true);
869 return DBG_CONTINUE;
870}
871
872DWORD
873DebuggerThread::HandleUnloadDllEvent(const UNLOAD_DLL_DEBUG_INFO &info,
874 DWORD thread_id) {
876 LLDB_LOG(log, "process {0} unloading DLL at addr {1:x}.",
877 m_process.GetProcessId(), info.lpBaseOfDll);
878
879 m_dll_event_pred.SetValue(false, eBroadcastNever);
880 DllEventAction action = m_debug_delegate->OnUnloadDll(
881 reinterpret_cast<lldb::addr_t>(info.lpBaseOfDll), thread_id);
882 if (action == DllEventAction::ParkDebugLoop && !m_is_shutting_down.load())
883 m_dll_event_pred.WaitForValueEqualTo(true);
884 return DBG_CONTINUE;
885}
886
887DWORD
888DebuggerThread::HandleODSEvent(const OUTPUT_DEBUG_STRING_INFO &info,
889 DWORD thread_id) {
890 m_debug_delegate->OnDebugString(
891 static_cast<lldb::addr_t>(
892 reinterpret_cast<uintptr_t>(info.lpDebugStringData)),
893 info.fUnicode == TRUE, info.nDebugStringLength);
894 return DBG_CONTINUE;
895}
896
897DWORD
898DebuggerThread::HandleRipEvent(const RIP_INFO &info, DWORD thread_id) {
900 LLDB_LOG(log, "encountered error {0} (type={1}) in process {2} thread {3}",
901 info.dwError, info.dwType, m_process.GetProcessId(), thread_id);
902
903 Status error(info.dwError, eErrorTypeWin32);
904 m_debug_delegate->OnDebuggerError(error, info.dwType);
905
906 return DBG_CONTINUE;
907}
static llvm::raw_ostream & error(Stream &strm)
static std::optional< std::string > GetLoaderModuleName(HANDLE process, LPVOID base_addr)
The path the loader recorded for the module at base_addr, or nullopt if the loader's module list has ...
static std::optional< std::string > GetMappedFileDosPath(HANDLE process, LPVOID addr)
static SIZE_T BytesReadableAt(HANDLE process, LPCVOID addr)
static std::optional< std::string > GetImagePathFromPEB(HANDLE process)
Read the path the process was created with from its process parameters (PEB::ProcessParameters->Image...
static WaitForDebugEventFn * g_wait_for_debug_event
static std::optional< std::string > GetFileNameFromImageNameField(HANDLE process, const LOAD_DLL_DEBUG_INFO &info)
static std::optional< std::string > GetFileNameFromHandleFallback(HANDLE hFile)
static std::optional< std::string > ConvertNtDevicePathToDosPath(llvm::ArrayRef< wchar_t > nt_path)
#define STATUS_WX86_BREAKPOINT
BOOL WINAPI WaitForDebugEventFn(LPDEBUG_EVENT, DWORD)
static std::optional< std::string > ReadRemotePathStringW(HANDLE process, LPCVOID addr)
static void InitializeWaitForDebugEvent()
WaitForDebugEventEx is only available on Windows 10+.
static std::optional< std::string > ReadRemotePathStringA(HANDLE process, LPCVOID addr)
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::string StripExtendedLengthPrefix(llvm::StringRef path)
Convert an extended-length path to a regular DOS path: "\\?\C:\a" becomes "C:\a" and "\\?...
Definition PathUtils.h:21
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