Path: blob/main/contrib/llvm-project/lldb/source/Host/common/NativeProcessProtocol.cpp
39606 views
//===-- NativeProcessProtocol.cpp -----------------------------------------===//1//2// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.3// See https://llvm.org/LICENSE.txt for license information.4// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception5//6//===----------------------------------------------------------------------===//78#include "lldb/Host/common/NativeProcessProtocol.h"9#include "lldb/Host/Host.h"10#include "lldb/Host/common/NativeBreakpointList.h"11#include "lldb/Host/common/NativeRegisterContext.h"12#include "lldb/Host/common/NativeThreadProtocol.h"13#include "lldb/Utility/LLDBAssert.h"14#include "lldb/Utility/LLDBLog.h"15#include "lldb/Utility/Log.h"16#include "lldb/Utility/State.h"17#include "lldb/lldb-enumerations.h"1819#include "llvm/Support/Process.h"20#include <optional>2122using namespace lldb;23using namespace lldb_private;2425// NativeProcessProtocol Members2627NativeProcessProtocol::NativeProcessProtocol(lldb::pid_t pid, int terminal_fd,28NativeDelegate &delegate)29: m_pid(pid), m_delegate(delegate), m_terminal_fd(terminal_fd) {30delegate.InitializeDelegate(this);31}3233lldb_private::Status NativeProcessProtocol::Interrupt() {34Status error;35#if !defined(SIGSTOP)36error.SetErrorString("local host does not support signaling");37return error;38#else39return Signal(SIGSTOP);40#endif41}4243Status NativeProcessProtocol::IgnoreSignals(llvm::ArrayRef<int> signals) {44m_signals_to_ignore.clear();45m_signals_to_ignore.insert(signals.begin(), signals.end());46return Status();47}4849lldb_private::Status50NativeProcessProtocol::GetMemoryRegionInfo(lldb::addr_t load_addr,51MemoryRegionInfo &range_info) {52// Default: not implemented.53return Status("not implemented");54}5556lldb_private::Status57NativeProcessProtocol::ReadMemoryTags(int32_t type, lldb::addr_t addr,58size_t len, std::vector<uint8_t> &tags) {59return Status("not implemented");60}6162lldb_private::Status63NativeProcessProtocol::WriteMemoryTags(int32_t type, lldb::addr_t addr,64size_t len,65const std::vector<uint8_t> &tags) {66return Status("not implemented");67}6869std::optional<WaitStatus> NativeProcessProtocol::GetExitStatus() {70if (m_state == lldb::eStateExited)71return m_exit_status;7273return std::nullopt;74}7576bool NativeProcessProtocol::SetExitStatus(WaitStatus status,77bool bNotifyStateChange) {78Log *log = GetLog(LLDBLog::Process);79LLDB_LOG(log, "status = {0}, notify = {1}", status, bNotifyStateChange);8081// Exit status already set82if (m_state == lldb::eStateExited) {83if (m_exit_status)84LLDB_LOG(log, "exit status already set to {0}", *m_exit_status);85else86LLDB_LOG(log, "state is exited, but status not set");87return false;88}8990m_state = lldb::eStateExited;91m_exit_status = status;9293if (bNotifyStateChange)94SynchronouslyNotifyProcessStateChanged(lldb::eStateExited);9596return true;97}9899NativeThreadProtocol *NativeProcessProtocol::GetThreadAtIndex(uint32_t idx) {100std::lock_guard<std::recursive_mutex> guard(m_threads_mutex);101if (idx < m_threads.size())102return m_threads[idx].get();103return nullptr;104}105106NativeThreadProtocol *107NativeProcessProtocol::GetThreadByIDUnlocked(lldb::tid_t tid) {108for (const auto &thread : m_threads) {109if (thread->GetID() == tid)110return thread.get();111}112return nullptr;113}114115NativeThreadProtocol *NativeProcessProtocol::GetThreadByID(lldb::tid_t tid) {116std::lock_guard<std::recursive_mutex> guard(m_threads_mutex);117return GetThreadByIDUnlocked(tid);118}119120bool NativeProcessProtocol::IsAlive() const {121return m_state != eStateDetached && m_state != eStateExited &&122m_state != eStateInvalid && m_state != eStateUnloaded;123}124125const NativeWatchpointList::WatchpointMap &126NativeProcessProtocol::GetWatchpointMap() const {127return m_watchpoint_list.GetWatchpointMap();128}129130std::optional<std::pair<uint32_t, uint32_t>>131NativeProcessProtocol::GetHardwareDebugSupportInfo() const {132Log *log = GetLog(LLDBLog::Process);133134// get any thread135NativeThreadProtocol *thread(136const_cast<NativeProcessProtocol *>(this)->GetThreadAtIndex(0));137if (!thread) {138LLDB_LOG(log, "failed to find a thread to grab a NativeRegisterContext!");139return std::nullopt;140}141142NativeRegisterContext ®_ctx = thread->GetRegisterContext();143return std::make_pair(reg_ctx.NumSupportedHardwareBreakpoints(),144reg_ctx.NumSupportedHardwareWatchpoints());145}146147Status NativeProcessProtocol::SetWatchpoint(lldb::addr_t addr, size_t size,148uint32_t watch_flags,149bool hardware) {150// This default implementation assumes setting the watchpoint for the process151// will require setting the watchpoint for each of the threads. Furthermore,152// it will track watchpoints set for the process and will add them to each153// thread that is attached to via the (FIXME implement) OnThreadAttached ()154// method.155156Log *log = GetLog(LLDBLog::Process);157158// Update the thread list159UpdateThreads();160161// Keep track of the threads we successfully set the watchpoint for. If one162// of the thread watchpoint setting operations fails, back off and remove the163// watchpoint for all the threads that were successfully set so we get back164// to a consistent state.165std::vector<NativeThreadProtocol *> watchpoint_established_threads;166167// Tell each thread to set a watchpoint. In the event that hardware168// watchpoints are requested but the SetWatchpoint fails, try to set a169// software watchpoint as a fallback. It's conceivable that if there are170// more threads than hardware watchpoints available, some of the threads will171// fail to set hardware watchpoints while software ones may be available.172std::lock_guard<std::recursive_mutex> guard(m_threads_mutex);173for (const auto &thread : m_threads) {174assert(thread && "thread list should not have a NULL thread!");175176Status thread_error =177thread->SetWatchpoint(addr, size, watch_flags, hardware);178if (thread_error.Fail() && hardware) {179// Try software watchpoints since we failed on hardware watchpoint180// setting and we may have just run out of hardware watchpoints.181thread_error = thread->SetWatchpoint(addr, size, watch_flags, false);182if (thread_error.Success())183LLDB_LOG(log,184"hardware watchpoint requested but software watchpoint set");185}186187if (thread_error.Success()) {188// Remember that we set this watchpoint successfully in case we need to189// clear it later.190watchpoint_established_threads.push_back(thread.get());191} else {192// Unset the watchpoint for each thread we successfully set so that we193// get back to a consistent state of "not set" for the watchpoint.194for (auto unwatch_thread_sp : watchpoint_established_threads) {195Status remove_error = unwatch_thread_sp->RemoveWatchpoint(addr);196if (remove_error.Fail())197LLDB_LOG(log, "RemoveWatchpoint failed for pid={0}, tid={1}: {2}",198GetID(), unwatch_thread_sp->GetID(), remove_error);199}200201return thread_error;202}203}204return m_watchpoint_list.Add(addr, size, watch_flags, hardware);205}206207Status NativeProcessProtocol::RemoveWatchpoint(lldb::addr_t addr) {208// Update the thread list209UpdateThreads();210211Status overall_error;212213std::lock_guard<std::recursive_mutex> guard(m_threads_mutex);214for (const auto &thread : m_threads) {215assert(thread && "thread list should not have a NULL thread!");216217const Status thread_error = thread->RemoveWatchpoint(addr);218if (thread_error.Fail()) {219// Keep track of the first thread error if any threads fail. We want to220// try to remove the watchpoint from every thread, though, even if one or221// more have errors.222if (!overall_error.Fail())223overall_error = thread_error;224}225}226const Status error = m_watchpoint_list.Remove(addr);227return overall_error.Fail() ? overall_error : error;228}229230const HardwareBreakpointMap &231NativeProcessProtocol::GetHardwareBreakpointMap() const {232return m_hw_breakpoints_map;233}234235Status NativeProcessProtocol::SetHardwareBreakpoint(lldb::addr_t addr,236size_t size) {237// This default implementation assumes setting a hardware breakpoint for this238// process will require setting same hardware breakpoint for each of its239// existing threads. New thread will do the same once created.240Log *log = GetLog(LLDBLog::Process);241242// Update the thread list243UpdateThreads();244245// Exit here if target does not have required hardware breakpoint capability.246auto hw_debug_cap = GetHardwareDebugSupportInfo();247248if (hw_debug_cap == std::nullopt || hw_debug_cap->first == 0 ||249hw_debug_cap->first <= m_hw_breakpoints_map.size())250return Status("Target does not have required no of hardware breakpoints");251252// Vector below stores all thread pointer for which we have we successfully253// set this hardware breakpoint. If any of the current process threads fails254// to set this hardware breakpoint then roll back and remove this breakpoint255// for all the threads that had already set it successfully.256std::vector<NativeThreadProtocol *> breakpoint_established_threads;257258// Request to set a hardware breakpoint for each of current process threads.259std::lock_guard<std::recursive_mutex> guard(m_threads_mutex);260for (const auto &thread : m_threads) {261assert(thread && "thread list should not have a NULL thread!");262263Status thread_error = thread->SetHardwareBreakpoint(addr, size);264if (thread_error.Success()) {265// Remember that we set this breakpoint successfully in case we need to266// clear it later.267breakpoint_established_threads.push_back(thread.get());268} else {269// Unset the breakpoint for each thread we successfully set so that we270// get back to a consistent state of "not set" for this hardware271// breakpoint.272for (auto rollback_thread_sp : breakpoint_established_threads) {273Status remove_error =274rollback_thread_sp->RemoveHardwareBreakpoint(addr);275if (remove_error.Fail())276LLDB_LOG(log,277"RemoveHardwareBreakpoint failed for pid={0}, tid={1}: {2}",278GetID(), rollback_thread_sp->GetID(), remove_error);279}280281return thread_error;282}283}284285// Register new hardware breakpoint into hardware breakpoints map of current286// process.287m_hw_breakpoints_map[addr] = {addr, size};288289return Status();290}291292Status NativeProcessProtocol::RemoveHardwareBreakpoint(lldb::addr_t addr) {293// Update the thread list294UpdateThreads();295296Status error;297298std::lock_guard<std::recursive_mutex> guard(m_threads_mutex);299for (const auto &thread : m_threads) {300assert(thread && "thread list should not have a NULL thread!");301error = thread->RemoveHardwareBreakpoint(addr);302}303304// Also remove from hardware breakpoint map of current process.305m_hw_breakpoints_map.erase(addr);306307return error;308}309310void NativeProcessProtocol::SynchronouslyNotifyProcessStateChanged(311lldb::StateType state) {312Log *log = GetLog(LLDBLog::Process);313314m_delegate.ProcessStateChanged(this, state);315316switch (state) {317case eStateStopped:318case eStateExited:319case eStateCrashed:320NotifyTracersProcessDidStop();321break;322default:323break;324}325326LLDB_LOG(log, "sent state notification [{0}] from process {1}", state,327GetID());328}329330void NativeProcessProtocol::NotifyDidExec() {331Log *log = GetLog(LLDBLog::Process);332LLDB_LOG(log, "process {0} exec()ed", GetID());333334m_software_breakpoints.clear();335336m_delegate.DidExec(this);337}338339Status NativeProcessProtocol::SetSoftwareBreakpoint(lldb::addr_t addr,340uint32_t size_hint) {341Log *log = GetLog(LLDBLog::Breakpoints);342LLDB_LOG(log, "addr = {0:x}, size_hint = {1}", addr, size_hint);343344auto it = m_software_breakpoints.find(addr);345if (it != m_software_breakpoints.end()) {346++it->second.ref_count;347return Status();348}349auto expected_bkpt = EnableSoftwareBreakpoint(addr, size_hint);350if (!expected_bkpt)351return Status(expected_bkpt.takeError());352353m_software_breakpoints.emplace(addr, std::move(*expected_bkpt));354return Status();355}356357Status NativeProcessProtocol::RemoveSoftwareBreakpoint(lldb::addr_t addr) {358Log *log = GetLog(LLDBLog::Breakpoints);359LLDB_LOG(log, "addr = {0:x}", addr);360auto it = m_software_breakpoints.find(addr);361if (it == m_software_breakpoints.end())362return Status("Breakpoint not found.");363assert(it->second.ref_count > 0);364if (--it->second.ref_count > 0)365return Status();366367// This is the last reference. Let's remove the breakpoint.368Status error;369370// Clear a software breakpoint instruction371llvm::SmallVector<uint8_t, 4> curr_break_op(372it->second.breakpoint_opcodes.size(), 0);373374// Read the breakpoint opcode375size_t bytes_read = 0;376error =377ReadMemory(addr, curr_break_op.data(), curr_break_op.size(), bytes_read);378if (error.Fail() || bytes_read < curr_break_op.size()) {379return Status("addr=0x%" PRIx64380": tried to read %zu bytes but only read %zu",381addr, curr_break_op.size(), bytes_read);382}383const auto &saved = it->second.saved_opcodes;384// Make sure the breakpoint opcode exists at this address385if (llvm::ArrayRef(curr_break_op) != it->second.breakpoint_opcodes) {386if (curr_break_op != it->second.saved_opcodes)387return Status("Original breakpoint trap is no longer in memory.");388LLDB_LOG(log,389"Saved opcodes ({0:@[x]}) have already been restored at {1:x}.",390llvm::make_range(saved.begin(), saved.end()), addr);391} else {392// We found a valid breakpoint opcode at this address, now restore the393// saved opcode.394size_t bytes_written = 0;395error = WriteMemory(addr, saved.data(), saved.size(), bytes_written);396if (error.Fail() || bytes_written < saved.size()) {397return Status("addr=0x%" PRIx64398": tried to write %zu bytes but only wrote %zu",399addr, saved.size(), bytes_written);400}401402// Verify that our original opcode made it back to the inferior403llvm::SmallVector<uint8_t, 4> verify_opcode(saved.size(), 0);404size_t verify_bytes_read = 0;405error = ReadMemory(addr, verify_opcode.data(), verify_opcode.size(),406verify_bytes_read);407if (error.Fail() || verify_bytes_read < verify_opcode.size()) {408return Status("addr=0x%" PRIx64409": tried to read %zu verification bytes but only read %zu",410addr, verify_opcode.size(), verify_bytes_read);411}412if (verify_opcode != saved)413LLDB_LOG(log, "Restoring bytes at {0:x}: {1:@[x]}", addr,414llvm::make_range(saved.begin(), saved.end()));415}416417m_software_breakpoints.erase(it);418return Status();419}420421llvm::Expected<NativeProcessProtocol::SoftwareBreakpoint>422NativeProcessProtocol::EnableSoftwareBreakpoint(lldb::addr_t addr,423uint32_t size_hint) {424Log *log = GetLog(LLDBLog::Breakpoints);425426auto expected_trap = GetSoftwareBreakpointTrapOpcode(size_hint);427if (!expected_trap)428return expected_trap.takeError();429430llvm::SmallVector<uint8_t, 4> saved_opcode_bytes(expected_trap->size(), 0);431// Save the original opcodes by reading them so we can restore later.432size_t bytes_read = 0;433Status error = ReadMemory(addr, saved_opcode_bytes.data(),434saved_opcode_bytes.size(), bytes_read);435if (error.Fail())436return error.ToError();437438// Ensure we read as many bytes as we expected.439if (bytes_read != saved_opcode_bytes.size()) {440return llvm::createStringError(441llvm::inconvertibleErrorCode(),442"Failed to read memory while attempting to set breakpoint: attempted "443"to read {0} bytes but only read {1}.",444saved_opcode_bytes.size(), bytes_read);445}446447LLDB_LOG(448log, "Overwriting bytes at {0:x}: {1:@[x]}", addr,449llvm::make_range(saved_opcode_bytes.begin(), saved_opcode_bytes.end()));450451// Write a software breakpoint in place of the original opcode.452size_t bytes_written = 0;453error = WriteMemory(addr, expected_trap->data(), expected_trap->size(),454bytes_written);455if (error.Fail())456return error.ToError();457458// Ensure we wrote as many bytes as we expected.459if (bytes_written != expected_trap->size()) {460return llvm::createStringError(461llvm::inconvertibleErrorCode(),462"Failed write memory while attempting to set "463"breakpoint: attempted to write {0} bytes but only wrote {1}",464expected_trap->size(), bytes_written);465}466467llvm::SmallVector<uint8_t, 4> verify_bp_opcode_bytes(expected_trap->size(),4680);469size_t verify_bytes_read = 0;470error = ReadMemory(addr, verify_bp_opcode_bytes.data(),471verify_bp_opcode_bytes.size(), verify_bytes_read);472if (error.Fail())473return error.ToError();474475// Ensure we read as many verification bytes as we expected.476if (verify_bytes_read != verify_bp_opcode_bytes.size()) {477return llvm::createStringError(478llvm::inconvertibleErrorCode(),479"Failed to read memory while "480"attempting to verify breakpoint: attempted to read {0} bytes "481"but only read {1}",482verify_bp_opcode_bytes.size(), verify_bytes_read);483}484485if (llvm::ArrayRef(verify_bp_opcode_bytes.data(), verify_bytes_read) !=486*expected_trap) {487return llvm::createStringError(488llvm::inconvertibleErrorCode(),489"Verification of software breakpoint "490"writing failed - trap opcodes not successfully read back "491"after writing when setting breakpoint at {0:x}",492addr);493}494495LLDB_LOG(log, "addr = {0:x}: SUCCESS", addr);496return SoftwareBreakpoint{1, saved_opcode_bytes, *expected_trap};497}498499llvm::Expected<llvm::ArrayRef<uint8_t>>500NativeProcessProtocol::GetSoftwareBreakpointTrapOpcode(size_t size_hint) {501static const uint8_t g_aarch64_opcode[] = {0x00, 0x00, 0x20, 0xd4};502static const uint8_t g_i386_opcode[] = {0xCC};503static const uint8_t g_mips64_opcode[] = {0x00, 0x00, 0x00, 0x0d};504static const uint8_t g_mips64el_opcode[] = {0x0d, 0x00, 0x00, 0x00};505static const uint8_t g_msp430_opcode[] = {0x43, 0x43};506static const uint8_t g_s390x_opcode[] = {0x00, 0x01};507static const uint8_t g_ppc_opcode[] = {0x7f, 0xe0, 0x00, 0x08}; // trap508static const uint8_t g_ppcle_opcode[] = {0x08, 0x00, 0xe0, 0x7f}; // trap509static const uint8_t g_riscv_opcode[] = {0x73, 0x00, 0x10, 0x00}; // ebreak510static const uint8_t g_riscv_opcode_c[] = {0x02, 0x90}; // c.ebreak511static const uint8_t g_loongarch_opcode[] = {0x05, 0x00, 0x2a,5120x00}; // break 0x5513514switch (GetArchitecture().GetMachine()) {515case llvm::Triple::aarch64:516case llvm::Triple::aarch64_32:517return llvm::ArrayRef(g_aarch64_opcode);518519case llvm::Triple::x86:520case llvm::Triple::x86_64:521return llvm::ArrayRef(g_i386_opcode);522523case llvm::Triple::mips:524case llvm::Triple::mips64:525return llvm::ArrayRef(g_mips64_opcode);526527case llvm::Triple::mipsel:528case llvm::Triple::mips64el:529return llvm::ArrayRef(g_mips64el_opcode);530531case llvm::Triple::msp430:532return llvm::ArrayRef(g_msp430_opcode);533534case llvm::Triple::systemz:535return llvm::ArrayRef(g_s390x_opcode);536537case llvm::Triple::ppc:538case llvm::Triple::ppc64:539return llvm::ArrayRef(g_ppc_opcode);540541case llvm::Triple::ppc64le:542return llvm::ArrayRef(g_ppcle_opcode);543544case llvm::Triple::riscv32:545case llvm::Triple::riscv64: {546return size_hint == 2 ? llvm::ArrayRef(g_riscv_opcode_c)547: llvm::ArrayRef(g_riscv_opcode);548}549550case llvm::Triple::loongarch32:551case llvm::Triple::loongarch64:552return llvm::ArrayRef(g_loongarch_opcode);553554default:555return llvm::createStringError(llvm::inconvertibleErrorCode(),556"CPU type not supported!");557}558}559560size_t NativeProcessProtocol::GetSoftwareBreakpointPCOffset() {561switch (GetArchitecture().GetMachine()) {562case llvm::Triple::x86:563case llvm::Triple::x86_64:564case llvm::Triple::systemz:565// These architectures report increment the PC after breakpoint is hit.566return cantFail(GetSoftwareBreakpointTrapOpcode(0)).size();567568case llvm::Triple::arm:569case llvm::Triple::aarch64:570case llvm::Triple::aarch64_32:571case llvm::Triple::mips64:572case llvm::Triple::mips64el:573case llvm::Triple::mips:574case llvm::Triple::mipsel:575case llvm::Triple::ppc:576case llvm::Triple::ppc64:577case llvm::Triple::ppc64le:578case llvm::Triple::riscv32:579case llvm::Triple::riscv64:580case llvm::Triple::loongarch32:581case llvm::Triple::loongarch64:582// On these architectures the PC doesn't get updated for breakpoint hits.583return 0;584585default:586llvm_unreachable("CPU type not supported!");587}588}589590void NativeProcessProtocol::FixupBreakpointPCAsNeeded(591NativeThreadProtocol &thread) {592Log *log = GetLog(LLDBLog::Breakpoints);593594Status error;595596// Find out the size of a breakpoint (might depend on where we are in the597// code).598NativeRegisterContext &context = thread.GetRegisterContext();599600uint32_t breakpoint_size = GetSoftwareBreakpointPCOffset();601LLDB_LOG(log, "breakpoint size: {0}", breakpoint_size);602if (breakpoint_size == 0)603return;604605// First try probing for a breakpoint at a software breakpoint location: PC -606// breakpoint size.607const lldb::addr_t initial_pc_addr = context.GetPCfromBreakpointLocation();608lldb::addr_t breakpoint_addr = initial_pc_addr;609// Do not allow breakpoint probe to wrap around.610if (breakpoint_addr >= breakpoint_size)611breakpoint_addr -= breakpoint_size;612613if (m_software_breakpoints.count(breakpoint_addr) == 0) {614// We didn't find one at a software probe location. Nothing to do.615LLDB_LOG(log,616"pid {0} no lldb software breakpoint found at current pc with "617"adjustment: {1}",618GetID(), breakpoint_addr);619return;620}621622//623// We have a software breakpoint and need to adjust the PC.624//625626// Change the program counter.627LLDB_LOG(log, "pid {0} tid {1}: changing PC from {2:x} to {3:x}", GetID(),628thread.GetID(), initial_pc_addr, breakpoint_addr);629630error = context.SetPC(breakpoint_addr);631if (error.Fail()) {632// This can happen in case the process was killed between the time we read633// the PC and when we are updating it. There's nothing better to do than to634// swallow the error.635LLDB_LOG(log, "pid {0} tid {1}: failed to set PC: {2}", GetID(),636thread.GetID(), error);637}638}639640Status NativeProcessProtocol::RemoveBreakpoint(lldb::addr_t addr,641bool hardware) {642if (hardware)643return RemoveHardwareBreakpoint(addr);644else645return RemoveSoftwareBreakpoint(addr);646}647648Status NativeProcessProtocol::ReadMemoryWithoutTrap(lldb::addr_t addr,649void *buf, size_t size,650size_t &bytes_read) {651Status error = ReadMemory(addr, buf, size, bytes_read);652if (error.Fail())653return error;654655llvm::MutableArrayRef data(static_cast<uint8_t *>(buf), bytes_read);656for (const auto &pair : m_software_breakpoints) {657lldb::addr_t bp_addr = pair.first;658auto saved_opcodes = llvm::ArrayRef(pair.second.saved_opcodes);659660if (bp_addr + saved_opcodes.size() < addr || addr + bytes_read <= bp_addr)661continue; // Breakpoint not in range, ignore662663if (bp_addr < addr) {664saved_opcodes = saved_opcodes.drop_front(addr - bp_addr);665bp_addr = addr;666}667auto bp_data = data.drop_front(bp_addr - addr);668std::copy_n(saved_opcodes.begin(),669std::min(saved_opcodes.size(), bp_data.size()),670bp_data.begin());671}672return Status();673}674675llvm::Expected<llvm::StringRef>676NativeProcessProtocol::ReadCStringFromMemory(lldb::addr_t addr, char *buffer,677size_t max_size,678size_t &total_bytes_read) {679static const size_t cache_line_size =680llvm::sys::Process::getPageSizeEstimate();681size_t bytes_read = 0;682size_t bytes_left = max_size;683addr_t curr_addr = addr;684size_t string_size;685char *curr_buffer = buffer;686total_bytes_read = 0;687Status status;688689while (bytes_left > 0 && status.Success()) {690addr_t cache_line_bytes_left =691cache_line_size - (curr_addr % cache_line_size);692addr_t bytes_to_read = std::min<addr_t>(bytes_left, cache_line_bytes_left);693status = ReadMemory(curr_addr, static_cast<void *>(curr_buffer),694bytes_to_read, bytes_read);695696if (bytes_read == 0)697break;698699void *str_end = std::memchr(curr_buffer, '\0', bytes_read);700if (str_end != nullptr) {701total_bytes_read =702static_cast<size_t>((static_cast<char *>(str_end) - buffer + 1));703status.Clear();704break;705}706707total_bytes_read += bytes_read;708curr_buffer += bytes_read;709curr_addr += bytes_read;710bytes_left -= bytes_read;711}712713string_size = total_bytes_read - 1;714715// Make sure we return a null terminated string.716if (bytes_left == 0 && max_size > 0 && buffer[max_size - 1] != '\0') {717buffer[max_size - 1] = '\0';718total_bytes_read--;719}720721if (!status.Success())722return status.ToError();723724return llvm::StringRef(buffer, string_size);725}726727lldb::StateType NativeProcessProtocol::GetState() const {728std::lock_guard<std::recursive_mutex> guard(m_state_mutex);729return m_state;730}731732void NativeProcessProtocol::SetState(lldb::StateType state,733bool notify_delegates) {734std::lock_guard<std::recursive_mutex> guard(m_state_mutex);735736if (state == m_state)737return;738739m_state = state;740741if (StateIsStoppedState(state, false)) {742++m_stop_id;743744// Give process a chance to do any stop id bump processing, such as745// clearing cached data that is invalidated each time the process runs.746// Note if/when we support some threads running, we'll end up needing to747// manage this per thread and per process.748DoStopIDBumped(m_stop_id);749}750751// Optionally notify delegates of the state change.752if (notify_delegates)753SynchronouslyNotifyProcessStateChanged(state);754}755756uint32_t NativeProcessProtocol::GetStopID() const {757std::lock_guard<std::recursive_mutex> guard(m_state_mutex);758return m_stop_id;759}760761void NativeProcessProtocol::DoStopIDBumped(uint32_t /* newBumpId */) {762// Default implementation does nothing.763}764765NativeProcessProtocol::Manager::~Manager() = default;766767768