brintos

brintos / llvm-project-archived public Read only

0
0
Text · 234.6 KiB · 3c4d9a1 Raw
6152 lines · cpp
1//===-- ProcessGDBRemote.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-exception6//7//===----------------------------------------------------------------------===//8 9#include "lldb/Host/Config.h"10 11#include <cerrno>12#include <cstdlib>13#if LLDB_ENABLE_POSIX14#include <netinet/in.h>15#include <sys/mman.h>16#include <sys/socket.h>17#include <unistd.h>18#endif19#include <sys/stat.h>20#if defined(__APPLE__)21#include <sys/sysctl.h>22#endif23#include <ctime>24#include <sys/types.h>25 26#include "lldb/Breakpoint/Watchpoint.h"27#include "lldb/Breakpoint/WatchpointAlgorithms.h"28#include "lldb/Breakpoint/WatchpointResource.h"29#include "lldb/Core/Debugger.h"30#include "lldb/Core/Module.h"31#include "lldb/Core/ModuleSpec.h"32#include "lldb/Core/PluginManager.h"33#include "lldb/Core/Value.h"34#include "lldb/DataFormatters/FormatManager.h"35#include "lldb/Host/ConnectionFileDescriptor.h"36#include "lldb/Host/FileSystem.h"37#include "lldb/Host/HostInfo.h"38#include "lldb/Host/HostThread.h"39#include "lldb/Host/PosixApi.h"40#include "lldb/Host/PseudoTerminal.h"41#include "lldb/Host/StreamFile.h"42#include "lldb/Host/ThreadLauncher.h"43#include "lldb/Host/XML.h"44#include "lldb/Interpreter/CommandInterpreter.h"45#include "lldb/Interpreter/CommandObject.h"46#include "lldb/Interpreter/CommandObjectMultiword.h"47#include "lldb/Interpreter/CommandReturnObject.h"48#include "lldb/Interpreter/OptionArgParser.h"49#include "lldb/Interpreter/OptionGroupBoolean.h"50#include "lldb/Interpreter/OptionGroupUInt64.h"51#include "lldb/Interpreter/OptionValueProperties.h"52#include "lldb/Interpreter/Options.h"53#include "lldb/Interpreter/Property.h"54#include "lldb/Symbol/ObjectFile.h"55#include "lldb/Target/ABI.h"56#include "lldb/Target/DynamicLoader.h"57#include "lldb/Target/MemoryRegionInfo.h"58#include "lldb/Target/RegisterFlags.h"59#include "lldb/Target/SystemRuntime.h"60#include "lldb/Target/Target.h"61#include "lldb/Target/TargetList.h"62#include "lldb/Target/ThreadPlanCallFunction.h"63#include "lldb/Utility/Args.h"64#include "lldb/Utility/FileSpec.h"65#include "lldb/Utility/LLDBLog.h"66#include "lldb/Utility/State.h"67#include "lldb/Utility/StreamString.h"68#include "lldb/Utility/Timer.h"69#include <algorithm>70#include <csignal>71#include <map>72#include <memory>73#include <mutex>74#include <optional>75#include <sstream>76#include <thread>77 78#include "GDBRemoteRegisterContext.h"79#include "GDBRemoteRegisterFallback.h"80#include "Plugins/Process/Utility/GDBRemoteSignals.h"81#include "Plugins/Process/Utility/InferiorCallPOSIX.h"82#include "Plugins/Process/Utility/StopInfoMachException.h"83#include "ProcessGDBRemote.h"84#include "ProcessGDBRemoteLog.h"85#include "ThreadGDBRemote.h"86#include "lldb/Host/Host.h"87#include "lldb/Utility/StringExtractorGDBRemote.h"88 89#include "llvm/ADT/STLExtras.h"90#include "llvm/ADT/ScopeExit.h"91#include "llvm/ADT/StringMap.h"92#include "llvm/ADT/StringSwitch.h"93#include "llvm/Support/FormatAdapters.h"94#include "llvm/Support/Threading.h"95#include "llvm/Support/raw_ostream.h"96 97#if defined(__APPLE__)98#define DEBUGSERVER_BASENAME "debugserver"99#elif defined(_WIN32)100#define DEBUGSERVER_BASENAME "lldb-server.exe"101#else102#define DEBUGSERVER_BASENAME "lldb-server"103#endif104 105using namespace lldb;106using namespace lldb_private;107using namespace lldb_private::process_gdb_remote;108 109LLDB_PLUGIN_DEFINE(ProcessGDBRemote)110 111namespace lldb {112// Provide a function that can easily dump the packet history if we know a113// ProcessGDBRemote * value (which we can get from logs or from debugging). We114// need the function in the lldb namespace so it makes it into the final115// executable since the LLDB shared library only exports stuff in the lldb116// namespace. This allows you to attach with a debugger and call this function117// and get the packet history dumped to a file.118void DumpProcessGDBRemotePacketHistory(void *p, const char *path) {119  auto file = FileSystem::Instance().Open(120      FileSpec(path), File::eOpenOptionWriteOnly | File::eOpenOptionCanCreate);121  if (!file) {122    llvm::consumeError(file.takeError());123    return;124  }125  StreamFile stream(std::move(file.get()));126  ((Process *)p)->DumpPluginHistory(stream);127}128} // namespace lldb129 130namespace {131 132#define LLDB_PROPERTIES_processgdbremote133#include "ProcessGDBRemoteProperties.inc"134 135enum {136#define LLDB_PROPERTIES_processgdbremote137#include "ProcessGDBRemotePropertiesEnum.inc"138};139 140class PluginProperties : public Properties {141public:142  static llvm::StringRef GetSettingName() {143    return ProcessGDBRemote::GetPluginNameStatic();144  }145 146  PluginProperties() : Properties() {147    m_collection_sp = std::make_shared<OptionValueProperties>(GetSettingName());148    m_collection_sp->Initialize(g_processgdbremote_properties);149  }150 151  ~PluginProperties() override = default;152 153  uint64_t GetPacketTimeout() {154    const uint32_t idx = ePropertyPacketTimeout;155    return GetPropertyAtIndexAs<uint64_t>(156        idx, g_processgdbremote_properties[idx].default_uint_value);157  }158 159  bool SetPacketTimeout(uint64_t timeout) {160    const uint32_t idx = ePropertyPacketTimeout;161    return SetPropertyAtIndex(idx, timeout);162  }163 164  FileSpec GetTargetDefinitionFile() const {165    const uint32_t idx = ePropertyTargetDefinitionFile;166    return GetPropertyAtIndexAs<FileSpec>(idx, {});167  }168 169  bool GetUseSVR4() const {170    const uint32_t idx = ePropertyUseSVR4;171    return GetPropertyAtIndexAs<bool>(172        idx, g_processgdbremote_properties[idx].default_uint_value != 0);173  }174 175  bool GetUseGPacketForReading() const {176    const uint32_t idx = ePropertyUseGPacketForReading;177    return GetPropertyAtIndexAs<bool>(idx, true);178  }179};180 181std::chrono::seconds ResumeTimeout() { return std::chrono::seconds(5); }182 183} // namespace184 185static PluginProperties &GetGlobalPluginProperties() {186  static PluginProperties g_settings;187  return g_settings;188}189 190// TODO Randomly assigning a port is unsafe.  We should get an unused191// ephemeral port from the kernel and make sure we reserve it before passing it192// to debugserver.193 194#if defined(__APPLE__)195#define LOW_PORT (IPPORT_RESERVED)196#define HIGH_PORT (IPPORT_HIFIRSTAUTO)197#else198#define LOW_PORT (1024u)199#define HIGH_PORT (49151u)200#endif201 202llvm::StringRef ProcessGDBRemote::GetPluginDescriptionStatic() {203  return "GDB Remote protocol based debugging plug-in.";204}205 206void ProcessGDBRemote::Terminate() {207  PluginManager::UnregisterPlugin(ProcessGDBRemote::CreateInstance);208}209 210lldb::ProcessSP ProcessGDBRemote::CreateInstance(211    lldb::TargetSP target_sp, ListenerSP listener_sp,212    const FileSpec *crash_file_path, bool can_connect) {213  lldb::ProcessSP process_sp;214  if (crash_file_path == nullptr)215    process_sp = std::shared_ptr<ProcessGDBRemote>(216        new ProcessGDBRemote(target_sp, listener_sp));217  return process_sp;218}219 220void ProcessGDBRemote::DumpPluginHistory(Stream &s) {221  GDBRemoteCommunicationClient &gdb_comm(GetGDBRemote());222  gdb_comm.DumpHistory(s);223}224 225std::chrono::seconds ProcessGDBRemote::GetPacketTimeout() {226  return std::chrono::seconds(GetGlobalPluginProperties().GetPacketTimeout());227}228 229ArchSpec ProcessGDBRemote::GetSystemArchitecture() {230  return m_gdb_comm.GetHostArchitecture();231}232 233bool ProcessGDBRemote::CanDebug(lldb::TargetSP target_sp,234                                bool plugin_specified_by_name) {235  if (plugin_specified_by_name)236    return true;237 238  // For now we are just making sure the file exists for a given module239  Module *exe_module = target_sp->GetExecutableModulePointer();240  if (exe_module) {241    ObjectFile *exe_objfile = exe_module->GetObjectFile();242    // We can't debug core files...243    switch (exe_objfile->GetType()) {244    case ObjectFile::eTypeInvalid:245    case ObjectFile::eTypeCoreFile:246    case ObjectFile::eTypeDebugInfo:247    case ObjectFile::eTypeObjectFile:248    case ObjectFile::eTypeSharedLibrary:249    case ObjectFile::eTypeStubLibrary:250    case ObjectFile::eTypeJIT:251      return false;252    case ObjectFile::eTypeExecutable:253    case ObjectFile::eTypeDynamicLinker:254    case ObjectFile::eTypeUnknown:255      break;256    }257    return FileSystem::Instance().Exists(exe_module->GetFileSpec());258  }259  // However, if there is no executable module, we return true since we might260  // be preparing to attach.261  return true;262}263 264// ProcessGDBRemote constructor265ProcessGDBRemote::ProcessGDBRemote(lldb::TargetSP target_sp,266                                   ListenerSP listener_sp)267    : Process(target_sp, listener_sp),268      m_debugserver_pid(LLDB_INVALID_PROCESS_ID), m_register_info_sp(nullptr),269      m_async_broadcaster(nullptr, "lldb.process.gdb-remote.async-broadcaster"),270      m_async_listener_sp(271          Listener::MakeListener("lldb.process.gdb-remote.async-listener")),272      m_async_thread_state_mutex(), m_thread_ids(), m_thread_pcs(),273      m_jstopinfo_sp(), m_jthreadsinfo_sp(), m_continue_c_tids(),274      m_continue_C_tids(), m_continue_s_tids(), m_continue_S_tids(),275      m_max_memory_size(0), m_remote_stub_max_memory_size(0),276      m_addr_to_mmap_size(), m_thread_create_bp_sp(),277      m_waiting_for_attach(false), m_command_sp(), m_breakpoint_pc_offset(0),278      m_initial_tid(LLDB_INVALID_THREAD_ID), m_allow_flash_writes(false),279      m_erased_flash_ranges(), m_vfork_in_progress_count(0) {280  m_async_broadcaster.SetEventName(eBroadcastBitAsyncThreadShouldExit,281                                   "async thread should exit");282  m_async_broadcaster.SetEventName(eBroadcastBitAsyncContinue,283                                   "async thread continue");284  m_async_broadcaster.SetEventName(eBroadcastBitAsyncThreadDidExit,285                                   "async thread did exit");286 287  Log *log = GetLog(GDBRLog::Async);288 289  const uint32_t async_event_mask =290      eBroadcastBitAsyncContinue | eBroadcastBitAsyncThreadShouldExit;291 292  if (m_async_listener_sp->StartListeningForEvents(293          &m_async_broadcaster, async_event_mask) != async_event_mask) {294    LLDB_LOGF(log,295              "ProcessGDBRemote::%s failed to listen for "296              "m_async_broadcaster events",297              __FUNCTION__);298  }299 300  const uint64_t timeout_seconds =301      GetGlobalPluginProperties().GetPacketTimeout();302  if (timeout_seconds > 0)303    m_gdb_comm.SetPacketTimeout(std::chrono::seconds(timeout_seconds));304 305  m_use_g_packet_for_reading =306      GetGlobalPluginProperties().GetUseGPacketForReading();307}308 309// Destructor310ProcessGDBRemote::~ProcessGDBRemote() {311  //  m_mach_process.UnregisterNotificationCallbacks (this);312  Clear();313  // We need to call finalize on the process before destroying ourselves to314  // make sure all of the broadcaster cleanup goes as planned. If we destruct315  // this class, then Process::~Process() might have problems trying to fully316  // destroy the broadcaster.317  Finalize(true /* destructing */);318 319  // The general Finalize is going to try to destroy the process and that320  // SHOULD shut down the async thread.  However, if we don't kill it it will321  // get stranded and its connection will go away so when it wakes up it will322  // crash.  So kill it for sure here.323  StopAsyncThread();324  KillDebugserverProcess();325}326 327std::shared_ptr<ThreadGDBRemote>328ProcessGDBRemote::CreateThread(lldb::tid_t tid) {329  return std::make_shared<ThreadGDBRemote>(*this, tid);330}331 332bool ProcessGDBRemote::ParsePythonTargetDefinition(333    const FileSpec &target_definition_fspec) {334  ScriptInterpreter *interpreter =335      GetTarget().GetDebugger().GetScriptInterpreter();336  Status error;337  StructuredData::ObjectSP module_object_sp(338      interpreter->LoadPluginModule(target_definition_fspec, error));339  if (module_object_sp) {340    StructuredData::DictionarySP target_definition_sp(341        interpreter->GetDynamicSettings(module_object_sp, &GetTarget(),342                                        "gdb-server-target-definition", error));343 344    if (target_definition_sp) {345      StructuredData::ObjectSP target_object(346          target_definition_sp->GetValueForKey("host-info"));347      if (target_object) {348        if (auto host_info_dict = target_object->GetAsDictionary()) {349          StructuredData::ObjectSP triple_value =350              host_info_dict->GetValueForKey("triple");351          if (auto triple_string_value = triple_value->GetAsString()) {352            std::string triple_string =353                std::string(triple_string_value->GetValue());354            ArchSpec host_arch(triple_string.c_str());355            if (!host_arch.IsCompatibleMatch(GetTarget().GetArchitecture())) {356              GetTarget().SetArchitecture(host_arch);357            }358          }359        }360      }361      m_breakpoint_pc_offset = 0;362      StructuredData::ObjectSP breakpoint_pc_offset_value =363          target_definition_sp->GetValueForKey("breakpoint-pc-offset");364      if (breakpoint_pc_offset_value) {365        if (auto breakpoint_pc_int_value =366                breakpoint_pc_offset_value->GetAsSignedInteger())367          m_breakpoint_pc_offset = breakpoint_pc_int_value->GetValue();368      }369 370      if (m_register_info_sp->SetRegisterInfo(371              *target_definition_sp, GetTarget().GetArchitecture()) > 0) {372        return true;373      }374    }375  }376  return false;377}378 379static size_t SplitCommaSeparatedRegisterNumberString(380    const llvm::StringRef &comma_separated_register_numbers,381    std::vector<uint32_t> &regnums, int base) {382  regnums.clear();383  for (llvm::StringRef x : llvm::split(comma_separated_register_numbers, ',')) {384    uint32_t reg;385    if (llvm::to_integer(x, reg, base))386      regnums.push_back(reg);387  }388  return regnums.size();389}390 391void ProcessGDBRemote::BuildDynamicRegisterInfo(bool force) {392  if (!force && m_register_info_sp)393    return;394 395  m_register_info_sp = std::make_shared<GDBRemoteDynamicRegisterInfo>();396 397  // Check if qHostInfo specified a specific packet timeout for this398  // connection. If so then lets update our setting so the user knows what the399  // timeout is and can see it.400  const auto host_packet_timeout = m_gdb_comm.GetHostDefaultPacketTimeout();401  if (host_packet_timeout > std::chrono::seconds(0)) {402    GetGlobalPluginProperties().SetPacketTimeout(host_packet_timeout.count());403  }404 405  // Register info search order:406  //     1 - Use the target definition python file if one is specified.407  //     2 - If the target definition doesn't have any of the info from the408  //     target.xml (registers) then proceed to read the target.xml.409  //     3 - Fall back on the qRegisterInfo packets.410  //     4 - Use hardcoded defaults if available.411 412  FileSpec target_definition_fspec =413      GetGlobalPluginProperties().GetTargetDefinitionFile();414  if (!FileSystem::Instance().Exists(target_definition_fspec)) {415    // If the filename doesn't exist, it may be a ~ not having been expanded -416    // try to resolve it.417    FileSystem::Instance().Resolve(target_definition_fspec);418  }419  if (target_definition_fspec) {420    // See if we can get register definitions from a python file421    if (ParsePythonTargetDefinition(target_definition_fspec))422      return;423 424    Debugger::ReportError("target description file " +425                              target_definition_fspec.GetPath() +426                              " failed to parse",427                          GetTarget().GetDebugger().GetID());428  }429 430  const ArchSpec &target_arch = GetTarget().GetArchitecture();431  const ArchSpec &remote_host_arch = m_gdb_comm.GetHostArchitecture();432  const ArchSpec &remote_process_arch = m_gdb_comm.GetProcessArchitecture();433 434  // Use the process' architecture instead of the host arch, if available435  ArchSpec arch_to_use;436  if (remote_process_arch.IsValid())437    arch_to_use = remote_process_arch;438  else439    arch_to_use = remote_host_arch;440 441  if (!arch_to_use.IsValid())442    arch_to_use = target_arch;443 444  if (GetGDBServerRegisterInfo(arch_to_use))445    return;446 447  char packet[128];448  std::vector<DynamicRegisterInfo::Register> registers;449  uint32_t reg_num = 0;450  for (StringExtractorGDBRemote::ResponseType response_type =451           StringExtractorGDBRemote::eResponse;452       response_type == StringExtractorGDBRemote::eResponse; ++reg_num) {453    const int packet_len =454        ::snprintf(packet, sizeof(packet), "qRegisterInfo%x", reg_num);455    assert(packet_len < (int)sizeof(packet));456    UNUSED_IF_ASSERT_DISABLED(packet_len);457    StringExtractorGDBRemote response;458    if (m_gdb_comm.SendPacketAndWaitForResponse(packet, response) ==459        GDBRemoteCommunication::PacketResult::Success) {460      response_type = response.GetResponseType();461      if (response_type == StringExtractorGDBRemote::eResponse) {462        llvm::StringRef name;463        llvm::StringRef value;464        DynamicRegisterInfo::Register reg_info;465 466        while (response.GetNameColonValue(name, value)) {467          if (name == "name") {468            reg_info.name.SetString(value);469          } else if (name == "alt-name") {470            reg_info.alt_name.SetString(value);471          } else if (name == "bitsize") {472            if (!value.getAsInteger(0, reg_info.byte_size))473              reg_info.byte_size /= CHAR_BIT;474          } else if (name == "offset") {475            value.getAsInteger(0, reg_info.byte_offset);476          } else if (name == "encoding") {477            const Encoding encoding = Args::StringToEncoding(value);478            if (encoding != eEncodingInvalid)479              reg_info.encoding = encoding;480          } else if (name == "format") {481            if (!OptionArgParser::ToFormat(value.str().c_str(), reg_info.format, nullptr)482                    .Success())483              reg_info.format =484                  llvm::StringSwitch<Format>(value)485                      .Case("boolean", eFormatBoolean)486                      .Case("binary", eFormatBinary)487                      .Case("bytes", eFormatBytes)488                      .Case("bytes-with-ascii", eFormatBytesWithASCII)489                      .Case("char", eFormatChar)490                      .Case("char-printable", eFormatCharPrintable)491                      .Case("complex", eFormatComplex)492                      .Case("cstring", eFormatCString)493                      .Case("decimal", eFormatDecimal)494                      .Case("enum", eFormatEnum)495                      .Case("hex", eFormatHex)496                      .Case("hex-uppercase", eFormatHexUppercase)497                      .Case("float", eFormatFloat)498                      .Case("octal", eFormatOctal)499                      .Case("ostype", eFormatOSType)500                      .Case("unicode16", eFormatUnicode16)501                      .Case("unicode32", eFormatUnicode32)502                      .Case("unsigned", eFormatUnsigned)503                      .Case("pointer", eFormatPointer)504                      .Case("vector-char", eFormatVectorOfChar)505                      .Case("vector-sint64", eFormatVectorOfSInt64)506                      .Case("vector-float16", eFormatVectorOfFloat16)507                      .Case("vector-float64", eFormatVectorOfFloat64)508                      .Case("vector-sint8", eFormatVectorOfSInt8)509                      .Case("vector-uint8", eFormatVectorOfUInt8)510                      .Case("vector-sint16", eFormatVectorOfSInt16)511                      .Case("vector-uint16", eFormatVectorOfUInt16)512                      .Case("vector-sint32", eFormatVectorOfSInt32)513                      .Case("vector-uint32", eFormatVectorOfUInt32)514                      .Case("vector-float32", eFormatVectorOfFloat32)515                      .Case("vector-uint64", eFormatVectorOfUInt64)516                      .Case("vector-uint128", eFormatVectorOfUInt128)517                      .Case("complex-integer", eFormatComplexInteger)518                      .Case("char-array", eFormatCharArray)519                      .Case("address-info", eFormatAddressInfo)520                      .Case("hex-float", eFormatHexFloat)521                      .Case("instruction", eFormatInstruction)522                      .Case("void", eFormatVoid)523                      .Case("unicode8", eFormatUnicode8)524                      .Case("float128", eFormatFloat128)525                      .Default(eFormatInvalid);526          } else if (name == "set") {527            reg_info.set_name.SetString(value);528          } else if (name == "gcc" || name == "ehframe") {529            value.getAsInteger(0, reg_info.regnum_ehframe);530          } else if (name == "dwarf") {531            value.getAsInteger(0, reg_info.regnum_dwarf);532          } else if (name == "generic") {533            reg_info.regnum_generic = Args::StringToGenericRegister(value);534          } else if (name == "container-regs") {535            SplitCommaSeparatedRegisterNumberString(value, reg_info.value_regs, 16);536          } else if (name == "invalidate-regs") {537            SplitCommaSeparatedRegisterNumberString(value, reg_info.invalidate_regs, 16);538          }539        }540 541        assert(reg_info.byte_size != 0);542        registers.push_back(reg_info);543      } else {544        break; // ensure exit before reg_num is incremented545      }546    } else {547      break;548    }549  }550 551  if (registers.empty())552    registers = GetFallbackRegisters(arch_to_use);553 554  AddRemoteRegisters(registers, arch_to_use);555}556 557Status ProcessGDBRemote::DoWillLaunch(lldb_private::Module *module) {558  return WillLaunchOrAttach();559}560 561Status ProcessGDBRemote::DoWillAttachToProcessWithID(lldb::pid_t pid) {562  return WillLaunchOrAttach();563}564 565Status ProcessGDBRemote::DoWillAttachToProcessWithName(const char *process_name,566                                                       bool wait_for_launch) {567  return WillLaunchOrAttach();568}569 570Status ProcessGDBRemote::DoConnectRemote(llvm::StringRef remote_url) {571  Log *log = GetLog(GDBRLog::Process);572 573  Status error(WillLaunchOrAttach());574  if (error.Fail())575    return error;576 577  error = ConnectToDebugserver(remote_url);578  if (error.Fail())579    return error;580 581  StartAsyncThread();582 583  lldb::pid_t pid = m_gdb_comm.GetCurrentProcessID();584  if (pid == LLDB_INVALID_PROCESS_ID) {585    // We don't have a valid process ID, so note that we are connected and586    // could now request to launch or attach, or get remote process listings...587    SetPrivateState(eStateConnected);588  } else {589    // We have a valid process590    SetID(pid);591    GetThreadList();592    StringExtractorGDBRemote response;593    if (m_gdb_comm.GetStopReply(response)) {594      SetLastStopPacket(response);595 596      Target &target = GetTarget();597      if (!target.GetArchitecture().IsValid()) {598        if (m_gdb_comm.GetProcessArchitecture().IsValid()) {599          target.SetArchitecture(m_gdb_comm.GetProcessArchitecture());600        } else {601          if (m_gdb_comm.GetHostArchitecture().IsValid()) {602            target.SetArchitecture(m_gdb_comm.GetHostArchitecture());603          }604        }605      }606 607      const StateType state = SetThreadStopInfo(response);608      if (state != eStateInvalid) {609        SetPrivateState(state);610      } else611        error = Status::FromErrorStringWithFormat(612            "Process %" PRIu64 " was reported after connecting to "613            "'%s', but state was not stopped: %s",614            pid, remote_url.str().c_str(), StateAsCString(state));615    } else616      error = Status::FromErrorStringWithFormat(617          "Process %" PRIu64 " was reported after connecting to '%s', "618          "but no stop reply packet was received",619          pid, remote_url.str().c_str());620  }621 622  LLDB_LOGF(log,623            "ProcessGDBRemote::%s pid %" PRIu64624            ": normalizing target architecture initial triple: %s "625            "(GetTarget().GetArchitecture().IsValid() %s, "626            "m_gdb_comm.GetHostArchitecture().IsValid(): %s)",627            __FUNCTION__, GetID(),628            GetTarget().GetArchitecture().GetTriple().getTriple().c_str(),629            GetTarget().GetArchitecture().IsValid() ? "true" : "false",630            m_gdb_comm.GetHostArchitecture().IsValid() ? "true" : "false");631 632  if (error.Success() && !GetTarget().GetArchitecture().IsValid() &&633      m_gdb_comm.GetHostArchitecture().IsValid()) {634    // Prefer the *process'* architecture over that of the *host*, if635    // available.636    if (m_gdb_comm.GetProcessArchitecture().IsValid())637      GetTarget().SetArchitecture(m_gdb_comm.GetProcessArchitecture());638    else639      GetTarget().SetArchitecture(m_gdb_comm.GetHostArchitecture());640  }641 642  LLDB_LOGF(log,643            "ProcessGDBRemote::%s pid %" PRIu64644            ": normalized target architecture triple: %s",645            __FUNCTION__, GetID(),646            GetTarget().GetArchitecture().GetTriple().getTriple().c_str());647 648  return error;649}650 651Status ProcessGDBRemote::WillLaunchOrAttach() {652  Status error;653  m_stdio_communication.Clear();654  return error;655}656 657// Process Control658Status ProcessGDBRemote::DoLaunch(lldb_private::Module *exe_module,659                                  ProcessLaunchInfo &launch_info) {660  Log *log = GetLog(GDBRLog::Process);661  Status error;662 663  LLDB_LOGF(log, "ProcessGDBRemote::%s() entered", __FUNCTION__);664 665  uint32_t launch_flags = launch_info.GetFlags().Get();666  FileSpec stdin_file_spec{};667  FileSpec stdout_file_spec{};668  FileSpec stderr_file_spec{};669  FileSpec working_dir = launch_info.GetWorkingDirectory();670 671  const FileAction *file_action;672  file_action = launch_info.GetFileActionForFD(STDIN_FILENO);673  if (file_action) {674    if (file_action->GetAction() == FileAction::eFileActionOpen)675      stdin_file_spec = file_action->GetFileSpec();676  }677  file_action = launch_info.GetFileActionForFD(STDOUT_FILENO);678  if (file_action) {679    if (file_action->GetAction() == FileAction::eFileActionOpen)680      stdout_file_spec = file_action->GetFileSpec();681  }682  file_action = launch_info.GetFileActionForFD(STDERR_FILENO);683  if (file_action) {684    if (file_action->GetAction() == FileAction::eFileActionOpen)685      stderr_file_spec = file_action->GetFileSpec();686  }687 688  if (log) {689    if (stdin_file_spec || stdout_file_spec || stderr_file_spec)690      LLDB_LOGF(log,691                "ProcessGDBRemote::%s provided with STDIO paths via "692                "launch_info: stdin=%s, stdout=%s, stderr=%s",693                __FUNCTION__,694                stdin_file_spec ? stdin_file_spec.GetPath().c_str() : "<null>",695                stdout_file_spec ? stdout_file_spec.GetPath().c_str() : "<null>",696                stderr_file_spec ? stderr_file_spec.GetPath().c_str() : "<null>");697    else698      LLDB_LOGF(log,699                "ProcessGDBRemote::%s no STDIO paths given via launch_info",700                __FUNCTION__);701  }702 703  const bool disable_stdio = (launch_flags & eLaunchFlagDisableSTDIO) != 0;704  if (stdin_file_spec || disable_stdio) {705    // the inferior will be reading stdin from the specified file or stdio is706    // completely disabled707    m_stdin_forward = false;708  } else {709    m_stdin_forward = true;710  }711 712  //  ::LogSetBitMask (GDBR_LOG_DEFAULT);713  //  ::LogSetOptions (LLDB_LOG_OPTION_THREADSAFE |714  //  LLDB_LOG_OPTION_PREPEND_TIMESTAMP |715  //  LLDB_LOG_OPTION_PREPEND_PROC_AND_THREAD);716  //  ::LogSetLogFile ("/dev/stdout");717 718  error = EstablishConnectionIfNeeded(launch_info);719  if (error.Success()) {720    PseudoTerminal pty;721    const bool disable_stdio = (launch_flags & eLaunchFlagDisableSTDIO) != 0;722 723    PlatformSP platform_sp(GetTarget().GetPlatform());724    if (disable_stdio) {725      // set to /dev/null unless redirected to a file above726      if (!stdin_file_spec)727        stdin_file_spec.SetFile(FileSystem::DEV_NULL,728                                FileSpec::Style::native);729      if (!stdout_file_spec)730        stdout_file_spec.SetFile(FileSystem::DEV_NULL,731                                 FileSpec::Style::native);732      if (!stderr_file_spec)733        stderr_file_spec.SetFile(FileSystem::DEV_NULL,734                                 FileSpec::Style::native);735    } else if (platform_sp && platform_sp->IsHost()) {736      // If the debugserver is local and we aren't disabling STDIO, lets use737      // a pseudo terminal to instead of relying on the 'O' packets for stdio738      // since 'O' packets can really slow down debugging if the inferior739      // does a lot of output.740      if ((!stdin_file_spec || !stdout_file_spec || !stderr_file_spec) &&741          !errorToBool(pty.OpenFirstAvailablePrimary(O_RDWR | O_NOCTTY))) {742        FileSpec secondary_name(pty.GetSecondaryName());743 744        if (!stdin_file_spec)745          stdin_file_spec = secondary_name;746 747        if (!stdout_file_spec)748          stdout_file_spec = secondary_name;749 750        if (!stderr_file_spec)751          stderr_file_spec = secondary_name;752      }753      LLDB_LOGF(754          log,755          "ProcessGDBRemote::%s adjusted STDIO paths for local platform "756          "(IsHost() is true) using secondary: stdin=%s, stdout=%s, "757          "stderr=%s",758          __FUNCTION__,759          stdin_file_spec ? stdin_file_spec.GetPath().c_str() : "<null>",760          stdout_file_spec ? stdout_file_spec.GetPath().c_str() : "<null>",761          stderr_file_spec ? stderr_file_spec.GetPath().c_str() : "<null>");762    }763 764    LLDB_LOGF(log,765              "ProcessGDBRemote::%s final STDIO paths after all "766              "adjustments: stdin=%s, stdout=%s, stderr=%s",767              __FUNCTION__,768              stdin_file_spec ? stdin_file_spec.GetPath().c_str() : "<null>",769              stdout_file_spec ? stdout_file_spec.GetPath().c_str() : "<null>",770              stderr_file_spec ? stderr_file_spec.GetPath().c_str() : "<null>");771 772    if (stdin_file_spec)773      m_gdb_comm.SetSTDIN(stdin_file_spec);774    if (stdout_file_spec)775      m_gdb_comm.SetSTDOUT(stdout_file_spec);776    if (stderr_file_spec)777      m_gdb_comm.SetSTDERR(stderr_file_spec);778 779    m_gdb_comm.SetDisableASLR(launch_flags & eLaunchFlagDisableASLR);780    m_gdb_comm.SetDetachOnError(launch_flags & eLaunchFlagDetachOnError);781 782    m_gdb_comm.SendLaunchArchPacket(783        GetTarget().GetArchitecture().GetArchitectureName());784 785    const char *launch_event_data = launch_info.GetLaunchEventData();786    if (launch_event_data != nullptr && *launch_event_data != '\0')787      m_gdb_comm.SendLaunchEventDataPacket(launch_event_data);788 789    if (working_dir) {790      m_gdb_comm.SetWorkingDir(working_dir);791    }792 793    // Send the environment and the program + arguments after we connect794    m_gdb_comm.SendEnvironment(launch_info.GetEnvironment());795 796    {797      // Scope for the scoped timeout object798      GDBRemoteCommunication::ScopedTimeout timeout(m_gdb_comm,799                                                    std::chrono::seconds(10));800 801      // Since we can't send argv0 separate from the executable path, we need to802      // make sure to use the actual executable path found in the launch_info...803      Args args = launch_info.GetArguments();804      if (FileSpec exe_file = launch_info.GetExecutableFile())805        args.ReplaceArgumentAtIndex(0, exe_file.GetPath(false));806      if (llvm::Error err = m_gdb_comm.LaunchProcess(args)) {807        error = Status::FromErrorStringWithFormatv(808            "Cannot launch '{0}': {1}", args.GetArgumentAtIndex(0),809            llvm::fmt_consume(std::move(err)));810      } else {811        SetID(m_gdb_comm.GetCurrentProcessID());812      }813    }814 815    if (GetID() == LLDB_INVALID_PROCESS_ID) {816      LLDB_LOGF(log, "failed to connect to debugserver: %s",817                error.AsCString());818      KillDebugserverProcess();819      return error;820    }821 822    StringExtractorGDBRemote response;823    if (m_gdb_comm.GetStopReply(response)) {824      SetLastStopPacket(response);825 826      const ArchSpec &process_arch = m_gdb_comm.GetProcessArchitecture();827 828      if (process_arch.IsValid()) {829        GetTarget().MergeArchitecture(process_arch);830      } else {831        const ArchSpec &host_arch = m_gdb_comm.GetHostArchitecture();832        if (host_arch.IsValid())833          GetTarget().MergeArchitecture(host_arch);834      }835 836      SetPrivateState(SetThreadStopInfo(response));837 838      if (!disable_stdio) {839        if (pty.GetPrimaryFileDescriptor() != PseudoTerminal::invalid_fd)840          SetSTDIOFileDescriptor(pty.ReleasePrimaryFileDescriptor());841      }842    }843  } else {844    LLDB_LOGF(log, "failed to connect to debugserver: %s", error.AsCString());845  }846  return error;847}848 849Status ProcessGDBRemote::ConnectToDebugserver(llvm::StringRef connect_url) {850  Status error;851  // Only connect if we have a valid connect URL852  Log *log = GetLog(GDBRLog::Process);853 854  if (!connect_url.empty()) {855    LLDB_LOGF(log, "ProcessGDBRemote::%s Connecting to %s", __FUNCTION__,856              connect_url.str().c_str());857    std::unique_ptr<ConnectionFileDescriptor> conn_up(858        new ConnectionFileDescriptor());859    if (conn_up) {860      const uint32_t max_retry_count = 50;861      uint32_t retry_count = 0;862      while (!m_gdb_comm.IsConnected()) {863        if (conn_up->Connect(connect_url, &error) == eConnectionStatusSuccess) {864          m_gdb_comm.SetConnection(std::move(conn_up));865          break;866        }867 868        retry_count++;869 870        if (retry_count >= max_retry_count)871          break;872 873        std::this_thread::sleep_for(std::chrono::milliseconds(100));874      }875    }876  }877 878  if (!m_gdb_comm.IsConnected()) {879    if (error.Success())880      error = Status::FromErrorString("not connected to remote gdb server");881    return error;882  }883 884  // We always seem to be able to open a connection to a local port so we need885  // to make sure we can then send data to it. If we can't then we aren't886  // actually connected to anything, so try and do the handshake with the887  // remote GDB server and make sure that goes alright.888  if (!m_gdb_comm.HandshakeWithServer(&error)) {889    m_gdb_comm.Disconnect();890    if (error.Success())891      error = Status::FromErrorString("not connected to remote gdb server");892    return error;893  }894 895  m_gdb_comm.GetEchoSupported();896  m_gdb_comm.GetThreadSuffixSupported();897  m_gdb_comm.GetListThreadsInStopReplySupported();898  m_gdb_comm.GetHostInfo();899  m_gdb_comm.GetVContSupported('c');900  m_gdb_comm.GetVAttachOrWaitSupported();901  m_gdb_comm.EnableErrorStringInPacket();902 903  // First dispatch any commands from the platform:904  auto handle_cmds = [&] (const Args &args) ->  void {905    for (const Args::ArgEntry &entry : args) {906      StringExtractorGDBRemote response;907      m_gdb_comm.SendPacketAndWaitForResponse(908          entry.c_str(), response);909    }910  };911 912  PlatformSP platform_sp = GetTarget().GetPlatform();913  if (platform_sp) {914    handle_cmds(platform_sp->GetExtraStartupCommands());915  }916 917  // Then dispatch any process commands:918  handle_cmds(GetExtraStartupCommands());919 920  return error;921}922 923void ProcessGDBRemote::DidLaunchOrAttach(ArchSpec &process_arch) {924  Log *log = GetLog(GDBRLog::Process);925  BuildDynamicRegisterInfo(false);926 927  // See if the GDB server supports qHostInfo or qProcessInfo packets. Prefer928  // qProcessInfo as it will be more specific to our process.929 930  const ArchSpec &remote_process_arch = m_gdb_comm.GetProcessArchitecture();931  if (remote_process_arch.IsValid()) {932    process_arch = remote_process_arch;933    LLDB_LOG(log, "gdb-remote had process architecture, using {0} {1}",934             process_arch.GetArchitectureName(),935             process_arch.GetTriple().getTriple());936  } else {937    process_arch = m_gdb_comm.GetHostArchitecture();938    LLDB_LOG(log,939             "gdb-remote did not have process architecture, using gdb-remote "940             "host architecture {0} {1}",941             process_arch.GetArchitectureName(),942             process_arch.GetTriple().getTriple());943  }944 945  AddressableBits addressable_bits = m_gdb_comm.GetAddressableBits();946  SetAddressableBitMasks(addressable_bits);947 948  if (process_arch.IsValid()) {949    const ArchSpec &target_arch = GetTarget().GetArchitecture();950    if (target_arch.IsValid()) {951      LLDB_LOG(log, "analyzing target arch, currently {0} {1}",952               target_arch.GetArchitectureName(),953               target_arch.GetTriple().getTriple());954 955      // If the remote host is ARM and we have apple as the vendor, then956      // ARM executables and shared libraries can have mixed ARM957      // architectures.958      // You can have an armv6 executable, and if the host is armv7, then the959      // system will load the best possible architecture for all shared960      // libraries it has, so we really need to take the remote host961      // architecture as our defacto architecture in this case.962 963      if ((process_arch.GetMachine() == llvm::Triple::arm ||964           process_arch.GetMachine() == llvm::Triple::thumb) &&965          process_arch.GetTriple().getVendor() == llvm::Triple::Apple) {966        GetTarget().SetArchitecture(process_arch);967        LLDB_LOG(log,968                 "remote process is ARM/Apple, "969                 "setting target arch to {0} {1}",970                 process_arch.GetArchitectureName(),971                 process_arch.GetTriple().getTriple());972      } else {973        // Fill in what is missing in the triple974        const llvm::Triple &remote_triple = process_arch.GetTriple();975        llvm::Triple new_target_triple = target_arch.GetTriple();976        if (new_target_triple.getVendorName().size() == 0) {977          new_target_triple.setVendor(remote_triple.getVendor());978 979          if (new_target_triple.getOSName().size() == 0) {980            new_target_triple.setOS(remote_triple.getOS());981 982            if (new_target_triple.getEnvironmentName().size() == 0)983              new_target_triple.setEnvironment(remote_triple.getEnvironment());984          }985 986          ArchSpec new_target_arch = target_arch;987          new_target_arch.SetTriple(new_target_triple);988          GetTarget().SetArchitecture(new_target_arch);989        }990      }991 992      LLDB_LOG(log,993               "final target arch after adjustments for remote architecture: "994               "{0} {1}",995               target_arch.GetArchitectureName(),996               target_arch.GetTriple().getTriple());997    } else {998      // The target doesn't have a valid architecture yet, set it from the999      // architecture we got from the remote GDB server1000      GetTarget().SetArchitecture(process_arch);1001    }1002  }1003 1004  // Target and Process are reasonably initailized;1005  // load any binaries we have metadata for / set load address.1006  LoadStubBinaries();1007  MaybeLoadExecutableModule();1008 1009  // Find out which StructuredDataPlugins are supported by the debug monitor.1010  // These plugins transmit data over async $J packets.1011  if (StructuredData::Array *supported_packets =1012          m_gdb_comm.GetSupportedStructuredDataPlugins())1013    MapSupportedStructuredDataPlugins(*supported_packets);1014 1015  // If connected to LLDB ("native-signals+"), use signal defs for1016  // the remote platform.  If connected to GDB, just use the standard set.1017  if (!m_gdb_comm.UsesNativeSignals()) {1018    SetUnixSignals(std::make_shared<GDBRemoteSignals>());1019  } else {1020    PlatformSP platform_sp = GetTarget().GetPlatform();1021    if (platform_sp && platform_sp->IsConnected())1022      SetUnixSignals(platform_sp->GetUnixSignals());1023    else1024      SetUnixSignals(UnixSignals::Create(GetTarget().GetArchitecture()));1025  }1026}1027 1028void ProcessGDBRemote::LoadStubBinaries() {1029  // The remote stub may know about the "main binary" in1030  // the context of a firmware debug session, and can1031  // give us a UUID and an address/slide of where the1032  // binary is loaded in memory.1033  UUID standalone_uuid;1034  addr_t standalone_value;1035  bool standalone_value_is_offset;1036  if (m_gdb_comm.GetProcessStandaloneBinary(standalone_uuid, standalone_value,1037                                            standalone_value_is_offset)) {1038    ModuleSP module_sp;1039 1040    if (standalone_uuid.IsValid()) {1041      const bool force_symbol_search = true;1042      const bool notify = true;1043      const bool set_address_in_target = true;1044      const bool allow_memory_image_last_resort = false;1045      DynamicLoader::LoadBinaryWithUUIDAndAddress(1046          this, "", standalone_uuid, standalone_value,1047          standalone_value_is_offset, force_symbol_search, notify,1048          set_address_in_target, allow_memory_image_last_resort);1049    }1050  }1051 1052  // The remote stub may know about a list of binaries to1053  // force load into the process -- a firmware type situation1054  // where multiple binaries are present in virtual memory,1055  // and we are only given the addresses of the binaries.1056  // Not intended for use with userland debugging, when we use1057  // a DynamicLoader plugin that knows how to find the loaded1058  // binaries, and will track updates as binaries are added.1059 1060  std::vector<addr_t> bin_addrs = m_gdb_comm.GetProcessStandaloneBinaries();1061  if (bin_addrs.size()) {1062    UUID uuid;1063    const bool value_is_slide = false;1064    for (addr_t addr : bin_addrs) {1065      const bool notify = true;1066      // First see if this is a special platform1067      // binary that may determine the DynamicLoader and1068      // Platform to be used in this Process and Target.1069      if (GetTarget()1070              .GetDebugger()1071              .GetPlatformList()1072              .LoadPlatformBinaryAndSetup(this, addr, notify))1073        continue;1074 1075      const bool force_symbol_search = true;1076      const bool set_address_in_target = true;1077      const bool allow_memory_image_last_resort = false;1078      // Second manually load this binary into the Target.1079      DynamicLoader::LoadBinaryWithUUIDAndAddress(1080          this, llvm::StringRef(), uuid, addr, value_is_slide,1081          force_symbol_search, notify, set_address_in_target,1082          allow_memory_image_last_resort);1083    }1084  }1085}1086 1087void ProcessGDBRemote::MaybeLoadExecutableModule() {1088  ModuleSP module_sp = GetTarget().GetExecutableModule();1089  if (!module_sp)1090    return;1091 1092  std::optional<QOffsets> offsets = m_gdb_comm.GetQOffsets();1093  if (!offsets)1094    return;1095 1096  bool is_uniform =1097      size_t(llvm::count(offsets->offsets, offsets->offsets[0])) ==1098      offsets->offsets.size();1099  if (!is_uniform)1100    return; // TODO: Handle non-uniform responses.1101 1102  bool changed = false;1103  module_sp->SetLoadAddress(GetTarget(), offsets->offsets[0],1104                            /*value_is_offset=*/true, changed);1105  if (changed) {1106    ModuleList list;1107    list.Append(module_sp);1108    m_process->GetTarget().ModulesDidLoad(list);1109  }1110}1111 1112void ProcessGDBRemote::DidLaunch() {1113  ArchSpec process_arch;1114  DidLaunchOrAttach(process_arch);1115}1116 1117Status ProcessGDBRemote::DoAttachToProcessWithID(1118    lldb::pid_t attach_pid, const ProcessAttachInfo &attach_info) {1119  Log *log = GetLog(GDBRLog::Process);1120  Status error;1121 1122  LLDB_LOGF(log, "ProcessGDBRemote::%s()", __FUNCTION__);1123 1124  // Clear out and clean up from any current state1125  Clear();1126  if (attach_pid != LLDB_INVALID_PROCESS_ID) {1127    error = EstablishConnectionIfNeeded(attach_info);1128    if (error.Success()) {1129      m_gdb_comm.SetDetachOnError(attach_info.GetDetachOnError());1130 1131      char packet[64];1132      const int packet_len =1133          ::snprintf(packet, sizeof(packet), "vAttach;%" PRIx64, attach_pid);1134      SetID(attach_pid);1135      auto data_sp =1136          std::make_shared<EventDataBytes>(llvm::StringRef(packet, packet_len));1137      m_async_broadcaster.BroadcastEvent(eBroadcastBitAsyncContinue, data_sp);1138    } else1139      SetExitStatus(-1, error.AsCString());1140  }1141 1142  return error;1143}1144 1145Status ProcessGDBRemote::DoAttachToProcessWithName(1146    const char *process_name, const ProcessAttachInfo &attach_info) {1147  Status error;1148  // Clear out and clean up from any current state1149  Clear();1150 1151  if (process_name && process_name[0]) {1152    error = EstablishConnectionIfNeeded(attach_info);1153    if (error.Success()) {1154      StreamString packet;1155 1156      m_gdb_comm.SetDetachOnError(attach_info.GetDetachOnError());1157 1158      if (attach_info.GetWaitForLaunch()) {1159        if (!m_gdb_comm.GetVAttachOrWaitSupported()) {1160          packet.PutCString("vAttachWait");1161        } else {1162          if (attach_info.GetIgnoreExisting())1163            packet.PutCString("vAttachWait");1164          else1165            packet.PutCString("vAttachOrWait");1166        }1167      } else1168        packet.PutCString("vAttachName");1169      packet.PutChar(';');1170      packet.PutBytesAsRawHex8(process_name, strlen(process_name),1171                               endian::InlHostByteOrder(),1172                               endian::InlHostByteOrder());1173 1174      auto data_sp = std::make_shared<EventDataBytes>(packet.GetString());1175      m_async_broadcaster.BroadcastEvent(eBroadcastBitAsyncContinue, data_sp);1176 1177    } else1178      SetExitStatus(-1, error.AsCString());1179  }1180  return error;1181}1182 1183llvm::Expected<TraceSupportedResponse> ProcessGDBRemote::TraceSupported() {1184  return m_gdb_comm.SendTraceSupported(GetInterruptTimeout());1185}1186 1187llvm::Error ProcessGDBRemote::TraceStop(const TraceStopRequest &request) {1188  return m_gdb_comm.SendTraceStop(request, GetInterruptTimeout());1189}1190 1191llvm::Error ProcessGDBRemote::TraceStart(const llvm::json::Value &request) {1192  return m_gdb_comm.SendTraceStart(request, GetInterruptTimeout());1193}1194 1195llvm::Expected<std::string>1196ProcessGDBRemote::TraceGetState(llvm::StringRef type) {1197  return m_gdb_comm.SendTraceGetState(type, GetInterruptTimeout());1198}1199 1200llvm::Expected<std::vector<uint8_t>>1201ProcessGDBRemote::TraceGetBinaryData(const TraceGetBinaryDataRequest &request) {1202  return m_gdb_comm.SendTraceGetBinaryData(request, GetInterruptTimeout());1203}1204 1205void ProcessGDBRemote::DidExit() {1206  // When we exit, disconnect from the GDB server communications1207  m_gdb_comm.Disconnect();1208}1209 1210void ProcessGDBRemote::DidAttach(ArchSpec &process_arch) {1211  // If you can figure out what the architecture is, fill it in here.1212  process_arch.Clear();1213  DidLaunchOrAttach(process_arch);1214}1215 1216Status ProcessGDBRemote::WillResume() {1217  m_continue_c_tids.clear();1218  m_continue_C_tids.clear();1219  m_continue_s_tids.clear();1220  m_continue_S_tids.clear();1221  m_jstopinfo_sp.reset();1222  m_jthreadsinfo_sp.reset();1223  return Status();1224}1225 1226bool ProcessGDBRemote::SupportsReverseDirection() {1227  return m_gdb_comm.GetReverseStepSupported() ||1228         m_gdb_comm.GetReverseContinueSupported();1229}1230 1231Status ProcessGDBRemote::DoResume(RunDirection direction) {1232  Status error;1233  Log *log = GetLog(GDBRLog::Process);1234  LLDB_LOGF(log, "ProcessGDBRemote::Resume(%s)",1235            direction == RunDirection::eRunForward ? "" : "reverse");1236 1237  ListenerSP listener_sp(1238      Listener::MakeListener("gdb-remote.resume-packet-sent"));1239  if (listener_sp->StartListeningForEvents(1240          &m_gdb_comm, GDBRemoteClientBase::eBroadcastBitRunPacketSent)) {1241    listener_sp->StartListeningForEvents(1242        &m_async_broadcaster,1243        ProcessGDBRemote::eBroadcastBitAsyncThreadDidExit);1244 1245    const size_t num_threads = GetThreadList().GetSize();1246 1247    StreamString continue_packet;1248    bool continue_packet_error = false;1249    // Number of threads continuing with "c", i.e. continuing without a signal1250    // to deliver.1251    const size_t num_continue_c_tids = m_continue_c_tids.size();1252    // Number of threads continuing with "C", i.e. continuing with a signal to1253    // deliver.1254    const size_t num_continue_C_tids = m_continue_C_tids.size();1255    // Number of threads continuing with "s", i.e. single-stepping.1256    const size_t num_continue_s_tids = m_continue_s_tids.size();1257    // Number of threads continuing with "S", i.e. single-stepping with a signal1258    // to deliver.1259    const size_t num_continue_S_tids = m_continue_S_tids.size();1260    if (direction == RunDirection::eRunForward &&1261        m_gdb_comm.HasAnyVContSupport()) {1262      std::string pid_prefix;1263      if (m_gdb_comm.GetMultiprocessSupported())1264        pid_prefix = llvm::formatv("p{0:x-}.", GetID());1265 1266      if (num_continue_c_tids == num_threads ||1267          (m_continue_c_tids.empty() && m_continue_C_tids.empty() &&1268           m_continue_s_tids.empty() && m_continue_S_tids.empty())) {1269        // All threads are continuing1270        if (m_gdb_comm.GetMultiprocessSupported())1271          continue_packet.Format("vCont;c:{0}-1", pid_prefix);1272        else1273          continue_packet.PutCString("c");1274      } else {1275        continue_packet.PutCString("vCont");1276 1277        if (!m_continue_c_tids.empty()) {1278          if (m_gdb_comm.GetVContSupported('c')) {1279            for (tid_collection::const_iterator1280                     t_pos = m_continue_c_tids.begin(),1281                     t_end = m_continue_c_tids.end();1282                 t_pos != t_end; ++t_pos)1283              continue_packet.Format(";c:{0}{1:x-}", pid_prefix, *t_pos);1284          } else1285            continue_packet_error = true;1286        }1287 1288        if (!continue_packet_error && !m_continue_C_tids.empty()) {1289          if (m_gdb_comm.GetVContSupported('C')) {1290            for (tid_sig_collection::const_iterator1291                     s_pos = m_continue_C_tids.begin(),1292                     s_end = m_continue_C_tids.end();1293                 s_pos != s_end; ++s_pos)1294              continue_packet.Format(";C{0:x-2}:{1}{2:x-}", s_pos->second,1295                                     pid_prefix, s_pos->first);1296          } else1297            continue_packet_error = true;1298        }1299 1300        if (!continue_packet_error && !m_continue_s_tids.empty()) {1301          if (m_gdb_comm.GetVContSupported('s')) {1302            for (tid_collection::const_iterator1303                     t_pos = m_continue_s_tids.begin(),1304                     t_end = m_continue_s_tids.end();1305                 t_pos != t_end; ++t_pos)1306              continue_packet.Format(";s:{0}{1:x-}", pid_prefix, *t_pos);1307          } else1308            continue_packet_error = true;1309        }1310 1311        if (!continue_packet_error && !m_continue_S_tids.empty()) {1312          if (m_gdb_comm.GetVContSupported('S')) {1313            for (tid_sig_collection::const_iterator1314                     s_pos = m_continue_S_tids.begin(),1315                     s_end = m_continue_S_tids.end();1316                 s_pos != s_end; ++s_pos)1317              continue_packet.Format(";S{0:x-2}:{1}{2:x-}", s_pos->second,1318                                     pid_prefix, s_pos->first);1319          } else1320            continue_packet_error = true;1321        }1322 1323        if (continue_packet_error)1324          continue_packet.Clear();1325      }1326    } else1327      continue_packet_error = true;1328 1329    if (direction == RunDirection::eRunForward && continue_packet_error) {1330      // Either no vCont support, or we tried to use part of the vCont packet1331      // that wasn't supported by the remote GDB server. We need to try and1332      // make a simple packet that can do our continue.1333      if (num_continue_c_tids > 0) {1334        if (num_continue_c_tids == num_threads) {1335          // All threads are resuming...1336          m_gdb_comm.SetCurrentThreadForRun(-1);1337          continue_packet.PutChar('c');1338          continue_packet_error = false;1339        } else if (num_continue_c_tids == 1 && num_continue_C_tids == 0 &&1340                   num_continue_s_tids == 0 && num_continue_S_tids == 0) {1341          // Only one thread is continuing1342          m_gdb_comm.SetCurrentThreadForRun(m_continue_c_tids.front());1343          continue_packet.PutChar('c');1344          continue_packet_error = false;1345        }1346      }1347 1348      if (continue_packet_error && num_continue_C_tids > 0) {1349        if ((num_continue_C_tids + num_continue_c_tids) == num_threads &&1350            num_continue_C_tids > 0 && num_continue_s_tids == 0 &&1351            num_continue_S_tids == 0) {1352          const int continue_signo = m_continue_C_tids.front().second;1353          // Only one thread is continuing1354          if (num_continue_C_tids > 1) {1355            // More that one thread with a signal, yet we don't have vCont1356            // support and we are being asked to resume each thread with a1357            // signal, we need to make sure they are all the same signal, or we1358            // can't issue the continue accurately with the current support...1359            if (num_continue_C_tids > 1) {1360              continue_packet_error = false;1361              for (size_t i = 1; i < m_continue_C_tids.size(); ++i) {1362                if (m_continue_C_tids[i].second != continue_signo)1363                  continue_packet_error = true;1364              }1365            }1366            if (!continue_packet_error)1367              m_gdb_comm.SetCurrentThreadForRun(-1);1368          } else {1369            // Set the continue thread ID1370            continue_packet_error = false;1371            m_gdb_comm.SetCurrentThreadForRun(m_continue_C_tids.front().first);1372          }1373          if (!continue_packet_error) {1374            // Add threads continuing with the same signo...1375            continue_packet.Printf("C%2.2x", continue_signo);1376          }1377        }1378      }1379 1380      if (continue_packet_error && num_continue_s_tids > 0) {1381        if (num_continue_s_tids == num_threads) {1382          // All threads are resuming...1383          m_gdb_comm.SetCurrentThreadForRun(-1);1384 1385          continue_packet.PutChar('s');1386 1387          continue_packet_error = false;1388        } else if (num_continue_c_tids == 0 && num_continue_C_tids == 0 &&1389                   num_continue_s_tids == 1 && num_continue_S_tids == 0) {1390          // Only one thread is stepping1391          m_gdb_comm.SetCurrentThreadForRun(m_continue_s_tids.front());1392          continue_packet.PutChar('s');1393          continue_packet_error = false;1394        }1395      }1396 1397      if (!continue_packet_error && num_continue_S_tids > 0) {1398        if (num_continue_S_tids == num_threads) {1399          const int step_signo = m_continue_S_tids.front().second;1400          // Are all threads trying to step with the same signal?1401          continue_packet_error = false;1402          if (num_continue_S_tids > 1) {1403            for (size_t i = 1; i < num_threads; ++i) {1404              if (m_continue_S_tids[i].second != step_signo)1405                continue_packet_error = true;1406            }1407          }1408          if (!continue_packet_error) {1409            // Add threads stepping with the same signo...1410            m_gdb_comm.SetCurrentThreadForRun(-1);1411            continue_packet.Printf("S%2.2x", step_signo);1412          }1413        } else if (num_continue_c_tids == 0 && num_continue_C_tids == 0 &&1414                   num_continue_s_tids == 0 && num_continue_S_tids == 1) {1415          // Only one thread is stepping with signal1416          m_gdb_comm.SetCurrentThreadForRun(m_continue_S_tids.front().first);1417          continue_packet.Printf("S%2.2x", m_continue_S_tids.front().second);1418          continue_packet_error = false;1419        }1420      }1421    }1422 1423    if (direction == RunDirection::eRunReverse) {1424      if (num_continue_s_tids > 0 || num_continue_S_tids > 0) {1425        if (!m_gdb_comm.GetReverseStepSupported()) {1426          LLDB_LOGF(log, "ProcessGDBRemote::DoResume: target does not "1427                         "support reverse-stepping");1428          return Status::FromErrorString(1429              "target does not support reverse-stepping");1430        }1431 1432        if (num_continue_S_tids > 0) {1433          LLDB_LOGF(1434              log,1435              "ProcessGDBRemote::DoResume: Signals not supported in reverse");1436          return Status::FromErrorString(1437              "can't deliver signals while running in reverse");1438        }1439 1440        if (num_continue_s_tids > 1) {1441          LLDB_LOGF(log, "ProcessGDBRemote::DoResume: can't step multiple "1442                         "threads in reverse");1443          return Status::FromErrorString(1444              "can't step multiple threads while reverse-stepping");1445        }1446 1447        m_gdb_comm.SetCurrentThreadForRun(m_continue_s_tids.front());1448        continue_packet.PutCString("bs");1449      } else {1450        if (!m_gdb_comm.GetReverseContinueSupported()) {1451          LLDB_LOGF(log, "ProcessGDBRemote::DoResume: target does not "1452                         "support reverse-continue");1453          return Status::FromErrorString(1454              "target does not support reverse execution of processes");1455        }1456 1457        if (num_continue_C_tids > 0) {1458          LLDB_LOGF(1459              log,1460              "ProcessGDBRemote::DoResume: Signals not supported in reverse");1461          return Status::FromErrorString(1462              "can't deliver signals while running in reverse");1463        }1464 1465        // All threads continue whether requested or not ---1466        // we can't change how threads ran in the past.1467        continue_packet.PutCString("bc");1468      }1469 1470      continue_packet_error = false;1471    }1472 1473    if (continue_packet_error) {1474      return Status::FromErrorString(1475          "can't make continue packet for this resume");1476    } else {1477      EventSP event_sp;1478      if (!m_async_thread.IsJoinable()) {1479        error = Status::FromErrorString(1480            "Trying to resume but the async thread is dead.");1481        LLDB_LOGF(log, "ProcessGDBRemote::DoResume: Trying to resume but the "1482                       "async thread is dead.");1483        return error;1484      }1485 1486      auto data_sp =1487          std::make_shared<EventDataBytes>(continue_packet.GetString());1488      m_async_broadcaster.BroadcastEvent(eBroadcastBitAsyncContinue, data_sp);1489 1490      if (!listener_sp->GetEvent(event_sp, ResumeTimeout())) {1491        error = Status::FromErrorString("Resume timed out.");1492        LLDB_LOGF(log, "ProcessGDBRemote::DoResume: Resume timed out.");1493      } else if (event_sp->BroadcasterIs(&m_async_broadcaster)) {1494        error = Status::FromErrorString(1495            "Broadcast continue, but the async thread was "1496            "killed before we got an ack back.");1497        LLDB_LOGF(log,1498                  "ProcessGDBRemote::DoResume: Broadcast continue, but the "1499                  "async thread was killed before we got an ack back.");1500        return error;1501      }1502    }1503  }1504 1505  return error;1506}1507 1508void ProcessGDBRemote::ClearThreadIDList() {1509  std::lock_guard<std::recursive_mutex> guard(m_thread_list_real.GetMutex());1510  m_thread_ids.clear();1511  m_thread_pcs.clear();1512}1513 1514size_t ProcessGDBRemote::UpdateThreadIDsFromStopReplyThreadsValue(1515    llvm::StringRef value) {1516  m_thread_ids.clear();1517  lldb::pid_t pid = m_gdb_comm.GetCurrentProcessID();1518  StringExtractorGDBRemote thread_ids{value};1519 1520  do {1521    auto pid_tid = thread_ids.GetPidTid(pid);1522    if (pid_tid && pid_tid->first == pid) {1523      lldb::tid_t tid = pid_tid->second;1524      if (tid != LLDB_INVALID_THREAD_ID &&1525          tid != StringExtractorGDBRemote::AllProcesses)1526        m_thread_ids.push_back(tid);1527    }1528  } while (thread_ids.GetChar() == ',');1529 1530  return m_thread_ids.size();1531}1532 1533size_t ProcessGDBRemote::UpdateThreadPCsFromStopReplyThreadsValue(1534    llvm::StringRef value) {1535  m_thread_pcs.clear();1536  for (llvm::StringRef x : llvm::split(value, ',')) {1537    lldb::addr_t pc;1538    if (llvm::to_integer(x, pc, 16))1539      m_thread_pcs.push_back(pc);1540  }1541  return m_thread_pcs.size();1542}1543 1544bool ProcessGDBRemote::UpdateThreadIDList() {1545  std::lock_guard<std::recursive_mutex> guard(m_thread_list_real.GetMutex());1546 1547  if (m_jthreadsinfo_sp) {1548    // If we have the JSON threads info, we can get the thread list from that1549    StructuredData::Array *thread_infos = m_jthreadsinfo_sp->GetAsArray();1550    if (thread_infos && thread_infos->GetSize() > 0) {1551      m_thread_ids.clear();1552      m_thread_pcs.clear();1553      thread_infos->ForEach([this](StructuredData::Object *object) -> bool {1554        StructuredData::Dictionary *thread_dict = object->GetAsDictionary();1555        if (thread_dict) {1556          // Set the thread stop info from the JSON dictionary1557          SetThreadStopInfo(thread_dict);1558          lldb::tid_t tid = LLDB_INVALID_THREAD_ID;1559          if (thread_dict->GetValueForKeyAsInteger<lldb::tid_t>("tid", tid))1560            m_thread_ids.push_back(tid);1561        }1562        return true; // Keep iterating through all thread_info objects1563      });1564    }1565    if (!m_thread_ids.empty())1566      return true;1567  } else {1568    // See if we can get the thread IDs from the current stop reply packets1569    // that might contain a "threads" key/value pair1570 1571    if (m_last_stop_packet) {1572      // Get the thread stop info1573      StringExtractorGDBRemote &stop_info = *m_last_stop_packet;1574      const std::string &stop_info_str = std::string(stop_info.GetStringRef());1575 1576      m_thread_pcs.clear();1577      const size_t thread_pcs_pos = stop_info_str.find(";thread-pcs:");1578      if (thread_pcs_pos != std::string::npos) {1579        const size_t start = thread_pcs_pos + strlen(";thread-pcs:");1580        const size_t end = stop_info_str.find(';', start);1581        if (end != std::string::npos) {1582          std::string value = stop_info_str.substr(start, end - start);1583          UpdateThreadPCsFromStopReplyThreadsValue(value);1584        }1585      }1586 1587      const size_t threads_pos = stop_info_str.find(";threads:");1588      if (threads_pos != std::string::npos) {1589        const size_t start = threads_pos + strlen(";threads:");1590        const size_t end = stop_info_str.find(';', start);1591        if (end != std::string::npos) {1592          std::string value = stop_info_str.substr(start, end - start);1593          if (UpdateThreadIDsFromStopReplyThreadsValue(value))1594            return true;1595        }1596      }1597    }1598  }1599 1600  bool sequence_mutex_unavailable = false;1601  m_gdb_comm.GetCurrentThreadIDs(m_thread_ids, sequence_mutex_unavailable);1602  if (sequence_mutex_unavailable) {1603    return false; // We just didn't get the list1604  }1605  return true;1606}1607 1608bool ProcessGDBRemote::DoUpdateThreadList(ThreadList &old_thread_list,1609                                          ThreadList &new_thread_list) {1610  // locker will keep a mutex locked until it goes out of scope1611  Log *log = GetLog(GDBRLog::Thread);1612  LLDB_LOGV(log, "pid = {0}", GetID());1613 1614  size_t num_thread_ids = m_thread_ids.size();1615  // The "m_thread_ids" thread ID list should always be updated after each stop1616  // reply packet, but in case it isn't, update it here.1617  if (num_thread_ids == 0) {1618    if (!UpdateThreadIDList())1619      return false;1620    num_thread_ids = m_thread_ids.size();1621  }1622 1623  ThreadList old_thread_list_copy(old_thread_list);1624  if (num_thread_ids > 0) {1625    for (size_t i = 0; i < num_thread_ids; ++i) {1626      lldb::tid_t tid = m_thread_ids[i];1627      ThreadSP thread_sp(1628          old_thread_list_copy.RemoveThreadByProtocolID(tid, false));1629      if (!thread_sp) {1630        thread_sp = CreateThread(tid);1631        LLDB_LOGV(log, "Making new thread: {0} for thread ID: {1:x}.",1632                  thread_sp.get(), thread_sp->GetID());1633      } else {1634        LLDB_LOGV(log, "Found old thread: {0} for thread ID: {1:x}.",1635                  thread_sp.get(), thread_sp->GetID());1636      }1637 1638      SetThreadPc(thread_sp, i);1639      new_thread_list.AddThreadSortedByIndexID(thread_sp);1640    }1641  }1642 1643  // Whatever that is left in old_thread_list_copy are not present in1644  // new_thread_list. Remove non-existent threads from internal id table.1645  size_t old_num_thread_ids = old_thread_list_copy.GetSize(false);1646  for (size_t i = 0; i < old_num_thread_ids; i++) {1647    ThreadSP old_thread_sp(old_thread_list_copy.GetThreadAtIndex(i, false));1648    if (old_thread_sp) {1649      lldb::tid_t old_thread_id = old_thread_sp->GetProtocolID();1650      m_thread_id_to_index_id_map.erase(old_thread_id);1651    }1652  }1653 1654  return true;1655}1656 1657void ProcessGDBRemote::SetThreadPc(const ThreadSP &thread_sp, uint64_t index) {1658  if (m_thread_ids.size() == m_thread_pcs.size() && thread_sp.get() &&1659      GetByteOrder() != eByteOrderInvalid) {1660    ThreadGDBRemote *gdb_thread =1661        static_cast<ThreadGDBRemote *>(thread_sp.get());1662    RegisterContextSP reg_ctx_sp(thread_sp->GetRegisterContext());1663    if (reg_ctx_sp) {1664      uint32_t pc_regnum = reg_ctx_sp->ConvertRegisterKindToRegisterNumber(1665          eRegisterKindGeneric, LLDB_REGNUM_GENERIC_PC);1666      if (pc_regnum != LLDB_INVALID_REGNUM) {1667        gdb_thread->PrivateSetRegisterValue(pc_regnum, m_thread_pcs[index]);1668      }1669    }1670  }1671}1672 1673bool ProcessGDBRemote::GetThreadStopInfoFromJSON(1674    ThreadGDBRemote *thread, const StructuredData::ObjectSP &thread_infos_sp) {1675  // See if we got thread stop infos for all threads via the "jThreadsInfo"1676  // packet1677  if (thread_infos_sp) {1678    StructuredData::Array *thread_infos = thread_infos_sp->GetAsArray();1679    if (thread_infos) {1680      lldb::tid_t tid;1681      const size_t n = thread_infos->GetSize();1682      for (size_t i = 0; i < n; ++i) {1683        StructuredData::Dictionary *thread_dict =1684            thread_infos->GetItemAtIndex(i)->GetAsDictionary();1685        if (thread_dict) {1686          if (thread_dict->GetValueForKeyAsInteger<lldb::tid_t>(1687                  "tid", tid, LLDB_INVALID_THREAD_ID)) {1688            if (tid == thread->GetID())1689              return (bool)SetThreadStopInfo(thread_dict);1690          }1691        }1692      }1693    }1694  }1695  return false;1696}1697 1698bool ProcessGDBRemote::CalculateThreadStopInfo(ThreadGDBRemote *thread) {1699  // See if we got thread stop infos for all threads via the "jThreadsInfo"1700  // packet1701  if (GetThreadStopInfoFromJSON(thread, m_jthreadsinfo_sp))1702    return true;1703 1704  // See if we got thread stop info for any threads valid stop info reasons1705  // threads via the "jstopinfo" packet stop reply packet key/value pair?1706  if (m_jstopinfo_sp) {1707    // If we have "jstopinfo" then we have stop descriptions for all threads1708    // that have stop reasons, and if there is no entry for a thread, then it1709    // has no stop reason.1710    if (!GetThreadStopInfoFromJSON(thread, m_jstopinfo_sp))1711      thread->SetStopInfo(StopInfoSP());1712    return true;1713  }1714 1715  // Fall back to using the qThreadStopInfo packet1716  StringExtractorGDBRemote stop_packet;1717  if (GetGDBRemote().GetThreadStopInfo(thread->GetProtocolID(), stop_packet))1718    return SetThreadStopInfo(stop_packet) == eStateStopped;1719  return false;1720}1721 1722void ProcessGDBRemote::ParseExpeditedRegisters(1723    ExpeditedRegisterMap &expedited_register_map, ThreadSP thread_sp) {1724  ThreadGDBRemote *gdb_thread = static_cast<ThreadGDBRemote *>(thread_sp.get());1725  RegisterContextSP gdb_reg_ctx_sp(gdb_thread->GetRegisterContext());1726 1727  for (const auto &pair : expedited_register_map) {1728    StringExtractor reg_value_extractor(pair.second);1729    WritableDataBufferSP buffer_sp(1730        new DataBufferHeap(reg_value_extractor.GetStringRef().size() / 2, 0));1731    reg_value_extractor.GetHexBytes(buffer_sp->GetData(), '\xcc');1732    uint32_t lldb_regnum = gdb_reg_ctx_sp->ConvertRegisterKindToRegisterNumber(1733        eRegisterKindProcessPlugin, pair.first);1734    gdb_thread->PrivateSetRegisterValue(lldb_regnum, buffer_sp->GetData());1735  }1736}1737 1738ThreadSP ProcessGDBRemote::SetThreadStopInfo(1739    lldb::tid_t tid, ExpeditedRegisterMap &expedited_register_map,1740    uint8_t signo, const std::string &thread_name, const std::string &reason,1741    const std::string &description, uint32_t exc_type,1742    const std::vector<addr_t> &exc_data, addr_t thread_dispatch_qaddr,1743    bool queue_vars_valid, // Set to true if queue_name, queue_kind and1744                           // queue_serial are valid1745    LazyBool associated_with_dispatch_queue, addr_t dispatch_queue_t,1746    std::string &queue_name, QueueKind queue_kind, uint64_t queue_serial) {1747 1748  if (tid == LLDB_INVALID_THREAD_ID)1749    return nullptr;1750 1751  ThreadSP thread_sp;1752  // Scope for "locker" below1753  {1754    // m_thread_list_real does have its own mutex, but we need to hold onto the1755    // mutex between the call to m_thread_list_real.FindThreadByID(...) and the1756    // m_thread_list_real.AddThread(...) so it doesn't change on us1757    std::lock_guard<std::recursive_mutex> guard(m_thread_list_real.GetMutex());1758    thread_sp = m_thread_list_real.FindThreadByProtocolID(tid, false);1759 1760    if (!thread_sp) {1761      // Create the thread if we need to1762      thread_sp = CreateThread(tid);1763      m_thread_list_real.AddThread(thread_sp);1764    }1765  }1766 1767  ThreadGDBRemote *gdb_thread = static_cast<ThreadGDBRemote *>(thread_sp.get());1768  RegisterContextSP reg_ctx_sp(gdb_thread->GetRegisterContext());1769 1770  reg_ctx_sp->InvalidateIfNeeded(true);1771 1772  auto iter = llvm::find(m_thread_ids, tid);1773  if (iter != m_thread_ids.end())1774    SetThreadPc(thread_sp, iter - m_thread_ids.begin());1775 1776  ParseExpeditedRegisters(expedited_register_map, thread_sp);1777 1778  if (reg_ctx_sp->ReconfigureRegisterInfo()) {1779    // Now we have changed the offsets of all the registers, so the values1780    // will be corrupted.1781    reg_ctx_sp->InvalidateAllRegisters();1782    // Expedited registers values will never contain registers that would be1783    // resized by a reconfigure. So we are safe to continue using these1784    // values.1785    ParseExpeditedRegisters(expedited_register_map, thread_sp);1786  }1787 1788  thread_sp->SetName(thread_name.empty() ? nullptr : thread_name.c_str());1789 1790  gdb_thread->SetThreadDispatchQAddr(thread_dispatch_qaddr);1791  // Check if the GDB server was able to provide the queue name, kind and serial1792  // number1793  if (queue_vars_valid)1794    gdb_thread->SetQueueInfo(std::move(queue_name), queue_kind, queue_serial,1795                             dispatch_queue_t, associated_with_dispatch_queue);1796  else1797    gdb_thread->ClearQueueInfo();1798 1799  gdb_thread->SetAssociatedWithLibdispatchQueue(associated_with_dispatch_queue);1800 1801  if (dispatch_queue_t != LLDB_INVALID_ADDRESS)1802    gdb_thread->SetQueueLibdispatchQueueAddress(dispatch_queue_t);1803 1804  // Make sure we update our thread stop reason just once, but don't overwrite1805  // the stop info for threads that haven't moved:1806  StopInfoSP current_stop_info_sp = thread_sp->GetPrivateStopInfo(false);1807  if (thread_sp->GetTemporaryResumeState() == eStateSuspended &&1808      current_stop_info_sp) {1809    thread_sp->SetStopInfo(current_stop_info_sp);1810    return thread_sp;1811  }1812 1813  if (!thread_sp->StopInfoIsUpToDate()) {1814    thread_sp->SetStopInfo(StopInfoSP());1815 1816    addr_t pc = thread_sp->GetRegisterContext()->GetPC();1817    BreakpointSiteSP bp_site_sp =1818        thread_sp->GetProcess()->GetBreakpointSiteList().FindByAddress(pc);1819    if (bp_site_sp && bp_site_sp->IsEnabled())1820      thread_sp->SetThreadStoppedAtUnexecutedBP(pc);1821 1822    if (exc_type != 0) {1823      // For thread plan async interrupt, creating stop info on the1824      // original async interrupt request thread instead. If interrupt thread1825      // does not exist anymore we fallback to current signal receiving thread1826      // instead.1827      ThreadSP interrupt_thread;1828      if (m_interrupt_tid != LLDB_INVALID_THREAD_ID)1829        interrupt_thread = HandleThreadAsyncInterrupt(signo, description);1830      if (interrupt_thread)1831        thread_sp = interrupt_thread;1832      else {1833        const size_t exc_data_size = exc_data.size();1834        thread_sp->SetStopInfo(1835            StopInfoMachException::CreateStopReasonWithMachException(1836                *thread_sp, exc_type, exc_data_size,1837                exc_data_size >= 1 ? exc_data[0] : 0,1838                exc_data_size >= 2 ? exc_data[1] : 0,1839                exc_data_size >= 3 ? exc_data[2] : 0));1840      }1841    } else {1842      bool handled = false;1843      bool did_exec = false;1844      // debugserver can send reason = "none" which is equivalent1845      // to no reason.1846      if (!reason.empty() && reason != "none") {1847        if (reason == "trace") {1848          thread_sp->SetStopInfo(StopInfo::CreateStopReasonToTrace(*thread_sp));1849          handled = true;1850        } else if (reason == "breakpoint") {1851          thread_sp->SetThreadHitBreakpointSite();1852          if (bp_site_sp) {1853            // If the breakpoint is for this thread, then we'll report the hit,1854            // but if it is for another thread, we can just report no reason.1855            // We don't need to worry about stepping over the breakpoint here,1856            // that will be taken care of when the thread resumes and notices1857            // that there's a breakpoint under the pc.1858            handled = true;1859            if (bp_site_sp->ValidForThisThread(*thread_sp)) {1860              thread_sp->SetStopInfo(1861                  StopInfo::CreateStopReasonWithBreakpointSiteID(1862                      *thread_sp, bp_site_sp->GetID()));1863            } else {1864              StopInfoSP invalid_stop_info_sp;1865              thread_sp->SetStopInfo(invalid_stop_info_sp);1866            }1867          }1868        } else if (reason == "trap") {1869          // Let the trap just use the standard signal stop reason below...1870        } else if (reason == "watchpoint") {1871          // We will have between 1 and 3 fields in the description.1872          //1873          // \a wp_addr which is the original start address that1874          // lldb requested be watched, or an address that the1875          // hardware reported.  This address should be within the1876          // range of a currently active watchpoint region - lldb1877          // should be able to find a watchpoint with this address.1878          //1879          // \a wp_index is the hardware watchpoint register number.1880          //1881          // \a wp_hit_addr is the actual address reported by the hardware,1882          // which may be outside the range of a region we are watching.1883          //1884          // On MIPS, we may get a false watchpoint exception where an1885          // access to the same 8 byte granule as a watchpoint will trigger,1886          // even if the access was not within the range of the watched1887          // region. When we get a \a wp_hit_addr outside the range of any1888          // set watchpoint, continue execution without making it visible to1889          // the user.1890          //1891          // On ARM, a related issue where a large access that starts1892          // before the watched region (and extends into the watched1893          // region) may report a hit address before the watched region.1894          // lldb will not find the "nearest" watchpoint to1895          // disable/step/re-enable it, so one of the valid watchpoint1896          // addresses should be provided as \a wp_addr.1897          StringExtractor desc_extractor(description.c_str());1898          // FIXME NativeThreadLinux::SetStoppedByWatchpoint sends this1899          // up as1900          //  <address within wp range> <wp hw index> <actual accessed addr>1901          // but this is not reading the <wp hw index>.  Seems like it1902          // wouldn't work on MIPS, where that third field is important.1903          addr_t wp_addr = desc_extractor.GetU64(LLDB_INVALID_ADDRESS);1904          addr_t wp_hit_addr = desc_extractor.GetU64(LLDB_INVALID_ADDRESS);1905          watch_id_t watch_id = LLDB_INVALID_WATCH_ID;1906          bool silently_continue = false;1907          WatchpointResourceSP wp_resource_sp;1908          if (wp_hit_addr != LLDB_INVALID_ADDRESS) {1909            wp_resource_sp =1910                m_watchpoint_resource_list.FindByAddress(wp_hit_addr);1911            // On MIPS, \a wp_hit_addr outside the range of a watched1912            // region means we should silently continue, it is a false hit.1913            ArchSpec::Core core = GetTarget().GetArchitecture().GetCore();1914            if (!wp_resource_sp && core >= ArchSpec::kCore_mips_first &&1915                core <= ArchSpec::kCore_mips_last)1916              silently_continue = true;1917          }1918          if (!wp_resource_sp && wp_addr != LLDB_INVALID_ADDRESS)1919            wp_resource_sp = m_watchpoint_resource_list.FindByAddress(wp_addr);1920          if (!wp_resource_sp) {1921            Log *log(GetLog(GDBRLog::Watchpoints));1922            LLDB_LOGF(log, "failed to find watchpoint");1923            watch_id = LLDB_INVALID_SITE_ID;1924          } else {1925            // LWP_TODO: This is hardcoding a single Watchpoint in a1926            // Resource, need to add1927            // StopInfo::CreateStopReasonWithWatchpointResource which1928            // represents all watchpoints that were tripped at this stop.1929            watch_id = wp_resource_sp->GetConstituentAtIndex(0)->GetID();1930          }1931          thread_sp->SetStopInfo(StopInfo::CreateStopReasonWithWatchpointID(1932              *thread_sp, watch_id, silently_continue));1933          handled = true;1934        } else if (reason == "exception") {1935          thread_sp->SetStopInfo(StopInfo::CreateStopReasonWithException(1936              *thread_sp, description.c_str()));1937          handled = true;1938        } else if (reason == "history boundary") {1939          thread_sp->SetStopInfo(StopInfo::CreateStopReasonHistoryBoundary(1940              *thread_sp, description.c_str()));1941          handled = true;1942        } else if (reason == "exec") {1943          did_exec = true;1944          thread_sp->SetStopInfo(1945              StopInfo::CreateStopReasonWithExec(*thread_sp));1946          handled = true;1947        } else if (reason == "processor trace") {1948          thread_sp->SetStopInfo(StopInfo::CreateStopReasonProcessorTrace(1949              *thread_sp, description.c_str()));1950        } else if (reason == "fork") {1951          StringExtractor desc_extractor(description.c_str());1952          lldb::pid_t child_pid =1953              desc_extractor.GetU64(LLDB_INVALID_PROCESS_ID);1954          lldb::tid_t child_tid = desc_extractor.GetU64(LLDB_INVALID_THREAD_ID);1955          thread_sp->SetStopInfo(1956              StopInfo::CreateStopReasonFork(*thread_sp, child_pid, child_tid));1957          handled = true;1958        } else if (reason == "vfork") {1959          StringExtractor desc_extractor(description.c_str());1960          lldb::pid_t child_pid =1961              desc_extractor.GetU64(LLDB_INVALID_PROCESS_ID);1962          lldb::tid_t child_tid = desc_extractor.GetU64(LLDB_INVALID_THREAD_ID);1963          thread_sp->SetStopInfo(StopInfo::CreateStopReasonVFork(1964              *thread_sp, child_pid, child_tid));1965          handled = true;1966        } else if (reason == "vforkdone") {1967          thread_sp->SetStopInfo(1968              StopInfo::CreateStopReasonVForkDone(*thread_sp));1969          handled = true;1970        }1971      }1972 1973      if (!handled && signo && !did_exec) {1974        if (signo == SIGTRAP) {1975          // Currently we are going to assume SIGTRAP means we are either1976          // hitting a breakpoint or hardware single stepping.1977 1978          // We can't disambiguate between stepping-to-a-breakpointsite and1979          // hitting-a-breakpointsite.1980          //1981          // A user can instruction-step, and be stopped at a BreakpointSite.1982          // Or a user can be sitting at a BreakpointSite,1983          // instruction-step which hits the breakpoint and the pc does not1984          // advance.1985          //1986          // In both cases, we're at a BreakpointSite when stopped, and1987          // the resume state was eStateStepping.1988 1989          // Assume if we're at a BreakpointSite, we hit it.1990          handled = true;1991          addr_t pc =1992              thread_sp->GetRegisterContext()->GetPC() + m_breakpoint_pc_offset;1993          BreakpointSiteSP bp_site_sp =1994              thread_sp->GetProcess()->GetBreakpointSiteList().FindByAddress(1995                  pc);1996 1997          // We can't know if we hit it or not. So if we are stopped at1998          // a BreakpointSite, assume we hit it, and should step past the1999          // breakpoint when we resume. This is contrary to how we handle2000          // BreakpointSites in any other location, but we can't know for2001          // sure what happened so it's a reasonable default.2002          if (bp_site_sp) {2003            if (bp_site_sp->IsEnabled())2004              thread_sp->SetThreadHitBreakpointSite();2005 2006            if (bp_site_sp->ValidForThisThread(*thread_sp)) {2007              if (m_breakpoint_pc_offset != 0)2008                thread_sp->GetRegisterContext()->SetPC(pc);2009              thread_sp->SetStopInfo(2010                  StopInfo::CreateStopReasonWithBreakpointSiteID(2011                      *thread_sp, bp_site_sp->GetID()));2012            } else {2013              StopInfoSP invalid_stop_info_sp;2014              thread_sp->SetStopInfo(invalid_stop_info_sp);2015            }2016          } else {2017            // If we were stepping then assume the stop was the result of the2018            // trace.  If we were not stepping then report the SIGTRAP.2019            if (thread_sp->GetTemporaryResumeState() == eStateStepping)2020              thread_sp->SetStopInfo(2021                  StopInfo::CreateStopReasonToTrace(*thread_sp));2022            else2023              thread_sp->SetStopInfo(StopInfo::CreateStopReasonWithSignal(2024                  *thread_sp, signo, description.c_str()));2025          }2026        }2027        if (!handled) {2028          // For thread plan async interrupt, creating stop info on the2029          // original async interrupt request thread instead. If interrupt2030          // thread does not exist anymore we fallback to current signal2031          // receiving thread instead.2032          ThreadSP interrupt_thread;2033          if (m_interrupt_tid != LLDB_INVALID_THREAD_ID)2034            interrupt_thread = HandleThreadAsyncInterrupt(signo, description);2035          if (interrupt_thread)2036            thread_sp = interrupt_thread;2037          else2038            thread_sp->SetStopInfo(StopInfo::CreateStopReasonWithSignal(2039                *thread_sp, signo, description.c_str()));2040        }2041      }2042 2043      if (!description.empty()) {2044        lldb::StopInfoSP stop_info_sp(thread_sp->GetStopInfo());2045        if (stop_info_sp) {2046          const char *stop_info_desc = stop_info_sp->GetDescription();2047          if (!stop_info_desc || !stop_info_desc[0])2048            stop_info_sp->SetDescription(description.c_str());2049        } else {2050          thread_sp->SetStopInfo(StopInfo::CreateStopReasonWithException(2051              *thread_sp, description.c_str()));2052        }2053      }2054    }2055  }2056  return thread_sp;2057}2058 2059ThreadSP2060ProcessGDBRemote::HandleThreadAsyncInterrupt(uint8_t signo,2061                                             const std::string &description) {2062  ThreadSP thread_sp;2063  {2064    std::lock_guard<std::recursive_mutex> guard(m_thread_list_real.GetMutex());2065    thread_sp = m_thread_list_real.FindThreadByProtocolID(m_interrupt_tid,2066                                                          /*can_update=*/false);2067  }2068  if (thread_sp)2069    thread_sp->SetStopInfo(StopInfo::CreateStopReasonWithInterrupt(2070        *thread_sp, signo, description.c_str()));2071  // Clear m_interrupt_tid regardless we can find original interrupt thread or2072  // not.2073  m_interrupt_tid = LLDB_INVALID_THREAD_ID;2074  return thread_sp;2075}2076 2077lldb::ThreadSP2078ProcessGDBRemote::SetThreadStopInfo(StructuredData::Dictionary *thread_dict) {2079  static constexpr llvm::StringLiteral g_key_tid("tid");2080  static constexpr llvm::StringLiteral g_key_name("name");2081  static constexpr llvm::StringLiteral g_key_reason("reason");2082  static constexpr llvm::StringLiteral g_key_metype("metype");2083  static constexpr llvm::StringLiteral g_key_medata("medata");2084  static constexpr llvm::StringLiteral g_key_qaddr("qaddr");2085  static constexpr llvm::StringLiteral g_key_dispatch_queue_t(2086      "dispatch_queue_t");2087  static constexpr llvm::StringLiteral g_key_associated_with_dispatch_queue(2088      "associated_with_dispatch_queue");2089  static constexpr llvm::StringLiteral g_key_queue_name("qname");2090  static constexpr llvm::StringLiteral g_key_queue_kind("qkind");2091  static constexpr llvm::StringLiteral g_key_queue_serial_number("qserialnum");2092  static constexpr llvm::StringLiteral g_key_registers("registers");2093  static constexpr llvm::StringLiteral g_key_memory("memory");2094  static constexpr llvm::StringLiteral g_key_description("description");2095  static constexpr llvm::StringLiteral g_key_signal("signal");2096 2097  // Stop with signal and thread info2098  lldb::tid_t tid = LLDB_INVALID_THREAD_ID;2099  uint8_t signo = 0;2100  std::string thread_name;2101  std::string reason;2102  std::string description;2103  uint32_t exc_type = 0;2104  std::vector<addr_t> exc_data;2105  addr_t thread_dispatch_qaddr = LLDB_INVALID_ADDRESS;2106  ExpeditedRegisterMap expedited_register_map;2107  bool queue_vars_valid = false;2108  addr_t dispatch_queue_t = LLDB_INVALID_ADDRESS;2109  LazyBool associated_with_dispatch_queue = eLazyBoolCalculate;2110  std::string queue_name;2111  QueueKind queue_kind = eQueueKindUnknown;2112  uint64_t queue_serial_number = 0;2113  // Iterate through all of the thread dictionary key/value pairs from the2114  // structured data dictionary2115 2116  // FIXME: we're silently ignoring invalid data here2117  thread_dict->ForEach([this, &tid, &expedited_register_map, &thread_name,2118                        &signo, &reason, &description, &exc_type, &exc_data,2119                        &thread_dispatch_qaddr, &queue_vars_valid,2120                        &associated_with_dispatch_queue, &dispatch_queue_t,2121                        &queue_name, &queue_kind, &queue_serial_number](2122                           llvm::StringRef key,2123                           StructuredData::Object *object) -> bool {2124    if (key == g_key_tid) {2125      // thread in big endian hex2126      tid = object->GetUnsignedIntegerValue(LLDB_INVALID_THREAD_ID);2127    } else if (key == g_key_metype) {2128      // exception type in big endian hex2129      exc_type = object->GetUnsignedIntegerValue(0);2130    } else if (key == g_key_medata) {2131      // exception data in big endian hex2132      StructuredData::Array *array = object->GetAsArray();2133      if (array) {2134        array->ForEach([&exc_data](StructuredData::Object *object) -> bool {2135          exc_data.push_back(object->GetUnsignedIntegerValue());2136          return true; // Keep iterating through all array items2137        });2138      }2139    } else if (key == g_key_name) {2140      thread_name = std::string(object->GetStringValue());2141    } else if (key == g_key_qaddr) {2142      thread_dispatch_qaddr =2143          object->GetUnsignedIntegerValue(LLDB_INVALID_ADDRESS);2144    } else if (key == g_key_queue_name) {2145      queue_vars_valid = true;2146      queue_name = std::string(object->GetStringValue());2147    } else if (key == g_key_queue_kind) {2148      std::string queue_kind_str = std::string(object->GetStringValue());2149      if (queue_kind_str == "serial") {2150        queue_vars_valid = true;2151        queue_kind = eQueueKindSerial;2152      } else if (queue_kind_str == "concurrent") {2153        queue_vars_valid = true;2154        queue_kind = eQueueKindConcurrent;2155      }2156    } else if (key == g_key_queue_serial_number) {2157      queue_serial_number = object->GetUnsignedIntegerValue(0);2158      if (queue_serial_number != 0)2159        queue_vars_valid = true;2160    } else if (key == g_key_dispatch_queue_t) {2161      dispatch_queue_t = object->GetUnsignedIntegerValue(0);2162      if (dispatch_queue_t != 0 && dispatch_queue_t != LLDB_INVALID_ADDRESS)2163        queue_vars_valid = true;2164    } else if (key == g_key_associated_with_dispatch_queue) {2165      queue_vars_valid = true;2166      bool associated = object->GetBooleanValue();2167      if (associated)2168        associated_with_dispatch_queue = eLazyBoolYes;2169      else2170        associated_with_dispatch_queue = eLazyBoolNo;2171    } else if (key == g_key_reason) {2172      reason = std::string(object->GetStringValue());2173    } else if (key == g_key_description) {2174      description = std::string(object->GetStringValue());2175    } else if (key == g_key_registers) {2176      StructuredData::Dictionary *registers_dict = object->GetAsDictionary();2177 2178      if (registers_dict) {2179        registers_dict->ForEach(2180            [&expedited_register_map](llvm::StringRef key,2181                                      StructuredData::Object *object) -> bool {2182              uint32_t reg;2183              if (llvm::to_integer(key, reg))2184                expedited_register_map[reg] =2185                    std::string(object->GetStringValue());2186              return true; // Keep iterating through all array items2187            });2188      }2189    } else if (key == g_key_memory) {2190      StructuredData::Array *array = object->GetAsArray();2191      if (array) {2192        array->ForEach([this](StructuredData::Object *object) -> bool {2193          StructuredData::Dictionary *mem_cache_dict =2194              object->GetAsDictionary();2195          if (mem_cache_dict) {2196            lldb::addr_t mem_cache_addr = LLDB_INVALID_ADDRESS;2197            if (mem_cache_dict->GetValueForKeyAsInteger<lldb::addr_t>(2198                    "address", mem_cache_addr)) {2199              if (mem_cache_addr != LLDB_INVALID_ADDRESS) {2200                llvm::StringRef str;2201                if (mem_cache_dict->GetValueForKeyAsString("bytes", str)) {2202                  StringExtractor bytes(str);2203                  bytes.SetFilePos(0);2204 2205                  const size_t byte_size = bytes.GetStringRef().size() / 2;2206                  WritableDataBufferSP data_buffer_sp(2207                      new DataBufferHeap(byte_size, 0));2208                  const size_t bytes_copied =2209                      bytes.GetHexBytes(data_buffer_sp->GetData(), 0);2210                  if (bytes_copied == byte_size)2211                    m_memory_cache.AddL1CacheData(mem_cache_addr,2212                                                  data_buffer_sp);2213                }2214              }2215            }2216          }2217          return true; // Keep iterating through all array items2218        });2219      }2220 2221    } else if (key == g_key_signal)2222      signo = object->GetUnsignedIntegerValue(LLDB_INVALID_SIGNAL_NUMBER);2223    return true; // Keep iterating through all dictionary key/value pairs2224  });2225 2226  return SetThreadStopInfo(tid, expedited_register_map, signo, thread_name,2227                           reason, description, exc_type, exc_data,2228                           thread_dispatch_qaddr, queue_vars_valid,2229                           associated_with_dispatch_queue, dispatch_queue_t,2230                           queue_name, queue_kind, queue_serial_number);2231}2232 2233StateType ProcessGDBRemote::SetThreadStopInfo(StringExtractor &stop_packet) {2234  lldb::pid_t pid = m_gdb_comm.GetCurrentProcessID();2235  stop_packet.SetFilePos(0);2236  const char stop_type = stop_packet.GetChar();2237  switch (stop_type) {2238  case 'T':2239  case 'S': {2240    // This is a bit of a hack, but it is required. If we did exec, we need to2241    // clear our thread lists and also know to rebuild our dynamic register2242    // info before we lookup and threads and populate the expedited register2243    // values so we need to know this right away so we can cleanup and update2244    // our registers.2245    const uint32_t stop_id = GetStopID();2246    if (stop_id == 0) {2247      // Our first stop, make sure we have a process ID, and also make sure we2248      // know about our registers2249      if (GetID() == LLDB_INVALID_PROCESS_ID && pid != LLDB_INVALID_PROCESS_ID)2250        SetID(pid);2251      BuildDynamicRegisterInfo(true);2252    }2253    // Stop with signal and thread info2254    lldb::pid_t stop_pid = LLDB_INVALID_PROCESS_ID;2255    lldb::tid_t tid = LLDB_INVALID_THREAD_ID;2256    const uint8_t signo = stop_packet.GetHexU8();2257    llvm::StringRef key;2258    llvm::StringRef value;2259    std::string thread_name;2260    std::string reason;2261    std::string description;2262    uint32_t exc_type = 0;2263    std::vector<addr_t> exc_data;2264    addr_t thread_dispatch_qaddr = LLDB_INVALID_ADDRESS;2265    bool queue_vars_valid =2266        false; // says if locals below that start with "queue_" are valid2267    addr_t dispatch_queue_t = LLDB_INVALID_ADDRESS;2268    LazyBool associated_with_dispatch_queue = eLazyBoolCalculate;2269    std::string queue_name;2270    QueueKind queue_kind = eQueueKindUnknown;2271    uint64_t queue_serial_number = 0;2272    ExpeditedRegisterMap expedited_register_map;2273    AddressableBits addressable_bits;2274    while (stop_packet.GetNameColonValue(key, value)) {2275      if (key.compare("metype") == 0) {2276        // exception type in big endian hex2277        value.getAsInteger(16, exc_type);2278      } else if (key.compare("medata") == 0) {2279        // exception data in big endian hex2280        uint64_t x;2281        value.getAsInteger(16, x);2282        exc_data.push_back(x);2283      } else if (key.compare("thread") == 0) {2284        // thread-id2285        StringExtractorGDBRemote thread_id{value};2286        auto pid_tid = thread_id.GetPidTid(pid);2287        if (pid_tid) {2288          stop_pid = pid_tid->first;2289          tid = pid_tid->second;2290        } else2291          tid = LLDB_INVALID_THREAD_ID;2292      } else if (key.compare("threads") == 0) {2293        std::lock_guard<std::recursive_mutex> guard(2294            m_thread_list_real.GetMutex());2295        UpdateThreadIDsFromStopReplyThreadsValue(value);2296      } else if (key.compare("thread-pcs") == 0) {2297        m_thread_pcs.clear();2298        // A comma separated list of all threads in the current2299        // process that includes the thread for this stop reply packet2300        lldb::addr_t pc;2301        while (!value.empty()) {2302          llvm::StringRef pc_str;2303          std::tie(pc_str, value) = value.split(',');2304          if (pc_str.getAsInteger(16, pc))2305            pc = LLDB_INVALID_ADDRESS;2306          m_thread_pcs.push_back(pc);2307        }2308      } else if (key.compare("jstopinfo") == 0) {2309        StringExtractor json_extractor(value);2310        std::string json;2311        // Now convert the HEX bytes into a string value2312        json_extractor.GetHexByteString(json);2313 2314        // This JSON contains thread IDs and thread stop info for all threads.2315        // It doesn't contain expedited registers, memory or queue info.2316        m_jstopinfo_sp = StructuredData::ParseJSON(json);2317      } else if (key.compare("hexname") == 0) {2318        StringExtractor name_extractor(value);2319        // Now convert the HEX bytes into a string value2320        name_extractor.GetHexByteString(thread_name);2321      } else if (key.compare("name") == 0) {2322        thread_name = std::string(value);2323      } else if (key.compare("qaddr") == 0) {2324        value.getAsInteger(16, thread_dispatch_qaddr);2325      } else if (key.compare("dispatch_queue_t") == 0) {2326        queue_vars_valid = true;2327        value.getAsInteger(16, dispatch_queue_t);2328      } else if (key.compare("qname") == 0) {2329        queue_vars_valid = true;2330        StringExtractor name_extractor(value);2331        // Now convert the HEX bytes into a string value2332        name_extractor.GetHexByteString(queue_name);2333      } else if (key.compare("qkind") == 0) {2334        queue_kind = llvm::StringSwitch<QueueKind>(value)2335                         .Case("serial", eQueueKindSerial)2336                         .Case("concurrent", eQueueKindConcurrent)2337                         .Default(eQueueKindUnknown);2338        queue_vars_valid = queue_kind != eQueueKindUnknown;2339      } else if (key.compare("qserialnum") == 0) {2340        if (!value.getAsInteger(0, queue_serial_number))2341          queue_vars_valid = true;2342      } else if (key.compare("reason") == 0) {2343        reason = std::string(value);2344      } else if (key.compare("description") == 0) {2345        StringExtractor desc_extractor(value);2346        // Now convert the HEX bytes into a string value2347        desc_extractor.GetHexByteString(description);2348      } else if (key.compare("memory") == 0) {2349        // Expedited memory. GDB servers can choose to send back expedited2350        // memory that can populate the L1 memory cache in the process so that2351        // things like the frame pointer backchain can be expedited. This will2352        // help stack backtracing be more efficient by not having to send as2353        // many memory read requests down the remote GDB server.2354 2355        // Key/value pair format: memory:<addr>=<bytes>;2356        // <addr> is a number whose base will be interpreted by the prefix:2357        //      "0x[0-9a-fA-F]+" for hex2358        //      "0[0-7]+" for octal2359        //      "[1-9]+" for decimal2360        // <bytes> is native endian ASCII hex bytes just like the register2361        // values2362        llvm::StringRef addr_str, bytes_str;2363        std::tie(addr_str, bytes_str) = value.split('=');2364        if (!addr_str.empty() && !bytes_str.empty()) {2365          lldb::addr_t mem_cache_addr = LLDB_INVALID_ADDRESS;2366          if (!addr_str.getAsInteger(0, mem_cache_addr)) {2367            StringExtractor bytes(bytes_str);2368            const size_t byte_size = bytes.GetBytesLeft() / 2;2369            WritableDataBufferSP data_buffer_sp(2370                new DataBufferHeap(byte_size, 0));2371            const size_t bytes_copied =2372                bytes.GetHexBytes(data_buffer_sp->GetData(), 0);2373            if (bytes_copied == byte_size)2374              m_memory_cache.AddL1CacheData(mem_cache_addr, data_buffer_sp);2375          }2376        }2377      } else if (key.compare("watch") == 0 || key.compare("rwatch") == 0 ||2378                 key.compare("awatch") == 0) {2379        // Support standard GDB remote stop reply packet 'TAAwatch:addr'2380        lldb::addr_t wp_addr = LLDB_INVALID_ADDRESS;2381        value.getAsInteger(16, wp_addr);2382 2383        WatchpointResourceSP wp_resource_sp =2384            m_watchpoint_resource_list.FindByAddress(wp_addr);2385 2386        // Rewrite gdb standard watch/rwatch/awatch to2387        // "reason:watchpoint" + "description:ADDR",2388        // which is parsed in SetThreadStopInfo.2389        reason = "watchpoint";2390        StreamString ostr;2391        ostr.Printf("%" PRIu64, wp_addr);2392        description = std::string(ostr.GetString());2393      } else if (key.compare("swbreak") == 0 || key.compare("hwbreak") == 0) {2394        reason = "breakpoint";2395      } else if (key.compare("replaylog") == 0) {2396        reason = "history boundary";2397      } else if (key.compare("library") == 0) {2398        auto error = LoadModules();2399        if (error) {2400          Log *log(GetLog(GDBRLog::Process));2401          LLDB_LOG_ERROR(log, std::move(error), "Failed to load modules: {0}");2402        }2403      } else if (key.compare("fork") == 0 || key.compare("vfork") == 0) {2404        // fork includes child pid/tid in thread-id format2405        StringExtractorGDBRemote thread_id{value};2406        auto pid_tid = thread_id.GetPidTid(LLDB_INVALID_PROCESS_ID);2407        if (!pid_tid) {2408          Log *log(GetLog(GDBRLog::Process));2409          LLDB_LOG(log, "Invalid PID/TID to fork: {0}", value);2410          pid_tid = {{LLDB_INVALID_PROCESS_ID, LLDB_INVALID_THREAD_ID}};2411        }2412 2413        reason = key.str();2414        StreamString ostr;2415        ostr.Printf("%" PRIu64 " %" PRIu64, pid_tid->first, pid_tid->second);2416        description = std::string(ostr.GetString());2417      } else if (key.compare("addressing_bits") == 0) {2418        uint64_t addressing_bits;2419        if (!value.getAsInteger(0, addressing_bits)) {2420          addressable_bits.SetAddressableBits(addressing_bits);2421        }2422      } else if (key.compare("low_mem_addressing_bits") == 0) {2423        uint64_t addressing_bits;2424        if (!value.getAsInteger(0, addressing_bits)) {2425          addressable_bits.SetLowmemAddressableBits(addressing_bits);2426        }2427      } else if (key.compare("high_mem_addressing_bits") == 0) {2428        uint64_t addressing_bits;2429        if (!value.getAsInteger(0, addressing_bits)) {2430          addressable_bits.SetHighmemAddressableBits(addressing_bits);2431        }2432      } else if (key.size() == 2 && ::isxdigit(key[0]) && ::isxdigit(key[1])) {2433        uint32_t reg = UINT32_MAX;2434        if (!key.getAsInteger(16, reg))2435          expedited_register_map[reg] = std::string(std::move(value));2436      }2437      // swbreak and hwbreak are also expected keys, but we don't need to2438      // change our behaviour for them because lldb always expects the remote2439      // to adjust the program counter (if relevant, e.g., for x86 targets)2440    }2441 2442    if (stop_pid != LLDB_INVALID_PROCESS_ID && stop_pid != pid) {2443      Log *log = GetLog(GDBRLog::Process);2444      LLDB_LOG(log,2445               "Received stop for incorrect PID = {0} (inferior PID = {1})",2446               stop_pid, pid);2447      return eStateInvalid;2448    }2449 2450    if (tid == LLDB_INVALID_THREAD_ID) {2451      // A thread id may be invalid if the response is old style 'S' packet2452      // which does not provide the2453      // thread information. So update the thread list and choose the first2454      // one.2455      UpdateThreadIDList();2456 2457      if (!m_thread_ids.empty()) {2458        tid = m_thread_ids.front();2459      }2460    }2461 2462    SetAddressableBitMasks(addressable_bits);2463 2464    ThreadSP thread_sp = SetThreadStopInfo(2465        tid, expedited_register_map, signo, thread_name, reason, description,2466        exc_type, exc_data, thread_dispatch_qaddr, queue_vars_valid,2467        associated_with_dispatch_queue, dispatch_queue_t, queue_name,2468        queue_kind, queue_serial_number);2469 2470    return eStateStopped;2471  } break;2472 2473  case 'W':2474  case 'X':2475    // process exited2476    return eStateExited;2477 2478  default:2479    break;2480  }2481  return eStateInvalid;2482}2483 2484void ProcessGDBRemote::RefreshStateAfterStop() {2485  std::lock_guard<std::recursive_mutex> guard(m_thread_list_real.GetMutex());2486 2487  m_thread_ids.clear();2488  m_thread_pcs.clear();2489 2490  // Set the thread stop info. It might have a "threads" key whose value is a2491  // list of all thread IDs in the current process, so m_thread_ids might get2492  // set.2493  // Check to see if SetThreadStopInfo() filled in m_thread_ids?2494  if (m_thread_ids.empty()) {2495      // No, we need to fetch the thread list manually2496      UpdateThreadIDList();2497  }2498 2499  // We might set some stop info's so make sure the thread list is up to2500  // date before we do that or we might overwrite what was computed here.2501  UpdateThreadListIfNeeded();2502 2503  if (m_last_stop_packet)2504    SetThreadStopInfo(*m_last_stop_packet);2505  m_last_stop_packet.reset();2506 2507  // If we have queried for a default thread id2508  if (m_initial_tid != LLDB_INVALID_THREAD_ID) {2509    m_thread_list.SetSelectedThreadByID(m_initial_tid);2510    m_initial_tid = LLDB_INVALID_THREAD_ID;2511  }2512 2513  // Let all threads recover from stopping and do any clean up based on the2514  // previous thread state (if any).2515  m_thread_list_real.RefreshStateAfterStop();2516}2517 2518Status ProcessGDBRemote::DoHalt(bool &caused_stop) {2519  Status error;2520 2521  if (m_public_state.GetValue() == eStateAttaching) {2522    // We are being asked to halt during an attach. We used to just close our2523    // file handle and debugserver will go away, but with remote proxies, it2524    // is better to send a positive signal, so let's send the interrupt first...2525    caused_stop = m_gdb_comm.Interrupt(GetInterruptTimeout());2526    m_gdb_comm.Disconnect();2527  } else2528    caused_stop = m_gdb_comm.Interrupt(GetInterruptTimeout());2529  return error;2530}2531 2532Status ProcessGDBRemote::DoDetach(bool keep_stopped) {2533  Status error;2534  Log *log = GetLog(GDBRLog::Process);2535  LLDB_LOGF(log, "ProcessGDBRemote::DoDetach(keep_stopped: %i)", keep_stopped);2536 2537  error = m_gdb_comm.Detach(keep_stopped);2538  if (log) {2539    if (error.Success())2540      log->PutCString(2541          "ProcessGDBRemote::DoDetach() detach packet sent successfully");2542    else2543      LLDB_LOGF(log,2544                "ProcessGDBRemote::DoDetach() detach packet send failed: %s",2545                error.AsCString() ? error.AsCString() : "<unknown error>");2546  }2547 2548  if (!error.Success())2549    return error;2550 2551  // Sleep for one second to let the process get all detached...2552  StopAsyncThread();2553 2554  SetPrivateState(eStateDetached);2555  ResumePrivateStateThread();2556 2557  // KillDebugserverProcess ();2558  return error;2559}2560 2561Status ProcessGDBRemote::DoDestroy() {2562  Log *log = GetLog(GDBRLog::Process);2563  LLDB_LOGF(log, "ProcessGDBRemote::DoDestroy()");2564 2565  // Interrupt if our inferior is running...2566  int exit_status = SIGABRT;2567  std::string exit_string;2568 2569  if (m_gdb_comm.IsConnected()) {2570    if (m_public_state.GetValue() != eStateAttaching) {2571      llvm::Expected<int> kill_res = m_gdb_comm.KillProcess(GetID());2572 2573      if (kill_res) {2574        exit_status = kill_res.get();2575#if defined(__APPLE__)2576        // For Native processes on Mac OS X, we launch through the Host2577        // Platform, then hand the process off to debugserver, which becomes2578        // the parent process through "PT_ATTACH".  Then when we go to kill2579        // the process on Mac OS X we call ptrace(PT_KILL) to kill it, then2580        // we call waitpid which returns with no error and the correct2581        // status.  But amusingly enough that doesn't seem to actually reap2582        // the process, but instead it is left around as a Zombie.  Probably2583        // the kernel is in the process of switching ownership back to lldb2584        // which was the original parent, and gets confused in the handoff.2585        // Anyway, so call waitpid here to finally reap it.2586        PlatformSP platform_sp(GetTarget().GetPlatform());2587        if (platform_sp && platform_sp->IsHost()) {2588          int status;2589          ::pid_t reap_pid;2590          reap_pid = waitpid(GetID(), &status, WNOHANG);2591          LLDB_LOGF(log, "Reaped pid: %d, status: %d.\n", reap_pid, status);2592        }2593#endif2594        ClearThreadIDList();2595        exit_string.assign("killed");2596      } else {2597        exit_string.assign(llvm::toString(kill_res.takeError()));2598      }2599    } else {2600      exit_string.assign("killed or interrupted while attaching.");2601    }2602  } else {2603    // If we missed setting the exit status on the way out, do it here.2604    // NB set exit status can be called multiple times, the first one sets the2605    // status.2606    exit_string.assign("destroying when not connected to debugserver");2607  }2608 2609  SetExitStatus(exit_status, exit_string.c_str());2610 2611  StopAsyncThread();2612  KillDebugserverProcess();2613  RemoveNewThreadBreakpoints();2614  return Status();2615}2616 2617void ProcessGDBRemote::RemoveNewThreadBreakpoints() {2618  if (m_thread_create_bp_sp) {2619    if (TargetSP target_sp = m_target_wp.lock())2620      target_sp->RemoveBreakpointByID(m_thread_create_bp_sp->GetID());2621    m_thread_create_bp_sp.reset();2622  }2623}2624 2625void ProcessGDBRemote::SetLastStopPacket(2626    const StringExtractorGDBRemote &response) {2627  const bool did_exec =2628      response.GetStringRef().find(";reason:exec;") != std::string::npos;2629  if (did_exec) {2630    Log *log = GetLog(GDBRLog::Process);2631    LLDB_LOGF(log, "ProcessGDBRemote::SetLastStopPacket () - detected exec");2632 2633    m_thread_list_real.Clear();2634    m_thread_list.Clear();2635    BuildDynamicRegisterInfo(true);2636    m_gdb_comm.ResetDiscoverableSettings(did_exec);2637  }2638 2639  m_last_stop_packet = response;2640}2641 2642void ProcessGDBRemote::SetUnixSignals(const UnixSignalsSP &signals_sp) {2643  Process::SetUnixSignals(std::make_shared<GDBRemoteSignals>(signals_sp));2644}2645 2646// Process Queries2647 2648bool ProcessGDBRemote::IsAlive() {2649  return m_gdb_comm.IsConnected() && Process::IsAlive();2650}2651 2652addr_t ProcessGDBRemote::GetImageInfoAddress() {2653  // request the link map address via the $qShlibInfoAddr packet2654  lldb::addr_t addr = m_gdb_comm.GetShlibInfoAddr();2655 2656  // the loaded module list can also provides a link map address2657  if (addr == LLDB_INVALID_ADDRESS) {2658    llvm::Expected<LoadedModuleInfoList> list = GetLoadedModuleList();2659    if (!list) {2660      Log *log = GetLog(GDBRLog::Process);2661      LLDB_LOG_ERROR(log, list.takeError(), "Failed to read module list: {0}.");2662    } else {2663      addr = list->m_link_map;2664    }2665  }2666 2667  return addr;2668}2669 2670void ProcessGDBRemote::WillPublicStop() {2671  // See if the GDB remote client supports the JSON threads info. If so, we2672  // gather stop info for all threads, expedited registers, expedited memory,2673  // runtime queue information (iOS and MacOSX only), and more. Expediting2674  // memory will help stack backtracing be much faster. Expediting registers2675  // will make sure we don't have to read the thread registers for GPRs.2676  m_jthreadsinfo_sp = m_gdb_comm.GetThreadsInfo();2677 2678  if (m_jthreadsinfo_sp) {2679    // Now set the stop info for each thread and also expedite any registers2680    // and memory that was in the jThreadsInfo response.2681    StructuredData::Array *thread_infos = m_jthreadsinfo_sp->GetAsArray();2682    if (thread_infos) {2683      const size_t n = thread_infos->GetSize();2684      for (size_t i = 0; i < n; ++i) {2685        StructuredData::Dictionary *thread_dict =2686            thread_infos->GetItemAtIndex(i)->GetAsDictionary();2687        if (thread_dict)2688          SetThreadStopInfo(thread_dict);2689      }2690    }2691  }2692}2693 2694// Process Memory2695size_t ProcessGDBRemote::DoReadMemory(addr_t addr, void *buf, size_t size,2696                                      Status &error) {2697  using xPacketState = GDBRemoteCommunicationClient::xPacketState;2698 2699  GetMaxMemorySize();2700  xPacketState x_state = m_gdb_comm.GetxPacketState();2701 2702  // M and m packets take 2 bytes for 1 byte of memory2703  size_t max_memory_size = x_state != xPacketState::Unimplemented2704                               ? m_max_memory_size2705                               : m_max_memory_size / 2;2706  if (size > max_memory_size) {2707    // Keep memory read sizes down to a sane limit. This function will be2708    // called multiple times in order to complete the task by2709    // lldb_private::Process so it is ok to do this.2710    size = max_memory_size;2711  }2712 2713  char packet[64];2714  int packet_len;2715  packet_len = ::snprintf(packet, sizeof(packet), "%c%" PRIx64 ",%" PRIx64,2716                          x_state != xPacketState::Unimplemented ? 'x' : 'm',2717                          (uint64_t)addr, (uint64_t)size);2718  assert(packet_len + 1 < (int)sizeof(packet));2719  UNUSED_IF_ASSERT_DISABLED(packet_len);2720  StringExtractorGDBRemote response;2721  if (m_gdb_comm.SendPacketAndWaitForResponse(packet, response,2722                                              GetInterruptTimeout()) ==2723      GDBRemoteCommunication::PacketResult::Success) {2724    if (response.IsNormalResponse()) {2725      error.Clear();2726      if (x_state != xPacketState::Unimplemented) {2727        // The lower level GDBRemoteCommunication packet receive layer has2728        // already de-quoted any 0x7d character escaping that was present in2729        // the packet2730 2731        llvm::StringRef data_received = response.GetStringRef();2732        if (x_state == xPacketState::Prefixed &&2733            !data_received.consume_front("b")) {2734          error = Status::FromErrorStringWithFormatv(2735              "unexpected response to GDB server memory read packet '{0}': "2736              "'{1}'",2737              packet, data_received);2738          return 0;2739        }2740        // Don't write past the end of BUF if the remote debug server gave us2741        // too much data for some reason.2742        size_t memcpy_size = std::min(size, data_received.size());2743        memcpy(buf, data_received.data(), memcpy_size);2744        return memcpy_size;2745      } else {2746        return response.GetHexBytes(2747            llvm::MutableArrayRef<uint8_t>((uint8_t *)buf, size), '\xdd');2748      }2749    } else if (response.IsErrorResponse())2750      error = Status::FromErrorStringWithFormat(2751          "memory read failed for 0x%" PRIx64, addr);2752    else if (response.IsUnsupportedResponse())2753      error = Status::FromErrorStringWithFormat(2754          "GDB server does not support reading memory");2755    else2756      error = Status::FromErrorStringWithFormat(2757          "unexpected response to GDB server memory read packet '%s': '%s'",2758          packet, response.GetStringRef().data());2759  } else {2760    error = Status::FromErrorStringWithFormat("failed to send packet: '%s'",2761                                              packet);2762  }2763  return 0;2764}2765 2766llvm::SmallVector<llvm::MutableArrayRef<uint8_t>>2767ProcessGDBRemote::ReadMemoryRanges(2768    llvm::ArrayRef<Range<lldb::addr_t, size_t>> ranges,2769    llvm::MutableArrayRef<uint8_t> buffer) {2770  if (!m_gdb_comm.GetMultiMemReadSupported())2771    return Process::ReadMemoryRanges(ranges, buffer);2772 2773  llvm::Expected<StringExtractorGDBRemote> response =2774      SendMultiMemReadPacket(ranges);2775  if (!response) {2776    LLDB_LOG_ERROR(GetLog(GDBRLog::Process), response.takeError(),2777                   "MultiMemRead error response: {0}");2778    return Process::ReadMemoryRanges(ranges, buffer);2779  }2780 2781  llvm::StringRef response_str = response->GetStringRef();2782  const unsigned expected_num_ranges = ranges.size();2783  llvm::Expected<llvm::SmallVector<llvm::MutableArrayRef<uint8_t>>>2784      parsed_response =2785          ParseMultiMemReadPacket(response_str, buffer, expected_num_ranges);2786  if (!parsed_response) {2787    LLDB_LOG_ERROR(GetLog(GDBRLog::Process), parsed_response.takeError(),2788                   "MultiMemRead error parsing response: {0}");2789    return Process::ReadMemoryRanges(ranges, buffer);2790  }2791  return std::move(*parsed_response);2792}2793 2794llvm::Expected<StringExtractorGDBRemote>2795ProcessGDBRemote::SendMultiMemReadPacket(2796    llvm::ArrayRef<Range<lldb::addr_t, size_t>> ranges) {2797  std::string packet_str;2798  llvm::raw_string_ostream stream(packet_str);2799  stream << "MultiMemRead:ranges:";2800 2801  auto range_to_stream = [&](auto range) {2802    // the "-" marker omits the '0x' prefix.2803    stream << llvm::formatv("{0:x-},{1:x-}", range.base, range.size);2804  };2805  llvm::interleave(ranges, stream, range_to_stream, ",");2806  stream << ";";2807 2808  StringExtractorGDBRemote response;2809  GDBRemoteCommunication::PacketResult packet_result =2810      m_gdb_comm.SendPacketAndWaitForResponse(packet_str.data(), response,2811                                              GetInterruptTimeout());2812  if (packet_result != GDBRemoteCommunication::PacketResult::Success)2813    return llvm::createStringError(2814        llvm::formatv("MultiMemRead failed to send packet: '{0}'", packet_str));2815 2816  if (response.IsErrorResponse())2817    return llvm::createStringError(2818        llvm::formatv("MultiMemRead failed: '{0}'", response.GetStringRef()));2819 2820  if (!response.IsNormalResponse())2821    return llvm::createStringError(llvm::formatv(2822        "MultiMemRead unexpected response: '{0}'", response.GetStringRef()));2823 2824  return response;2825}2826 2827llvm::Expected<llvm::SmallVector<llvm::MutableArrayRef<uint8_t>>>2828ProcessGDBRemote::ParseMultiMemReadPacket(llvm::StringRef response_str,2829                                          llvm::MutableArrayRef<uint8_t> buffer,2830                                          unsigned expected_num_ranges) {2831  // The sizes and the data are separated by a `;`.2832  auto [sizes_str, memory_data] = response_str.split(';');2833  if (sizes_str.size() == response_str.size())2834    return llvm::createStringError(llvm::formatv(2835        "MultiMemRead response missing field separator ';' in: '{0}'",2836        response_str));2837 2838  llvm::SmallVector<llvm::MutableArrayRef<uint8_t>> read_results;2839 2840  // Sizes are separated by a `,`.2841  for (llvm::StringRef size_str : llvm::split(sizes_str, ',')) {2842    uint64_t read_size;2843    if (size_str.getAsInteger(16, read_size))2844      return llvm::createStringError(llvm::formatv(2845          "MultiMemRead response has invalid size string: {0}", size_str));2846 2847    if (memory_data.size() < read_size)2848      return llvm::createStringError(2849          llvm::formatv("MultiMemRead response did not have enough data, "2850                        "requested sizes: {0}",2851                        sizes_str));2852 2853    llvm::StringRef region_to_read = memory_data.take_front(read_size);2854    memory_data = memory_data.drop_front(read_size);2855 2856    assert(buffer.size() >= read_size);2857    llvm::MutableArrayRef<uint8_t> region_to_write =2858        buffer.take_front(read_size);2859    buffer = buffer.drop_front(read_size);2860 2861    memcpy(region_to_write.data(), region_to_read.data(), read_size);2862    read_results.push_back(region_to_write);2863  }2864 2865  return read_results;2866}2867 2868bool ProcessGDBRemote::SupportsMemoryTagging() {2869  return m_gdb_comm.GetMemoryTaggingSupported();2870}2871 2872llvm::Expected<std::vector<uint8_t>>2873ProcessGDBRemote::DoReadMemoryTags(lldb::addr_t addr, size_t len,2874                                   int32_t type) {2875  // By this point ReadMemoryTags has validated that tagging is enabled2876  // for this target/process/address.2877  DataBufferSP buffer_sp = m_gdb_comm.ReadMemoryTags(addr, len, type);2878  if (!buffer_sp) {2879    return llvm::createStringError(llvm::inconvertibleErrorCode(),2880                                   "Error reading memory tags from remote");2881  }2882 2883  // Return the raw tag data2884  llvm::ArrayRef<uint8_t> tag_data = buffer_sp->GetData();2885  std::vector<uint8_t> got;2886  got.reserve(tag_data.size());2887  std::copy(tag_data.begin(), tag_data.end(), std::back_inserter(got));2888  return got;2889}2890 2891Status ProcessGDBRemote::DoWriteMemoryTags(lldb::addr_t addr, size_t len,2892                                           int32_t type,2893                                           const std::vector<uint8_t> &tags) {2894  // By now WriteMemoryTags should have validated that tagging is enabled2895  // for this target/process.2896  return m_gdb_comm.WriteMemoryTags(addr, len, type, tags);2897}2898 2899Status ProcessGDBRemote::WriteObjectFile(2900    std::vector<ObjectFile::LoadableData> entries) {2901  Status error;2902  // Sort the entries by address because some writes, like those to flash2903  // memory, must happen in order of increasing address.2904  llvm::stable_sort(entries, [](const ObjectFile::LoadableData a,2905                                const ObjectFile::LoadableData b) {2906    return a.Dest < b.Dest;2907  });2908  m_allow_flash_writes = true;2909  error = Process::WriteObjectFile(entries);2910  if (error.Success())2911    error = FlashDone();2912  else2913    // Even though some of the writing failed, try to send a flash done if some2914    // of the writing succeeded so the flash state is reset to normal, but2915    // don't stomp on the error status that was set in the write failure since2916    // that's the one we want to report back.2917    FlashDone();2918  m_allow_flash_writes = false;2919  return error;2920}2921 2922bool ProcessGDBRemote::HasErased(FlashRange range) {2923  auto size = m_erased_flash_ranges.GetSize();2924  for (size_t i = 0; i < size; ++i)2925    if (m_erased_flash_ranges.GetEntryAtIndex(i)->Contains(range))2926      return true;2927  return false;2928}2929 2930Status ProcessGDBRemote::FlashErase(lldb::addr_t addr, size_t size) {2931  Status status;2932 2933  MemoryRegionInfo region;2934  status = GetMemoryRegionInfo(addr, region);2935  if (!status.Success())2936    return status;2937 2938  // The gdb spec doesn't say if erasures are allowed across multiple regions,2939  // but we'll disallow it to be safe and to keep the logic simple by worring2940  // about only one region's block size.  DoMemoryWrite is this function's2941  // primary user, and it can easily keep writes within a single memory region2942  if (addr + size > region.GetRange().GetRangeEnd()) {2943    status =2944        Status::FromErrorString("Unable to erase flash in multiple regions");2945    return status;2946  }2947 2948  uint64_t blocksize = region.GetBlocksize();2949  if (blocksize == 0) {2950    status =2951        Status::FromErrorString("Unable to erase flash because blocksize is 0");2952    return status;2953  }2954 2955  // Erasures can only be done on block boundary adresses, so round down addr2956  // and round up size2957  lldb::addr_t block_start_addr = addr - (addr % blocksize);2958  size += (addr - block_start_addr);2959  if ((size % blocksize) != 0)2960    size += (blocksize - size % blocksize);2961 2962  FlashRange range(block_start_addr, size);2963 2964  if (HasErased(range))2965    return status;2966 2967  // We haven't erased the entire range, but we may have erased part of it.2968  // (e.g., block A is already erased and range starts in A and ends in B). So,2969  // adjust range if necessary to exclude already erased blocks.2970  if (!m_erased_flash_ranges.IsEmpty()) {2971    // Assuming that writes and erasures are done in increasing addr order,2972    // because that is a requirement of the vFlashWrite command.  Therefore, we2973    // only need to look at the last range in the list for overlap.2974    const auto &last_range = *m_erased_flash_ranges.Back();2975    if (range.GetRangeBase() < last_range.GetRangeEnd()) {2976      auto overlap = last_range.GetRangeEnd() - range.GetRangeBase();2977      // overlap will be less than range.GetByteSize() or else HasErased()2978      // would have been true2979      range.SetByteSize(range.GetByteSize() - overlap);2980      range.SetRangeBase(range.GetRangeBase() + overlap);2981    }2982  }2983 2984  StreamString packet;2985  packet.Printf("vFlashErase:%" PRIx64 ",%" PRIx64, range.GetRangeBase(),2986                (uint64_t)range.GetByteSize());2987 2988  StringExtractorGDBRemote response;2989  if (m_gdb_comm.SendPacketAndWaitForResponse(packet.GetString(), response,2990                                              GetInterruptTimeout()) ==2991      GDBRemoteCommunication::PacketResult::Success) {2992    if (response.IsOKResponse()) {2993      m_erased_flash_ranges.Insert(range, true);2994    } else {2995      if (response.IsErrorResponse())2996        status = Status::FromErrorStringWithFormat(2997            "flash erase failed for 0x%" PRIx64, addr);2998      else if (response.IsUnsupportedResponse())2999        status = Status::FromErrorStringWithFormat(3000            "GDB server does not support flashing");3001      else3002        status = Status::FromErrorStringWithFormat(3003            "unexpected response to GDB server flash erase packet '%s': '%s'",3004            packet.GetData(), response.GetStringRef().data());3005    }3006  } else {3007    status = Status::FromErrorStringWithFormat("failed to send packet: '%s'",3008                                               packet.GetData());3009  }3010  return status;3011}3012 3013Status ProcessGDBRemote::FlashDone() {3014  Status status;3015  // If we haven't erased any blocks, then we must not have written anything3016  // either, so there is no need to actually send a vFlashDone command3017  if (m_erased_flash_ranges.IsEmpty())3018    return status;3019  StringExtractorGDBRemote response;3020  if (m_gdb_comm.SendPacketAndWaitForResponse("vFlashDone", response,3021                                              GetInterruptTimeout()) ==3022      GDBRemoteCommunication::PacketResult::Success) {3023    if (response.IsOKResponse()) {3024      m_erased_flash_ranges.Clear();3025    } else {3026      if (response.IsErrorResponse())3027        status = Status::FromErrorStringWithFormat("flash done failed");3028      else if (response.IsUnsupportedResponse())3029        status = Status::FromErrorStringWithFormat(3030            "GDB server does not support flashing");3031      else3032        status = Status::FromErrorStringWithFormat(3033            "unexpected response to GDB server flash done packet: '%s'",3034            response.GetStringRef().data());3035    }3036  } else {3037    status =3038        Status::FromErrorStringWithFormat("failed to send flash done packet");3039  }3040  return status;3041}3042 3043size_t ProcessGDBRemote::DoWriteMemory(addr_t addr, const void *buf,3044                                       size_t size, Status &error) {3045  GetMaxMemorySize();3046  // M and m packets take 2 bytes for 1 byte of memory3047  size_t max_memory_size = m_max_memory_size / 2;3048  if (size > max_memory_size) {3049    // Keep memory read sizes down to a sane limit. This function will be3050    // called multiple times in order to complete the task by3051    // lldb_private::Process so it is ok to do this.3052    size = max_memory_size;3053  }3054 3055  StreamGDBRemote packet;3056 3057  MemoryRegionInfo region;3058  Status region_status = GetMemoryRegionInfo(addr, region);3059 3060  bool is_flash =3061      region_status.Success() && region.GetFlash() == MemoryRegionInfo::eYes;3062 3063  if (is_flash) {3064    if (!m_allow_flash_writes) {3065      error = Status::FromErrorString("Writing to flash memory is not allowed");3066      return 0;3067    }3068    // Keep the write within a flash memory region3069    if (addr + size > region.GetRange().GetRangeEnd())3070      size = region.GetRange().GetRangeEnd() - addr;3071    // Flash memory must be erased before it can be written3072    error = FlashErase(addr, size);3073    if (!error.Success())3074      return 0;3075    packet.Printf("vFlashWrite:%" PRIx64 ":", addr);3076    packet.PutEscapedBytes(buf, size);3077  } else {3078    packet.Printf("M%" PRIx64 ",%" PRIx64 ":", addr, (uint64_t)size);3079    packet.PutBytesAsRawHex8(buf, size, endian::InlHostByteOrder(),3080                             endian::InlHostByteOrder());3081  }3082  StringExtractorGDBRemote response;3083  if (m_gdb_comm.SendPacketAndWaitForResponse(packet.GetString(), response,3084                                              GetInterruptTimeout()) ==3085      GDBRemoteCommunication::PacketResult::Success) {3086    if (response.IsOKResponse()) {3087      error.Clear();3088      return size;3089    } else if (response.IsErrorResponse())3090      error = Status::FromErrorStringWithFormat(3091          "memory write failed for 0x%" PRIx64, addr);3092    else if (response.IsUnsupportedResponse())3093      error = Status::FromErrorStringWithFormat(3094          "GDB server does not support writing memory");3095    else3096      error = Status::FromErrorStringWithFormat(3097          "unexpected response to GDB server memory write packet '%s': '%s'",3098          packet.GetData(), response.GetStringRef().data());3099  } else {3100    error = Status::FromErrorStringWithFormat("failed to send packet: '%s'",3101                                              packet.GetData());3102  }3103  return 0;3104}3105 3106lldb::addr_t ProcessGDBRemote::DoAllocateMemory(size_t size,3107                                                uint32_t permissions,3108                                                Status &error) {3109  Log *log = GetLog(LLDBLog::Process | LLDBLog::Expressions);3110  addr_t allocated_addr = LLDB_INVALID_ADDRESS;3111 3112  if (m_gdb_comm.SupportsAllocDeallocMemory() != eLazyBoolNo) {3113    allocated_addr = m_gdb_comm.AllocateMemory(size, permissions);3114    if (allocated_addr != LLDB_INVALID_ADDRESS ||3115        m_gdb_comm.SupportsAllocDeallocMemory() == eLazyBoolYes)3116      return allocated_addr;3117  }3118 3119  if (m_gdb_comm.SupportsAllocDeallocMemory() == eLazyBoolNo) {3120    // Call mmap() to create memory in the inferior..3121    unsigned prot = 0;3122    if (permissions & lldb::ePermissionsReadable)3123      prot |= eMmapProtRead;3124    if (permissions & lldb::ePermissionsWritable)3125      prot |= eMmapProtWrite;3126    if (permissions & lldb::ePermissionsExecutable)3127      prot |= eMmapProtExec;3128 3129    if (InferiorCallMmap(this, allocated_addr, 0, size, prot,3130                         eMmapFlagsAnon | eMmapFlagsPrivate, -1, 0))3131      m_addr_to_mmap_size[allocated_addr] = size;3132    else {3133      allocated_addr = LLDB_INVALID_ADDRESS;3134      LLDB_LOGF(log,3135                "ProcessGDBRemote::%s no direct stub support for memory "3136                "allocation, and InferiorCallMmap also failed - is stub "3137                "missing register context save/restore capability?",3138                __FUNCTION__);3139    }3140  }3141 3142  if (allocated_addr == LLDB_INVALID_ADDRESS)3143    error = Status::FromErrorStringWithFormat(3144        "unable to allocate %" PRIu64 " bytes of memory with permissions %s",3145        (uint64_t)size, GetPermissionsAsCString(permissions));3146  else3147    error.Clear();3148  return allocated_addr;3149}3150 3151Status ProcessGDBRemote::DoGetMemoryRegionInfo(addr_t load_addr,3152                                               MemoryRegionInfo &region_info) {3153 3154  Status error(m_gdb_comm.GetMemoryRegionInfo(load_addr, region_info));3155  return error;3156}3157 3158std::optional<uint32_t> ProcessGDBRemote::GetWatchpointSlotCount() {3159  return m_gdb_comm.GetWatchpointSlotCount();3160}3161 3162std::optional<bool> ProcessGDBRemote::DoGetWatchpointReportedAfter() {3163  return m_gdb_comm.GetWatchpointReportedAfter();3164}3165 3166Status ProcessGDBRemote::DoDeallocateMemory(lldb::addr_t addr) {3167  Status error;3168  LazyBool supported = m_gdb_comm.SupportsAllocDeallocMemory();3169 3170  switch (supported) {3171  case eLazyBoolCalculate:3172    // We should never be deallocating memory without allocating memory first3173    // so we should never get eLazyBoolCalculate3174    error = Status::FromErrorString(3175        "tried to deallocate memory without ever allocating memory");3176    break;3177 3178  case eLazyBoolYes:3179    if (!m_gdb_comm.DeallocateMemory(addr))3180      error = Status::FromErrorStringWithFormat(3181          "unable to deallocate memory at 0x%" PRIx64, addr);3182    break;3183 3184  case eLazyBoolNo:3185    // Call munmap() to deallocate memory in the inferior..3186    {3187      MMapMap::iterator pos = m_addr_to_mmap_size.find(addr);3188      if (pos != m_addr_to_mmap_size.end() &&3189          InferiorCallMunmap(this, addr, pos->second))3190        m_addr_to_mmap_size.erase(pos);3191      else3192        error = Status::FromErrorStringWithFormat(3193            "unable to deallocate memory at 0x%" PRIx64, addr);3194    }3195    break;3196  }3197 3198  return error;3199}3200 3201// Process STDIO3202size_t ProcessGDBRemote::PutSTDIN(const char *src, size_t src_len,3203                                  Status &error) {3204  if (m_stdio_communication.IsConnected()) {3205    ConnectionStatus status;3206    m_stdio_communication.WriteAll(src, src_len, status, nullptr);3207  } else if (m_stdin_forward) {3208    m_gdb_comm.SendStdinNotification(src, src_len);3209  }3210  return 0;3211}3212 3213Status ProcessGDBRemote::EnableBreakpointSite(BreakpointSite *bp_site) {3214  Status error;3215  assert(bp_site != nullptr);3216 3217  // Get logging info3218  Log *log = GetLog(GDBRLog::Breakpoints);3219  user_id_t site_id = bp_site->GetID();3220 3221  // Get the breakpoint address3222  const addr_t addr = bp_site->GetLoadAddress();3223 3224  // Log that a breakpoint was requested3225  LLDB_LOGF(log,3226            "ProcessGDBRemote::EnableBreakpointSite (size_id = %" PRIu643227            ") address = 0x%" PRIx64,3228            site_id, (uint64_t)addr);3229 3230  // Breakpoint already exists and is enabled3231  if (bp_site->IsEnabled()) {3232    LLDB_LOGF(log,3233              "ProcessGDBRemote::EnableBreakpointSite (size_id = %" PRIu643234              ") address = 0x%" PRIx64 " -- SUCCESS (already enabled)",3235              site_id, (uint64_t)addr);3236    return error;3237  }3238 3239  // Get the software breakpoint trap opcode size3240  const size_t bp_op_size = GetSoftwareBreakpointTrapOpcode(bp_site);3241 3242  // SupportsGDBStoppointPacket() simply checks a boolean, indicating if this3243  // breakpoint type is supported by the remote stub. These are set to true by3244  // default, and later set to false only after we receive an unimplemented3245  // response when sending a breakpoint packet. This means initially that3246  // unless we were specifically instructed to use a hardware breakpoint, LLDB3247  // will attempt to set a software breakpoint. HardwareRequired() also queries3248  // a boolean variable which indicates if the user specifically asked for3249  // hardware breakpoints.  If true then we will skip over software3250  // breakpoints.3251  if (m_gdb_comm.SupportsGDBStoppointPacket(eBreakpointSoftware) &&3252      (!bp_site->HardwareRequired())) {3253    // Try to send off a software breakpoint packet ($Z0)3254    uint8_t error_no = m_gdb_comm.SendGDBStoppointTypePacket(3255        eBreakpointSoftware, true, addr, bp_op_size, GetInterruptTimeout());3256    if (error_no == 0) {3257      // The breakpoint was placed successfully3258      bp_site->SetEnabled(true);3259      bp_site->SetType(BreakpointSite::eExternal);3260      return error;3261    }3262 3263    // SendGDBStoppointTypePacket() will return an error if it was unable to3264    // set this breakpoint. We need to differentiate between a error specific3265    // to placing this breakpoint or if we have learned that this breakpoint3266    // type is unsupported. To do this, we must test the support boolean for3267    // this breakpoint type to see if it now indicates that this breakpoint3268    // type is unsupported.  If they are still supported then we should return3269    // with the error code.  If they are now unsupported, then we would like to3270    // fall through and try another form of breakpoint.3271    if (m_gdb_comm.SupportsGDBStoppointPacket(eBreakpointSoftware)) {3272      if (error_no != UINT8_MAX)3273        error = Status::FromErrorStringWithFormat(3274            "error: %d sending the breakpoint request", error_no);3275      else3276        error = Status::FromErrorString("error sending the breakpoint request");3277      return error;3278    }3279 3280    // We reach here when software breakpoints have been found to be3281    // unsupported. For future calls to set a breakpoint, we will not attempt3282    // to set a breakpoint with a type that is known not to be supported.3283    LLDB_LOGF(log, "Software breakpoints are unsupported");3284 3285    // So we will fall through and try a hardware breakpoint3286  }3287 3288  // The process of setting a hardware breakpoint is much the same as above.3289  // We check the supported boolean for this breakpoint type, and if it is3290  // thought to be supported then we will try to set this breakpoint with a3291  // hardware breakpoint.3292  if (m_gdb_comm.SupportsGDBStoppointPacket(eBreakpointHardware)) {3293    // Try to send off a hardware breakpoint packet ($Z1)3294    uint8_t error_no = m_gdb_comm.SendGDBStoppointTypePacket(3295        eBreakpointHardware, true, addr, bp_op_size, GetInterruptTimeout());3296    if (error_no == 0) {3297      // The breakpoint was placed successfully3298      bp_site->SetEnabled(true);3299      bp_site->SetType(BreakpointSite::eHardware);3300      return error;3301    }3302 3303    // Check if the error was something other then an unsupported breakpoint3304    // type3305    if (m_gdb_comm.SupportsGDBStoppointPacket(eBreakpointHardware)) {3306      // Unable to set this hardware breakpoint3307      if (error_no != UINT8_MAX)3308        error = Status::FromErrorStringWithFormat(3309            "error: %d sending the hardware breakpoint request "3310            "(hardware breakpoint resources might be exhausted or unavailable)",3311            error_no);3312      else3313        error = Status::FromErrorString(3314            "error sending the hardware breakpoint request "3315            "(hardware breakpoint resources "3316            "might be exhausted or unavailable)");3317      return error;3318    }3319 3320    // We will reach here when the stub gives an unsupported response to a3321    // hardware breakpoint3322    LLDB_LOGF(log, "Hardware breakpoints are unsupported");3323 3324    // Finally we will falling through to a #trap style breakpoint3325  }3326 3327  // Don't fall through when hardware breakpoints were specifically requested3328  if (bp_site->HardwareRequired()) {3329    error = Status::FromErrorString("hardware breakpoints are not supported");3330    return error;3331  }3332 3333  // As a last resort we want to place a manual breakpoint. An instruction is3334  // placed into the process memory using memory write packets.3335  return EnableSoftwareBreakpoint(bp_site);3336}3337 3338Status ProcessGDBRemote::DisableBreakpointSite(BreakpointSite *bp_site) {3339  Status error;3340  assert(bp_site != nullptr);3341  addr_t addr = bp_site->GetLoadAddress();3342  user_id_t site_id = bp_site->GetID();3343  Log *log = GetLog(GDBRLog::Breakpoints);3344  LLDB_LOGF(log,3345            "ProcessGDBRemote::DisableBreakpointSite (site_id = %" PRIu643346            ") addr = 0x%8.8" PRIx64,3347            site_id, (uint64_t)addr);3348 3349  if (bp_site->IsEnabled()) {3350    const size_t bp_op_size = GetSoftwareBreakpointTrapOpcode(bp_site);3351 3352    BreakpointSite::Type bp_type = bp_site->GetType();3353    switch (bp_type) {3354    case BreakpointSite::eSoftware:3355      error = DisableSoftwareBreakpoint(bp_site);3356      break;3357 3358    case BreakpointSite::eHardware:3359      if (m_gdb_comm.SendGDBStoppointTypePacket(eBreakpointHardware, false,3360                                                addr, bp_op_size,3361                                                GetInterruptTimeout()))3362        error = Status::FromErrorString("unknown error");3363      break;3364 3365    case BreakpointSite::eExternal: {3366      if (m_gdb_comm.SendGDBStoppointTypePacket(eBreakpointSoftware, false,3367                                                addr, bp_op_size,3368                                                GetInterruptTimeout()))3369        error = Status::FromErrorString("unknown error");3370    } break;3371    }3372    if (error.Success())3373      bp_site->SetEnabled(false);3374  } else {3375    LLDB_LOGF(log,3376              "ProcessGDBRemote::DisableBreakpointSite (site_id = %" PRIu643377              ") addr = 0x%8.8" PRIx64 " -- SUCCESS (already disabled)",3378              site_id, (uint64_t)addr);3379    return error;3380  }3381 3382  if (error.Success())3383    error = Status::FromErrorString("unknown error");3384  return error;3385}3386 3387// Pre-requisite: wp != NULL.3388static GDBStoppointType3389GetGDBStoppointType(const WatchpointResourceSP &wp_res_sp) {3390  assert(wp_res_sp);3391  bool read = wp_res_sp->WatchpointResourceRead();3392  bool write = wp_res_sp->WatchpointResourceWrite();3393 3394  assert((read || write) &&3395         "WatchpointResource type is neither read nor write");3396  if (read && write)3397    return eWatchpointReadWrite;3398  else if (read)3399    return eWatchpointRead;3400  else3401    return eWatchpointWrite;3402}3403 3404Status ProcessGDBRemote::EnableWatchpoint(WatchpointSP wp_sp, bool notify) {3405  Status error;3406  if (!wp_sp) {3407    error = Status::FromErrorString("No watchpoint specified");3408    return error;3409  }3410  user_id_t watchID = wp_sp->GetID();3411  addr_t addr = wp_sp->GetLoadAddress();3412  Log *log(GetLog(GDBRLog::Watchpoints));3413  LLDB_LOGF(log, "ProcessGDBRemote::EnableWatchpoint(watchID = %" PRIu64 ")",3414            watchID);3415  if (wp_sp->IsEnabled()) {3416    LLDB_LOGF(log,3417              "ProcessGDBRemote::EnableWatchpoint(watchID = %" PRIu643418              ") addr = 0x%8.8" PRIx64 ": watchpoint already enabled.",3419              watchID, (uint64_t)addr);3420    return error;3421  }3422 3423  bool read = wp_sp->WatchpointRead();3424  bool write = wp_sp->WatchpointWrite() || wp_sp->WatchpointModify();3425  size_t size = wp_sp->GetByteSize();3426 3427  ArchSpec target_arch = GetTarget().GetArchitecture();3428  WatchpointHardwareFeature supported_features =3429      m_gdb_comm.GetSupportedWatchpointTypes();3430 3431  std::vector<WatchpointResourceSP> resources =3432      WatchpointAlgorithms::AtomizeWatchpointRequest(3433          addr, size, read, write, supported_features, target_arch);3434 3435  // LWP_TODO: Now that we know the WP Resources needed to implement this3436  // Watchpoint, we need to look at currently allocated Resources in the3437  // Process and if they match, or are within the same memory granule, or3438  // overlapping memory ranges, then we need to combine them.  e.g. one3439  // Watchpoint watching 1 byte at 0x1002 and a second watchpoint watching 13440  // byte at 0x1003, they must use the same hardware watchpoint register3441  // (Resource) to watch them.3442 3443  // This may mean that an existing resource changes its type (read to3444  // read+write) or address range it is watching, in which case the old3445  // watchpoint needs to be disabled and the new Resource addr/size/type3446  // watchpoint enabled.3447 3448  // If we modify a shared Resource to accomodate this newly added Watchpoint,3449  // and we are unable to set all of the Resources for it in the inferior, we3450  // will return an error for this Watchpoint and the shared Resource should3451  // be restored.  e.g. this Watchpoint requires three Resources, one which3452  // is shared with another Watchpoint.  We extend the shared Resouce to3453  // handle both Watchpoints and we try to set two new ones.  But if we don't3454  // have sufficient watchpoint register for all 3, we need to show an error3455  // for creating this Watchpoint and we should reset the shared Resource to3456  // its original configuration because it is no longer shared.3457 3458  bool set_all_resources = true;3459  std::vector<WatchpointResourceSP> succesfully_set_resources;3460  for (const auto &wp_res_sp : resources) {3461    addr_t addr = wp_res_sp->GetLoadAddress();3462    size_t size = wp_res_sp->GetByteSize();3463    GDBStoppointType type = GetGDBStoppointType(wp_res_sp);3464    if (!m_gdb_comm.SupportsGDBStoppointPacket(type) ||3465        m_gdb_comm.SendGDBStoppointTypePacket(type, true, addr, size,3466                                              GetInterruptTimeout())) {3467      set_all_resources = false;3468      break;3469    } else {3470      succesfully_set_resources.push_back(wp_res_sp);3471    }3472  }3473  if (set_all_resources) {3474    wp_sp->SetEnabled(true, notify);3475    for (const auto &wp_res_sp : resources) {3476      // LWP_TODO: If we expanded/reused an existing Resource,3477      // it's already in the WatchpointResourceList.3478      wp_res_sp->AddConstituent(wp_sp);3479      m_watchpoint_resource_list.Add(wp_res_sp);3480    }3481    return error;3482  } else {3483    // We failed to allocate one of the resources.  Unset all3484    // of the new resources we did successfully set in the3485    // process.3486    for (const auto &wp_res_sp : succesfully_set_resources) {3487      addr_t addr = wp_res_sp->GetLoadAddress();3488      size_t size = wp_res_sp->GetByteSize();3489      GDBStoppointType type = GetGDBStoppointType(wp_res_sp);3490      m_gdb_comm.SendGDBStoppointTypePacket(type, false, addr, size,3491                                            GetInterruptTimeout());3492    }3493    error = Status::FromErrorString(3494        "Setting one of the watchpoint resources failed");3495  }3496  return error;3497}3498 3499Status ProcessGDBRemote::DisableWatchpoint(WatchpointSP wp_sp, bool notify) {3500  Status error;3501  if (!wp_sp) {3502    error = Status::FromErrorString("Watchpoint argument was NULL.");3503    return error;3504  }3505 3506  user_id_t watchID = wp_sp->GetID();3507 3508  Log *log(GetLog(GDBRLog::Watchpoints));3509 3510  addr_t addr = wp_sp->GetLoadAddress();3511 3512  LLDB_LOGF(log,3513            "ProcessGDBRemote::DisableWatchpoint (watchID = %" PRIu643514            ") addr = 0x%8.8" PRIx64,3515            watchID, (uint64_t)addr);3516 3517  if (!wp_sp->IsEnabled()) {3518    LLDB_LOGF(log,3519              "ProcessGDBRemote::DisableWatchpoint (watchID = %" PRIu643520              ") addr = 0x%8.8" PRIx64 " -- SUCCESS (already disabled)",3521              watchID, (uint64_t)addr);3522    // See also 'class WatchpointSentry' within StopInfo.cpp. This disabling3523    // attempt might come from the user-supplied actions, we'll route it in3524    // order for the watchpoint object to intelligently process this action.3525    wp_sp->SetEnabled(false, notify);3526    return error;3527  }3528 3529  if (wp_sp->IsHardware()) {3530    bool disabled_all = true;3531 3532    std::vector<WatchpointResourceSP> unused_resources;3533    for (const auto &wp_res_sp : m_watchpoint_resource_list.Sites()) {3534      if (wp_res_sp->ConstituentsContains(wp_sp)) {3535        GDBStoppointType type = GetGDBStoppointType(wp_res_sp);3536        addr_t addr = wp_res_sp->GetLoadAddress();3537        size_t size = wp_res_sp->GetByteSize();3538        if (m_gdb_comm.SendGDBStoppointTypePacket(type, false, addr, size,3539                                                  GetInterruptTimeout())) {3540          disabled_all = false;3541        } else {3542          wp_res_sp->RemoveConstituent(wp_sp);3543          if (wp_res_sp->GetNumberOfConstituents() == 0)3544            unused_resources.push_back(wp_res_sp);3545        }3546      }3547    }3548    for (auto &wp_res_sp : unused_resources)3549      m_watchpoint_resource_list.Remove(wp_res_sp->GetID());3550 3551    wp_sp->SetEnabled(false, notify);3552    if (!disabled_all)3553      error = Status::FromErrorString(3554          "Failure disabling one of the watchpoint locations");3555  }3556  return error;3557}3558 3559void ProcessGDBRemote::Clear() {3560  m_thread_list_real.Clear();3561  m_thread_list.Clear();3562}3563 3564Status ProcessGDBRemote::DoSignal(int signo) {3565  Status error;3566  Log *log = GetLog(GDBRLog::Process);3567  LLDB_LOGF(log, "ProcessGDBRemote::DoSignal (signal = %d)", signo);3568 3569  if (!m_gdb_comm.SendAsyncSignal(signo, GetInterruptTimeout()))3570    error =3571        Status::FromErrorStringWithFormat("failed to send signal %i", signo);3572  return error;3573}3574 3575Status3576ProcessGDBRemote::EstablishConnectionIfNeeded(const ProcessInfo &process_info) {3577  // Make sure we aren't already connected?3578  if (m_gdb_comm.IsConnected())3579    return Status();3580 3581  PlatformSP platform_sp(GetTarget().GetPlatform());3582  if (platform_sp && !platform_sp->IsHost())3583    return Status::FromErrorString("Lost debug server connection");3584 3585  auto error = LaunchAndConnectToDebugserver(process_info);3586  if (error.Fail()) {3587    const char *error_string = error.AsCString();3588    if (error_string == nullptr)3589      error_string = "unable to launch " DEBUGSERVER_BASENAME;3590  }3591  return error;3592}3593 3594static FileSpec GetDebugserverPath(Platform &platform) {3595  Log *log = GetLog(GDBRLog::Process);3596  // If we locate debugserver, keep that located version around3597  static FileSpec g_debugserver_file_spec;3598  FileSpec debugserver_file_spec;3599 3600  Environment host_env = Host::GetEnvironment();3601 3602  // Always check to see if we have an environment override for the path to the3603  // debugserver to use and use it if we do.3604  std::string env_debugserver_path = host_env.lookup("LLDB_DEBUGSERVER_PATH");3605  if (!env_debugserver_path.empty()) {3606    debugserver_file_spec.SetFile(env_debugserver_path,3607                                  FileSpec::Style::native);3608    LLDB_LOG(log, "gdb-remote stub exe path set from environment variable: {0}",3609             env_debugserver_path);3610  } else3611    debugserver_file_spec = g_debugserver_file_spec;3612  if (FileSystem::Instance().Exists(debugserver_file_spec))3613    return debugserver_file_spec;3614 3615  // The debugserver binary is in the LLDB.framework/Resources directory.3616  debugserver_file_spec = HostInfo::GetSupportExeDir();3617  if (debugserver_file_spec) {3618    debugserver_file_spec.AppendPathComponent(DEBUGSERVER_BASENAME);3619    if (FileSystem::Instance().Exists(debugserver_file_spec)) {3620      LLDB_LOG(log, "found gdb-remote stub exe '{0}'", debugserver_file_spec);3621 3622      g_debugserver_file_spec = debugserver_file_spec;3623    } else {3624      debugserver_file_spec = platform.LocateExecutable(DEBUGSERVER_BASENAME);3625      if (!debugserver_file_spec) {3626        // Platform::LocateExecutable() wouldn't return a path if it doesn't3627        // exist3628        LLDB_LOG(log, "could not find gdb-remote stub exe '{0}'",3629                 debugserver_file_spec);3630      }3631      // Don't cache the platform specific GDB server binary as it could3632      // change from platform to platform3633      g_debugserver_file_spec.Clear();3634    }3635  }3636  return debugserver_file_spec;3637}3638 3639Status ProcessGDBRemote::LaunchAndConnectToDebugserver(3640    const ProcessInfo &process_info) {3641  using namespace std::placeholders; // For _1, _2, etc.3642 3643  if (m_debugserver_pid != LLDB_INVALID_PROCESS_ID)3644    return Status();3645 3646  ProcessLaunchInfo debugserver_launch_info;3647  // Make debugserver run in its own session so signals generated by special3648  // terminal key sequences (^C) don't affect debugserver.3649  debugserver_launch_info.SetLaunchInSeparateProcessGroup(true);3650 3651  const std::weak_ptr<ProcessGDBRemote> this_wp =3652      std::static_pointer_cast<ProcessGDBRemote>(shared_from_this());3653  debugserver_launch_info.SetMonitorProcessCallback(3654      std::bind(MonitorDebugserverProcess, this_wp, _1, _2, _3));3655  debugserver_launch_info.SetUserID(process_info.GetUserID());3656 3657  FileSpec debugserver_path = GetDebugserverPath(*GetTarget().GetPlatform());3658 3659#if defined(__APPLE__)3660  // On macOS 11, we need to support x86_64 applications translated to3661  // arm64. We check whether a binary is translated and spawn the correct3662  // debugserver accordingly.3663  int mib[] = {CTL_KERN, KERN_PROC, KERN_PROC_PID,3664               static_cast<int>(process_info.GetProcessID())};3665  struct kinfo_proc processInfo;3666  size_t bufsize = sizeof(processInfo);3667  if (sysctl(mib, (unsigned)(sizeof(mib) / sizeof(int)), &processInfo, &bufsize,3668             NULL, 0) == 0 &&3669      bufsize > 0) {3670    if (processInfo.kp_proc.p_flag & P_TRANSLATED) {3671      debugserver_path = FileSpec("/Library/Apple/usr/libexec/oah/debugserver");3672    }3673  }3674#endif3675 3676  if (!FileSystem::Instance().Exists(debugserver_path))3677    return Status::FromErrorString("could not find '" DEBUGSERVER_BASENAME3678                                   "'. Please ensure it is properly installed "3679                                   "and available in your PATH");3680 3681  debugserver_launch_info.SetExecutableFile(debugserver_path,3682                                            /*add_exe_file_as_first_arg=*/true);3683 3684  llvm::Expected<Socket::Pair> socket_pair = Socket::CreatePair();3685  if (!socket_pair)3686    return Status::FromError(socket_pair.takeError());3687 3688  Status error;3689  SharedSocket shared_socket(socket_pair->first.get(), error);3690  if (error.Fail())3691    return error;3692 3693  error = m_gdb_comm.StartDebugserverProcess(shared_socket.GetSendableFD(),3694                                             debugserver_launch_info, nullptr);3695 3696  if (error.Fail()) {3697    Log *log = GetLog(GDBRLog::Process);3698 3699    LLDB_LOGF(log, "failed to start debugserver process: %s",3700              error.AsCString());3701    return error;3702  }3703 3704  m_debugserver_pid = debugserver_launch_info.GetProcessID();3705  shared_socket.CompleteSending(m_debugserver_pid);3706 3707  // Our process spawned correctly, we can now set our connection to use3708  // our end of the socket pair3709  m_gdb_comm.SetConnection(std::make_unique<ConnectionFileDescriptor>(3710      std::move(socket_pair->second)));3711  StartAsyncThread();3712 3713  if (m_gdb_comm.IsConnected()) {3714    // Finish the connection process by doing the handshake without3715    // connecting (send NULL URL)3716    error = ConnectToDebugserver("");3717  } else {3718    error = Status::FromErrorString("connection failed");3719  }3720  return error;3721}3722 3723void ProcessGDBRemote::MonitorDebugserverProcess(3724    std::weak_ptr<ProcessGDBRemote> process_wp, lldb::pid_t debugserver_pid,3725    int signo,      // Zero for no signal3726    int exit_status // Exit value of process if signal is zero3727) {3728  // "debugserver_pid" argument passed in is the process ID for debugserver3729  // that we are tracking...3730  Log *log = GetLog(GDBRLog::Process);3731 3732  LLDB_LOGF(log,3733            "ProcessGDBRemote::%s(process_wp, pid=%" PRIu643734            ", signo=%i (0x%x), exit_status=%i)",3735            __FUNCTION__, debugserver_pid, signo, signo, exit_status);3736 3737  std::shared_ptr<ProcessGDBRemote> process_sp = process_wp.lock();3738  LLDB_LOGF(log, "ProcessGDBRemote::%s(process = %p)", __FUNCTION__,3739            static_cast<void *>(process_sp.get()));3740  if (!process_sp || process_sp->m_debugserver_pid != debugserver_pid)3741    return;3742 3743  // Sleep for a half a second to make sure our inferior process has time to3744  // set its exit status before we set it incorrectly when both the debugserver3745  // and the inferior process shut down.3746  std::this_thread::sleep_for(std::chrono::milliseconds(500));3747 3748  // If our process hasn't yet exited, debugserver might have died. If the3749  // process did exit, then we are reaping it.3750  const StateType state = process_sp->GetState();3751 3752  if (state != eStateInvalid && state != eStateUnloaded &&3753      state != eStateExited && state != eStateDetached) {3754    StreamString stream;3755    if (signo == 0)3756      stream.Format(DEBUGSERVER_BASENAME " died with an exit status of {0:x8}",3757                    exit_status);3758    else {3759      llvm::StringRef signal_name =3760          process_sp->GetUnixSignals()->GetSignalAsStringRef(signo);3761      const char *format_str = DEBUGSERVER_BASENAME " died with signal {0}";3762      if (!signal_name.empty())3763        stream.Format(format_str, signal_name);3764      else3765        stream.Format(format_str, signo);3766    }3767    process_sp->SetExitStatus(-1, stream.GetString());3768  }3769  // Debugserver has exited we need to let our ProcessGDBRemote know that it no3770  // longer has a debugserver instance3771  process_sp->m_debugserver_pid = LLDB_INVALID_PROCESS_ID;3772}3773 3774void ProcessGDBRemote::KillDebugserverProcess() {3775  m_gdb_comm.Disconnect();3776  if (m_debugserver_pid != LLDB_INVALID_PROCESS_ID) {3777    Host::Kill(m_debugserver_pid, SIGINT);3778    m_debugserver_pid = LLDB_INVALID_PROCESS_ID;3779  }3780}3781 3782void ProcessGDBRemote::Initialize() {3783  static llvm::once_flag g_once_flag;3784 3785  llvm::call_once(g_once_flag, []() {3786    PluginManager::RegisterPlugin(GetPluginNameStatic(),3787                                  GetPluginDescriptionStatic(), CreateInstance,3788                                  DebuggerInitialize);3789  });3790}3791 3792void ProcessGDBRemote::DebuggerInitialize(Debugger &debugger) {3793  if (!PluginManager::GetSettingForProcessPlugin(3794          debugger, PluginProperties::GetSettingName())) {3795    const bool is_global_setting = true;3796    PluginManager::CreateSettingForProcessPlugin(3797        debugger, GetGlobalPluginProperties().GetValueProperties(),3798        "Properties for the gdb-remote process plug-in.", is_global_setting);3799  }3800}3801 3802bool ProcessGDBRemote::StartAsyncThread() {3803  Log *log = GetLog(GDBRLog::Process);3804 3805  LLDB_LOGF(log, "ProcessGDBRemote::%s ()", __FUNCTION__);3806 3807  std::lock_guard<std::recursive_mutex> guard(m_async_thread_state_mutex);3808  if (!m_async_thread.IsJoinable()) {3809    // Create a thread that watches our internal state and controls which3810    // events make it to clients (into the DCProcess event queue).3811 3812    llvm::Expected<HostThread> async_thread =3813        ThreadLauncher::LaunchThread("<lldb.process.gdb-remote.async>", [this] {3814          return ProcessGDBRemote::AsyncThread();3815        });3816    if (!async_thread) {3817      LLDB_LOG_ERROR(GetLog(LLDBLog::Host), async_thread.takeError(),3818                     "failed to launch host thread: {0}");3819      return false;3820    }3821    m_async_thread = *async_thread;3822  } else3823    LLDB_LOGF(log,3824              "ProcessGDBRemote::%s () - Called when Async thread was "3825              "already running.",3826              __FUNCTION__);3827 3828  return m_async_thread.IsJoinable();3829}3830 3831void ProcessGDBRemote::StopAsyncThread() {3832  Log *log = GetLog(GDBRLog::Process);3833 3834  LLDB_LOGF(log, "ProcessGDBRemote::%s ()", __FUNCTION__);3835 3836  std::lock_guard<std::recursive_mutex> guard(m_async_thread_state_mutex);3837  if (m_async_thread.IsJoinable()) {3838    m_async_broadcaster.BroadcastEvent(eBroadcastBitAsyncThreadShouldExit);3839 3840    //  This will shut down the async thread.3841    m_gdb_comm.Disconnect(); // Disconnect from the debug server.3842 3843    // Stop the stdio thread3844    m_async_thread.Join(nullptr);3845    m_async_thread.Reset();3846  } else3847    LLDB_LOGF(3848        log,3849        "ProcessGDBRemote::%s () - Called when Async thread was not running.",3850        __FUNCTION__);3851}3852 3853thread_result_t ProcessGDBRemote::AsyncThread() {3854  Log *log = GetLog(GDBRLog::Process);3855  LLDB_LOGF(log, "ProcessGDBRemote::%s(pid = %" PRIu64 ") thread starting...",3856            __FUNCTION__, GetID());3857 3858  EventSP event_sp;3859 3860  // We need to ignore any packets that come in after we have3861  // have decided the process has exited.  There are some3862  // situations, for instance when we try to interrupt a running3863  // process and the interrupt fails, where another packet might3864  // get delivered after we've decided to give up on the process.3865  // But once we've decided we are done with the process we will3866  // not be in a state to do anything useful with new packets.3867  // So it is safer to simply ignore any remaining packets by3868  // explicitly checking for eStateExited before reentering the3869  // fetch loop.3870 3871  bool done = false;3872  while (!done && GetPrivateState() != eStateExited) {3873    LLDB_LOGF(log,3874              "ProcessGDBRemote::%s(pid = %" PRIu643875              ") listener.WaitForEvent (NULL, event_sp)...",3876              __FUNCTION__, GetID());3877 3878    if (m_async_listener_sp->GetEvent(event_sp, std::nullopt)) {3879      const uint32_t event_type = event_sp->GetType();3880      if (event_sp->BroadcasterIs(&m_async_broadcaster)) {3881        LLDB_LOGF(log,3882                  "ProcessGDBRemote::%s(pid = %" PRIu643883                  ") Got an event of type: %d...",3884                  __FUNCTION__, GetID(), event_type);3885 3886        switch (event_type) {3887        case eBroadcastBitAsyncContinue: {3888          const EventDataBytes *continue_packet =3889              EventDataBytes::GetEventDataFromEvent(event_sp.get());3890 3891          if (continue_packet) {3892            const char *continue_cstr =3893                (const char *)continue_packet->GetBytes();3894            const size_t continue_cstr_len = continue_packet->GetByteSize();3895            LLDB_LOGF(log,3896                      "ProcessGDBRemote::%s(pid = %" PRIu643897                      ") got eBroadcastBitAsyncContinue: %s",3898                      __FUNCTION__, GetID(), continue_cstr);3899 3900            if (::strstr(continue_cstr, "vAttach") == nullptr)3901              SetPrivateState(eStateRunning);3902            StringExtractorGDBRemote response;3903 3904            StateType stop_state =3905                GetGDBRemote().SendContinuePacketAndWaitForResponse(3906                    *this, *GetUnixSignals(),3907                    llvm::StringRef(continue_cstr, continue_cstr_len),3908                    GetInterruptTimeout(), response);3909 3910            // We need to immediately clear the thread ID list so we are sure3911            // to get a valid list of threads. The thread ID list might be3912            // contained within the "response", or the stop reply packet that3913            // caused the stop. So clear it now before we give the stop reply3914            // packet to the process using the3915            // SetLastStopPacket()...3916            ClearThreadIDList();3917 3918            switch (stop_state) {3919            case eStateStopped:3920            case eStateCrashed:3921            case eStateSuspended:3922              SetLastStopPacket(response);3923              SetPrivateState(stop_state);3924              break;3925 3926            case eStateExited: {3927              SetLastStopPacket(response);3928              ClearThreadIDList();3929              response.SetFilePos(1);3930 3931              int exit_status = response.GetHexU8();3932              std::string desc_string;3933              if (response.GetBytesLeft() > 0 && response.GetChar('-') == ';') {3934                llvm::StringRef desc_str;3935                llvm::StringRef desc_token;3936                while (response.GetNameColonValue(desc_token, desc_str)) {3937                  if (desc_token != "description")3938                    continue;3939                  StringExtractor extractor(desc_str);3940                  extractor.GetHexByteString(desc_string);3941                }3942              }3943              SetExitStatus(exit_status, desc_string.c_str());3944              done = true;3945              break;3946            }3947            case eStateInvalid: {3948              // Check to see if we were trying to attach and if we got back3949              // the "E87" error code from debugserver -- this indicates that3950              // the process is not debuggable.  Return a slightly more3951              // helpful error message about why the attach failed.3952              if (::strstr(continue_cstr, "vAttach") != nullptr &&3953                  response.GetError() == 0x87) {3954                SetExitStatus(-1, "cannot attach to process due to "3955                                  "System Integrity Protection");3956              } else if (::strstr(continue_cstr, "vAttach") != nullptr &&3957                         response.GetStatus().Fail()) {3958                SetExitStatus(-1, response.GetStatus().AsCString());3959              } else {3960                SetExitStatus(-1, "lost connection");3961              }3962              done = true;3963              break;3964            }3965 3966            default:3967              SetPrivateState(stop_state);3968              break;3969            }   // switch(stop_state)3970          }     // if (continue_packet)3971        }       // case eBroadcastBitAsyncContinue3972        break;3973 3974        case eBroadcastBitAsyncThreadShouldExit:3975          LLDB_LOGF(log,3976                    "ProcessGDBRemote::%s(pid = %" PRIu643977                    ") got eBroadcastBitAsyncThreadShouldExit...",3978                    __FUNCTION__, GetID());3979          done = true;3980          break;3981 3982        default:3983          LLDB_LOGF(log,3984                    "ProcessGDBRemote::%s(pid = %" PRIu643985                    ") got unknown event 0x%8.8x",3986                    __FUNCTION__, GetID(), event_type);3987          done = true;3988          break;3989        }3990      }3991    } else {3992      LLDB_LOGF(log,3993                "ProcessGDBRemote::%s(pid = %" PRIu643994                ") listener.WaitForEvent (NULL, event_sp) => false",3995                __FUNCTION__, GetID());3996      done = true;3997    }3998  }3999 4000  LLDB_LOGF(log, "ProcessGDBRemote::%s(pid = %" PRIu64 ") thread exiting...",4001            __FUNCTION__, GetID());4002 4003  return {};4004}4005 4006// uint32_t4007// ProcessGDBRemote::ListProcessesMatchingName (const char *name, StringList4008// &matches, std::vector<lldb::pid_t> &pids)4009//{4010//    // If we are planning to launch the debugserver remotely, then we need to4011//    fire up a debugserver4012//    // process and ask it for the list of processes. But if we are local, we4013//    can let the Host do it.4014//    if (m_local_debugserver)4015//    {4016//        return Host::ListProcessesMatchingName (name, matches, pids);4017//    }4018//    else4019//    {4020//        // FIXME: Implement talking to the remote debugserver.4021//        return 0;4022//    }4023//4024//}4025//4026bool ProcessGDBRemote::NewThreadNotifyBreakpointHit(4027    void *baton, StoppointCallbackContext *context, lldb::user_id_t break_id,4028    lldb::user_id_t break_loc_id) {4029  // I don't think I have to do anything here, just make sure I notice the new4030  // thread when it starts to4031  // run so I can stop it if that's what I want to do.4032  Log *log = GetLog(LLDBLog::Step);4033  LLDB_LOGF(log, "Hit New Thread Notification breakpoint.");4034  return false;4035}4036 4037Status ProcessGDBRemote::UpdateAutomaticSignalFiltering() {4038  Log *log = GetLog(GDBRLog::Process);4039  LLDB_LOG(log, "Check if need to update ignored signals");4040 4041  // QPassSignals package is not supported by the server, there is no way we4042  // can ignore any signals on server side.4043  if (!m_gdb_comm.GetQPassSignalsSupported())4044    return Status();4045 4046  // No signals, nothing to send.4047  if (m_unix_signals_sp == nullptr)4048    return Status();4049 4050  // Signals' version hasn't changed, no need to send anything.4051  uint64_t new_signals_version = m_unix_signals_sp->GetVersion();4052  if (new_signals_version == m_last_signals_version) {4053    LLDB_LOG(log, "Signals' version hasn't changed. version={0}",4054             m_last_signals_version);4055    return Status();4056  }4057 4058  auto signals_to_ignore =4059      m_unix_signals_sp->GetFilteredSignals(false, false, false);4060  Status error = m_gdb_comm.SendSignalsToIgnore(signals_to_ignore);4061 4062  LLDB_LOG(log,4063           "Signals' version changed. old version={0}, new version={1}, "4064           "signals ignored={2}, update result={3}",4065           m_last_signals_version, new_signals_version,4066           signals_to_ignore.size(), error);4067 4068  if (error.Success())4069    m_last_signals_version = new_signals_version;4070 4071  return error;4072}4073 4074bool ProcessGDBRemote::StartNoticingNewThreads() {4075  Log *log = GetLog(LLDBLog::Step);4076  if (m_thread_create_bp_sp) {4077    if (log && log->GetVerbose())4078      LLDB_LOGF(log, "Enabled noticing new thread breakpoint.");4079    m_thread_create_bp_sp->SetEnabled(true);4080  } else {4081    PlatformSP platform_sp(GetTarget().GetPlatform());4082    if (platform_sp) {4083      m_thread_create_bp_sp =4084          platform_sp->SetThreadCreationBreakpoint(GetTarget());4085      if (m_thread_create_bp_sp) {4086        if (log && log->GetVerbose())4087          LLDB_LOGF(4088              log, "Successfully created new thread notification breakpoint %i",4089              m_thread_create_bp_sp->GetID());4090        m_thread_create_bp_sp->SetCallback(4091            ProcessGDBRemote::NewThreadNotifyBreakpointHit, this, true);4092      } else {4093        LLDB_LOGF(log, "Failed to create new thread notification breakpoint.");4094      }4095    }4096  }4097  return m_thread_create_bp_sp.get() != nullptr;4098}4099 4100bool ProcessGDBRemote::StopNoticingNewThreads() {4101  Log *log = GetLog(LLDBLog::Step);4102  if (log && log->GetVerbose())4103    LLDB_LOGF(log, "Disabling new thread notification breakpoint.");4104 4105  if (m_thread_create_bp_sp)4106    m_thread_create_bp_sp->SetEnabled(false);4107 4108  return true;4109}4110 4111DynamicLoader *ProcessGDBRemote::GetDynamicLoader() {4112  if (m_dyld_up.get() == nullptr)4113    m_dyld_up.reset(DynamicLoader::FindPlugin(this, ""));4114  return m_dyld_up.get();4115}4116 4117Status ProcessGDBRemote::SendEventData(const char *data) {4118  int return_value;4119  bool was_supported;4120 4121  Status error;4122 4123  return_value = m_gdb_comm.SendLaunchEventDataPacket(data, &was_supported);4124  if (return_value != 0) {4125    if (!was_supported)4126      error = Status::FromErrorString(4127          "Sending events is not supported for this process.");4128    else4129      error = Status::FromErrorStringWithFormat("Error sending event data: %d.",4130                                                return_value);4131  }4132  return error;4133}4134 4135DataExtractor ProcessGDBRemote::GetAuxvData() {4136  DataBufferSP buf;4137  if (m_gdb_comm.GetQXferAuxvReadSupported()) {4138    llvm::Expected<std::string> response = m_gdb_comm.ReadExtFeature("auxv", "");4139    if (response)4140      buf = std::make_shared<DataBufferHeap>(response->c_str(),4141                                             response->length());4142    else4143      LLDB_LOG_ERROR(GetLog(GDBRLog::Process), response.takeError(), "{0}");4144  }4145  return DataExtractor(buf, GetByteOrder(), GetAddressByteSize());4146}4147 4148StructuredData::ObjectSP4149ProcessGDBRemote::GetExtendedInfoForThread(lldb::tid_t tid) {4150  StructuredData::ObjectSP object_sp;4151 4152  if (m_gdb_comm.GetThreadExtendedInfoSupported()) {4153    StructuredData::ObjectSP args_dict(new StructuredData::Dictionary());4154    SystemRuntime *runtime = GetSystemRuntime();4155    if (runtime) {4156      runtime->AddThreadExtendedInfoPacketHints(args_dict);4157    }4158    args_dict->GetAsDictionary()->AddIntegerItem("thread", tid);4159 4160    StreamString packet;4161    packet << "jThreadExtendedInfo:";4162    args_dict->Dump(packet, false);4163 4164    // FIXME the final character of a JSON dictionary, '}', is the escape4165    // character in gdb-remote binary mode.  lldb currently doesn't escape4166    // these characters in its packet output -- so we add the quoted version of4167    // the } character here manually in case we talk to a debugserver which un-4168    // escapes the characters at packet read time.4169    packet << (char)(0x7d ^ 0x20);4170 4171    StringExtractorGDBRemote response;4172    response.SetResponseValidatorToJSON();4173    if (m_gdb_comm.SendPacketAndWaitForResponse(packet.GetString(), response) ==4174        GDBRemoteCommunication::PacketResult::Success) {4175      StringExtractorGDBRemote::ResponseType response_type =4176          response.GetResponseType();4177      if (response_type == StringExtractorGDBRemote::eResponse) {4178        if (!response.Empty()) {4179          object_sp = StructuredData::ParseJSON(response.GetStringRef());4180        }4181      }4182    }4183  }4184  return object_sp;4185}4186 4187StructuredData::ObjectSP ProcessGDBRemote::GetLoadedDynamicLibrariesInfos(4188    lldb::addr_t image_list_address, lldb::addr_t image_count) {4189 4190  StructuredData::ObjectSP args_dict(new StructuredData::Dictionary());4191  args_dict->GetAsDictionary()->AddIntegerItem("image_list_address",4192                                               image_list_address);4193  args_dict->GetAsDictionary()->AddIntegerItem("image_count", image_count);4194 4195  return GetLoadedDynamicLibrariesInfos_sender(args_dict);4196}4197 4198StructuredData::ObjectSP ProcessGDBRemote::GetLoadedDynamicLibrariesInfos() {4199  StructuredData::ObjectSP args_dict(new StructuredData::Dictionary());4200 4201  args_dict->GetAsDictionary()->AddBooleanItem("fetch_all_solibs", true);4202 4203  return GetLoadedDynamicLibrariesInfos_sender(args_dict);4204}4205 4206StructuredData::ObjectSP ProcessGDBRemote::GetLoadedDynamicLibrariesInfos(4207    const std::vector<lldb::addr_t> &load_addresses) {4208  StructuredData::ObjectSP args_dict(new StructuredData::Dictionary());4209  StructuredData::ArraySP addresses(new StructuredData::Array);4210 4211  for (auto addr : load_addresses)4212    addresses->AddIntegerItem(addr);4213 4214  args_dict->GetAsDictionary()->AddItem("solib_addresses", addresses);4215 4216  return GetLoadedDynamicLibrariesInfos_sender(args_dict);4217}4218 4219StructuredData::ObjectSP4220ProcessGDBRemote::GetLoadedDynamicLibrariesInfos_sender(4221    StructuredData::ObjectSP args_dict) {4222  StructuredData::ObjectSP object_sp;4223 4224  if (m_gdb_comm.GetLoadedDynamicLibrariesInfosSupported()) {4225    // Scope for the scoped timeout object4226    GDBRemoteCommunication::ScopedTimeout timeout(m_gdb_comm,4227                                                  std::chrono::seconds(10));4228 4229    StreamString packet;4230    packet << "jGetLoadedDynamicLibrariesInfos:";4231    args_dict->Dump(packet, false);4232 4233    // FIXME the final character of a JSON dictionary, '}', is the escape4234    // character in gdb-remote binary mode.  lldb currently doesn't escape4235    // these characters in its packet output -- so we add the quoted version of4236    // the } character here manually in case we talk to a debugserver which un-4237    // escapes the characters at packet read time.4238    packet << (char)(0x7d ^ 0x20);4239 4240    StringExtractorGDBRemote response;4241    response.SetResponseValidatorToJSON();4242    if (m_gdb_comm.SendPacketAndWaitForResponse(packet.GetString(), response) ==4243        GDBRemoteCommunication::PacketResult::Success) {4244      StringExtractorGDBRemote::ResponseType response_type =4245          response.GetResponseType();4246      if (response_type == StringExtractorGDBRemote::eResponse) {4247        if (!response.Empty()) {4248          object_sp = StructuredData::ParseJSON(response.GetStringRef());4249        }4250      }4251    }4252  }4253  return object_sp;4254}4255 4256StructuredData::ObjectSP ProcessGDBRemote::GetDynamicLoaderProcessState() {4257  StructuredData::ObjectSP object_sp;4258  StructuredData::ObjectSP args_dict(new StructuredData::Dictionary());4259 4260  if (m_gdb_comm.GetDynamicLoaderProcessStateSupported()) {4261    StringExtractorGDBRemote response;4262    response.SetResponseValidatorToJSON();4263    if (m_gdb_comm.SendPacketAndWaitForResponse("jGetDyldProcessState",4264                                                response) ==4265        GDBRemoteCommunication::PacketResult::Success) {4266      StringExtractorGDBRemote::ResponseType response_type =4267          response.GetResponseType();4268      if (response_type == StringExtractorGDBRemote::eResponse) {4269        if (!response.Empty()) {4270          object_sp = StructuredData::ParseJSON(response.GetStringRef());4271        }4272      }4273    }4274  }4275  return object_sp;4276}4277 4278StructuredData::ObjectSP ProcessGDBRemote::GetSharedCacheInfo() {4279  StructuredData::ObjectSP object_sp;4280  StructuredData::ObjectSP args_dict(new StructuredData::Dictionary());4281 4282  if (m_gdb_comm.GetSharedCacheInfoSupported()) {4283    StreamString packet;4284    packet << "jGetSharedCacheInfo:";4285    args_dict->Dump(packet, false);4286 4287    // FIXME the final character of a JSON dictionary, '}', is the escape4288    // character in gdb-remote binary mode.  lldb currently doesn't escape4289    // these characters in its packet output -- so we add the quoted version of4290    // the } character here manually in case we talk to a debugserver which un-4291    // escapes the characters at packet read time.4292    packet << (char)(0x7d ^ 0x20);4293 4294    StringExtractorGDBRemote response;4295    response.SetResponseValidatorToJSON();4296    if (m_gdb_comm.SendPacketAndWaitForResponse(packet.GetString(), response) ==4297        GDBRemoteCommunication::PacketResult::Success) {4298      StringExtractorGDBRemote::ResponseType response_type =4299          response.GetResponseType();4300      if (response_type == StringExtractorGDBRemote::eResponse) {4301        if (!response.Empty()) {4302          object_sp = StructuredData::ParseJSON(response.GetStringRef());4303        }4304      }4305    }4306  }4307  return object_sp;4308}4309 4310Status ProcessGDBRemote::ConfigureStructuredData(4311    llvm::StringRef type_name, const StructuredData::ObjectSP &config_sp) {4312  return m_gdb_comm.ConfigureRemoteStructuredData(type_name, config_sp);4313}4314 4315// Establish the largest memory read/write payloads we should use. If the4316// remote stub has a max packet size, stay under that size.4317//4318// If the remote stub's max packet size is crazy large, use a reasonable4319// largeish default.4320//4321// If the remote stub doesn't advertise a max packet size, use a conservative4322// default.4323 4324void ProcessGDBRemote::GetMaxMemorySize() {4325  const uint64_t reasonable_largeish_default = 128 * 1024;4326  const uint64_t conservative_default = 512;4327 4328  if (m_max_memory_size == 0) {4329    uint64_t stub_max_size = m_gdb_comm.GetRemoteMaxPacketSize();4330    if (stub_max_size != UINT64_MAX && stub_max_size != 0) {4331      // Save the stub's claimed maximum packet size4332      m_remote_stub_max_memory_size = stub_max_size;4333 4334      // Even if the stub says it can support ginormous packets, don't exceed4335      // our reasonable largeish default packet size.4336      if (stub_max_size > reasonable_largeish_default) {4337        stub_max_size = reasonable_largeish_default;4338      }4339 4340      // Memory packet have other overheads too like Maddr,size:#NN Instead of4341      // calculating the bytes taken by size and addr every time, we take a4342      // maximum guess here.4343      if (stub_max_size > 70)4344        stub_max_size -= 32 + 32 + 6;4345      else {4346        // In unlikely scenario that max packet size is less then 70, we will4347        // hope that data being written is small enough to fit.4348        Log *log(GetLog(GDBRLog::Comm | GDBRLog::Memory));4349        if (log)4350          log->Warning("Packet size is too small. "4351                       "LLDB may face problems while writing memory");4352      }4353 4354      m_max_memory_size = stub_max_size;4355    } else {4356      m_max_memory_size = conservative_default;4357    }4358  }4359}4360 4361void ProcessGDBRemote::SetUserSpecifiedMaxMemoryTransferSize(4362    uint64_t user_specified_max) {4363  if (user_specified_max != 0) {4364    GetMaxMemorySize();4365 4366    if (m_remote_stub_max_memory_size != 0) {4367      if (m_remote_stub_max_memory_size < user_specified_max) {4368        m_max_memory_size = m_remote_stub_max_memory_size; // user specified a4369                                                           // packet size too4370                                                           // big, go as big4371        // as the remote stub says we can go.4372      } else {4373        m_max_memory_size = user_specified_max; // user's packet size is good4374      }4375    } else {4376      m_max_memory_size =4377          user_specified_max; // user's packet size is probably fine4378    }4379  }4380}4381 4382bool ProcessGDBRemote::GetModuleSpec(const FileSpec &module_file_spec,4383                                     const ArchSpec &arch,4384                                     ModuleSpec &module_spec) {4385  Log *log = GetLog(LLDBLog::Platform);4386 4387  const ModuleCacheKey key(module_file_spec.GetPath(),4388                           arch.GetTriple().getTriple());4389  auto cached = m_cached_module_specs.find(key);4390  if (cached != m_cached_module_specs.end()) {4391    module_spec = cached->second;4392    return bool(module_spec);4393  }4394 4395  if (!m_gdb_comm.GetModuleInfo(module_file_spec, arch, module_spec)) {4396    LLDB_LOGF(log, "ProcessGDBRemote::%s - failed to get module info for %s:%s",4397              __FUNCTION__, module_file_spec.GetPath().c_str(),4398              arch.GetTriple().getTriple().c_str());4399    return false;4400  }4401 4402  if (log) {4403    StreamString stream;4404    module_spec.Dump(stream);4405    LLDB_LOGF(log, "ProcessGDBRemote::%s - got module info for (%s:%s) : %s",4406              __FUNCTION__, module_file_spec.GetPath().c_str(),4407              arch.GetTriple().getTriple().c_str(), stream.GetData());4408  }4409 4410  m_cached_module_specs[key] = module_spec;4411  return true;4412}4413 4414void ProcessGDBRemote::PrefetchModuleSpecs(4415    llvm::ArrayRef<FileSpec> module_file_specs, const llvm::Triple &triple) {4416  auto module_specs = m_gdb_comm.GetModulesInfo(module_file_specs, triple);4417  if (module_specs) {4418    for (const FileSpec &spec : module_file_specs)4419      m_cached_module_specs[ModuleCacheKey(spec.GetPath(),4420                                           triple.getTriple())] = ModuleSpec();4421    for (const ModuleSpec &spec : *module_specs)4422      m_cached_module_specs[ModuleCacheKey(spec.GetFileSpec().GetPath(),4423                                           triple.getTriple())] = spec;4424  }4425}4426 4427llvm::VersionTuple ProcessGDBRemote::GetHostOSVersion() {4428  return m_gdb_comm.GetOSVersion();4429}4430 4431llvm::VersionTuple ProcessGDBRemote::GetHostMacCatalystVersion() {4432  return m_gdb_comm.GetMacCatalystVersion();4433}4434 4435namespace {4436 4437typedef std::vector<std::string> stringVec;4438 4439typedef std::vector<struct GdbServerRegisterInfo> GDBServerRegisterVec;4440struct RegisterSetInfo {4441  ConstString name;4442};4443 4444typedef std::map<uint32_t, RegisterSetInfo> RegisterSetMap;4445 4446struct GdbServerTargetInfo {4447  std::string arch;4448  std::string osabi;4449  stringVec includes;4450  RegisterSetMap reg_set_map;4451};4452 4453static FieldEnum::Enumerators ParseEnumEvalues(const XMLNode &enum_node) {4454  Log *log(GetLog(GDBRLog::Process));4455  // We will use the last instance of each value. Also we preserve the order4456  // of declaration in the XML, as it may not be numerical.4457  // For example, hardware may intially release with two states that softwware4458  // can read from a register field:4459  // 0 = startup, 1 = running4460  // If in a future hardware release, the designers added a pre-startup state:4461  // 0 = startup, 1 = running, 2 = pre-startup4462  // Now it makes more sense to list them in this logical order as opposed to4463  // numerical order:4464  // 2 = pre-startup, 1 = startup, 0 = startup4465  // This only matters for "register info" but let's trust what the server4466  // chose regardless.4467  std::map<uint64_t, FieldEnum::Enumerator> enumerators;4468 4469  enum_node.ForEachChildElementWithName(4470      "evalue", [&enumerators, &log](const XMLNode &enumerator_node) {4471        std::optional<llvm::StringRef> name;4472        std::optional<uint64_t> value;4473 4474        enumerator_node.ForEachAttribute(4475            [&name, &value, &log](const llvm::StringRef &attr_name,4476                                  const llvm::StringRef &attr_value) {4477              if (attr_name == "name") {4478                if (attr_value.size())4479                  name = attr_value;4480                else4481                  LLDB_LOG(log, "ProcessGDBRemote::ParseEnumEvalues "4482                                "Ignoring empty name in evalue");4483              } else if (attr_name == "value") {4484                uint64_t parsed_value = 0;4485                if (llvm::to_integer(attr_value, parsed_value))4486                  value = parsed_value;4487                else4488                  LLDB_LOG(log,4489                           "ProcessGDBRemote::ParseEnumEvalues "4490                           "Invalid value \"{0}\" in "4491                           "evalue",4492                           attr_value.data());4493              } else4494                LLDB_LOG(log,4495                         "ProcessGDBRemote::ParseEnumEvalues Ignoring "4496                         "unknown attribute "4497                         "\"{0}\" in evalue",4498                         attr_name.data());4499 4500              // Keep walking attributes.4501              return true;4502            });4503 4504        if (value && name)4505          enumerators.insert_or_assign(4506              *value, FieldEnum::Enumerator(*value, name->str()));4507 4508        // Find all evalue elements.4509        return true;4510      });4511 4512  FieldEnum::Enumerators final_enumerators;4513  for (auto [_, enumerator] : enumerators)4514    final_enumerators.push_back(enumerator);4515 4516  return final_enumerators;4517}4518 4519static void4520ParseEnums(XMLNode feature_node,4521           llvm::StringMap<std::unique_ptr<FieldEnum>> &registers_enum_types) {4522  Log *log(GetLog(GDBRLog::Process));4523 4524  // The top level element is "<enum...".4525  feature_node.ForEachChildElementWithName(4526      "enum", [log, &registers_enum_types](const XMLNode &enum_node) {4527        std::string id;4528 4529        enum_node.ForEachAttribute([&id](const llvm::StringRef &attr_name,4530                                         const llvm::StringRef &attr_value) {4531          if (attr_name == "id")4532            id = attr_value;4533 4534          // There is also a "size" attribute that is supposed to be the size in4535          // bytes of the register this applies to. However:4536          // * LLDB doesn't need this information.4537          // * It  is difficult to verify because you have to wait until the4538          //   enum is applied to a field.4539          //4540          // So we will emit this attribute in XML for GDB's sake, but will not4541          // bother ingesting it.4542 4543          // Walk all attributes.4544          return true;4545        });4546 4547        if (!id.empty()) {4548          FieldEnum::Enumerators enumerators = ParseEnumEvalues(enum_node);4549          if (!enumerators.empty()) {4550            LLDB_LOG(log,4551                     "ProcessGDBRemote::ParseEnums Found enum type \"{0}\"",4552                     id);4553            registers_enum_types.insert_or_assign(4554                id, std::make_unique<FieldEnum>(id, enumerators));4555          }4556        }4557 4558        // Find all <enum> elements.4559        return true;4560      });4561}4562 4563static std::vector<RegisterFlags::Field> ParseFlagsFields(4564    XMLNode flags_node, unsigned size,4565    const llvm::StringMap<std::unique_ptr<FieldEnum>> &registers_enum_types) {4566  Log *log(GetLog(GDBRLog::Process));4567  const unsigned max_start_bit = size * 8 - 1;4568 4569  // Process the fields of this set of flags.4570  std::vector<RegisterFlags::Field> fields;4571  flags_node.ForEachChildElementWithName("field", [&fields, max_start_bit, &log,4572                                                   &registers_enum_types](4573                                                      const XMLNode4574                                                          &field_node) {4575    std::optional<llvm::StringRef> name;4576    std::optional<unsigned> start;4577    std::optional<unsigned> end;4578    std::optional<llvm::StringRef> type;4579 4580    field_node.ForEachAttribute([&name, &start, &end, &type, max_start_bit,4581                                 &log](const llvm::StringRef &attr_name,4582                                       const llvm::StringRef &attr_value) {4583      // Note that XML in general requires that each of these attributes only4584      // appears once, so we don't have to handle that here.4585      if (attr_name == "name") {4586        LLDB_LOG(4587            log,4588            "ProcessGDBRemote::ParseFlagsFields Found field node name \"{0}\"",4589            attr_value.data());4590        name = attr_value;4591      } else if (attr_name == "start") {4592        unsigned parsed_start = 0;4593        if (llvm::to_integer(attr_value, parsed_start)) {4594          if (parsed_start > max_start_bit) {4595            LLDB_LOG(log,4596                     "ProcessGDBRemote::ParseFlagsFields Invalid start {0} in "4597                     "field node, "4598                     "cannot be > {1}",4599                     parsed_start, max_start_bit);4600          } else4601            start = parsed_start;4602        } else {4603          LLDB_LOG(4604              log,4605              "ProcessGDBRemote::ParseFlagsFields Invalid start \"{0}\" in "4606              "field node",4607              attr_value.data());4608        }4609      } else if (attr_name == "end") {4610        unsigned parsed_end = 0;4611        if (llvm::to_integer(attr_value, parsed_end))4612          if (parsed_end > max_start_bit) {4613            LLDB_LOG(log,4614                     "ProcessGDBRemote::ParseFlagsFields Invalid end {0} in "4615                     "field node, "4616                     "cannot be > {1}",4617                     parsed_end, max_start_bit);4618          } else4619            end = parsed_end;4620        else {4621          LLDB_LOG(log,4622                   "ProcessGDBRemote::ParseFlagsFields Invalid end \"{0}\" in "4623                   "field node",4624                   attr_value.data());4625        }4626      } else if (attr_name == "type") {4627        type = attr_value;4628      } else {4629        LLDB_LOG(4630            log,4631            "ProcessGDBRemote::ParseFlagsFields Ignoring unknown attribute "4632            "\"{0}\" in field node",4633            attr_name.data());4634      }4635 4636      return true; // Walk all attributes of the field.4637    });4638 4639    if (name && start && end) {4640      if (*start > *end)4641        LLDB_LOG(4642            log,4643            "ProcessGDBRemote::ParseFlagsFields Start {0} > end {1} in field "4644            "\"{2}\", ignoring",4645            *start, *end, name->data());4646      else {4647        if (RegisterFlags::Field::GetSizeInBits(*start, *end) > 64)4648          LLDB_LOG(log,4649                   "ProcessGDBRemote::ParseFlagsFields Ignoring field \"{2}\" "4650                   "that has "4651                   "size > 64 bits, this is not supported",4652                   name->data());4653        else {4654          // A field's type may be set to the name of an enum type.4655          const FieldEnum *enum_type = nullptr;4656          if (type && !type->empty()) {4657            auto found = registers_enum_types.find(*type);4658            if (found != registers_enum_types.end()) {4659              enum_type = found->second.get();4660 4661              // No enumerator can exceed the range of the field itself.4662              uint64_t max_value =4663                  RegisterFlags::Field::GetMaxValue(*start, *end);4664              for (const auto &enumerator : enum_type->GetEnumerators()) {4665                if (enumerator.m_value > max_value) {4666                  enum_type = nullptr;4667                  LLDB_LOG(4668                      log,4669                      "ProcessGDBRemote::ParseFlagsFields In enum \"{0}\" "4670                      "evalue \"{1}\" with value {2} exceeds the maximum value "4671                      "of field \"{3}\" ({4}), ignoring enum",4672                      type->data(), enumerator.m_name, enumerator.m_value,4673                      name->data(), max_value);4674                  break;4675                }4676              }4677            } else {4678              LLDB_LOG(log,4679                       "ProcessGDBRemote::ParseFlagsFields Could not find type "4680                       "\"{0}\" "4681                       "for field \"{1}\", ignoring",4682                       type->data(), name->data());4683            }4684          }4685 4686          fields.push_back(4687              RegisterFlags::Field(name->str(), *start, *end, enum_type));4688        }4689      }4690    }4691 4692    return true; // Iterate all "field" nodes.4693  });4694  return fields;4695}4696 4697void ParseFlags(4698    XMLNode feature_node,4699    llvm::StringMap<std::unique_ptr<RegisterFlags>> &registers_flags_types,4700    const llvm::StringMap<std::unique_ptr<FieldEnum>> &registers_enum_types) {4701  Log *log(GetLog(GDBRLog::Process));4702 4703  feature_node.ForEachChildElementWithName(4704      "flags",4705      [&log, &registers_flags_types,4706       &registers_enum_types](const XMLNode &flags_node) -> bool {4707        LLDB_LOG(log, "ProcessGDBRemote::ParseFlags Found flags node \"{0}\"",4708                 flags_node.GetAttributeValue("id").c_str());4709 4710        std::optional<llvm::StringRef> id;4711        std::optional<unsigned> size;4712        flags_node.ForEachAttribute(4713            [&id, &size, &log](const llvm::StringRef &name,4714                               const llvm::StringRef &value) {4715              if (name == "id") {4716                id = value;4717              } else if (name == "size") {4718                unsigned parsed_size = 0;4719                if (llvm::to_integer(value, parsed_size))4720                  size = parsed_size;4721                else {4722                  LLDB_LOG(log,4723                           "ProcessGDBRemote::ParseFlags Invalid size \"{0}\" "4724                           "in flags node",4725                           value.data());4726                }4727              } else {4728                LLDB_LOG(log,4729                         "ProcessGDBRemote::ParseFlags Ignoring unknown "4730                         "attribute \"{0}\" in flags node",4731                         name.data());4732              }4733              return true; // Walk all attributes.4734            });4735 4736        if (id && size) {4737          // Process the fields of this set of flags.4738          std::vector<RegisterFlags::Field> fields =4739              ParseFlagsFields(flags_node, *size, registers_enum_types);4740          if (fields.size()) {4741            // Sort so that the fields with the MSBs are first.4742            std::sort(fields.rbegin(), fields.rend());4743            std::vector<RegisterFlags::Field>::const_iterator overlap =4744                std::adjacent_find(fields.begin(), fields.end(),4745                                   [](const RegisterFlags::Field &lhs,4746                                      const RegisterFlags::Field &rhs) {4747                                     return lhs.Overlaps(rhs);4748                                   });4749 4750            // If no fields overlap, use them.4751            if (overlap == fields.end()) {4752              if (registers_flags_types.contains(*id)) {4753                // In theory you could define some flag set, use it with a4754                // register then redefine it. We do not know if anyone does4755                // that, or what they would expect to happen in that case.4756                //4757                // LLDB chooses to take the first definition and ignore the rest4758                // as waiting until everything has been processed is more4759                // expensive and difficult. This means that pointers to flag4760                // sets in the register info remain valid if later the flag set4761                // is redefined. If we allowed redefinitions, LLDB would crash4762                // when you tried to print a register that used the original4763                // definition.4764                LLDB_LOG(4765                    log,4766                    "ProcessGDBRemote::ParseFlags Definition of flags "4767                    "\"{0}\" shadows "4768                    "previous definition, using original definition instead.",4769                    id->data());4770              } else {4771                registers_flags_types.insert_or_assign(4772                    *id, std::make_unique<RegisterFlags>(id->str(), *size,4773                                                         std::move(fields)));4774              }4775            } else {4776              // If any fields overlap, ignore the whole set of flags.4777              std::vector<RegisterFlags::Field>::const_iterator next =4778                  std::next(overlap);4779              LLDB_LOG(4780                  log,4781                  "ProcessGDBRemote::ParseFlags Ignoring flags because fields "4782                  "{0} (start: {1} end: {2}) and {3} (start: {4} end: {5}) "4783                  "overlap.",4784                  overlap->GetName().c_str(), overlap->GetStart(),4785                  overlap->GetEnd(), next->GetName().c_str(), next->GetStart(),4786                  next->GetEnd());4787            }4788          } else {4789            LLDB_LOG(4790                log,4791                "ProcessGDBRemote::ParseFlags Ignoring definition of flags "4792                "\"{0}\" because it contains no fields.",4793                id->data());4794          }4795        }4796 4797        return true; // Keep iterating through all "flags" elements.4798      });4799}4800 4801bool ParseRegisters(4802    XMLNode feature_node, GdbServerTargetInfo &target_info,4803    std::vector<DynamicRegisterInfo::Register> &registers,4804    llvm::StringMap<std::unique_ptr<RegisterFlags>> &registers_flags_types,4805    llvm::StringMap<std::unique_ptr<FieldEnum>> &registers_enum_types) {4806  if (!feature_node)4807    return false;4808 4809  Log *log(GetLog(GDBRLog::Process));4810 4811  // Enums first because they are referenced by fields in the flags.4812  ParseEnums(feature_node, registers_enum_types);4813  for (const auto &enum_type : registers_enum_types)4814    enum_type.second->DumpToLog(log);4815 4816  ParseFlags(feature_node, registers_flags_types, registers_enum_types);4817  for (const auto &flags : registers_flags_types)4818    flags.second->DumpToLog(log);4819 4820  feature_node.ForEachChildElementWithName(4821      "reg",4822      [&target_info, &registers, &registers_flags_types,4823       log](const XMLNode &reg_node) -> bool {4824        std::string gdb_group;4825        std::string gdb_type;4826        DynamicRegisterInfo::Register reg_info;4827        bool encoding_set = false;4828        bool format_set = false;4829 4830        // FIXME: we're silently ignoring invalid data here4831        reg_node.ForEachAttribute([&target_info, &gdb_group, &gdb_type,4832                                   &encoding_set, &format_set, &reg_info,4833                                   log](const llvm::StringRef &name,4834                                        const llvm::StringRef &value) -> bool {4835          if (name == "name") {4836            reg_info.name.SetString(value);4837          } else if (name == "bitsize") {4838            if (llvm::to_integer(value, reg_info.byte_size))4839              reg_info.byte_size =4840                  llvm::divideCeil(reg_info.byte_size, CHAR_BIT);4841          } else if (name == "type") {4842            gdb_type = value.str();4843          } else if (name == "group") {4844            gdb_group = value.str();4845          } else if (name == "regnum") {4846            llvm::to_integer(value, reg_info.regnum_remote);4847          } else if (name == "offset") {4848            llvm::to_integer(value, reg_info.byte_offset);4849          } else if (name == "altname") {4850            reg_info.alt_name.SetString(value);4851          } else if (name == "encoding") {4852            encoding_set = true;4853            reg_info.encoding = Args::StringToEncoding(value, eEncodingUint);4854          } else if (name == "format") {4855            format_set = true;4856            if (!OptionArgParser::ToFormat(value.data(), reg_info.format,4857                                           nullptr)4858                     .Success())4859              reg_info.format =4860                  llvm::StringSwitch<lldb::Format>(value)4861                      .Case("vector-sint8", eFormatVectorOfSInt8)4862                      .Case("vector-uint8", eFormatVectorOfUInt8)4863                      .Case("vector-sint16", eFormatVectorOfSInt16)4864                      .Case("vector-uint16", eFormatVectorOfUInt16)4865                      .Case("vector-sint32", eFormatVectorOfSInt32)4866                      .Case("vector-uint32", eFormatVectorOfUInt32)4867                      .Case("vector-float32", eFormatVectorOfFloat32)4868                      .Case("vector-uint64", eFormatVectorOfUInt64)4869                      .Case("vector-uint128", eFormatVectorOfUInt128)4870                      .Default(eFormatInvalid);4871          } else if (name == "group_id") {4872            uint32_t set_id = UINT32_MAX;4873            llvm::to_integer(value, set_id);4874            RegisterSetMap::const_iterator pos =4875                target_info.reg_set_map.find(set_id);4876            if (pos != target_info.reg_set_map.end())4877              reg_info.set_name = pos->second.name;4878          } else if (name == "gcc_regnum" || name == "ehframe_regnum") {4879            llvm::to_integer(value, reg_info.regnum_ehframe);4880          } else if (name == "dwarf_regnum") {4881            llvm::to_integer(value, reg_info.regnum_dwarf);4882          } else if (name == "generic") {4883            reg_info.regnum_generic = Args::StringToGenericRegister(value);4884          } else if (name == "value_regnums") {4885            SplitCommaSeparatedRegisterNumberString(value, reg_info.value_regs,4886                                                    0);4887          } else if (name == "invalidate_regnums") {4888            SplitCommaSeparatedRegisterNumberString(4889                value, reg_info.invalidate_regs, 0);4890          } else {4891            LLDB_LOGF(log,4892                      "ProcessGDBRemote::ParseRegisters unhandled reg "4893                      "attribute %s = %s",4894                      name.data(), value.data());4895          }4896          return true; // Keep iterating through all attributes4897        });4898 4899        if (!gdb_type.empty()) {4900          // gdb_type could reference some flags type defined in XML.4901          llvm::StringMap<std::unique_ptr<RegisterFlags>>::iterator it =4902              registers_flags_types.find(gdb_type);4903          if (it != registers_flags_types.end()) {4904            auto flags_type = it->second.get();4905            if (reg_info.byte_size == flags_type->GetSize())4906              reg_info.flags_type = flags_type;4907            else4908              LLDB_LOGF(log,4909                        "ProcessGDBRemote::ParseRegisters Size of register "4910                        "flags %s (%d bytes) for "4911                        "register %s does not match the register size (%d "4912                        "bytes). Ignoring this set of flags.",4913                        flags_type->GetID().c_str(), flags_type->GetSize(),4914                        reg_info.name.AsCString(), reg_info.byte_size);4915          }4916 4917          // There's a slim chance that the gdb_type name is both a flags type4918          // and a simple type. Just in case, look for that too (setting both4919          // does no harm).4920          if (!gdb_type.empty() && !(encoding_set || format_set)) {4921            if (llvm::StringRef(gdb_type).starts_with("int")) {4922              reg_info.format = eFormatHex;4923              reg_info.encoding = eEncodingUint;4924            } else if (gdb_type == "data_ptr" || gdb_type == "code_ptr") {4925              reg_info.format = eFormatAddressInfo;4926              reg_info.encoding = eEncodingUint;4927            } else if (gdb_type == "float" || gdb_type == "ieee_single" ||4928                       gdb_type == "ieee_double") {4929              reg_info.format = eFormatFloat;4930              reg_info.encoding = eEncodingIEEE754;4931            } else if (gdb_type == "aarch64v" ||4932                       llvm::StringRef(gdb_type).starts_with("vec") ||4933                       gdb_type == "i387_ext" || gdb_type == "uint128" ||4934                       reg_info.byte_size > 16) {4935              // lldb doesn't handle 128-bit uints correctly (for ymm*h), so4936              // treat them as vector (similarly to xmm/ymm).4937              // We can fall back to handling anything else <= 128 bit as an4938              // unsigned integer, more than that, call it a vector of bytes.4939              // This can happen if we don't recognise the type for AArc64 SVE4940              // registers.4941              reg_info.format = eFormatVectorOfUInt8;4942              reg_info.encoding = eEncodingVector;4943            } else {4944              LLDB_LOGF(4945                  log,4946                  "ProcessGDBRemote::ParseRegisters Could not determine lldb"4947                  "format and encoding for gdb type %s",4948                  gdb_type.c_str());4949            }4950          }4951        }4952 4953        // Only update the register set name if we didn't get a "reg_set"4954        // attribute. "set_name" will be empty if we didn't have a "reg_set"4955        // attribute.4956        if (!reg_info.set_name) {4957          if (!gdb_group.empty()) {4958            reg_info.set_name.SetCString(gdb_group.c_str());4959          } else {4960            // If no register group name provided anywhere,4961            // we'll create a 'general' register set4962            reg_info.set_name.SetCString("general");4963          }4964        }4965 4966        if (reg_info.byte_size == 0) {4967          LLDB_LOGF(log,4968                    "ProcessGDBRemote::%s Skipping zero bitsize register %s",4969                    __FUNCTION__, reg_info.name.AsCString());4970        } else4971          registers.push_back(reg_info);4972 4973        return true; // Keep iterating through all "reg" elements4974      });4975  return true;4976}4977 4978} // namespace4979 4980// This method fetches a register description feature xml file from4981// the remote stub and adds registers/register groupsets/architecture4982// information to the current process.  It will call itself recursively4983// for nested register definition files.  It returns true if it was able4984// to fetch and parse an xml file.4985bool ProcessGDBRemote::GetGDBServerRegisterInfoXMLAndProcess(4986    ArchSpec &arch_to_use, std::string xml_filename,4987    std::vector<DynamicRegisterInfo::Register> &registers) {4988  // request the target xml file4989  llvm::Expected<std::string> raw = m_gdb_comm.ReadExtFeature("features", xml_filename);4990  if (errorToBool(raw.takeError()))4991    return false;4992 4993  XMLDocument xml_document;4994 4995  if (xml_document.ParseMemory(raw->c_str(), raw->size(),4996                               xml_filename.c_str())) {4997    GdbServerTargetInfo target_info;4998    std::vector<XMLNode> feature_nodes;4999 5000    // The top level feature XML file will start with a <target> tag.5001    XMLNode target_node = xml_document.GetRootElement("target");5002    if (target_node) {5003      target_node.ForEachChildElement([&target_info, &feature_nodes](5004                                          const XMLNode &node) -> bool {5005        llvm::StringRef name = node.GetName();5006        if (name == "architecture") {5007          node.GetElementText(target_info.arch);5008        } else if (name == "osabi") {5009          node.GetElementText(target_info.osabi);5010        } else if (name == "xi:include" || name == "include") {5011          std::string href = node.GetAttributeValue("href");5012          if (!href.empty())5013            target_info.includes.push_back(href);5014        } else if (name == "feature") {5015          feature_nodes.push_back(node);5016        } else if (name == "groups") {5017          node.ForEachChildElementWithName(5018              "group", [&target_info](const XMLNode &node) -> bool {5019                uint32_t set_id = UINT32_MAX;5020                RegisterSetInfo set_info;5021 5022                node.ForEachAttribute(5023                    [&set_id, &set_info](const llvm::StringRef &name,5024                                         const llvm::StringRef &value) -> bool {5025                      // FIXME: we're silently ignoring invalid data here5026                      if (name == "id")5027                        llvm::to_integer(value, set_id);5028                      if (name == "name")5029                        set_info.name = ConstString(value);5030                      return true; // Keep iterating through all attributes5031                    });5032 5033                if (set_id != UINT32_MAX)5034                  target_info.reg_set_map[set_id] = set_info;5035                return true; // Keep iterating through all "group" elements5036              });5037        }5038        return true; // Keep iterating through all children of the target_node5039      });5040    } else {5041      // In an included XML feature file, we're already "inside" the <target>5042      // tag of the initial XML file; this included file will likely only have5043      // a <feature> tag.  Need to check for any more included files in this5044      // <feature> element.5045      XMLNode feature_node = xml_document.GetRootElement("feature");5046      if (feature_node) {5047        feature_nodes.push_back(feature_node);5048        feature_node.ForEachChildElement([&target_info](5049                                        const XMLNode &node) -> bool {5050          llvm::StringRef name = node.GetName();5051          if (name == "xi:include" || name == "include") {5052            std::string href = node.GetAttributeValue("href");5053            if (!href.empty())5054              target_info.includes.push_back(href);5055            }5056            return true;5057          });5058      }5059    }5060 5061    // gdbserver does not implement the LLDB packets used to determine host5062    // or process architecture.  If that is the case, attempt to use5063    // the <architecture/> field from target.xml, e.g.:5064    //5065    //   <architecture>i386:x86-64</architecture> (seen from VMWare ESXi)5066    //   <architecture>arm</architecture> (seen from Segger JLink on unspecified5067    //   arm board)5068    if (!arch_to_use.IsValid() && !target_info.arch.empty()) {5069      // We don't have any information about vendor or OS.5070      arch_to_use.SetTriple(llvm::StringSwitch<std::string>(target_info.arch)5071                                .Case("i386:x86-64", "x86_64")5072                                .Case("riscv:rv64", "riscv64")5073                                .Case("riscv:rv32", "riscv32")5074                                .Default(target_info.arch) +5075                            "--");5076 5077      if (arch_to_use.IsValid())5078        GetTarget().MergeArchitecture(arch_to_use);5079    }5080 5081    if (arch_to_use.IsValid()) {5082      for (auto &feature_node : feature_nodes) {5083        ParseRegisters(feature_node, target_info, registers,5084                       m_registers_flags_types, m_registers_enum_types);5085      }5086 5087      for (const auto &include : target_info.includes) {5088        GetGDBServerRegisterInfoXMLAndProcess(arch_to_use, include,5089                                              registers);5090      }5091    }5092  } else {5093    return false;5094  }5095  return true;5096}5097 5098void ProcessGDBRemote::AddRemoteRegisters(5099    std::vector<DynamicRegisterInfo::Register> &registers,5100    const ArchSpec &arch_to_use) {5101  std::map<uint32_t, uint32_t> remote_to_local_map;5102  uint32_t remote_regnum = 0;5103  for (auto it : llvm::enumerate(registers)) {5104    DynamicRegisterInfo::Register &remote_reg_info = it.value();5105 5106    // Assign successive remote regnums if missing.5107    if (remote_reg_info.regnum_remote == LLDB_INVALID_REGNUM)5108      remote_reg_info.regnum_remote = remote_regnum;5109 5110    // Create a mapping from remote to local regnos.5111    remote_to_local_map[remote_reg_info.regnum_remote] = it.index();5112 5113    remote_regnum = remote_reg_info.regnum_remote + 1;5114  }5115 5116  for (DynamicRegisterInfo::Register &remote_reg_info : registers) {5117    auto proc_to_lldb = [&remote_to_local_map](uint32_t process_regnum) {5118      auto lldb_regit = remote_to_local_map.find(process_regnum);5119      return lldb_regit != remote_to_local_map.end() ? lldb_regit->second5120                                                     : LLDB_INVALID_REGNUM;5121    };5122 5123    llvm::transform(remote_reg_info.value_regs,5124                    remote_reg_info.value_regs.begin(), proc_to_lldb);5125    llvm::transform(remote_reg_info.invalidate_regs,5126                    remote_reg_info.invalidate_regs.begin(), proc_to_lldb);5127  }5128 5129  // Don't use Process::GetABI, this code gets called from DidAttach, and5130  // in that context we haven't set the Target's architecture yet, so the5131  // ABI is also potentially incorrect.5132  if (ABISP abi_sp = ABI::FindPlugin(shared_from_this(), arch_to_use))5133    abi_sp->AugmentRegisterInfo(registers);5134 5135  m_register_info_sp->SetRegisterInfo(std::move(registers), arch_to_use);5136}5137 5138// query the target of gdb-remote for extended target information returns5139// true on success (got register definitions), false on failure (did not).5140bool ProcessGDBRemote::GetGDBServerRegisterInfo(ArchSpec &arch_to_use) {5141  // Make sure LLDB has an XML parser it can use first5142  if (!XMLDocument::XMLEnabled())5143    return false;5144 5145  // check that we have extended feature read support5146  if (!m_gdb_comm.GetQXferFeaturesReadSupported())5147    return false;5148 5149  // These hold register type information for the whole of target.xml.5150  // target.xml may include further documents that5151  // GetGDBServerRegisterInfoXMLAndProcess will recurse to fetch and process.5152  // That's why we clear the cache here, and not in5153  // GetGDBServerRegisterInfoXMLAndProcess. To prevent it being cleared on every5154  // include read.5155  m_registers_flags_types.clear();5156  m_registers_enum_types.clear();5157  std::vector<DynamicRegisterInfo::Register> registers;5158  if (GetGDBServerRegisterInfoXMLAndProcess(arch_to_use, "target.xml",5159                                            registers) &&5160      // Target XML is not required to include register information.5161      !registers.empty())5162    AddRemoteRegisters(registers, arch_to_use);5163 5164  return m_register_info_sp->GetNumRegisters() > 0;5165}5166 5167llvm::Expected<LoadedModuleInfoList> ProcessGDBRemote::GetLoadedModuleList() {5168  // Make sure LLDB has an XML parser it can use first5169  if (!XMLDocument::XMLEnabled())5170    return llvm::createStringError(llvm::inconvertibleErrorCode(),5171                                   "XML parsing not available");5172 5173  Log *log = GetLog(LLDBLog::Process);5174  LLDB_LOGF(log, "ProcessGDBRemote::%s", __FUNCTION__);5175 5176  LoadedModuleInfoList list;5177  GDBRemoteCommunicationClient &comm = m_gdb_comm;5178  bool can_use_svr4 = GetGlobalPluginProperties().GetUseSVR4();5179 5180  // check that we have extended feature read support5181  if (can_use_svr4 && comm.GetQXferLibrariesSVR4ReadSupported()) {5182    // request the loaded library list5183    llvm::Expected<std::string> raw = comm.ReadExtFeature("libraries-svr4", "");5184    if (!raw)5185      return raw.takeError();5186 5187    // parse the xml file in memory5188    LLDB_LOGF(log, "parsing: %s", raw->c_str());5189    XMLDocument doc;5190 5191    if (!doc.ParseMemory(raw->c_str(), raw->size(), "noname.xml"))5192      return llvm::createStringError(llvm::inconvertibleErrorCode(),5193                                     "Error reading noname.xml");5194 5195    XMLNode root_element = doc.GetRootElement("library-list-svr4");5196    if (!root_element)5197      return llvm::createStringError(5198          llvm::inconvertibleErrorCode(),5199          "Error finding library-list-svr4 xml element");5200 5201    // main link map structure5202    std::string main_lm = root_element.GetAttributeValue("main-lm");5203    // FIXME: we're silently ignoring invalid data here5204    if (!main_lm.empty())5205      llvm::to_integer(main_lm, list.m_link_map);5206 5207    root_element.ForEachChildElementWithName(5208        "library", [log, &list](const XMLNode &library) -> bool {5209          LoadedModuleInfoList::LoadedModuleInfo module;5210 5211          // FIXME: we're silently ignoring invalid data here5212          library.ForEachAttribute(5213              [&module](const llvm::StringRef &name,5214                        const llvm::StringRef &value) -> bool {5215                uint64_t uint_value = LLDB_INVALID_ADDRESS;5216                if (name == "name")5217                  module.set_name(value.str());5218                else if (name == "lm") {5219                  // the address of the link_map struct.5220                  llvm::to_integer(value, uint_value);5221                  module.set_link_map(uint_value);5222                } else if (name == "l_addr") {5223                  // the displacement as read from the field 'l_addr' of the5224                  // link_map struct.5225                  llvm::to_integer(value, uint_value);5226                  module.set_base(uint_value);5227                  // base address is always a displacement, not an absolute5228                  // value.5229                  module.set_base_is_offset(true);5230                } else if (name == "l_ld") {5231                  // the memory address of the libraries PT_DYNAMIC section.5232                  llvm::to_integer(value, uint_value);5233                  module.set_dynamic(uint_value);5234                }5235 5236                return true; // Keep iterating over all properties of "library"5237              });5238 5239          if (log) {5240            std::string name;5241            lldb::addr_t lm = 0, base = 0, ld = 0;5242            bool base_is_offset;5243 5244            module.get_name(name);5245            module.get_link_map(lm);5246            module.get_base(base);5247            module.get_base_is_offset(base_is_offset);5248            module.get_dynamic(ld);5249 5250            LLDB_LOGF(log,5251                      "found (link_map:0x%08" PRIx64 ", base:0x%08" PRIx645252                      "[%s], ld:0x%08" PRIx64 ", name:'%s')",5253                      lm, base, (base_is_offset ? "offset" : "absolute"), ld,5254                      name.c_str());5255          }5256 5257          list.add(module);5258          return true; // Keep iterating over all "library" elements in the root5259                       // node5260        });5261 5262    if (log)5263      LLDB_LOGF(log, "found %" PRId32 " modules in total",5264                (int)list.m_list.size());5265    return list;5266  } else if (comm.GetQXferLibrariesReadSupported()) {5267    // request the loaded library list5268    llvm::Expected<std::string> raw = comm.ReadExtFeature("libraries", "");5269 5270    if (!raw)5271      return raw.takeError();5272 5273    LLDB_LOGF(log, "parsing: %s", raw->c_str());5274    XMLDocument doc;5275 5276    if (!doc.ParseMemory(raw->c_str(), raw->size(), "noname.xml"))5277      return llvm::createStringError(llvm::inconvertibleErrorCode(),5278                                     "Error reading noname.xml");5279 5280    XMLNode root_element = doc.GetRootElement("library-list");5281    if (!root_element)5282      return llvm::createStringError(llvm::inconvertibleErrorCode(),5283                                     "Error finding library-list xml element");5284 5285    // FIXME: we're silently ignoring invalid data here5286    root_element.ForEachChildElementWithName(5287        "library", [log, &list](const XMLNode &library) -> bool {5288          LoadedModuleInfoList::LoadedModuleInfo module;5289 5290          std::string name = library.GetAttributeValue("name");5291          module.set_name(name);5292 5293          // The base address of a given library will be the address of its5294          // first section. Most remotes send only one section for Windows5295          // targets for example.5296          const XMLNode &section =5297              library.FindFirstChildElementWithName("section");5298          std::string address = section.GetAttributeValue("address");5299          uint64_t address_value = LLDB_INVALID_ADDRESS;5300          llvm::to_integer(address, address_value);5301          module.set_base(address_value);5302          // These addresses are absolute values.5303          module.set_base_is_offset(false);5304 5305          if (log) {5306            std::string name;5307            lldb::addr_t base = 0;5308            bool base_is_offset;5309            module.get_name(name);5310            module.get_base(base);5311            module.get_base_is_offset(base_is_offset);5312 5313            LLDB_LOGF(log, "found (base:0x%08" PRIx64 "[%s], name:'%s')", base,5314                      (base_is_offset ? "offset" : "absolute"), name.c_str());5315          }5316 5317          list.add(module);5318          return true; // Keep iterating over all "library" elements in the root5319                       // node5320        });5321 5322    if (log)5323      LLDB_LOGF(log, "found %" PRId32 " modules in total",5324                (int)list.m_list.size());5325    return list;5326  } else {5327    return llvm::createStringError(llvm::inconvertibleErrorCode(),5328                                   "Remote libraries not supported");5329  }5330}5331 5332lldb::ModuleSP ProcessGDBRemote::LoadModuleAtAddress(const FileSpec &file,5333                                                     lldb::addr_t link_map,5334                                                     lldb::addr_t base_addr,5335                                                     bool value_is_offset) {5336  DynamicLoader *loader = GetDynamicLoader();5337  if (!loader)5338    return nullptr;5339 5340  return loader->LoadModuleAtAddress(file, link_map, base_addr,5341                                     value_is_offset);5342}5343 5344llvm::Error ProcessGDBRemote::LoadModules() {5345  using lldb_private::process_gdb_remote::ProcessGDBRemote;5346 5347  // request a list of loaded libraries from GDBServer5348  llvm::Expected<LoadedModuleInfoList> module_list = GetLoadedModuleList();5349  if (!module_list)5350    return module_list.takeError();5351 5352  // get a list of all the modules5353  ModuleList new_modules;5354 5355  for (LoadedModuleInfoList::LoadedModuleInfo &modInfo : module_list->m_list) {5356    std::string mod_name;5357    lldb::addr_t mod_base;5358    lldb::addr_t link_map;5359    bool mod_base_is_offset;5360 5361    bool valid = true;5362    valid &= modInfo.get_name(mod_name);5363    valid &= modInfo.get_base(mod_base);5364    valid &= modInfo.get_base_is_offset(mod_base_is_offset);5365    if (!valid)5366      continue;5367 5368    if (!modInfo.get_link_map(link_map))5369      link_map = LLDB_INVALID_ADDRESS;5370 5371    FileSpec file(mod_name);5372    FileSystem::Instance().Resolve(file);5373    lldb::ModuleSP module_sp =5374        LoadModuleAtAddress(file, link_map, mod_base, mod_base_is_offset);5375 5376    if (module_sp.get())5377      new_modules.Append(module_sp);5378  }5379 5380  if (new_modules.GetSize() > 0) {5381    ModuleList removed_modules;5382    Target &target = GetTarget();5383    ModuleList &loaded_modules = m_process->GetTarget().GetImages();5384 5385    for (size_t i = 0; i < loaded_modules.GetSize(); ++i) {5386      const lldb::ModuleSP loaded_module = loaded_modules.GetModuleAtIndex(i);5387 5388      bool found = false;5389      for (size_t j = 0; j < new_modules.GetSize(); ++j) {5390        if (new_modules.GetModuleAtIndex(j).get() == loaded_module.get())5391          found = true;5392      }5393 5394      // The main executable will never be included in libraries-svr4, don't5395      // remove it5396      if (!found &&5397          loaded_module.get() != target.GetExecutableModulePointer()) {5398        removed_modules.Append(loaded_module);5399      }5400    }5401 5402    loaded_modules.Remove(removed_modules);5403    m_process->GetTarget().ModulesDidUnload(removed_modules, false);5404 5405    new_modules.ForEach([&target](const lldb::ModuleSP module_sp) {5406      lldb_private::ObjectFile *obj = module_sp->GetObjectFile();5407      if (!obj)5408        return IterationAction::Continue;5409 5410      if (obj->GetType() != ObjectFile::Type::eTypeExecutable)5411        return IterationAction::Continue;5412 5413      lldb::ModuleSP module_copy_sp = module_sp;5414      target.SetExecutableModule(module_copy_sp, eLoadDependentsNo);5415      return IterationAction::Stop;5416    });5417 5418    loaded_modules.AppendIfNeeded(new_modules);5419    m_process->GetTarget().ModulesDidLoad(new_modules);5420  }5421 5422  return llvm::ErrorSuccess();5423}5424 5425Status ProcessGDBRemote::GetFileLoadAddress(const FileSpec &file,5426                                            bool &is_loaded,5427                                            lldb::addr_t &load_addr) {5428  is_loaded = false;5429  load_addr = LLDB_INVALID_ADDRESS;5430 5431  std::string file_path = file.GetPath(false);5432  if (file_path.empty())5433    return Status::FromErrorString("Empty file name specified");5434 5435  StreamString packet;5436  packet.PutCString("qFileLoadAddress:");5437  packet.PutStringAsRawHex8(file_path);5438 5439  StringExtractorGDBRemote response;5440  if (m_gdb_comm.SendPacketAndWaitForResponse(packet.GetString(), response) !=5441      GDBRemoteCommunication::PacketResult::Success)5442    return Status::FromErrorString("Sending qFileLoadAddress packet failed");5443 5444  if (response.IsErrorResponse()) {5445    if (response.GetError() == 1) {5446      // The file is not loaded into the inferior5447      is_loaded = false;5448      load_addr = LLDB_INVALID_ADDRESS;5449      return Status();5450    }5451 5452    return Status::FromErrorString(5453        "Fetching file load address from remote server returned an error");5454  }5455 5456  if (response.IsNormalResponse()) {5457    is_loaded = true;5458    load_addr = response.GetHexMaxU64(false, LLDB_INVALID_ADDRESS);5459    return Status();5460  }5461 5462  return Status::FromErrorString(5463      "Unknown error happened during sending the load address packet");5464}5465 5466void ProcessGDBRemote::ModulesDidLoad(ModuleList &module_list) {5467  // We must call the lldb_private::Process::ModulesDidLoad () first before we5468  // do anything5469  Process::ModulesDidLoad(module_list);5470 5471  // After loading shared libraries, we can ask our remote GDB server if it5472  // needs any symbols.5473  m_gdb_comm.ServeSymbolLookups(this);5474}5475 5476void ProcessGDBRemote::HandleAsyncStdout(llvm::StringRef out) {5477  AppendSTDOUT(out.data(), out.size());5478}5479 5480static const char *end_delimiter = "--end--;";5481static const int end_delimiter_len = 8;5482 5483void ProcessGDBRemote::HandleAsyncMisc(llvm::StringRef data) {5484  std::string input = data.str(); // '1' to move beyond 'A'5485  if (m_partial_profile_data.length() > 0) {5486    m_partial_profile_data.append(input);5487    input = m_partial_profile_data;5488    m_partial_profile_data.clear();5489  }5490 5491  size_t found, pos = 0, len = input.length();5492  while ((found = input.find(end_delimiter, pos)) != std::string::npos) {5493    StringExtractorGDBRemote profileDataExtractor(5494        input.substr(pos, found).c_str());5495    std::string profile_data =5496        HarmonizeThreadIdsForProfileData(profileDataExtractor);5497    BroadcastAsyncProfileData(profile_data);5498 5499    pos = found + end_delimiter_len;5500  }5501 5502  if (pos < len) {5503    // Last incomplete chunk.5504    m_partial_profile_data = input.substr(pos);5505  }5506}5507 5508std::string ProcessGDBRemote::HarmonizeThreadIdsForProfileData(5509    StringExtractorGDBRemote &profileDataExtractor) {5510  std::map<uint64_t, uint32_t> new_thread_id_to_used_usec_map;5511  std::string output;5512  llvm::raw_string_ostream output_stream(output);5513  llvm::StringRef name, value;5514 5515  // Going to assuming thread_used_usec comes first, else bail out.5516  while (profileDataExtractor.GetNameColonValue(name, value)) {5517    if (name.compare("thread_used_id") == 0) {5518      StringExtractor threadIDHexExtractor(value);5519      uint64_t thread_id = threadIDHexExtractor.GetHexMaxU64(false, 0);5520 5521      bool has_used_usec = false;5522      uint32_t curr_used_usec = 0;5523      llvm::StringRef usec_name, usec_value;5524      uint32_t input_file_pos = profileDataExtractor.GetFilePos();5525      if (profileDataExtractor.GetNameColonValue(usec_name, usec_value)) {5526        if (usec_name == "thread_used_usec") {5527          has_used_usec = true;5528          usec_value.getAsInteger(0, curr_used_usec);5529        } else {5530          // We didn't find what we want, it is probably an older version. Bail5531          // out.5532          profileDataExtractor.SetFilePos(input_file_pos);5533        }5534      }5535 5536      if (has_used_usec) {5537        uint32_t prev_used_usec = 0;5538        std::map<uint64_t, uint32_t>::iterator iterator =5539            m_thread_id_to_used_usec_map.find(thread_id);5540        if (iterator != m_thread_id_to_used_usec_map.end())5541          prev_used_usec = iterator->second;5542 5543        uint32_t real_used_usec = curr_used_usec - prev_used_usec;5544        // A good first time record is one that runs for at least 0.25 sec5545        bool good_first_time =5546            (prev_used_usec == 0) && (real_used_usec > 250000);5547        bool good_subsequent_time =5548            (prev_used_usec > 0) &&5549            ((real_used_usec > 0) || (HasAssignedIndexIDToThread(thread_id)));5550 5551        if (good_first_time || good_subsequent_time) {5552          // We try to avoid doing too many index id reservation, resulting in5553          // fast increase of index ids.5554 5555          output_stream << name << ":";5556          int32_t index_id = AssignIndexIDToThread(thread_id);5557          output_stream << index_id << ";";5558 5559          output_stream << usec_name << ":" << usec_value << ";";5560        } else {5561          // Skip past 'thread_used_name'.5562          llvm::StringRef local_name, local_value;5563          profileDataExtractor.GetNameColonValue(local_name, local_value);5564        }5565 5566        // Store current time as previous time so that they can be compared5567        // later.5568        new_thread_id_to_used_usec_map[thread_id] = curr_used_usec;5569      } else {5570        // Bail out and use old string.5571        output_stream << name << ":" << value << ";";5572      }5573    } else {5574      output_stream << name << ":" << value << ";";5575    }5576  }5577  output_stream << end_delimiter;5578  m_thread_id_to_used_usec_map = new_thread_id_to_used_usec_map;5579 5580  return output;5581}5582 5583void ProcessGDBRemote::HandleStopReply() {5584  if (GetStopID() != 0)5585    return;5586 5587  if (GetID() == LLDB_INVALID_PROCESS_ID) {5588    lldb::pid_t pid = m_gdb_comm.GetCurrentProcessID();5589    if (pid != LLDB_INVALID_PROCESS_ID)5590      SetID(pid);5591  }5592  BuildDynamicRegisterInfo(true);5593}5594 5595llvm::Expected<bool> ProcessGDBRemote::SaveCore(llvm::StringRef outfile) {5596  if (!m_gdb_comm.GetSaveCoreSupported())5597    return false;5598 5599  StreamString packet;5600  packet.PutCString("qSaveCore;path-hint:");5601  packet.PutStringAsRawHex8(outfile);5602 5603  StringExtractorGDBRemote response;5604  if (m_gdb_comm.SendPacketAndWaitForResponse(packet.GetString(), response) ==5605      GDBRemoteCommunication::PacketResult::Success) {5606    // TODO: grab error message from the packet?  StringExtractor seems to5607    // be missing a method for that5608    if (response.IsErrorResponse())5609      return llvm::createStringError(5610          llvm::inconvertibleErrorCode(),5611          llvm::formatv("qSaveCore returned an error"));5612 5613    std::string path;5614 5615    // process the response5616    for (auto x : llvm::split(response.GetStringRef(), ';')) {5617      if (x.consume_front("core-path:"))5618        StringExtractor(x).GetHexByteString(path);5619    }5620 5621    // verify that we've gotten what we need5622    if (path.empty())5623      return llvm::createStringError(llvm::inconvertibleErrorCode(),5624                                     "qSaveCore returned no core path");5625 5626    // now transfer the core file5627    FileSpec remote_core{llvm::StringRef(path)};5628    Platform &platform = *GetTarget().GetPlatform();5629    Status error = platform.GetFile(remote_core, FileSpec(outfile));5630 5631    if (platform.IsRemote()) {5632      // NB: we unlink the file on error too5633      platform.Unlink(remote_core);5634      if (error.Fail())5635        return error.ToError();5636    }5637 5638    return true;5639  }5640 5641  return llvm::createStringError(llvm::inconvertibleErrorCode(),5642                                 "Unable to send qSaveCore");5643}5644 5645static const char *const s_async_json_packet_prefix = "JSON-async:";5646 5647static StructuredData::ObjectSP5648ParseStructuredDataPacket(llvm::StringRef packet) {5649  Log *log = GetLog(GDBRLog::Process);5650 5651  if (!packet.consume_front(s_async_json_packet_prefix)) {5652    if (log) {5653      LLDB_LOGF(5654          log,5655          "GDBRemoteCommunicationClientBase::%s() received $J packet "5656          "but was not a StructuredData packet: packet starts with "5657          "%s",5658          __FUNCTION__,5659          packet.slice(0, strlen(s_async_json_packet_prefix)).str().c_str());5660    }5661    return StructuredData::ObjectSP();5662  }5663 5664  // This is an asynchronous JSON packet, destined for a StructuredDataPlugin.5665  StructuredData::ObjectSP json_sp = StructuredData::ParseJSON(packet);5666  if (log) {5667    if (json_sp) {5668      StreamString json_str;5669      json_sp->Dump(json_str, true);5670      json_str.Flush();5671      LLDB_LOGF(log,5672                "ProcessGDBRemote::%s() "5673                "received Async StructuredData packet: %s",5674                __FUNCTION__, json_str.GetData());5675    } else {5676      LLDB_LOGF(log,5677                "ProcessGDBRemote::%s"5678                "() received StructuredData packet:"5679                " parse failure",5680                __FUNCTION__);5681    }5682  }5683  return json_sp;5684}5685 5686void ProcessGDBRemote::HandleAsyncStructuredDataPacket(llvm::StringRef data) {5687  auto structured_data_sp = ParseStructuredDataPacket(data);5688  if (structured_data_sp)5689    RouteAsyncStructuredData(structured_data_sp);5690}5691 5692class CommandObjectProcessGDBRemoteSpeedTest : public CommandObjectParsed {5693public:5694  CommandObjectProcessGDBRemoteSpeedTest(CommandInterpreter &interpreter)5695      : CommandObjectParsed(interpreter, "process plugin packet speed-test",5696                            "Tests packet speeds of various sizes to determine "5697                            "the performance characteristics of the GDB remote "5698                            "connection. ",5699                            nullptr),5700        m_option_group(),5701        m_num_packets(LLDB_OPT_SET_1, false, "count", 'c', 0, eArgTypeCount,5702                      "The number of packets to send of each varying size "5703                      "(default is 1000).",5704                      1000),5705        m_max_send(LLDB_OPT_SET_1, false, "max-send", 's', 0, eArgTypeCount,5706                   "The maximum number of bytes to send in a packet. Sizes "5707                   "increase in powers of 2 while the size is less than or "5708                   "equal to this option value. (default 1024).",5709                   1024),5710        m_max_recv(LLDB_OPT_SET_1, false, "max-receive", 'r', 0, eArgTypeCount,5711                   "The maximum number of bytes to receive in a packet. Sizes "5712                   "increase in powers of 2 while the size is less than or "5713                   "equal to this option value. (default 1024).",5714                   1024),5715        m_json(LLDB_OPT_SET_1, false, "json", 'j',5716               "Print the output as JSON data for easy parsing.", false, true) {5717    m_option_group.Append(&m_num_packets, LLDB_OPT_SET_ALL, LLDB_OPT_SET_1);5718    m_option_group.Append(&m_max_send, LLDB_OPT_SET_ALL, LLDB_OPT_SET_1);5719    m_option_group.Append(&m_max_recv, LLDB_OPT_SET_ALL, LLDB_OPT_SET_1);5720    m_option_group.Append(&m_json, LLDB_OPT_SET_ALL, LLDB_OPT_SET_1);5721    m_option_group.Finalize();5722  }5723 5724  ~CommandObjectProcessGDBRemoteSpeedTest() override = default;5725 5726  Options *GetOptions() override { return &m_option_group; }5727 5728  void DoExecute(Args &command, CommandReturnObject &result) override {5729    const size_t argc = command.GetArgumentCount();5730    if (argc == 0) {5731      ProcessGDBRemote *process =5732          (ProcessGDBRemote *)m_interpreter.GetExecutionContext()5733              .GetProcessPtr();5734      if (process) {5735        StreamSP output_stream_sp = result.GetImmediateOutputStream();5736        if (!output_stream_sp)5737          output_stream_sp = m_interpreter.GetDebugger().GetAsyncOutputStream();5738        result.SetImmediateOutputStream(output_stream_sp);5739 5740        const uint32_t num_packets =5741            (uint32_t)m_num_packets.GetOptionValue().GetCurrentValue();5742        const uint64_t max_send = m_max_send.GetOptionValue().GetCurrentValue();5743        const uint64_t max_recv = m_max_recv.GetOptionValue().GetCurrentValue();5744        const bool json = m_json.GetOptionValue().GetCurrentValue();5745        const uint64_t k_recv_amount =5746            4 * 1024 * 1024; // Receive amount in bytes5747        process->GetGDBRemote().TestPacketSpeed(5748            num_packets, max_send, max_recv, k_recv_amount, json,5749            output_stream_sp ? *output_stream_sp : result.GetOutputStream());5750        result.SetStatus(eReturnStatusSuccessFinishResult);5751        return;5752      }5753    } else {5754      result.AppendErrorWithFormat("'%s' takes no arguments",5755                                   m_cmd_name.c_str());5756    }5757    result.SetStatus(eReturnStatusFailed);5758  }5759 5760protected:5761  OptionGroupOptions m_option_group;5762  OptionGroupUInt64 m_num_packets;5763  OptionGroupUInt64 m_max_send;5764  OptionGroupUInt64 m_max_recv;5765  OptionGroupBoolean m_json;5766};5767 5768class CommandObjectProcessGDBRemotePacketHistory : public CommandObjectParsed {5769private:5770public:5771  CommandObjectProcessGDBRemotePacketHistory(CommandInterpreter &interpreter)5772      : CommandObjectParsed(interpreter, "process plugin packet history",5773                            "Dumps the packet history buffer. ", nullptr) {}5774 5775  ~CommandObjectProcessGDBRemotePacketHistory() override = default;5776 5777  void DoExecute(Args &command, CommandReturnObject &result) override {5778    ProcessGDBRemote *process =5779        (ProcessGDBRemote *)m_interpreter.GetExecutionContext().GetProcessPtr();5780    if (process) {5781      process->DumpPluginHistory(result.GetOutputStream());5782      result.SetStatus(eReturnStatusSuccessFinishResult);5783      return;5784    }5785    result.SetStatus(eReturnStatusFailed);5786  }5787};5788 5789class CommandObjectProcessGDBRemotePacketXferSize : public CommandObjectParsed {5790private:5791public:5792  CommandObjectProcessGDBRemotePacketXferSize(CommandInterpreter &interpreter)5793      : CommandObjectParsed(5794            interpreter, "process plugin packet xfer-size",5795            "Maximum size that lldb will try to read/write one one chunk.",5796            nullptr) {5797    AddSimpleArgumentList(eArgTypeUnsignedInteger);5798  }5799 5800  ~CommandObjectProcessGDBRemotePacketXferSize() override = default;5801 5802  void DoExecute(Args &command, CommandReturnObject &result) override {5803    const size_t argc = command.GetArgumentCount();5804    if (argc == 0) {5805      result.AppendErrorWithFormat("'%s' takes an argument to specify the max "5806                                   "amount to be transferred when "5807                                   "reading/writing",5808                                   m_cmd_name.c_str());5809      return;5810    }5811 5812    ProcessGDBRemote *process =5813        (ProcessGDBRemote *)m_interpreter.GetExecutionContext().GetProcessPtr();5814    if (process) {5815      const char *packet_size = command.GetArgumentAtIndex(0);5816      errno = 0;5817      uint64_t user_specified_max = strtoul(packet_size, nullptr, 10);5818      if (errno == 0 && user_specified_max != 0) {5819        process->SetUserSpecifiedMaxMemoryTransferSize(user_specified_max);5820        result.SetStatus(eReturnStatusSuccessFinishResult);5821        return;5822      }5823    }5824    result.SetStatus(eReturnStatusFailed);5825  }5826};5827 5828class CommandObjectProcessGDBRemotePacketSend : public CommandObjectParsed {5829private:5830public:5831  CommandObjectProcessGDBRemotePacketSend(CommandInterpreter &interpreter)5832      : CommandObjectParsed(interpreter, "process plugin packet send",5833                            "Send a custom packet through the GDB remote "5834                            "protocol and print the answer. "5835                            "The packet header and footer will automatically "5836                            "be added to the packet prior to sending and "5837                            "stripped from the result.",5838                            nullptr) {5839    AddSimpleArgumentList(eArgTypeNone, eArgRepeatStar);5840  }5841 5842  ~CommandObjectProcessGDBRemotePacketSend() override = default;5843 5844  void DoExecute(Args &command, CommandReturnObject &result) override {5845    const size_t argc = command.GetArgumentCount();5846    if (argc == 0) {5847      result.AppendErrorWithFormat(5848          "'%s' takes a one or more packet content arguments",5849          m_cmd_name.c_str());5850      return;5851    }5852 5853    ProcessGDBRemote *process =5854        (ProcessGDBRemote *)m_interpreter.GetExecutionContext().GetProcessPtr();5855    if (process) {5856      for (size_t i = 0; i < argc; ++i) {5857        const char *packet_cstr = command.GetArgumentAtIndex(0);5858        StringExtractorGDBRemote response;5859        process->GetGDBRemote().SendPacketAndWaitForResponse(5860            packet_cstr, response, process->GetInterruptTimeout());5861        result.SetStatus(eReturnStatusSuccessFinishResult);5862        Stream &output_strm = result.GetOutputStream();5863        output_strm.Printf("  packet: %s\n", packet_cstr);5864        std::string response_str = std::string(response.GetStringRef());5865 5866        if (strstr(packet_cstr, "qGetProfileData") != nullptr) {5867          response_str = process->HarmonizeThreadIdsForProfileData(response);5868        }5869 5870        if (response_str.empty())5871          output_strm.PutCString("response: \nerror: UNIMPLEMENTED\n");5872        else5873          output_strm.Printf("response: %s\n", response.GetStringRef().data());5874      }5875    }5876  }5877};5878 5879class CommandObjectProcessGDBRemotePacketMonitor : public CommandObjectRaw {5880private:5881public:5882  CommandObjectProcessGDBRemotePacketMonitor(CommandInterpreter &interpreter)5883      : CommandObjectRaw(interpreter, "process plugin packet monitor",5884                         "Send a qRcmd packet through the GDB remote protocol "5885                         "and print the response. "5886                         "The argument passed to this command will be hex "5887                         "encoded into a valid 'qRcmd' packet, sent and the "5888                         "response will be printed.") {}5889 5890  ~CommandObjectProcessGDBRemotePacketMonitor() override = default;5891 5892  void DoExecute(llvm::StringRef command,5893                 CommandReturnObject &result) override {5894    if (command.empty()) {5895      result.AppendErrorWithFormat("'%s' takes a command string argument",5896                                   m_cmd_name.c_str());5897      return;5898    }5899 5900    ProcessGDBRemote *process =5901        (ProcessGDBRemote *)m_interpreter.GetExecutionContext().GetProcessPtr();5902    if (process) {5903      StreamString packet;5904      packet.PutCString("qRcmd,");5905      packet.PutBytesAsRawHex8(command.data(), command.size());5906 5907      StringExtractorGDBRemote response;5908      Stream &output_strm = result.GetOutputStream();5909      process->GetGDBRemote().SendPacketAndReceiveResponseWithOutputSupport(5910          packet.GetString(), response, process->GetInterruptTimeout(),5911          [&output_strm](llvm::StringRef output) { output_strm << output; });5912      result.SetStatus(eReturnStatusSuccessFinishResult);5913      output_strm.Printf("  packet: %s\n", packet.GetData());5914      const std::string &response_str = std::string(response.GetStringRef());5915 5916      if (response_str.empty())5917        output_strm.PutCString("response: \nerror: UNIMPLEMENTED\n");5918      else5919        output_strm.Printf("response: %s\n", response.GetStringRef().data());5920    }5921  }5922};5923 5924class CommandObjectProcessGDBRemotePacket : public CommandObjectMultiword {5925private:5926public:5927  CommandObjectProcessGDBRemotePacket(CommandInterpreter &interpreter)5928      : CommandObjectMultiword(interpreter, "process plugin packet",5929                               "Commands that deal with GDB remote packets.",5930                               nullptr) {5931    LoadSubCommand(5932        "history",5933        CommandObjectSP(5934            new CommandObjectProcessGDBRemotePacketHistory(interpreter)));5935    LoadSubCommand(5936        "send", CommandObjectSP(5937                    new CommandObjectProcessGDBRemotePacketSend(interpreter)));5938    LoadSubCommand(5939        "monitor",5940        CommandObjectSP(5941            new CommandObjectProcessGDBRemotePacketMonitor(interpreter)));5942    LoadSubCommand(5943        "xfer-size",5944        CommandObjectSP(5945            new CommandObjectProcessGDBRemotePacketXferSize(interpreter)));5946    LoadSubCommand("speed-test",5947                   CommandObjectSP(new CommandObjectProcessGDBRemoteSpeedTest(5948                       interpreter)));5949  }5950 5951  ~CommandObjectProcessGDBRemotePacket() override = default;5952};5953 5954class CommandObjectMultiwordProcessGDBRemote : public CommandObjectMultiword {5955public:5956  CommandObjectMultiwordProcessGDBRemote(CommandInterpreter &interpreter)5957      : CommandObjectMultiword(5958            interpreter, "process plugin",5959            "Commands for operating on a ProcessGDBRemote process.",5960            "process plugin <subcommand> [<subcommand-options>]") {5961    LoadSubCommand(5962        "packet",5963        CommandObjectSP(new CommandObjectProcessGDBRemotePacket(interpreter)));5964  }5965 5966  ~CommandObjectMultiwordProcessGDBRemote() override = default;5967};5968 5969CommandObject *ProcessGDBRemote::GetPluginCommandObject() {5970  if (!m_command_sp)5971    m_command_sp = std::make_shared<CommandObjectMultiwordProcessGDBRemote>(5972        GetTarget().GetDebugger().GetCommandInterpreter());5973  return m_command_sp.get();5974}5975 5976void ProcessGDBRemote::DidForkSwitchSoftwareBreakpoints(bool enable) {5977  GetBreakpointSiteList().ForEach([this, enable](BreakpointSite *bp_site) {5978    if (bp_site->IsEnabled() &&5979        (bp_site->GetType() == BreakpointSite::eSoftware ||5980         bp_site->GetType() == BreakpointSite::eExternal)) {5981      m_gdb_comm.SendGDBStoppointTypePacket(5982          eBreakpointSoftware, enable, bp_site->GetLoadAddress(),5983          GetSoftwareBreakpointTrapOpcode(bp_site), GetInterruptTimeout());5984    }5985  });5986}5987 5988void ProcessGDBRemote::DidForkSwitchHardwareTraps(bool enable) {5989  if (m_gdb_comm.SupportsGDBStoppointPacket(eBreakpointHardware)) {5990    GetBreakpointSiteList().ForEach([this, enable](BreakpointSite *bp_site) {5991      if (bp_site->IsEnabled() &&5992          bp_site->GetType() == BreakpointSite::eHardware) {5993        m_gdb_comm.SendGDBStoppointTypePacket(5994            eBreakpointHardware, enable, bp_site->GetLoadAddress(),5995            GetSoftwareBreakpointTrapOpcode(bp_site), GetInterruptTimeout());5996      }5997    });5998  }5999 6000  for (const auto &wp_res_sp : m_watchpoint_resource_list.Sites()) {6001    addr_t addr = wp_res_sp->GetLoadAddress();6002    size_t size = wp_res_sp->GetByteSize();6003    GDBStoppointType type = GetGDBStoppointType(wp_res_sp);6004    m_gdb_comm.SendGDBStoppointTypePacket(type, enable, addr, size,6005                                          GetInterruptTimeout());6006  }6007}6008 6009void ProcessGDBRemote::DidFork(lldb::pid_t child_pid, lldb::tid_t child_tid) {6010  Log *log = GetLog(GDBRLog::Process);6011 6012  lldb::pid_t parent_pid = m_gdb_comm.GetCurrentProcessID();6013  // Any valid TID will suffice, thread-relevant actions will set a proper TID6014  // anyway.6015  lldb::tid_t parent_tid = m_thread_ids.front();6016 6017  lldb::pid_t follow_pid, detach_pid;6018  lldb::tid_t follow_tid, detach_tid;6019 6020  switch (GetFollowForkMode()) {6021  case eFollowParent:6022    follow_pid = parent_pid;6023    follow_tid = parent_tid;6024    detach_pid = child_pid;6025    detach_tid = child_tid;6026    break;6027  case eFollowChild:6028    follow_pid = child_pid;6029    follow_tid = child_tid;6030    detach_pid = parent_pid;6031    detach_tid = parent_tid;6032    break;6033  }6034 6035  // Switch to the process that is going to be detached.6036  if (!m_gdb_comm.SetCurrentThread(detach_tid, detach_pid)) {6037    LLDB_LOG(log, "ProcessGDBRemote::DidFork() unable to set pid/tid");6038    return;6039  }6040 6041  // Disable all software breakpoints in the forked process.6042  if (m_gdb_comm.SupportsGDBStoppointPacket(eBreakpointSoftware))6043    DidForkSwitchSoftwareBreakpoints(false);6044 6045  // Remove hardware breakpoints / watchpoints from parent process if we're6046  // following child.6047  if (GetFollowForkMode() == eFollowChild)6048    DidForkSwitchHardwareTraps(false);6049 6050  // Switch to the process that is going to be followed6051  if (!m_gdb_comm.SetCurrentThread(follow_tid, follow_pid) ||6052      !m_gdb_comm.SetCurrentThreadForRun(follow_tid, follow_pid)) {6053    LLDB_LOG(log, "ProcessGDBRemote::DidFork() unable to reset pid/tid");6054    return;6055  }6056 6057  LLDB_LOG(log, "Detaching process {0}", detach_pid);6058  Status error = m_gdb_comm.Detach(false, detach_pid);6059  if (error.Fail()) {6060    LLDB_LOG(log, "ProcessGDBRemote::DidFork() detach packet send failed: {0}",6061             error.AsCString() ? error.AsCString() : "<unknown error>");6062    return;6063  }6064 6065  // Hardware breakpoints/watchpoints are not inherited implicitly,6066  // so we need to readd them if we're following child.6067  if (GetFollowForkMode() == eFollowChild) {6068    DidForkSwitchHardwareTraps(true);6069    // Update our PID6070    SetID(child_pid);6071  }6072}6073 6074void ProcessGDBRemote::DidVFork(lldb::pid_t child_pid, lldb::tid_t child_tid) {6075  Log *log = GetLog(GDBRLog::Process);6076 6077  LLDB_LOG(6078      log,6079      "ProcessGDBRemote::DidFork() called for child_pid: {0}, child_tid {1}",6080      child_pid, child_tid);6081  ++m_vfork_in_progress_count;6082 6083  // Disable all software breakpoints for the duration of vfork.6084  if (m_gdb_comm.SupportsGDBStoppointPacket(eBreakpointSoftware))6085    DidForkSwitchSoftwareBreakpoints(false);6086 6087  lldb::pid_t detach_pid;6088  lldb::tid_t detach_tid;6089 6090  switch (GetFollowForkMode()) {6091  case eFollowParent:6092    detach_pid = child_pid;6093    detach_tid = child_tid;6094    break;6095  case eFollowChild:6096    detach_pid = m_gdb_comm.GetCurrentProcessID();6097    // Any valid TID will suffice, thread-relevant actions will set a proper TID6098    // anyway.6099    detach_tid = m_thread_ids.front();6100 6101    // Switch to the parent process before detaching it.6102    if (!m_gdb_comm.SetCurrentThread(detach_tid, detach_pid)) {6103      LLDB_LOG(log, "ProcessGDBRemote::DidFork() unable to set pid/tid");6104      return;6105    }6106 6107    // Remove hardware breakpoints / watchpoints from the parent process.6108    DidForkSwitchHardwareTraps(false);6109 6110    // Switch to the child process.6111    if (!m_gdb_comm.SetCurrentThread(child_tid, child_pid) ||6112        !m_gdb_comm.SetCurrentThreadForRun(child_tid, child_pid)) {6113      LLDB_LOG(log, "ProcessGDBRemote::DidFork() unable to reset pid/tid");6114      return;6115    }6116    break;6117  }6118 6119  LLDB_LOG(log, "Detaching process {0}", detach_pid);6120  Status error = m_gdb_comm.Detach(false, detach_pid);6121  if (error.Fail()) {6122      LLDB_LOG(log,6123               "ProcessGDBRemote::DidFork() detach packet send failed: {0}",6124                error.AsCString() ? error.AsCString() : "<unknown error>");6125      return;6126  }6127 6128  if (GetFollowForkMode() == eFollowChild) {6129    // Update our PID6130    SetID(child_pid);6131  }6132}6133 6134void ProcessGDBRemote::DidVForkDone() {6135  assert(m_vfork_in_progress_count > 0);6136  --m_vfork_in_progress_count;6137 6138  // Reenable all software breakpoints that were enabled before vfork.6139  if (m_gdb_comm.SupportsGDBStoppointPacket(eBreakpointSoftware))6140    DidForkSwitchSoftwareBreakpoints(true);6141}6142 6143void ProcessGDBRemote::DidExec() {6144  // If we are following children, vfork is finished by exec (rather than6145  // vforkdone that is submitted for parent).6146  if (GetFollowForkMode() == eFollowChild) {6147    if (m_vfork_in_progress_count > 0)6148      --m_vfork_in_progress_count;6149  }6150  Process::DidExec();6151}6152