24#include "lldb/Host/Config.h"
43#include "llvm/Support/ConvertUTF.h"
44#include "llvm/Support/ErrorExtras.h"
45#include "llvm/Support/Format.h"
46#include "llvm/Support/Threading.h"
47#include "llvm/Support/raw_ostream.h"
62std::string GetProcessExecutableName(
HANDLE process_handle) {
63 std::vector<wchar_t> file_name;
68 file_name.resize(file_name_size);
69 copied = ::GetModuleFileNameExW(process_handle,
nullptr, file_name.data(),
71 }
while (copied >= file_name_size);
72 file_name.resize(copied);
74 llvm::convertWideToUTF8(file_name.data(), result);
78std::string GetProcessExecutableName(DWORD pid) {
79 std::string file_name;
81 ::OpenProcess(PROCESS_QUERY_INFORMATION | PROCESS_VM_READ, FALSE, pid);
82 if (process_handle !=
nullptr) {
83 file_name = GetProcessExecutableName(process_handle);
84 ::CloseHandle(process_handle);
102 if (
const char *env = ::getenv(
"LLDB_USE_LLDB_SERVER")) {
103 llvm::StringRef use_lldb_server(env);
104 return use_lldb_server.equals_insensitive(
"on") ||
105 use_lldb_server.equals_insensitive(
"yes") ||
106 use_lldb_server.equals_insensitive(
"1") ||
107 use_lldb_server.equals_insensitive(
"true");
109 return LLDB_ENABLE_LIBXML2;
125 return "Process plugin for Windows";
144 LLDB_LOG(log,
"bp_site = {0:x}, id={1}, addr={2:x}", bp_site,
148 if (!
error.Success())
155 LLDB_LOG(log,
"bp_site = {0:x}, id={1}, addr={2:x}", bp_site,
160 if (!
error.Success())
175 LLDB_LOG(log,
"process {0} is in state {1}. Resuming for detach...",
179 LLDB_LOG(log,
"resuming {0} threads for detach.",
184 auto thread = std::static_pointer_cast<TargetThreadWindows>(
186 Status result = thread->DoResume();
190 "Trying to resume thread at index {0}, but failed with "
209 "error: process {0} in state = {1}, but "
210 "cannot detach it in this state.",
211 GetID(), private_state);
243 llvm::sys::ScopedLock lock(
m_mutex);
247 "{0} does not support reverse execution of processes",
GetPluginName());
254 LLDB_LOG(log,
"process {0} is in state {1}. Resuming...",
262 auto thread = std::static_pointer_cast<TargetThreadWindows>(
264 Status result = thread->DoResume();
269 "Trying to resume thread at index {0}, but failed with error {1}.",
282 if (active_exception) {
290 LLDB_LOG(log,
"error: process {0} is in state {1}. Returning...",
307 if (
error.Fail() || !caused_stop)
320 llvm::sys::ScopedLock lock(
m_mutex);
331 llvm::sys::ScopedLock lock(
m_mutex);
334 LLDB_LOG(log,
"no active session. Returning...");
340 std::weak_ptr<ExceptionRecord> exception_record =
343 if (!active_exception) {
345 "there is no active exception in process {0}. Why is the "
352 m_thread_list.SetSelectedThreadByID(active_exception->GetThreadID());
358 uint64_t
pc = register_context->GetPC();
364 stop_thread->SetThreadStoppedAtUnexecutedBP(
pc);
366 switch (active_exception->GetExceptionValue()) {
367 case EXCEPTION_SINGLE_STEP: {
369 stop_thread->GetRegisterContext().get());
374 "Single-stepped onto a watchpoint in process {0} at address "
375 "{1:x} with watchpoint {2}",
379 stop_thread->SetStopInfo(stop_info);
384 LLDB_LOG(log,
"single stepping thread {0}", stop_thread->GetID());
386 stop_thread->SetStopInfo(stop_info);
391 case EXCEPTION_BREAKPOINT: {
392 int breakpoint_size = 1;
393 switch (
GetTarget().GetArchitecture().GetMachine()) {
394 case llvm::Triple::aarch64:
398 case llvm::Triple::arm:
399 case llvm::Triple::thumb:
403 case llvm::Triple::x86:
404 case llvm::Triple::x86_64:
409 LLDB_LOG(log,
"Unknown breakpoint size for architecture");
414 pc = register_context->GetPC() - breakpoint_size;
419 "detected breakpoint in process {0} at address {1:x} with "
420 "breakpoint site {2}",
424 stop_thread->SetThreadHitBreakpointSite();
425 if (site->ValidForThisThread(*stop_thread)) {
427 "Breakpoint site {0} is valid for this thread ({1:x}), "
428 "creating stop info.",
429 site->GetID(), stop_thread->GetID());
432 *stop_thread, site->GetID());
433 register_context->SetPC(
pc);
436 "Breakpoint site {0} is not valid for this thread, "
437 "creating empty stop info.",
440 stop_thread->SetStopInfo(stop_info);
446 "No breakpoint site matches for this thread. __debugbreak()? "
447 "Creating stop info with the exception.");
456 llvm::raw_string_ostream desc_stream(desc);
457 desc_stream <<
"Exception "
458 << llvm::format_hex(active_exception->GetExceptionValue(), 8)
459 <<
" encountered at address "
460 << llvm::format_hex(active_exception->GetExceptionAddress(), 8);
461 active_exception->Dump(desc_stream);
465 stop_thread->SetStopInfo(stop_info);
473 bool plugin_specified_by_name) {
474 if (plugin_specified_by_name)
478 ModuleSP exe_module_sp(target_sp->GetExecutableModule());
479 if (exe_module_sp.get())
492 int continued_threads = 0;
493 int exited_threads = 0;
498 auto exited_thread_iter =
500 if (exited_thread_iter ==
m_session_data->m_exited_threads.end()) {
516 new_thread_list.
AddThread(thread_info.second);
523 LLDB_LOG(log,
"{0} new threads, {1} old threads, {2} exited threads.",
524 new_threads, continued_threads, exited_threads);
547 return HostInfo::GetArchitecture();
552 size_t bytes_read = 0;
559 size_t bytes_written = 0;
561 return bytes_written;
600 LLDB_LOG(log,
"Process {0} exited with code {1}",
GetID(), exit_code);
604 m_pty->SetStopping(
true);
612 ModuleSP executable_module = target->GetExecutableModule();
614 unloaded_modules.
Append(executable_module);
615 target->ModulesDidUnload(unloaded_modules,
false);
632 for (
int consec_empty = 0; consec_empty < 3;) {
637 if (!::PeekNamedPipe(pipe,
nullptr, 0,
nullptr, &avail,
nullptr))
644 if (consec_empty < 3)
653 LLDB_LOG(log,
"Debugger connected to process {0}. Image base = {1:x}",
654 debugger->GetProcess().GetProcessId(), image_base);
658 const DWORD pid = debugger->GetProcess().GetProcessId();
659 const std::string file_name = GetProcessExecutableName(pid);
660 if (file_name.empty())
663 FileSpec executable_file(file_name);
668 GetTarget().GetOrCreateModule(module_spec, true, &error);
675 dyld->OnLoadModule(module,
ModuleSpec(), image_base);
681 llvm::sys::ScopedLock lock(
m_mutex);
683 const HostThread &host_main_thread = debugger->GetMainThread();
685 std::make_shared<TargetThreadWindows>(*
this, host_main_thread);
688 main_thread->SetID(
id);
697 llvm::sys::ScopedLock lock(
m_mutex);
708 "Debugger thread reported exception {0:x} at address {1:x}, "
709 "but there is no session.",
723 case EXCEPTION_BREAKPOINT: {
733 "Skipping expected loader breakpoint at address {0:x} in a "
745 "Hit loader breakpoint at address {0:x}, setting initial stop event.",
750 LLDB_LOG(log,
"Hit non-loader breakpoint at address {0:x}.",
762 case EXCEPTION_SINGLE_STEP:
769 "Debugger thread reported exception {0:x} at address {1:x} "
770 "(first_chance={2})",
785 llvm::sys::ScopedLock lock(
m_mutex);
787 ThreadSP thread = std::make_shared<TargetThreadWindows>(*
this, new_thread);
790 tid_t id = native_new_thread.GetThreadId();
795 for (
const std::map<int, WatchpointInfo>::value_type &p :
m_watchpoints) {
797 thread->GetRegisterContext().get());
799 p.second.size, p.second.read,
805 llvm::sys::ScopedLock lock(
m_mutex);
826 dyld->OnLoadModule(
nullptr, module_spec, module_addr);
833 dyld->OnUnloadModule(module_addr);
839 uint16_t length_lower_word) {
842 llvm::SmallVector<char, 256> buffer;
844 ReadDebugString(debug_string_addr, is_unicode, length_lower_word, buffer);
847 "Failed to read debug string at {1:x} (size & 0xffff={2}, "
849 debug_string_addr, length_lower_word, is_unicode);
856 assert(buffer.size() % 2 == 0);
857 llvm::ArrayRef<unsigned short> utf16(
858 reinterpret_cast<const unsigned short *
>(buffer.data()),
861 if (!llvm::convertUTF16ToUTF8String(utf16, out)) {
862 LLDB_LOG(log,
"Debug string is not valid Utf 16");
873 llvm::sys::ScopedLock lock(
m_mutex);
880 "Error {0} occurred during debugging. Unexpected behavior "
891 "Error {0} occurred launching the process before the initial stop. {1}",
904 auto exc =
m_session_data->m_debugger->GetActiveException().lock();
907 return exc->GetExceptionValue();
913 if (wp_sp->IsEnabled()) {
914 wp_sp->SetEnabled(
true, notify);
926 "Can't find free slot for watchpoint %i", wp_sp->GetID());
929 info.
address = wp_sp->GetLoadAddress();
930 info.
size = wp_sp->GetByteSize();
931 info.
read = wp_sp->WatchpointRead();
932 info.
write = wp_sp->WatchpointWrite() || wp_sp->WatchpointModify();
937 thread->GetRegisterContext().get());
941 "Can't enable watchpoint %i on thread 0x%llx", wp_sp->GetID(),
950 thread->GetRegisterContext().get());
959 wp_sp->SetEnabled(
true, notify);
967 if (!wp_sp->IsEnabled()) {
968 wp_sp->SetEnabled(
false, notify);
975 "Info about watchpoint %i is not found", wp_sp->GetID());
982 thread->GetRegisterContext().get());
983 if (!reg_ctx->RemoveHardwareBreakpoint(it->second.slot_id)) {
985 "Can't disable watchpoint %i on thread 0x%llx", wp_sp->GetID(),
996 wp_sp->SetEnabled(
false, notify);
1012 if (
m_pty ==
nullptr)
1015 std::make_unique<ConnectionConPTY>(
m_pty));
1026 std::make_shared<IOHandlerProcessSTDIOWindows>(
this);
static llvm::raw_ostream & error(Stream &strm)
#define LLDB_LOG(log,...)
The LLDB_LOG* macros defined below are the way to emit log messages.
#define LLDB_LOG_ERROR(log, error,...)
#define LLDB_LOG_VERBOSE(log,...)
#define LLDB_PLUGIN_DEFINE_ADV(ClassName, PluginName)
A section + offset based address class.
lldb::addr_t GetLoadAddress(Target *target) const
Get the load address.
bool IsValid() const
Check if the object state is valid.
An architecture specification class.
Class that manages the actual breakpoint that will be inserted into the running program.
static llvm::StringRef GetPluginNameStatic()
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
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.
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.
A plug-in interface definition class for object file parsers.
virtual lldb_private::Address GetImageInfoAddress(Target *target)
Similar to Process::GetImageInfoAddress().
static bool RegisterPlugin(llvm::StringRef name, llvm::StringRef description, ABICreateInstance create_callback)
static bool UnregisterPlugin(ABICreateInstance create_callback)
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
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.
Status DoDestroy() override
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 SetPseudoConsoleHandle() override
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
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.
size_t DoReadMemory(lldb::addr_t vm_addr, void *buf, size_t size, Status &error) override
Actually do the reading of memory from a 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
bool m_expecting_loader_int3
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
std::mutex m_process_input_reader_mutex
StopPointSiteList< lldb_private::BreakpointSite > & GetBreakpointSiteList()
virtual Status DisableSoftwareBreakpoint(BreakpointSite *bp_site)
lldb::pid_t GetID() const
Returns the pid of the process or LLDB_INVALID_PROCESS_ID if there is no known pid.
Process(lldb::TargetSP target_sp, lldb::ListenerSP listener_sp)
Construct with a shared pointer to a target, and the Process listener.
lldb::StateType GetPrivateState() const
lldb::DynamicLoaderUP m_dyld_up
bool IsBreakpointSitePhysicallyEnabled(const BreakpointSite &site)
void AppendSTDOUT(const char *s, size_t len)
lldb::TargetSP CalculateTarget() override
virtual Status EnableSoftwareBreakpoint(BreakpointSite *bp_site)
void SetID(lldb::pid_t new_pid)
Sets the stored pid.
virtual bool SetExitStatus(int exit_status, llvm::StringRef exit_string)
Set accessor for the process exit status (return code).
static void STDIOReadThreadBytesReceived(void *baton, const void *src, size_t src_len)
void SetPrivateState(lldb::StateType state)
ThreadList m_thread_list
The threads for this process as the user will see them.
ThreadedCommunication m_stdio_communication
Target & GetTarget()
Get the target object pointer for this module.
static constexpr uint32_t GetNumHardwareBreakpointSlots()
uint32_t GetTriggeredHardwareBreakpointSlotId()
bool RemoveHardwareBreakpoint(uint32_t slot)
bool AddHardwareBreakpoint(uint32_t slot, lldb::addr_t address, uint32_t size, bool read, bool write)
static Status FromErrorStringWithFormat(const char *format,...) __attribute__((format(printf
static Status FromErrorString(const char *str)
bool Fail() const
Test for error condition.
static Status static Status FromErrorStringWithFormatv(const char *format, Args &&...args)
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
bool HardwareRequired() const
lldb::ModuleSP GetExecutableModule()
Gets the module for the main executable.
void SetExecutableModule(lldb::ModuleSP &module_sp, LoadDependentFiles load_dependent_files=eLoadDependentsDefault)
Set the main executable module.
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.
HostThreadPosix HostNativeThread
std::shared_ptr< DebuggerThread > DebuggerThreadSP
std::shared_ptr< IDebugDelegate > DebugDelegateSP
std::shared_ptr< ExceptionRecord > ExceptionRecordSP
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
std::shared_ptr< lldb_private::Watchpoint > WatchpointSP
std::shared_ptr< lldb_private::Listener > ListenerSP
std::shared_ptr< lldb_private::StopInfo > StopInfoSP
std::shared_ptr< lldb_private::Target > TargetSP
std::shared_ptr< lldb_private::RegisterContext > RegisterContextSP
std::shared_ptr< lldb_private::Module > ModuleSP