Path: blob/main/contrib/llvm-project/lldb/source/Plugins/Process/gdb-remote/GDBRemoteCommunicationServerCommon.cpp
39642 views
//===-- GDBRemoteCommunicationServerCommon.cpp ----------------------------===//1//2// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.3// See https://llvm.org/LICENSE.txt for license information.4// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception5//6//===----------------------------------------------------------------------===//78#include "GDBRemoteCommunicationServerCommon.h"910#include <cerrno>1112#ifdef __APPLE__13#include <TargetConditionals.h>14#endif1516#include <chrono>17#include <cstring>18#include <optional>1920#include "lldb/Core/ModuleSpec.h"21#include "lldb/Host/Config.h"22#include "lldb/Host/File.h"23#include "lldb/Host/FileAction.h"24#include "lldb/Host/FileSystem.h"25#include "lldb/Host/Host.h"26#include "lldb/Host/HostInfo.h"27#include "lldb/Host/SafeMachO.h"28#include "lldb/Interpreter/OptionArgParser.h"29#include "lldb/Symbol/ObjectFile.h"30#include "lldb/Target/Platform.h"31#include "lldb/Utility/Endian.h"32#include "lldb/Utility/GDBRemote.h"33#include "lldb/Utility/LLDBLog.h"34#include "lldb/Utility/Log.h"35#include "lldb/Utility/StreamString.h"36#include "lldb/Utility/StructuredData.h"37#include "llvm/ADT/StringSwitch.h"38#include "llvm/Support/JSON.h"39#include "llvm/TargetParser/Triple.h"4041#include "ProcessGDBRemoteLog.h"42#include "lldb/Utility/StringExtractorGDBRemote.h"4344#ifdef __ANDROID__45#include "lldb/Host/android/HostInfoAndroid.h"46#include "lldb/Host/common/ZipFileResolver.h"47#endif4849using namespace lldb;50using namespace lldb_private::process_gdb_remote;51using namespace lldb_private;5253#ifdef __ANDROID__54const static uint32_t g_default_packet_timeout_sec = 20; // seconds55#else56const static uint32_t g_default_packet_timeout_sec = 0; // not specified57#endif5859// GDBRemoteCommunicationServerCommon constructor60GDBRemoteCommunicationServerCommon::GDBRemoteCommunicationServerCommon()61: GDBRemoteCommunicationServer(), m_process_launch_info(),62m_process_launch_error(), m_proc_infos(), m_proc_infos_index(0) {63RegisterMemberFunctionHandler(StringExtractorGDBRemote::eServerPacketType_A,64&GDBRemoteCommunicationServerCommon::Handle_A);65RegisterMemberFunctionHandler(66StringExtractorGDBRemote::eServerPacketType_QEnvironment,67&GDBRemoteCommunicationServerCommon::Handle_QEnvironment);68RegisterMemberFunctionHandler(69StringExtractorGDBRemote::eServerPacketType_QEnvironmentHexEncoded,70&GDBRemoteCommunicationServerCommon::Handle_QEnvironmentHexEncoded);71RegisterMemberFunctionHandler(72StringExtractorGDBRemote::eServerPacketType_qfProcessInfo,73&GDBRemoteCommunicationServerCommon::Handle_qfProcessInfo);74RegisterMemberFunctionHandler(75StringExtractorGDBRemote::eServerPacketType_qGroupName,76&GDBRemoteCommunicationServerCommon::Handle_qGroupName);77RegisterMemberFunctionHandler(78StringExtractorGDBRemote::eServerPacketType_qHostInfo,79&GDBRemoteCommunicationServerCommon::Handle_qHostInfo);80RegisterMemberFunctionHandler(81StringExtractorGDBRemote::eServerPacketType_QLaunchArch,82&GDBRemoteCommunicationServerCommon::Handle_QLaunchArch);83RegisterMemberFunctionHandler(84StringExtractorGDBRemote::eServerPacketType_qLaunchSuccess,85&GDBRemoteCommunicationServerCommon::Handle_qLaunchSuccess);86RegisterMemberFunctionHandler(87StringExtractorGDBRemote::eServerPacketType_qEcho,88&GDBRemoteCommunicationServerCommon::Handle_qEcho);89RegisterMemberFunctionHandler(90StringExtractorGDBRemote::eServerPacketType_qModuleInfo,91&GDBRemoteCommunicationServerCommon::Handle_qModuleInfo);92RegisterMemberFunctionHandler(93StringExtractorGDBRemote::eServerPacketType_jModulesInfo,94&GDBRemoteCommunicationServerCommon::Handle_jModulesInfo);95RegisterMemberFunctionHandler(96StringExtractorGDBRemote::eServerPacketType_qPlatform_chmod,97&GDBRemoteCommunicationServerCommon::Handle_qPlatform_chmod);98RegisterMemberFunctionHandler(99StringExtractorGDBRemote::eServerPacketType_qPlatform_mkdir,100&GDBRemoteCommunicationServerCommon::Handle_qPlatform_mkdir);101RegisterMemberFunctionHandler(102StringExtractorGDBRemote::eServerPacketType_qPlatform_shell,103&GDBRemoteCommunicationServerCommon::Handle_qPlatform_shell);104RegisterMemberFunctionHandler(105StringExtractorGDBRemote::eServerPacketType_qProcessInfoPID,106&GDBRemoteCommunicationServerCommon::Handle_qProcessInfoPID);107RegisterMemberFunctionHandler(108StringExtractorGDBRemote::eServerPacketType_QSetDetachOnError,109&GDBRemoteCommunicationServerCommon::Handle_QSetDetachOnError);110RegisterMemberFunctionHandler(111StringExtractorGDBRemote::eServerPacketType_QSetSTDERR,112&GDBRemoteCommunicationServerCommon::Handle_QSetSTDERR);113RegisterMemberFunctionHandler(114StringExtractorGDBRemote::eServerPacketType_QSetSTDIN,115&GDBRemoteCommunicationServerCommon::Handle_QSetSTDIN);116RegisterMemberFunctionHandler(117StringExtractorGDBRemote::eServerPacketType_QSetSTDOUT,118&GDBRemoteCommunicationServerCommon::Handle_QSetSTDOUT);119RegisterMemberFunctionHandler(120StringExtractorGDBRemote::eServerPacketType_qSpeedTest,121&GDBRemoteCommunicationServerCommon::Handle_qSpeedTest);122RegisterMemberFunctionHandler(123StringExtractorGDBRemote::eServerPacketType_qsProcessInfo,124&GDBRemoteCommunicationServerCommon::Handle_qsProcessInfo);125RegisterMemberFunctionHandler(126StringExtractorGDBRemote::eServerPacketType_QStartNoAckMode,127&GDBRemoteCommunicationServerCommon::Handle_QStartNoAckMode);128RegisterMemberFunctionHandler(129StringExtractorGDBRemote::eServerPacketType_qSupported,130&GDBRemoteCommunicationServerCommon::Handle_qSupported);131RegisterMemberFunctionHandler(132StringExtractorGDBRemote::eServerPacketType_qUserName,133&GDBRemoteCommunicationServerCommon::Handle_qUserName);134RegisterMemberFunctionHandler(135StringExtractorGDBRemote::eServerPacketType_vFile_close,136&GDBRemoteCommunicationServerCommon::Handle_vFile_Close);137RegisterMemberFunctionHandler(138StringExtractorGDBRemote::eServerPacketType_vFile_exists,139&GDBRemoteCommunicationServerCommon::Handle_vFile_Exists);140RegisterMemberFunctionHandler(141StringExtractorGDBRemote::eServerPacketType_vFile_md5,142&GDBRemoteCommunicationServerCommon::Handle_vFile_MD5);143RegisterMemberFunctionHandler(144StringExtractorGDBRemote::eServerPacketType_vFile_mode,145&GDBRemoteCommunicationServerCommon::Handle_vFile_Mode);146RegisterMemberFunctionHandler(147StringExtractorGDBRemote::eServerPacketType_vFile_open,148&GDBRemoteCommunicationServerCommon::Handle_vFile_Open);149RegisterMemberFunctionHandler(150StringExtractorGDBRemote::eServerPacketType_vFile_pread,151&GDBRemoteCommunicationServerCommon::Handle_vFile_pRead);152RegisterMemberFunctionHandler(153StringExtractorGDBRemote::eServerPacketType_vFile_pwrite,154&GDBRemoteCommunicationServerCommon::Handle_vFile_pWrite);155RegisterMemberFunctionHandler(156StringExtractorGDBRemote::eServerPacketType_vFile_size,157&GDBRemoteCommunicationServerCommon::Handle_vFile_Size);158RegisterMemberFunctionHandler(159StringExtractorGDBRemote::eServerPacketType_vFile_fstat,160&GDBRemoteCommunicationServerCommon::Handle_vFile_FStat);161RegisterMemberFunctionHandler(162StringExtractorGDBRemote::eServerPacketType_vFile_stat,163&GDBRemoteCommunicationServerCommon::Handle_vFile_Stat);164RegisterMemberFunctionHandler(165StringExtractorGDBRemote::eServerPacketType_vFile_symlink,166&GDBRemoteCommunicationServerCommon::Handle_vFile_symlink);167RegisterMemberFunctionHandler(168StringExtractorGDBRemote::eServerPacketType_vFile_unlink,169&GDBRemoteCommunicationServerCommon::Handle_vFile_unlink);170}171172// Destructor173GDBRemoteCommunicationServerCommon::~GDBRemoteCommunicationServerCommon() =174default;175176GDBRemoteCommunication::PacketResult177GDBRemoteCommunicationServerCommon::Handle_qHostInfo(178StringExtractorGDBRemote &packet) {179StreamString response;180181// $cputype:16777223;cpusubtype:3;ostype:Darwin;vendor:apple;endian:little;ptrsize:8;#00182183ArchSpec host_arch(HostInfo::GetArchitecture());184const llvm::Triple &host_triple = host_arch.GetTriple();185response.PutCString("triple:");186response.PutStringAsRawHex8(host_triple.getTriple());187response.Printf(";ptrsize:%u;", host_arch.GetAddressByteSize());188189llvm::StringRef distribution_id = HostInfo::GetDistributionId();190if (!distribution_id.empty()) {191response.PutCString("distribution_id:");192response.PutStringAsRawHex8(distribution_id);193response.PutCString(";");194}195196#if defined(__APPLE__)197// For parity with debugserver, we'll include the vendor key.198response.PutCString("vendor:apple;");199200// Send out MachO info.201uint32_t cpu = host_arch.GetMachOCPUType();202uint32_t sub = host_arch.GetMachOCPUSubType();203if (cpu != LLDB_INVALID_CPUTYPE)204response.Printf("cputype:%u;", cpu);205if (sub != LLDB_INVALID_CPUTYPE)206response.Printf("cpusubtype:%u;", sub);207208if (cpu == llvm::MachO::CPU_TYPE_ARM || cpu == llvm::MachO::CPU_TYPE_ARM64) {209// Indicate the OS type.210#if defined(TARGET_OS_TV) && TARGET_OS_TV == 1211response.PutCString("ostype:tvos;");212#elif defined(TARGET_OS_WATCH) && TARGET_OS_WATCH == 1213response.PutCString("ostype:watchos;");214#elif defined(TARGET_OS_BRIDGE) && TARGET_OS_BRIDGE == 1215response.PutCString("ostype:bridgeos;");216#else217response.PutCString("ostype:ios;");218#endif219220// On arm, we use "synchronous" watchpoints which means the exception is221// delivered before the instruction executes.222response.PutCString("watchpoint_exceptions_received:before;");223} else {224response.PutCString("ostype:macosx;");225response.Printf("watchpoint_exceptions_received:after;");226}227228#else229if (host_arch.GetMachine() == llvm::Triple::aarch64 ||230host_arch.GetMachine() == llvm::Triple::aarch64_32 ||231host_arch.GetMachine() == llvm::Triple::aarch64_be ||232host_arch.GetMachine() == llvm::Triple::arm ||233host_arch.GetMachine() == llvm::Triple::armeb || host_arch.IsMIPS())234response.Printf("watchpoint_exceptions_received:before;");235else236response.Printf("watchpoint_exceptions_received:after;");237#endif238239switch (endian::InlHostByteOrder()) {240case eByteOrderBig:241response.PutCString("endian:big;");242break;243case eByteOrderLittle:244response.PutCString("endian:little;");245break;246case eByteOrderPDP:247response.PutCString("endian:pdp;");248break;249default:250response.PutCString("endian:unknown;");251break;252}253254llvm::VersionTuple version = HostInfo::GetOSVersion();255if (!version.empty()) {256response.Format("os_version:{0}", version.getAsString());257response.PutChar(';');258}259260#if defined(__APPLE__)261llvm::VersionTuple maccatalyst_version = HostInfo::GetMacCatalystVersion();262if (!maccatalyst_version.empty()) {263response.Format("maccatalyst_version:{0}",264maccatalyst_version.getAsString());265response.PutChar(';');266}267#endif268269if (std::optional<std::string> s = HostInfo::GetOSBuildString()) {270response.PutCString("os_build:");271response.PutStringAsRawHex8(*s);272response.PutChar(';');273}274if (std::optional<std::string> s = HostInfo::GetOSKernelDescription()) {275response.PutCString("os_kernel:");276response.PutStringAsRawHex8(*s);277response.PutChar(';');278}279280std::string s;281#if defined(__APPLE__)282283#if defined(__arm__) || defined(__arm64__) || defined(__aarch64__)284// For iOS devices, we are connected through a USB Mux so we never pretend to285// actually have a hostname as far as the remote lldb that is connecting to286// this lldb-platform is concerned287response.PutCString("hostname:");288response.PutStringAsRawHex8("127.0.0.1");289response.PutChar(';');290#else // #if defined(__arm__) || defined(__arm64__) || defined(__aarch64__)291if (HostInfo::GetHostname(s)) {292response.PutCString("hostname:");293response.PutStringAsRawHex8(s);294response.PutChar(';');295}296#endif // #if defined(__arm__) || defined(__arm64__) || defined(__aarch64__)297298#else // #if defined(__APPLE__)299if (HostInfo::GetHostname(s)) {300response.PutCString("hostname:");301response.PutStringAsRawHex8(s);302response.PutChar(';');303}304#endif // #if defined(__APPLE__)305// coverity[unsigned_compare]306if (g_default_packet_timeout_sec > 0)307response.Printf("default_packet_timeout:%u;", g_default_packet_timeout_sec);308309return SendPacketNoLock(response.GetString());310}311312GDBRemoteCommunication::PacketResult313GDBRemoteCommunicationServerCommon::Handle_qProcessInfoPID(314StringExtractorGDBRemote &packet) {315// Packet format: "qProcessInfoPID:%i" where %i is the pid316packet.SetFilePos(::strlen("qProcessInfoPID:"));317lldb::pid_t pid = packet.GetU32(LLDB_INVALID_PROCESS_ID);318if (pid != LLDB_INVALID_PROCESS_ID) {319ProcessInstanceInfo proc_info;320if (Host::GetProcessInfo(pid, proc_info)) {321StreamString response;322CreateProcessInfoResponse(proc_info, response);323return SendPacketNoLock(response.GetString());324}325}326return SendErrorResponse(1);327}328329GDBRemoteCommunication::PacketResult330GDBRemoteCommunicationServerCommon::Handle_qfProcessInfo(331StringExtractorGDBRemote &packet) {332m_proc_infos_index = 0;333m_proc_infos.clear();334335ProcessInstanceInfoMatch match_info;336packet.SetFilePos(::strlen("qfProcessInfo"));337if (packet.GetChar() == ':') {338llvm::StringRef key;339llvm::StringRef value;340while (packet.GetNameColonValue(key, value)) {341bool success = true;342if (key == "name") {343StringExtractor extractor(value);344std::string file;345extractor.GetHexByteString(file);346match_info.GetProcessInfo().GetExecutableFile().SetFile(347file, FileSpec::Style::native);348} else if (key == "name_match") {349NameMatch name_match = llvm::StringSwitch<NameMatch>(value)350.Case("equals", NameMatch::Equals)351.Case("starts_with", NameMatch::StartsWith)352.Case("ends_with", NameMatch::EndsWith)353.Case("contains", NameMatch::Contains)354.Case("regex", NameMatch::RegularExpression)355.Default(NameMatch::Ignore);356match_info.SetNameMatchType(name_match);357if (name_match == NameMatch::Ignore)358return SendErrorResponse(2);359} else if (key == "pid") {360lldb::pid_t pid = LLDB_INVALID_PROCESS_ID;361if (value.getAsInteger(0, pid))362return SendErrorResponse(2);363match_info.GetProcessInfo().SetProcessID(pid);364} else if (key == "parent_pid") {365lldb::pid_t pid = LLDB_INVALID_PROCESS_ID;366if (value.getAsInteger(0, pid))367return SendErrorResponse(2);368match_info.GetProcessInfo().SetParentProcessID(pid);369} else if (key == "uid") {370uint32_t uid = UINT32_MAX;371if (value.getAsInteger(0, uid))372return SendErrorResponse(2);373match_info.GetProcessInfo().SetUserID(uid);374} else if (key == "gid") {375uint32_t gid = UINT32_MAX;376if (value.getAsInteger(0, gid))377return SendErrorResponse(2);378match_info.GetProcessInfo().SetGroupID(gid);379} else if (key == "euid") {380uint32_t uid = UINT32_MAX;381if (value.getAsInteger(0, uid))382return SendErrorResponse(2);383match_info.GetProcessInfo().SetEffectiveUserID(uid);384} else if (key == "egid") {385uint32_t gid = UINT32_MAX;386if (value.getAsInteger(0, gid))387return SendErrorResponse(2);388match_info.GetProcessInfo().SetEffectiveGroupID(gid);389} else if (key == "all_users") {390match_info.SetMatchAllUsers(391OptionArgParser::ToBoolean(value, false, &success));392} else if (key == "triple") {393match_info.GetProcessInfo().GetArchitecture() =394HostInfo::GetAugmentedArchSpec(value);395} else {396success = false;397}398399if (!success)400return SendErrorResponse(2);401}402}403404if (Host::FindProcesses(match_info, m_proc_infos)) {405// We found something, return the first item by calling the get subsequent406// process info packet handler...407return Handle_qsProcessInfo(packet);408}409return SendErrorResponse(3);410}411412GDBRemoteCommunication::PacketResult413GDBRemoteCommunicationServerCommon::Handle_qsProcessInfo(414StringExtractorGDBRemote &packet) {415if (m_proc_infos_index < m_proc_infos.size()) {416StreamString response;417CreateProcessInfoResponse(m_proc_infos[m_proc_infos_index], response);418++m_proc_infos_index;419return SendPacketNoLock(response.GetString());420}421return SendErrorResponse(4);422}423424GDBRemoteCommunication::PacketResult425GDBRemoteCommunicationServerCommon::Handle_qUserName(426StringExtractorGDBRemote &packet) {427#if LLDB_ENABLE_POSIX428Log *log = GetLog(LLDBLog::Process);429LLDB_LOGF(log, "GDBRemoteCommunicationServerCommon::%s begin", __FUNCTION__);430431// Packet format: "qUserName:%i" where %i is the uid432packet.SetFilePos(::strlen("qUserName:"));433uint32_t uid = packet.GetU32(UINT32_MAX);434if (uid != UINT32_MAX) {435if (std::optional<llvm::StringRef> name =436HostInfo::GetUserIDResolver().GetUserName(uid)) {437StreamString response;438response.PutStringAsRawHex8(*name);439return SendPacketNoLock(response.GetString());440}441}442LLDB_LOGF(log, "GDBRemoteCommunicationServerCommon::%s end", __FUNCTION__);443#endif444return SendErrorResponse(5);445}446447GDBRemoteCommunication::PacketResult448GDBRemoteCommunicationServerCommon::Handle_qGroupName(449StringExtractorGDBRemote &packet) {450#if LLDB_ENABLE_POSIX451// Packet format: "qGroupName:%i" where %i is the gid452packet.SetFilePos(::strlen("qGroupName:"));453uint32_t gid = packet.GetU32(UINT32_MAX);454if (gid != UINT32_MAX) {455if (std::optional<llvm::StringRef> name =456HostInfo::GetUserIDResolver().GetGroupName(gid)) {457StreamString response;458response.PutStringAsRawHex8(*name);459return SendPacketNoLock(response.GetString());460}461}462#endif463return SendErrorResponse(6);464}465466GDBRemoteCommunication::PacketResult467GDBRemoteCommunicationServerCommon::Handle_qSpeedTest(468StringExtractorGDBRemote &packet) {469packet.SetFilePos(::strlen("qSpeedTest:"));470471llvm::StringRef key;472llvm::StringRef value;473bool success = packet.GetNameColonValue(key, value);474if (success && key == "response_size") {475uint32_t response_size = 0;476if (!value.getAsInteger(0, response_size)) {477if (response_size == 0)478return SendOKResponse();479StreamString response;480uint32_t bytes_left = response_size;481response.PutCString("data:");482while (bytes_left > 0) {483if (bytes_left >= 26) {484response.PutCString("ABCDEFGHIJKLMNOPQRSTUVWXYZ");485bytes_left -= 26;486} else {487response.Printf("%*.*s;", bytes_left, bytes_left,488"ABCDEFGHIJKLMNOPQRSTUVWXYZ");489bytes_left = 0;490}491}492return SendPacketNoLock(response.GetString());493}494}495return SendErrorResponse(7);496}497498GDBRemoteCommunication::PacketResult499GDBRemoteCommunicationServerCommon::Handle_vFile_Open(500StringExtractorGDBRemote &packet) {501packet.SetFilePos(::strlen("vFile:open:"));502std::string path;503packet.GetHexByteStringTerminatedBy(path, ',');504if (!path.empty()) {505if (packet.GetChar() == ',') {506auto flags = File::OpenOptions(packet.GetHexMaxU32(false, 0));507if (packet.GetChar() == ',') {508mode_t mode = packet.GetHexMaxU32(false, 0600);509FileSpec path_spec(path);510FileSystem::Instance().Resolve(path_spec);511// Do not close fd.512auto file = FileSystem::Instance().Open(path_spec, flags, mode, false);513514StreamString response;515response.PutChar('F');516517int descriptor = File::kInvalidDescriptor;518if (file) {519descriptor = file.get()->GetDescriptor();520response.Printf("%x", descriptor);521} else {522response.PutCString("-1");523std::error_code code = errorToErrorCode(file.takeError());524if (code.category() == std::system_category()) {525response.Printf(",%x", code.value());526}527}528529return SendPacketNoLock(response.GetString());530}531}532}533return SendErrorResponse(18);534}535536static GDBErrno system_errno_to_gdb(int err) {537switch (err) {538#define HANDLE_ERRNO(name, value) \539case name: \540return GDB_##name;541#include "Plugins/Process/gdb-remote/GDBRemoteErrno.def"542default:543return GDB_EUNKNOWN;544}545}546547GDBRemoteCommunication::PacketResult548GDBRemoteCommunicationServerCommon::Handle_vFile_Close(549StringExtractorGDBRemote &packet) {550packet.SetFilePos(::strlen("vFile:close:"));551int fd = packet.GetS32(-1, 16);552int err = -1;553int save_errno = 0;554if (fd >= 0) {555NativeFile file(fd, File::OpenOptions(0), true);556Status error = file.Close();557err = 0;558save_errno = error.GetError();559} else {560save_errno = EINVAL;561}562StreamString response;563response.PutChar('F');564response.Printf("%x", err);565if (save_errno)566response.Printf(",%x", system_errno_to_gdb(save_errno));567return SendPacketNoLock(response.GetString());568}569570GDBRemoteCommunication::PacketResult571GDBRemoteCommunicationServerCommon::Handle_vFile_pRead(572StringExtractorGDBRemote &packet) {573StreamGDBRemote response;574packet.SetFilePos(::strlen("vFile:pread:"));575int fd = packet.GetS32(-1, 16);576if (packet.GetChar() == ',') {577size_t count = packet.GetHexMaxU64(false, SIZE_MAX);578if (packet.GetChar() == ',') {579off_t offset = packet.GetHexMaxU32(false, UINT32_MAX);580if (count == SIZE_MAX) {581response.Printf("F-1:%x", EINVAL);582return SendPacketNoLock(response.GetString());583}584585std::string buffer(count, 0);586NativeFile file(fd, File::eOpenOptionReadOnly, false);587Status error = file.Read(static_cast<void *>(&buffer[0]), count, offset);588const int save_errno = error.GetError();589response.PutChar('F');590if (error.Success()) {591response.Printf("%zx", count);592response.PutChar(';');593response.PutEscapedBytes(&buffer[0], count);594} else {595response.PutCString("-1");596if (save_errno)597response.Printf(",%x", system_errno_to_gdb(save_errno));598}599return SendPacketNoLock(response.GetString());600}601}602return SendErrorResponse(21);603}604605GDBRemoteCommunication::PacketResult606GDBRemoteCommunicationServerCommon::Handle_vFile_pWrite(607StringExtractorGDBRemote &packet) {608packet.SetFilePos(::strlen("vFile:pwrite:"));609610StreamGDBRemote response;611response.PutChar('F');612613int fd = packet.GetS32(-1, 16);614if (packet.GetChar() == ',') {615off_t offset = packet.GetHexMaxU32(false, UINT32_MAX);616if (packet.GetChar() == ',') {617std::string buffer;618if (packet.GetEscapedBinaryData(buffer)) {619NativeFile file(fd, File::eOpenOptionWriteOnly, false);620size_t count = buffer.size();621Status error =622file.Write(static_cast<const void *>(&buffer[0]), count, offset);623const int save_errno = error.GetError();624if (error.Success())625response.Printf("%zx", count);626else {627response.PutCString("-1");628if (save_errno)629response.Printf(",%x", system_errno_to_gdb(save_errno));630}631} else {632response.Printf("-1,%x", EINVAL);633}634return SendPacketNoLock(response.GetString());635}636}637return SendErrorResponse(27);638}639640GDBRemoteCommunication::PacketResult641GDBRemoteCommunicationServerCommon::Handle_vFile_Size(642StringExtractorGDBRemote &packet) {643packet.SetFilePos(::strlen("vFile:size:"));644std::string path;645packet.GetHexByteString(path);646if (!path.empty()) {647uint64_t Size;648if (llvm::sys::fs::file_size(path, Size))649return SendErrorResponse(5);650StreamString response;651response.PutChar('F');652response.PutHex64(Size);653if (Size == UINT64_MAX) {654response.PutChar(',');655response.PutHex64(Size); // TODO: replace with Host::GetSyswideErrorCode()656}657return SendPacketNoLock(response.GetString());658}659return SendErrorResponse(22);660}661662GDBRemoteCommunication::PacketResult663GDBRemoteCommunicationServerCommon::Handle_vFile_Mode(664StringExtractorGDBRemote &packet) {665packet.SetFilePos(::strlen("vFile:mode:"));666std::string path;667packet.GetHexByteString(path);668if (!path.empty()) {669FileSpec file_spec(path);670FileSystem::Instance().Resolve(file_spec);671std::error_code ec;672const uint32_t mode = FileSystem::Instance().GetPermissions(file_spec, ec);673StreamString response;674if (mode != llvm::sys::fs::perms_not_known)675response.Printf("F%x", mode);676else677response.Printf("F-1,%x", (int)Status(ec).GetError());678return SendPacketNoLock(response.GetString());679}680return SendErrorResponse(23);681}682683GDBRemoteCommunication::PacketResult684GDBRemoteCommunicationServerCommon::Handle_vFile_Exists(685StringExtractorGDBRemote &packet) {686packet.SetFilePos(::strlen("vFile:exists:"));687std::string path;688packet.GetHexByteString(path);689if (!path.empty()) {690bool retcode = llvm::sys::fs::exists(path);691StreamString response;692response.PutChar('F');693response.PutChar(',');694if (retcode)695response.PutChar('1');696else697response.PutChar('0');698return SendPacketNoLock(response.GetString());699}700return SendErrorResponse(24);701}702703GDBRemoteCommunication::PacketResult704GDBRemoteCommunicationServerCommon::Handle_vFile_symlink(705StringExtractorGDBRemote &packet) {706packet.SetFilePos(::strlen("vFile:symlink:"));707std::string dst, src;708packet.GetHexByteStringTerminatedBy(dst, ',');709packet.GetChar(); // Skip ',' char710packet.GetHexByteString(src);711712FileSpec src_spec(src);713FileSystem::Instance().Resolve(src_spec);714Status error = FileSystem::Instance().Symlink(src_spec, FileSpec(dst));715716StreamString response;717response.Printf("F%x,%x", error.GetError(), error.GetError());718return SendPacketNoLock(response.GetString());719}720721GDBRemoteCommunication::PacketResult722GDBRemoteCommunicationServerCommon::Handle_vFile_unlink(723StringExtractorGDBRemote &packet) {724packet.SetFilePos(::strlen("vFile:unlink:"));725std::string path;726packet.GetHexByteString(path);727Status error(llvm::sys::fs::remove(path));728StreamString response;729response.Printf("F%x,%x", error.GetError(), error.GetError());730return SendPacketNoLock(response.GetString());731}732733GDBRemoteCommunication::PacketResult734GDBRemoteCommunicationServerCommon::Handle_qPlatform_shell(735StringExtractorGDBRemote &packet) {736packet.SetFilePos(::strlen("qPlatform_shell:"));737std::string path;738std::string working_dir;739packet.GetHexByteStringTerminatedBy(path, ',');740if (!path.empty()) {741if (packet.GetChar() == ',') {742// FIXME: add timeout to qPlatform_shell packet743// uint32_t timeout = packet.GetHexMaxU32(false, 32);744if (packet.GetChar() == ',')745packet.GetHexByteString(working_dir);746int status, signo;747std::string output;748FileSpec working_spec(working_dir);749FileSystem::Instance().Resolve(working_spec);750Status err =751Host::RunShellCommand(path.c_str(), working_spec, &status, &signo,752&output, std::chrono::seconds(10));753StreamGDBRemote response;754if (err.Fail()) {755response.PutCString("F,");756response.PutHex32(UINT32_MAX);757} else {758response.PutCString("F,");759response.PutHex32(status);760response.PutChar(',');761response.PutHex32(signo);762response.PutChar(',');763response.PutEscapedBytes(output.c_str(), output.size());764}765return SendPacketNoLock(response.GetString());766}767}768return SendErrorResponse(24);769}770771template <typename T, typename U>772static void fill_clamp(T &dest, U src, typename T::value_type fallback) {773static_assert(std::is_unsigned<typename T::value_type>::value,774"Destination type must be unsigned.");775using UU = std::make_unsigned_t<U>;776constexpr auto T_max = std::numeric_limits<typename T::value_type>::max();777dest = src >= 0 && static_cast<UU>(src) <= T_max ? src : fallback;778}779780GDBRemoteCommunication::PacketResult781GDBRemoteCommunicationServerCommon::Handle_vFile_FStat(782StringExtractorGDBRemote &packet) {783StreamGDBRemote response;784packet.SetFilePos(::strlen("vFile:fstat:"));785int fd = packet.GetS32(-1, 16);786787struct stat file_stats;788if (::fstat(fd, &file_stats) == -1) {789const int save_errno = errno;790response.Printf("F-1,%x", system_errno_to_gdb(save_errno));791return SendPacketNoLock(response.GetString());792}793794GDBRemoteFStatData data;795fill_clamp(data.gdb_st_dev, file_stats.st_dev, 0);796fill_clamp(data.gdb_st_ino, file_stats.st_ino, 0);797data.gdb_st_mode = file_stats.st_mode;798fill_clamp(data.gdb_st_nlink, file_stats.st_nlink, UINT32_MAX);799fill_clamp(data.gdb_st_uid, file_stats.st_uid, 0);800fill_clamp(data.gdb_st_gid, file_stats.st_gid, 0);801fill_clamp(data.gdb_st_rdev, file_stats.st_rdev, 0);802data.gdb_st_size = file_stats.st_size;803#if !defined(_WIN32)804data.gdb_st_blksize = file_stats.st_blksize;805data.gdb_st_blocks = file_stats.st_blocks;806#else807data.gdb_st_blksize = 0;808data.gdb_st_blocks = 0;809#endif810fill_clamp(data.gdb_st_atime, file_stats.st_atime, 0);811fill_clamp(data.gdb_st_mtime, file_stats.st_mtime, 0);812fill_clamp(data.gdb_st_ctime, file_stats.st_ctime, 0);813814response.Printf("F%zx;", sizeof(data));815response.PutEscapedBytes(&data, sizeof(data));816return SendPacketNoLock(response.GetString());817}818819GDBRemoteCommunication::PacketResult820GDBRemoteCommunicationServerCommon::Handle_vFile_Stat(821StringExtractorGDBRemote &packet) {822return SendUnimplementedResponse(823"GDBRemoteCommunicationServerCommon::Handle_vFile_Stat() unimplemented");824}825826GDBRemoteCommunication::PacketResult827GDBRemoteCommunicationServerCommon::Handle_vFile_MD5(828StringExtractorGDBRemote &packet) {829packet.SetFilePos(::strlen("vFile:MD5:"));830std::string path;831packet.GetHexByteString(path);832if (!path.empty()) {833StreamGDBRemote response;834auto Result = llvm::sys::fs::md5_contents(path);835if (!Result) {836response.PutCString("F,");837response.PutCString("x");838} else {839response.PutCString("F,");840response.PutHex64(Result->low());841response.PutHex64(Result->high());842}843return SendPacketNoLock(response.GetString());844}845return SendErrorResponse(25);846}847848GDBRemoteCommunication::PacketResult849GDBRemoteCommunicationServerCommon::Handle_qPlatform_mkdir(850StringExtractorGDBRemote &packet) {851packet.SetFilePos(::strlen("qPlatform_mkdir:"));852mode_t mode = packet.GetHexMaxU32(false, UINT32_MAX);853if (packet.GetChar() == ',') {854std::string path;855packet.GetHexByteString(path);856Status error(llvm::sys::fs::create_directory(path, mode));857858StreamGDBRemote response;859response.Printf("F%x", error.GetError());860861return SendPacketNoLock(response.GetString());862}863return SendErrorResponse(20);864}865866GDBRemoteCommunication::PacketResult867GDBRemoteCommunicationServerCommon::Handle_qPlatform_chmod(868StringExtractorGDBRemote &packet) {869packet.SetFilePos(::strlen("qPlatform_chmod:"));870871auto perms =872static_cast<llvm::sys::fs::perms>(packet.GetHexMaxU32(false, UINT32_MAX));873if (packet.GetChar() == ',') {874std::string path;875packet.GetHexByteString(path);876Status error(llvm::sys::fs::setPermissions(path, perms));877878StreamGDBRemote response;879response.Printf("F%x", error.GetError());880881return SendPacketNoLock(response.GetString());882}883return SendErrorResponse(19);884}885886GDBRemoteCommunication::PacketResult887GDBRemoteCommunicationServerCommon::Handle_qSupported(888StringExtractorGDBRemote &packet) {889// Parse client-indicated features.890llvm::SmallVector<llvm::StringRef, 4> client_features;891packet.GetStringRef().split(client_features, ';');892return SendPacketNoLock(llvm::join(HandleFeatures(client_features), ";"));893}894895GDBRemoteCommunication::PacketResult896GDBRemoteCommunicationServerCommon::Handle_QSetDetachOnError(897StringExtractorGDBRemote &packet) {898packet.SetFilePos(::strlen("QSetDetachOnError:"));899if (packet.GetU32(0))900m_process_launch_info.GetFlags().Set(eLaunchFlagDetachOnError);901else902m_process_launch_info.GetFlags().Clear(eLaunchFlagDetachOnError);903return SendOKResponse();904}905906GDBRemoteCommunication::PacketResult907GDBRemoteCommunicationServerCommon::Handle_QStartNoAckMode(908StringExtractorGDBRemote &packet) {909// Send response first before changing m_send_acks to we ack this packet910PacketResult packet_result = SendOKResponse();911m_send_acks = false;912return packet_result;913}914915GDBRemoteCommunication::PacketResult916GDBRemoteCommunicationServerCommon::Handle_QSetSTDIN(917StringExtractorGDBRemote &packet) {918packet.SetFilePos(::strlen("QSetSTDIN:"));919FileAction file_action;920std::string path;921packet.GetHexByteString(path);922const bool read = true;923const bool write = false;924if (file_action.Open(STDIN_FILENO, FileSpec(path), read, write)) {925m_process_launch_info.AppendFileAction(file_action);926return SendOKResponse();927}928return SendErrorResponse(15);929}930931GDBRemoteCommunication::PacketResult932GDBRemoteCommunicationServerCommon::Handle_QSetSTDOUT(933StringExtractorGDBRemote &packet) {934packet.SetFilePos(::strlen("QSetSTDOUT:"));935FileAction file_action;936std::string path;937packet.GetHexByteString(path);938const bool read = false;939const bool write = true;940if (file_action.Open(STDOUT_FILENO, FileSpec(path), read, write)) {941m_process_launch_info.AppendFileAction(file_action);942return SendOKResponse();943}944return SendErrorResponse(16);945}946947GDBRemoteCommunication::PacketResult948GDBRemoteCommunicationServerCommon::Handle_QSetSTDERR(949StringExtractorGDBRemote &packet) {950packet.SetFilePos(::strlen("QSetSTDERR:"));951FileAction file_action;952std::string path;953packet.GetHexByteString(path);954const bool read = false;955const bool write = true;956if (file_action.Open(STDERR_FILENO, FileSpec(path), read, write)) {957m_process_launch_info.AppendFileAction(file_action);958return SendOKResponse();959}960return SendErrorResponse(17);961}962963GDBRemoteCommunication::PacketResult964GDBRemoteCommunicationServerCommon::Handle_qLaunchSuccess(965StringExtractorGDBRemote &packet) {966if (m_process_launch_error.Success())967return SendOKResponse();968StreamString response;969response.PutChar('E');970response.PutCString(m_process_launch_error.AsCString("<unknown error>"));971return SendPacketNoLock(response.GetString());972}973974GDBRemoteCommunication::PacketResult975GDBRemoteCommunicationServerCommon::Handle_QEnvironment(976StringExtractorGDBRemote &packet) {977packet.SetFilePos(::strlen("QEnvironment:"));978const uint32_t bytes_left = packet.GetBytesLeft();979if (bytes_left > 0) {980m_process_launch_info.GetEnvironment().insert(packet.Peek());981return SendOKResponse();982}983return SendErrorResponse(12);984}985986GDBRemoteCommunication::PacketResult987GDBRemoteCommunicationServerCommon::Handle_QEnvironmentHexEncoded(988StringExtractorGDBRemote &packet) {989packet.SetFilePos(::strlen("QEnvironmentHexEncoded:"));990const uint32_t bytes_left = packet.GetBytesLeft();991if (bytes_left > 0) {992std::string str;993packet.GetHexByteString(str);994m_process_launch_info.GetEnvironment().insert(str);995return SendOKResponse();996}997return SendErrorResponse(12);998}9991000GDBRemoteCommunication::PacketResult1001GDBRemoteCommunicationServerCommon::Handle_QLaunchArch(1002StringExtractorGDBRemote &packet) {1003packet.SetFilePos(::strlen("QLaunchArch:"));1004const uint32_t bytes_left = packet.GetBytesLeft();1005if (bytes_left > 0) {1006const char *arch_triple = packet.Peek();1007m_process_launch_info.SetArchitecture(1008HostInfo::GetAugmentedArchSpec(arch_triple));1009return SendOKResponse();1010}1011return SendErrorResponse(13);1012}10131014GDBRemoteCommunication::PacketResult1015GDBRemoteCommunicationServerCommon::Handle_A(StringExtractorGDBRemote &packet) {1016// The 'A' packet is the most over designed packet ever here with redundant1017// argument indexes, redundant argument lengths and needed hex encoded1018// argument string values. Really all that is needed is a comma separated hex1019// encoded argument value list, but we will stay true to the documented1020// version of the 'A' packet here...10211022Log *log = GetLog(LLDBLog::Process);1023int actual_arg_index = 0;10241025packet.SetFilePos(1); // Skip the 'A'1026bool success = true;1027while (success && packet.GetBytesLeft() > 0) {1028// Decode the decimal argument string length. This length is the number of1029// hex nibbles in the argument string value.1030const uint32_t arg_len = packet.GetU32(UINT32_MAX);1031if (arg_len == UINT32_MAX)1032success = false;1033else {1034// Make sure the argument hex string length is followed by a comma1035if (packet.GetChar() != ',')1036success = false;1037else {1038// Decode the argument index. We ignore this really because who would1039// really send down the arguments in a random order???1040const uint32_t arg_idx = packet.GetU32(UINT32_MAX);1041if (arg_idx == UINT32_MAX)1042success = false;1043else {1044// Make sure the argument index is followed by a comma1045if (packet.GetChar() != ',')1046success = false;1047else {1048// Decode the argument string value from hex bytes back into a UTF81049// string and make sure the length matches the one supplied in the1050// packet1051std::string arg;1052if (packet.GetHexByteStringFixedLength(arg, arg_len) !=1053(arg_len / 2))1054success = false;1055else {1056// If there are any bytes left1057if (packet.GetBytesLeft()) {1058if (packet.GetChar() != ',')1059success = false;1060}10611062if (success) {1063if (arg_idx == 0)1064m_process_launch_info.GetExecutableFile().SetFile(1065arg, FileSpec::Style::native);1066m_process_launch_info.GetArguments().AppendArgument(arg);1067LLDB_LOGF(log, "LLGSPacketHandler::%s added arg %d: \"%s\"",1068__FUNCTION__, actual_arg_index, arg.c_str());1069++actual_arg_index;1070}1071}1072}1073}1074}1075}1076}10771078if (success) {1079m_process_launch_error = LaunchProcess();1080if (m_process_launch_error.Success())1081return SendOKResponse();1082LLDB_LOG(log, "failed to launch exe: {0}", m_process_launch_error);1083}1084return SendErrorResponse(8);1085}10861087GDBRemoteCommunication::PacketResult1088GDBRemoteCommunicationServerCommon::Handle_qEcho(1089StringExtractorGDBRemote &packet) {1090// Just echo back the exact same packet for qEcho...1091return SendPacketNoLock(packet.GetStringRef());1092}10931094GDBRemoteCommunication::PacketResult1095GDBRemoteCommunicationServerCommon::Handle_qModuleInfo(1096StringExtractorGDBRemote &packet) {1097packet.SetFilePos(::strlen("qModuleInfo:"));10981099std::string module_path;1100packet.GetHexByteStringTerminatedBy(module_path, ';');1101if (module_path.empty())1102return SendErrorResponse(1);11031104if (packet.GetChar() != ';')1105return SendErrorResponse(2);11061107std::string triple;1108packet.GetHexByteString(triple);11091110ModuleSpec matched_module_spec = GetModuleInfo(module_path, triple);1111if (!matched_module_spec.GetFileSpec())1112return SendErrorResponse(3);11131114const auto file_offset = matched_module_spec.GetObjectOffset();1115const auto file_size = matched_module_spec.GetObjectSize();1116const auto uuid_str = matched_module_spec.GetUUID().GetAsString("");11171118StreamGDBRemote response;11191120if (uuid_str.empty()) {1121auto Result = llvm::sys::fs::md5_contents(1122matched_module_spec.GetFileSpec().GetPath());1123if (!Result)1124return SendErrorResponse(5);1125response.PutCString("md5:");1126response.PutStringAsRawHex8(Result->digest());1127} else {1128response.PutCString("uuid:");1129response.PutStringAsRawHex8(uuid_str);1130}1131response.PutChar(';');11321133const auto &module_arch = matched_module_spec.GetArchitecture();1134response.PutCString("triple:");1135response.PutStringAsRawHex8(module_arch.GetTriple().getTriple());1136response.PutChar(';');11371138response.PutCString("file_path:");1139response.PutStringAsRawHex8(1140matched_module_spec.GetFileSpec().GetPath().c_str());1141response.PutChar(';');1142response.PutCString("file_offset:");1143response.PutHex64(file_offset);1144response.PutChar(';');1145response.PutCString("file_size:");1146response.PutHex64(file_size);1147response.PutChar(';');11481149return SendPacketNoLock(response.GetString());1150}11511152GDBRemoteCommunication::PacketResult1153GDBRemoteCommunicationServerCommon::Handle_jModulesInfo(1154StringExtractorGDBRemote &packet) {1155namespace json = llvm::json;11561157packet.SetFilePos(::strlen("jModulesInfo:"));11581159StructuredData::ObjectSP object_sp = StructuredData::ParseJSON(packet.Peek());1160if (!object_sp)1161return SendErrorResponse(1);11621163StructuredData::Array *packet_array = object_sp->GetAsArray();1164if (!packet_array)1165return SendErrorResponse(2);11661167json::Array response_array;1168for (size_t i = 0; i < packet_array->GetSize(); ++i) {1169StructuredData::Dictionary *query =1170packet_array->GetItemAtIndex(i)->GetAsDictionary();1171if (!query)1172continue;1173llvm::StringRef file, triple;1174if (!query->GetValueForKeyAsString("file", file) ||1175!query->GetValueForKeyAsString("triple", triple))1176continue;11771178ModuleSpec matched_module_spec = GetModuleInfo(file, triple);1179if (!matched_module_spec.GetFileSpec())1180continue;11811182const auto file_offset = matched_module_spec.GetObjectOffset();1183const auto file_size = matched_module_spec.GetObjectSize();1184const auto uuid_str = matched_module_spec.GetUUID().GetAsString("");1185if (uuid_str.empty())1186continue;1187const auto triple_str =1188matched_module_spec.GetArchitecture().GetTriple().getTriple();1189const auto file_path = matched_module_spec.GetFileSpec().GetPath();11901191json::Object response{{"uuid", uuid_str},1192{"triple", triple_str},1193{"file_path", file_path},1194{"file_offset", static_cast<int64_t>(file_offset)},1195{"file_size", static_cast<int64_t>(file_size)}};1196response_array.push_back(std::move(response));1197}11981199StreamString response;1200response.AsRawOstream() << std::move(response_array);1201StreamGDBRemote escaped_response;1202escaped_response.PutEscapedBytes(response.GetString().data(),1203response.GetSize());1204return SendPacketNoLock(escaped_response.GetString());1205}12061207void GDBRemoteCommunicationServerCommon::CreateProcessInfoResponse(1208const ProcessInstanceInfo &proc_info, StreamString &response) {1209response.Printf(1210"pid:%" PRIu64 ";ppid:%" PRIu64 ";uid:%i;gid:%i;euid:%i;egid:%i;",1211proc_info.GetProcessID(), proc_info.GetParentProcessID(),1212proc_info.GetUserID(), proc_info.GetGroupID(),1213proc_info.GetEffectiveUserID(), proc_info.GetEffectiveGroupID());1214response.PutCString("name:");1215response.PutStringAsRawHex8(proc_info.GetExecutableFile().GetPath().c_str());12161217response.PutChar(';');1218response.PutCString("args:");1219response.PutStringAsRawHex8(proc_info.GetArg0());1220for (auto &arg : proc_info.GetArguments()) {1221response.PutChar('-');1222response.PutStringAsRawHex8(arg.ref());1223}12241225response.PutChar(';');1226const ArchSpec &proc_arch = proc_info.GetArchitecture();1227if (proc_arch.IsValid()) {1228const llvm::Triple &proc_triple = proc_arch.GetTriple();1229response.PutCString("triple:");1230response.PutStringAsRawHex8(proc_triple.getTriple());1231response.PutChar(';');1232}1233}12341235void GDBRemoteCommunicationServerCommon::1236CreateProcessInfoResponse_DebugServerStyle(1237const ProcessInstanceInfo &proc_info, StreamString &response) {1238response.Printf("pid:%" PRIx64 ";parent-pid:%" PRIx641239";real-uid:%x;real-gid:%x;effective-uid:%x;effective-gid:%x;",1240proc_info.GetProcessID(), proc_info.GetParentProcessID(),1241proc_info.GetUserID(), proc_info.GetGroupID(),1242proc_info.GetEffectiveUserID(),1243proc_info.GetEffectiveGroupID());12441245const ArchSpec &proc_arch = proc_info.GetArchitecture();1246if (proc_arch.IsValid()) {1247const llvm::Triple &proc_triple = proc_arch.GetTriple();1248#if defined(__APPLE__)1249// We'll send cputype/cpusubtype.1250const uint32_t cpu_type = proc_arch.GetMachOCPUType();1251if (cpu_type != 0)1252response.Printf("cputype:%" PRIx32 ";", cpu_type);12531254const uint32_t cpu_subtype = proc_arch.GetMachOCPUSubType();1255if (cpu_subtype != 0)1256response.Printf("cpusubtype:%" PRIx32 ";", cpu_subtype);12571258const std::string vendor = proc_triple.getVendorName().str();1259if (!vendor.empty())1260response.Printf("vendor:%s;", vendor.c_str());1261#else1262// We'll send the triple.1263response.PutCString("triple:");1264response.PutStringAsRawHex8(proc_triple.getTriple());1265response.PutChar(';');1266#endif1267std::string ostype = std::string(proc_triple.getOSName());1268// Adjust so ostype reports ios for Apple/ARM and Apple/ARM64.1269if (proc_triple.getVendor() == llvm::Triple::Apple) {1270switch (proc_triple.getArch()) {1271case llvm::Triple::arm:1272case llvm::Triple::thumb:1273case llvm::Triple::aarch64:1274case llvm::Triple::aarch64_32:1275ostype = "ios";1276break;1277default:1278// No change.1279break;1280}1281}1282response.Printf("ostype:%s;", ostype.c_str());12831284switch (proc_arch.GetByteOrder()) {1285case lldb::eByteOrderLittle:1286response.PutCString("endian:little;");1287break;1288case lldb::eByteOrderBig:1289response.PutCString("endian:big;");1290break;1291case lldb::eByteOrderPDP:1292response.PutCString("endian:pdp;");1293break;1294default:1295// Nothing.1296break;1297}1298// In case of MIPS64, pointer size is depend on ELF ABI For N32 the pointer1299// size is 4 and for N64 it is 81300std::string abi = proc_arch.GetTargetABI();1301if (!abi.empty())1302response.Printf("elf_abi:%s;", abi.c_str());1303response.Printf("ptrsize:%d;", proc_arch.GetAddressByteSize());1304}1305}13061307FileSpec GDBRemoteCommunicationServerCommon::FindModuleFile(1308const std::string &module_path, const ArchSpec &arch) {1309#ifdef __ANDROID__1310return HostInfoAndroid::ResolveLibraryPath(module_path, arch);1311#else1312FileSpec file_spec(module_path);1313FileSystem::Instance().Resolve(file_spec);1314return file_spec;1315#endif1316}13171318ModuleSpec1319GDBRemoteCommunicationServerCommon::GetModuleInfo(llvm::StringRef module_path,1320llvm::StringRef triple) {1321ArchSpec arch(triple);13221323FileSpec req_module_path_spec(module_path);1324FileSystem::Instance().Resolve(req_module_path_spec);13251326const FileSpec module_path_spec =1327FindModuleFile(req_module_path_spec.GetPath(), arch);13281329lldb::offset_t file_offset = 0;1330lldb::offset_t file_size = 0;1331#ifdef __ANDROID__1332// In Android API level 23 and above, dynamic loader is able to load .so file1333// directly from zip file. In that case, module_path will be1334// "zip_path!/so_path". Resolve the zip file path, .so file offset and size.1335ZipFileResolver::FileKind file_kind = ZipFileResolver::eFileKindInvalid;1336std::string file_path;1337if (!ZipFileResolver::ResolveSharedLibraryPath(1338module_path_spec, file_kind, file_path, file_offset, file_size)) {1339return ModuleSpec();1340}1341lldbassert(file_kind != ZipFileResolver::eFileKindInvalid);1342// For zip .so file, this file_path will contain only the actual zip file1343// path for the object file processing. Otherwise it is the same as1344// module_path.1345const FileSpec actual_module_path_spec(file_path);1346#else1347// It is just module_path_spec reference for other platforms.1348const FileSpec &actual_module_path_spec = module_path_spec;1349#endif13501351const ModuleSpec module_spec(actual_module_path_spec, arch);13521353ModuleSpecList module_specs;1354if (!ObjectFile::GetModuleSpecifications(actual_module_path_spec, file_offset,1355file_size, module_specs))1356return ModuleSpec();13571358ModuleSpec matched_module_spec;1359if (!module_specs.FindMatchingModuleSpec(module_spec, matched_module_spec))1360return ModuleSpec();13611362#ifdef __ANDROID__1363if (file_kind == ZipFileResolver::eFileKindZip) {1364// For zip .so file, matched_module_spec contains only the actual zip file1365// path for the object file processing. Overwrite the matched_module_spec1366// file spec with the original module_path_spec to pass "zip_path!/so_path"1367// through to PlatformAndroid::DownloadModuleSlice.1368*matched_module_spec.GetFileSpecPtr() = module_path_spec;1369}1370#endif13711372return matched_module_spec;1373}13741375std::vector<std::string> GDBRemoteCommunicationServerCommon::HandleFeatures(1376const llvm::ArrayRef<llvm::StringRef> client_features) {1377// 128KBytes is a reasonable max packet size--debugger can always use less.1378constexpr uint32_t max_packet_size = 128 * 1024;13791380// Features common to platform server and llgs.1381return {1382llvm::formatv("PacketSize={0}", max_packet_size),1383"QStartNoAckMode+",1384"qEcho+",1385"native-signals+",1386};1387}138813891390