LLDB mainline
ProcessWindows.cpp
Go to the documentation of this file.
1//===-- ProcessWindows.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 "ProcessWindows.h"
10
11// Windows includes
13#include <dbghelp.h>
14#include <excpt.h>
15#include <psapi.h>
16
18#include "lldb/Core/Address.h"
19#include "lldb/Core/IOHandler.h"
20#include "lldb/Core/Module.h"
23#include "lldb/Core/Section.h"
24#include "lldb/Host/Config.h"
26#include "lldb/Host/HostInfo.h"
29#include "lldb/Host/Pipe.h"
39#include "lldb/Target/Target.h"
41#include "lldb/Utility/Log.h"
42#include "lldb/Utility/State.h"
43
44#include "llvm/Support/ConvertUTF.h"
45#include "llvm/Support/ErrorExtras.h"
46#include "llvm/Support/Format.h"
47#include "llvm/Support/Threading.h"
48#include "llvm/Support/raw_ostream.h"
49
50#include "DebuggerThread.h"
51#include "ExceptionRecord.h"
52#include "ForwardDecl.h"
53#include "LocalDebugDelegate.h"
54#include "ProcessWindowsLog.h"
55#include "TargetThreadWindows.h"
56
57using namespace lldb;
58using namespace lldb_private;
59
60LLDB_PLUGIN_DEFINE_ADV(ProcessWindows, ProcessWindowsCommon)
61
62namespace {
63std::string GetProcessExecutableName(HANDLE process_handle) {
64 std::vector<wchar_t> file_name;
65 DWORD file_name_size = MAX_PATH; // first guess, not an absolute limit
66 DWORD copied = 0;
67 do {
68 file_name_size *= 2;
69 file_name.resize(file_name_size);
70 copied = ::GetModuleFileNameExW(process_handle, nullptr, file_name.data(),
71 file_name_size);
72 } while (copied >= file_name_size);
73 file_name.resize(copied);
74 std::string result;
75 llvm::convertWideToUTF8(file_name.data(), result);
76 // A process launched through an extended-length path has the "\\?\" prefix.
77 return StripExtendedLengthPrefix(result);
78}
79
80std::string GetProcessExecutableName(DWORD pid) {
81 std::string file_name;
82 HANDLE process_handle =
83 ::OpenProcess(PROCESS_QUERY_INFORMATION | PROCESS_VM_READ, FALSE, pid);
84 if (process_handle != nullptr) {
85 file_name = GetProcessExecutableName(process_handle);
86 ::CloseHandle(process_handle);
87 }
88 return file_name;
89}
90} // anonymous namespace
91
92namespace lldb_private {
93
95 lldb::ListenerSP listener_sp,
96 const FileSpec *crash_file_path,
97 bool can_connect) {
98 if (crash_file_path)
99 return nullptr; // Cannot create a Windows process from a crash_file.
100 return ProcessSP(new ProcessWindows(target_sp, listener_sp));
101}
102
103static bool ShouldUseLLDBServer() {
104 if (const char *env = ::getenv("LLDB_USE_LLDB_SERVER")) {
105 llvm::StringRef use_lldb_server(env);
106 return use_lldb_server.equals_insensitive("on") ||
107 use_lldb_server.equals_insensitive("yes") ||
108 use_lldb_server.equals_insensitive("1") ||
109 use_lldb_server.equals_insensitive("true");
110 }
111 return LLDB_ENABLE_LIBXML2;
112}
113
120
125
127 return "Process plugin for Windows";
128}
129
130// Constructors and destructors.
131
133 lldb::ListenerSP listener_sp)
134 : lldb_private::Process(target_sp, listener_sp),
136 RegisterContextWindows::GetNumHardwareBreakpointSlots(),
138
140
142 if (bp_site->HardwareRequired())
143 return Status::FromErrorString("Hardware breakpoints are not supported.");
144
146 LLDB_LOG(log, "bp_site = {0:x}, id={1}, addr={2:x}", bp_site,
147 bp_site->GetID(), bp_site->GetLoadAddress());
148
150 if (!error.Success())
151 LLDB_LOG(log, "error: {0}", error);
152 return error;
153}
154
157 LLDB_LOG(log, "bp_site = {0:x}, id={1}, addr={2:x}", bp_site,
158 bp_site->GetID(), bp_site->GetLoadAddress());
159
161
162 if (!error.Success())
163 LLDB_LOG(log, "error: {0}", error);
164 return error;
165}
166
170 StateType private_state = GetPrivateState();
171 if (private_state != eStateExited && private_state != eStateDetached) {
172 if (!keep_stopped) {
173 // if the thread is suspended by lldb, we have to resume threads before
174 // detaching process. When we do after DetachProcess(), thread handles
175 // become invalid so we do before detach.
176 if (private_state == eStateStopped || private_state == eStateCrashed) {
177 LLDB_LOG(log, "process {0} is in state {1}. Resuming for detach...",
178 m_session_data->m_debugger->GetProcess().GetProcessId(),
180
181 LLDB_LOG(log, "resuming {0} threads for detach.",
182 m_thread_list.GetSize());
183
184 bool failed = false;
185 for (uint32_t i = 0; i < m_thread_list.GetSize(); ++i) {
186 auto thread = std::static_pointer_cast<TargetThreadWindows>(
187 m_thread_list.GetThreadAtIndex(i));
188 Status result = thread->DoResume();
189 if (result.Fail()) {
190 failed = true;
191 LLDB_LOG(log,
192 "Trying to resume thread at index {0}, but failed with "
193 "error {1}.",
194 i, result);
195 }
196 }
197
198 if (failed) {
199 error = Status::FromErrorString("Resuming Threads for Detach failed");
200 }
201 }
202 }
203
205 if (error.Success())
207 else
208 LLDB_LOG(log, "Detaching process error: {0}", error);
209 } else {
211 "error: process {0} in state = {1}, but "
212 "cannot detach it in this state.",
213 GetID(), private_state);
214 LLDB_LOG(log, "error: {0}", error);
215 }
216 return error;
217}
218
220 ProcessLaunchInfo &launch_info) {
222 DebugDelegateSP delegate(new LocalDebugDelegate(shared_from_this()));
223 error = LaunchProcess(launch_info, delegate);
224 if (error.Success())
225 SetID(launch_info.GetProcessID());
226 m_pty = launch_info.TakePTY();
227 return error;
228}
229
230Status
232 const ProcessAttachInfo &attach_info) {
233 DebugDelegateSP delegate(new LocalDebugDelegate(shared_from_this()));
234 Status error = AttachProcess(pid, attach_info, delegate);
235 if (error.Success())
237
239
240 return error;
241}
242
245 llvm::sys::ScopedLock lock(m_mutex);
246
247 if (direction == RunDirection::eRunReverse) {
249 "{0} does not support reverse execution of processes", GetPluginName());
250 }
251
253
254 StateType private_state = GetPrivateState();
255 if (private_state == eStateStopped || private_state == eStateCrashed) {
256 LLDB_LOG(log, "process {0} is in state {1}. Resuming...",
257 m_session_data->m_debugger->GetProcess().GetProcessId(),
259
260 LLDB_LOG(log, "resuming {0} threads.", m_thread_list.GetSize());
261
262 bool failed = false;
263 for (uint32_t i = 0; i < m_thread_list.GetSize(); ++i) {
264 auto thread = std::static_pointer_cast<TargetThreadWindows>(
265 m_thread_list.GetThreadAtIndex(i));
266 Status result = thread->DoResume();
267 if (result.Fail()) {
268 failed = true;
269 LLDB_LOG(
270 log,
271 "Trying to resume thread at index {0}, but failed with error {1}.",
272 i, result);
273 }
274 }
275
276 if (failed) {
277 error = Status::FromErrorString("ProcessWindows::DoResume failed");
278 } else {
280 }
281
282 ExceptionRecordSP active_exception =
283 m_session_data->m_debugger->GetActiveException();
284 if (active_exception) {
285 // Resume the process and continue processing debug events. Mask the
286 // exception so that from the process's view, there is no indication that
287 // anything happened.
288 m_session_data->m_debugger->ContinueAsyncException(
290 }
291 } else {
292 LLDB_LOG(log, "error: process {0} is in state {1}. Returning...",
293 m_session_data->m_debugger->GetProcess().GetProcessId(),
295 }
296 return error;
297}
298
300 StateType private_state = GetPrivateState();
301 return DestroyProcess(private_state);
302}
303
304Status ProcessWindows::DoHalt(bool &caused_stop) {
305 StateType state = GetPrivateState();
306 if (state != eStateStopped) {
307 m_pending_halt = true;
308 Status error = HaltProcess(caused_stop);
309 if (error.Fail() || !caused_stop)
310 m_pending_halt = false;
311 }
312 caused_stop = false;
313 return Status();
314}
315
317 ArchSpec arch_spec;
318 DidAttach(arch_spec);
319}
320
322 llvm::sys::ScopedLock lock(m_mutex);
323
324 // The initial stop won't broadcast the state change event, so account for
325 // that here.
327 m_session_data->m_stop_at_entry)
329}
330
333 llvm::sys::ScopedLock lock(m_mutex);
334
335 if (!m_session_data) {
336 LLDB_LOG(log, "no active session. Returning...");
337 return;
338 }
339
340 m_thread_list.RefreshStateAfterStop();
341
342 ExceptionRecordSP active_exception =
343 m_session_data->m_debugger->GetActiveException();
344 if (!active_exception) {
345 LLDB_LOG(log,
346 "there is no active exception in process {0}. Why is the "
347 "process stopped?",
348 m_session_data->m_debugger->GetProcess().GetProcessId());
349 return;
350 }
351
352 StopInfoSP stop_info;
353 m_thread_list.SetSelectedThreadByID(active_exception->GetThreadID());
354 ThreadSP stop_thread = m_thread_list.GetSelectedThread();
355 if (!stop_thread)
356 return;
357
358 RegisterContextSP register_context = stop_thread->GetRegisterContext();
359 uint64_t pc = register_context->GetPC();
360
361 // If we're at a BreakpointSite, mark this as an Unexecuted Breakpoint.
362 // We'll clear that state if we've actually executed the breakpoint.
363 BreakpointSiteSP site(GetBreakpointSiteList().FindByAddress(pc));
364 if (site && IsBreakpointSitePhysicallyEnabled(*site))
365 stop_thread->SetThreadStoppedAtUnexecutedBP(pc);
366
367 switch (active_exception->GetExceptionValue()) {
368 case EXCEPTION_SINGLE_STEP: {
369 auto *reg_ctx = static_cast<RegisterContextWindows *>(
370 stop_thread->GetRegisterContext().get());
371 uint32_t slot_id = reg_ctx->GetTriggeredHardwareBreakpointSlotId();
372 if (slot_id != LLDB_INVALID_INDEX32) {
373 int id = m_watchpoint_ids[slot_id];
374 LLDB_LOG(log,
375 "Single-stepped onto a watchpoint in process {0} at address "
376 "{1:x} with watchpoint {2}",
377 m_session_data->m_debugger->GetProcess().GetProcessId(), pc, id);
378
379 stop_info = StopInfo::CreateStopReasonWithWatchpointID(*stop_thread, id);
380 stop_thread->SetStopInfo(stop_info);
381
382 return;
383 }
384
385 LLDB_LOG(log, "single stepping thread {0}", stop_thread->GetID());
386 stop_info = StopInfo::CreateStopReasonToTrace(*stop_thread);
387 stop_thread->SetStopInfo(stop_info);
388
389 return;
390 }
391
392 case EXCEPTION_BREAKPOINT: {
393 int breakpoint_size = 1;
394 switch (GetTarget().GetArchitecture().GetMachine()) {
395 case llvm::Triple::aarch64:
396 breakpoint_size = 4;
397 break;
398
399 case llvm::Triple::arm:
400 case llvm::Triple::thumb:
401 breakpoint_size = 2;
402 break;
403
404 case llvm::Triple::x86:
405 case llvm::Triple::x86_64:
406 breakpoint_size = 1;
407 break;
408
409 default:
410 LLDB_LOG(log, "Unknown breakpoint size for architecture");
411 break;
412 }
413
414 // The current PC is AFTER the BP opcode, on all architectures.
415 pc = register_context->GetPC() - breakpoint_size;
416
418 if (site) {
419 LLDB_LOG(log,
420 "detected breakpoint in process {0} at address {1:x} with "
421 "breakpoint site {2}",
422 m_session_data->m_debugger->GetProcess().GetProcessId(), pc,
423 site->GetID());
424
425 stop_thread->SetThreadHitBreakpointSite();
426 if (site->ValidForThisThread(*stop_thread)) {
427 LLDB_LOG(log,
428 "Breakpoint site {0} is valid for this thread ({1:x}), "
429 "creating stop info.",
430 site->GetID(), stop_thread->GetID());
431
433 *stop_thread, site->GetID());
434 register_context->SetPC(pc);
435 } else {
436 LLDB_LOG(log,
437 "Breakpoint site {0} is not valid for this thread, "
438 "creating empty stop info.",
439 site->GetID());
440 }
441 stop_thread->SetStopInfo(stop_info);
442 return;
443 } else {
444 // The thread hit a hard-coded breakpoint like an `int 3` or
445 // `__debugbreak()`.
446 LLDB_LOG(log,
447 "No breakpoint site matches for this thread. __debugbreak()? "
448 "Creating stop info with the exception.");
449 // FALLTHROUGH: We'll treat this as a generic exception record in the
450 // default case.
451 [[fallthrough]];
452 }
453 }
454
455 default: {
456 std::string desc;
457 llvm::raw_string_ostream desc_stream(desc);
458 desc_stream << "Exception "
459 << llvm::format_hex(active_exception->GetExceptionValue(), 8)
460 << " encountered at address "
461 << llvm::format_hex(active_exception->GetExceptionAddress(), 8);
462 active_exception->Dump(desc_stream);
463
464 stop_info =
465 StopInfo::CreateStopReasonWithException(*stop_thread, desc.c_str());
466 stop_thread->SetStopInfo(stop_info);
467 LLDB_LOG(log, "{0}", desc);
468 return;
469 }
470 }
471}
472
474 bool plugin_specified_by_name) {
475 if (plugin_specified_by_name)
476 return true;
477
478 // For now we are just making sure the file exists for a given module
479 ModuleSP exe_module_sp(target_sp->GetExecutableModule());
480 if (exe_module_sp.get())
481 return FileSystem::Instance().Exists(exe_module_sp->GetFileSpec());
482 // However, if there is no executable module, we return true since we might
483 // be preparing to attach.
484 return true;
485}
486
488 ThreadList &new_thread_list) {
490 // Add all the threads that were previously running and for which we did not
491 // detect a thread exited event.
492 int new_size = 0;
493 int continued_threads = 0;
494 int exited_threads = 0;
495 int new_threads = 0;
496
497 for (ThreadSP old_thread : old_thread_list.Threads()) {
498 lldb::tid_t old_thread_id = old_thread->GetID();
499 auto exited_thread_iter =
500 m_session_data->m_exited_threads.find(old_thread_id);
501 if (exited_thread_iter == m_session_data->m_exited_threads.end()) {
502 new_thread_list.AddThread(old_thread);
503 ++new_size;
504 ++continued_threads;
505 LLDB_LOG_VERBOSE(log, "Thread {0} was running and is still running.",
506 old_thread_id);
507 } else {
508 LLDB_LOG_VERBOSE(log, "Thread {0} was running and has exited.",
509 old_thread_id);
510 ++exited_threads;
511 }
512 }
513
514 // Also add all the threads that are new since the last time we broke into
515 // the debugger.
516 for (const auto &thread_info : m_session_data->m_new_threads) {
517 new_thread_list.AddThread(thread_info.second);
518 ++new_size;
519 ++new_threads;
520 LLDB_LOG_VERBOSE(log, "Thread {0} is new since last update.",
521 thread_info.first);
522 }
523
524 LLDB_LOG(log, "{0} new threads, {1} old threads, {2} exited threads.",
525 new_threads, continued_threads, exited_threads);
526
527 m_session_data->m_new_threads.clear();
528 m_session_data->m_exited_threads.clear();
529
530 return new_size > 0;
531}
532
534 StateType state = GetPrivateState();
535 switch (state) {
536 case eStateCrashed:
537 case eStateDetached:
538 case eStateUnloaded:
539 case eStateExited:
540 case eStateInvalid:
541 return false;
542 default:
543 return true;
544 }
545}
546
548 return HostInfo::GetArchitecture();
549}
550
552 void *buf, size_t size, Status &error) {
553 lldb::addr_t vm_addr = process_addr.GetValue();
554 size_t bytes_read = 0;
555 error = ProcessDebugger::ReadMemory(vm_addr, buf, size, bytes_read);
556 return bytes_read;
557}
558
559size_t ProcessWindows::DoWriteMemory(lldb::addr_t vm_addr, const void *buf,
560 size_t size, Status &error) {
561 size_t bytes_written = 0;
562 error = ProcessDebugger::WriteMemory(vm_addr, buf, size, bytes_written);
563 return bytes_written;
564}
565
566lldb::addr_t ProcessWindows::DoAllocateMemory(size_t size, uint32_t permissions,
567 Status &error) {
569 error = ProcessDebugger::AllocateMemory(size, permissions, vm_addr);
570 return vm_addr;
571}
572
576
581
583 Target &target = GetTarget();
584 ModuleSP executable_sp = target.GetExecutableModule();
585 if (!executable_sp)
587 ObjectFile *obj_file = executable_sp->GetObjectFile();
588 Address addr = obj_file->GetImageInfoAddress(&target);
589 if (addr.IsValid())
590 return addr.GetLoadAddress(&target);
591 else
593}
594
601
602void ProcessWindows::OnExitProcess(uint32_t exit_code) {
603 // No need to acquire the lock since m_session_data isn't accessed.
605 LLDB_LOG(log, "Process {0} exited with code {1}", GetID(), exit_code);
606
607 if (m_pty) {
609 m_pty->SetStopping(true);
610 m_pty->Close();
611 m_stdio_communication.InterruptRead();
612 m_stdio_communication.StopReadThread();
613 }
614
615 TargetSP target = CalculateTarget();
616 if (target) {
617 ModuleSP executable_module = target->GetExecutableModule();
618 ModuleList unloaded_modules;
619 unloaded_modules.Append(executable_module);
620 target->ModulesDidUnload(unloaded_modules, false);
621 }
622
623 SetExitStatus(exit_code, /*exit_string=*/"");
625
627}
628
630 if (!m_stdio_communication.ReadThreadIsRunning())
631 return;
632 m_stdio_communication.SynchronizeWithReadThread();
633 if (!m_pty || m_pty->GetMode() != PseudoConsole::Mode::ConPTY)
634 return;
635
636 HANDLE pipe = m_pty->GetSTDOUTHandle();
637 for (int consec_empty = 0; consec_empty < 3;) {
638 if (!m_stdio_communication.ReadThreadIsRunning())
639 break;
640 DWORD avail = 0;
641 // PeekNamedPipe is thread safe.
642 if (!::PeekNamedPipe(pipe, nullptr, 0, nullptr, &avail, nullptr))
643 break;
644 if (avail > 0) {
645 consec_empty = 0;
646 m_stdio_communication.SynchronizeWithReadThread();
647 } else {
648 ++consec_empty;
649 if (consec_empty < 3)
650 ::SleepEx(1, FALSE);
651 }
652 }
653}
654
656 DebuggerThreadSP debugger = m_session_data->m_debugger;
658 LLDB_LOG(log, "Debugger connected to process {0}. Image base = {1:x}",
659 debugger->GetProcess().GetProcessId(), image_base);
660
662 if (!module) {
663 const DWORD pid = debugger->GetProcess().GetProcessId();
664 const std::string file_name = GetProcessExecutableName(pid);
665 if (file_name.empty())
666 return;
667
668 FileSpec executable_file(file_name);
669 FileSystem::Instance().Resolve(executable_file);
670 ModuleSpec module_spec(executable_file);
672 module =
673 GetTarget().GetOrCreateModule(module_spec, /*notify=*/true, &error);
674 if (!module)
675 return;
677 }
678
679 if (auto dyld = GetDynamicLoader())
680 dyld->OnLoadModule(module, ModuleSpec(), image_base);
681
682 // Add the main executable module to the list of pending module loads. We
683 // can't call GetTarget().ModulesDidLoad() here because we still haven't
684 // returned from DoLaunch() / DoAttach() yet so the target may not have set
685 // the process instance to `this` yet.
686 llvm::sys::ScopedLock lock(m_mutex);
687
688 const HostThread &host_main_thread = debugger->GetMainThread();
689 ThreadSP main_thread =
690 std::make_shared<TargetThreadWindows>(*this, host_main_thread);
691
692 tid_t id = host_main_thread.GetNativeThread().GetThreadId();
693 main_thread->SetID(id);
694
695 m_session_data->m_new_threads[id] = main_thread;
696}
697
700 const ExceptionRecord &record) {
702 llvm::sys::ScopedLock lock(m_mutex);
703
704 // FIXME: Without this check, occasionally when running the test suite there
705 // is
706 // an issue where m_session_data can be null. It's not clear how this could
707 // happen but it only surfaces while running the test suite. In order to
708 // properly diagnose this, we probably need to first figure allow the test
709 // suite to print out full lldb logs, and then add logging to the process
710 // plugin.
711 if (!m_session_data) {
712 LLDB_LOG(log,
713 "Debugger thread reported exception {0:x} at address {1:x}, "
714 "but there is no session.",
715 record.GetExceptionValue(), record.GetExceptionAddress());
717 }
718
719 if (!first_chance) {
720 // Not any second chance exception is an application crash by definition.
721 // It may be an expression evaluation crash.
724 }
725
727 switch (record.GetExceptionValue()) {
728 case EXCEPTION_BREAKPOINT: {
729 const lldb::addr_t bp_addr = record.GetExceptionAddress();
730 if (m_pending_halt) {
731 m_pending_halt = false;
732 } else if (m_expecting_loader_int3 && first_chance &&
733 m_session_data->m_initial_stop_received &&
734 !GetBreakpointSiteList().FindByAddress(bp_addr) &&
735 IsSystemModuleAddress(bp_addr)) {
737 LLDB_LOG(log,
738 "Skipping expected loader breakpoint at address {0:x} in a "
739 "system module.",
740 bp_addr);
742 }
743
744 // Handle breakpoints at the first chance.
746
747 if (!m_session_data->m_initial_stop_received) {
748 LLDB_LOG(
749 log,
750 "Hit loader breakpoint at address {0:x}, setting initial stop event.",
751 record.GetExceptionAddress());
752 m_session_data->m_initial_stop_received = true;
753 ::SetEvent(m_session_data->m_initial_stop_event);
754 } else {
755 LLDB_LOG(log, "Hit non-loader breakpoint at address {0:x}.",
756 record.GetExceptionAddress());
757 }
758 // Drain any in-flight process output before announcing the stop. The I/O
759 // reader thread and this debug-event thread run concurrently. Without
760 // synchronization the eBroadcastBitStateChanged(Stopped) event can reach
761 // the Debugger event thread before the preceding eBroadcastBitSTDOUT
762 // events.
765 break;
766 }
767 case EXCEPTION_SINGLE_STEP:
771 break;
772 default:
773 LLDB_LOG(log,
774 "Debugger thread reported exception {0:x} at address {1:x} "
775 "(first_chance={2})",
776 record.GetExceptionValue(), record.GetExceptionAddress(),
777 first_chance);
778 // For non-breakpoints, give the application a chance to handle the
779 // exception first.
780 if (first_chance)
782 else
784 }
785
786 return result;
787}
788
790 llvm::sys::ScopedLock lock(m_mutex);
791
792 ThreadSP thread = std::make_shared<TargetThreadWindows>(*this, new_thread);
793
794 const HostNativeThread &native_new_thread = new_thread.GetNativeThread();
795 tid_t id = native_new_thread.GetThreadId();
796 thread->SetID(id);
797
798 m_session_data->m_new_threads[id] = thread;
799
800 for (const std::map<int, WatchpointInfo>::value_type &p : m_watchpoints) {
801 auto *reg_ctx = static_cast<RegisterContextWindows *>(
802 thread->GetRegisterContext().get());
803 reg_ctx->AddHardwareBreakpoint(p.second.slot_id, p.second.address,
804 p.second.size, p.second.read,
805 p.second.write);
806 }
807}
808
809void ProcessWindows::OnExitThread(lldb::tid_t thread_id, uint32_t exit_code) {
810 llvm::sys::ScopedLock lock(m_mutex);
811
812 // On a forced termination, we may get exit thread events after the session
813 // data has been cleaned up.
814 if (!m_session_data)
815 return;
816
817 // A thread may have started and exited before the debugger stopped allowing a
818 // refresh.
819 // Just remove it from the new threads list in that case.
820 auto iter = m_session_data->m_new_threads.find(thread_id);
821 if (iter != m_session_data->m_new_threads.end())
822 m_session_data->m_new_threads.erase(iter);
823 else
824 m_session_data->m_exited_threads.insert(thread_id);
825}
826
828 lldb::addr_t module_addr,
829 lldb::tid_t thread_id) {
830 if (auto dyld = GetDynamicLoader())
831 dyld->OnLoadModule(nullptr, module_spec, module_addr);
833}
834
836 lldb::tid_t thread_id) {
837 if (auto dyld = GetDynamicLoader())
838 dyld->OnUnloadModule(module_addr);
840}
841
843 bool is_unicode,
844 uint16_t length_lower_word) {
846
847 llvm::SmallVector<char, 256> buffer;
848 llvm::Error err =
849 ReadDebugString(debug_string_addr, is_unicode, length_lower_word, buffer);
850 if (err) {
851 LLDB_LOG_ERROR(log, std::move(err),
852 "Failed to read debug string at {1:x} (size & 0xffff={2}, "
853 "unicode={3}): {0}",
854 debug_string_addr, length_lower_word, is_unicode);
855 return;
856 }
857 if (buffer.empty())
858 return;
859
860 if (is_unicode) {
861 assert(buffer.size() % 2 == 0);
862 llvm::ArrayRef<unsigned short> utf16(
863 reinterpret_cast<const unsigned short *>(buffer.data()),
864 buffer.size() / 2);
865 std::string out;
866 if (!llvm::convertUTF16ToUTF8String(utf16, out)) {
867 LLDB_LOG(log, "Debug string is not valid Utf 16");
868 return;
869 }
870
871 AppendSTDOUT(out.data(), out.size());
872 } else {
873 AppendSTDOUT(buffer.data(), buffer.size());
874 }
875}
876
877void ProcessWindows::OnDebuggerError(const Status &error, uint32_t type) {
878 llvm::sys::ScopedLock lock(m_mutex);
880
881 if (m_session_data->m_initial_stop_received) {
882 // This happened while debugging. Do we shutdown the debugging session,
883 // try to continue, or do something else?
884 LLDB_LOG(log,
885 "Error {0} occurred during debugging. Unexpected behavior "
886 "may result. {1}",
887 error.GetError(), error);
888 } else {
889 // If we haven't actually launched the process yet, this was an error
890 // launching the process. Set the internal error and signal the initial
891 // stop event so that the DoLaunch method wakes up and returns a failure.
892 m_session_data->m_launch_error = error.Clone();
893 ::SetEvent(m_session_data->m_initial_stop_event);
894 LLDB_LOG(
895 log,
896 "Error {0} occurred launching the process before the initial stop. {1}",
897 error.GetError(), error);
898 return;
899 }
900}
901
905
906std::optional<DWORD> ProcessWindows::GetActiveExceptionCode() const {
907 if (!m_session_data || !m_session_data->m_debugger)
908 return std::nullopt;
909 auto exc = m_session_data->m_debugger->GetActiveException();
910 if (!exc)
911 return std::nullopt;
912 return exc->GetExceptionValue();
913}
914
917
918 if (wp_sp->IsEnabled()) {
919 wp_sp->SetEnabled(true, notify);
920 return error;
921 }
922
923 WatchpointInfo info;
924 for (info.slot_id = 0;
926 info.slot_id++)
928 break;
931 "Can't find free slot for watchpoint %i", wp_sp->GetID());
932 return error;
933 }
934 info.address = wp_sp->GetLoadAddress();
935 info.size = wp_sp->GetByteSize();
936 info.read = wp_sp->WatchpointRead();
937 info.write = wp_sp->WatchpointWrite() || wp_sp->WatchpointModify();
938
939 for (unsigned i = 0U; i < m_thread_list.GetSize(); i++) {
940 Thread *thread = m_thread_list.GetThreadAtIndex(i).get();
941 auto *reg_ctx = static_cast<RegisterContextWindows *>(
942 thread->GetRegisterContext().get());
943 if (!reg_ctx->AddHardwareBreakpoint(info.slot_id, info.address, info.size,
944 info.read, info.write)) {
946 "Can't enable watchpoint %i on thread 0x%llx", wp_sp->GetID(),
947 thread->GetID());
948 break;
949 }
950 }
951 if (error.Fail()) {
952 for (unsigned i = 0U; i < m_thread_list.GetSize(); i++) {
953 Thread *thread = m_thread_list.GetThreadAtIndex(i).get();
954 auto *reg_ctx = static_cast<RegisterContextWindows *>(
955 thread->GetRegisterContext().get());
956 reg_ctx->RemoveHardwareBreakpoint(info.slot_id);
957 }
958 return error;
959 }
960
961 m_watchpoints[wp_sp->GetID()] = info;
962 m_watchpoint_ids[info.slot_id] = wp_sp->GetID();
963
964 wp_sp->SetEnabled(true, notify);
965
966 return error;
967}
968
971
972 if (!wp_sp->IsEnabled()) {
973 wp_sp->SetEnabled(false, notify);
974 return error;
975 }
976
977 auto it = m_watchpoints.find(wp_sp->GetID());
978 if (it == m_watchpoints.end()) {
980 "Info about watchpoint %i is not found", wp_sp->GetID());
981 return error;
982 }
983
984 for (unsigned i = 0U; i < m_thread_list.GetSize(); i++) {
985 Thread *thread = m_thread_list.GetThreadAtIndex(i).get();
986 auto *reg_ctx = static_cast<RegisterContextWindows *>(
987 thread->GetRegisterContext().get());
988 if (!reg_ctx->RemoveHardwareBreakpoint(it->second.slot_id)) {
990 "Can't disable watchpoint %i on thread 0x%llx", wp_sp->GetID(),
991 thread->GetID());
992 break;
993 }
994 }
995 if (error.Fail())
996 return error;
997
998 m_watchpoint_ids[it->second.slot_id] = LLDB_INVALID_BREAK_ID;
999 m_watchpoints.erase(it);
1000
1001 wp_sp->SetEnabled(false, notify);
1002
1003 return error;
1004}
1005
1006size_t ProcessWindows::PutSTDIN(const char *src, size_t src_len,
1007 Status &error) {
1008 if (!m_stdio_communication.IsConnected()) {
1009 error = Status::FromErrorString("stdin not connected");
1010 return 0;
1011 }
1012 ConnectionStatus status;
1013 return m_stdio_communication.WriteAll(src, src_len, status, &error);
1014}
1015
1017 if (m_pty == nullptr)
1018 return;
1019 m_stdio_communication.SetConnection(
1020 std::make_unique<ConnectionConPTY>(m_pty));
1021 if (m_stdio_communication.IsConnected()) {
1022 m_stdio_communication.SetReadThreadBytesReceivedCallback(
1024 m_stdio_communication.StartReadThread();
1025
1026 // Now read thread is set up, set up input reader.
1027 {
1028 std::lock_guard<std::mutex> guard(m_process_input_reader_mutex);
1031 std::make_shared<IOHandlerProcessSTDIOWindows>(this);
1032 }
1033 }
1034}
1035} // namespace lldb_private
static llvm::raw_ostream & error(Stream &strm)
DllEventAction
Definition ForwardDecl.h:29
#define LLDB_LOG(log,...)
The LLDB_LOG* macros defined below are the way to emit log messages.
Definition Log.h:375
#define LLDB_LOG_ERROR(log, error,...)
Definition Log.h:405
#define LLDB_LOG_VERBOSE(log,...)
Definition Log.h:382
#define MAX_PATH
#define LLDB_PLUGIN_DEFINE_ADV(ClassName, PluginName)
void * HANDLE
A section + offset based address class.
Definition Address.h:62
lldb::addr_t GetLoadAddress(Target *target) const
Get the load address.
Definition Address.cpp:303
bool IsValid() const
Check if the object state is valid.
Definition Address.h:355
An architecture specification class.
Definition ArchSpec.h:32
Class that manages the actual breakpoint that will be inserted into the running program.
static DynamicLoader * FindPlugin(Process *process, llvm::StringRef plugin_name)
Find a dynamic loader plugin for a given process.
unsigned long GetExceptionValue() const
lldb::addr_t GetExceptionAddress() const
A file utility class.
Definition FileSpec.h:56
bool Exists(const FileSpec &file_spec) const
Returns whether the given file exists.
static FileSystem & Instance()
void Resolve(llvm::SmallVectorImpl< char > &path, bool force_make_absolute=false)
Resolve path to make it canonical.
HostNativeThread & GetNativeThread()
A collection class for Module objects.
Definition ModuleList.h:125
void Append(const lldb::ModuleSP &module_sp, bool notify=true)
Append a module to the module list.
A class that describes an executable image and its associated object and symbol files.
Definition Module.h:91
A plug-in interface definition class for object file parsers.
Definition ObjectFile.h:46
virtual lldb_private::Address GetImageInfoAddress(Target *target)
Similar to Process::GetImageInfoAddress().
Definition ObjectFile.h:448
static bool RegisterPlugin(llvm::StringRef name, llvm::StringRef description, ABICreateInstance create_callback)
static bool UnregisterPlugin(ABICreateInstance create_callback)
An address in a process, qualified by an address space.
lldb::addr_t GetValue() const
Status WriteMemory(lldb::addr_t addr, const void *buf, size_t size, size_t &bytes_written)
Status DestroyProcess(lldb::StateType process_state)
Status LaunchProcess(ProcessLaunchInfo &launch_info, DebugDelegateSP delegate)
Status GetMemoryRegionInfo(lldb::addr_t load_addr, MemoryRegionInfo &range_info)
std::unique_ptr< ProcessWindowsData > m_session_data
Status AllocateMemory(size_t size, uint32_t permissions, lldb::addr_t &addr)
Status AttachProcess(lldb::pid_t pid, const ProcessAttachInfo &attach_info, DebugDelegateSP delegate)
lldb::pid_t GetDebuggedProcessId() const
Status ReadMemory(lldb::addr_t addr, void *buf, size_t size, size_t &bytes_read)
bool IsSystemModuleAddress(lldb::addr_t addr)
virtual void OnExitProcess(uint32_t exit_code)
llvm::Error ReadDebugString(lldb::addr_t debug_string_addr, bool is_unicode, uint16_t length_lower_word, llvm::SmallVectorImpl< char > &output)
Read an OUTPUT_DEBUG_STRING_INFO payload from the inferior.
Status HaltProcess(bool &caused_stop)
Status DeallocateMemory(lldb::addr_t addr)
lldb::pid_t GetProcessID() const
Definition ProcessInfo.h:66
std::shared_ptr< PTY > TakePTY()
ProcessWindows(lldb::TargetSP target_sp, lldb::ListenerSP listener_sp)
bool DoUpdateThreadList(ThreadList &old_thread_list, ThreadList &new_thread_list) override
Update the thread list following process plug-in's specific logic.
DllEventAction OnUnloadDll(lldb::addr_t module_addr, lldb::tid_t thread_id) override
void RefreshStateAfterStop() override
Currently called as part of ShouldStop.
void OnDebuggerConnected(lldb::addr_t image_base) override
Status DoDeallocateMemory(lldb::addr_t ptr) override
Actually deallocate memory in the process.
std::shared_ptr< PTY > m_pty
Status EnableBreakpointSite(BreakpointSite *bp_site) override
void DrainProcessStdout()
Block until the stdio read thread has surfaced everything currently buffered in the ConPTY/pipe to th...
void DidLaunch() override
Called after launching a process.
std::optional< uint32_t > GetWatchpointSlotCount() override
Get the number of watchpoints supported by this target.
Status DoResume(lldb::RunDirection direction) override
Resumes all of a process's threads as configured using the Thread run control functions.
DynamicLoaderWindowsDYLD * GetDynamicLoader() override
Get the dynamic loader plug-in for this process.
void OnDebugString(lldb::addr_t debug_string_addr, bool is_unicode, uint16_t length_lower_word) override
size_t DoReadMemory(const ProcessAddress &vm_addr, void *buf, size_t size, Status &error) override
Actually do the reading of memory from a process.
Status DisableWatchpoint(lldb::WatchpointSP wp_sp, bool notify=true) override
bool IsAlive() override
Check if a process is still alive.
Status DoGetMemoryRegionInfo(lldb::addr_t vm_addr, MemoryRegionInfo &info) override
DoGetMemoryRegionInfo is called by GetMemoryRegionInfo after it has removed non address bits from loa...
void OnCreateThread(const HostThread &thread) override
DllEventAction OnLoadDll(const ModuleSpec &module_spec, lldb::addr_t module_addr, lldb::tid_t thread_id) override
static llvm::StringRef GetPluginDescriptionStatic()
size_t DoWriteMemory(lldb::addr_t vm_addr, const void *buf, size_t size, Status &error) override
Actually do the writing of memory to a process.
llvm::StringRef GetPluginName() override
Status DoLaunch(Module *exe_module, ProcessLaunchInfo &launch_info) override
Launch a new process.
bool CanDebug(lldb::TargetSP target_sp, bool plugin_specified_by_name) override
Check if a plug-in instance can debug the file in module.
static llvm::StringRef GetPluginNameStatic()
void DidAttach(lldb_private::ArchSpec &arch_spec) override
Called after attaching a process.
void OnExitProcess(uint32_t exit_code) override
static lldb::ProcessSP CreateInstance(lldb::TargetSP target_sp, lldb::ListenerSP listener_sp, const FileSpec *, bool can_connect)
void OnExitThread(lldb::tid_t thread_id, uint32_t exit_code) override
Status DoAttachToProcessWithID(lldb::pid_t pid, const lldb_private::ProcessAttachInfo &attach_info) override
Attach to an existing process using a process ID.
lldb::addr_t GetImageInfoAddress() override
Get the image information address for the current process.
size_t PutSTDIN(const char *src, size_t src_len, Status &error) override
Puts data into this process's STDIN.
ExceptionResult OnDebugException(bool first_chance, const ExceptionRecord &record) override
std::map< lldb::break_id_t, WatchpointInfo > m_watchpoints
std::optional< DWORD > GetActiveExceptionCode() const
Returns the exception code of the active (current) debug exception, or std::nullopt if there is no ac...
void OnDebuggerError(const Status &error, uint32_t type) override
ArchSpec GetSystemArchitecture() override
Get the system architecture for this process.
Status DoDetach(bool keep_stopped) override
Detaches from a running or stopped process.
std::vector< lldb::break_id_t > m_watchpoint_ids
lldb::addr_t DoAllocateMemory(size_t size, uint32_t permissions, Status &error) override
Actually allocate memory in the process.
Status DisableBreakpointSite(BreakpointSite *bp_site) override
Status DoHalt(bool &caused_stop) override
Halts a running process.
Status EnableWatchpoint(lldb::WatchpointSP wp_sp, bool notify=true) override
lldb::IOHandlerSP m_process_input_reader
Definition Process.h:3523
std::mutex m_process_input_reader_mutex
Definition Process.h:3524
StopPointSiteList< lldb_private::BreakpointSite > & GetBreakpointSiteList()
Definition Process.cpp:1604
virtual Status DisableSoftwareBreakpoint(BreakpointSite *bp_site)
Definition Process.cpp:1982
lldb::pid_t GetID() const
Returns the pid of the process or LLDB_INVALID_PROCESS_ID if there is no known pid.
Definition Process.h:552
Process(lldb::TargetSP target_sp, lldb::ListenerSP listener_sp)
Construct with a shared pointer to a target, and the Process listener.
Definition Process.cpp:485
lldb::StateType GetPrivateState() const
Definition Process.h:3430
lldb::DynamicLoaderUP m_dyld_up
Definition Process.h:3511
bool IsBreakpointSitePhysicallyEnabled(const BreakpointSite &site)
Definition Process.cpp:1709
void AppendSTDOUT(const char *s, size_t len)
Definition Process.cpp:4892
lldb::TargetSP CalculateTarget() override
Definition Process.cpp:4858
virtual Status EnableSoftwareBreakpoint(BreakpointSite *bp_site)
Definition Process.cpp:1902
void SetID(lldb::pid_t new_pid)
Sets the stored pid.
Definition Process.h:557
friend class Target
Definition Process.h:374
virtual bool SetExitStatus(int exit_status, llvm::StringRef exit_string)
Set accessor for the process exit status (return code).
Definition Process.cpp:1080
static void STDIOReadThreadBytesReceived(void *baton, const void *src, size_t src_len)
Definition Process.cpp:4992
void SetPrivateState(lldb::StateType state)
Definition Process.cpp:1444
ThreadList m_thread_list
The threads for this process as the user will see them.
Definition Process.h:3481
ThreadedCommunication m_stdio_communication
Definition Process.h:3525
friend class ThreadList
Definition Process.h:375
Target & GetTarget()
Get the target object pointer for this module.
Definition Process.h:1267
static constexpr uint32_t GetNumHardwareBreakpointSlots()
bool AddHardwareBreakpoint(uint32_t slot, lldb::addr_t address, uint32_t size, bool read, bool write)
An error handling class.
Definition Status.h:118
static Status FromErrorStringWithFormat(const char *format,...) __attribute__((format(printf
Definition Status.cpp:106
static Status FromErrorString(const char *str)
Definition Status.h:141
bool Fail() const
Test for error condition.
Definition Status.cpp:293
static Status static Status FromErrorStringWithFormatv(const char *format, Args &&...args)
Definition Status.h:151
static lldb::StopInfoSP CreateStopReasonToTrace(Thread &thread)
static lldb::StopInfoSP CreateStopReasonWithWatchpointID(Thread &thread, lldb::break_id_t watch_id, bool silently_continue=false)
static lldb::StopInfoSP CreateStopReasonWithException(Thread &thread, const char *description)
static lldb::StopInfoSP CreateStopReasonWithBreakpointSiteID(Thread &thread, lldb::break_id_t break_id)
StopPointSiteSP FindByAddress(lldb::addr_t addr)
Returns a shared pointer to the site at address addr.
lldb::break_id_t GetID() const
virtual lldb::addr_t GetLoadAddress() const
lldb::ModuleSP GetExecutableModule()
Gets the module for the main executable.
Definition Target.cpp:1630
void RebuildModuleListWithExecutable(lldb::ModuleSP &module_sp, LoadDependentFiles load_dependent_files=eLoadDependentsDefault)
Clear the module list and rebuild it around a new main executable.
Definition Target.cpp:1673
void AddThread(const lldb::ThreadSP &thread_sp)
virtual ThreadIterable Threads()
#define LLDB_INVALID_BREAK_ID
#define LLDB_INVALID_INDEX32
#define LLDB_INVALID_ADDRESS
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
HostThreadPosix HostNativeThread
std::shared_ptr< DebuggerThread > DebuggerThreadSP
Definition ForwardDecl.h:46
std::shared_ptr< IDebugDelegate > DebugDelegateSP
Definition ForwardDecl.h:45
std::shared_ptr< ExceptionRecord > ExceptionRecordSP
Definition ForwardDecl.h:47
static bool ShouldUseLLDBServer()
std::shared_ptr< lldb_private::BreakpointSite > BreakpointSiteSP
RunDirection
Execution directions.
std::shared_ptr< lldb_private::Thread > ThreadSP
ConnectionStatus
Connection Status Types.
StateType
Process and Thread States.
@ eStateUnloaded
Process is object is valid, but not currently loaded.
@ eStateDetached
Process has been detached and can't be examined.
@ eStateStopped
Process or thread is stopped and can be examined.
@ eStateRunning
Process or thread is running and can't be examined.
@ eStateExited
Process has exited and can't be examined.
@ eStateCrashed
Process or thread has crashed and can be examined.
std::shared_ptr< lldb_private::Process > ProcessSP
uint64_t pid_t
Definition lldb-types.h:84
std::shared_ptr< lldb_private::Watchpoint > WatchpointSP
std::shared_ptr< lldb_private::Listener > ListenerSP
std::shared_ptr< lldb_private::StopInfo > StopInfoSP
uint64_t addr_t
Definition lldb-types.h:80
std::shared_ptr< lldb_private::Target > TargetSP
std::shared_ptr< lldb_private::RegisterContext > RegisterContextSP
uint64_t tid_t
Definition lldb-types.h:85
std::shared_ptr< lldb_private::Module > ModuleSP