Path: blob/main/contrib/llvm-project/lldb/source/Plugins/Process/gdb-remote/GDBRemoteCommunicationServerLLGS.cpp
39642 views
//===-- GDBRemoteCommunicationServerLLGS.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 <cerrno>910#include "lldb/Host/Config.h"1112#include <chrono>13#include <cstring>14#include <limits>15#include <optional>16#include <thread>1718#include "GDBRemoteCommunicationServerLLGS.h"19#include "lldb/Host/ConnectionFileDescriptor.h"20#include "lldb/Host/Debug.h"21#include "lldb/Host/File.h"22#include "lldb/Host/FileAction.h"23#include "lldb/Host/FileSystem.h"24#include "lldb/Host/Host.h"25#include "lldb/Host/HostInfo.h"26#include "lldb/Host/PosixApi.h"27#include "lldb/Host/Socket.h"28#include "lldb/Host/common/NativeProcessProtocol.h"29#include "lldb/Host/common/NativeRegisterContext.h"30#include "lldb/Host/common/NativeThreadProtocol.h"31#include "lldb/Target/MemoryRegionInfo.h"32#include "lldb/Utility/Args.h"33#include "lldb/Utility/DataBuffer.h"34#include "lldb/Utility/Endian.h"35#include "lldb/Utility/GDBRemote.h"36#include "lldb/Utility/LLDBAssert.h"37#include "lldb/Utility/LLDBLog.h"38#include "lldb/Utility/Log.h"39#include "lldb/Utility/State.h"40#include "lldb/Utility/StreamString.h"41#include "lldb/Utility/UnimplementedError.h"42#include "lldb/Utility/UriParser.h"43#include "llvm/Support/JSON.h"44#include "llvm/Support/ScopedPrinter.h"45#include "llvm/TargetParser/Triple.h"4647#include "ProcessGDBRemote.h"48#include "ProcessGDBRemoteLog.h"49#include "lldb/Utility/StringExtractorGDBRemote.h"5051using namespace lldb;52using namespace lldb_private;53using namespace lldb_private::process_gdb_remote;54using namespace llvm;5556// GDBRemote Errors5758namespace {59enum GDBRemoteServerError {60// Set to the first unused error number in literal form below61eErrorFirst = 29,62eErrorNoProcess = eErrorFirst,63eErrorResume,64eErrorExitStatus65};66}6768// GDBRemoteCommunicationServerLLGS constructor69GDBRemoteCommunicationServerLLGS::GDBRemoteCommunicationServerLLGS(70MainLoop &mainloop, NativeProcessProtocol::Manager &process_manager)71: GDBRemoteCommunicationServerCommon(), m_mainloop(mainloop),72m_process_manager(process_manager), m_current_process(nullptr),73m_continue_process(nullptr), m_stdio_communication() {74RegisterPacketHandlers();75}7677void GDBRemoteCommunicationServerLLGS::RegisterPacketHandlers() {78RegisterMemberFunctionHandler(StringExtractorGDBRemote::eServerPacketType_C,79&GDBRemoteCommunicationServerLLGS::Handle_C);80RegisterMemberFunctionHandler(StringExtractorGDBRemote::eServerPacketType_c,81&GDBRemoteCommunicationServerLLGS::Handle_c);82RegisterMemberFunctionHandler(StringExtractorGDBRemote::eServerPacketType_D,83&GDBRemoteCommunicationServerLLGS::Handle_D);84RegisterMemberFunctionHandler(StringExtractorGDBRemote::eServerPacketType_H,85&GDBRemoteCommunicationServerLLGS::Handle_H);86RegisterMemberFunctionHandler(StringExtractorGDBRemote::eServerPacketType_I,87&GDBRemoteCommunicationServerLLGS::Handle_I);88RegisterMemberFunctionHandler(89StringExtractorGDBRemote::eServerPacketType_interrupt,90&GDBRemoteCommunicationServerLLGS::Handle_interrupt);91RegisterMemberFunctionHandler(92StringExtractorGDBRemote::eServerPacketType_m,93&GDBRemoteCommunicationServerLLGS::Handle_memory_read);94RegisterMemberFunctionHandler(StringExtractorGDBRemote::eServerPacketType_M,95&GDBRemoteCommunicationServerLLGS::Handle_M);96RegisterMemberFunctionHandler(StringExtractorGDBRemote::eServerPacketType__M,97&GDBRemoteCommunicationServerLLGS::Handle__M);98RegisterMemberFunctionHandler(StringExtractorGDBRemote::eServerPacketType__m,99&GDBRemoteCommunicationServerLLGS::Handle__m);100RegisterMemberFunctionHandler(StringExtractorGDBRemote::eServerPacketType_p,101&GDBRemoteCommunicationServerLLGS::Handle_p);102RegisterMemberFunctionHandler(StringExtractorGDBRemote::eServerPacketType_P,103&GDBRemoteCommunicationServerLLGS::Handle_P);104RegisterMemberFunctionHandler(StringExtractorGDBRemote::eServerPacketType_qC,105&GDBRemoteCommunicationServerLLGS::Handle_qC);106RegisterMemberFunctionHandler(StringExtractorGDBRemote::eServerPacketType_T,107&GDBRemoteCommunicationServerLLGS::Handle_T);108RegisterMemberFunctionHandler(109StringExtractorGDBRemote::eServerPacketType_qfThreadInfo,110&GDBRemoteCommunicationServerLLGS::Handle_qfThreadInfo);111RegisterMemberFunctionHandler(112StringExtractorGDBRemote::eServerPacketType_qFileLoadAddress,113&GDBRemoteCommunicationServerLLGS::Handle_qFileLoadAddress);114RegisterMemberFunctionHandler(115StringExtractorGDBRemote::eServerPacketType_qGetWorkingDir,116&GDBRemoteCommunicationServerLLGS::Handle_qGetWorkingDir);117RegisterMemberFunctionHandler(118StringExtractorGDBRemote::eServerPacketType_QThreadSuffixSupported,119&GDBRemoteCommunicationServerLLGS::Handle_QThreadSuffixSupported);120RegisterMemberFunctionHandler(121StringExtractorGDBRemote::eServerPacketType_QListThreadsInStopReply,122&GDBRemoteCommunicationServerLLGS::Handle_QListThreadsInStopReply);123RegisterMemberFunctionHandler(124StringExtractorGDBRemote::eServerPacketType_qMemoryRegionInfo,125&GDBRemoteCommunicationServerLLGS::Handle_qMemoryRegionInfo);126RegisterMemberFunctionHandler(127StringExtractorGDBRemote::eServerPacketType_qMemoryRegionInfoSupported,128&GDBRemoteCommunicationServerLLGS::Handle_qMemoryRegionInfoSupported);129RegisterMemberFunctionHandler(130StringExtractorGDBRemote::eServerPacketType_qProcessInfo,131&GDBRemoteCommunicationServerLLGS::Handle_qProcessInfo);132RegisterMemberFunctionHandler(133StringExtractorGDBRemote::eServerPacketType_qRegisterInfo,134&GDBRemoteCommunicationServerLLGS::Handle_qRegisterInfo);135RegisterMemberFunctionHandler(136StringExtractorGDBRemote::eServerPacketType_QRestoreRegisterState,137&GDBRemoteCommunicationServerLLGS::Handle_QRestoreRegisterState);138RegisterMemberFunctionHandler(139StringExtractorGDBRemote::eServerPacketType_QSaveRegisterState,140&GDBRemoteCommunicationServerLLGS::Handle_QSaveRegisterState);141RegisterMemberFunctionHandler(142StringExtractorGDBRemote::eServerPacketType_QSetDisableASLR,143&GDBRemoteCommunicationServerLLGS::Handle_QSetDisableASLR);144RegisterMemberFunctionHandler(145StringExtractorGDBRemote::eServerPacketType_QSetWorkingDir,146&GDBRemoteCommunicationServerLLGS::Handle_QSetWorkingDir);147RegisterMemberFunctionHandler(148StringExtractorGDBRemote::eServerPacketType_qsThreadInfo,149&GDBRemoteCommunicationServerLLGS::Handle_qsThreadInfo);150RegisterMemberFunctionHandler(151StringExtractorGDBRemote::eServerPacketType_qThreadStopInfo,152&GDBRemoteCommunicationServerLLGS::Handle_qThreadStopInfo);153RegisterMemberFunctionHandler(154StringExtractorGDBRemote::eServerPacketType_jThreadsInfo,155&GDBRemoteCommunicationServerLLGS::Handle_jThreadsInfo);156RegisterMemberFunctionHandler(157StringExtractorGDBRemote::eServerPacketType_qWatchpointSupportInfo,158&GDBRemoteCommunicationServerLLGS::Handle_qWatchpointSupportInfo);159RegisterMemberFunctionHandler(160StringExtractorGDBRemote::eServerPacketType_qXfer,161&GDBRemoteCommunicationServerLLGS::Handle_qXfer);162RegisterMemberFunctionHandler(StringExtractorGDBRemote::eServerPacketType_s,163&GDBRemoteCommunicationServerLLGS::Handle_s);164RegisterMemberFunctionHandler(165StringExtractorGDBRemote::eServerPacketType_stop_reason,166&GDBRemoteCommunicationServerLLGS::Handle_stop_reason); // ?167RegisterMemberFunctionHandler(168StringExtractorGDBRemote::eServerPacketType_vAttach,169&GDBRemoteCommunicationServerLLGS::Handle_vAttach);170RegisterMemberFunctionHandler(171StringExtractorGDBRemote::eServerPacketType_vAttachWait,172&GDBRemoteCommunicationServerLLGS::Handle_vAttachWait);173RegisterMemberFunctionHandler(174StringExtractorGDBRemote::eServerPacketType_qVAttachOrWaitSupported,175&GDBRemoteCommunicationServerLLGS::Handle_qVAttachOrWaitSupported);176RegisterMemberFunctionHandler(177StringExtractorGDBRemote::eServerPacketType_vAttachOrWait,178&GDBRemoteCommunicationServerLLGS::Handle_vAttachOrWait);179RegisterMemberFunctionHandler(180StringExtractorGDBRemote::eServerPacketType_vCont,181&GDBRemoteCommunicationServerLLGS::Handle_vCont);182RegisterMemberFunctionHandler(183StringExtractorGDBRemote::eServerPacketType_vCont_actions,184&GDBRemoteCommunicationServerLLGS::Handle_vCont_actions);185RegisterMemberFunctionHandler(186StringExtractorGDBRemote::eServerPacketType_vRun,187&GDBRemoteCommunicationServerLLGS::Handle_vRun);188RegisterMemberFunctionHandler(189StringExtractorGDBRemote::eServerPacketType_x,190&GDBRemoteCommunicationServerLLGS::Handle_memory_read);191RegisterMemberFunctionHandler(StringExtractorGDBRemote::eServerPacketType_Z,192&GDBRemoteCommunicationServerLLGS::Handle_Z);193RegisterMemberFunctionHandler(StringExtractorGDBRemote::eServerPacketType_z,194&GDBRemoteCommunicationServerLLGS::Handle_z);195RegisterMemberFunctionHandler(196StringExtractorGDBRemote::eServerPacketType_QPassSignals,197&GDBRemoteCommunicationServerLLGS::Handle_QPassSignals);198199RegisterMemberFunctionHandler(200StringExtractorGDBRemote::eServerPacketType_jLLDBTraceSupported,201&GDBRemoteCommunicationServerLLGS::Handle_jLLDBTraceSupported);202RegisterMemberFunctionHandler(203StringExtractorGDBRemote::eServerPacketType_jLLDBTraceStart,204&GDBRemoteCommunicationServerLLGS::Handle_jLLDBTraceStart);205RegisterMemberFunctionHandler(206StringExtractorGDBRemote::eServerPacketType_jLLDBTraceStop,207&GDBRemoteCommunicationServerLLGS::Handle_jLLDBTraceStop);208RegisterMemberFunctionHandler(209StringExtractorGDBRemote::eServerPacketType_jLLDBTraceGetState,210&GDBRemoteCommunicationServerLLGS::Handle_jLLDBTraceGetState);211RegisterMemberFunctionHandler(212StringExtractorGDBRemote::eServerPacketType_jLLDBTraceGetBinaryData,213&GDBRemoteCommunicationServerLLGS::Handle_jLLDBTraceGetBinaryData);214215RegisterMemberFunctionHandler(StringExtractorGDBRemote::eServerPacketType_g,216&GDBRemoteCommunicationServerLLGS::Handle_g);217218RegisterMemberFunctionHandler(219StringExtractorGDBRemote::eServerPacketType_qMemTags,220&GDBRemoteCommunicationServerLLGS::Handle_qMemTags);221222RegisterMemberFunctionHandler(223StringExtractorGDBRemote::eServerPacketType_QMemTags,224&GDBRemoteCommunicationServerLLGS::Handle_QMemTags);225226RegisterPacketHandler(StringExtractorGDBRemote::eServerPacketType_k,227[this](StringExtractorGDBRemote packet, Status &error,228bool &interrupt, bool &quit) {229quit = true;230return this->Handle_k(packet);231});232233RegisterMemberFunctionHandler(234StringExtractorGDBRemote::eServerPacketType_vKill,235&GDBRemoteCommunicationServerLLGS::Handle_vKill);236237RegisterMemberFunctionHandler(238StringExtractorGDBRemote::eServerPacketType_qLLDBSaveCore,239&GDBRemoteCommunicationServerLLGS::Handle_qSaveCore);240241RegisterMemberFunctionHandler(242StringExtractorGDBRemote::eServerPacketType_QNonStop,243&GDBRemoteCommunicationServerLLGS::Handle_QNonStop);244RegisterMemberFunctionHandler(245StringExtractorGDBRemote::eServerPacketType_vStdio,246&GDBRemoteCommunicationServerLLGS::Handle_vStdio);247RegisterMemberFunctionHandler(248StringExtractorGDBRemote::eServerPacketType_vStopped,249&GDBRemoteCommunicationServerLLGS::Handle_vStopped);250RegisterMemberFunctionHandler(251StringExtractorGDBRemote::eServerPacketType_vCtrlC,252&GDBRemoteCommunicationServerLLGS::Handle_vCtrlC);253}254255void GDBRemoteCommunicationServerLLGS::SetLaunchInfo(const ProcessLaunchInfo &info) {256m_process_launch_info = info;257}258259Status GDBRemoteCommunicationServerLLGS::LaunchProcess() {260Log *log = GetLog(LLDBLog::Process);261262if (!m_process_launch_info.GetArguments().GetArgumentCount())263return Status("%s: no process command line specified to launch",264__FUNCTION__);265266const bool should_forward_stdio =267m_process_launch_info.GetFileActionForFD(STDIN_FILENO) == nullptr ||268m_process_launch_info.GetFileActionForFD(STDOUT_FILENO) == nullptr ||269m_process_launch_info.GetFileActionForFD(STDERR_FILENO) == nullptr;270m_process_launch_info.SetLaunchInSeparateProcessGroup(true);271m_process_launch_info.GetFlags().Set(eLaunchFlagDebug);272273if (should_forward_stdio) {274// Temporarily relax the following for Windows until we can take advantage275// of the recently added pty support. This doesn't really affect the use of276// lldb-server on Windows.277#if !defined(_WIN32)278if (llvm::Error Err = m_process_launch_info.SetUpPtyRedirection())279return Status(std::move(Err));280#endif281}282283{284std::lock_guard<std::recursive_mutex> guard(m_debugged_process_mutex);285assert(m_debugged_processes.empty() && "lldb-server creating debugged "286"process but one already exists");287auto process_or = m_process_manager.Launch(m_process_launch_info, *this);288if (!process_or)289return Status(process_or.takeError());290m_continue_process = m_current_process = process_or->get();291m_debugged_processes.emplace(292m_current_process->GetID(),293DebuggedProcess{std::move(*process_or), DebuggedProcess::Flag{}});294}295296SetEnabledExtensions(*m_current_process);297298// Handle mirroring of inferior stdout/stderr over the gdb-remote protocol as299// needed. llgs local-process debugging may specify PTY paths, which will300// make these file actions non-null process launch -i/e/o will also make301// these file actions non-null nullptr means that the traffic is expected to302// flow over gdb-remote protocol303if (should_forward_stdio) {304// nullptr means it's not redirected to file or pty (in case of LLGS local)305// at least one of stdio will be transferred pty<->gdb-remote we need to306// give the pty primary handle to this object to read and/or write307LLDB_LOG(log,308"pid = {0}: setting up stdout/stderr redirection via $O "309"gdb-remote commands",310m_current_process->GetID());311312// Setup stdout/stderr mapping from inferior to $O313auto terminal_fd = m_current_process->GetTerminalFileDescriptor();314if (terminal_fd >= 0) {315LLDB_LOGF(log,316"ProcessGDBRemoteCommunicationServerLLGS::%s setting "317"inferior STDIO fd to %d",318__FUNCTION__, terminal_fd);319Status status = SetSTDIOFileDescriptor(terminal_fd);320if (status.Fail())321return status;322} else {323LLDB_LOGF(log,324"ProcessGDBRemoteCommunicationServerLLGS::%s ignoring "325"inferior STDIO since terminal fd reported as %d",326__FUNCTION__, terminal_fd);327}328} else {329LLDB_LOG(log,330"pid = {0} skipping stdout/stderr redirection via $O: inferior "331"will communicate over client-provided file descriptors",332m_current_process->GetID());333}334335printf("Launched '%s' as process %" PRIu64 "...\n",336m_process_launch_info.GetArguments().GetArgumentAtIndex(0),337m_current_process->GetID());338339return Status();340}341342Status GDBRemoteCommunicationServerLLGS::AttachToProcess(lldb::pid_t pid) {343Log *log = GetLog(LLDBLog::Process);344LLDB_LOGF(log, "GDBRemoteCommunicationServerLLGS::%s pid %" PRIu64,345__FUNCTION__, pid);346347// Before we try to attach, make sure we aren't already monitoring something348// else.349if (!m_debugged_processes.empty())350return Status("cannot attach to process %" PRIu64351" when another process with pid %" PRIu64352" is being debugged.",353pid, m_current_process->GetID());354355// Try to attach.356auto process_or = m_process_manager.Attach(pid, *this);357if (!process_or) {358Status status(process_or.takeError());359llvm::errs() << llvm::formatv("failed to attach to process {0}: {1}\n", pid,360status);361return status;362}363m_continue_process = m_current_process = process_or->get();364m_debugged_processes.emplace(365m_current_process->GetID(),366DebuggedProcess{std::move(*process_or), DebuggedProcess::Flag{}});367SetEnabledExtensions(*m_current_process);368369// Setup stdout/stderr mapping from inferior.370auto terminal_fd = m_current_process->GetTerminalFileDescriptor();371if (terminal_fd >= 0) {372LLDB_LOGF(log,373"ProcessGDBRemoteCommunicationServerLLGS::%s setting "374"inferior STDIO fd to %d",375__FUNCTION__, terminal_fd);376Status status = SetSTDIOFileDescriptor(terminal_fd);377if (status.Fail())378return status;379} else {380LLDB_LOGF(log,381"ProcessGDBRemoteCommunicationServerLLGS::%s ignoring "382"inferior STDIO since terminal fd reported as %d",383__FUNCTION__, terminal_fd);384}385386printf("Attached to process %" PRIu64 "...\n", pid);387return Status();388}389390Status GDBRemoteCommunicationServerLLGS::AttachWaitProcess(391llvm::StringRef process_name, bool include_existing) {392Log *log = GetLog(LLDBLog::Process);393394std::chrono::milliseconds polling_interval = std::chrono::milliseconds(1);395396// Create the matcher used to search the process list.397ProcessInstanceInfoList exclusion_list;398ProcessInstanceInfoMatch match_info;399match_info.GetProcessInfo().GetExecutableFile().SetFile(400process_name, llvm::sys::path::Style::native);401match_info.SetNameMatchType(NameMatch::Equals);402403if (include_existing) {404LLDB_LOG(log, "including existing processes in search");405} else {406// Create the excluded process list before polling begins.407Host::FindProcesses(match_info, exclusion_list);408LLDB_LOG(log, "placed '{0}' processes in the exclusion list.",409exclusion_list.size());410}411412LLDB_LOG(log, "waiting for '{0}' to appear", process_name);413414auto is_in_exclusion_list =415[&exclusion_list](const ProcessInstanceInfo &info) {416for (auto &excluded : exclusion_list) {417if (excluded.GetProcessID() == info.GetProcessID())418return true;419}420return false;421};422423ProcessInstanceInfoList loop_process_list;424while (true) {425loop_process_list.clear();426if (Host::FindProcesses(match_info, loop_process_list)) {427// Remove all the elements that are in the exclusion list.428llvm::erase_if(loop_process_list, is_in_exclusion_list);429430// One match! We found the desired process.431if (loop_process_list.size() == 1) {432auto matching_process_pid = loop_process_list[0].GetProcessID();433LLDB_LOG(log, "found pid {0}", matching_process_pid);434return AttachToProcess(matching_process_pid);435}436437// Multiple matches! Return an error reporting the PIDs we found.438if (loop_process_list.size() > 1) {439StreamString error_stream;440error_stream.Format(441"Multiple executables with name: '{0}' found. Pids: ",442process_name);443for (size_t i = 0; i < loop_process_list.size() - 1; ++i) {444error_stream.Format("{0}, ", loop_process_list[i].GetProcessID());445}446error_stream.Format("{0}.", loop_process_list.back().GetProcessID());447448Status error;449error.SetErrorString(error_stream.GetString());450return error;451}452}453// No matches, we have not found the process. Sleep until next poll.454LLDB_LOG(log, "sleep {0} seconds", polling_interval);455std::this_thread::sleep_for(polling_interval);456}457}458459void GDBRemoteCommunicationServerLLGS::InitializeDelegate(460NativeProcessProtocol *process) {461assert(process && "process cannot be NULL");462Log *log = GetLog(LLDBLog::Process);463if (log) {464LLDB_LOGF(log,465"GDBRemoteCommunicationServerLLGS::%s called with "466"NativeProcessProtocol pid %" PRIu64 ", current state: %s",467__FUNCTION__, process->GetID(),468StateAsCString(process->GetState()));469}470}471472GDBRemoteCommunication::PacketResult473GDBRemoteCommunicationServerLLGS::SendWResponse(474NativeProcessProtocol *process) {475assert(process && "process cannot be NULL");476Log *log = GetLog(LLDBLog::Process);477478// send W notification479auto wait_status = process->GetExitStatus();480if (!wait_status) {481LLDB_LOG(log, "pid = {0}, failed to retrieve process exit status",482process->GetID());483484StreamGDBRemote response;485response.PutChar('E');486response.PutHex8(GDBRemoteServerError::eErrorExitStatus);487return SendPacketNoLock(response.GetString());488}489490LLDB_LOG(log, "pid = {0}, returning exit type {1}", process->GetID(),491*wait_status);492493// If the process was killed through vKill, return "OK".494if (bool(m_debugged_processes.at(process->GetID()).flags &495DebuggedProcess::Flag::vkilled))496return SendOKResponse();497498StreamGDBRemote response;499response.Format("{0:g}", *wait_status);500if (bool(m_extensions_supported &501NativeProcessProtocol::Extension::multiprocess))502response.Format(";process:{0:x-}", process->GetID());503if (m_non_stop)504return SendNotificationPacketNoLock("Stop", m_stop_notification_queue,505response.GetString());506return SendPacketNoLock(response.GetString());507}508509static void AppendHexValue(StreamString &response, const uint8_t *buf,510uint32_t buf_size, bool swap) {511int64_t i;512if (swap) {513for (i = buf_size - 1; i >= 0; i--)514response.PutHex8(buf[i]);515} else {516for (i = 0; i < buf_size; i++)517response.PutHex8(buf[i]);518}519}520521static llvm::StringRef GetEncodingNameOrEmpty(const RegisterInfo ®_info) {522switch (reg_info.encoding) {523case eEncodingUint:524return "uint";525case eEncodingSint:526return "sint";527case eEncodingIEEE754:528return "ieee754";529case eEncodingVector:530return "vector";531default:532return "";533}534}535536static llvm::StringRef GetFormatNameOrEmpty(const RegisterInfo ®_info) {537switch (reg_info.format) {538case eFormatBinary:539return "binary";540case eFormatDecimal:541return "decimal";542case eFormatHex:543return "hex";544case eFormatFloat:545return "float";546case eFormatVectorOfSInt8:547return "vector-sint8";548case eFormatVectorOfUInt8:549return "vector-uint8";550case eFormatVectorOfSInt16:551return "vector-sint16";552case eFormatVectorOfUInt16:553return "vector-uint16";554case eFormatVectorOfSInt32:555return "vector-sint32";556case eFormatVectorOfUInt32:557return "vector-uint32";558case eFormatVectorOfFloat32:559return "vector-float32";560case eFormatVectorOfUInt64:561return "vector-uint64";562case eFormatVectorOfUInt128:563return "vector-uint128";564default:565return "";566};567}568569static llvm::StringRef GetKindGenericOrEmpty(const RegisterInfo ®_info) {570switch (reg_info.kinds[RegisterKind::eRegisterKindGeneric]) {571case LLDB_REGNUM_GENERIC_PC:572return "pc";573case LLDB_REGNUM_GENERIC_SP:574return "sp";575case LLDB_REGNUM_GENERIC_FP:576return "fp";577case LLDB_REGNUM_GENERIC_RA:578return "ra";579case LLDB_REGNUM_GENERIC_FLAGS:580return "flags";581case LLDB_REGNUM_GENERIC_ARG1:582return "arg1";583case LLDB_REGNUM_GENERIC_ARG2:584return "arg2";585case LLDB_REGNUM_GENERIC_ARG3:586return "arg3";587case LLDB_REGNUM_GENERIC_ARG4:588return "arg4";589case LLDB_REGNUM_GENERIC_ARG5:590return "arg5";591case LLDB_REGNUM_GENERIC_ARG6:592return "arg6";593case LLDB_REGNUM_GENERIC_ARG7:594return "arg7";595case LLDB_REGNUM_GENERIC_ARG8:596return "arg8";597case LLDB_REGNUM_GENERIC_TP:598return "tp";599default:600return "";601}602}603604static void CollectRegNums(const uint32_t *reg_num, StreamString &response,605bool usehex) {606for (int i = 0; *reg_num != LLDB_INVALID_REGNUM; ++reg_num, ++i) {607if (i > 0)608response.PutChar(',');609if (usehex)610response.Printf("%" PRIx32, *reg_num);611else612response.Printf("%" PRIu32, *reg_num);613}614}615616static void WriteRegisterValueInHexFixedWidth(617StreamString &response, NativeRegisterContext ®_ctx,618const RegisterInfo ®_info, const RegisterValue *reg_value_p,619lldb::ByteOrder byte_order) {620RegisterValue reg_value;621if (!reg_value_p) {622Status error = reg_ctx.ReadRegister(®_info, reg_value);623if (error.Success())624reg_value_p = ®_value;625// else log.626}627628if (reg_value_p) {629AppendHexValue(response, (const uint8_t *)reg_value_p->GetBytes(),630reg_value_p->GetByteSize(),631byte_order == lldb::eByteOrderLittle);632} else {633// Zero-out any unreadable values.634if (reg_info.byte_size > 0) {635std::vector<uint8_t> zeros(reg_info.byte_size, '\0');636AppendHexValue(response, zeros.data(), zeros.size(), false);637}638}639}640641static std::optional<json::Object>642GetRegistersAsJSON(NativeThreadProtocol &thread) {643Log *log = GetLog(LLDBLog::Thread);644645NativeRegisterContext& reg_ctx = thread.GetRegisterContext();646647json::Object register_object;648649#ifdef LLDB_JTHREADSINFO_FULL_REGISTER_SET650const auto expedited_regs =651reg_ctx.GetExpeditedRegisters(ExpeditedRegs::Full);652#else653const auto expedited_regs =654reg_ctx.GetExpeditedRegisters(ExpeditedRegs::Minimal);655#endif656if (expedited_regs.empty())657return std::nullopt;658659for (auto ®_num : expedited_regs) {660const RegisterInfo *const reg_info_p =661reg_ctx.GetRegisterInfoAtIndex(reg_num);662if (reg_info_p == nullptr) {663LLDB_LOGF(log,664"%s failed to get register info for register index %" PRIu32,665__FUNCTION__, reg_num);666continue;667}668669if (reg_info_p->value_regs != nullptr)670continue; // Only expedite registers that are not contained in other671// registers.672673RegisterValue reg_value;674Status error = reg_ctx.ReadRegister(reg_info_p, reg_value);675if (error.Fail()) {676LLDB_LOGF(log, "%s failed to read register '%s' index %" PRIu32 ": %s",677__FUNCTION__,678reg_info_p->name ? reg_info_p->name : "<unnamed-register>",679reg_num, error.AsCString());680continue;681}682683StreamString stream;684WriteRegisterValueInHexFixedWidth(stream, reg_ctx, *reg_info_p,685®_value, lldb::eByteOrderBig);686687register_object.try_emplace(llvm::to_string(reg_num),688stream.GetString().str());689}690691return register_object;692}693694static const char *GetStopReasonString(StopReason stop_reason) {695switch (stop_reason) {696case eStopReasonTrace:697return "trace";698case eStopReasonBreakpoint:699return "breakpoint";700case eStopReasonWatchpoint:701return "watchpoint";702case eStopReasonSignal:703return "signal";704case eStopReasonException:705return "exception";706case eStopReasonExec:707return "exec";708case eStopReasonProcessorTrace:709return "processor trace";710case eStopReasonFork:711return "fork";712case eStopReasonVFork:713return "vfork";714case eStopReasonVForkDone:715return "vforkdone";716case eStopReasonInstrumentation:717case eStopReasonInvalid:718case eStopReasonPlanComplete:719case eStopReasonThreadExiting:720case eStopReasonNone:721break; // ignored722}723return nullptr;724}725726static llvm::Expected<json::Array>727GetJSONThreadsInfo(NativeProcessProtocol &process, bool abridged) {728Log *log = GetLog(LLDBLog::Process | LLDBLog::Thread);729730json::Array threads_array;731732// Ensure we can get info on the given thread.733for (NativeThreadProtocol &thread : process.Threads()) {734lldb::tid_t tid = thread.GetID();735// Grab the reason this thread stopped.736struct ThreadStopInfo tid_stop_info;737std::string description;738if (!thread.GetStopReason(tid_stop_info, description))739return llvm::make_error<llvm::StringError>(740"failed to get stop reason", llvm::inconvertibleErrorCode());741742const int signum = tid_stop_info.signo;743if (log) {744LLDB_LOGF(log,745"GDBRemoteCommunicationServerLLGS::%s pid %" PRIu64746" tid %" PRIu64747" got signal signo = %d, reason = %d, exc_type = %" PRIu64,748__FUNCTION__, process.GetID(), tid, signum,749tid_stop_info.reason, tid_stop_info.details.exception.type);750}751752json::Object thread_obj;753754if (!abridged) {755if (std::optional<json::Object> registers = GetRegistersAsJSON(thread))756thread_obj.try_emplace("registers", std::move(*registers));757}758759thread_obj.try_emplace("tid", static_cast<int64_t>(tid));760761if (signum != 0)762thread_obj.try_emplace("signal", signum);763764const std::string thread_name = thread.GetName();765if (!thread_name.empty())766thread_obj.try_emplace("name", thread_name);767768const char *stop_reason = GetStopReasonString(tid_stop_info.reason);769if (stop_reason)770thread_obj.try_emplace("reason", stop_reason);771772if (!description.empty())773thread_obj.try_emplace("description", description);774775if ((tid_stop_info.reason == eStopReasonException) &&776tid_stop_info.details.exception.type) {777thread_obj.try_emplace(778"metype", static_cast<int64_t>(tid_stop_info.details.exception.type));779780json::Array medata_array;781for (uint32_t i = 0; i < tid_stop_info.details.exception.data_count;782++i) {783medata_array.push_back(784static_cast<int64_t>(tid_stop_info.details.exception.data[i]));785}786thread_obj.try_emplace("medata", std::move(medata_array));787}788threads_array.push_back(std::move(thread_obj));789}790return threads_array;791}792793StreamString794GDBRemoteCommunicationServerLLGS::PrepareStopReplyPacketForThread(795NativeThreadProtocol &thread) {796Log *log = GetLog(LLDBLog::Process | LLDBLog::Thread);797798NativeProcessProtocol &process = thread.GetProcess();799800LLDB_LOG(log, "preparing packet for pid {0} tid {1}", process.GetID(),801thread.GetID());802803// Grab the reason this thread stopped.804StreamString response;805struct ThreadStopInfo tid_stop_info;806std::string description;807if (!thread.GetStopReason(tid_stop_info, description))808return response;809810// FIXME implement register handling for exec'd inferiors.811// if (tid_stop_info.reason == eStopReasonExec) {812// const bool force = true;813// InitializeRegisters(force);814// }815816// Output the T packet with the thread817response.PutChar('T');818int signum = tid_stop_info.signo;819LLDB_LOG(820log,821"pid {0}, tid {1}, got signal signo = {2}, reason = {3}, exc_type = {4}",822process.GetID(), thread.GetID(), signum, int(tid_stop_info.reason),823tid_stop_info.details.exception.type);824825// Print the signal number.826response.PutHex8(signum & 0xff);827828// Include the (pid and) tid.829response.PutCString("thread:");830AppendThreadIDToResponse(response, process.GetID(), thread.GetID());831response.PutChar(';');832833// Include the thread name if there is one.834const std::string thread_name = thread.GetName();835if (!thread_name.empty()) {836size_t thread_name_len = thread_name.length();837838if (::strcspn(thread_name.c_str(), "$#+-;:") == thread_name_len) {839response.PutCString("name:");840response.PutCString(thread_name);841} else {842// The thread name contains special chars, send as hex bytes.843response.PutCString("hexname:");844response.PutStringAsRawHex8(thread_name);845}846response.PutChar(';');847}848849// If a 'QListThreadsInStopReply' was sent to enable this feature, we will850// send all thread IDs back in the "threads" key whose value is a list of hex851// thread IDs separated by commas:852// "threads:10a,10b,10c;"853// This will save the debugger from having to send a pair of qfThreadInfo and854// qsThreadInfo packets, but it also might take a lot of room in the stop855// reply packet, so it must be enabled only on systems where there are no856// limits on packet lengths.857if (m_list_threads_in_stop_reply) {858response.PutCString("threads:");859860uint32_t thread_num = 0;861for (NativeThreadProtocol &listed_thread : process.Threads()) {862if (thread_num > 0)863response.PutChar(',');864response.Printf("%" PRIx64, listed_thread.GetID());865++thread_num;866}867response.PutChar(';');868869// Include JSON info that describes the stop reason for any threads that870// actually have stop reasons. We use the new "jstopinfo" key whose values871// is hex ascii JSON that contains the thread IDs thread stop info only for872// threads that have stop reasons. Only send this if we have more than one873// thread otherwise this packet has all the info it needs.874if (thread_num > 1) {875const bool threads_with_valid_stop_info_only = true;876llvm::Expected<json::Array> threads_info = GetJSONThreadsInfo(877*m_current_process, threads_with_valid_stop_info_only);878if (threads_info) {879response.PutCString("jstopinfo:");880StreamString unescaped_response;881unescaped_response.AsRawOstream() << std::move(*threads_info);882response.PutStringAsRawHex8(unescaped_response.GetData());883response.PutChar(';');884} else {885LLDB_LOG_ERROR(log, threads_info.takeError(),886"failed to prepare a jstopinfo field for pid {1}: {0}",887process.GetID());888}889}890891response.PutCString("thread-pcs");892char delimiter = ':';893for (NativeThreadProtocol &thread : process.Threads()) {894NativeRegisterContext ®_ctx = thread.GetRegisterContext();895896uint32_t reg_to_read = reg_ctx.ConvertRegisterKindToRegisterNumber(897eRegisterKindGeneric, LLDB_REGNUM_GENERIC_PC);898const RegisterInfo *const reg_info_p =899reg_ctx.GetRegisterInfoAtIndex(reg_to_read);900901RegisterValue reg_value;902Status error = reg_ctx.ReadRegister(reg_info_p, reg_value);903if (error.Fail()) {904LLDB_LOGF(log, "%s failed to read register '%s' index %" PRIu32 ": %s",905__FUNCTION__,906reg_info_p->name ? reg_info_p->name : "<unnamed-register>",907reg_to_read, error.AsCString());908continue;909}910911response.PutChar(delimiter);912delimiter = ',';913WriteRegisterValueInHexFixedWidth(response, reg_ctx, *reg_info_p,914®_value, endian::InlHostByteOrder());915}916917response.PutChar(';');918}919920//921// Expedite registers.922//923924// Grab the register context.925NativeRegisterContext ®_ctx = thread.GetRegisterContext();926const auto expedited_regs =927reg_ctx.GetExpeditedRegisters(ExpeditedRegs::Full);928929for (auto ®_num : expedited_regs) {930const RegisterInfo *const reg_info_p =931reg_ctx.GetRegisterInfoAtIndex(reg_num);932// Only expediate registers that are not contained in other registers.933if (reg_info_p != nullptr && reg_info_p->value_regs == nullptr) {934RegisterValue reg_value;935Status error = reg_ctx.ReadRegister(reg_info_p, reg_value);936if (error.Success()) {937response.Printf("%.02x:", reg_num);938WriteRegisterValueInHexFixedWidth(response, reg_ctx, *reg_info_p,939®_value, lldb::eByteOrderBig);940response.PutChar(';');941} else {942LLDB_LOGF(log,943"GDBRemoteCommunicationServerLLGS::%s failed to read "944"register '%s' index %" PRIu32 ": %s",945__FUNCTION__,946reg_info_p->name ? reg_info_p->name : "<unnamed-register>",947reg_num, error.AsCString());948}949}950}951952const char *reason_str = GetStopReasonString(tid_stop_info.reason);953if (reason_str != nullptr) {954response.Printf("reason:%s;", reason_str);955}956957if (!description.empty()) {958// Description may contains special chars, send as hex bytes.959response.PutCString("description:");960response.PutStringAsRawHex8(description);961response.PutChar(';');962} else if ((tid_stop_info.reason == eStopReasonException) &&963tid_stop_info.details.exception.type) {964response.PutCString("metype:");965response.PutHex64(tid_stop_info.details.exception.type);966response.PutCString(";mecount:");967response.PutHex32(tid_stop_info.details.exception.data_count);968response.PutChar(';');969970for (uint32_t i = 0; i < tid_stop_info.details.exception.data_count; ++i) {971response.PutCString("medata:");972response.PutHex64(tid_stop_info.details.exception.data[i]);973response.PutChar(';');974}975}976977// Include child process PID/TID for forks.978if (tid_stop_info.reason == eStopReasonFork ||979tid_stop_info.reason == eStopReasonVFork) {980assert(bool(m_extensions_supported &981NativeProcessProtocol::Extension::multiprocess));982if (tid_stop_info.reason == eStopReasonFork)983assert(bool(m_extensions_supported &984NativeProcessProtocol::Extension::fork));985if (tid_stop_info.reason == eStopReasonVFork)986assert(bool(m_extensions_supported &987NativeProcessProtocol::Extension::vfork));988response.Printf("%s:p%" PRIx64 ".%" PRIx64 ";", reason_str,989tid_stop_info.details.fork.child_pid,990tid_stop_info.details.fork.child_tid);991}992993return response;994}995996GDBRemoteCommunication::PacketResult997GDBRemoteCommunicationServerLLGS::SendStopReplyPacketForThread(998NativeProcessProtocol &process, lldb::tid_t tid, bool force_synchronous) {999// Ensure we can get info on the given thread.1000NativeThreadProtocol *thread = process.GetThreadByID(tid);1001if (!thread)1002return SendErrorResponse(51);10031004StreamString response = PrepareStopReplyPacketForThread(*thread);1005if (response.Empty())1006return SendErrorResponse(42);10071008if (m_non_stop && !force_synchronous) {1009PacketResult ret = SendNotificationPacketNoLock(1010"Stop", m_stop_notification_queue, response.GetString());1011// Queue notification events for the remaining threads.1012EnqueueStopReplyPackets(tid);1013return ret;1014}10151016return SendPacketNoLock(response.GetString());1017}10181019void GDBRemoteCommunicationServerLLGS::EnqueueStopReplyPackets(1020lldb::tid_t thread_to_skip) {1021if (!m_non_stop)1022return;10231024for (NativeThreadProtocol &listed_thread : m_current_process->Threads()) {1025if (listed_thread.GetID() != thread_to_skip) {1026StreamString stop_reply = PrepareStopReplyPacketForThread(listed_thread);1027if (!stop_reply.Empty())1028m_stop_notification_queue.push_back(stop_reply.GetString().str());1029}1030}1031}10321033void GDBRemoteCommunicationServerLLGS::HandleInferiorState_Exited(1034NativeProcessProtocol *process) {1035assert(process && "process cannot be NULL");10361037Log *log = GetLog(LLDBLog::Process);1038LLDB_LOGF(log, "GDBRemoteCommunicationServerLLGS::%s called", __FUNCTION__);10391040PacketResult result = SendStopReasonForState(1041*process, StateType::eStateExited, /*force_synchronous=*/false);1042if (result != PacketResult::Success) {1043LLDB_LOGF(log,1044"GDBRemoteCommunicationServerLLGS::%s failed to send stop "1045"notification for PID %" PRIu64 ", state: eStateExited",1046__FUNCTION__, process->GetID());1047}10481049if (m_current_process == process)1050m_current_process = nullptr;1051if (m_continue_process == process)1052m_continue_process = nullptr;10531054lldb::pid_t pid = process->GetID();1055m_mainloop.AddPendingCallback([this, pid](MainLoopBase &loop) {1056auto find_it = m_debugged_processes.find(pid);1057assert(find_it != m_debugged_processes.end());1058bool vkilled = bool(find_it->second.flags & DebuggedProcess::Flag::vkilled);1059m_debugged_processes.erase(find_it);1060// Terminate the main loop only if vKill has not been used.1061// When running in non-stop mode, wait for the vStopped to clear1062// the notification queue.1063if (m_debugged_processes.empty() && !m_non_stop && !vkilled) {1064// Close the pipe to the inferior terminal i/o if we launched it and set1065// one up.1066MaybeCloseInferiorTerminalConnection();10671068// We are ready to exit the debug monitor.1069m_exit_now = true;1070loop.RequestTermination();1071}1072});1073}10741075void GDBRemoteCommunicationServerLLGS::HandleInferiorState_Stopped(1076NativeProcessProtocol *process) {1077assert(process && "process cannot be NULL");10781079Log *log = GetLog(LLDBLog::Process);1080LLDB_LOGF(log, "GDBRemoteCommunicationServerLLGS::%s called", __FUNCTION__);10811082PacketResult result = SendStopReasonForState(1083*process, StateType::eStateStopped, /*force_synchronous=*/false);1084if (result != PacketResult::Success) {1085LLDB_LOGF(log,1086"GDBRemoteCommunicationServerLLGS::%s failed to send stop "1087"notification for PID %" PRIu64 ", state: eStateExited",1088__FUNCTION__, process->GetID());1089}1090}10911092void GDBRemoteCommunicationServerLLGS::ProcessStateChanged(1093NativeProcessProtocol *process, lldb::StateType state) {1094assert(process && "process cannot be NULL");1095Log *log = GetLog(LLDBLog::Process);1096if (log) {1097LLDB_LOGF(log,1098"GDBRemoteCommunicationServerLLGS::%s called with "1099"NativeProcessProtocol pid %" PRIu64 ", state: %s",1100__FUNCTION__, process->GetID(), StateAsCString(state));1101}11021103switch (state) {1104case StateType::eStateRunning:1105break;11061107case StateType::eStateStopped:1108// Make sure we get all of the pending stdout/stderr from the inferior and1109// send it to the lldb host before we send the state change notification1110SendProcessOutput();1111// Then stop the forwarding, so that any late output (see llvm.org/pr25652)1112// does not interfere with our protocol.1113if (!m_non_stop)1114StopSTDIOForwarding();1115HandleInferiorState_Stopped(process);1116break;11171118case StateType::eStateExited:1119// Same as above1120SendProcessOutput();1121if (!m_non_stop)1122StopSTDIOForwarding();1123HandleInferiorState_Exited(process);1124break;11251126default:1127if (log) {1128LLDB_LOGF(log,1129"GDBRemoteCommunicationServerLLGS::%s didn't handle state "1130"change for pid %" PRIu64 ", new state: %s",1131__FUNCTION__, process->GetID(), StateAsCString(state));1132}1133break;1134}1135}11361137void GDBRemoteCommunicationServerLLGS::DidExec(NativeProcessProtocol *process) {1138ClearProcessSpecificData();1139}11401141void GDBRemoteCommunicationServerLLGS::NewSubprocess(1142NativeProcessProtocol *parent_process,1143std::unique_ptr<NativeProcessProtocol> child_process) {1144lldb::pid_t child_pid = child_process->GetID();1145assert(child_pid != LLDB_INVALID_PROCESS_ID);1146assert(m_debugged_processes.find(child_pid) == m_debugged_processes.end());1147m_debugged_processes.emplace(1148child_pid,1149DebuggedProcess{std::move(child_process), DebuggedProcess::Flag{}});1150}11511152void GDBRemoteCommunicationServerLLGS::DataAvailableCallback() {1153Log *log = GetLog(GDBRLog::Comm);11541155bool interrupt = false;1156bool done = false;1157Status error;1158while (true) {1159const PacketResult result = GetPacketAndSendResponse(1160std::chrono::microseconds(0), error, interrupt, done);1161if (result == PacketResult::ErrorReplyTimeout)1162break; // No more packets in the queue11631164if ((result != PacketResult::Success)) {1165LLDB_LOGF(log,1166"GDBRemoteCommunicationServerLLGS::%s processing a packet "1167"failed: %s",1168__FUNCTION__, error.AsCString());1169m_mainloop.RequestTermination();1170break;1171}1172}1173}11741175Status GDBRemoteCommunicationServerLLGS::InitializeConnection(1176std::unique_ptr<Connection> connection) {1177IOObjectSP read_object_sp = connection->GetReadObject();1178GDBRemoteCommunicationServer::SetConnection(std::move(connection));11791180Status error;1181m_network_handle_up = m_mainloop.RegisterReadObject(1182read_object_sp, [this](MainLoopBase &) { DataAvailableCallback(); },1183error);1184return error;1185}11861187GDBRemoteCommunication::PacketResult1188GDBRemoteCommunicationServerLLGS::SendONotification(const char *buffer,1189uint32_t len) {1190if ((buffer == nullptr) || (len == 0)) {1191// Nothing to send.1192return PacketResult::Success;1193}11941195StreamString response;1196response.PutChar('O');1197response.PutBytesAsRawHex8(buffer, len);11981199if (m_non_stop)1200return SendNotificationPacketNoLock("Stdio", m_stdio_notification_queue,1201response.GetString());1202return SendPacketNoLock(response.GetString());1203}12041205Status GDBRemoteCommunicationServerLLGS::SetSTDIOFileDescriptor(int fd) {1206Status error;12071208// Set up the reading/handling of process I/O1209std::unique_ptr<ConnectionFileDescriptor> conn_up(1210new ConnectionFileDescriptor(fd, true));1211if (!conn_up) {1212error.SetErrorString("failed to create ConnectionFileDescriptor");1213return error;1214}12151216m_stdio_communication.SetCloseOnEOF(false);1217m_stdio_communication.SetConnection(std::move(conn_up));1218if (!m_stdio_communication.IsConnected()) {1219error.SetErrorString(1220"failed to set connection for inferior I/O communication");1221return error;1222}12231224return Status();1225}12261227void GDBRemoteCommunicationServerLLGS::StartSTDIOForwarding() {1228// Don't forward if not connected (e.g. when attaching).1229if (!m_stdio_communication.IsConnected())1230return;12311232Status error;1233assert(!m_stdio_handle_up);1234m_stdio_handle_up = m_mainloop.RegisterReadObject(1235m_stdio_communication.GetConnection()->GetReadObject(),1236[this](MainLoopBase &) { SendProcessOutput(); }, error);12371238if (!m_stdio_handle_up) {1239// Not much we can do about the failure. Log it and continue without1240// forwarding.1241if (Log *log = GetLog(LLDBLog::Process))1242LLDB_LOG(log, "Failed to set up stdio forwarding: {0}", error);1243}1244}12451246void GDBRemoteCommunicationServerLLGS::StopSTDIOForwarding() {1247m_stdio_handle_up.reset();1248}12491250void GDBRemoteCommunicationServerLLGS::SendProcessOutput() {1251char buffer[1024];1252ConnectionStatus status;1253Status error;1254while (true) {1255size_t bytes_read = m_stdio_communication.Read(1256buffer, sizeof buffer, std::chrono::microseconds(0), status, &error);1257switch (status) {1258case eConnectionStatusSuccess:1259SendONotification(buffer, bytes_read);1260break;1261case eConnectionStatusLostConnection:1262case eConnectionStatusEndOfFile:1263case eConnectionStatusError:1264case eConnectionStatusNoConnection:1265if (Log *log = GetLog(LLDBLog::Process))1266LLDB_LOGF(log,1267"GDBRemoteCommunicationServerLLGS::%s Stopping stdio "1268"forwarding as communication returned status %d (error: "1269"%s)",1270__FUNCTION__, status, error.AsCString());1271m_stdio_handle_up.reset();1272return;12731274case eConnectionStatusInterrupted:1275case eConnectionStatusTimedOut:1276return;1277}1278}1279}12801281GDBRemoteCommunication::PacketResult1282GDBRemoteCommunicationServerLLGS::Handle_jLLDBTraceSupported(1283StringExtractorGDBRemote &packet) {12841285// Fail if we don't have a current process.1286if (!m_current_process ||1287(m_current_process->GetID() == LLDB_INVALID_PROCESS_ID))1288return SendErrorResponse(Status("Process not running."));12891290return SendJSONResponse(m_current_process->TraceSupported());1291}12921293GDBRemoteCommunication::PacketResult1294GDBRemoteCommunicationServerLLGS::Handle_jLLDBTraceStop(1295StringExtractorGDBRemote &packet) {1296// Fail if we don't have a current process.1297if (!m_current_process ||1298(m_current_process->GetID() == LLDB_INVALID_PROCESS_ID))1299return SendErrorResponse(Status("Process not running."));13001301packet.ConsumeFront("jLLDBTraceStop:");1302Expected<TraceStopRequest> stop_request =1303json::parse<TraceStopRequest>(packet.Peek(), "TraceStopRequest");1304if (!stop_request)1305return SendErrorResponse(stop_request.takeError());13061307if (Error err = m_current_process->TraceStop(*stop_request))1308return SendErrorResponse(std::move(err));13091310return SendOKResponse();1311}13121313GDBRemoteCommunication::PacketResult1314GDBRemoteCommunicationServerLLGS::Handle_jLLDBTraceStart(1315StringExtractorGDBRemote &packet) {13161317// Fail if we don't have a current process.1318if (!m_current_process ||1319(m_current_process->GetID() == LLDB_INVALID_PROCESS_ID))1320return SendErrorResponse(Status("Process not running."));13211322packet.ConsumeFront("jLLDBTraceStart:");1323Expected<TraceStartRequest> request =1324json::parse<TraceStartRequest>(packet.Peek(), "TraceStartRequest");1325if (!request)1326return SendErrorResponse(request.takeError());13271328if (Error err = m_current_process->TraceStart(packet.Peek(), request->type))1329return SendErrorResponse(std::move(err));13301331return SendOKResponse();1332}13331334GDBRemoteCommunication::PacketResult1335GDBRemoteCommunicationServerLLGS::Handle_jLLDBTraceGetState(1336StringExtractorGDBRemote &packet) {13371338// Fail if we don't have a current process.1339if (!m_current_process ||1340(m_current_process->GetID() == LLDB_INVALID_PROCESS_ID))1341return SendErrorResponse(Status("Process not running."));13421343packet.ConsumeFront("jLLDBTraceGetState:");1344Expected<TraceGetStateRequest> request =1345json::parse<TraceGetStateRequest>(packet.Peek(), "TraceGetStateRequest");1346if (!request)1347return SendErrorResponse(request.takeError());13481349return SendJSONResponse(m_current_process->TraceGetState(request->type));1350}13511352GDBRemoteCommunication::PacketResult1353GDBRemoteCommunicationServerLLGS::Handle_jLLDBTraceGetBinaryData(1354StringExtractorGDBRemote &packet) {13551356// Fail if we don't have a current process.1357if (!m_current_process ||1358(m_current_process->GetID() == LLDB_INVALID_PROCESS_ID))1359return SendErrorResponse(Status("Process not running."));13601361packet.ConsumeFront("jLLDBTraceGetBinaryData:");1362llvm::Expected<TraceGetBinaryDataRequest> request =1363llvm::json::parse<TraceGetBinaryDataRequest>(packet.Peek(),1364"TraceGetBinaryDataRequest");1365if (!request)1366return SendErrorResponse(Status(request.takeError()));13671368if (Expected<std::vector<uint8_t>> bytes =1369m_current_process->TraceGetBinaryData(*request)) {1370StreamGDBRemote response;1371response.PutEscapedBytes(bytes->data(), bytes->size());1372return SendPacketNoLock(response.GetString());1373} else1374return SendErrorResponse(bytes.takeError());1375}13761377GDBRemoteCommunication::PacketResult1378GDBRemoteCommunicationServerLLGS::Handle_qProcessInfo(1379StringExtractorGDBRemote &packet) {1380// Fail if we don't have a current process.1381if (!m_current_process ||1382(m_current_process->GetID() == LLDB_INVALID_PROCESS_ID))1383return SendErrorResponse(68);13841385lldb::pid_t pid = m_current_process->GetID();13861387if (pid == LLDB_INVALID_PROCESS_ID)1388return SendErrorResponse(1);13891390ProcessInstanceInfo proc_info;1391if (!Host::GetProcessInfo(pid, proc_info))1392return SendErrorResponse(1);13931394StreamString response;1395CreateProcessInfoResponse_DebugServerStyle(proc_info, response);1396return SendPacketNoLock(response.GetString());1397}13981399GDBRemoteCommunication::PacketResult1400GDBRemoteCommunicationServerLLGS::Handle_qC(StringExtractorGDBRemote &packet) {1401// Fail if we don't have a current process.1402if (!m_current_process ||1403(m_current_process->GetID() == LLDB_INVALID_PROCESS_ID))1404return SendErrorResponse(68);14051406// Make sure we set the current thread so g and p packets return the data the1407// gdb will expect.1408lldb::tid_t tid = m_current_process->GetCurrentThreadID();1409SetCurrentThreadID(tid);14101411NativeThreadProtocol *thread = m_current_process->GetCurrentThread();1412if (!thread)1413return SendErrorResponse(69);14141415StreamString response;1416response.PutCString("QC");1417AppendThreadIDToResponse(response, m_current_process->GetID(),1418thread->GetID());14191420return SendPacketNoLock(response.GetString());1421}14221423GDBRemoteCommunication::PacketResult1424GDBRemoteCommunicationServerLLGS::Handle_k(StringExtractorGDBRemote &packet) {1425Log *log = GetLog(LLDBLog::Process);14261427if (!m_non_stop)1428StopSTDIOForwarding();14291430if (m_debugged_processes.empty()) {1431LLDB_LOG(log, "No debugged process found.");1432return PacketResult::Success;1433}14341435for (auto it = m_debugged_processes.begin(); it != m_debugged_processes.end();1436++it) {1437LLDB_LOG(log, "Killing process {0}", it->first);1438Status error = it->second.process_up->Kill();1439if (error.Fail())1440LLDB_LOG(log, "Failed to kill debugged process {0}: {1}", it->first,1441error);1442}14431444// The response to kill packet is undefined per the spec. LLDB1445// follows the same rules as for continue packets, i.e. no response1446// in all-stop mode, and "OK" in non-stop mode; in both cases this1447// is followed by the actual stop reason.1448return SendContinueSuccessResponse();1449}14501451GDBRemoteCommunication::PacketResult1452GDBRemoteCommunicationServerLLGS::Handle_vKill(1453StringExtractorGDBRemote &packet) {1454if (!m_non_stop)1455StopSTDIOForwarding();14561457packet.SetFilePos(6); // vKill;1458uint32_t pid = packet.GetU32(LLDB_INVALID_PROCESS_ID, 16);1459if (pid == LLDB_INVALID_PROCESS_ID)1460return SendIllFormedResponse(packet,1461"vKill failed to parse the process id");14621463auto it = m_debugged_processes.find(pid);1464if (it == m_debugged_processes.end())1465return SendErrorResponse(42);14661467Status error = it->second.process_up->Kill();1468if (error.Fail())1469return SendErrorResponse(error.ToError());14701471// OK response is sent when the process dies.1472it->second.flags |= DebuggedProcess::Flag::vkilled;1473return PacketResult::Success;1474}14751476GDBRemoteCommunication::PacketResult1477GDBRemoteCommunicationServerLLGS::Handle_QSetDisableASLR(1478StringExtractorGDBRemote &packet) {1479packet.SetFilePos(::strlen("QSetDisableASLR:"));1480if (packet.GetU32(0))1481m_process_launch_info.GetFlags().Set(eLaunchFlagDisableASLR);1482else1483m_process_launch_info.GetFlags().Clear(eLaunchFlagDisableASLR);1484return SendOKResponse();1485}14861487GDBRemoteCommunication::PacketResult1488GDBRemoteCommunicationServerLLGS::Handle_QSetWorkingDir(1489StringExtractorGDBRemote &packet) {1490packet.SetFilePos(::strlen("QSetWorkingDir:"));1491std::string path;1492packet.GetHexByteString(path);1493m_process_launch_info.SetWorkingDirectory(FileSpec(path));1494return SendOKResponse();1495}14961497GDBRemoteCommunication::PacketResult1498GDBRemoteCommunicationServerLLGS::Handle_qGetWorkingDir(1499StringExtractorGDBRemote &packet) {1500FileSpec working_dir{m_process_launch_info.GetWorkingDirectory()};1501if (working_dir) {1502StreamString response;1503response.PutStringAsRawHex8(working_dir.GetPath().c_str());1504return SendPacketNoLock(response.GetString());1505}15061507return SendErrorResponse(14);1508}15091510GDBRemoteCommunication::PacketResult1511GDBRemoteCommunicationServerLLGS::Handle_QThreadSuffixSupported(1512StringExtractorGDBRemote &packet) {1513m_thread_suffix_supported = true;1514return SendOKResponse();1515}15161517GDBRemoteCommunication::PacketResult1518GDBRemoteCommunicationServerLLGS::Handle_QListThreadsInStopReply(1519StringExtractorGDBRemote &packet) {1520m_list_threads_in_stop_reply = true;1521return SendOKResponse();1522}15231524GDBRemoteCommunication::PacketResult1525GDBRemoteCommunicationServerLLGS::ResumeProcess(1526NativeProcessProtocol &process, const ResumeActionList &actions) {1527Log *log = GetLog(LLDBLog::Process | LLDBLog::Thread);15281529// In non-stop protocol mode, the process could be running already.1530// We do not support resuming threads independently, so just error out.1531if (!process.CanResume()) {1532LLDB_LOG(log, "process {0} cannot be resumed (state={1})", process.GetID(),1533process.GetState());1534return SendErrorResponse(0x37);1535}15361537Status error = process.Resume(actions);1538if (error.Fail()) {1539LLDB_LOG(log, "process {0} failed to resume: {1}", process.GetID(), error);1540return SendErrorResponse(GDBRemoteServerError::eErrorResume);1541}15421543LLDB_LOG(log, "process {0} resumed", process.GetID());15441545return PacketResult::Success;1546}15471548GDBRemoteCommunication::PacketResult1549GDBRemoteCommunicationServerLLGS::Handle_C(StringExtractorGDBRemote &packet) {1550Log *log = GetLog(LLDBLog::Process | LLDBLog::Thread);1551LLDB_LOGF(log, "GDBRemoteCommunicationServerLLGS::%s called", __FUNCTION__);15521553// Ensure we have a native process.1554if (!m_continue_process) {1555LLDB_LOGF(log,1556"GDBRemoteCommunicationServerLLGS::%s no debugged process "1557"shared pointer",1558__FUNCTION__);1559return SendErrorResponse(0x36);1560}15611562// Pull out the signal number.1563packet.SetFilePos(::strlen("C"));1564if (packet.GetBytesLeft() < 1) {1565// Shouldn't be using a C without a signal.1566return SendIllFormedResponse(packet, "C packet specified without signal.");1567}1568const uint32_t signo =1569packet.GetHexMaxU32(false, std::numeric_limits<uint32_t>::max());1570if (signo == std::numeric_limits<uint32_t>::max())1571return SendIllFormedResponse(packet, "failed to parse signal number");15721573// Handle optional continue address.1574if (packet.GetBytesLeft() > 0) {1575// FIXME add continue at address support for $C{signo}[;{continue-address}].1576if (*packet.Peek() == ';')1577return SendUnimplementedResponse(packet.GetStringRef().data());1578else1579return SendIllFormedResponse(1580packet, "unexpected content after $C{signal-number}");1581}15821583// In non-stop protocol mode, the process could be running already.1584// We do not support resuming threads independently, so just error out.1585if (!m_continue_process->CanResume()) {1586LLDB_LOG(log, "process cannot be resumed (state={0})",1587m_continue_process->GetState());1588return SendErrorResponse(0x37);1589}15901591ResumeActionList resume_actions(StateType::eStateRunning,1592LLDB_INVALID_SIGNAL_NUMBER);1593Status error;15941595// We have two branches: what to do if a continue thread is specified (in1596// which case we target sending the signal to that thread), or when we don't1597// have a continue thread set (in which case we send a signal to the1598// process).15991600// TODO discuss with Greg Clayton, make sure this makes sense.16011602lldb::tid_t signal_tid = GetContinueThreadID();1603if (signal_tid != LLDB_INVALID_THREAD_ID) {1604// The resume action for the continue thread (or all threads if a continue1605// thread is not set).1606ResumeAction action = {GetContinueThreadID(), StateType::eStateRunning,1607static_cast<int>(signo)};16081609// Add the action for the continue thread (or all threads when the continue1610// thread isn't present).1611resume_actions.Append(action);1612} else {1613// Send the signal to the process since we weren't targeting a specific1614// continue thread with the signal.1615error = m_continue_process->Signal(signo);1616if (error.Fail()) {1617LLDB_LOG(log, "failed to send signal for process {0}: {1}",1618m_continue_process->GetID(), error);16191620return SendErrorResponse(0x52);1621}1622}16231624// NB: this checks CanResume() twice but using a single code path for1625// resuming still seems worth it.1626PacketResult resume_res = ResumeProcess(*m_continue_process, resume_actions);1627if (resume_res != PacketResult::Success)1628return resume_res;16291630// Don't send an "OK" packet, except in non-stop mode;1631// otherwise, the response is the stopped/exited message.1632return SendContinueSuccessResponse();1633}16341635GDBRemoteCommunication::PacketResult1636GDBRemoteCommunicationServerLLGS::Handle_c(StringExtractorGDBRemote &packet) {1637Log *log = GetLog(LLDBLog::Process | LLDBLog::Thread);1638LLDB_LOGF(log, "GDBRemoteCommunicationServerLLGS::%s called", __FUNCTION__);16391640packet.SetFilePos(packet.GetFilePos() + ::strlen("c"));16411642// For now just support all continue.1643const bool has_continue_address = (packet.GetBytesLeft() > 0);1644if (has_continue_address) {1645LLDB_LOG(log, "not implemented for c[address] variant [{0} remains]",1646packet.Peek());1647return SendUnimplementedResponse(packet.GetStringRef().data());1648}16491650// Ensure we have a native process.1651if (!m_continue_process) {1652LLDB_LOGF(log,1653"GDBRemoteCommunicationServerLLGS::%s no debugged process "1654"shared pointer",1655__FUNCTION__);1656return SendErrorResponse(0x36);1657}16581659// Build the ResumeActionList1660ResumeActionList actions(StateType::eStateRunning,1661LLDB_INVALID_SIGNAL_NUMBER);16621663PacketResult resume_res = ResumeProcess(*m_continue_process, actions);1664if (resume_res != PacketResult::Success)1665return resume_res;16661667return SendContinueSuccessResponse();1668}16691670GDBRemoteCommunication::PacketResult1671GDBRemoteCommunicationServerLLGS::Handle_vCont_actions(1672StringExtractorGDBRemote &packet) {1673StreamString response;1674response.Printf("vCont;c;C;s;S;t");16751676return SendPacketNoLock(response.GetString());1677}16781679static bool ResumeActionListStopsAllThreads(ResumeActionList &actions) {1680// We're doing a stop-all if and only if our only action is a "t" for all1681// threads.1682if (const ResumeAction *default_action =1683actions.GetActionForThread(LLDB_INVALID_THREAD_ID, false)) {1684if (default_action->state == eStateSuspended && actions.GetSize() == 1)1685return true;1686}16871688return false;1689}16901691GDBRemoteCommunication::PacketResult1692GDBRemoteCommunicationServerLLGS::Handle_vCont(1693StringExtractorGDBRemote &packet) {1694Log *log = GetLog(LLDBLog::Process);1695LLDB_LOGF(log, "GDBRemoteCommunicationServerLLGS::%s handling vCont packet",1696__FUNCTION__);16971698packet.SetFilePos(::strlen("vCont"));16991700if (packet.GetBytesLeft() == 0) {1701LLDB_LOGF(log,1702"GDBRemoteCommunicationServerLLGS::%s missing action from "1703"vCont package",1704__FUNCTION__);1705return SendIllFormedResponse(packet, "Missing action from vCont package");1706}17071708if (::strcmp(packet.Peek(), ";s") == 0) {1709// Move past the ';', then do a simple 's'.1710packet.SetFilePos(packet.GetFilePos() + 1);1711return Handle_s(packet);1712}17131714std::unordered_map<lldb::pid_t, ResumeActionList> thread_actions;17151716while (packet.GetBytesLeft() && *packet.Peek() == ';') {1717// Skip the semi-colon.1718packet.GetChar();17191720// Build up the thread action.1721ResumeAction thread_action;1722thread_action.tid = LLDB_INVALID_THREAD_ID;1723thread_action.state = eStateInvalid;1724thread_action.signal = LLDB_INVALID_SIGNAL_NUMBER;17251726const char action = packet.GetChar();1727switch (action) {1728case 'C':1729thread_action.signal = packet.GetHexMaxU32(false, 0);1730if (thread_action.signal == 0)1731return SendIllFormedResponse(1732packet, "Could not parse signal in vCont packet C action");1733[[fallthrough]];17341735case 'c':1736// Continue1737thread_action.state = eStateRunning;1738break;17391740case 'S':1741thread_action.signal = packet.GetHexMaxU32(false, 0);1742if (thread_action.signal == 0)1743return SendIllFormedResponse(1744packet, "Could not parse signal in vCont packet S action");1745[[fallthrough]];17461747case 's':1748// Step1749thread_action.state = eStateStepping;1750break;17511752case 't':1753// Stop1754thread_action.state = eStateSuspended;1755break;17561757default:1758return SendIllFormedResponse(packet, "Unsupported vCont action");1759break;1760}17611762// If there's no thread-id (e.g. "vCont;c"), it's "p-1.-1".1763lldb::pid_t pid = StringExtractorGDBRemote::AllProcesses;1764lldb::tid_t tid = StringExtractorGDBRemote::AllThreads;17651766// Parse out optional :{thread-id} value.1767if (packet.GetBytesLeft() && (*packet.Peek() == ':')) {1768// Consume the separator.1769packet.GetChar();17701771auto pid_tid = packet.GetPidTid(LLDB_INVALID_PROCESS_ID);1772if (!pid_tid)1773return SendIllFormedResponse(packet, "Malformed thread-id");17741775pid = pid_tid->first;1776tid = pid_tid->second;1777}17781779if (thread_action.state == eStateSuspended &&1780tid != StringExtractorGDBRemote::AllThreads) {1781return SendIllFormedResponse(1782packet, "'t' action not supported for individual threads");1783}17841785// If we get TID without PID, it's the current process.1786if (pid == LLDB_INVALID_PROCESS_ID) {1787if (!m_continue_process) {1788LLDB_LOG(log, "no process selected via Hc");1789return SendErrorResponse(0x36);1790}1791pid = m_continue_process->GetID();1792}17931794assert(pid != LLDB_INVALID_PROCESS_ID);1795if (tid == StringExtractorGDBRemote::AllThreads)1796tid = LLDB_INVALID_THREAD_ID;1797thread_action.tid = tid;17981799if (pid == StringExtractorGDBRemote::AllProcesses) {1800if (tid != LLDB_INVALID_THREAD_ID)1801return SendIllFormedResponse(1802packet, "vCont: p-1 is not valid with a specific tid");1803for (auto &process_it : m_debugged_processes)1804thread_actions[process_it.first].Append(thread_action);1805} else1806thread_actions[pid].Append(thread_action);1807}18081809assert(thread_actions.size() >= 1);1810if (thread_actions.size() > 1 && !m_non_stop)1811return SendIllFormedResponse(1812packet,1813"Resuming multiple processes is supported in non-stop mode only");18141815for (std::pair<lldb::pid_t, ResumeActionList> x : thread_actions) {1816auto process_it = m_debugged_processes.find(x.first);1817if (process_it == m_debugged_processes.end()) {1818LLDB_LOG(log, "vCont failed for process {0}: process not debugged",1819x.first);1820return SendErrorResponse(GDBRemoteServerError::eErrorResume);1821}18221823// There are four possible scenarios here. These are:1824// 1. vCont on a stopped process that resumes at least one thread.1825// In this case, we call Resume().1826// 2. vCont on a stopped process that leaves all threads suspended.1827// A no-op.1828// 3. vCont on a running process that requests suspending all1829// running threads. In this case, we call Interrupt().1830// 4. vCont on a running process that requests suspending a subset1831// of running threads or resuming a subset of suspended threads.1832// Since we do not support full nonstop mode, this is unsupported1833// and we return an error.18341835assert(process_it->second.process_up);1836if (ResumeActionListStopsAllThreads(x.second)) {1837if (process_it->second.process_up->IsRunning()) {1838assert(m_non_stop);18391840Status error = process_it->second.process_up->Interrupt();1841if (error.Fail()) {1842LLDB_LOG(log, "vCont failed to halt process {0}: {1}", x.first,1843error);1844return SendErrorResponse(GDBRemoteServerError::eErrorResume);1845}18461847LLDB_LOG(log, "halted process {0}", x.first);18481849// hack to avoid enabling stdio forwarding after stop1850// TODO: remove this when we improve stdio forwarding for nonstop1851assert(thread_actions.size() == 1);1852return SendOKResponse();1853}1854} else {1855PacketResult resume_res =1856ResumeProcess(*process_it->second.process_up, x.second);1857if (resume_res != PacketResult::Success)1858return resume_res;1859}1860}18611862return SendContinueSuccessResponse();1863}18641865void GDBRemoteCommunicationServerLLGS::SetCurrentThreadID(lldb::tid_t tid) {1866Log *log = GetLog(LLDBLog::Thread);1867LLDB_LOG(log, "setting current thread id to {0}", tid);18681869m_current_tid = tid;1870if (m_current_process)1871m_current_process->SetCurrentThreadID(m_current_tid);1872}18731874void GDBRemoteCommunicationServerLLGS::SetContinueThreadID(lldb::tid_t tid) {1875Log *log = GetLog(LLDBLog::Thread);1876LLDB_LOG(log, "setting continue thread id to {0}", tid);18771878m_continue_tid = tid;1879}18801881GDBRemoteCommunication::PacketResult1882GDBRemoteCommunicationServerLLGS::Handle_stop_reason(1883StringExtractorGDBRemote &packet) {1884// Handle the $? gdbremote command.18851886if (m_non_stop) {1887// Clear the notification queue first, except for pending exit1888// notifications.1889llvm::erase_if(m_stop_notification_queue, [](const std::string &x) {1890return x.front() != 'W' && x.front() != 'X';1891});18921893if (m_current_process) {1894// Queue stop reply packets for all active threads. Start with1895// the current thread (for clients that don't actually support multiple1896// stop reasons).1897NativeThreadProtocol *thread = m_current_process->GetCurrentThread();1898if (thread) {1899StreamString stop_reply = PrepareStopReplyPacketForThread(*thread);1900if (!stop_reply.Empty())1901m_stop_notification_queue.push_back(stop_reply.GetString().str());1902}1903EnqueueStopReplyPackets(thread ? thread->GetID()1904: LLDB_INVALID_THREAD_ID);1905}19061907// If the notification queue is empty (i.e. everything is running), send OK.1908if (m_stop_notification_queue.empty())1909return SendOKResponse();19101911// Send the first item from the new notification queue synchronously.1912return SendPacketNoLock(m_stop_notification_queue.front());1913}19141915// If no process, indicate error1916if (!m_current_process)1917return SendErrorResponse(02);19181919return SendStopReasonForState(*m_current_process,1920m_current_process->GetState(),1921/*force_synchronous=*/true);1922}19231924GDBRemoteCommunication::PacketResult1925GDBRemoteCommunicationServerLLGS::SendStopReasonForState(1926NativeProcessProtocol &process, lldb::StateType process_state,1927bool force_synchronous) {1928Log *log = GetLog(LLDBLog::Process);19291930if (m_disabling_non_stop) {1931// Check if we are waiting for any more processes to stop. If we are,1932// do not send the OK response yet.1933for (const auto &it : m_debugged_processes) {1934if (it.second.process_up->IsRunning())1935return PacketResult::Success;1936}19371938// If all expected processes were stopped after a QNonStop:0 request,1939// send the OK response.1940m_disabling_non_stop = false;1941return SendOKResponse();1942}19431944switch (process_state) {1945case eStateAttaching:1946case eStateLaunching:1947case eStateRunning:1948case eStateStepping:1949case eStateDetached:1950// NOTE: gdb protocol doc looks like it should return $OK1951// when everything is running (i.e. no stopped result).1952return PacketResult::Success; // Ignore19531954case eStateSuspended:1955case eStateStopped:1956case eStateCrashed: {1957lldb::tid_t tid = process.GetCurrentThreadID();1958// Make sure we set the current thread so g and p packets return the data1959// the gdb will expect.1960SetCurrentThreadID(tid);1961return SendStopReplyPacketForThread(process, tid, force_synchronous);1962}19631964case eStateInvalid:1965case eStateUnloaded:1966case eStateExited:1967return SendWResponse(&process);19681969default:1970LLDB_LOG(log, "pid {0}, current state reporting not handled: {1}",1971process.GetID(), process_state);1972break;1973}19741975return SendErrorResponse(0);1976}19771978GDBRemoteCommunication::PacketResult1979GDBRemoteCommunicationServerLLGS::Handle_qRegisterInfo(1980StringExtractorGDBRemote &packet) {1981// Fail if we don't have a current process.1982if (!m_current_process ||1983(m_current_process->GetID() == LLDB_INVALID_PROCESS_ID))1984return SendErrorResponse(68);19851986// Ensure we have a thread.1987NativeThreadProtocol *thread = m_current_process->GetThreadAtIndex(0);1988if (!thread)1989return SendErrorResponse(69);19901991// Get the register context for the first thread.1992NativeRegisterContext ®_context = thread->GetRegisterContext();19931994// Parse out the register number from the request.1995packet.SetFilePos(strlen("qRegisterInfo"));1996const uint32_t reg_index =1997packet.GetHexMaxU32(false, std::numeric_limits<uint32_t>::max());1998if (reg_index == std::numeric_limits<uint32_t>::max())1999return SendErrorResponse(69);20002001// Return the end of registers response if we've iterated one past the end of2002// the register set.2003if (reg_index >= reg_context.GetUserRegisterCount())2004return SendErrorResponse(69);20052006const RegisterInfo *reg_info = reg_context.GetRegisterInfoAtIndex(reg_index);2007if (!reg_info)2008return SendErrorResponse(69);20092010// Build the reginfos response.2011StreamGDBRemote response;20122013response.PutCString("name:");2014response.PutCString(reg_info->name);2015response.PutChar(';');20162017if (reg_info->alt_name && reg_info->alt_name[0]) {2018response.PutCString("alt-name:");2019response.PutCString(reg_info->alt_name);2020response.PutChar(';');2021}20222023response.Printf("bitsize:%" PRIu32 ";", reg_info->byte_size * 8);20242025if (!reg_context.RegisterOffsetIsDynamic())2026response.Printf("offset:%" PRIu32 ";", reg_info->byte_offset);20272028llvm::StringRef encoding = GetEncodingNameOrEmpty(*reg_info);2029if (!encoding.empty())2030response << "encoding:" << encoding << ';';20312032llvm::StringRef format = GetFormatNameOrEmpty(*reg_info);2033if (!format.empty())2034response << "format:" << format << ';';20352036const char *const register_set_name =2037reg_context.GetRegisterSetNameForRegisterAtIndex(reg_index);2038if (register_set_name)2039response << "set:" << register_set_name << ';';20402041if (reg_info->kinds[RegisterKind::eRegisterKindEHFrame] !=2042LLDB_INVALID_REGNUM)2043response.Printf("ehframe:%" PRIu32 ";",2044reg_info->kinds[RegisterKind::eRegisterKindEHFrame]);20452046if (reg_info->kinds[RegisterKind::eRegisterKindDWARF] != LLDB_INVALID_REGNUM)2047response.Printf("dwarf:%" PRIu32 ";",2048reg_info->kinds[RegisterKind::eRegisterKindDWARF]);20492050llvm::StringRef kind_generic = GetKindGenericOrEmpty(*reg_info);2051if (!kind_generic.empty())2052response << "generic:" << kind_generic << ';';20532054if (reg_info->value_regs && reg_info->value_regs[0] != LLDB_INVALID_REGNUM) {2055response.PutCString("container-regs:");2056CollectRegNums(reg_info->value_regs, response, true);2057response.PutChar(';');2058}20592060if (reg_info->invalidate_regs && reg_info->invalidate_regs[0]) {2061response.PutCString("invalidate-regs:");2062CollectRegNums(reg_info->invalidate_regs, response, true);2063response.PutChar(';');2064}20652066return SendPacketNoLock(response.GetString());2067}20682069void GDBRemoteCommunicationServerLLGS::AddProcessThreads(2070StreamGDBRemote &response, NativeProcessProtocol &process, bool &had_any) {2071Log *log = GetLog(LLDBLog::Thread);20722073lldb::pid_t pid = process.GetID();2074if (pid == LLDB_INVALID_PROCESS_ID)2075return;20762077LLDB_LOG(log, "iterating over threads of process {0}", process.GetID());2078for (NativeThreadProtocol &thread : process.Threads()) {2079LLDB_LOG(log, "iterated thread tid={0}", thread.GetID());2080response.PutChar(had_any ? ',' : 'm');2081AppendThreadIDToResponse(response, pid, thread.GetID());2082had_any = true;2083}2084}20852086GDBRemoteCommunication::PacketResult2087GDBRemoteCommunicationServerLLGS::Handle_qfThreadInfo(2088StringExtractorGDBRemote &packet) {2089assert(m_debugged_processes.size() <= 1 ||2090bool(m_extensions_supported &2091NativeProcessProtocol::Extension::multiprocess));20922093bool had_any = false;2094StreamGDBRemote response;20952096for (auto &pid_ptr : m_debugged_processes)2097AddProcessThreads(response, *pid_ptr.second.process_up, had_any);20982099if (!had_any)2100return SendOKResponse();2101return SendPacketNoLock(response.GetString());2102}21032104GDBRemoteCommunication::PacketResult2105GDBRemoteCommunicationServerLLGS::Handle_qsThreadInfo(2106StringExtractorGDBRemote &packet) {2107// FIXME for now we return the full thread list in the initial packet and2108// always do nothing here.2109return SendPacketNoLock("l");2110}21112112GDBRemoteCommunication::PacketResult2113GDBRemoteCommunicationServerLLGS::Handle_g(StringExtractorGDBRemote &packet) {2114Log *log = GetLog(LLDBLog::Thread);21152116// Move past packet name.2117packet.SetFilePos(strlen("g"));21182119// Get the thread to use.2120NativeThreadProtocol *thread = GetThreadFromSuffix(packet);2121if (!thread) {2122LLDB_LOG(log, "failed, no thread available");2123return SendErrorResponse(0x15);2124}21252126// Get the thread's register context.2127NativeRegisterContext ®_ctx = thread->GetRegisterContext();21282129std::vector<uint8_t> regs_buffer;2130for (uint32_t reg_num = 0; reg_num < reg_ctx.GetUserRegisterCount();2131++reg_num) {2132const RegisterInfo *reg_info = reg_ctx.GetRegisterInfoAtIndex(reg_num);21332134if (reg_info == nullptr) {2135LLDB_LOG(log, "failed to get register info for register index {0}",2136reg_num);2137return SendErrorResponse(0x15);2138}21392140if (reg_info->value_regs != nullptr)2141continue; // skip registers that are contained in other registers21422143RegisterValue reg_value;2144Status error = reg_ctx.ReadRegister(reg_info, reg_value);2145if (error.Fail()) {2146LLDB_LOG(log, "failed to read register at index {0}", reg_num);2147return SendErrorResponse(0x15);2148}21492150if (reg_info->byte_offset + reg_info->byte_size >= regs_buffer.size())2151// Resize the buffer to guarantee it can store the register offsetted2152// data.2153regs_buffer.resize(reg_info->byte_offset + reg_info->byte_size);21542155// Copy the register offsetted data to the buffer.2156memcpy(regs_buffer.data() + reg_info->byte_offset, reg_value.GetBytes(),2157reg_info->byte_size);2158}21592160// Write the response.2161StreamGDBRemote response;2162response.PutBytesAsRawHex8(regs_buffer.data(), regs_buffer.size());21632164return SendPacketNoLock(response.GetString());2165}21662167GDBRemoteCommunication::PacketResult2168GDBRemoteCommunicationServerLLGS::Handle_p(StringExtractorGDBRemote &packet) {2169Log *log = GetLog(LLDBLog::Thread);21702171// Parse out the register number from the request.2172packet.SetFilePos(strlen("p"));2173const uint32_t reg_index =2174packet.GetHexMaxU32(false, std::numeric_limits<uint32_t>::max());2175if (reg_index == std::numeric_limits<uint32_t>::max()) {2176LLDB_LOGF(log,2177"GDBRemoteCommunicationServerLLGS::%s failed, could not "2178"parse register number from request \"%s\"",2179__FUNCTION__, packet.GetStringRef().data());2180return SendErrorResponse(0x15);2181}21822183// Get the thread to use.2184NativeThreadProtocol *thread = GetThreadFromSuffix(packet);2185if (!thread) {2186LLDB_LOG(log, "failed, no thread available");2187return SendErrorResponse(0x15);2188}21892190// Get the thread's register context.2191NativeRegisterContext ®_context = thread->GetRegisterContext();21922193// Return the end of registers response if we've iterated one past the end of2194// the register set.2195if (reg_index >= reg_context.GetUserRegisterCount()) {2196LLDB_LOGF(log,2197"GDBRemoteCommunicationServerLLGS::%s failed, requested "2198"register %" PRIu32 " beyond register count %" PRIu32,2199__FUNCTION__, reg_index, reg_context.GetUserRegisterCount());2200return SendErrorResponse(0x15);2201}22022203const RegisterInfo *reg_info = reg_context.GetRegisterInfoAtIndex(reg_index);2204if (!reg_info) {2205LLDB_LOGF(log,2206"GDBRemoteCommunicationServerLLGS::%s failed, requested "2207"register %" PRIu32 " returned NULL",2208__FUNCTION__, reg_index);2209return SendErrorResponse(0x15);2210}22112212// Build the reginfos response.2213StreamGDBRemote response;22142215// Retrieve the value2216RegisterValue reg_value;2217Status error = reg_context.ReadRegister(reg_info, reg_value);2218if (error.Fail()) {2219LLDB_LOGF(log,2220"GDBRemoteCommunicationServerLLGS::%s failed, read of "2221"requested register %" PRIu32 " (%s) failed: %s",2222__FUNCTION__, reg_index, reg_info->name, error.AsCString());2223return SendErrorResponse(0x15);2224}22252226const uint8_t *const data =2227static_cast<const uint8_t *>(reg_value.GetBytes());2228if (!data) {2229LLDB_LOGF(log,2230"GDBRemoteCommunicationServerLLGS::%s failed to get data "2231"bytes from requested register %" PRIu32,2232__FUNCTION__, reg_index);2233return SendErrorResponse(0x15);2234}22352236// FIXME flip as needed to get data in big/little endian format for this host.2237for (uint32_t i = 0; i < reg_value.GetByteSize(); ++i)2238response.PutHex8(data[i]);22392240return SendPacketNoLock(response.GetString());2241}22422243GDBRemoteCommunication::PacketResult2244GDBRemoteCommunicationServerLLGS::Handle_P(StringExtractorGDBRemote &packet) {2245Log *log = GetLog(LLDBLog::Thread);22462247// Ensure there is more content.2248if (packet.GetBytesLeft() < 1)2249return SendIllFormedResponse(packet, "Empty P packet");22502251// Parse out the register number from the request.2252packet.SetFilePos(strlen("P"));2253const uint32_t reg_index =2254packet.GetHexMaxU32(false, std::numeric_limits<uint32_t>::max());2255if (reg_index == std::numeric_limits<uint32_t>::max()) {2256LLDB_LOGF(log,2257"GDBRemoteCommunicationServerLLGS::%s failed, could not "2258"parse register number from request \"%s\"",2259__FUNCTION__, packet.GetStringRef().data());2260return SendErrorResponse(0x29);2261}22622263// Note debugserver would send an E30 here.2264if ((packet.GetBytesLeft() < 1) || (packet.GetChar() != '='))2265return SendIllFormedResponse(2266packet, "P packet missing '=' char after register number");22672268// Parse out the value.2269size_t reg_size = packet.GetHexBytesAvail(m_reg_bytes);22702271// Get the thread to use.2272NativeThreadProtocol *thread = GetThreadFromSuffix(packet);2273if (!thread) {2274LLDB_LOGF(log,2275"GDBRemoteCommunicationServerLLGS::%s failed, no thread "2276"available (thread index 0)",2277__FUNCTION__);2278return SendErrorResponse(0x28);2279}22802281// Get the thread's register context.2282NativeRegisterContext ®_context = thread->GetRegisterContext();2283const RegisterInfo *reg_info = reg_context.GetRegisterInfoAtIndex(reg_index);2284if (!reg_info) {2285LLDB_LOGF(log,2286"GDBRemoteCommunicationServerLLGS::%s failed, requested "2287"register %" PRIu32 " returned NULL",2288__FUNCTION__, reg_index);2289return SendErrorResponse(0x48);2290}22912292// Return the end of registers response if we've iterated one past the end of2293// the register set.2294if (reg_index >= reg_context.GetUserRegisterCount()) {2295LLDB_LOGF(log,2296"GDBRemoteCommunicationServerLLGS::%s failed, requested "2297"register %" PRIu32 " beyond register count %" PRIu32,2298__FUNCTION__, reg_index, reg_context.GetUserRegisterCount());2299return SendErrorResponse(0x47);2300}23012302if (reg_size != reg_info->byte_size)2303return SendIllFormedResponse(packet, "P packet register size is incorrect");23042305// Build the reginfos response.2306StreamGDBRemote response;23072308RegisterValue reg_value(ArrayRef<uint8_t>(m_reg_bytes, reg_size),2309m_current_process->GetArchitecture().GetByteOrder());2310Status error = reg_context.WriteRegister(reg_info, reg_value);2311if (error.Fail()) {2312LLDB_LOGF(log,2313"GDBRemoteCommunicationServerLLGS::%s failed, write of "2314"requested register %" PRIu32 " (%s) failed: %s",2315__FUNCTION__, reg_index, reg_info->name, error.AsCString());2316return SendErrorResponse(0x32);2317}23182319return SendOKResponse();2320}23212322GDBRemoteCommunication::PacketResult2323GDBRemoteCommunicationServerLLGS::Handle_H(StringExtractorGDBRemote &packet) {2324Log *log = GetLog(LLDBLog::Thread);23252326// Parse out which variant of $H is requested.2327packet.SetFilePos(strlen("H"));2328if (packet.GetBytesLeft() < 1) {2329LLDB_LOGF(log,2330"GDBRemoteCommunicationServerLLGS::%s failed, H command "2331"missing {g,c} variant",2332__FUNCTION__);2333return SendIllFormedResponse(packet, "H command missing {g,c} variant");2334}23352336const char h_variant = packet.GetChar();2337NativeProcessProtocol *default_process;2338switch (h_variant) {2339case 'g':2340default_process = m_current_process;2341break;23422343case 'c':2344default_process = m_continue_process;2345break;23462347default:2348LLDB_LOGF(2349log,2350"GDBRemoteCommunicationServerLLGS::%s failed, invalid $H variant %c",2351__FUNCTION__, h_variant);2352return SendIllFormedResponse(packet,2353"H variant unsupported, should be c or g");2354}23552356// Parse out the thread number.2357auto pid_tid = packet.GetPidTid(default_process ? default_process->GetID()2358: LLDB_INVALID_PROCESS_ID);2359if (!pid_tid)2360return SendErrorResponse(llvm::make_error<StringError>(2361inconvertibleErrorCode(), "Malformed thread-id"));23622363lldb::pid_t pid = pid_tid->first;2364lldb::tid_t tid = pid_tid->second;23652366if (pid == StringExtractorGDBRemote::AllProcesses)2367return SendUnimplementedResponse("Selecting all processes not supported");2368if (pid == LLDB_INVALID_PROCESS_ID)2369return SendErrorResponse(llvm::make_error<StringError>(2370inconvertibleErrorCode(), "No current process and no PID provided"));23712372// Check the process ID and find respective process instance.2373auto new_process_it = m_debugged_processes.find(pid);2374if (new_process_it == m_debugged_processes.end())2375return SendErrorResponse(llvm::make_error<StringError>(2376inconvertibleErrorCode(),2377llvm::formatv("No process with PID {0} debugged", pid)));23782379// Ensure we have the given thread when not specifying -1 (all threads) or 02380// (any thread).2381if (tid != LLDB_INVALID_THREAD_ID && tid != 0) {2382NativeThreadProtocol *thread =2383new_process_it->second.process_up->GetThreadByID(tid);2384if (!thread) {2385LLDB_LOGF(log,2386"GDBRemoteCommunicationServerLLGS::%s failed, tid %" PRIu642387" not found",2388__FUNCTION__, tid);2389return SendErrorResponse(0x15);2390}2391}23922393// Now switch the given process and thread type.2394switch (h_variant) {2395case 'g':2396m_current_process = new_process_it->second.process_up.get();2397SetCurrentThreadID(tid);2398break;23992400case 'c':2401m_continue_process = new_process_it->second.process_up.get();2402SetContinueThreadID(tid);2403break;24042405default:2406assert(false && "unsupported $H variant - shouldn't get here");2407return SendIllFormedResponse(packet,2408"H variant unsupported, should be c or g");2409}24102411return SendOKResponse();2412}24132414GDBRemoteCommunication::PacketResult2415GDBRemoteCommunicationServerLLGS::Handle_I(StringExtractorGDBRemote &packet) {2416Log *log = GetLog(LLDBLog::Thread);24172418// Fail if we don't have a current process.2419if (!m_current_process ||2420(m_current_process->GetID() == LLDB_INVALID_PROCESS_ID)) {2421LLDB_LOGF(2422log,2423"GDBRemoteCommunicationServerLLGS::%s failed, no process available",2424__FUNCTION__);2425return SendErrorResponse(0x15);2426}24272428packet.SetFilePos(::strlen("I"));2429uint8_t tmp[4096];2430for (;;) {2431size_t read = packet.GetHexBytesAvail(tmp);2432if (read == 0) {2433break;2434}2435// write directly to stdin *this might block if stdin buffer is full*2436// TODO: enqueue this block in circular buffer and send window size to2437// remote host2438ConnectionStatus status;2439Status error;2440m_stdio_communication.WriteAll(tmp, read, status, &error);2441if (error.Fail()) {2442return SendErrorResponse(0x15);2443}2444}24452446return SendOKResponse();2447}24482449GDBRemoteCommunication::PacketResult2450GDBRemoteCommunicationServerLLGS::Handle_interrupt(2451StringExtractorGDBRemote &packet) {2452Log *log = GetLog(LLDBLog::Process | LLDBLog::Thread);24532454// Fail if we don't have a current process.2455if (!m_current_process ||2456(m_current_process->GetID() == LLDB_INVALID_PROCESS_ID)) {2457LLDB_LOG(log, "failed, no process available");2458return SendErrorResponse(0x15);2459}24602461// Interrupt the process.2462Status error = m_current_process->Interrupt();2463if (error.Fail()) {2464LLDB_LOG(log, "failed for process {0}: {1}", m_current_process->GetID(),2465error);2466return SendErrorResponse(GDBRemoteServerError::eErrorResume);2467}24682469LLDB_LOG(log, "stopped process {0}", m_current_process->GetID());24702471// No response required from stop all.2472return PacketResult::Success;2473}24742475GDBRemoteCommunication::PacketResult2476GDBRemoteCommunicationServerLLGS::Handle_memory_read(2477StringExtractorGDBRemote &packet) {2478Log *log = GetLog(LLDBLog::Process);24792480if (!m_current_process ||2481(m_current_process->GetID() == LLDB_INVALID_PROCESS_ID)) {2482LLDB_LOGF(2483log,2484"GDBRemoteCommunicationServerLLGS::%s failed, no process available",2485__FUNCTION__);2486return SendErrorResponse(0x15);2487}24882489// Parse out the memory address.2490packet.SetFilePos(strlen("m"));2491if (packet.GetBytesLeft() < 1)2492return SendIllFormedResponse(packet, "Too short m packet");24932494// Read the address. Punting on validation.2495// FIXME replace with Hex U64 read with no default value that fails on failed2496// read.2497const lldb::addr_t read_addr = packet.GetHexMaxU64(false, 0);24982499// Validate comma.2500if ((packet.GetBytesLeft() < 1) || (packet.GetChar() != ','))2501return SendIllFormedResponse(packet, "Comma sep missing in m packet");25022503// Get # bytes to read.2504if (packet.GetBytesLeft() < 1)2505return SendIllFormedResponse(packet, "Length missing in m packet");25062507const uint64_t byte_count = packet.GetHexMaxU64(false, 0);2508if (byte_count == 0) {2509LLDB_LOGF(log,2510"GDBRemoteCommunicationServerLLGS::%s nothing to read: "2511"zero-length packet",2512__FUNCTION__);2513return SendOKResponse();2514}25152516// Allocate the response buffer.2517std::string buf(byte_count, '\0');2518if (buf.empty())2519return SendErrorResponse(0x78);25202521// Retrieve the process memory.2522size_t bytes_read = 0;2523Status error = m_current_process->ReadMemoryWithoutTrap(2524read_addr, &buf[0], byte_count, bytes_read);2525if (error.Fail()) {2526LLDB_LOGF(log,2527"GDBRemoteCommunicationServerLLGS::%s pid %" PRIu642528" mem 0x%" PRIx64 ": failed to read. Error: %s",2529__FUNCTION__, m_current_process->GetID(), read_addr,2530error.AsCString());2531return SendErrorResponse(0x08);2532}25332534if (bytes_read == 0) {2535LLDB_LOGF(log,2536"GDBRemoteCommunicationServerLLGS::%s pid %" PRIu642537" mem 0x%" PRIx64 ": read 0 of %" PRIu64 " requested bytes",2538__FUNCTION__, m_current_process->GetID(), read_addr, byte_count);2539return SendErrorResponse(0x08);2540}25412542StreamGDBRemote response;2543packet.SetFilePos(0);2544char kind = packet.GetChar('?');2545if (kind == 'x')2546response.PutEscapedBytes(buf.data(), byte_count);2547else {2548assert(kind == 'm');2549for (size_t i = 0; i < bytes_read; ++i)2550response.PutHex8(buf[i]);2551}25522553return SendPacketNoLock(response.GetString());2554}25552556GDBRemoteCommunication::PacketResult2557GDBRemoteCommunicationServerLLGS::Handle__M(StringExtractorGDBRemote &packet) {2558Log *log = GetLog(LLDBLog::Process);25592560if (!m_current_process ||2561(m_current_process->GetID() == LLDB_INVALID_PROCESS_ID)) {2562LLDB_LOGF(2563log,2564"GDBRemoteCommunicationServerLLGS::%s failed, no process available",2565__FUNCTION__);2566return SendErrorResponse(0x15);2567}25682569// Parse out the memory address.2570packet.SetFilePos(strlen("_M"));2571if (packet.GetBytesLeft() < 1)2572return SendIllFormedResponse(packet, "Too short _M packet");25732574const lldb::addr_t size = packet.GetHexMaxU64(false, LLDB_INVALID_ADDRESS);2575if (size == LLDB_INVALID_ADDRESS)2576return SendIllFormedResponse(packet, "Address not valid");2577if (packet.GetChar() != ',')2578return SendIllFormedResponse(packet, "Bad packet");2579Permissions perms = {};2580while (packet.GetBytesLeft() > 0) {2581switch (packet.GetChar()) {2582case 'r':2583perms |= ePermissionsReadable;2584break;2585case 'w':2586perms |= ePermissionsWritable;2587break;2588case 'x':2589perms |= ePermissionsExecutable;2590break;2591default:2592return SendIllFormedResponse(packet, "Bad permissions");2593}2594}25952596llvm::Expected<addr_t> addr = m_current_process->AllocateMemory(size, perms);2597if (!addr)2598return SendErrorResponse(addr.takeError());25992600StreamGDBRemote response;2601response.PutHex64(*addr);2602return SendPacketNoLock(response.GetString());2603}26042605GDBRemoteCommunication::PacketResult2606GDBRemoteCommunicationServerLLGS::Handle__m(StringExtractorGDBRemote &packet) {2607Log *log = GetLog(LLDBLog::Process);26082609if (!m_current_process ||2610(m_current_process->GetID() == LLDB_INVALID_PROCESS_ID)) {2611LLDB_LOGF(2612log,2613"GDBRemoteCommunicationServerLLGS::%s failed, no process available",2614__FUNCTION__);2615return SendErrorResponse(0x15);2616}26172618// Parse out the memory address.2619packet.SetFilePos(strlen("_m"));2620if (packet.GetBytesLeft() < 1)2621return SendIllFormedResponse(packet, "Too short m packet");26222623const lldb::addr_t addr = packet.GetHexMaxU64(false, LLDB_INVALID_ADDRESS);2624if (addr == LLDB_INVALID_ADDRESS)2625return SendIllFormedResponse(packet, "Address not valid");26262627if (llvm::Error Err = m_current_process->DeallocateMemory(addr))2628return SendErrorResponse(std::move(Err));26292630return SendOKResponse();2631}26322633GDBRemoteCommunication::PacketResult2634GDBRemoteCommunicationServerLLGS::Handle_M(StringExtractorGDBRemote &packet) {2635Log *log = GetLog(LLDBLog::Process);26362637if (!m_current_process ||2638(m_current_process->GetID() == LLDB_INVALID_PROCESS_ID)) {2639LLDB_LOGF(2640log,2641"GDBRemoteCommunicationServerLLGS::%s failed, no process available",2642__FUNCTION__);2643return SendErrorResponse(0x15);2644}26452646// Parse out the memory address.2647packet.SetFilePos(strlen("M"));2648if (packet.GetBytesLeft() < 1)2649return SendIllFormedResponse(packet, "Too short M packet");26502651// Read the address. Punting on validation.2652// FIXME replace with Hex U64 read with no default value that fails on failed2653// read.2654const lldb::addr_t write_addr = packet.GetHexMaxU64(false, 0);26552656// Validate comma.2657if ((packet.GetBytesLeft() < 1) || (packet.GetChar() != ','))2658return SendIllFormedResponse(packet, "Comma sep missing in M packet");26592660// Get # bytes to read.2661if (packet.GetBytesLeft() < 1)2662return SendIllFormedResponse(packet, "Length missing in M packet");26632664const uint64_t byte_count = packet.GetHexMaxU64(false, 0);2665if (byte_count == 0) {2666LLDB_LOG(log, "nothing to write: zero-length packet");2667return PacketResult::Success;2668}26692670// Validate colon.2671if ((packet.GetBytesLeft() < 1) || (packet.GetChar() != ':'))2672return SendIllFormedResponse(2673packet, "Comma sep missing in M packet after byte length");26742675// Allocate the conversion buffer.2676std::vector<uint8_t> buf(byte_count, 0);2677if (buf.empty())2678return SendErrorResponse(0x78);26792680// Convert the hex memory write contents to bytes.2681StreamGDBRemote response;2682const uint64_t convert_count = packet.GetHexBytes(buf, 0);2683if (convert_count != byte_count) {2684LLDB_LOG(log,2685"pid {0} mem {1:x}: asked to write {2} bytes, but only found {3} "2686"to convert.",2687m_current_process->GetID(), write_addr, byte_count, convert_count);2688return SendIllFormedResponse(packet, "M content byte length specified did "2689"not match hex-encoded content "2690"length");2691}26922693// Write the process memory.2694size_t bytes_written = 0;2695Status error = m_current_process->WriteMemory(write_addr, &buf[0], byte_count,2696bytes_written);2697if (error.Fail()) {2698LLDB_LOG(log, "pid {0} mem {1:x}: failed to write. Error: {2}",2699m_current_process->GetID(), write_addr, error);2700return SendErrorResponse(0x09);2701}27022703if (bytes_written == 0) {2704LLDB_LOG(log, "pid {0} mem {1:x}: wrote 0 of {2} requested bytes",2705m_current_process->GetID(), write_addr, byte_count);2706return SendErrorResponse(0x09);2707}27082709return SendOKResponse();2710}27112712GDBRemoteCommunication::PacketResult2713GDBRemoteCommunicationServerLLGS::Handle_qMemoryRegionInfoSupported(2714StringExtractorGDBRemote &packet) {2715Log *log = GetLog(LLDBLog::Process);27162717// Currently only the NativeProcessProtocol knows if it can handle a2718// qMemoryRegionInfoSupported request, but we're not guaranteed to be2719// attached to a process. For now we'll assume the client only asks this2720// when a process is being debugged.27212722// Ensure we have a process running; otherwise, we can't figure this out2723// since we won't have a NativeProcessProtocol.2724if (!m_current_process ||2725(m_current_process->GetID() == LLDB_INVALID_PROCESS_ID)) {2726LLDB_LOGF(2727log,2728"GDBRemoteCommunicationServerLLGS::%s failed, no process available",2729__FUNCTION__);2730return SendErrorResponse(0x15);2731}27322733// Test if we can get any region back when asking for the region around NULL.2734MemoryRegionInfo region_info;2735const Status error = m_current_process->GetMemoryRegionInfo(0, region_info);2736if (error.Fail()) {2737// We don't support memory region info collection for this2738// NativeProcessProtocol.2739return SendUnimplementedResponse("");2740}27412742return SendOKResponse();2743}27442745GDBRemoteCommunication::PacketResult2746GDBRemoteCommunicationServerLLGS::Handle_qMemoryRegionInfo(2747StringExtractorGDBRemote &packet) {2748Log *log = GetLog(LLDBLog::Process);27492750// Ensure we have a process.2751if (!m_current_process ||2752(m_current_process->GetID() == LLDB_INVALID_PROCESS_ID)) {2753LLDB_LOGF(2754log,2755"GDBRemoteCommunicationServerLLGS::%s failed, no process available",2756__FUNCTION__);2757return SendErrorResponse(0x15);2758}27592760// Parse out the memory address.2761packet.SetFilePos(strlen("qMemoryRegionInfo:"));2762if (packet.GetBytesLeft() < 1)2763return SendIllFormedResponse(packet, "Too short qMemoryRegionInfo: packet");27642765// Read the address. Punting on validation.2766const lldb::addr_t read_addr = packet.GetHexMaxU64(false, 0);27672768StreamGDBRemote response;27692770// Get the memory region info for the target address.2771MemoryRegionInfo region_info;2772const Status error =2773m_current_process->GetMemoryRegionInfo(read_addr, region_info);2774if (error.Fail()) {2775// Return the error message.27762777response.PutCString("error:");2778response.PutStringAsRawHex8(error.AsCString());2779response.PutChar(';');2780} else {2781// Range start and size.2782response.Printf("start:%" PRIx64 ";size:%" PRIx64 ";",2783region_info.GetRange().GetRangeBase(),2784region_info.GetRange().GetByteSize());27852786// Permissions.2787if (region_info.GetReadable() || region_info.GetWritable() ||2788region_info.GetExecutable()) {2789// Write permissions info.2790response.PutCString("permissions:");27912792if (region_info.GetReadable())2793response.PutChar('r');2794if (region_info.GetWritable())2795response.PutChar('w');2796if (region_info.GetExecutable())2797response.PutChar('x');27982799response.PutChar(';');2800}28012802// Flags2803MemoryRegionInfo::OptionalBool memory_tagged =2804region_info.GetMemoryTagged();2805if (memory_tagged != MemoryRegionInfo::eDontKnow) {2806response.PutCString("flags:");2807if (memory_tagged == MemoryRegionInfo::eYes) {2808response.PutCString("mt");2809}2810response.PutChar(';');2811}28122813// Name2814ConstString name = region_info.GetName();2815if (name) {2816response.PutCString("name:");2817response.PutStringAsRawHex8(name.GetStringRef());2818response.PutChar(';');2819}2820}28212822return SendPacketNoLock(response.GetString());2823}28242825GDBRemoteCommunication::PacketResult2826GDBRemoteCommunicationServerLLGS::Handle_Z(StringExtractorGDBRemote &packet) {2827// Ensure we have a process.2828if (!m_current_process ||2829(m_current_process->GetID() == LLDB_INVALID_PROCESS_ID)) {2830Log *log = GetLog(LLDBLog::Process);2831LLDB_LOG(log, "failed, no process available");2832return SendErrorResponse(0x15);2833}28342835// Parse out software or hardware breakpoint or watchpoint requested.2836packet.SetFilePos(strlen("Z"));2837if (packet.GetBytesLeft() < 1)2838return SendIllFormedResponse(2839packet, "Too short Z packet, missing software/hardware specifier");28402841bool want_breakpoint = true;2842bool want_hardware = false;2843uint32_t watch_flags = 0;28442845const GDBStoppointType stoppoint_type =2846GDBStoppointType(packet.GetS32(eStoppointInvalid));2847switch (stoppoint_type) {2848case eBreakpointSoftware:2849want_hardware = false;2850want_breakpoint = true;2851break;2852case eBreakpointHardware:2853want_hardware = true;2854want_breakpoint = true;2855break;2856case eWatchpointWrite:2857watch_flags = 1;2858want_hardware = true;2859want_breakpoint = false;2860break;2861case eWatchpointRead:2862watch_flags = 2;2863want_hardware = true;2864want_breakpoint = false;2865break;2866case eWatchpointReadWrite:2867watch_flags = 3;2868want_hardware = true;2869want_breakpoint = false;2870break;2871case eStoppointInvalid:2872return SendIllFormedResponse(2873packet, "Z packet had invalid software/hardware specifier");2874}28752876if ((packet.GetBytesLeft() < 1) || packet.GetChar() != ',')2877return SendIllFormedResponse(2878packet, "Malformed Z packet, expecting comma after stoppoint type");28792880// Parse out the stoppoint address.2881if (packet.GetBytesLeft() < 1)2882return SendIllFormedResponse(packet, "Too short Z packet, missing address");2883const lldb::addr_t addr = packet.GetHexMaxU64(false, 0);28842885if ((packet.GetBytesLeft() < 1) || packet.GetChar() != ',')2886return SendIllFormedResponse(2887packet, "Malformed Z packet, expecting comma after address");28882889// Parse out the stoppoint size (i.e. size hint for opcode size).2890const uint32_t size =2891packet.GetHexMaxU32(false, std::numeric_limits<uint32_t>::max());2892if (size == std::numeric_limits<uint32_t>::max())2893return SendIllFormedResponse(2894packet, "Malformed Z packet, failed to parse size argument");28952896if (want_breakpoint) {2897// Try to set the breakpoint.2898const Status error =2899m_current_process->SetBreakpoint(addr, size, want_hardware);2900if (error.Success())2901return SendOKResponse();2902Log *log = GetLog(LLDBLog::Breakpoints);2903LLDB_LOG(log, "pid {0} failed to set breakpoint: {1}",2904m_current_process->GetID(), error);2905return SendErrorResponse(0x09);2906} else {2907// Try to set the watchpoint.2908const Status error = m_current_process->SetWatchpoint(2909addr, size, watch_flags, want_hardware);2910if (error.Success())2911return SendOKResponse();2912Log *log = GetLog(LLDBLog::Watchpoints);2913LLDB_LOG(log, "pid {0} failed to set watchpoint: {1}",2914m_current_process->GetID(), error);2915return SendErrorResponse(0x09);2916}2917}29182919GDBRemoteCommunication::PacketResult2920GDBRemoteCommunicationServerLLGS::Handle_z(StringExtractorGDBRemote &packet) {2921// Ensure we have a process.2922if (!m_current_process ||2923(m_current_process->GetID() == LLDB_INVALID_PROCESS_ID)) {2924Log *log = GetLog(LLDBLog::Process);2925LLDB_LOG(log, "failed, no process available");2926return SendErrorResponse(0x15);2927}29282929// Parse out software or hardware breakpoint or watchpoint requested.2930packet.SetFilePos(strlen("z"));2931if (packet.GetBytesLeft() < 1)2932return SendIllFormedResponse(2933packet, "Too short z packet, missing software/hardware specifier");29342935bool want_breakpoint = true;2936bool want_hardware = false;29372938const GDBStoppointType stoppoint_type =2939GDBStoppointType(packet.GetS32(eStoppointInvalid));2940switch (stoppoint_type) {2941case eBreakpointHardware:2942want_breakpoint = true;2943want_hardware = true;2944break;2945case eBreakpointSoftware:2946want_breakpoint = true;2947break;2948case eWatchpointWrite:2949want_breakpoint = false;2950break;2951case eWatchpointRead:2952want_breakpoint = false;2953break;2954case eWatchpointReadWrite:2955want_breakpoint = false;2956break;2957default:2958return SendIllFormedResponse(2959packet, "z packet had invalid software/hardware specifier");2960}29612962if ((packet.GetBytesLeft() < 1) || packet.GetChar() != ',')2963return SendIllFormedResponse(2964packet, "Malformed z packet, expecting comma after stoppoint type");29652966// Parse out the stoppoint address.2967if (packet.GetBytesLeft() < 1)2968return SendIllFormedResponse(packet, "Too short z packet, missing address");2969const lldb::addr_t addr = packet.GetHexMaxU64(false, 0);29702971if ((packet.GetBytesLeft() < 1) || packet.GetChar() != ',')2972return SendIllFormedResponse(2973packet, "Malformed z packet, expecting comma after address");29742975/*2976// Parse out the stoppoint size (i.e. size hint for opcode size).2977const uint32_t size = packet.GetHexMaxU32 (false,2978std::numeric_limits<uint32_t>::max ());2979if (size == std::numeric_limits<uint32_t>::max ())2980return SendIllFormedResponse(packet, "Malformed z packet, failed to parse2981size argument");2982*/29832984if (want_breakpoint) {2985// Try to clear the breakpoint.2986const Status error =2987m_current_process->RemoveBreakpoint(addr, want_hardware);2988if (error.Success())2989return SendOKResponse();2990Log *log = GetLog(LLDBLog::Breakpoints);2991LLDB_LOG(log, "pid {0} failed to remove breakpoint: {1}",2992m_current_process->GetID(), error);2993return SendErrorResponse(0x09);2994} else {2995// Try to clear the watchpoint.2996const Status error = m_current_process->RemoveWatchpoint(addr);2997if (error.Success())2998return SendOKResponse();2999Log *log = GetLog(LLDBLog::Watchpoints);3000LLDB_LOG(log, "pid {0} failed to remove watchpoint: {1}",3001m_current_process->GetID(), error);3002return SendErrorResponse(0x09);3003}3004}30053006GDBRemoteCommunication::PacketResult3007GDBRemoteCommunicationServerLLGS::Handle_s(StringExtractorGDBRemote &packet) {3008Log *log = GetLog(LLDBLog::Process | LLDBLog::Thread);30093010// Ensure we have a process.3011if (!m_continue_process ||3012(m_continue_process->GetID() == LLDB_INVALID_PROCESS_ID)) {3013LLDB_LOGF(3014log,3015"GDBRemoteCommunicationServerLLGS::%s failed, no process available",3016__FUNCTION__);3017return SendErrorResponse(0x32);3018}30193020// We first try to use a continue thread id. If any one or any all set, use3021// the current thread. Bail out if we don't have a thread id.3022lldb::tid_t tid = GetContinueThreadID();3023if (tid == 0 || tid == LLDB_INVALID_THREAD_ID)3024tid = GetCurrentThreadID();3025if (tid == LLDB_INVALID_THREAD_ID)3026return SendErrorResponse(0x33);30273028// Double check that we have such a thread.3029// TODO investigate: on MacOSX we might need to do an UpdateThreads () here.3030NativeThreadProtocol *thread = m_continue_process->GetThreadByID(tid);3031if (!thread)3032return SendErrorResponse(0x33);30333034// Create the step action for the given thread.3035ResumeAction action = {tid, eStateStepping, LLDB_INVALID_SIGNAL_NUMBER};30363037// Setup the actions list.3038ResumeActionList actions;3039actions.Append(action);30403041// All other threads stop while we're single stepping a thread.3042actions.SetDefaultThreadActionIfNeeded(eStateStopped, 0);30433044PacketResult resume_res = ResumeProcess(*m_continue_process, actions);3045if (resume_res != PacketResult::Success)3046return resume_res;30473048// No response here, unless in non-stop mode.3049// Otherwise, the stop or exit will come from the resulting action.3050return SendContinueSuccessResponse();3051}30523053llvm::Expected<std::unique_ptr<llvm::MemoryBuffer>>3054GDBRemoteCommunicationServerLLGS::BuildTargetXml() {3055// Ensure we have a thread.3056NativeThreadProtocol *thread = m_current_process->GetThreadAtIndex(0);3057if (!thread)3058return llvm::createStringError(llvm::inconvertibleErrorCode(),3059"No thread available");30603061Log *log = GetLog(LLDBLog::Process | LLDBLog::Thread);3062// Get the register context for the first thread.3063NativeRegisterContext ®_context = thread->GetRegisterContext();30643065StreamString response;30663067response.Printf("<?xml version=\"1.0\"?>\n");3068response.Printf("<target version=\"1.0\">\n");3069response.IndentMore();30703071response.Indent();3072response.Printf("<architecture>%s</architecture>\n",3073m_current_process->GetArchitecture()3074.GetTriple()3075.getArchName()3076.str()3077.c_str());30783079response.Indent("<feature>\n");30803081const int registers_count = reg_context.GetUserRegisterCount();3082if (registers_count)3083response.IndentMore();30843085llvm::StringSet<> field_enums_seen;3086for (int reg_index = 0; reg_index < registers_count; reg_index++) {3087const RegisterInfo *reg_info =3088reg_context.GetRegisterInfoAtIndex(reg_index);30893090if (!reg_info) {3091LLDB_LOGF(log,3092"%s failed to get register info for register index %" PRIu32,3093"target.xml", reg_index);3094continue;3095}30963097if (reg_info->flags_type) {3098response.IndentMore();3099reg_info->flags_type->EnumsToXML(response, field_enums_seen);3100reg_info->flags_type->ToXML(response);3101response.IndentLess();3102}31033104response.Indent();3105response.Printf("<reg name=\"%s\" bitsize=\"%" PRIu323106"\" regnum=\"%d\" ",3107reg_info->name, reg_info->byte_size * 8, reg_index);31083109if (!reg_context.RegisterOffsetIsDynamic())3110response.Printf("offset=\"%" PRIu32 "\" ", reg_info->byte_offset);31113112if (reg_info->alt_name && reg_info->alt_name[0])3113response.Printf("altname=\"%s\" ", reg_info->alt_name);31143115llvm::StringRef encoding = GetEncodingNameOrEmpty(*reg_info);3116if (!encoding.empty())3117response << "encoding=\"" << encoding << "\" ";31183119llvm::StringRef format = GetFormatNameOrEmpty(*reg_info);3120if (!format.empty())3121response << "format=\"" << format << "\" ";31223123if (reg_info->flags_type)3124response << "type=\"" << reg_info->flags_type->GetID() << "\" ";31253126const char *const register_set_name =3127reg_context.GetRegisterSetNameForRegisterAtIndex(reg_index);3128if (register_set_name)3129response << "group=\"" << register_set_name << "\" ";31303131if (reg_info->kinds[RegisterKind::eRegisterKindEHFrame] !=3132LLDB_INVALID_REGNUM)3133response.Printf("ehframe_regnum=\"%" PRIu32 "\" ",3134reg_info->kinds[RegisterKind::eRegisterKindEHFrame]);31353136if (reg_info->kinds[RegisterKind::eRegisterKindDWARF] !=3137LLDB_INVALID_REGNUM)3138response.Printf("dwarf_regnum=\"%" PRIu32 "\" ",3139reg_info->kinds[RegisterKind::eRegisterKindDWARF]);31403141llvm::StringRef kind_generic = GetKindGenericOrEmpty(*reg_info);3142if (!kind_generic.empty())3143response << "generic=\"" << kind_generic << "\" ";31443145if (reg_info->value_regs &&3146reg_info->value_regs[0] != LLDB_INVALID_REGNUM) {3147response.PutCString("value_regnums=\"");3148CollectRegNums(reg_info->value_regs, response, false);3149response.Printf("\" ");3150}31513152if (reg_info->invalidate_regs && reg_info->invalidate_regs[0]) {3153response.PutCString("invalidate_regnums=\"");3154CollectRegNums(reg_info->invalidate_regs, response, false);3155response.Printf("\" ");3156}31573158response.Printf("/>\n");3159}31603161if (registers_count)3162response.IndentLess();31633164response.Indent("</feature>\n");3165response.IndentLess();3166response.Indent("</target>\n");3167return MemoryBuffer::getMemBufferCopy(response.GetString(), "target.xml");3168}31693170llvm::Expected<std::unique_ptr<llvm::MemoryBuffer>>3171GDBRemoteCommunicationServerLLGS::ReadXferObject(llvm::StringRef object,3172llvm::StringRef annex) {3173// Make sure we have a valid process.3174if (!m_current_process ||3175(m_current_process->GetID() == LLDB_INVALID_PROCESS_ID)) {3176return llvm::createStringError(llvm::inconvertibleErrorCode(),3177"No process available");3178}31793180if (object == "auxv") {3181// Grab the auxv data.3182auto buffer_or_error = m_current_process->GetAuxvData();3183if (!buffer_or_error)3184return llvm::errorCodeToError(buffer_or_error.getError());3185return std::move(*buffer_or_error);3186}31873188if (object == "siginfo") {3189NativeThreadProtocol *thread = m_current_process->GetCurrentThread();3190if (!thread)3191return llvm::createStringError(llvm::inconvertibleErrorCode(),3192"no current thread");31933194auto buffer_or_error = thread->GetSiginfo();3195if (!buffer_or_error)3196return buffer_or_error.takeError();3197return std::move(*buffer_or_error);3198}31993200if (object == "libraries-svr4") {3201auto library_list = m_current_process->GetLoadedSVR4Libraries();3202if (!library_list)3203return library_list.takeError();32043205StreamString response;3206response.Printf("<library-list-svr4 version=\"1.0\">");3207for (auto const &library : *library_list) {3208response.Printf("<library name=\"%s\" ",3209XMLEncodeAttributeValue(library.name.c_str()).c_str());3210response.Printf("lm=\"0x%" PRIx64 "\" ", library.link_map);3211response.Printf("l_addr=\"0x%" PRIx64 "\" ", library.base_addr);3212response.Printf("l_ld=\"0x%" PRIx64 "\" />", library.ld_addr);3213}3214response.Printf("</library-list-svr4>");3215return MemoryBuffer::getMemBufferCopy(response.GetString(), __FUNCTION__);3216}32173218if (object == "features" && annex == "target.xml")3219return BuildTargetXml();32203221return llvm::make_error<UnimplementedError>();3222}32233224GDBRemoteCommunication::PacketResult3225GDBRemoteCommunicationServerLLGS::Handle_qXfer(3226StringExtractorGDBRemote &packet) {3227SmallVector<StringRef, 5> fields;3228// The packet format is "qXfer:<object>:<action>:<annex>:offset,length"3229StringRef(packet.GetStringRef()).split(fields, ':', 4);3230if (fields.size() != 5)3231return SendIllFormedResponse(packet, "malformed qXfer packet");3232StringRef &xfer_object = fields[1];3233StringRef &xfer_action = fields[2];3234StringRef &xfer_annex = fields[3];3235StringExtractor offset_data(fields[4]);3236if (xfer_action != "read")3237return SendUnimplementedResponse("qXfer action not supported");3238// Parse offset.3239const uint64_t xfer_offset =3240offset_data.GetHexMaxU64(false, std::numeric_limits<uint64_t>::max());3241if (xfer_offset == std::numeric_limits<uint64_t>::max())3242return SendIllFormedResponse(packet, "qXfer packet missing offset");3243// Parse out comma.3244if (offset_data.GetChar() != ',')3245return SendIllFormedResponse(packet,3246"qXfer packet missing comma after offset");3247// Parse out the length.3248const uint64_t xfer_length =3249offset_data.GetHexMaxU64(false, std::numeric_limits<uint64_t>::max());3250if (xfer_length == std::numeric_limits<uint64_t>::max())3251return SendIllFormedResponse(packet, "qXfer packet missing length");32523253// Get a previously constructed buffer if it exists or create it now.3254std::string buffer_key = (xfer_object + xfer_action + xfer_annex).str();3255auto buffer_it = m_xfer_buffer_map.find(buffer_key);3256if (buffer_it == m_xfer_buffer_map.end()) {3257auto buffer_up = ReadXferObject(xfer_object, xfer_annex);3258if (!buffer_up)3259return SendErrorResponse(buffer_up.takeError());3260buffer_it = m_xfer_buffer_map3261.insert(std::make_pair(buffer_key, std::move(*buffer_up)))3262.first;3263}32643265// Send back the response3266StreamGDBRemote response;3267bool done_with_buffer = false;3268llvm::StringRef buffer = buffer_it->second->getBuffer();3269if (xfer_offset >= buffer.size()) {3270// We have nothing left to send. Mark the buffer as complete.3271response.PutChar('l');3272done_with_buffer = true;3273} else {3274// Figure out how many bytes are available starting at the given offset.3275buffer = buffer.drop_front(xfer_offset);3276// Mark the response type according to whether we're reading the remainder3277// of the data.3278if (xfer_length >= buffer.size()) {3279// There will be nothing left to read after this3280response.PutChar('l');3281done_with_buffer = true;3282} else {3283// There will still be bytes to read after this request.3284response.PutChar('m');3285buffer = buffer.take_front(xfer_length);3286}3287// Now write the data in encoded binary form.3288response.PutEscapedBytes(buffer.data(), buffer.size());3289}32903291if (done_with_buffer)3292m_xfer_buffer_map.erase(buffer_it);32933294return SendPacketNoLock(response.GetString());3295}32963297GDBRemoteCommunication::PacketResult3298GDBRemoteCommunicationServerLLGS::Handle_QSaveRegisterState(3299StringExtractorGDBRemote &packet) {3300Log *log = GetLog(LLDBLog::Thread);33013302// Move past packet name.3303packet.SetFilePos(strlen("QSaveRegisterState"));33043305// Get the thread to use.3306NativeThreadProtocol *thread = GetThreadFromSuffix(packet);3307if (!thread) {3308if (m_thread_suffix_supported)3309return SendIllFormedResponse(3310packet, "No thread specified in QSaveRegisterState packet");3311else3312return SendIllFormedResponse(packet,3313"No thread was is set with the Hg packet");3314}33153316// Grab the register context for the thread.3317NativeRegisterContext& reg_context = thread->GetRegisterContext();33183319// Save registers to a buffer.3320WritableDataBufferSP register_data_sp;3321Status error = reg_context.ReadAllRegisterValues(register_data_sp);3322if (error.Fail()) {3323LLDB_LOG(log, "pid {0} failed to save all register values: {1}",3324m_current_process->GetID(), error);3325return SendErrorResponse(0x75);3326}33273328// Allocate a new save id.3329const uint32_t save_id = GetNextSavedRegistersID();3330assert((m_saved_registers_map.find(save_id) == m_saved_registers_map.end()) &&3331"GetNextRegisterSaveID() returned an existing register save id");33323333// Save the register data buffer under the save id.3334{3335std::lock_guard<std::mutex> guard(m_saved_registers_mutex);3336m_saved_registers_map[save_id] = register_data_sp;3337}33383339// Write the response.3340StreamGDBRemote response;3341response.Printf("%" PRIu32, save_id);3342return SendPacketNoLock(response.GetString());3343}33443345GDBRemoteCommunication::PacketResult3346GDBRemoteCommunicationServerLLGS::Handle_QRestoreRegisterState(3347StringExtractorGDBRemote &packet) {3348Log *log = GetLog(LLDBLog::Thread);33493350// Parse out save id.3351packet.SetFilePos(strlen("QRestoreRegisterState:"));3352if (packet.GetBytesLeft() < 1)3353return SendIllFormedResponse(3354packet, "QRestoreRegisterState packet missing register save id");33553356const uint32_t save_id = packet.GetU32(0);3357if (save_id == 0) {3358LLDB_LOG(log, "QRestoreRegisterState packet has malformed save id, "3359"expecting decimal uint32_t");3360return SendErrorResponse(0x76);3361}33623363// Get the thread to use.3364NativeThreadProtocol *thread = GetThreadFromSuffix(packet);3365if (!thread) {3366if (m_thread_suffix_supported)3367return SendIllFormedResponse(3368packet, "No thread specified in QRestoreRegisterState packet");3369else3370return SendIllFormedResponse(packet,3371"No thread was is set with the Hg packet");3372}33733374// Grab the register context for the thread.3375NativeRegisterContext ®_context = thread->GetRegisterContext();33763377// Retrieve register state buffer, then remove from the list.3378DataBufferSP register_data_sp;3379{3380std::lock_guard<std::mutex> guard(m_saved_registers_mutex);33813382// Find the register set buffer for the given save id.3383auto it = m_saved_registers_map.find(save_id);3384if (it == m_saved_registers_map.end()) {3385LLDB_LOG(log,3386"pid {0} does not have a register set save buffer for id {1}",3387m_current_process->GetID(), save_id);3388return SendErrorResponse(0x77);3389}3390register_data_sp = it->second;33913392// Remove it from the map.3393m_saved_registers_map.erase(it);3394}33953396Status error = reg_context.WriteAllRegisterValues(register_data_sp);3397if (error.Fail()) {3398LLDB_LOG(log, "pid {0} failed to restore all register values: {1}",3399m_current_process->GetID(), error);3400return SendErrorResponse(0x77);3401}34023403return SendOKResponse();3404}34053406GDBRemoteCommunication::PacketResult3407GDBRemoteCommunicationServerLLGS::Handle_vAttach(3408StringExtractorGDBRemote &packet) {3409Log *log = GetLog(LLDBLog::Process);34103411// Consume the ';' after vAttach.3412packet.SetFilePos(strlen("vAttach"));3413if (!packet.GetBytesLeft() || packet.GetChar() != ';')3414return SendIllFormedResponse(packet, "vAttach missing expected ';'");34153416// Grab the PID to which we will attach (assume hex encoding).3417lldb::pid_t pid = packet.GetU32(LLDB_INVALID_PROCESS_ID, 16);3418if (pid == LLDB_INVALID_PROCESS_ID)3419return SendIllFormedResponse(packet,3420"vAttach failed to parse the process id");34213422// Attempt to attach.3423LLDB_LOGF(log,3424"GDBRemoteCommunicationServerLLGS::%s attempting to attach to "3425"pid %" PRIu64,3426__FUNCTION__, pid);34273428Status error = AttachToProcess(pid);34293430if (error.Fail()) {3431LLDB_LOGF(log,3432"GDBRemoteCommunicationServerLLGS::%s failed to attach to "3433"pid %" PRIu64 ": %s\n",3434__FUNCTION__, pid, error.AsCString());3435return SendErrorResponse(error);3436}34373438// Notify we attached by sending a stop packet.3439assert(m_current_process);3440return SendStopReasonForState(*m_current_process,3441m_current_process->GetState(),3442/*force_synchronous=*/false);3443}34443445GDBRemoteCommunication::PacketResult3446GDBRemoteCommunicationServerLLGS::Handle_vAttachWait(3447StringExtractorGDBRemote &packet) {3448Log *log = GetLog(LLDBLog::Process);34493450// Consume the ';' after the identifier.3451packet.SetFilePos(strlen("vAttachWait"));34523453if (!packet.GetBytesLeft() || packet.GetChar() != ';')3454return SendIllFormedResponse(packet, "vAttachWait missing expected ';'");34553456// Allocate the buffer for the process name from vAttachWait.3457std::string process_name;3458if (!packet.GetHexByteString(process_name))3459return SendIllFormedResponse(packet,3460"vAttachWait failed to parse process name");34613462LLDB_LOG(log, "attempting to attach to process named '{0}'", process_name);34633464Status error = AttachWaitProcess(process_name, false);3465if (error.Fail()) {3466LLDB_LOG(log, "failed to attach to process named '{0}': {1}", process_name,3467error);3468return SendErrorResponse(error);3469}34703471// Notify we attached by sending a stop packet.3472assert(m_current_process);3473return SendStopReasonForState(*m_current_process,3474m_current_process->GetState(),3475/*force_synchronous=*/false);3476}34773478GDBRemoteCommunication::PacketResult3479GDBRemoteCommunicationServerLLGS::Handle_qVAttachOrWaitSupported(3480StringExtractorGDBRemote &packet) {3481return SendOKResponse();3482}34833484GDBRemoteCommunication::PacketResult3485GDBRemoteCommunicationServerLLGS::Handle_vAttachOrWait(3486StringExtractorGDBRemote &packet) {3487Log *log = GetLog(LLDBLog::Process);34883489// Consume the ';' after the identifier.3490packet.SetFilePos(strlen("vAttachOrWait"));34913492if (!packet.GetBytesLeft() || packet.GetChar() != ';')3493return SendIllFormedResponse(packet, "vAttachOrWait missing expected ';'");34943495// Allocate the buffer for the process name from vAttachWait.3496std::string process_name;3497if (!packet.GetHexByteString(process_name))3498return SendIllFormedResponse(packet,3499"vAttachOrWait failed to parse process name");35003501LLDB_LOG(log, "attempting to attach to process named '{0}'", process_name);35023503Status error = AttachWaitProcess(process_name, true);3504if (error.Fail()) {3505LLDB_LOG(log, "failed to attach to process named '{0}': {1}", process_name,3506error);3507return SendErrorResponse(error);3508}35093510// Notify we attached by sending a stop packet.3511assert(m_current_process);3512return SendStopReasonForState(*m_current_process,3513m_current_process->GetState(),3514/*force_synchronous=*/false);3515}35163517GDBRemoteCommunication::PacketResult3518GDBRemoteCommunicationServerLLGS::Handle_vRun(3519StringExtractorGDBRemote &packet) {3520Log *log = GetLog(LLDBLog::Process);35213522llvm::StringRef s = packet.GetStringRef();3523if (!s.consume_front("vRun;"))3524return SendErrorResponse(8);35253526llvm::SmallVector<llvm::StringRef, 16> argv;3527s.split(argv, ';');35283529for (llvm::StringRef hex_arg : argv) {3530StringExtractor arg_ext{hex_arg};3531std::string arg;3532arg_ext.GetHexByteString(arg);3533m_process_launch_info.GetArguments().AppendArgument(arg);3534LLDB_LOGF(log, "LLGSPacketHandler::%s added arg: \"%s\"", __FUNCTION__,3535arg.c_str());3536}35373538if (argv.empty())3539return SendErrorResponse(Status("No arguments"));3540m_process_launch_info.GetExecutableFile().SetFile(3541m_process_launch_info.GetArguments()[0].ref(), FileSpec::Style::native);3542m_process_launch_error = LaunchProcess();3543if (m_process_launch_error.Fail())3544return SendErrorResponse(m_process_launch_error);3545assert(m_current_process);3546return SendStopReasonForState(*m_current_process,3547m_current_process->GetState(),3548/*force_synchronous=*/true);3549}35503551GDBRemoteCommunication::PacketResult3552GDBRemoteCommunicationServerLLGS::Handle_D(StringExtractorGDBRemote &packet) {3553Log *log = GetLog(LLDBLog::Process);3554if (!m_non_stop)3555StopSTDIOForwarding();35563557lldb::pid_t pid = LLDB_INVALID_PROCESS_ID;35583559// Consume the ';' after D.3560packet.SetFilePos(1);3561if (packet.GetBytesLeft()) {3562if (packet.GetChar() != ';')3563return SendIllFormedResponse(packet, "D missing expected ';'");35643565// Grab the PID from which we will detach (assume hex encoding).3566pid = packet.GetU32(LLDB_INVALID_PROCESS_ID, 16);3567if (pid == LLDB_INVALID_PROCESS_ID)3568return SendIllFormedResponse(packet, "D failed to parse the process id");3569}35703571// Detach forked children if their PID was specified *or* no PID was requested3572// (i.e. detach-all packet).3573llvm::Error detach_error = llvm::Error::success();3574bool detached = false;3575for (auto it = m_debugged_processes.begin();3576it != m_debugged_processes.end();) {3577if (pid == LLDB_INVALID_PROCESS_ID || pid == it->first) {3578LLDB_LOGF(log,3579"GDBRemoteCommunicationServerLLGS::%s detaching %" PRId64,3580__FUNCTION__, it->first);3581if (llvm::Error e = it->second.process_up->Detach().ToError())3582detach_error = llvm::joinErrors(std::move(detach_error), std::move(e));3583else {3584if (it->second.process_up.get() == m_current_process)3585m_current_process = nullptr;3586if (it->second.process_up.get() == m_continue_process)3587m_continue_process = nullptr;3588it = m_debugged_processes.erase(it);3589detached = true;3590continue;3591}3592}3593++it;3594}35953596if (detach_error)3597return SendErrorResponse(std::move(detach_error));3598if (!detached)3599return SendErrorResponse(Status("PID %" PRIu64 " not traced", pid));3600return SendOKResponse();3601}36023603GDBRemoteCommunication::PacketResult3604GDBRemoteCommunicationServerLLGS::Handle_qThreadStopInfo(3605StringExtractorGDBRemote &packet) {3606Log *log = GetLog(LLDBLog::Thread);36073608if (!m_current_process ||3609(m_current_process->GetID() == LLDB_INVALID_PROCESS_ID))3610return SendErrorResponse(50);36113612packet.SetFilePos(strlen("qThreadStopInfo"));3613const lldb::tid_t tid = packet.GetHexMaxU64(false, LLDB_INVALID_THREAD_ID);3614if (tid == LLDB_INVALID_THREAD_ID) {3615LLDB_LOGF(log,3616"GDBRemoteCommunicationServerLLGS::%s failed, could not "3617"parse thread id from request \"%s\"",3618__FUNCTION__, packet.GetStringRef().data());3619return SendErrorResponse(0x15);3620}3621return SendStopReplyPacketForThread(*m_current_process, tid,3622/*force_synchronous=*/true);3623}36243625GDBRemoteCommunication::PacketResult3626GDBRemoteCommunicationServerLLGS::Handle_jThreadsInfo(3627StringExtractorGDBRemote &) {3628Log *log = GetLog(LLDBLog::Process | LLDBLog::Thread);36293630// Ensure we have a debugged process.3631if (!m_current_process ||3632(m_current_process->GetID() == LLDB_INVALID_PROCESS_ID))3633return SendErrorResponse(50);3634LLDB_LOG(log, "preparing packet for pid {0}", m_current_process->GetID());36353636StreamString response;3637const bool threads_with_valid_stop_info_only = false;3638llvm::Expected<json::Value> threads_info =3639GetJSONThreadsInfo(*m_current_process, threads_with_valid_stop_info_only);3640if (!threads_info) {3641LLDB_LOG_ERROR(log, threads_info.takeError(),3642"failed to prepare a packet for pid {1}: {0}",3643m_current_process->GetID());3644return SendErrorResponse(52);3645}36463647response.AsRawOstream() << *threads_info;3648StreamGDBRemote escaped_response;3649escaped_response.PutEscapedBytes(response.GetData(), response.GetSize());3650return SendPacketNoLock(escaped_response.GetString());3651}36523653GDBRemoteCommunication::PacketResult3654GDBRemoteCommunicationServerLLGS::Handle_qWatchpointSupportInfo(3655StringExtractorGDBRemote &packet) {3656// Fail if we don't have a current process.3657if (!m_current_process ||3658m_current_process->GetID() == LLDB_INVALID_PROCESS_ID)3659return SendErrorResponse(68);36603661packet.SetFilePos(strlen("qWatchpointSupportInfo"));3662if (packet.GetBytesLeft() == 0)3663return SendOKResponse();3664if (packet.GetChar() != ':')3665return SendErrorResponse(67);36663667auto hw_debug_cap = m_current_process->GetHardwareDebugSupportInfo();36683669StreamGDBRemote response;3670if (hw_debug_cap == std::nullopt)3671response.Printf("num:0;");3672else3673response.Printf("num:%d;", hw_debug_cap->second);36743675return SendPacketNoLock(response.GetString());3676}36773678GDBRemoteCommunication::PacketResult3679GDBRemoteCommunicationServerLLGS::Handle_qFileLoadAddress(3680StringExtractorGDBRemote &packet) {3681// Fail if we don't have a current process.3682if (!m_current_process ||3683m_current_process->GetID() == LLDB_INVALID_PROCESS_ID)3684return SendErrorResponse(67);36853686packet.SetFilePos(strlen("qFileLoadAddress:"));3687if (packet.GetBytesLeft() == 0)3688return SendErrorResponse(68);36893690std::string file_name;3691packet.GetHexByteString(file_name);36923693lldb::addr_t file_load_address = LLDB_INVALID_ADDRESS;3694Status error =3695m_current_process->GetFileLoadAddress(file_name, file_load_address);3696if (error.Fail())3697return SendErrorResponse(69);36983699if (file_load_address == LLDB_INVALID_ADDRESS)3700return SendErrorResponse(1); // File not loaded37013702StreamGDBRemote response;3703response.PutHex64(file_load_address);3704return SendPacketNoLock(response.GetString());3705}37063707GDBRemoteCommunication::PacketResult3708GDBRemoteCommunicationServerLLGS::Handle_QPassSignals(3709StringExtractorGDBRemote &packet) {3710std::vector<int> signals;3711packet.SetFilePos(strlen("QPassSignals:"));37123713// Read sequence of hex signal numbers divided by a semicolon and optionally3714// spaces.3715while (packet.GetBytesLeft() > 0) {3716int signal = packet.GetS32(-1, 16);3717if (signal < 0)3718return SendIllFormedResponse(packet, "Failed to parse signal number.");3719signals.push_back(signal);37203721packet.SkipSpaces();3722char separator = packet.GetChar();3723if (separator == '\0')3724break; // End of string3725if (separator != ';')3726return SendIllFormedResponse(packet, "Invalid separator,"3727" expected semicolon.");3728}37293730// Fail if we don't have a current process.3731if (!m_current_process)3732return SendErrorResponse(68);37333734Status error = m_current_process->IgnoreSignals(signals);3735if (error.Fail())3736return SendErrorResponse(69);37373738return SendOKResponse();3739}37403741GDBRemoteCommunication::PacketResult3742GDBRemoteCommunicationServerLLGS::Handle_qMemTags(3743StringExtractorGDBRemote &packet) {3744Log *log = GetLog(LLDBLog::Process);37453746// Ensure we have a process.3747if (!m_current_process ||3748(m_current_process->GetID() == LLDB_INVALID_PROCESS_ID)) {3749LLDB_LOGF(3750log,3751"GDBRemoteCommunicationServerLLGS::%s failed, no process available",3752__FUNCTION__);3753return SendErrorResponse(1);3754}37553756// We are expecting3757// qMemTags:<hex address>,<hex length>:<hex type>37583759// Address3760packet.SetFilePos(strlen("qMemTags:"));3761const char *current_char = packet.Peek();3762if (!current_char || *current_char == ',')3763return SendIllFormedResponse(packet, "Missing address in qMemTags packet");3764const lldb::addr_t addr = packet.GetHexMaxU64(/*little_endian=*/false, 0);37653766// Length3767char previous_char = packet.GetChar();3768current_char = packet.Peek();3769// If we don't have a separator or the length field is empty3770if (previous_char != ',' || (current_char && *current_char == ':'))3771return SendIllFormedResponse(packet,3772"Invalid addr,length pair in qMemTags packet");37733774if (packet.GetBytesLeft() < 1)3775return SendIllFormedResponse(3776packet, "Too short qMemtags: packet (looking for length)");3777const size_t length = packet.GetHexMaxU64(/*little_endian=*/false, 0);37783779// Type3780const char *invalid_type_err = "Invalid type field in qMemTags: packet";3781if (packet.GetBytesLeft() < 1 || packet.GetChar() != ':')3782return SendIllFormedResponse(packet, invalid_type_err);37833784// Type is a signed integer but packed into the packet as its raw bytes.3785// However, our GetU64 uses strtoull which allows +/-. We do not want this.3786const char *first_type_char = packet.Peek();3787if (first_type_char && (*first_type_char == '+' || *first_type_char == '-'))3788return SendIllFormedResponse(packet, invalid_type_err);37893790// Extract type as unsigned then cast to signed.3791// Using a uint64_t here so that we have some value outside of the 32 bit3792// range to use as the invalid return value.3793uint64_t raw_type =3794packet.GetU64(std::numeric_limits<uint64_t>::max(), /*base=*/16);37953796if ( // Make sure the cast below would be valid3797raw_type > std::numeric_limits<uint32_t>::max() ||3798// To catch inputs like "123aardvark" that will parse but clearly aren't3799// valid in this case.3800packet.GetBytesLeft()) {3801return SendIllFormedResponse(packet, invalid_type_err);3802}38033804// First narrow to 32 bits otherwise the copy into type would take3805// the wrong 4 bytes on big endian.3806uint32_t raw_type_32 = raw_type;3807int32_t type = reinterpret_cast<int32_t &>(raw_type_32);38083809StreamGDBRemote response;3810std::vector<uint8_t> tags;3811Status error = m_current_process->ReadMemoryTags(type, addr, length, tags);3812if (error.Fail())3813return SendErrorResponse(1);38143815// This m is here in case we want to support multi part replies in the future.3816// In the same manner as qfThreadInfo/qsThreadInfo.3817response.PutChar('m');3818response.PutBytesAsRawHex8(tags.data(), tags.size());3819return SendPacketNoLock(response.GetString());3820}38213822GDBRemoteCommunication::PacketResult3823GDBRemoteCommunicationServerLLGS::Handle_QMemTags(3824StringExtractorGDBRemote &packet) {3825Log *log = GetLog(LLDBLog::Process);38263827// Ensure we have a process.3828if (!m_current_process ||3829(m_current_process->GetID() == LLDB_INVALID_PROCESS_ID)) {3830LLDB_LOGF(3831log,3832"GDBRemoteCommunicationServerLLGS::%s failed, no process available",3833__FUNCTION__);3834return SendErrorResponse(1);3835}38363837// We are expecting3838// QMemTags:<hex address>,<hex length>:<hex type>:<tags as hex bytes>38393840// Address3841packet.SetFilePos(strlen("QMemTags:"));3842const char *current_char = packet.Peek();3843if (!current_char || *current_char == ',')3844return SendIllFormedResponse(packet, "Missing address in QMemTags packet");3845const lldb::addr_t addr = packet.GetHexMaxU64(/*little_endian=*/false, 0);38463847// Length3848char previous_char = packet.GetChar();3849current_char = packet.Peek();3850// If we don't have a separator or the length field is empty3851if (previous_char != ',' || (current_char && *current_char == ':'))3852return SendIllFormedResponse(packet,3853"Invalid addr,length pair in QMemTags packet");38543855if (packet.GetBytesLeft() < 1)3856return SendIllFormedResponse(3857packet, "Too short QMemtags: packet (looking for length)");3858const size_t length = packet.GetHexMaxU64(/*little_endian=*/false, 0);38593860// Type3861const char *invalid_type_err = "Invalid type field in QMemTags: packet";3862if (packet.GetBytesLeft() < 1 || packet.GetChar() != ':')3863return SendIllFormedResponse(packet, invalid_type_err);38643865// Our GetU64 uses strtoull which allows leading +/-, we don't want that.3866const char *first_type_char = packet.Peek();3867if (first_type_char && (*first_type_char == '+' || *first_type_char == '-'))3868return SendIllFormedResponse(packet, invalid_type_err);38693870// The type is a signed integer but is in the packet as its raw bytes.3871// So parse first as unsigned then cast to signed later.3872// We extract to 64 bit, even though we only expect 32, so that we've3873// got some invalid value we can check for.3874uint64_t raw_type =3875packet.GetU64(std::numeric_limits<uint64_t>::max(), /*base=*/16);3876if (raw_type > std::numeric_limits<uint32_t>::max())3877return SendIllFormedResponse(packet, invalid_type_err);38783879// First narrow to 32 bits. Otherwise the copy below would get the wrong3880// 4 bytes on big endian.3881uint32_t raw_type_32 = raw_type;3882int32_t type = reinterpret_cast<int32_t &>(raw_type_32);38833884// Tag data3885if (packet.GetBytesLeft() < 1 || packet.GetChar() != ':')3886return SendIllFormedResponse(packet,3887"Missing tag data in QMemTags: packet");38883889// Must be 2 chars per byte3890const char *invalid_data_err = "Invalid tag data in QMemTags: packet";3891if (packet.GetBytesLeft() % 2)3892return SendIllFormedResponse(packet, invalid_data_err);38933894// This is bytes here and is unpacked into target specific tags later3895// We cannot assume that number of bytes == length here because the server3896// can repeat tags to fill a given range.3897std::vector<uint8_t> tag_data;3898// Zero length writes will not have any tag data3899// (but we pass them on because it will still check that tagging is enabled)3900if (packet.GetBytesLeft()) {3901size_t byte_count = packet.GetBytesLeft() / 2;3902tag_data.resize(byte_count);3903size_t converted_bytes = packet.GetHexBytes(tag_data, 0);3904if (converted_bytes != byte_count) {3905return SendIllFormedResponse(packet, invalid_data_err);3906}3907}39083909Status status =3910m_current_process->WriteMemoryTags(type, addr, length, tag_data);3911return status.Success() ? SendOKResponse() : SendErrorResponse(1);3912}39133914GDBRemoteCommunication::PacketResult3915GDBRemoteCommunicationServerLLGS::Handle_qSaveCore(3916StringExtractorGDBRemote &packet) {3917// Fail if we don't have a current process.3918if (!m_current_process ||3919(m_current_process->GetID() == LLDB_INVALID_PROCESS_ID))3920return SendErrorResponse(Status("Process not running."));39213922std::string path_hint;39233924StringRef packet_str{packet.GetStringRef()};3925assert(packet_str.starts_with("qSaveCore"));3926if (packet_str.consume_front("qSaveCore;")) {3927for (auto x : llvm::split(packet_str, ';')) {3928if (x.consume_front("path-hint:"))3929StringExtractor(x).GetHexByteString(path_hint);3930else3931return SendErrorResponse(Status("Unsupported qSaveCore option"));3932}3933}39343935llvm::Expected<std::string> ret = m_current_process->SaveCore(path_hint);3936if (!ret)3937return SendErrorResponse(ret.takeError());39383939StreamString response;3940response.PutCString("core-path:");3941response.PutStringAsRawHex8(ret.get());3942return SendPacketNoLock(response.GetString());3943}39443945GDBRemoteCommunication::PacketResult3946GDBRemoteCommunicationServerLLGS::Handle_QNonStop(3947StringExtractorGDBRemote &packet) {3948Log *log = GetLog(LLDBLog::Process);39493950StringRef packet_str{packet.GetStringRef()};3951assert(packet_str.starts_with("QNonStop:"));3952packet_str.consume_front("QNonStop:");3953if (packet_str == "0") {3954if (m_non_stop)3955StopSTDIOForwarding();3956for (auto &process_it : m_debugged_processes) {3957if (process_it.second.process_up->IsRunning()) {3958assert(m_non_stop);3959Status error = process_it.second.process_up->Interrupt();3960if (error.Fail()) {3961LLDB_LOG(log,3962"while disabling nonstop, failed to halt process {0}: {1}",3963process_it.first, error);3964return SendErrorResponse(0x41);3965}3966// we must not send stop reasons after QNonStop3967m_disabling_non_stop = true;3968}3969}3970m_stdio_notification_queue.clear();3971m_stop_notification_queue.clear();3972m_non_stop = false;3973// If we are stopping anything, defer sending the OK response until we're3974// done.3975if (m_disabling_non_stop)3976return PacketResult::Success;3977} else if (packet_str == "1") {3978if (!m_non_stop)3979StartSTDIOForwarding();3980m_non_stop = true;3981} else3982return SendErrorResponse(Status("Invalid QNonStop packet"));3983return SendOKResponse();3984}39853986GDBRemoteCommunication::PacketResult3987GDBRemoteCommunicationServerLLGS::HandleNotificationAck(3988std::deque<std::string> &queue) {3989// Per the protocol, the first message put into the queue is sent3990// immediately. However, it remains the queue until the client ACKs it --3991// then we pop it and send the next message. The process repeats until3992// the last message in the queue is ACK-ed, in which case the packet sends3993// an OK response.3994if (queue.empty())3995return SendErrorResponse(Status("No pending notification to ack"));3996queue.pop_front();3997if (!queue.empty())3998return SendPacketNoLock(queue.front());3999return SendOKResponse();4000}40014002GDBRemoteCommunication::PacketResult4003GDBRemoteCommunicationServerLLGS::Handle_vStdio(4004StringExtractorGDBRemote &packet) {4005return HandleNotificationAck(m_stdio_notification_queue);4006}40074008GDBRemoteCommunication::PacketResult4009GDBRemoteCommunicationServerLLGS::Handle_vStopped(4010StringExtractorGDBRemote &packet) {4011PacketResult ret = HandleNotificationAck(m_stop_notification_queue);4012// If this was the last notification and all the processes exited,4013// terminate the server.4014if (m_stop_notification_queue.empty() && m_debugged_processes.empty()) {4015m_exit_now = true;4016m_mainloop.RequestTermination();4017}4018return ret;4019}40204021GDBRemoteCommunication::PacketResult4022GDBRemoteCommunicationServerLLGS::Handle_vCtrlC(4023StringExtractorGDBRemote &packet) {4024if (!m_non_stop)4025return SendErrorResponse(Status("vCtrl is only valid in non-stop mode"));40264027PacketResult interrupt_res = Handle_interrupt(packet);4028// If interrupting the process failed, pass the result through.4029if (interrupt_res != PacketResult::Success)4030return interrupt_res;4031// Otherwise, vCtrlC should issue an OK response (normal interrupts do not).4032return SendOKResponse();4033}40344035GDBRemoteCommunication::PacketResult4036GDBRemoteCommunicationServerLLGS::Handle_T(StringExtractorGDBRemote &packet) {4037packet.SetFilePos(strlen("T"));4038auto pid_tid = packet.GetPidTid(m_current_process ? m_current_process->GetID()4039: LLDB_INVALID_PROCESS_ID);4040if (!pid_tid)4041return SendErrorResponse(llvm::make_error<StringError>(4042inconvertibleErrorCode(), "Malformed thread-id"));40434044lldb::pid_t pid = pid_tid->first;4045lldb::tid_t tid = pid_tid->second;40464047// Technically, this would also be caught by the PID check but let's be more4048// explicit about the error.4049if (pid == LLDB_INVALID_PROCESS_ID)4050return SendErrorResponse(llvm::make_error<StringError>(4051inconvertibleErrorCode(), "No current process and no PID provided"));40524053// Check the process ID and find respective process instance.4054auto new_process_it = m_debugged_processes.find(pid);4055if (new_process_it == m_debugged_processes.end())4056return SendErrorResponse(1);40574058// Check the thread ID4059if (!new_process_it->second.process_up->GetThreadByID(tid))4060return SendErrorResponse(2);40614062return SendOKResponse();4063}40644065void GDBRemoteCommunicationServerLLGS::MaybeCloseInferiorTerminalConnection() {4066Log *log = GetLog(LLDBLog::Process);40674068// Tell the stdio connection to shut down.4069if (m_stdio_communication.IsConnected()) {4070auto connection = m_stdio_communication.GetConnection();4071if (connection) {4072Status error;4073connection->Disconnect(&error);40744075if (error.Success()) {4076LLDB_LOGF(log,4077"GDBRemoteCommunicationServerLLGS::%s disconnect process "4078"terminal stdio - SUCCESS",4079__FUNCTION__);4080} else {4081LLDB_LOGF(log,4082"GDBRemoteCommunicationServerLLGS::%s disconnect process "4083"terminal stdio - FAIL: %s",4084__FUNCTION__, error.AsCString());4085}4086}4087}4088}40894090NativeThreadProtocol *GDBRemoteCommunicationServerLLGS::GetThreadFromSuffix(4091StringExtractorGDBRemote &packet) {4092// We have no thread if we don't have a process.4093if (!m_current_process ||4094m_current_process->GetID() == LLDB_INVALID_PROCESS_ID)4095return nullptr;40964097// If the client hasn't asked for thread suffix support, there will not be a4098// thread suffix. Use the current thread in that case.4099if (!m_thread_suffix_supported) {4100const lldb::tid_t current_tid = GetCurrentThreadID();4101if (current_tid == LLDB_INVALID_THREAD_ID)4102return nullptr;4103else if (current_tid == 0) {4104// Pick a thread.4105return m_current_process->GetThreadAtIndex(0);4106} else4107return m_current_process->GetThreadByID(current_tid);4108}41094110Log *log = GetLog(LLDBLog::Thread);41114112// Parse out the ';'.4113if (packet.GetBytesLeft() < 1 || packet.GetChar() != ';') {4114LLDB_LOGF(log,4115"GDBRemoteCommunicationServerLLGS::%s gdb-remote parse "4116"error: expected ';' prior to start of thread suffix: packet "4117"contents = '%s'",4118__FUNCTION__, packet.GetStringRef().data());4119return nullptr;4120}41214122if (!packet.GetBytesLeft())4123return nullptr;41244125// Parse out thread: portion.4126if (strncmp(packet.Peek(), "thread:", strlen("thread:")) != 0) {4127LLDB_LOGF(log,4128"GDBRemoteCommunicationServerLLGS::%s gdb-remote parse "4129"error: expected 'thread:' but not found, packet contents = "4130"'%s'",4131__FUNCTION__, packet.GetStringRef().data());4132return nullptr;4133}4134packet.SetFilePos(packet.GetFilePos() + strlen("thread:"));4135const lldb::tid_t tid = packet.GetHexMaxU64(false, 0);4136if (tid != 0)4137return m_current_process->GetThreadByID(tid);41384139return nullptr;4140}41414142lldb::tid_t GDBRemoteCommunicationServerLLGS::GetCurrentThreadID() const {4143if (m_current_tid == 0 || m_current_tid == LLDB_INVALID_THREAD_ID) {4144// Use whatever the debug process says is the current thread id since the4145// protocol either didn't specify or specified we want any/all threads4146// marked as the current thread.4147if (!m_current_process)4148return LLDB_INVALID_THREAD_ID;4149return m_current_process->GetCurrentThreadID();4150}4151// Use the specific current thread id set by the gdb remote protocol.4152return m_current_tid;4153}41544155uint32_t GDBRemoteCommunicationServerLLGS::GetNextSavedRegistersID() {4156std::lock_guard<std::mutex> guard(m_saved_registers_mutex);4157return m_next_saved_registers_id++;4158}41594160void GDBRemoteCommunicationServerLLGS::ClearProcessSpecificData() {4161Log *log = GetLog(LLDBLog::Process);41624163LLDB_LOG(log, "clearing {0} xfer buffers", m_xfer_buffer_map.size());4164m_xfer_buffer_map.clear();4165}41664167FileSpec4168GDBRemoteCommunicationServerLLGS::FindModuleFile(const std::string &module_path,4169const ArchSpec &arch) {4170if (m_current_process) {4171FileSpec file_spec;4172if (m_current_process4173->GetLoadedModuleFileSpec(module_path.c_str(), file_spec)4174.Success()) {4175if (FileSystem::Instance().Exists(file_spec))4176return file_spec;4177}4178}41794180return GDBRemoteCommunicationServerCommon::FindModuleFile(module_path, arch);4181}41824183std::string GDBRemoteCommunicationServerLLGS::XMLEncodeAttributeValue(4184llvm::StringRef value) {4185std::string result;4186for (const char &c : value) {4187switch (c) {4188case '\'':4189result += "'";4190break;4191case '"':4192result += """;4193break;4194case '<':4195result += "<";4196break;4197case '>':4198result += ">";4199break;4200default:4201result += c;4202break;4203}4204}4205return result;4206}42074208std::vector<std::string> GDBRemoteCommunicationServerLLGS::HandleFeatures(4209const llvm::ArrayRef<llvm::StringRef> client_features) {4210std::vector<std::string> ret =4211GDBRemoteCommunicationServerCommon::HandleFeatures(client_features);4212ret.insert(ret.end(), {4213"QThreadSuffixSupported+",4214"QListThreadsInStopReply+",4215"qXfer:features:read+",4216"QNonStop+",4217});42184219// report server-only features4220using Extension = NativeProcessProtocol::Extension;4221Extension plugin_features = m_process_manager.GetSupportedExtensions();4222if (bool(plugin_features & Extension::pass_signals))4223ret.push_back("QPassSignals+");4224if (bool(plugin_features & Extension::auxv))4225ret.push_back("qXfer:auxv:read+");4226if (bool(plugin_features & Extension::libraries_svr4))4227ret.push_back("qXfer:libraries-svr4:read+");4228if (bool(plugin_features & Extension::siginfo_read))4229ret.push_back("qXfer:siginfo:read+");4230if (bool(plugin_features & Extension::memory_tagging))4231ret.push_back("memory-tagging+");4232if (bool(plugin_features & Extension::savecore))4233ret.push_back("qSaveCore+");42344235// check for client features4236m_extensions_supported = {};4237for (llvm::StringRef x : client_features)4238m_extensions_supported |=4239llvm::StringSwitch<Extension>(x)4240.Case("multiprocess+", Extension::multiprocess)4241.Case("fork-events+", Extension::fork)4242.Case("vfork-events+", Extension::vfork)4243.Default({});42444245m_extensions_supported &= plugin_features;42464247// fork & vfork require multiprocess4248if (!bool(m_extensions_supported & Extension::multiprocess))4249m_extensions_supported &= ~(Extension::fork | Extension::vfork);42504251// report only if actually supported4252if (bool(m_extensions_supported & Extension::multiprocess))4253ret.push_back("multiprocess+");4254if (bool(m_extensions_supported & Extension::fork))4255ret.push_back("fork-events+");4256if (bool(m_extensions_supported & Extension::vfork))4257ret.push_back("vfork-events+");42584259for (auto &x : m_debugged_processes)4260SetEnabledExtensions(*x.second.process_up);4261return ret;4262}42634264void GDBRemoteCommunicationServerLLGS::SetEnabledExtensions(4265NativeProcessProtocol &process) {4266NativeProcessProtocol::Extension flags = m_extensions_supported;4267assert(!bool(flags & ~m_process_manager.GetSupportedExtensions()));4268process.SetEnabledExtensions(flags);4269}42704271GDBRemoteCommunication::PacketResult4272GDBRemoteCommunicationServerLLGS::SendContinueSuccessResponse() {4273if (m_non_stop)4274return SendOKResponse();4275StartSTDIOForwarding();4276return PacketResult::Success;4277}42784279void GDBRemoteCommunicationServerLLGS::AppendThreadIDToResponse(4280Stream &response, lldb::pid_t pid, lldb::tid_t tid) {4281if (bool(m_extensions_supported &4282NativeProcessProtocol::Extension::multiprocess))4283response.Format("p{0:x-}.", pid);4284response.Format("{0:x-}", tid);4285}42864287std::string4288lldb_private::process_gdb_remote::LLGSArgToURL(llvm::StringRef url_arg,4289bool reverse_connect) {4290// Try parsing the argument as URL.4291if (std::optional<URI> url = URI::Parse(url_arg)) {4292if (reverse_connect)4293return url_arg.str();42944295// Translate the scheme from LLGS notation to ConnectionFileDescriptor.4296// If the scheme doesn't match any, pass it through to support using CFD4297// schemes directly.4298std::string new_url = llvm::StringSwitch<std::string>(url->scheme)4299.Case("tcp", "listen")4300.Case("unix", "unix-accept")4301.Case("unix-abstract", "unix-abstract-accept")4302.Default(url->scheme.str());4303llvm::append_range(new_url, url_arg.substr(url->scheme.size()));4304return new_url;4305}43064307std::string host_port = url_arg.str();4308// If host_and_port starts with ':', default the host to be "localhost" and4309// expect the remainder to be the port.4310if (url_arg.starts_with(":"))4311host_port.insert(0, "localhost");43124313// Try parsing the (preprocessed) argument as host:port pair.4314if (!llvm::errorToBool(Socket::DecodeHostAndPort(host_port).takeError()))4315return (reverse_connect ? "connect://" : "listen://") + host_port;43164317// If none of the above applied, interpret the argument as UNIX socket path.4318return (reverse_connect ? "unix-connect://" : "unix-accept://") +4319url_arg.str();4320}432143224323