4420 lines · cpp
1//===-- GDBRemoteCommunicationServerLLGS.cpp ------------------------------===//2//3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.4// See https://llvm.org/LICENSE.txt for license information.5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception6//7//===----------------------------------------------------------------------===//8 9#include <cerrno>10 11#include "lldb/Host/Config.h"12 13#include <chrono>14#include <cstring>15#include <limits>16#include <optional>17#include <thread>18 19#include "GDBRemoteCommunicationServerLLGS.h"20#include "lldb/Host/ConnectionFileDescriptor.h"21#include "lldb/Host/Debug.h"22#include "lldb/Host/File.h"23#include "lldb/Host/FileAction.h"24#include "lldb/Host/FileSystem.h"25#include "lldb/Host/Host.h"26#include "lldb/Host/HostInfo.h"27#include "lldb/Host/PosixApi.h"28#include "lldb/Host/Socket.h"29#include "lldb/Host/common/NativeProcessProtocol.h"30#include "lldb/Host/common/NativeRegisterContext.h"31#include "lldb/Host/common/NativeThreadProtocol.h"32#include "lldb/Target/MemoryRegionInfo.h"33#include "lldb/Utility/Args.h"34#include "lldb/Utility/DataBuffer.h"35#include "lldb/Utility/Endian.h"36#include "lldb/Utility/GDBRemote.h"37#include "lldb/Utility/LLDBAssert.h"38#include "lldb/Utility/LLDBLog.h"39#include "lldb/Utility/Log.h"40#include "lldb/Utility/State.h"41#include "lldb/Utility/StreamString.h"42#include "lldb/Utility/UnimplementedError.h"43#include "lldb/Utility/UriParser.h"44#include "llvm/Support/ErrorHandling.h"45#include "llvm/Support/JSON.h"46#include "llvm/Support/ScopedPrinter.h"47#include "llvm/TargetParser/Triple.h"48 49#include "ProcessGDBRemote.h"50#include "ProcessGDBRemoteLog.h"51#include "lldb/Utility/StringExtractorGDBRemote.h"52 53using namespace lldb;54using namespace lldb_private;55using namespace lldb_private::process_gdb_remote;56using namespace llvm;57 58// GDBRemote Errors59 60namespace {61enum GDBRemoteServerError {62 // Set to the first unused error number in literal form below63 eErrorFirst = 29,64 eErrorNoProcess = eErrorFirst,65 eErrorResume,66 eErrorExitStatus67};68}69 70// GDBRemoteCommunicationServerLLGS constructor71GDBRemoteCommunicationServerLLGS::GDBRemoteCommunicationServerLLGS(72 MainLoop &mainloop, NativeProcessProtocol::Manager &process_manager)73 : GDBRemoteCommunicationServerCommon(), m_mainloop(mainloop),74 m_process_manager(process_manager), m_current_process(nullptr),75 m_continue_process(nullptr), m_stdio_communication() {76 RegisterPacketHandlers();77}78 79void GDBRemoteCommunicationServerLLGS::RegisterPacketHandlers() {80 RegisterMemberFunctionHandler(StringExtractorGDBRemote::eServerPacketType_C,81 &GDBRemoteCommunicationServerLLGS::Handle_C);82 RegisterMemberFunctionHandler(StringExtractorGDBRemote::eServerPacketType_c,83 &GDBRemoteCommunicationServerLLGS::Handle_c);84 RegisterMemberFunctionHandler(StringExtractorGDBRemote::eServerPacketType_D,85 &GDBRemoteCommunicationServerLLGS::Handle_D);86 RegisterMemberFunctionHandler(StringExtractorGDBRemote::eServerPacketType_H,87 &GDBRemoteCommunicationServerLLGS::Handle_H);88 RegisterMemberFunctionHandler(StringExtractorGDBRemote::eServerPacketType_I,89 &GDBRemoteCommunicationServerLLGS::Handle_I);90 RegisterMemberFunctionHandler(91 StringExtractorGDBRemote::eServerPacketType_interrupt,92 &GDBRemoteCommunicationServerLLGS::Handle_interrupt);93 RegisterMemberFunctionHandler(94 StringExtractorGDBRemote::eServerPacketType_m,95 &GDBRemoteCommunicationServerLLGS::Handle_memory_read);96 RegisterMemberFunctionHandler(StringExtractorGDBRemote::eServerPacketType_M,97 &GDBRemoteCommunicationServerLLGS::Handle_M);98 RegisterMemberFunctionHandler(StringExtractorGDBRemote::eServerPacketType__M,99 &GDBRemoteCommunicationServerLLGS::Handle__M);100 RegisterMemberFunctionHandler(StringExtractorGDBRemote::eServerPacketType__m,101 &GDBRemoteCommunicationServerLLGS::Handle__m);102 RegisterMemberFunctionHandler(StringExtractorGDBRemote::eServerPacketType_p,103 &GDBRemoteCommunicationServerLLGS::Handle_p);104 RegisterMemberFunctionHandler(StringExtractorGDBRemote::eServerPacketType_P,105 &GDBRemoteCommunicationServerLLGS::Handle_P);106 RegisterMemberFunctionHandler(StringExtractorGDBRemote::eServerPacketType_qC,107 &GDBRemoteCommunicationServerLLGS::Handle_qC);108 RegisterMemberFunctionHandler(StringExtractorGDBRemote::eServerPacketType_T,109 &GDBRemoteCommunicationServerLLGS::Handle_T);110 RegisterMemberFunctionHandler(111 StringExtractorGDBRemote::eServerPacketType_qfThreadInfo,112 &GDBRemoteCommunicationServerLLGS::Handle_qfThreadInfo);113 RegisterMemberFunctionHandler(114 StringExtractorGDBRemote::eServerPacketType_qFileLoadAddress,115 &GDBRemoteCommunicationServerLLGS::Handle_qFileLoadAddress);116 RegisterMemberFunctionHandler(117 StringExtractorGDBRemote::eServerPacketType_qGetWorkingDir,118 &GDBRemoteCommunicationServerLLGS::Handle_qGetWorkingDir);119 RegisterMemberFunctionHandler(120 StringExtractorGDBRemote::eServerPacketType_QThreadSuffixSupported,121 &GDBRemoteCommunicationServerLLGS::Handle_QThreadSuffixSupported);122 RegisterMemberFunctionHandler(123 StringExtractorGDBRemote::eServerPacketType_QListThreadsInStopReply,124 &GDBRemoteCommunicationServerLLGS::Handle_QListThreadsInStopReply);125 RegisterMemberFunctionHandler(126 StringExtractorGDBRemote::eServerPacketType_qMemoryRegionInfo,127 &GDBRemoteCommunicationServerLLGS::Handle_qMemoryRegionInfo);128 RegisterMemberFunctionHandler(129 StringExtractorGDBRemote::eServerPacketType_qMemoryRegionInfoSupported,130 &GDBRemoteCommunicationServerLLGS::Handle_qMemoryRegionInfoSupported);131 RegisterMemberFunctionHandler(132 StringExtractorGDBRemote::eServerPacketType_qProcessInfo,133 &GDBRemoteCommunicationServerLLGS::Handle_qProcessInfo);134 RegisterMemberFunctionHandler(135 StringExtractorGDBRemote::eServerPacketType_qRegisterInfo,136 &GDBRemoteCommunicationServerLLGS::Handle_qRegisterInfo);137 RegisterMemberFunctionHandler(138 StringExtractorGDBRemote::eServerPacketType_QRestoreRegisterState,139 &GDBRemoteCommunicationServerLLGS::Handle_QRestoreRegisterState);140 RegisterMemberFunctionHandler(141 StringExtractorGDBRemote::eServerPacketType_QSaveRegisterState,142 &GDBRemoteCommunicationServerLLGS::Handle_QSaveRegisterState);143 RegisterMemberFunctionHandler(144 StringExtractorGDBRemote::eServerPacketType_QSetDisableASLR,145 &GDBRemoteCommunicationServerLLGS::Handle_QSetDisableASLR);146 RegisterMemberFunctionHandler(147 StringExtractorGDBRemote::eServerPacketType_QSetWorkingDir,148 &GDBRemoteCommunicationServerLLGS::Handle_QSetWorkingDir);149 RegisterMemberFunctionHandler(150 StringExtractorGDBRemote::eServerPacketType_qStructuredDataPlugins,151 &GDBRemoteCommunicationServerLLGS::Handle_qStructuredDataPlugins);152 RegisterMemberFunctionHandler(153 StringExtractorGDBRemote::eServerPacketType_qsThreadInfo,154 &GDBRemoteCommunicationServerLLGS::Handle_qsThreadInfo);155 RegisterMemberFunctionHandler(156 StringExtractorGDBRemote::eServerPacketType_qThreadStopInfo,157 &GDBRemoteCommunicationServerLLGS::Handle_qThreadStopInfo);158 RegisterMemberFunctionHandler(159 StringExtractorGDBRemote::eServerPacketType_jThreadsInfo,160 &GDBRemoteCommunicationServerLLGS::Handle_jThreadsInfo);161 RegisterMemberFunctionHandler(162 StringExtractorGDBRemote::eServerPacketType_qWatchpointSupportInfo,163 &GDBRemoteCommunicationServerLLGS::Handle_qWatchpointSupportInfo);164 RegisterMemberFunctionHandler(165 StringExtractorGDBRemote::eServerPacketType_qXfer,166 &GDBRemoteCommunicationServerLLGS::Handle_qXfer);167 RegisterMemberFunctionHandler(StringExtractorGDBRemote::eServerPacketType_s,168 &GDBRemoteCommunicationServerLLGS::Handle_s);169 RegisterMemberFunctionHandler(170 StringExtractorGDBRemote::eServerPacketType_stop_reason,171 &GDBRemoteCommunicationServerLLGS::Handle_stop_reason); // ?172 RegisterMemberFunctionHandler(173 StringExtractorGDBRemote::eServerPacketType_vAttach,174 &GDBRemoteCommunicationServerLLGS::Handle_vAttach);175 RegisterMemberFunctionHandler(176 StringExtractorGDBRemote::eServerPacketType_vAttachWait,177 &GDBRemoteCommunicationServerLLGS::Handle_vAttachWait);178 RegisterMemberFunctionHandler(179 StringExtractorGDBRemote::eServerPacketType_qVAttachOrWaitSupported,180 &GDBRemoteCommunicationServerLLGS::Handle_qVAttachOrWaitSupported);181 RegisterMemberFunctionHandler(182 StringExtractorGDBRemote::eServerPacketType_vAttachOrWait,183 &GDBRemoteCommunicationServerLLGS::Handle_vAttachOrWait);184 RegisterMemberFunctionHandler(185 StringExtractorGDBRemote::eServerPacketType_vCont,186 &GDBRemoteCommunicationServerLLGS::Handle_vCont);187 RegisterMemberFunctionHandler(188 StringExtractorGDBRemote::eServerPacketType_vCont_actions,189 &GDBRemoteCommunicationServerLLGS::Handle_vCont_actions);190 RegisterMemberFunctionHandler(191 StringExtractorGDBRemote::eServerPacketType_vRun,192 &GDBRemoteCommunicationServerLLGS::Handle_vRun);193 RegisterMemberFunctionHandler(194 StringExtractorGDBRemote::eServerPacketType_x,195 &GDBRemoteCommunicationServerLLGS::Handle_memory_read);196 RegisterMemberFunctionHandler(StringExtractorGDBRemote::eServerPacketType_Z,197 &GDBRemoteCommunicationServerLLGS::Handle_Z);198 RegisterMemberFunctionHandler(StringExtractorGDBRemote::eServerPacketType_z,199 &GDBRemoteCommunicationServerLLGS::Handle_z);200 RegisterMemberFunctionHandler(201 StringExtractorGDBRemote::eServerPacketType_QPassSignals,202 &GDBRemoteCommunicationServerLLGS::Handle_QPassSignals);203 204 RegisterMemberFunctionHandler(205 StringExtractorGDBRemote::eServerPacketType_jLLDBTraceSupported,206 &GDBRemoteCommunicationServerLLGS::Handle_jLLDBTraceSupported);207 RegisterMemberFunctionHandler(208 StringExtractorGDBRemote::eServerPacketType_jLLDBTraceStart,209 &GDBRemoteCommunicationServerLLGS::Handle_jLLDBTraceStart);210 RegisterMemberFunctionHandler(211 StringExtractorGDBRemote::eServerPacketType_jLLDBTraceStop,212 &GDBRemoteCommunicationServerLLGS::Handle_jLLDBTraceStop);213 RegisterMemberFunctionHandler(214 StringExtractorGDBRemote::eServerPacketType_jLLDBTraceGetState,215 &GDBRemoteCommunicationServerLLGS::Handle_jLLDBTraceGetState);216 RegisterMemberFunctionHandler(217 StringExtractorGDBRemote::eServerPacketType_jLLDBTraceGetBinaryData,218 &GDBRemoteCommunicationServerLLGS::Handle_jLLDBTraceGetBinaryData);219 220 RegisterMemberFunctionHandler(StringExtractorGDBRemote::eServerPacketType_g,221 &GDBRemoteCommunicationServerLLGS::Handle_g);222 223 RegisterMemberFunctionHandler(224 StringExtractorGDBRemote::eServerPacketType_qMemTags,225 &GDBRemoteCommunicationServerLLGS::Handle_qMemTags);226 227 RegisterMemberFunctionHandler(228 StringExtractorGDBRemote::eServerPacketType_QMemTags,229 &GDBRemoteCommunicationServerLLGS::Handle_QMemTags);230 231 RegisterPacketHandler(StringExtractorGDBRemote::eServerPacketType_k,232 [this](StringExtractorGDBRemote packet, Status &error,233 bool &interrupt, bool &quit) {234 quit = true;235 return this->Handle_k(packet);236 });237 238 RegisterMemberFunctionHandler(239 StringExtractorGDBRemote::eServerPacketType_vKill,240 &GDBRemoteCommunicationServerLLGS::Handle_vKill);241 242 RegisterMemberFunctionHandler(243 StringExtractorGDBRemote::eServerPacketType_qLLDBSaveCore,244 &GDBRemoteCommunicationServerLLGS::Handle_qSaveCore);245 246 RegisterMemberFunctionHandler(247 StringExtractorGDBRemote::eServerPacketType_QNonStop,248 &GDBRemoteCommunicationServerLLGS::Handle_QNonStop);249 RegisterMemberFunctionHandler(250 StringExtractorGDBRemote::eServerPacketType_vStdio,251 &GDBRemoteCommunicationServerLLGS::Handle_vStdio);252 RegisterMemberFunctionHandler(253 StringExtractorGDBRemote::eServerPacketType_vStopped,254 &GDBRemoteCommunicationServerLLGS::Handle_vStopped);255 RegisterMemberFunctionHandler(256 StringExtractorGDBRemote::eServerPacketType_vCtrlC,257 &GDBRemoteCommunicationServerLLGS::Handle_vCtrlC);258}259 260void GDBRemoteCommunicationServerLLGS::SetLaunchInfo(const ProcessLaunchInfo &info) {261 m_process_launch_info = info;262}263 264Status GDBRemoteCommunicationServerLLGS::LaunchProcess() {265 Log *log = GetLog(LLDBLog::Process);266 267 if (!m_process_launch_info.GetArguments().GetArgumentCount())268 return Status::FromErrorStringWithFormat(269 "%s: no process command line specified to launch", __FUNCTION__);270 271 const bool should_forward_stdio =272 m_process_launch_info.GetFileActionForFD(STDIN_FILENO) == nullptr ||273 m_process_launch_info.GetFileActionForFD(STDOUT_FILENO) == nullptr ||274 m_process_launch_info.GetFileActionForFD(STDERR_FILENO) == nullptr;275 m_process_launch_info.SetLaunchInSeparateProcessGroup(true);276 m_process_launch_info.GetFlags().Set(eLaunchFlagDebug);277 278 if (should_forward_stdio) {279 // Temporarily relax the following for Windows until we can take advantage280 // of the recently added pty support. This doesn't really affect the use of281 // lldb-server on Windows.282#if !defined(_WIN32)283 if (llvm::Error Err = m_process_launch_info.SetUpPtyRedirection())284 return Status::FromError(std::move(Err));285#endif286 }287 288 {289 std::lock_guard<std::recursive_mutex> guard(m_debugged_process_mutex);290 assert(m_debugged_processes.empty() && "lldb-server creating debugged "291 "process but one already exists");292 auto process_or = m_process_manager.Launch(m_process_launch_info, *this);293 if (!process_or)294 return Status::FromError(process_or.takeError());295 m_continue_process = m_current_process = process_or->get();296 m_debugged_processes.emplace(297 m_current_process->GetID(),298 DebuggedProcess{std::move(*process_or), DebuggedProcess::Flag{}});299 }300 301 SetEnabledExtensions(*m_current_process);302 303 // Handle mirroring of inferior stdout/stderr over the gdb-remote protocol as304 // needed. llgs local-process debugging may specify PTY paths, which will305 // make these file actions non-null process launch -i/e/o will also make306 // these file actions non-null nullptr means that the traffic is expected to307 // flow over gdb-remote protocol308 if (should_forward_stdio) {309 // nullptr means it's not redirected to file or pty (in case of LLGS local)310 // at least one of stdio will be transferred pty<->gdb-remote we need to311 // give the pty primary handle to this object to read and/or write312 LLDB_LOG(log,313 "pid = {0}: setting up stdout/stderr redirection via $O "314 "gdb-remote commands",315 m_current_process->GetID());316 317 // Setup stdout/stderr mapping from inferior to $O318 auto terminal_fd = m_current_process->GetTerminalFileDescriptor();319 if (terminal_fd >= 0) {320 LLDB_LOGF(log,321 "ProcessGDBRemoteCommunicationServerLLGS::%s setting "322 "inferior STDIO fd to %d",323 __FUNCTION__, terminal_fd);324 Status status = SetSTDIOFileDescriptor(terminal_fd);325 if (status.Fail())326 return status;327 } else {328 LLDB_LOGF(log,329 "ProcessGDBRemoteCommunicationServerLLGS::%s ignoring "330 "inferior STDIO since terminal fd reported as %d",331 __FUNCTION__, terminal_fd);332 }333 } else {334 LLDB_LOG(log,335 "pid = {0} skipping stdout/stderr redirection via $O: inferior "336 "will communicate over client-provided file descriptors",337 m_current_process->GetID());338 }339 340 printf("Launched '%s' as process %" PRIu64 "...\n",341 m_process_launch_info.GetArguments().GetArgumentAtIndex(0),342 m_current_process->GetID());343 344 return Status();345}346 347Status GDBRemoteCommunicationServerLLGS::AttachToProcess(lldb::pid_t pid) {348 Log *log = GetLog(LLDBLog::Process);349 LLDB_LOGF(log, "GDBRemoteCommunicationServerLLGS::%s pid %" PRIu64,350 __FUNCTION__, pid);351 352 // Before we try to attach, make sure we aren't already monitoring something353 // else.354 if (!m_debugged_processes.empty())355 return Status::FromErrorStringWithFormat(356 "cannot attach to process %" PRIu64357 " when another process with pid %" PRIu64 " is being debugged.",358 pid, m_current_process->GetID());359 360 // Try to attach.361 auto process_or = m_process_manager.Attach(pid, *this);362 if (!process_or) {363 Status status = Status::FromError(process_or.takeError());364 llvm::errs() << llvm::formatv("failed to attach to process {0}: {1}\n", pid,365 status);366 return status;367 }368 m_continue_process = m_current_process = process_or->get();369 m_debugged_processes.emplace(370 m_current_process->GetID(),371 DebuggedProcess{std::move(*process_or), DebuggedProcess::Flag{}});372 SetEnabledExtensions(*m_current_process);373 374 // Setup stdout/stderr mapping from inferior.375 auto terminal_fd = m_current_process->GetTerminalFileDescriptor();376 if (terminal_fd >= 0) {377 LLDB_LOGF(log,378 "ProcessGDBRemoteCommunicationServerLLGS::%s setting "379 "inferior STDIO fd to %d",380 __FUNCTION__, terminal_fd);381 Status status = SetSTDIOFileDescriptor(terminal_fd);382 if (status.Fail())383 return status;384 } else {385 LLDB_LOGF(log,386 "ProcessGDBRemoteCommunicationServerLLGS::%s ignoring "387 "inferior STDIO since terminal fd reported as %d",388 __FUNCTION__, terminal_fd);389 }390 391 printf("Attached to process %" PRIu64 "...\n", pid);392 return Status();393}394 395Status GDBRemoteCommunicationServerLLGS::AttachWaitProcess(396 llvm::StringRef process_name, bool include_existing) {397 Log *log = GetLog(LLDBLog::Process);398 399 std::chrono::milliseconds polling_interval = std::chrono::milliseconds(1);400 401 // Create the matcher used to search the process list.402 ProcessInstanceInfoList exclusion_list;403 ProcessInstanceInfoMatch match_info;404 match_info.GetProcessInfo().GetExecutableFile().SetFile(405 process_name, llvm::sys::path::Style::native);406 match_info.SetNameMatchType(NameMatch::Equals);407 408 if (include_existing) {409 LLDB_LOG(log, "including existing processes in search");410 } else {411 // Create the excluded process list before polling begins.412 Host::FindProcesses(match_info, exclusion_list);413 LLDB_LOG(log, "placed '{0}' processes in the exclusion list.",414 exclusion_list.size());415 }416 417 LLDB_LOG(log, "waiting for '{0}' to appear", process_name);418 419 auto is_in_exclusion_list =420 [&exclusion_list](const ProcessInstanceInfo &info) {421 for (auto &excluded : exclusion_list) {422 if (excluded.GetProcessID() == info.GetProcessID())423 return true;424 }425 return false;426 };427 428 ProcessInstanceInfoList loop_process_list;429 while (true) {430 loop_process_list.clear();431 if (Host::FindProcesses(match_info, loop_process_list)) {432 // Remove all the elements that are in the exclusion list.433 llvm::erase_if(loop_process_list, is_in_exclusion_list);434 435 // One match! We found the desired process.436 if (loop_process_list.size() == 1) {437 auto matching_process_pid = loop_process_list[0].GetProcessID();438 LLDB_LOG(log, "found pid {0}", matching_process_pid);439 return AttachToProcess(matching_process_pid);440 }441 442 // Multiple matches! Return an error reporting the PIDs we found.443 if (loop_process_list.size() > 1) {444 StreamString error_stream;445 error_stream.Format(446 "Multiple executables with name: '{0}' found. Pids: ",447 process_name);448 for (size_t i = 0; i < loop_process_list.size() - 1; ++i) {449 error_stream.Format("{0}, ", loop_process_list[i].GetProcessID());450 }451 error_stream.Format("{0}.", loop_process_list.back().GetProcessID());452 453 Status error;454 error = Status(error_stream.GetString().str());455 return error;456 }457 }458 // No matches, we have not found the process. Sleep until next poll.459 LLDB_LOG(log, "sleep {0} seconds", polling_interval);460 std::this_thread::sleep_for(polling_interval);461 }462}463 464void GDBRemoteCommunicationServerLLGS::InitializeDelegate(465 NativeProcessProtocol *process) {466 assert(process && "process cannot be NULL");467 Log *log = GetLog(LLDBLog::Process);468 if (log) {469 LLDB_LOGF(log,470 "GDBRemoteCommunicationServerLLGS::%s called with "471 "NativeProcessProtocol pid %" PRIu64 ", current state: %s",472 __FUNCTION__, process->GetID(),473 StateAsCString(process->GetState()));474 }475}476 477GDBRemoteCommunication::PacketResult478GDBRemoteCommunicationServerLLGS::SendWResponse(479 NativeProcessProtocol *process) {480 assert(process && "process cannot be NULL");481 Log *log = GetLog(LLDBLog::Process);482 483 // send W notification484 auto wait_status = process->GetExitStatus();485 if (!wait_status) {486 LLDB_LOG(log, "pid = {0}, failed to retrieve process exit status",487 process->GetID());488 489 StreamGDBRemote response;490 response.PutChar('E');491 response.PutHex8(GDBRemoteServerError::eErrorExitStatus);492 return SendPacketNoLock(response.GetString());493 }494 495 LLDB_LOG(log, "pid = {0}, returning exit type {1}", process->GetID(),496 *wait_status);497 498 // If the process was killed through vKill, return "OK".499 if (bool(m_debugged_processes.at(process->GetID()).flags &500 DebuggedProcess::Flag::vkilled))501 return SendOKResponse();502 503 StreamGDBRemote response;504 response.Format("{0:g}", *wait_status);505 if (bool(m_extensions_supported &506 NativeProcessProtocol::Extension::multiprocess))507 response.Format(";process:{0:x-}", process->GetID());508 if (m_non_stop)509 return SendNotificationPacketNoLock("Stop", m_stop_notification_queue,510 response.GetString());511 return SendPacketNoLock(response.GetString());512}513 514static void AppendHexValue(StreamString &response, const uint8_t *buf,515 uint32_t buf_size, bool swap) {516 int64_t i;517 if (swap) {518 for (i = buf_size - 1; i >= 0; i--)519 response.PutHex8(buf[i]);520 } else {521 for (i = 0; i < buf_size; i++)522 response.PutHex8(buf[i]);523 }524}525 526static llvm::StringRef GetEncodingNameOrEmpty(const RegisterInfo ®_info) {527 switch (reg_info.encoding) {528 case eEncodingUint:529 return "uint";530 case eEncodingSint:531 return "sint";532 case eEncodingIEEE754:533 return "ieee754";534 case eEncodingVector:535 return "vector";536 default:537 return "";538 }539}540 541static llvm::StringRef GetFormatNameOrEmpty(const RegisterInfo ®_info) {542 switch (reg_info.format) {543 case eFormatDefault:544 return "";545 case eFormatBoolean:546 return "boolean";547 case eFormatBinary:548 return "binary";549 case eFormatBytes:550 return "bytes";551 case eFormatBytesWithASCII:552 return "bytes-with-ascii";553 case eFormatChar:554 return "char";555 case eFormatCharPrintable:556 return "char-printable";557 case eFormatComplex:558 return "complex";559 case eFormatCString:560 return "cstring";561 case eFormatDecimal:562 return "decimal";563 case eFormatEnum:564 return "enum";565 case eFormatHex:566 return "hex";567 case eFormatHexUppercase:568 return "hex-uppercase";569 case eFormatFloat:570 return "float";571 case eFormatOctal:572 return "octal";573 case eFormatOSType:574 return "ostype";575 case eFormatUnicode16:576 return "unicode16";577 case eFormatUnicode32:578 return "unicode32";579 case eFormatUnsigned:580 return "unsigned";581 case eFormatPointer:582 return "pointer";583 case eFormatVectorOfChar:584 return "vector-char";585 case eFormatVectorOfSInt64:586 return "vector-sint64";587 case eFormatVectorOfFloat16:588 return "vector-float16";589 case eFormatVectorOfFloat64:590 return "vector-float64";591 case eFormatVectorOfSInt8:592 return "vector-sint8";593 case eFormatVectorOfUInt8:594 return "vector-uint8";595 case eFormatVectorOfSInt16:596 return "vector-sint16";597 case eFormatVectorOfUInt16:598 return "vector-uint16";599 case eFormatVectorOfSInt32:600 return "vector-sint32";601 case eFormatVectorOfUInt32:602 return "vector-uint32";603 case eFormatVectorOfFloat32:604 return "vector-float32";605 case eFormatVectorOfUInt64:606 return "vector-uint64";607 case eFormatVectorOfUInt128:608 return "vector-uint128";609 case eFormatComplexInteger:610 return "complex-integer";611 case eFormatCharArray:612 return "char-array";613 case eFormatAddressInfo:614 return "address-info";615 case eFormatHexFloat:616 return "hex-float";617 case eFormatInstruction:618 return "instruction";619 case eFormatVoid:620 return "void";621 case eFormatUnicode8:622 return "unicode8";623 case eFormatFloat128:624 return "float128";625 default:626 llvm_unreachable("Unknown register format");627 };628}629 630static llvm::StringRef GetKindGenericOrEmpty(const RegisterInfo ®_info) {631 switch (reg_info.kinds[RegisterKind::eRegisterKindGeneric]) {632 case LLDB_REGNUM_GENERIC_PC:633 return "pc";634 case LLDB_REGNUM_GENERIC_SP:635 return "sp";636 case LLDB_REGNUM_GENERIC_FP:637 return "fp";638 case LLDB_REGNUM_GENERIC_RA:639 return "ra";640 case LLDB_REGNUM_GENERIC_FLAGS:641 return "flags";642 case LLDB_REGNUM_GENERIC_ARG1:643 return "arg1";644 case LLDB_REGNUM_GENERIC_ARG2:645 return "arg2";646 case LLDB_REGNUM_GENERIC_ARG3:647 return "arg3";648 case LLDB_REGNUM_GENERIC_ARG4:649 return "arg4";650 case LLDB_REGNUM_GENERIC_ARG5:651 return "arg5";652 case LLDB_REGNUM_GENERIC_ARG6:653 return "arg6";654 case LLDB_REGNUM_GENERIC_ARG7:655 return "arg7";656 case LLDB_REGNUM_GENERIC_ARG8:657 return "arg8";658 case LLDB_REGNUM_GENERIC_TP:659 return "tp";660 default:661 return "";662 }663}664 665static void CollectRegNums(const uint32_t *reg_num, StreamString &response,666 bool usehex) {667 for (int i = 0; *reg_num != LLDB_INVALID_REGNUM; ++reg_num, ++i) {668 if (i > 0)669 response.PutChar(',');670 if (usehex)671 response.Printf("%" PRIx32, *reg_num);672 else673 response.Printf("%" PRIu32, *reg_num);674 }675}676 677static void WriteRegisterValueInHexFixedWidth(678 StreamString &response, NativeRegisterContext ®_ctx,679 const RegisterInfo ®_info, const RegisterValue *reg_value_p,680 lldb::ByteOrder byte_order) {681 RegisterValue reg_value;682 if (!reg_value_p) {683 Status error = reg_ctx.ReadRegister(®_info, reg_value);684 if (error.Success())685 reg_value_p = ®_value;686 // else log.687 }688 689 if (reg_value_p) {690 AppendHexValue(response, (const uint8_t *)reg_value_p->GetBytes(),691 reg_value_p->GetByteSize(),692 byte_order == lldb::eByteOrderLittle);693 } else {694 // Zero-out any unreadable values.695 if (reg_info.byte_size > 0) {696 std::vector<uint8_t> zeros(reg_info.byte_size, '\0');697 AppendHexValue(response, zeros.data(), zeros.size(), false);698 }699 }700}701 702static std::optional<json::Object>703GetRegistersAsJSON(NativeThreadProtocol &thread) {704 Log *log = GetLog(LLDBLog::Thread);705 706 NativeRegisterContext& reg_ctx = thread.GetRegisterContext();707 708 json::Object register_object;709 710#ifdef LLDB_JTHREADSINFO_FULL_REGISTER_SET711 const auto expedited_regs =712 reg_ctx.GetExpeditedRegisters(ExpeditedRegs::Full);713#else714 const auto expedited_regs =715 reg_ctx.GetExpeditedRegisters(ExpeditedRegs::Minimal);716#endif717 if (expedited_regs.empty())718 return std::nullopt;719 720 for (auto ®_num : expedited_regs) {721 const RegisterInfo *const reg_info_p =722 reg_ctx.GetRegisterInfoAtIndex(reg_num);723 if (reg_info_p == nullptr) {724 LLDB_LOGF(log,725 "%s failed to get register info for register index %" PRIu32,726 __FUNCTION__, reg_num);727 continue;728 }729 730 if (reg_info_p->value_regs != nullptr)731 continue; // Only expedite registers that are not contained in other732 // registers.733 734 RegisterValue reg_value;735 Status error = reg_ctx.ReadRegister(reg_info_p, reg_value);736 if (error.Fail()) {737 LLDB_LOGF(log, "%s failed to read register '%s' index %" PRIu32 ": %s",738 __FUNCTION__,739 reg_info_p->name ? reg_info_p->name : "<unnamed-register>",740 reg_num, error.AsCString());741 continue;742 }743 744 StreamString stream;745 WriteRegisterValueInHexFixedWidth(stream, reg_ctx, *reg_info_p,746 ®_value, lldb::eByteOrderBig);747 748 register_object.try_emplace(llvm::to_string(reg_num),749 stream.GetString().str());750 }751 752 return register_object;753}754 755static const char *GetStopReasonString(StopReason stop_reason) {756 switch (stop_reason) {757 case eStopReasonTrace:758 return "trace";759 case eStopReasonBreakpoint:760 return "breakpoint";761 case eStopReasonWatchpoint:762 return "watchpoint";763 case eStopReasonSignal:764 return "signal";765 case eStopReasonException:766 return "exception";767 case eStopReasonExec:768 return "exec";769 case eStopReasonProcessorTrace:770 return "processor trace";771 case eStopReasonFork:772 return "fork";773 case eStopReasonVFork:774 return "vfork";775 case eStopReasonVForkDone:776 return "vforkdone";777 case eStopReasonInterrupt:778 return "async interrupt";779 case eStopReasonHistoryBoundary:780 case eStopReasonInstrumentation:781 case eStopReasonInvalid:782 case eStopReasonPlanComplete:783 case eStopReasonThreadExiting:784 case eStopReasonNone:785 break; // ignored786 }787 return nullptr;788}789 790static llvm::Expected<json::Array>791GetJSONThreadsInfo(NativeProcessProtocol &process, bool abridged) {792 Log *log = GetLog(LLDBLog::Process | LLDBLog::Thread);793 794 json::Array threads_array;795 796 // Ensure we can get info on the given thread.797 for (NativeThreadProtocol &thread : process.Threads()) {798 lldb::tid_t tid = thread.GetID();799 // Grab the reason this thread stopped.800 struct ThreadStopInfo tid_stop_info;801 std::string description;802 if (!thread.GetStopReason(tid_stop_info, description))803 return llvm::make_error<llvm::StringError>(804 "failed to get stop reason", llvm::inconvertibleErrorCode());805 806 const int signum = tid_stop_info.signo;807 if (log) {808 LLDB_LOGF(log,809 "GDBRemoteCommunicationServerLLGS::%s pid %" PRIu64810 " tid %" PRIu64811 " got signal signo = %d, reason = %d, exc_type = %" PRIu64,812 __FUNCTION__, process.GetID(), tid, signum,813 tid_stop_info.reason, tid_stop_info.details.exception.type);814 }815 816 json::Object thread_obj;817 818 if (!abridged) {819 if (std::optional<json::Object> registers = GetRegistersAsJSON(thread))820 thread_obj.try_emplace("registers", std::move(*registers));821 }822 823 thread_obj.try_emplace("tid", static_cast<int64_t>(tid));824 825 if (signum != 0)826 thread_obj.try_emplace("signal", signum);827 828 const std::string thread_name = thread.GetName();829 if (!thread_name.empty())830 thread_obj.try_emplace("name", thread_name);831 832 const char *stop_reason = GetStopReasonString(tid_stop_info.reason);833 if (stop_reason)834 thread_obj.try_emplace("reason", stop_reason);835 836 if (!description.empty())837 thread_obj.try_emplace("description", description);838 839 if ((tid_stop_info.reason == eStopReasonException) &&840 tid_stop_info.details.exception.type) {841 thread_obj.try_emplace(842 "metype", static_cast<int64_t>(tid_stop_info.details.exception.type));843 844 json::Array medata_array;845 for (uint32_t i = 0; i < tid_stop_info.details.exception.data_count;846 ++i) {847 medata_array.push_back(848 static_cast<int64_t>(tid_stop_info.details.exception.data[i]));849 }850 thread_obj.try_emplace("medata", std::move(medata_array));851 }852 threads_array.push_back(std::move(thread_obj));853 }854 return threads_array;855}856 857StreamString858GDBRemoteCommunicationServerLLGS::PrepareStopReplyPacketForThread(859 NativeThreadProtocol &thread) {860 Log *log = GetLog(LLDBLog::Process | LLDBLog::Thread);861 862 NativeProcessProtocol &process = thread.GetProcess();863 864 LLDB_LOG(log, "preparing packet for pid {0} tid {1}", process.GetID(),865 thread.GetID());866 867 // Grab the reason this thread stopped.868 StreamString response;869 struct ThreadStopInfo tid_stop_info;870 std::string description;871 if (!thread.GetStopReason(tid_stop_info, description))872 return response;873 874 // FIXME implement register handling for exec'd inferiors.875 // if (tid_stop_info.reason == eStopReasonExec) {876 // const bool force = true;877 // InitializeRegisters(force);878 // }879 880 // Output the T packet with the thread881 response.PutChar('T');882 int signum = tid_stop_info.signo;883 LLDB_LOG(884 log,885 "pid {0}, tid {1}, got signal signo = {2}, reason = {3}, exc_type = {4}",886 process.GetID(), thread.GetID(), signum, int(tid_stop_info.reason),887 tid_stop_info.details.exception.type);888 889 // Print the signal number.890 response.PutHex8(signum & 0xff);891 892 // Include the (pid and) tid.893 response.PutCString("thread:");894 AppendThreadIDToResponse(response, process.GetID(), thread.GetID());895 response.PutChar(';');896 897 // Include the thread name if there is one.898 const std::string thread_name = thread.GetName();899 if (!thread_name.empty()) {900 size_t thread_name_len = thread_name.length();901 902 if (::strcspn(thread_name.c_str(), "$#+-;:") == thread_name_len) {903 response.PutCString("name:");904 response.PutCString(thread_name);905 } else {906 // The thread name contains special chars, send as hex bytes.907 response.PutCString("hexname:");908 response.PutStringAsRawHex8(thread_name);909 }910 response.PutChar(';');911 }912 913 // If a 'QListThreadsInStopReply' was sent to enable this feature, we will914 // send all thread IDs back in the "threads" key whose value is a list of hex915 // thread IDs separated by commas:916 // "threads:10a,10b,10c;"917 // This will save the debugger from having to send a pair of qfThreadInfo and918 // qsThreadInfo packets, but it also might take a lot of room in the stop919 // reply packet, so it must be enabled only on systems where there are no920 // limits on packet lengths.921 if (m_list_threads_in_stop_reply) {922 response.PutCString("threads:");923 924 uint32_t thread_num = 0;925 for (NativeThreadProtocol &listed_thread : process.Threads()) {926 if (thread_num > 0)927 response.PutChar(',');928 response.Printf("%" PRIx64, listed_thread.GetID());929 ++thread_num;930 }931 response.PutChar(';');932 933 // Include JSON info that describes the stop reason for any threads that934 // actually have stop reasons. We use the new "jstopinfo" key whose values935 // is hex ascii JSON that contains the thread IDs thread stop info only for936 // threads that have stop reasons. Only send this if we have more than one937 // thread otherwise this packet has all the info it needs.938 if (thread_num > 1) {939 const bool threads_with_valid_stop_info_only = true;940 llvm::Expected<json::Array> threads_info = GetJSONThreadsInfo(941 *m_current_process, threads_with_valid_stop_info_only);942 if (threads_info) {943 response.PutCString("jstopinfo:");944 StreamString unescaped_response;945 unescaped_response.AsRawOstream() << std::move(*threads_info);946 response.PutStringAsRawHex8(unescaped_response.GetData());947 response.PutChar(';');948 } else {949 LLDB_LOG_ERROR(log, threads_info.takeError(),950 "failed to prepare a jstopinfo field for pid {1}: {0}",951 process.GetID());952 }953 }954 955 response.PutCString("thread-pcs");956 char delimiter = ':';957 for (NativeThreadProtocol &thread : process.Threads()) {958 NativeRegisterContext ®_ctx = thread.GetRegisterContext();959 960 uint32_t reg_to_read = reg_ctx.ConvertRegisterKindToRegisterNumber(961 eRegisterKindGeneric, LLDB_REGNUM_GENERIC_PC);962 const RegisterInfo *const reg_info_p =963 reg_ctx.GetRegisterInfoAtIndex(reg_to_read);964 965 RegisterValue reg_value;966 Status error = reg_ctx.ReadRegister(reg_info_p, reg_value);967 if (error.Fail()) {968 LLDB_LOGF(log, "%s failed to read register '%s' index %" PRIu32 ": %s",969 __FUNCTION__,970 reg_info_p->name ? reg_info_p->name : "<unnamed-register>",971 reg_to_read, error.AsCString());972 continue;973 }974 975 response.PutChar(delimiter);976 delimiter = ',';977 WriteRegisterValueInHexFixedWidth(response, reg_ctx, *reg_info_p,978 ®_value, endian::InlHostByteOrder());979 }980 981 response.PutChar(';');982 }983 984 //985 // Expedite registers.986 //987 988 // Grab the register context.989 NativeRegisterContext ®_ctx = thread.GetRegisterContext();990 const auto expedited_regs =991 reg_ctx.GetExpeditedRegisters(ExpeditedRegs::Full);992 993 for (auto ®_num : expedited_regs) {994 const RegisterInfo *const reg_info_p =995 reg_ctx.GetRegisterInfoAtIndex(reg_num);996 // Only expediate registers that are not contained in other registers.997 if (reg_info_p != nullptr && reg_info_p->value_regs == nullptr) {998 RegisterValue reg_value;999 Status error = reg_ctx.ReadRegister(reg_info_p, reg_value);1000 if (error.Success()) {1001 response.Printf("%.02x:", reg_num);1002 WriteRegisterValueInHexFixedWidth(response, reg_ctx, *reg_info_p,1003 ®_value, lldb::eByteOrderBig);1004 response.PutChar(';');1005 } else {1006 LLDB_LOGF(log,1007 "GDBRemoteCommunicationServerLLGS::%s failed to read "1008 "register '%s' index %" PRIu32 ": %s",1009 __FUNCTION__,1010 reg_info_p->name ? reg_info_p->name : "<unnamed-register>",1011 reg_num, error.AsCString());1012 }1013 }1014 }1015 1016 const char *reason_str = GetStopReasonString(tid_stop_info.reason);1017 if (reason_str != nullptr) {1018 response.Printf("reason:%s;", reason_str);1019 }1020 1021 if (!description.empty()) {1022 // Description may contains special chars, send as hex bytes.1023 response.PutCString("description:");1024 response.PutStringAsRawHex8(description);1025 response.PutChar(';');1026 } else if ((tid_stop_info.reason == eStopReasonException) &&1027 tid_stop_info.details.exception.type) {1028 response.PutCString("metype:");1029 response.PutHex64(tid_stop_info.details.exception.type);1030 response.PutCString(";mecount:");1031 response.PutHex32(tid_stop_info.details.exception.data_count);1032 response.PutChar(';');1033 1034 for (uint32_t i = 0; i < tid_stop_info.details.exception.data_count; ++i) {1035 response.PutCString("medata:");1036 response.PutHex64(tid_stop_info.details.exception.data[i]);1037 response.PutChar(';');1038 }1039 }1040 1041 // Include child process PID/TID for forks.1042 if (tid_stop_info.reason == eStopReasonFork ||1043 tid_stop_info.reason == eStopReasonVFork) {1044 assert(bool(m_extensions_supported &1045 NativeProcessProtocol::Extension::multiprocess));1046 if (tid_stop_info.reason == eStopReasonFork)1047 assert(bool(m_extensions_supported &1048 NativeProcessProtocol::Extension::fork));1049 if (tid_stop_info.reason == eStopReasonVFork)1050 assert(bool(m_extensions_supported &1051 NativeProcessProtocol::Extension::vfork));1052 response.Printf("%s:p%" PRIx64 ".%" PRIx64 ";", reason_str,1053 tid_stop_info.details.fork.child_pid,1054 tid_stop_info.details.fork.child_tid);1055 }1056 1057 return response;1058}1059 1060GDBRemoteCommunication::PacketResult1061GDBRemoteCommunicationServerLLGS::SendStopReplyPacketForThread(1062 NativeProcessProtocol &process, lldb::tid_t tid, bool force_synchronous) {1063 // Ensure we can get info on the given thread.1064 NativeThreadProtocol *thread = process.GetThreadByID(tid);1065 if (!thread)1066 return SendErrorResponse(51);1067 1068 StreamString response = PrepareStopReplyPacketForThread(*thread);1069 if (response.Empty())1070 return SendErrorResponse(42);1071 1072 if (m_non_stop && !force_synchronous) {1073 PacketResult ret = SendNotificationPacketNoLock(1074 "Stop", m_stop_notification_queue, response.GetString());1075 // Queue notification events for the remaining threads.1076 EnqueueStopReplyPackets(tid);1077 return ret;1078 }1079 1080 return SendPacketNoLock(response.GetString());1081}1082 1083void GDBRemoteCommunicationServerLLGS::EnqueueStopReplyPackets(1084 lldb::tid_t thread_to_skip) {1085 if (!m_non_stop)1086 return;1087 1088 for (NativeThreadProtocol &listed_thread : m_current_process->Threads()) {1089 if (listed_thread.GetID() != thread_to_skip) {1090 StreamString stop_reply = PrepareStopReplyPacketForThread(listed_thread);1091 if (!stop_reply.Empty())1092 m_stop_notification_queue.push_back(stop_reply.GetString().str());1093 }1094 }1095}1096 1097void GDBRemoteCommunicationServerLLGS::HandleInferiorState_Exited(1098 NativeProcessProtocol *process) {1099 assert(process && "process cannot be NULL");1100 1101 Log *log = GetLog(LLDBLog::Process);1102 LLDB_LOGF(log, "GDBRemoteCommunicationServerLLGS::%s called", __FUNCTION__);1103 1104 PacketResult result = SendStopReasonForState(1105 *process, StateType::eStateExited, /*force_synchronous=*/false);1106 if (result != PacketResult::Success) {1107 LLDB_LOGF(log,1108 "GDBRemoteCommunicationServerLLGS::%s failed to send stop "1109 "notification for PID %" PRIu64 ", state: eStateExited",1110 __FUNCTION__, process->GetID());1111 }1112 1113 if (m_current_process == process)1114 m_current_process = nullptr;1115 if (m_continue_process == process)1116 m_continue_process = nullptr;1117 1118 lldb::pid_t pid = process->GetID();1119 m_mainloop.AddPendingCallback([this, pid](MainLoopBase &loop) {1120 auto find_it = m_debugged_processes.find(pid);1121 assert(find_it != m_debugged_processes.end());1122 bool vkilled = bool(find_it->second.flags & DebuggedProcess::Flag::vkilled);1123 m_debugged_processes.erase(find_it);1124 // Terminate the main loop only if vKill has not been used.1125 // When running in non-stop mode, wait for the vStopped to clear1126 // the notification queue.1127 if (m_debugged_processes.empty() && !m_non_stop && !vkilled) {1128 // Close the pipe to the inferior terminal i/o if we launched it and set1129 // one up.1130 MaybeCloseInferiorTerminalConnection();1131 1132 // We are ready to exit the debug monitor.1133 m_exit_now = true;1134 loop.RequestTermination();1135 }1136 });1137}1138 1139void GDBRemoteCommunicationServerLLGS::HandleInferiorState_Stopped(1140 NativeProcessProtocol *process) {1141 assert(process && "process cannot be NULL");1142 1143 Log *log = GetLog(LLDBLog::Process);1144 LLDB_LOGF(log, "GDBRemoteCommunicationServerLLGS::%s called", __FUNCTION__);1145 1146 PacketResult result = SendStopReasonForState(1147 *process, StateType::eStateStopped, /*force_synchronous=*/false);1148 if (result != PacketResult::Success) {1149 LLDB_LOGF(log,1150 "GDBRemoteCommunicationServerLLGS::%s failed to send stop "1151 "notification for PID %" PRIu64 ", state: eStateExited",1152 __FUNCTION__, process->GetID());1153 }1154}1155 1156void GDBRemoteCommunicationServerLLGS::ProcessStateChanged(1157 NativeProcessProtocol *process, lldb::StateType state) {1158 assert(process && "process cannot be NULL");1159 Log *log = GetLog(LLDBLog::Process);1160 if (log) {1161 LLDB_LOGF(log,1162 "GDBRemoteCommunicationServerLLGS::%s called with "1163 "NativeProcessProtocol pid %" PRIu64 ", state: %s",1164 __FUNCTION__, process->GetID(), StateAsCString(state));1165 }1166 1167 switch (state) {1168 case StateType::eStateRunning:1169 break;1170 1171 case StateType::eStateStopped:1172 // Make sure we get all of the pending stdout/stderr from the inferior and1173 // send it to the lldb host before we send the state change notification1174 SendProcessOutput();1175 // Then stop the forwarding, so that any late output (see llvm.org/pr25652)1176 // does not interfere with our protocol.1177 if (!m_non_stop)1178 StopSTDIOForwarding();1179 HandleInferiorState_Stopped(process);1180 break;1181 1182 case StateType::eStateExited:1183 // Same as above1184 SendProcessOutput();1185 if (!m_non_stop)1186 StopSTDIOForwarding();1187 HandleInferiorState_Exited(process);1188 break;1189 1190 default:1191 if (log) {1192 LLDB_LOGF(log,1193 "GDBRemoteCommunicationServerLLGS::%s didn't handle state "1194 "change for pid %" PRIu64 ", new state: %s",1195 __FUNCTION__, process->GetID(), StateAsCString(state));1196 }1197 break;1198 }1199}1200 1201void GDBRemoteCommunicationServerLLGS::DidExec(NativeProcessProtocol *process) {1202 ClearProcessSpecificData();1203}1204 1205void GDBRemoteCommunicationServerLLGS::NewSubprocess(1206 NativeProcessProtocol *parent_process,1207 std::unique_ptr<NativeProcessProtocol> child_process) {1208 lldb::pid_t child_pid = child_process->GetID();1209 assert(child_pid != LLDB_INVALID_PROCESS_ID);1210 assert(m_debugged_processes.find(child_pid) == m_debugged_processes.end());1211 m_debugged_processes.emplace(1212 child_pid,1213 DebuggedProcess{std::move(child_process), DebuggedProcess::Flag{}});1214}1215 1216void GDBRemoteCommunicationServerLLGS::DataAvailableCallback() {1217 Log *log = GetLog(GDBRLog::Comm);1218 1219 bool interrupt = false;1220 bool done = false;1221 Status error;1222 while (true) {1223 const PacketResult result = GetPacketAndSendResponse(1224 std::chrono::microseconds(0), error, interrupt, done);1225 if (result == PacketResult::ErrorReplyTimeout)1226 break; // No more packets in the queue1227 1228 if ((result != PacketResult::Success)) {1229 LLDB_LOGF(log,1230 "GDBRemoteCommunicationServerLLGS::%s processing a packet "1231 "failed: %s",1232 __FUNCTION__, error.AsCString());1233 m_mainloop.RequestTermination();1234 break;1235 }1236 }1237}1238 1239Status GDBRemoteCommunicationServerLLGS::InitializeConnection(1240 std::unique_ptr<Connection> connection) {1241 IOObjectSP read_object_sp = connection->GetReadObject();1242 GDBRemoteCommunicationServer::SetConnection(std::move(connection));1243 1244 Status error;1245 m_network_handle_up = m_mainloop.RegisterReadObject(1246 read_object_sp, [this](MainLoopBase &) { DataAvailableCallback(); },1247 error);1248 return error;1249}1250 1251GDBRemoteCommunication::PacketResult1252GDBRemoteCommunicationServerLLGS::SendStructuredDataPacket(1253 const llvm::json::Value &value) {1254 std::string json_string;1255 raw_string_ostream os(json_string);1256 os << value;1257 1258 StreamGDBRemote escaped_response;1259 escaped_response.PutCString("JSON-async:");1260 escaped_response.PutEscapedBytes(json_string.c_str(), json_string.size());1261 return SendPacketNoLock(escaped_response.GetString());1262}1263 1264GDBRemoteCommunication::PacketResult1265GDBRemoteCommunicationServerLLGS::SendONotification(const char *buffer,1266 uint32_t len) {1267 if ((buffer == nullptr) || (len == 0)) {1268 // Nothing to send.1269 return PacketResult::Success;1270 }1271 1272 StreamString response;1273 response.PutChar('O');1274 response.PutBytesAsRawHex8(buffer, len);1275 1276 if (m_non_stop)1277 return SendNotificationPacketNoLock("Stdio", m_stdio_notification_queue,1278 response.GetString());1279 return SendPacketNoLock(response.GetString());1280}1281 1282Status GDBRemoteCommunicationServerLLGS::SetSTDIOFileDescriptor(int fd) {1283 Status error;1284 1285 // Set up the reading/handling of process I/O1286 std::unique_ptr<ConnectionFileDescriptor> conn_up(1287 new ConnectionFileDescriptor(fd, true));1288 if (!conn_up) {1289 error =1290 Status::FromErrorString("failed to create ConnectionFileDescriptor");1291 return error;1292 }1293 1294 m_stdio_communication.SetCloseOnEOF(false);1295 m_stdio_communication.SetConnection(std::move(conn_up));1296 if (!m_stdio_communication.IsConnected()) {1297 error = Status::FromErrorString(1298 "failed to set connection for inferior I/O communication");1299 return error;1300 }1301 1302 return Status();1303}1304 1305void GDBRemoteCommunicationServerLLGS::StartSTDIOForwarding() {1306 // Don't forward if not connected (e.g. when attaching).1307 if (!m_stdio_communication.IsConnected())1308 return;1309 1310 Status error;1311 assert(!m_stdio_handle_up);1312 m_stdio_handle_up = m_mainloop.RegisterReadObject(1313 m_stdio_communication.GetConnection()->GetReadObject(),1314 [this](MainLoopBase &) { SendProcessOutput(); }, error);1315 1316 if (!m_stdio_handle_up) {1317 // Not much we can do about the failure. Log it and continue without1318 // forwarding.1319 if (Log *log = GetLog(LLDBLog::Process))1320 LLDB_LOG(log, "Failed to set up stdio forwarding: {0}", error);1321 }1322}1323 1324void GDBRemoteCommunicationServerLLGS::StopSTDIOForwarding() {1325 m_stdio_handle_up.reset();1326}1327 1328void GDBRemoteCommunicationServerLLGS::SendProcessOutput() {1329 char buffer[1024];1330 ConnectionStatus status;1331 Status error;1332 while (true) {1333 size_t bytes_read = m_stdio_communication.Read(1334 buffer, sizeof buffer, std::chrono::microseconds(0), status, &error);1335 switch (status) {1336 case eConnectionStatusSuccess:1337 SendONotification(buffer, bytes_read);1338 break;1339 case eConnectionStatusLostConnection:1340 case eConnectionStatusEndOfFile:1341 case eConnectionStatusError:1342 case eConnectionStatusNoConnection:1343 if (Log *log = GetLog(LLDBLog::Process))1344 LLDB_LOGF(log,1345 "GDBRemoteCommunicationServerLLGS::%s Stopping stdio "1346 "forwarding as communication returned status %d (error: "1347 "%s)",1348 __FUNCTION__, status, error.AsCString());1349 m_stdio_handle_up.reset();1350 return;1351 1352 case eConnectionStatusInterrupted:1353 case eConnectionStatusTimedOut:1354 return;1355 }1356 }1357}1358 1359GDBRemoteCommunication::PacketResult1360GDBRemoteCommunicationServerLLGS::Handle_jLLDBTraceSupported(1361 StringExtractorGDBRemote &packet) {1362 1363 // Fail if we don't have a current process.1364 if (!m_current_process ||1365 (m_current_process->GetID() == LLDB_INVALID_PROCESS_ID))1366 return SendErrorResponse(Status::FromErrorString("Process not running."));1367 1368 return SendJSONResponse(m_current_process->TraceSupported());1369}1370 1371GDBRemoteCommunication::PacketResult1372GDBRemoteCommunicationServerLLGS::Handle_jLLDBTraceStop(1373 StringExtractorGDBRemote &packet) {1374 // Fail if we don't have a current process.1375 if (!m_current_process ||1376 (m_current_process->GetID() == LLDB_INVALID_PROCESS_ID))1377 return SendErrorResponse(Status::FromErrorString("Process not running."));1378 1379 packet.ConsumeFront("jLLDBTraceStop:");1380 Expected<TraceStopRequest> stop_request =1381 json::parse<TraceStopRequest>(packet.Peek(), "TraceStopRequest");1382 if (!stop_request)1383 return SendErrorResponse(stop_request.takeError());1384 1385 if (Error err = m_current_process->TraceStop(*stop_request))1386 return SendErrorResponse(std::move(err));1387 1388 return SendOKResponse();1389}1390 1391GDBRemoteCommunication::PacketResult1392GDBRemoteCommunicationServerLLGS::Handle_jLLDBTraceStart(1393 StringExtractorGDBRemote &packet) {1394 1395 // Fail if we don't have a current process.1396 if (!m_current_process ||1397 (m_current_process->GetID() == LLDB_INVALID_PROCESS_ID))1398 return SendErrorResponse(Status::FromErrorString("Process not running."));1399 1400 packet.ConsumeFront("jLLDBTraceStart:");1401 Expected<TraceStartRequest> request =1402 json::parse<TraceStartRequest>(packet.Peek(), "TraceStartRequest");1403 if (!request)1404 return SendErrorResponse(request.takeError());1405 1406 if (Error err = m_current_process->TraceStart(packet.Peek(), request->type))1407 return SendErrorResponse(std::move(err));1408 1409 return SendOKResponse();1410}1411 1412GDBRemoteCommunication::PacketResult1413GDBRemoteCommunicationServerLLGS::Handle_jLLDBTraceGetState(1414 StringExtractorGDBRemote &packet) {1415 1416 // Fail if we don't have a current process.1417 if (!m_current_process ||1418 (m_current_process->GetID() == LLDB_INVALID_PROCESS_ID))1419 return SendErrorResponse(Status::FromErrorString("Process not running."));1420 1421 packet.ConsumeFront("jLLDBTraceGetState:");1422 Expected<TraceGetStateRequest> request =1423 json::parse<TraceGetStateRequest>(packet.Peek(), "TraceGetStateRequest");1424 if (!request)1425 return SendErrorResponse(request.takeError());1426 1427 return SendJSONResponse(m_current_process->TraceGetState(request->type));1428}1429 1430GDBRemoteCommunication::PacketResult1431GDBRemoteCommunicationServerLLGS::Handle_jLLDBTraceGetBinaryData(1432 StringExtractorGDBRemote &packet) {1433 1434 // Fail if we don't have a current process.1435 if (!m_current_process ||1436 (m_current_process->GetID() == LLDB_INVALID_PROCESS_ID))1437 return SendErrorResponse(Status::FromErrorString("Process not running."));1438 1439 packet.ConsumeFront("jLLDBTraceGetBinaryData:");1440 llvm::Expected<TraceGetBinaryDataRequest> request =1441 llvm::json::parse<TraceGetBinaryDataRequest>(packet.Peek(),1442 "TraceGetBinaryDataRequest");1443 if (!request)1444 return SendErrorResponse(Status::FromError(request.takeError()));1445 1446 if (Expected<std::vector<uint8_t>> bytes =1447 m_current_process->TraceGetBinaryData(*request)) {1448 StreamGDBRemote response;1449 response.PutEscapedBytes(bytes->data(), bytes->size());1450 return SendPacketNoLock(response.GetString());1451 } else1452 return SendErrorResponse(bytes.takeError());1453}1454 1455GDBRemoteCommunication::PacketResult1456GDBRemoteCommunicationServerLLGS::Handle_qStructuredDataPlugins(1457 StringExtractorGDBRemote &packet) {1458 // Fail if we don't have a current process.1459 if (!m_current_process ||1460 (m_current_process->GetID() == LLDB_INVALID_PROCESS_ID))1461 return SendErrorResponse(68);1462 1463 std::vector<std::string> structured_data_plugins =1464 m_current_process->GetStructuredDataPlugins();1465 1466 return SendJSONResponse(1467 llvm::json::Value(llvm::json::Array(structured_data_plugins)));1468}1469 1470GDBRemoteCommunication::PacketResult1471GDBRemoteCommunicationServerLLGS::Handle_qProcessInfo(1472 StringExtractorGDBRemote &packet) {1473 // Fail if we don't have a current process.1474 if (!m_current_process ||1475 (m_current_process->GetID() == LLDB_INVALID_PROCESS_ID))1476 return SendErrorResponse(68);1477 1478 lldb::pid_t pid = m_current_process->GetID();1479 1480 if (pid == LLDB_INVALID_PROCESS_ID)1481 return SendErrorResponse(1);1482 1483 ProcessInstanceInfo proc_info;1484 if (!Host::GetProcessInfo(pid, proc_info))1485 return SendErrorResponse(1);1486 1487 StreamString response;1488 CreateProcessInfoResponse_DebugServerStyle(proc_info, response);1489 return SendPacketNoLock(response.GetString());1490}1491 1492GDBRemoteCommunication::PacketResult1493GDBRemoteCommunicationServerLLGS::Handle_qC(StringExtractorGDBRemote &packet) {1494 // Fail if we don't have a current process.1495 if (!m_current_process ||1496 (m_current_process->GetID() == LLDB_INVALID_PROCESS_ID))1497 return SendErrorResponse(68);1498 1499 // Make sure we set the current thread so g and p packets return the data the1500 // gdb will expect.1501 lldb::tid_t tid = m_current_process->GetCurrentThreadID();1502 SetCurrentThreadID(tid);1503 1504 NativeThreadProtocol *thread = m_current_process->GetCurrentThread();1505 if (!thread)1506 return SendErrorResponse(69);1507 1508 StreamString response;1509 response.PutCString("QC");1510 AppendThreadIDToResponse(response, m_current_process->GetID(),1511 thread->GetID());1512 1513 return SendPacketNoLock(response.GetString());1514}1515 1516GDBRemoteCommunication::PacketResult1517GDBRemoteCommunicationServerLLGS::Handle_k(StringExtractorGDBRemote &packet) {1518 Log *log = GetLog(LLDBLog::Process);1519 1520 if (!m_non_stop)1521 StopSTDIOForwarding();1522 1523 if (m_debugged_processes.empty()) {1524 LLDB_LOG(log, "No debugged process found.");1525 return PacketResult::Success;1526 }1527 1528 for (auto it = m_debugged_processes.begin(); it != m_debugged_processes.end();1529 ++it) {1530 LLDB_LOG(log, "Killing process {0}", it->first);1531 Status error = it->second.process_up->Kill();1532 if (error.Fail())1533 LLDB_LOG(log, "Failed to kill debugged process {0}: {1}", it->first,1534 error);1535 }1536 1537 // The response to kill packet is undefined per the spec. LLDB1538 // follows the same rules as for continue packets, i.e. no response1539 // in all-stop mode, and "OK" in non-stop mode; in both cases this1540 // is followed by the actual stop reason.1541 return SendContinueSuccessResponse();1542}1543 1544GDBRemoteCommunication::PacketResult1545GDBRemoteCommunicationServerLLGS::Handle_vKill(1546 StringExtractorGDBRemote &packet) {1547 if (!m_non_stop)1548 StopSTDIOForwarding();1549 1550 packet.SetFilePos(6); // vKill;1551 uint32_t pid = packet.GetU32(LLDB_INVALID_PROCESS_ID, 16);1552 if (pid == LLDB_INVALID_PROCESS_ID)1553 return SendIllFormedResponse(packet,1554 "vKill failed to parse the process id");1555 1556 auto it = m_debugged_processes.find(pid);1557 if (it == m_debugged_processes.end())1558 return SendErrorResponse(42);1559 1560 Status error = it->second.process_up->Kill();1561 if (error.Fail())1562 return SendErrorResponse(error.ToError());1563 1564 // OK response is sent when the process dies.1565 it->second.flags |= DebuggedProcess::Flag::vkilled;1566 return PacketResult::Success;1567}1568 1569GDBRemoteCommunication::PacketResult1570GDBRemoteCommunicationServerLLGS::Handle_QSetDisableASLR(1571 StringExtractorGDBRemote &packet) {1572 packet.SetFilePos(::strlen("QSetDisableASLR:"));1573 if (packet.GetU32(0))1574 m_process_launch_info.GetFlags().Set(eLaunchFlagDisableASLR);1575 else1576 m_process_launch_info.GetFlags().Clear(eLaunchFlagDisableASLR);1577 return SendOKResponse();1578}1579 1580GDBRemoteCommunication::PacketResult1581GDBRemoteCommunicationServerLLGS::Handle_QSetWorkingDir(1582 StringExtractorGDBRemote &packet) {1583 packet.SetFilePos(::strlen("QSetWorkingDir:"));1584 std::string path;1585 packet.GetHexByteString(path);1586 m_process_launch_info.SetWorkingDirectory(FileSpec(path));1587 return SendOKResponse();1588}1589 1590GDBRemoteCommunication::PacketResult1591GDBRemoteCommunicationServerLLGS::Handle_qGetWorkingDir(1592 StringExtractorGDBRemote &packet) {1593 FileSpec working_dir{m_process_launch_info.GetWorkingDirectory()};1594 if (working_dir) {1595 StreamString response;1596 response.PutStringAsRawHex8(working_dir.GetPath().c_str());1597 return SendPacketNoLock(response.GetString());1598 }1599 1600 return SendErrorResponse(14);1601}1602 1603GDBRemoteCommunication::PacketResult1604GDBRemoteCommunicationServerLLGS::Handle_QThreadSuffixSupported(1605 StringExtractorGDBRemote &packet) {1606 m_thread_suffix_supported = true;1607 return SendOKResponse();1608}1609 1610GDBRemoteCommunication::PacketResult1611GDBRemoteCommunicationServerLLGS::Handle_QListThreadsInStopReply(1612 StringExtractorGDBRemote &packet) {1613 m_list_threads_in_stop_reply = true;1614 return SendOKResponse();1615}1616 1617GDBRemoteCommunication::PacketResult1618GDBRemoteCommunicationServerLLGS::ResumeProcess(1619 NativeProcessProtocol &process, const ResumeActionList &actions) {1620 Log *log = GetLog(LLDBLog::Process | LLDBLog::Thread);1621 1622 // In non-stop protocol mode, the process could be running already.1623 // We do not support resuming threads independently, so just error out.1624 if (!process.CanResume()) {1625 LLDB_LOG(log, "process {0} cannot be resumed (state={1})", process.GetID(),1626 process.GetState());1627 return SendErrorResponse(0x37);1628 }1629 1630 Status error = process.Resume(actions);1631 if (error.Fail()) {1632 LLDB_LOG(log, "process {0} failed to resume: {1}", process.GetID(), error);1633 return SendErrorResponse(GDBRemoteServerError::eErrorResume);1634 }1635 1636 LLDB_LOG(log, "process {0} resumed", process.GetID());1637 1638 return PacketResult::Success;1639}1640 1641GDBRemoteCommunication::PacketResult1642GDBRemoteCommunicationServerLLGS::Handle_C(StringExtractorGDBRemote &packet) {1643 Log *log = GetLog(LLDBLog::Process | LLDBLog::Thread);1644 LLDB_LOGF(log, "GDBRemoteCommunicationServerLLGS::%s called", __FUNCTION__);1645 1646 // Ensure we have a native process.1647 if (!m_continue_process) {1648 LLDB_LOGF(log,1649 "GDBRemoteCommunicationServerLLGS::%s no debugged process "1650 "shared pointer",1651 __FUNCTION__);1652 return SendErrorResponse(0x36);1653 }1654 1655 // Pull out the signal number.1656 packet.SetFilePos(::strlen("C"));1657 if (packet.GetBytesLeft() < 1) {1658 // Shouldn't be using a C without a signal.1659 return SendIllFormedResponse(packet, "C packet specified without signal.");1660 }1661 const uint32_t signo =1662 packet.GetHexMaxU32(false, std::numeric_limits<uint32_t>::max());1663 if (signo == std::numeric_limits<uint32_t>::max())1664 return SendIllFormedResponse(packet, "failed to parse signal number");1665 1666 // Handle optional continue address.1667 if (packet.GetBytesLeft() > 0) {1668 // FIXME add continue at address support for $C{signo}[;{continue-address}].1669 if (*packet.Peek() == ';')1670 return SendUnimplementedResponse(packet.GetStringRef().data());1671 else1672 return SendIllFormedResponse(1673 packet, "unexpected content after $C{signal-number}");1674 }1675 1676 // In non-stop protocol mode, the process could be running already.1677 // We do not support resuming threads independently, so just error out.1678 if (!m_continue_process->CanResume()) {1679 LLDB_LOG(log, "process cannot be resumed (state={0})",1680 m_continue_process->GetState());1681 return SendErrorResponse(0x37);1682 }1683 1684 ResumeActionList resume_actions(StateType::eStateRunning,1685 LLDB_INVALID_SIGNAL_NUMBER);1686 Status error;1687 1688 // We have two branches: what to do if a continue thread is specified (in1689 // which case we target sending the signal to that thread), or when we don't1690 // have a continue thread set (in which case we send a signal to the1691 // process).1692 1693 // TODO discuss with Greg Clayton, make sure this makes sense.1694 1695 lldb::tid_t signal_tid = GetContinueThreadID();1696 if (signal_tid != LLDB_INVALID_THREAD_ID) {1697 // The resume action for the continue thread (or all threads if a continue1698 // thread is not set).1699 ResumeAction action = {GetContinueThreadID(), StateType::eStateRunning,1700 static_cast<int>(signo)};1701 1702 // Add the action for the continue thread (or all threads when the continue1703 // thread isn't present).1704 resume_actions.Append(action);1705 } else {1706 // Send the signal to the process since we weren't targeting a specific1707 // continue thread with the signal.1708 error = m_continue_process->Signal(signo);1709 if (error.Fail()) {1710 LLDB_LOG(log, "failed to send signal for process {0}: {1}",1711 m_continue_process->GetID(), error);1712 1713 return SendErrorResponse(0x52);1714 }1715 }1716 1717 // NB: this checks CanResume() twice but using a single code path for1718 // resuming still seems worth it.1719 PacketResult resume_res = ResumeProcess(*m_continue_process, resume_actions);1720 if (resume_res != PacketResult::Success)1721 return resume_res;1722 1723 // Don't send an "OK" packet, except in non-stop mode;1724 // otherwise, the response is the stopped/exited message.1725 return SendContinueSuccessResponse();1726}1727 1728GDBRemoteCommunication::PacketResult1729GDBRemoteCommunicationServerLLGS::Handle_c(StringExtractorGDBRemote &packet) {1730 Log *log = GetLog(LLDBLog::Process | LLDBLog::Thread);1731 LLDB_LOGF(log, "GDBRemoteCommunicationServerLLGS::%s called", __FUNCTION__);1732 1733 packet.SetFilePos(packet.GetFilePos() + ::strlen("c"));1734 1735 // For now just support all continue.1736 const bool has_continue_address = (packet.GetBytesLeft() > 0);1737 if (has_continue_address) {1738 LLDB_LOG(log, "not implemented for c[address] variant [{0} remains]",1739 packet.Peek());1740 return SendUnimplementedResponse(packet.GetStringRef().data());1741 }1742 1743 // Ensure we have a native process.1744 if (!m_continue_process) {1745 LLDB_LOGF(log,1746 "GDBRemoteCommunicationServerLLGS::%s no debugged process "1747 "shared pointer",1748 __FUNCTION__);1749 return SendErrorResponse(0x36);1750 }1751 1752 // Build the ResumeActionList1753 ResumeActionList actions(StateType::eStateRunning,1754 LLDB_INVALID_SIGNAL_NUMBER);1755 1756 PacketResult resume_res = ResumeProcess(*m_continue_process, actions);1757 if (resume_res != PacketResult::Success)1758 return resume_res;1759 1760 return SendContinueSuccessResponse();1761}1762 1763GDBRemoteCommunication::PacketResult1764GDBRemoteCommunicationServerLLGS::Handle_vCont_actions(1765 StringExtractorGDBRemote &packet) {1766 StreamString response;1767 response.Printf("vCont;c;C;s;S;t");1768 1769 return SendPacketNoLock(response.GetString());1770}1771 1772static bool ResumeActionListStopsAllThreads(ResumeActionList &actions) {1773 // We're doing a stop-all if and only if our only action is a "t" for all1774 // threads.1775 if (const ResumeAction *default_action =1776 actions.GetActionForThread(LLDB_INVALID_THREAD_ID, false)) {1777 if (default_action->state == eStateSuspended && actions.GetSize() == 1)1778 return true;1779 }1780 1781 return false;1782}1783 1784GDBRemoteCommunication::PacketResult1785GDBRemoteCommunicationServerLLGS::Handle_vCont(1786 StringExtractorGDBRemote &packet) {1787 Log *log = GetLog(LLDBLog::Process);1788 LLDB_LOGF(log, "GDBRemoteCommunicationServerLLGS::%s handling vCont packet",1789 __FUNCTION__);1790 1791 packet.SetFilePos(::strlen("vCont"));1792 1793 if (packet.GetBytesLeft() == 0) {1794 LLDB_LOGF(log,1795 "GDBRemoteCommunicationServerLLGS::%s missing action from "1796 "vCont package",1797 __FUNCTION__);1798 return SendIllFormedResponse(packet, "Missing action from vCont package");1799 }1800 1801 if (::strcmp(packet.Peek(), ";s") == 0) {1802 // Move past the ';', then do a simple 's'.1803 packet.SetFilePos(packet.GetFilePos() + 1);1804 return Handle_s(packet);1805 }1806 1807 std::unordered_map<lldb::pid_t, ResumeActionList> thread_actions;1808 1809 while (packet.GetBytesLeft() && *packet.Peek() == ';') {1810 // Skip the semi-colon.1811 packet.GetChar();1812 1813 // Build up the thread action.1814 ResumeAction thread_action;1815 thread_action.tid = LLDB_INVALID_THREAD_ID;1816 thread_action.state = eStateInvalid;1817 thread_action.signal = LLDB_INVALID_SIGNAL_NUMBER;1818 1819 const char action = packet.GetChar();1820 switch (action) {1821 case 'C':1822 thread_action.signal = packet.GetHexMaxU32(false, 0);1823 if (thread_action.signal == 0)1824 return SendIllFormedResponse(1825 packet, "Could not parse signal in vCont packet C action");1826 [[fallthrough]];1827 1828 case 'c':1829 // Continue1830 thread_action.state = eStateRunning;1831 break;1832 1833 case 'S':1834 thread_action.signal = packet.GetHexMaxU32(false, 0);1835 if (thread_action.signal == 0)1836 return SendIllFormedResponse(1837 packet, "Could not parse signal in vCont packet S action");1838 [[fallthrough]];1839 1840 case 's':1841 // Step1842 thread_action.state = eStateStepping;1843 break;1844 1845 case 't':1846 // Stop1847 thread_action.state = eStateSuspended;1848 break;1849 1850 default:1851 return SendIllFormedResponse(packet, "Unsupported vCont action");1852 break;1853 }1854 1855 // If there's no thread-id (e.g. "vCont;c"), it's "p-1.-1".1856 lldb::pid_t pid = StringExtractorGDBRemote::AllProcesses;1857 lldb::tid_t tid = StringExtractorGDBRemote::AllThreads;1858 1859 // Parse out optional :{thread-id} value.1860 if (packet.GetBytesLeft() && (*packet.Peek() == ':')) {1861 // Consume the separator.1862 packet.GetChar();1863 1864 auto pid_tid = packet.GetPidTid(LLDB_INVALID_PROCESS_ID);1865 if (!pid_tid)1866 return SendIllFormedResponse(packet, "Malformed thread-id");1867 1868 pid = pid_tid->first;1869 tid = pid_tid->second;1870 }1871 1872 if (thread_action.state == eStateSuspended &&1873 tid != StringExtractorGDBRemote::AllThreads) {1874 return SendIllFormedResponse(1875 packet, "'t' action not supported for individual threads");1876 }1877 1878 // If we get TID without PID, it's the current process.1879 if (pid == LLDB_INVALID_PROCESS_ID) {1880 if (!m_continue_process) {1881 LLDB_LOG(log, "no process selected via Hc");1882 return SendErrorResponse(0x36);1883 }1884 pid = m_continue_process->GetID();1885 }1886 1887 assert(pid != LLDB_INVALID_PROCESS_ID);1888 if (tid == StringExtractorGDBRemote::AllThreads)1889 tid = LLDB_INVALID_THREAD_ID;1890 thread_action.tid = tid;1891 1892 if (pid == StringExtractorGDBRemote::AllProcesses) {1893 if (tid != LLDB_INVALID_THREAD_ID)1894 return SendIllFormedResponse(1895 packet, "vCont: p-1 is not valid with a specific tid");1896 for (auto &process_it : m_debugged_processes)1897 thread_actions[process_it.first].Append(thread_action);1898 } else1899 thread_actions[pid].Append(thread_action);1900 }1901 1902 assert(thread_actions.size() >= 1);1903 if (thread_actions.size() > 1 && !m_non_stop)1904 return SendIllFormedResponse(1905 packet,1906 "Resuming multiple processes is supported in non-stop mode only");1907 1908 for (std::pair<lldb::pid_t, ResumeActionList> x : thread_actions) {1909 auto process_it = m_debugged_processes.find(x.first);1910 if (process_it == m_debugged_processes.end()) {1911 LLDB_LOG(log, "vCont failed for process {0}: process not debugged",1912 x.first);1913 return SendErrorResponse(GDBRemoteServerError::eErrorResume);1914 }1915 1916 // There are four possible scenarios here. These are:1917 // 1. vCont on a stopped process that resumes at least one thread.1918 // In this case, we call Resume().1919 // 2. vCont on a stopped process that leaves all threads suspended.1920 // A no-op.1921 // 3. vCont on a running process that requests suspending all1922 // running threads. In this case, we call Interrupt().1923 // 4. vCont on a running process that requests suspending a subset1924 // of running threads or resuming a subset of suspended threads.1925 // Since we do not support full nonstop mode, this is unsupported1926 // and we return an error.1927 1928 assert(process_it->second.process_up);1929 if (ResumeActionListStopsAllThreads(x.second)) {1930 if (process_it->second.process_up->IsRunning()) {1931 assert(m_non_stop);1932 1933 Status error = process_it->second.process_up->Interrupt();1934 if (error.Fail()) {1935 LLDB_LOG(log, "vCont failed to halt process {0}: {1}", x.first,1936 error);1937 return SendErrorResponse(GDBRemoteServerError::eErrorResume);1938 }1939 1940 LLDB_LOG(log, "halted process {0}", x.first);1941 1942 // hack to avoid enabling stdio forwarding after stop1943 // TODO: remove this when we improve stdio forwarding for nonstop1944 assert(thread_actions.size() == 1);1945 return SendOKResponse();1946 }1947 } else {1948 PacketResult resume_res =1949 ResumeProcess(*process_it->second.process_up, x.second);1950 if (resume_res != PacketResult::Success)1951 return resume_res;1952 }1953 }1954 1955 return SendContinueSuccessResponse();1956}1957 1958void GDBRemoteCommunicationServerLLGS::SetCurrentThreadID(lldb::tid_t tid) {1959 Log *log = GetLog(LLDBLog::Thread);1960 LLDB_LOG(log, "setting current thread id to {0}", tid);1961 1962 m_current_tid = tid;1963 if (m_current_process)1964 m_current_process->SetCurrentThreadID(m_current_tid);1965}1966 1967void GDBRemoteCommunicationServerLLGS::SetContinueThreadID(lldb::tid_t tid) {1968 Log *log = GetLog(LLDBLog::Thread);1969 LLDB_LOG(log, "setting continue thread id to {0}", tid);1970 1971 m_continue_tid = tid;1972}1973 1974GDBRemoteCommunication::PacketResult1975GDBRemoteCommunicationServerLLGS::Handle_stop_reason(1976 StringExtractorGDBRemote &packet) {1977 // Handle the $? gdbremote command.1978 1979 if (m_non_stop) {1980 // Clear the notification queue first, except for pending exit1981 // notifications.1982 llvm::erase_if(m_stop_notification_queue, [](const std::string &x) {1983 return x.front() != 'W' && x.front() != 'X';1984 });1985 1986 if (m_current_process) {1987 // Queue stop reply packets for all active threads. Start with1988 // the current thread (for clients that don't actually support multiple1989 // stop reasons).1990 NativeThreadProtocol *thread = m_current_process->GetCurrentThread();1991 if (thread) {1992 StreamString stop_reply = PrepareStopReplyPacketForThread(*thread);1993 if (!stop_reply.Empty())1994 m_stop_notification_queue.push_back(stop_reply.GetString().str());1995 }1996 EnqueueStopReplyPackets(thread ? thread->GetID()1997 : LLDB_INVALID_THREAD_ID);1998 }1999 2000 // If the notification queue is empty (i.e. everything is running), send OK.2001 if (m_stop_notification_queue.empty())2002 return SendOKResponse();2003 2004 // Send the first item from the new notification queue synchronously.2005 return SendPacketNoLock(m_stop_notification_queue.front());2006 }2007 2008 // If no process, indicate error2009 if (!m_current_process)2010 return SendErrorResponse(02);2011 2012 return SendStopReasonForState(*m_current_process,2013 m_current_process->GetState(),2014 /*force_synchronous=*/true);2015}2016 2017GDBRemoteCommunication::PacketResult2018GDBRemoteCommunicationServerLLGS::SendStopReasonForState(2019 NativeProcessProtocol &process, lldb::StateType process_state,2020 bool force_synchronous) {2021 Log *log = GetLog(LLDBLog::Process);2022 2023 if (m_disabling_non_stop) {2024 // Check if we are waiting for any more processes to stop. If we are,2025 // do not send the OK response yet.2026 for (const auto &it : m_debugged_processes) {2027 if (it.second.process_up->IsRunning())2028 return PacketResult::Success;2029 }2030 2031 // If all expected processes were stopped after a QNonStop:0 request,2032 // send the OK response.2033 m_disabling_non_stop = false;2034 return SendOKResponse();2035 }2036 2037 switch (process_state) {2038 case eStateAttaching:2039 case eStateLaunching:2040 case eStateRunning:2041 case eStateStepping:2042 case eStateDetached:2043 // NOTE: gdb protocol doc looks like it should return $OK2044 // when everything is running (i.e. no stopped result).2045 return PacketResult::Success; // Ignore2046 2047 case eStateSuspended:2048 case eStateStopped:2049 case eStateCrashed: {2050 lldb::tid_t tid = process.GetCurrentThreadID();2051 // Make sure we set the current thread so g and p packets return the data2052 // the gdb will expect.2053 SetCurrentThreadID(tid);2054 return SendStopReplyPacketForThread(process, tid, force_synchronous);2055 }2056 2057 case eStateInvalid:2058 case eStateUnloaded:2059 case eStateExited:2060 return SendWResponse(&process);2061 2062 default:2063 LLDB_LOG(log, "pid {0}, current state reporting not handled: {1}",2064 process.GetID(), process_state);2065 break;2066 }2067 2068 return SendErrorResponse(0);2069}2070 2071GDBRemoteCommunication::PacketResult2072GDBRemoteCommunicationServerLLGS::Handle_qRegisterInfo(2073 StringExtractorGDBRemote &packet) {2074 // Fail if we don't have a current process.2075 if (!m_current_process ||2076 (m_current_process->GetID() == LLDB_INVALID_PROCESS_ID))2077 return SendErrorResponse(68);2078 2079 // Ensure we have a thread.2080 NativeThreadProtocol *thread = m_current_process->GetThreadAtIndex(0);2081 if (!thread)2082 return SendErrorResponse(69);2083 2084 // Get the register context for the first thread.2085 NativeRegisterContext ®_context = thread->GetRegisterContext();2086 2087 // Parse out the register number from the request.2088 packet.SetFilePos(strlen("qRegisterInfo"));2089 const uint32_t reg_index =2090 packet.GetHexMaxU32(false, std::numeric_limits<uint32_t>::max());2091 if (reg_index == std::numeric_limits<uint32_t>::max())2092 return SendErrorResponse(69);2093 2094 // Return the end of registers response if we've iterated one past the end of2095 // the register set.2096 if (reg_index >= reg_context.GetUserRegisterCount())2097 return SendErrorResponse(69);2098 2099 const RegisterInfo *reg_info = reg_context.GetRegisterInfoAtIndex(reg_index);2100 if (!reg_info)2101 return SendErrorResponse(69);2102 2103 // Build the reginfos response.2104 StreamGDBRemote response;2105 2106 response.PutCString("name:");2107 response.PutCString(reg_info->name);2108 response.PutChar(';');2109 2110 if (reg_info->alt_name && reg_info->alt_name[0]) {2111 response.PutCString("alt-name:");2112 response.PutCString(reg_info->alt_name);2113 response.PutChar(';');2114 }2115 2116 response.Printf("bitsize:%" PRIu32 ";", reg_info->byte_size * 8);2117 2118 if (!reg_context.RegisterOffsetIsDynamic())2119 response.Printf("offset:%" PRIu32 ";", reg_info->byte_offset);2120 2121 llvm::StringRef encoding = GetEncodingNameOrEmpty(*reg_info);2122 if (!encoding.empty())2123 response << "encoding:" << encoding << ';';2124 2125 llvm::StringRef format = GetFormatNameOrEmpty(*reg_info);2126 if (!format.empty())2127 response << "format:" << format << ';';2128 2129 const char *const register_set_name =2130 reg_context.GetRegisterSetNameForRegisterAtIndex(reg_index);2131 if (register_set_name)2132 response << "set:" << register_set_name << ';';2133 2134 if (reg_info->kinds[RegisterKind::eRegisterKindEHFrame] !=2135 LLDB_INVALID_REGNUM)2136 response.Printf("ehframe:%" PRIu32 ";",2137 reg_info->kinds[RegisterKind::eRegisterKindEHFrame]);2138 2139 if (reg_info->kinds[RegisterKind::eRegisterKindDWARF] != LLDB_INVALID_REGNUM)2140 response.Printf("dwarf:%" PRIu32 ";",2141 reg_info->kinds[RegisterKind::eRegisterKindDWARF]);2142 2143 llvm::StringRef kind_generic = GetKindGenericOrEmpty(*reg_info);2144 if (!kind_generic.empty())2145 response << "generic:" << kind_generic << ';';2146 2147 if (reg_info->value_regs && reg_info->value_regs[0] != LLDB_INVALID_REGNUM) {2148 response.PutCString("container-regs:");2149 CollectRegNums(reg_info->value_regs, response, true);2150 response.PutChar(';');2151 }2152 2153 if (reg_info->invalidate_regs && reg_info->invalidate_regs[0]) {2154 response.PutCString("invalidate-regs:");2155 CollectRegNums(reg_info->invalidate_regs, response, true);2156 response.PutChar(';');2157 }2158 2159 return SendPacketNoLock(response.GetString());2160}2161 2162void GDBRemoteCommunicationServerLLGS::AddProcessThreads(2163 StreamGDBRemote &response, NativeProcessProtocol &process, bool &had_any) {2164 Log *log = GetLog(LLDBLog::Thread);2165 2166 lldb::pid_t pid = process.GetID();2167 if (pid == LLDB_INVALID_PROCESS_ID)2168 return;2169 2170 LLDB_LOG(log, "iterating over threads of process {0}", process.GetID());2171 for (NativeThreadProtocol &thread : process.Threads()) {2172 LLDB_LOG(log, "iterated thread tid={0}", thread.GetID());2173 response.PutChar(had_any ? ',' : 'm');2174 AppendThreadIDToResponse(response, pid, thread.GetID());2175 had_any = true;2176 }2177}2178 2179GDBRemoteCommunication::PacketResult2180GDBRemoteCommunicationServerLLGS::Handle_qfThreadInfo(2181 StringExtractorGDBRemote &packet) {2182 assert(m_debugged_processes.size() <= 1 ||2183 bool(m_extensions_supported &2184 NativeProcessProtocol::Extension::multiprocess));2185 2186 bool had_any = false;2187 StreamGDBRemote response;2188 2189 for (auto &pid_ptr : m_debugged_processes)2190 AddProcessThreads(response, *pid_ptr.second.process_up, had_any);2191 2192 if (!had_any)2193 return SendOKResponse();2194 return SendPacketNoLock(response.GetString());2195}2196 2197GDBRemoteCommunication::PacketResult2198GDBRemoteCommunicationServerLLGS::Handle_qsThreadInfo(2199 StringExtractorGDBRemote &packet) {2200 // FIXME for now we return the full thread list in the initial packet and2201 // always do nothing here.2202 return SendPacketNoLock("l");2203}2204 2205GDBRemoteCommunication::PacketResult2206GDBRemoteCommunicationServerLLGS::Handle_g(StringExtractorGDBRemote &packet) {2207 Log *log = GetLog(LLDBLog::Thread);2208 2209 // Move past packet name.2210 packet.SetFilePos(strlen("g"));2211 2212 // Get the thread to use.2213 NativeThreadProtocol *thread = GetThreadFromSuffix(packet);2214 if (!thread) {2215 LLDB_LOG(log, "failed, no thread available");2216 return SendErrorResponse(0x15);2217 }2218 2219 // Get the thread's register context.2220 NativeRegisterContext ®_ctx = thread->GetRegisterContext();2221 2222 std::vector<uint8_t> regs_buffer;2223 for (uint32_t reg_num = 0; reg_num < reg_ctx.GetUserRegisterCount();2224 ++reg_num) {2225 const RegisterInfo *reg_info = reg_ctx.GetRegisterInfoAtIndex(reg_num);2226 2227 if (reg_info == nullptr) {2228 LLDB_LOG(log, "failed to get register info for register index {0}",2229 reg_num);2230 return SendErrorResponse(0x15);2231 }2232 2233 if (reg_info->value_regs != nullptr)2234 continue; // skip registers that are contained in other registers2235 2236 RegisterValue reg_value;2237 Status error = reg_ctx.ReadRegister(reg_info, reg_value);2238 if (error.Fail()) {2239 LLDB_LOG(log, "failed to read register at index {0}", reg_num);2240 return SendErrorResponse(0x15);2241 }2242 2243 if (reg_info->byte_offset + reg_info->byte_size >= regs_buffer.size())2244 // Resize the buffer to guarantee it can store the register offsetted2245 // data.2246 regs_buffer.resize(reg_info->byte_offset + reg_info->byte_size);2247 2248 // Copy the register offsetted data to the buffer.2249 memcpy(regs_buffer.data() + reg_info->byte_offset, reg_value.GetBytes(),2250 reg_info->byte_size);2251 }2252 2253 // Write the response.2254 StreamGDBRemote response;2255 response.PutBytesAsRawHex8(regs_buffer.data(), regs_buffer.size());2256 2257 return SendPacketNoLock(response.GetString());2258}2259 2260GDBRemoteCommunication::PacketResult2261GDBRemoteCommunicationServerLLGS::Handle_p(StringExtractorGDBRemote &packet) {2262 Log *log = GetLog(LLDBLog::Thread);2263 2264 // Parse out the register number from the request.2265 packet.SetFilePos(strlen("p"));2266 const uint32_t reg_index =2267 packet.GetHexMaxU32(false, std::numeric_limits<uint32_t>::max());2268 if (reg_index == std::numeric_limits<uint32_t>::max()) {2269 LLDB_LOGF(log,2270 "GDBRemoteCommunicationServerLLGS::%s failed, could not "2271 "parse register number from request \"%s\"",2272 __FUNCTION__, packet.GetStringRef().data());2273 return SendErrorResponse(0x15);2274 }2275 2276 // Get the thread to use.2277 NativeThreadProtocol *thread = GetThreadFromSuffix(packet);2278 if (!thread) {2279 LLDB_LOG(log, "failed, no thread available");2280 return SendErrorResponse(0x15);2281 }2282 2283 // Get the thread's register context.2284 NativeRegisterContext ®_context = thread->GetRegisterContext();2285 2286 // Return the end of registers response if we've iterated one past the end of2287 // the register set.2288 if (reg_index >= reg_context.GetUserRegisterCount()) {2289 LLDB_LOGF(log,2290 "GDBRemoteCommunicationServerLLGS::%s failed, requested "2291 "register %" PRIu32 " beyond register count %" PRIu32,2292 __FUNCTION__, reg_index, reg_context.GetUserRegisterCount());2293 return SendErrorResponse(0x15);2294 }2295 2296 const RegisterInfo *reg_info = reg_context.GetRegisterInfoAtIndex(reg_index);2297 if (!reg_info) {2298 LLDB_LOGF(log,2299 "GDBRemoteCommunicationServerLLGS::%s failed, requested "2300 "register %" PRIu32 " returned NULL",2301 __FUNCTION__, reg_index);2302 return SendErrorResponse(0x15);2303 }2304 2305 // Build the reginfos response.2306 StreamGDBRemote response;2307 2308 // Retrieve the value2309 RegisterValue reg_value;2310 Status error = reg_context.ReadRegister(reg_info, reg_value);2311 if (error.Fail()) {2312 LLDB_LOGF(log,2313 "GDBRemoteCommunicationServerLLGS::%s failed, read of "2314 "requested register %" PRIu32 " (%s) failed: %s",2315 __FUNCTION__, reg_index, reg_info->name, error.AsCString());2316 return SendErrorResponse(0x15);2317 }2318 2319 const uint8_t *const data =2320 static_cast<const uint8_t *>(reg_value.GetBytes());2321 if (!data) {2322 LLDB_LOGF(log,2323 "GDBRemoteCommunicationServerLLGS::%s failed to get data "2324 "bytes from requested register %" PRIu32,2325 __FUNCTION__, reg_index);2326 return SendErrorResponse(0x15);2327 }2328 2329 // FIXME flip as needed to get data in big/little endian format for this host.2330 for (uint32_t i = 0; i < reg_value.GetByteSize(); ++i)2331 response.PutHex8(data[i]);2332 2333 return SendPacketNoLock(response.GetString());2334}2335 2336GDBRemoteCommunication::PacketResult2337GDBRemoteCommunicationServerLLGS::Handle_P(StringExtractorGDBRemote &packet) {2338 Log *log = GetLog(LLDBLog::Thread);2339 2340 // Ensure there is more content.2341 if (packet.GetBytesLeft() < 1)2342 return SendIllFormedResponse(packet, "Empty P packet");2343 2344 // Parse out the register number from the request.2345 packet.SetFilePos(strlen("P"));2346 const uint32_t reg_index =2347 packet.GetHexMaxU32(false, std::numeric_limits<uint32_t>::max());2348 if (reg_index == std::numeric_limits<uint32_t>::max()) {2349 LLDB_LOGF(log,2350 "GDBRemoteCommunicationServerLLGS::%s failed, could not "2351 "parse register number from request \"%s\"",2352 __FUNCTION__, packet.GetStringRef().data());2353 return SendErrorResponse(0x29);2354 }2355 2356 // Note debugserver would send an E30 here.2357 if ((packet.GetBytesLeft() < 1) || (packet.GetChar() != '='))2358 return SendIllFormedResponse(2359 packet, "P packet missing '=' char after register number");2360 2361 // Parse out the value.2362 size_t reg_size = packet.GetHexBytesAvail(m_reg_bytes);2363 2364 // Get the thread to use.2365 NativeThreadProtocol *thread = GetThreadFromSuffix(packet);2366 if (!thread) {2367 LLDB_LOGF(log,2368 "GDBRemoteCommunicationServerLLGS::%s failed, no thread "2369 "available (thread index 0)",2370 __FUNCTION__);2371 return SendErrorResponse(0x28);2372 }2373 2374 // Get the thread's register context.2375 NativeRegisterContext ®_context = thread->GetRegisterContext();2376 const RegisterInfo *reg_info = reg_context.GetRegisterInfoAtIndex(reg_index);2377 if (!reg_info) {2378 LLDB_LOGF(log,2379 "GDBRemoteCommunicationServerLLGS::%s failed, requested "2380 "register %" PRIu32 " returned NULL",2381 __FUNCTION__, reg_index);2382 return SendErrorResponse(0x48);2383 }2384 2385 // Return the end of registers response if we've iterated one past the end of2386 // the register set.2387 if (reg_index >= reg_context.GetUserRegisterCount()) {2388 LLDB_LOGF(log,2389 "GDBRemoteCommunicationServerLLGS::%s failed, requested "2390 "register %" PRIu32 " beyond register count %" PRIu32,2391 __FUNCTION__, reg_index, reg_context.GetUserRegisterCount());2392 return SendErrorResponse(0x47);2393 }2394 2395 if (reg_size != reg_info->byte_size)2396 return SendIllFormedResponse(packet, "P packet register size is incorrect");2397 2398 // Build the reginfos response.2399 StreamGDBRemote response;2400 2401 RegisterValue reg_value(ArrayRef<uint8_t>(m_reg_bytes, reg_size),2402 m_current_process->GetArchitecture().GetByteOrder());2403 Status error = reg_context.WriteRegister(reg_info, reg_value);2404 if (error.Fail()) {2405 LLDB_LOGF(log,2406 "GDBRemoteCommunicationServerLLGS::%s failed, write of "2407 "requested register %" PRIu32 " (%s) failed: %s",2408 __FUNCTION__, reg_index, reg_info->name, error.AsCString());2409 return SendErrorResponse(0x32);2410 }2411 2412 return SendOKResponse();2413}2414 2415GDBRemoteCommunication::PacketResult2416GDBRemoteCommunicationServerLLGS::Handle_H(StringExtractorGDBRemote &packet) {2417 Log *log = GetLog(LLDBLog::Thread);2418 2419 // Parse out which variant of $H is requested.2420 packet.SetFilePos(strlen("H"));2421 if (packet.GetBytesLeft() < 1) {2422 LLDB_LOGF(log,2423 "GDBRemoteCommunicationServerLLGS::%s failed, H command "2424 "missing {g,c} variant",2425 __FUNCTION__);2426 return SendIllFormedResponse(packet, "H command missing {g,c} variant");2427 }2428 2429 const char h_variant = packet.GetChar();2430 NativeProcessProtocol *default_process;2431 switch (h_variant) {2432 case 'g':2433 default_process = m_current_process;2434 break;2435 2436 case 'c':2437 default_process = m_continue_process;2438 break;2439 2440 default:2441 LLDB_LOGF(2442 log,2443 "GDBRemoteCommunicationServerLLGS::%s failed, invalid $H variant %c",2444 __FUNCTION__, h_variant);2445 return SendIllFormedResponse(packet,2446 "H variant unsupported, should be c or g");2447 }2448 2449 // Parse out the thread number.2450 auto pid_tid = packet.GetPidTid(default_process ? default_process->GetID()2451 : LLDB_INVALID_PROCESS_ID);2452 if (!pid_tid)2453 return SendErrorResponse(llvm::make_error<StringError>(2454 inconvertibleErrorCode(), "Malformed thread-id"));2455 2456 lldb::pid_t pid = pid_tid->first;2457 lldb::tid_t tid = pid_tid->second;2458 2459 if (pid == StringExtractorGDBRemote::AllProcesses)2460 return SendUnimplementedResponse("Selecting all processes not supported");2461 if (pid == LLDB_INVALID_PROCESS_ID)2462 return SendErrorResponse(llvm::make_error<StringError>(2463 inconvertibleErrorCode(), "No current process and no PID provided"));2464 2465 // Check the process ID and find respective process instance.2466 auto new_process_it = m_debugged_processes.find(pid);2467 if (new_process_it == m_debugged_processes.end())2468 return SendErrorResponse(llvm::make_error<StringError>(2469 inconvertibleErrorCode(),2470 llvm::formatv("No process with PID {0} debugged", pid)));2471 2472 // Ensure we have the given thread when not specifying -1 (all threads) or 02473 // (any thread).2474 if (tid != LLDB_INVALID_THREAD_ID && tid != 0) {2475 NativeThreadProtocol *thread =2476 new_process_it->second.process_up->GetThreadByID(tid);2477 if (!thread) {2478 LLDB_LOGF(log,2479 "GDBRemoteCommunicationServerLLGS::%s failed, tid %" PRIu642480 " not found",2481 __FUNCTION__, tid);2482 return SendErrorResponse(0x15);2483 }2484 }2485 2486 // Now switch the given process and thread type.2487 switch (h_variant) {2488 case 'g':2489 m_current_process = new_process_it->second.process_up.get();2490 SetCurrentThreadID(tid);2491 break;2492 2493 case 'c':2494 m_continue_process = new_process_it->second.process_up.get();2495 SetContinueThreadID(tid);2496 break;2497 2498 default:2499 assert(false && "unsupported $H variant - shouldn't get here");2500 return SendIllFormedResponse(packet,2501 "H variant unsupported, should be c or g");2502 }2503 2504 return SendOKResponse();2505}2506 2507GDBRemoteCommunication::PacketResult2508GDBRemoteCommunicationServerLLGS::Handle_I(StringExtractorGDBRemote &packet) {2509 Log *log = GetLog(LLDBLog::Thread);2510 2511 // Fail if we don't have a current process.2512 if (!m_current_process ||2513 (m_current_process->GetID() == LLDB_INVALID_PROCESS_ID)) {2514 LLDB_LOGF(2515 log,2516 "GDBRemoteCommunicationServerLLGS::%s failed, no process available",2517 __FUNCTION__);2518 return SendErrorResponse(0x15);2519 }2520 2521 packet.SetFilePos(::strlen("I"));2522 uint8_t tmp[4096];2523 for (;;) {2524 size_t read = packet.GetHexBytesAvail(tmp);2525 if (read == 0) {2526 break;2527 }2528 // write directly to stdin *this might block if stdin buffer is full*2529 // TODO: enqueue this block in circular buffer and send window size to2530 // remote host2531 ConnectionStatus status;2532 Status error;2533 m_stdio_communication.WriteAll(tmp, read, status, &error);2534 if (error.Fail()) {2535 return SendErrorResponse(0x15);2536 }2537 }2538 2539 return SendOKResponse();2540}2541 2542GDBRemoteCommunication::PacketResult2543GDBRemoteCommunicationServerLLGS::Handle_interrupt(2544 StringExtractorGDBRemote &packet) {2545 Log *log = GetLog(LLDBLog::Process | LLDBLog::Thread);2546 2547 // Fail if we don't have a current process.2548 if (!m_current_process ||2549 (m_current_process->GetID() == LLDB_INVALID_PROCESS_ID)) {2550 LLDB_LOG(log, "failed, no process available");2551 return SendErrorResponse(0x15);2552 }2553 2554 // Interrupt the process.2555 Status error = m_current_process->Interrupt();2556 if (error.Fail()) {2557 LLDB_LOG(log, "failed for process {0}: {1}", m_current_process->GetID(),2558 error);2559 return SendErrorResponse(GDBRemoteServerError::eErrorResume);2560 }2561 2562 LLDB_LOG(log, "stopped process {0}", m_current_process->GetID());2563 2564 // No response required from stop all.2565 return PacketResult::Success;2566}2567 2568GDBRemoteCommunication::PacketResult2569GDBRemoteCommunicationServerLLGS::Handle_memory_read(2570 StringExtractorGDBRemote &packet) {2571 Log *log = GetLog(LLDBLog::Process);2572 2573 if (!m_current_process ||2574 (m_current_process->GetID() == LLDB_INVALID_PROCESS_ID)) {2575 LLDB_LOGF(2576 log,2577 "GDBRemoteCommunicationServerLLGS::%s failed, no process available",2578 __FUNCTION__);2579 return SendErrorResponse(0x15);2580 }2581 2582 // Parse out the memory address.2583 packet.SetFilePos(strlen("m"));2584 if (packet.GetBytesLeft() < 1)2585 return SendIllFormedResponse(packet, "Too short m packet");2586 2587 // Read the address. Punting on validation.2588 // FIXME replace with Hex U64 read with no default value that fails on failed2589 // read.2590 const lldb::addr_t read_addr = packet.GetHexMaxU64(false, 0);2591 2592 // Validate comma.2593 if ((packet.GetBytesLeft() < 1) || (packet.GetChar() != ','))2594 return SendIllFormedResponse(packet, "Comma sep missing in m packet");2595 2596 // Get # bytes to read.2597 if (packet.GetBytesLeft() < 1)2598 return SendIllFormedResponse(packet, "Length missing in m packet");2599 2600 const uint64_t byte_count = packet.GetHexMaxU64(false, 0);2601 if (byte_count == 0) {2602 LLDB_LOGF(log,2603 "GDBRemoteCommunicationServerLLGS::%s nothing to read: "2604 "zero-length packet",2605 __FUNCTION__);2606 return SendOKResponse();2607 }2608 2609 // Allocate the response buffer.2610 std::string buf(byte_count, '\0');2611 if (buf.empty())2612 return SendErrorResponse(0x78);2613 2614 // Retrieve the process memory.2615 size_t bytes_read = 0;2616 Status error = m_current_process->ReadMemoryWithoutTrap(2617 read_addr, &buf[0], byte_count, bytes_read);2618 LLDB_LOG(2619 log,2620 "ReadMemoryWithoutTrap({0}) read {1} of {2} requested bytes (error: {3})",2621 read_addr, byte_count, bytes_read, error);2622 if (bytes_read == 0)2623 return SendErrorResponse(0x08);2624 2625 StreamGDBRemote response;2626 packet.SetFilePos(0);2627 char kind = packet.GetChar('?');2628 if (kind == 'x')2629 response.PutEscapedBytes(buf.data(), bytes_read);2630 else {2631 assert(kind == 'm');2632 for (size_t i = 0; i < bytes_read; ++i)2633 response.PutHex8(buf[i]);2634 }2635 2636 return SendPacketNoLock(response.GetString());2637}2638 2639GDBRemoteCommunication::PacketResult2640GDBRemoteCommunicationServerLLGS::Handle__M(StringExtractorGDBRemote &packet) {2641 Log *log = GetLog(LLDBLog::Process);2642 2643 if (!m_current_process ||2644 (m_current_process->GetID() == LLDB_INVALID_PROCESS_ID)) {2645 LLDB_LOGF(2646 log,2647 "GDBRemoteCommunicationServerLLGS::%s failed, no process available",2648 __FUNCTION__);2649 return SendErrorResponse(0x15);2650 }2651 2652 // Parse out the memory address.2653 packet.SetFilePos(strlen("_M"));2654 if (packet.GetBytesLeft() < 1)2655 return SendIllFormedResponse(packet, "Too short _M packet");2656 2657 const lldb::addr_t size = packet.GetHexMaxU64(false, LLDB_INVALID_ADDRESS);2658 if (size == LLDB_INVALID_ADDRESS)2659 return SendIllFormedResponse(packet, "Address not valid");2660 if (packet.GetChar() != ',')2661 return SendIllFormedResponse(packet, "Bad packet");2662 Permissions perms = {};2663 while (packet.GetBytesLeft() > 0) {2664 switch (packet.GetChar()) {2665 case 'r':2666 perms |= ePermissionsReadable;2667 break;2668 case 'w':2669 perms |= ePermissionsWritable;2670 break;2671 case 'x':2672 perms |= ePermissionsExecutable;2673 break;2674 default:2675 return SendIllFormedResponse(packet, "Bad permissions");2676 }2677 }2678 2679 llvm::Expected<addr_t> addr = m_current_process->AllocateMemory(size, perms);2680 if (!addr)2681 return SendErrorResponse(addr.takeError());2682 2683 StreamGDBRemote response;2684 response.PutHex64(*addr);2685 return SendPacketNoLock(response.GetString());2686}2687 2688GDBRemoteCommunication::PacketResult2689GDBRemoteCommunicationServerLLGS::Handle__m(StringExtractorGDBRemote &packet) {2690 Log *log = GetLog(LLDBLog::Process);2691 2692 if (!m_current_process ||2693 (m_current_process->GetID() == LLDB_INVALID_PROCESS_ID)) {2694 LLDB_LOGF(2695 log,2696 "GDBRemoteCommunicationServerLLGS::%s failed, no process available",2697 __FUNCTION__);2698 return SendErrorResponse(0x15);2699 }2700 2701 // Parse out the memory address.2702 packet.SetFilePos(strlen("_m"));2703 if (packet.GetBytesLeft() < 1)2704 return SendIllFormedResponse(packet, "Too short m packet");2705 2706 const lldb::addr_t addr = packet.GetHexMaxU64(false, LLDB_INVALID_ADDRESS);2707 if (addr == LLDB_INVALID_ADDRESS)2708 return SendIllFormedResponse(packet, "Address not valid");2709 2710 if (llvm::Error Err = m_current_process->DeallocateMemory(addr))2711 return SendErrorResponse(std::move(Err));2712 2713 return SendOKResponse();2714}2715 2716GDBRemoteCommunication::PacketResult2717GDBRemoteCommunicationServerLLGS::Handle_M(StringExtractorGDBRemote &packet) {2718 Log *log = GetLog(LLDBLog::Process);2719 2720 if (!m_current_process ||2721 (m_current_process->GetID() == LLDB_INVALID_PROCESS_ID)) {2722 LLDB_LOGF(2723 log,2724 "GDBRemoteCommunicationServerLLGS::%s failed, no process available",2725 __FUNCTION__);2726 return SendErrorResponse(0x15);2727 }2728 2729 // Parse out the memory address.2730 packet.SetFilePos(strlen("M"));2731 if (packet.GetBytesLeft() < 1)2732 return SendIllFormedResponse(packet, "Too short M packet");2733 2734 // Read the address. Punting on validation.2735 // FIXME replace with Hex U64 read with no default value that fails on failed2736 // read.2737 const lldb::addr_t write_addr = packet.GetHexMaxU64(false, 0);2738 2739 // Validate comma.2740 if ((packet.GetBytesLeft() < 1) || (packet.GetChar() != ','))2741 return SendIllFormedResponse(packet, "Comma sep missing in M packet");2742 2743 // Get # bytes to read.2744 if (packet.GetBytesLeft() < 1)2745 return SendIllFormedResponse(packet, "Length missing in M packet");2746 2747 const uint64_t byte_count = packet.GetHexMaxU64(false, 0);2748 if (byte_count == 0) {2749 LLDB_LOG(log, "nothing to write: zero-length packet");2750 return PacketResult::Success;2751 }2752 2753 // Validate colon.2754 if ((packet.GetBytesLeft() < 1) || (packet.GetChar() != ':'))2755 return SendIllFormedResponse(2756 packet, "Comma sep missing in M packet after byte length");2757 2758 // Allocate the conversion buffer.2759 std::vector<uint8_t> buf(byte_count, 0);2760 if (buf.empty())2761 return SendErrorResponse(0x78);2762 2763 // Convert the hex memory write contents to bytes.2764 StreamGDBRemote response;2765 const uint64_t convert_count = packet.GetHexBytes(buf, 0);2766 if (convert_count != byte_count) {2767 LLDB_LOG(log,2768 "pid {0} mem {1:x}: asked to write {2} bytes, but only found {3} "2769 "to convert.",2770 m_current_process->GetID(), write_addr, byte_count, convert_count);2771 return SendIllFormedResponse(packet, "M content byte length specified did "2772 "not match hex-encoded content "2773 "length");2774 }2775 2776 // Write the process memory.2777 size_t bytes_written = 0;2778 Status error = m_current_process->WriteMemory(write_addr, &buf[0], byte_count,2779 bytes_written);2780 if (error.Fail()) {2781 LLDB_LOG(log, "pid {0} mem {1:x}: failed to write. Error: {2}",2782 m_current_process->GetID(), write_addr, error);2783 return SendErrorResponse(0x09);2784 }2785 2786 if (bytes_written == 0) {2787 LLDB_LOG(log, "pid {0} mem {1:x}: wrote 0 of {2} requested bytes",2788 m_current_process->GetID(), write_addr, byte_count);2789 return SendErrorResponse(0x09);2790 }2791 2792 return SendOKResponse();2793}2794 2795GDBRemoteCommunication::PacketResult2796GDBRemoteCommunicationServerLLGS::Handle_qMemoryRegionInfoSupported(2797 StringExtractorGDBRemote &packet) {2798 Log *log = GetLog(LLDBLog::Process);2799 2800 // Currently only the NativeProcessProtocol knows if it can handle a2801 // qMemoryRegionInfoSupported request, but we're not guaranteed to be2802 // attached to a process. For now we'll assume the client only asks this2803 // when a process is being debugged.2804 2805 // Ensure we have a process running; otherwise, we can't figure this out2806 // since we won't have a NativeProcessProtocol.2807 if (!m_current_process ||2808 (m_current_process->GetID() == LLDB_INVALID_PROCESS_ID)) {2809 LLDB_LOGF(2810 log,2811 "GDBRemoteCommunicationServerLLGS::%s failed, no process available",2812 __FUNCTION__);2813 return SendErrorResponse(0x15);2814 }2815 2816 // Test if we can get any region back when asking for the region around NULL.2817 MemoryRegionInfo region_info;2818 const Status error = m_current_process->GetMemoryRegionInfo(0, region_info);2819 if (error.Fail()) {2820 // We don't support memory region info collection for this2821 // NativeProcessProtocol.2822 return SendUnimplementedResponse("");2823 }2824 2825 return SendOKResponse();2826}2827 2828GDBRemoteCommunication::PacketResult2829GDBRemoteCommunicationServerLLGS::Handle_qMemoryRegionInfo(2830 StringExtractorGDBRemote &packet) {2831 Log *log = GetLog(LLDBLog::Process);2832 2833 // Ensure we have a process.2834 if (!m_current_process ||2835 (m_current_process->GetID() == LLDB_INVALID_PROCESS_ID)) {2836 LLDB_LOGF(2837 log,2838 "GDBRemoteCommunicationServerLLGS::%s failed, no process available",2839 __FUNCTION__);2840 return SendErrorResponse(0x15);2841 }2842 2843 // Parse out the memory address.2844 packet.SetFilePos(strlen("qMemoryRegionInfo:"));2845 if (packet.GetBytesLeft() < 1)2846 return SendIllFormedResponse(packet, "Too short qMemoryRegionInfo: packet");2847 2848 // Read the address. Punting on validation.2849 const lldb::addr_t read_addr = packet.GetHexMaxU64(false, 0);2850 2851 StreamGDBRemote response;2852 2853 // Get the memory region info for the target address.2854 MemoryRegionInfo region_info;2855 const Status error =2856 m_current_process->GetMemoryRegionInfo(read_addr, region_info);2857 if (error.Fail()) {2858 // Return the error message.2859 2860 response.PutCString("error:");2861 response.PutStringAsRawHex8(error.AsCString());2862 response.PutChar(';');2863 } else {2864 // Range start and size.2865 response.Printf("start:%" PRIx64 ";size:%" PRIx64 ";",2866 region_info.GetRange().GetRangeBase(),2867 region_info.GetRange().GetByteSize());2868 2869 // Permissions.2870 if (region_info.GetReadable() || region_info.GetWritable() ||2871 region_info.GetExecutable()) {2872 // Write permissions info.2873 response.PutCString("permissions:");2874 2875 if (region_info.GetReadable())2876 response.PutChar('r');2877 if (region_info.GetWritable())2878 response.PutChar('w');2879 if (region_info.GetExecutable())2880 response.PutChar('x');2881 2882 response.PutChar(';');2883 }2884 2885 // Flags2886 MemoryRegionInfo::OptionalBool memory_tagged =2887 region_info.GetMemoryTagged();2888 MemoryRegionInfo::OptionalBool is_shadow_stack =2889 region_info.IsShadowStack();2890 2891 if (memory_tagged != MemoryRegionInfo::eDontKnow ||2892 is_shadow_stack != MemoryRegionInfo::eDontKnow) {2893 response.PutCString("flags:");2894 // Space is the separator.2895 if (memory_tagged == MemoryRegionInfo::eYes)2896 response.PutCString("mt ");2897 if (is_shadow_stack == MemoryRegionInfo::eYes)2898 response.PutCString("ss ");2899 2900 response.PutChar(';');2901 }2902 2903 // Name2904 ConstString name = region_info.GetName();2905 if (name) {2906 response.PutCString("name:");2907 response.PutStringAsRawHex8(name.GetStringRef());2908 response.PutChar(';');2909 }2910 }2911 2912 return SendPacketNoLock(response.GetString());2913}2914 2915GDBRemoteCommunication::PacketResult2916GDBRemoteCommunicationServerLLGS::Handle_Z(StringExtractorGDBRemote &packet) {2917 // Ensure we have a process.2918 if (!m_current_process ||2919 (m_current_process->GetID() == LLDB_INVALID_PROCESS_ID)) {2920 Log *log = GetLog(LLDBLog::Process);2921 LLDB_LOG(log, "failed, no process available");2922 return SendErrorResponse(0x15);2923 }2924 2925 // Parse out software or hardware breakpoint or watchpoint requested.2926 packet.SetFilePos(strlen("Z"));2927 if (packet.GetBytesLeft() < 1)2928 return SendIllFormedResponse(2929 packet, "Too short Z packet, missing software/hardware specifier");2930 2931 bool want_breakpoint = true;2932 bool want_hardware = false;2933 uint32_t watch_flags = 0;2934 2935 const GDBStoppointType stoppoint_type =2936 GDBStoppointType(packet.GetS32(eStoppointInvalid));2937 switch (stoppoint_type) {2938 case eBreakpointSoftware:2939 want_hardware = false;2940 want_breakpoint = true;2941 break;2942 case eBreakpointHardware:2943 want_hardware = true;2944 want_breakpoint = true;2945 break;2946 case eWatchpointWrite:2947 watch_flags = 1;2948 want_hardware = true;2949 want_breakpoint = false;2950 break;2951 case eWatchpointRead:2952 watch_flags = 2;2953 want_hardware = true;2954 want_breakpoint = false;2955 break;2956 case eWatchpointReadWrite:2957 watch_flags = 3;2958 want_hardware = true;2959 want_breakpoint = false;2960 break;2961 case eStoppointInvalid:2962 return SendIllFormedResponse(2963 packet, "Z packet had invalid software/hardware specifier");2964 }2965 2966 if ((packet.GetBytesLeft() < 1) || packet.GetChar() != ',')2967 return SendIllFormedResponse(2968 packet, "Malformed Z packet, expecting comma after stoppoint type");2969 2970 // Parse out the stoppoint address.2971 if (packet.GetBytesLeft() < 1)2972 return SendIllFormedResponse(packet, "Too short Z packet, missing address");2973 const lldb::addr_t addr = packet.GetHexMaxU64(false, 0);2974 2975 if ((packet.GetBytesLeft() < 1) || packet.GetChar() != ',')2976 return SendIllFormedResponse(2977 packet, "Malformed Z packet, expecting comma after address");2978 2979 // Parse out the stoppoint size (i.e. size hint for opcode size).2980 const uint32_t size =2981 packet.GetHexMaxU32(false, std::numeric_limits<uint32_t>::max());2982 if (size == std::numeric_limits<uint32_t>::max())2983 return SendIllFormedResponse(2984 packet, "Malformed Z packet, failed to parse size argument");2985 2986 if (want_breakpoint) {2987 // Try to set the breakpoint.2988 const Status error =2989 m_current_process->SetBreakpoint(addr, size, want_hardware);2990 if (error.Success())2991 return SendOKResponse();2992 Log *log = GetLog(LLDBLog::Breakpoints);2993 LLDB_LOG(log, "pid {0} failed to set breakpoint: {1}",2994 m_current_process->GetID(), error);2995 return SendErrorResponse(0x09);2996 } else {2997 // Try to set the watchpoint.2998 const Status error = m_current_process->SetWatchpoint(2999 addr, size, watch_flags, want_hardware);3000 if (error.Success())3001 return SendOKResponse();3002 Log *log = GetLog(LLDBLog::Watchpoints);3003 LLDB_LOG(log, "pid {0} failed to set watchpoint: {1}",3004 m_current_process->GetID(), error);3005 return SendErrorResponse(0x09);3006 }3007}3008 3009GDBRemoteCommunication::PacketResult3010GDBRemoteCommunicationServerLLGS::Handle_z(StringExtractorGDBRemote &packet) {3011 // Ensure we have a process.3012 if (!m_current_process ||3013 (m_current_process->GetID() == LLDB_INVALID_PROCESS_ID)) {3014 Log *log = GetLog(LLDBLog::Process);3015 LLDB_LOG(log, "failed, no process available");3016 return SendErrorResponse(0x15);3017 }3018 3019 // Parse out software or hardware breakpoint or watchpoint requested.3020 packet.SetFilePos(strlen("z"));3021 if (packet.GetBytesLeft() < 1)3022 return SendIllFormedResponse(3023 packet, "Too short z packet, missing software/hardware specifier");3024 3025 bool want_breakpoint = true;3026 bool want_hardware = false;3027 3028 const GDBStoppointType stoppoint_type =3029 GDBStoppointType(packet.GetS32(eStoppointInvalid));3030 switch (stoppoint_type) {3031 case eBreakpointHardware:3032 want_breakpoint = true;3033 want_hardware = true;3034 break;3035 case eBreakpointSoftware:3036 want_breakpoint = true;3037 break;3038 case eWatchpointWrite:3039 want_breakpoint = false;3040 break;3041 case eWatchpointRead:3042 want_breakpoint = false;3043 break;3044 case eWatchpointReadWrite:3045 want_breakpoint = false;3046 break;3047 default:3048 return SendIllFormedResponse(3049 packet, "z packet had invalid software/hardware specifier");3050 }3051 3052 if ((packet.GetBytesLeft() < 1) || packet.GetChar() != ',')3053 return SendIllFormedResponse(3054 packet, "Malformed z packet, expecting comma after stoppoint type");3055 3056 // Parse out the stoppoint address.3057 if (packet.GetBytesLeft() < 1)3058 return SendIllFormedResponse(packet, "Too short z packet, missing address");3059 const lldb::addr_t addr = packet.GetHexMaxU64(false, 0);3060 3061 if ((packet.GetBytesLeft() < 1) || packet.GetChar() != ',')3062 return SendIllFormedResponse(3063 packet, "Malformed z packet, expecting comma after address");3064 3065 /*3066 // Parse out the stoppoint size (i.e. size hint for opcode size).3067 const uint32_t size = packet.GetHexMaxU32 (false,3068 std::numeric_limits<uint32_t>::max ());3069 if (size == std::numeric_limits<uint32_t>::max ())3070 return SendIllFormedResponse(packet, "Malformed z packet, failed to parse3071 size argument");3072 */3073 3074 if (want_breakpoint) {3075 // Try to clear the breakpoint.3076 const Status error =3077 m_current_process->RemoveBreakpoint(addr, want_hardware);3078 if (error.Success())3079 return SendOKResponse();3080 Log *log = GetLog(LLDBLog::Breakpoints);3081 LLDB_LOG(log, "pid {0} failed to remove breakpoint: {1}",3082 m_current_process->GetID(), error);3083 return SendErrorResponse(0x09);3084 } else {3085 // Try to clear the watchpoint.3086 const Status error = m_current_process->RemoveWatchpoint(addr);3087 if (error.Success())3088 return SendOKResponse();3089 Log *log = GetLog(LLDBLog::Watchpoints);3090 LLDB_LOG(log, "pid {0} failed to remove watchpoint: {1}",3091 m_current_process->GetID(), error);3092 return SendErrorResponse(0x09);3093 }3094}3095 3096GDBRemoteCommunication::PacketResult3097GDBRemoteCommunicationServerLLGS::Handle_s(StringExtractorGDBRemote &packet) {3098 Log *log = GetLog(LLDBLog::Process | LLDBLog::Thread);3099 3100 // Ensure we have a process.3101 if (!m_continue_process ||3102 (m_continue_process->GetID() == LLDB_INVALID_PROCESS_ID)) {3103 LLDB_LOGF(3104 log,3105 "GDBRemoteCommunicationServerLLGS::%s failed, no process available",3106 __FUNCTION__);3107 return SendErrorResponse(0x32);3108 }3109 3110 // We first try to use a continue thread id. If any one or any all set, use3111 // the current thread. Bail out if we don't have a thread id.3112 lldb::tid_t tid = GetContinueThreadID();3113 if (tid == 0 || tid == LLDB_INVALID_THREAD_ID)3114 tid = GetCurrentThreadID();3115 if (tid == LLDB_INVALID_THREAD_ID)3116 return SendErrorResponse(0x33);3117 3118 // Double check that we have such a thread.3119 // TODO investigate: on MacOSX we might need to do an UpdateThreads () here.3120 NativeThreadProtocol *thread = m_continue_process->GetThreadByID(tid);3121 if (!thread)3122 return SendErrorResponse(0x33);3123 3124 // Create the step action for the given thread.3125 ResumeAction action = {tid, eStateStepping, LLDB_INVALID_SIGNAL_NUMBER};3126 3127 // Setup the actions list.3128 ResumeActionList actions;3129 actions.Append(action);3130 3131 // All other threads stop while we're single stepping a thread.3132 actions.SetDefaultThreadActionIfNeeded(eStateStopped, 0);3133 3134 PacketResult resume_res = ResumeProcess(*m_continue_process, actions);3135 if (resume_res != PacketResult::Success)3136 return resume_res;3137 3138 // No response here, unless in non-stop mode.3139 // Otherwise, the stop or exit will come from the resulting action.3140 return SendContinueSuccessResponse();3141}3142 3143llvm::Expected<std::unique_ptr<llvm::MemoryBuffer>>3144GDBRemoteCommunicationServerLLGS::BuildTargetXml() {3145 // Ensure we have a thread.3146 NativeThreadProtocol *thread = m_current_process->GetThreadAtIndex(0);3147 if (!thread)3148 return llvm::createStringError(llvm::inconvertibleErrorCode(),3149 "No thread available");3150 3151 Log *log = GetLog(LLDBLog::Process | LLDBLog::Thread);3152 // Get the register context for the first thread.3153 NativeRegisterContext ®_context = thread->GetRegisterContext();3154 3155 StreamString response;3156 3157 response.Printf("<?xml version=\"1.0\"?>\n");3158 response.Printf("<target version=\"1.0\">\n");3159 response.IndentMore();3160 3161 response.Indent();3162 response.Printf("<architecture>%s</architecture>\n",3163 m_current_process->GetArchitecture()3164 .GetTriple()3165 .getArchName()3166 .str()3167 .c_str());3168 3169 response.Indent("<feature>\n");3170 3171 const int registers_count = reg_context.GetUserRegisterCount();3172 if (registers_count)3173 response.IndentMore();3174 3175 llvm::StringSet<> field_enums_seen;3176 for (int reg_index = 0; reg_index < registers_count; reg_index++) {3177 const RegisterInfo *reg_info =3178 reg_context.GetRegisterInfoAtIndex(reg_index);3179 3180 if (!reg_info) {3181 LLDB_LOGF(log,3182 "%s failed to get register info for register index %" PRIu32,3183 "target.xml", reg_index);3184 continue;3185 }3186 3187 if (reg_info->flags_type) {3188 response.IndentMore();3189 reg_info->flags_type->EnumsToXML(response, field_enums_seen);3190 reg_info->flags_type->ToXML(response);3191 response.IndentLess();3192 }3193 3194 response.Indent();3195 response.Printf("<reg name=\"%s\" bitsize=\"%" PRIu323196 "\" regnum=\"%d\" ",3197 reg_info->name, reg_info->byte_size * 8, reg_index);3198 3199 if (!reg_context.RegisterOffsetIsDynamic())3200 response.Printf("offset=\"%" PRIu32 "\" ", reg_info->byte_offset);3201 3202 if (reg_info->alt_name && reg_info->alt_name[0])3203 response.Printf("altname=\"%s\" ", reg_info->alt_name);3204 3205 llvm::StringRef encoding = GetEncodingNameOrEmpty(*reg_info);3206 if (!encoding.empty())3207 response << "encoding=\"" << encoding << "\" ";3208 3209 llvm::StringRef format = GetFormatNameOrEmpty(*reg_info);3210 if (!format.empty())3211 response << "format=\"" << format << "\" ";3212 3213 if (reg_info->flags_type)3214 response << "type=\"" << reg_info->flags_type->GetID() << "\" ";3215 3216 const char *const register_set_name =3217 reg_context.GetRegisterSetNameForRegisterAtIndex(reg_index);3218 if (register_set_name)3219 response << "group=\"" << register_set_name << "\" ";3220 3221 if (reg_info->kinds[RegisterKind::eRegisterKindEHFrame] !=3222 LLDB_INVALID_REGNUM)3223 response.Printf("ehframe_regnum=\"%" PRIu32 "\" ",3224 reg_info->kinds[RegisterKind::eRegisterKindEHFrame]);3225 3226 if (reg_info->kinds[RegisterKind::eRegisterKindDWARF] !=3227 LLDB_INVALID_REGNUM)3228 response.Printf("dwarf_regnum=\"%" PRIu32 "\" ",3229 reg_info->kinds[RegisterKind::eRegisterKindDWARF]);3230 3231 llvm::StringRef kind_generic = GetKindGenericOrEmpty(*reg_info);3232 if (!kind_generic.empty())3233 response << "generic=\"" << kind_generic << "\" ";3234 3235 if (reg_info->value_regs &&3236 reg_info->value_regs[0] != LLDB_INVALID_REGNUM) {3237 response.PutCString("value_regnums=\"");3238 CollectRegNums(reg_info->value_regs, response, false);3239 response.Printf("\" ");3240 }3241 3242 if (reg_info->invalidate_regs && reg_info->invalidate_regs[0]) {3243 response.PutCString("invalidate_regnums=\"");3244 CollectRegNums(reg_info->invalidate_regs, response, false);3245 response.Printf("\" ");3246 }3247 3248 response.Printf("/>\n");3249 }3250 3251 if (registers_count)3252 response.IndentLess();3253 3254 response.Indent("</feature>\n");3255 response.IndentLess();3256 response.Indent("</target>\n");3257 return MemoryBuffer::getMemBufferCopy(response.GetString(), "target.xml");3258}3259 3260llvm::Expected<std::unique_ptr<llvm::MemoryBuffer>>3261GDBRemoteCommunicationServerLLGS::ReadXferObject(llvm::StringRef object,3262 llvm::StringRef annex) {3263 // Make sure we have a valid process.3264 if (!m_current_process ||3265 (m_current_process->GetID() == LLDB_INVALID_PROCESS_ID)) {3266 return llvm::createStringError(llvm::inconvertibleErrorCode(),3267 "No process available");3268 }3269 3270 if (object == "auxv") {3271 // Grab the auxv data.3272 auto buffer_or_error = m_current_process->GetAuxvData();3273 if (!buffer_or_error)3274 return llvm::errorCodeToError(buffer_or_error.getError());3275 return std::move(*buffer_or_error);3276 }3277 3278 if (object == "siginfo") {3279 NativeThreadProtocol *thread = m_current_process->GetCurrentThread();3280 if (!thread)3281 return llvm::createStringError(llvm::inconvertibleErrorCode(),3282 "no current thread");3283 3284 auto buffer_or_error = thread->GetSiginfo();3285 if (!buffer_or_error)3286 return buffer_or_error.takeError();3287 return std::move(*buffer_or_error);3288 }3289 3290 if (object == "libraries-svr4") {3291 auto library_list = m_current_process->GetLoadedSVR4Libraries();3292 if (!library_list)3293 return library_list.takeError();3294 3295 StreamString response;3296 response.Printf("<library-list-svr4 version=\"1.0\">");3297 for (auto const &library : *library_list) {3298 response.Printf("<library name=\"%s\" ",3299 XMLEncodeAttributeValue(library.name.c_str()).c_str());3300 response.Printf("lm=\"0x%" PRIx64 "\" ", library.link_map);3301 response.Printf("l_addr=\"0x%" PRIx64 "\" ", library.base_addr);3302 response.Printf("l_ld=\"0x%" PRIx64 "\" />", library.ld_addr);3303 }3304 response.Printf("</library-list-svr4>");3305 return MemoryBuffer::getMemBufferCopy(response.GetString(), __FUNCTION__);3306 }3307 3308 if (object == "features" && annex == "target.xml")3309 return BuildTargetXml();3310 3311 return llvm::make_error<UnimplementedError>();3312}3313 3314GDBRemoteCommunication::PacketResult3315GDBRemoteCommunicationServerLLGS::Handle_qXfer(3316 StringExtractorGDBRemote &packet) {3317 SmallVector<StringRef, 5> fields;3318 // The packet format is "qXfer:<object>:<action>:<annex>:offset,length"3319 StringRef(packet.GetStringRef()).split(fields, ':', 4);3320 if (fields.size() != 5)3321 return SendIllFormedResponse(packet, "malformed qXfer packet");3322 StringRef &xfer_object = fields[1];3323 StringRef &xfer_action = fields[2];3324 StringRef &xfer_annex = fields[3];3325 StringExtractor offset_data(fields[4]);3326 if (xfer_action != "read")3327 return SendUnimplementedResponse("qXfer action not supported");3328 // Parse offset.3329 const uint64_t xfer_offset =3330 offset_data.GetHexMaxU64(false, std::numeric_limits<uint64_t>::max());3331 if (xfer_offset == std::numeric_limits<uint64_t>::max())3332 return SendIllFormedResponse(packet, "qXfer packet missing offset");3333 // Parse out comma.3334 if (offset_data.GetChar() != ',')3335 return SendIllFormedResponse(packet,3336 "qXfer packet missing comma after offset");3337 // Parse out the length.3338 const uint64_t xfer_length =3339 offset_data.GetHexMaxU64(false, std::numeric_limits<uint64_t>::max());3340 if (xfer_length == std::numeric_limits<uint64_t>::max())3341 return SendIllFormedResponse(packet, "qXfer packet missing length");3342 3343 // Get a previously constructed buffer if it exists or create it now.3344 std::string buffer_key = (xfer_object + xfer_action + xfer_annex).str();3345 auto buffer_it = m_xfer_buffer_map.find(buffer_key);3346 if (buffer_it == m_xfer_buffer_map.end()) {3347 auto buffer_up = ReadXferObject(xfer_object, xfer_annex);3348 if (!buffer_up)3349 return SendErrorResponse(buffer_up.takeError());3350 buffer_it = m_xfer_buffer_map3351 .insert(std::make_pair(buffer_key, std::move(*buffer_up)))3352 .first;3353 }3354 3355 // Send back the response3356 StreamGDBRemote response;3357 bool done_with_buffer = false;3358 llvm::StringRef buffer = buffer_it->second->getBuffer();3359 if (xfer_offset >= buffer.size()) {3360 // We have nothing left to send. Mark the buffer as complete.3361 response.PutChar('l');3362 done_with_buffer = true;3363 } else {3364 // Figure out how many bytes are available starting at the given offset.3365 buffer = buffer.drop_front(xfer_offset);3366 // Mark the response type according to whether we're reading the remainder3367 // of the data.3368 if (xfer_length >= buffer.size()) {3369 // There will be nothing left to read after this3370 response.PutChar('l');3371 done_with_buffer = true;3372 } else {3373 // There will still be bytes to read after this request.3374 response.PutChar('m');3375 buffer = buffer.take_front(xfer_length);3376 }3377 // Now write the data in encoded binary form.3378 response.PutEscapedBytes(buffer.data(), buffer.size());3379 }3380 3381 if (done_with_buffer)3382 m_xfer_buffer_map.erase(buffer_it);3383 3384 return SendPacketNoLock(response.GetString());3385}3386 3387GDBRemoteCommunication::PacketResult3388GDBRemoteCommunicationServerLLGS::Handle_QSaveRegisterState(3389 StringExtractorGDBRemote &packet) {3390 Log *log = GetLog(LLDBLog::Thread);3391 3392 // Move past packet name.3393 packet.SetFilePos(strlen("QSaveRegisterState"));3394 3395 // Get the thread to use.3396 NativeThreadProtocol *thread = GetThreadFromSuffix(packet);3397 if (!thread) {3398 if (m_thread_suffix_supported)3399 return SendIllFormedResponse(3400 packet, "No thread specified in QSaveRegisterState packet");3401 else3402 return SendIllFormedResponse(packet,3403 "No thread was is set with the Hg packet");3404 }3405 3406 // Grab the register context for the thread.3407 NativeRegisterContext& reg_context = thread->GetRegisterContext();3408 3409 // Save registers to a buffer.3410 WritableDataBufferSP register_data_sp;3411 Status error = reg_context.ReadAllRegisterValues(register_data_sp);3412 if (error.Fail()) {3413 LLDB_LOG(log, "pid {0} failed to save all register values: {1}",3414 m_current_process->GetID(), error);3415 return SendErrorResponse(0x75);3416 }3417 3418 // Allocate a new save id.3419 const uint32_t save_id = GetNextSavedRegistersID();3420 assert((m_saved_registers_map.find(save_id) == m_saved_registers_map.end()) &&3421 "GetNextRegisterSaveID() returned an existing register save id");3422 3423 // Save the register data buffer under the save id.3424 {3425 std::lock_guard<std::mutex> guard(m_saved_registers_mutex);3426 m_saved_registers_map[save_id] = register_data_sp;3427 }3428 3429 // Write the response.3430 StreamGDBRemote response;3431 response.Printf("%" PRIu32, save_id);3432 return SendPacketNoLock(response.GetString());3433}3434 3435GDBRemoteCommunication::PacketResult3436GDBRemoteCommunicationServerLLGS::Handle_QRestoreRegisterState(3437 StringExtractorGDBRemote &packet) {3438 Log *log = GetLog(LLDBLog::Thread);3439 3440 // Parse out save id.3441 packet.SetFilePos(strlen("QRestoreRegisterState:"));3442 if (packet.GetBytesLeft() < 1)3443 return SendIllFormedResponse(3444 packet, "QRestoreRegisterState packet missing register save id");3445 3446 const uint32_t save_id = packet.GetU32(0);3447 if (save_id == 0) {3448 LLDB_LOG(log, "QRestoreRegisterState packet has malformed save id, "3449 "expecting decimal uint32_t");3450 return SendErrorResponse(0x76);3451 }3452 3453 // Get the thread to use.3454 NativeThreadProtocol *thread = GetThreadFromSuffix(packet);3455 if (!thread) {3456 if (m_thread_suffix_supported)3457 return SendIllFormedResponse(3458 packet, "No thread specified in QRestoreRegisterState packet");3459 else3460 return SendIllFormedResponse(packet,3461 "No thread was is set with the Hg packet");3462 }3463 3464 // Grab the register context for the thread.3465 NativeRegisterContext ®_context = thread->GetRegisterContext();3466 3467 // Retrieve register state buffer, then remove from the list.3468 DataBufferSP register_data_sp;3469 {3470 std::lock_guard<std::mutex> guard(m_saved_registers_mutex);3471 3472 // Find the register set buffer for the given save id.3473 auto it = m_saved_registers_map.find(save_id);3474 if (it == m_saved_registers_map.end()) {3475 LLDB_LOG(log,3476 "pid {0} does not have a register set save buffer for id {1}",3477 m_current_process->GetID(), save_id);3478 return SendErrorResponse(0x77);3479 }3480 register_data_sp = it->second;3481 3482 // Remove it from the map.3483 m_saved_registers_map.erase(it);3484 }3485 3486 Status error = reg_context.WriteAllRegisterValues(register_data_sp);3487 if (error.Fail()) {3488 LLDB_LOG(log, "pid {0} failed to restore all register values: {1}",3489 m_current_process->GetID(), error);3490 return SendErrorResponse(0x77);3491 }3492 3493 return SendOKResponse();3494}3495 3496GDBRemoteCommunication::PacketResult3497GDBRemoteCommunicationServerLLGS::Handle_vAttach(3498 StringExtractorGDBRemote &packet) {3499 Log *log = GetLog(LLDBLog::Process);3500 3501 // Consume the ';' after vAttach.3502 packet.SetFilePos(strlen("vAttach"));3503 if (!packet.GetBytesLeft() || packet.GetChar() != ';')3504 return SendIllFormedResponse(packet, "vAttach missing expected ';'");3505 3506 // Grab the PID to which we will attach (assume hex encoding).3507 lldb::pid_t pid = packet.GetU32(LLDB_INVALID_PROCESS_ID, 16);3508 if (pid == LLDB_INVALID_PROCESS_ID)3509 return SendIllFormedResponse(packet,3510 "vAttach failed to parse the process id");3511 3512 // Attempt to attach.3513 LLDB_LOGF(log,3514 "GDBRemoteCommunicationServerLLGS::%s attempting to attach to "3515 "pid %" PRIu64,3516 __FUNCTION__, pid);3517 3518 Status error = AttachToProcess(pid);3519 3520 if (error.Fail()) {3521 LLDB_LOGF(log,3522 "GDBRemoteCommunicationServerLLGS::%s failed to attach to "3523 "pid %" PRIu64 ": %s\n",3524 __FUNCTION__, pid, error.AsCString());3525 return SendErrorResponse(error);3526 }3527 3528 // Notify we attached by sending a stop packet.3529 assert(m_current_process);3530 return SendStopReasonForState(*m_current_process,3531 m_current_process->GetState(),3532 /*force_synchronous=*/false);3533}3534 3535GDBRemoteCommunication::PacketResult3536GDBRemoteCommunicationServerLLGS::Handle_vAttachWait(3537 StringExtractorGDBRemote &packet) {3538 Log *log = GetLog(LLDBLog::Process);3539 3540 // Consume the ';' after the identifier.3541 packet.SetFilePos(strlen("vAttachWait"));3542 3543 if (!packet.GetBytesLeft() || packet.GetChar() != ';')3544 return SendIllFormedResponse(packet, "vAttachWait missing expected ';'");3545 3546 // Allocate the buffer for the process name from vAttachWait.3547 std::string process_name;3548 if (!packet.GetHexByteString(process_name))3549 return SendIllFormedResponse(packet,3550 "vAttachWait failed to parse process name");3551 3552 LLDB_LOG(log, "attempting to attach to process named '{0}'", process_name);3553 3554 Status error = AttachWaitProcess(process_name, false);3555 if (error.Fail()) {3556 LLDB_LOG(log, "failed to attach to process named '{0}': {1}", process_name,3557 error);3558 return SendErrorResponse(error);3559 }3560 3561 // Notify we attached by sending a stop packet.3562 assert(m_current_process);3563 return SendStopReasonForState(*m_current_process,3564 m_current_process->GetState(),3565 /*force_synchronous=*/false);3566}3567 3568GDBRemoteCommunication::PacketResult3569GDBRemoteCommunicationServerLLGS::Handle_qVAttachOrWaitSupported(3570 StringExtractorGDBRemote &packet) {3571 return SendOKResponse();3572}3573 3574GDBRemoteCommunication::PacketResult3575GDBRemoteCommunicationServerLLGS::Handle_vAttachOrWait(3576 StringExtractorGDBRemote &packet) {3577 Log *log = GetLog(LLDBLog::Process);3578 3579 // Consume the ';' after the identifier.3580 packet.SetFilePos(strlen("vAttachOrWait"));3581 3582 if (!packet.GetBytesLeft() || packet.GetChar() != ';')3583 return SendIllFormedResponse(packet, "vAttachOrWait missing expected ';'");3584 3585 // Allocate the buffer for the process name from vAttachWait.3586 std::string process_name;3587 if (!packet.GetHexByteString(process_name))3588 return SendIllFormedResponse(packet,3589 "vAttachOrWait failed to parse process name");3590 3591 LLDB_LOG(log, "attempting to attach to process named '{0}'", process_name);3592 3593 Status error = AttachWaitProcess(process_name, true);3594 if (error.Fail()) {3595 LLDB_LOG(log, "failed to attach to process named '{0}': {1}", process_name,3596 error);3597 return SendErrorResponse(error);3598 }3599 3600 // Notify we attached by sending a stop packet.3601 assert(m_current_process);3602 return SendStopReasonForState(*m_current_process,3603 m_current_process->GetState(),3604 /*force_synchronous=*/false);3605}3606 3607GDBRemoteCommunication::PacketResult3608GDBRemoteCommunicationServerLLGS::Handle_vRun(3609 StringExtractorGDBRemote &packet) {3610 Log *log = GetLog(LLDBLog::Process);3611 3612 llvm::StringRef s = packet.GetStringRef();3613 if (!s.consume_front("vRun;"))3614 return SendErrorResponse(8);3615 3616 llvm::SmallVector<llvm::StringRef, 16> argv;3617 s.split(argv, ';');3618 3619 for (llvm::StringRef hex_arg : argv) {3620 StringExtractor arg_ext{hex_arg};3621 std::string arg;3622 arg_ext.GetHexByteString(arg);3623 m_process_launch_info.GetArguments().AppendArgument(arg);3624 LLDB_LOGF(log, "LLGSPacketHandler::%s added arg: \"%s\"", __FUNCTION__,3625 arg.c_str());3626 }3627 3628 if (argv.empty())3629 return SendErrorResponse(Status::FromErrorString("No arguments"));3630 m_process_launch_info.GetExecutableFile().SetFile(3631 m_process_launch_info.GetArguments()[0].ref(), FileSpec::Style::native);3632 m_process_launch_error = LaunchProcess();3633 if (m_process_launch_error.Fail())3634 return SendErrorResponse(m_process_launch_error);3635 assert(m_current_process);3636 return SendStopReasonForState(*m_current_process,3637 m_current_process->GetState(),3638 /*force_synchronous=*/true);3639}3640 3641GDBRemoteCommunication::PacketResult3642GDBRemoteCommunicationServerLLGS::Handle_D(StringExtractorGDBRemote &packet) {3643 Log *log = GetLog(LLDBLog::Process);3644 if (!m_non_stop)3645 StopSTDIOForwarding();3646 3647 lldb::pid_t pid = LLDB_INVALID_PROCESS_ID;3648 3649 // Consume the ';' after D.3650 packet.SetFilePos(1);3651 if (packet.GetBytesLeft()) {3652 if (packet.GetChar() != ';')3653 return SendIllFormedResponse(packet, "D missing expected ';'");3654 3655 // Grab the PID from which we will detach (assume hex encoding).3656 pid = packet.GetU32(LLDB_INVALID_PROCESS_ID, 16);3657 if (pid == LLDB_INVALID_PROCESS_ID)3658 return SendIllFormedResponse(packet, "D failed to parse the process id");3659 }3660 3661 // Detach forked children if their PID was specified *or* no PID was requested3662 // (i.e. detach-all packet).3663 llvm::Error detach_error = llvm::Error::success();3664 bool detached = false;3665 for (auto it = m_debugged_processes.begin();3666 it != m_debugged_processes.end();) {3667 if (pid == LLDB_INVALID_PROCESS_ID || pid == it->first) {3668 LLDB_LOGF(log,3669 "GDBRemoteCommunicationServerLLGS::%s detaching %" PRId64,3670 __FUNCTION__, it->first);3671 if (llvm::Error e = it->second.process_up->Detach().ToError())3672 detach_error = llvm::joinErrors(std::move(detach_error), std::move(e));3673 else {3674 if (it->second.process_up.get() == m_current_process)3675 m_current_process = nullptr;3676 if (it->second.process_up.get() == m_continue_process)3677 m_continue_process = nullptr;3678 it = m_debugged_processes.erase(it);3679 detached = true;3680 continue;3681 }3682 }3683 ++it;3684 }3685 3686 if (detach_error)3687 return SendErrorResponse(std::move(detach_error));3688 if (!detached)3689 return SendErrorResponse(3690 Status::FromErrorStringWithFormat("PID %" PRIu64 " not traced", pid));3691 return SendOKResponse();3692}3693 3694GDBRemoteCommunication::PacketResult3695GDBRemoteCommunicationServerLLGS::Handle_qThreadStopInfo(3696 StringExtractorGDBRemote &packet) {3697 Log *log = GetLog(LLDBLog::Thread);3698 3699 if (!m_current_process ||3700 (m_current_process->GetID() == LLDB_INVALID_PROCESS_ID))3701 return SendErrorResponse(50);3702 3703 packet.SetFilePos(strlen("qThreadStopInfo"));3704 const lldb::tid_t tid = packet.GetHexMaxU64(false, LLDB_INVALID_THREAD_ID);3705 if (tid == LLDB_INVALID_THREAD_ID) {3706 LLDB_LOGF(log,3707 "GDBRemoteCommunicationServerLLGS::%s failed, could not "3708 "parse thread id from request \"%s\"",3709 __FUNCTION__, packet.GetStringRef().data());3710 return SendErrorResponse(0x15);3711 }3712 return SendStopReplyPacketForThread(*m_current_process, tid,3713 /*force_synchronous=*/true);3714}3715 3716GDBRemoteCommunication::PacketResult3717GDBRemoteCommunicationServerLLGS::Handle_jThreadsInfo(3718 StringExtractorGDBRemote &) {3719 Log *log = GetLog(LLDBLog::Process | LLDBLog::Thread);3720 3721 // Ensure we have a debugged process.3722 if (!m_current_process ||3723 (m_current_process->GetID() == LLDB_INVALID_PROCESS_ID))3724 return SendErrorResponse(50);3725 LLDB_LOG(log, "preparing packet for pid {0}", m_current_process->GetID());3726 3727 StreamString response;3728 const bool threads_with_valid_stop_info_only = false;3729 llvm::Expected<json::Value> threads_info =3730 GetJSONThreadsInfo(*m_current_process, threads_with_valid_stop_info_only);3731 if (!threads_info) {3732 LLDB_LOG_ERROR(log, threads_info.takeError(),3733 "failed to prepare a packet for pid {1}: {0}",3734 m_current_process->GetID());3735 return SendErrorResponse(52);3736 }3737 3738 response.AsRawOstream() << *threads_info;3739 StreamGDBRemote escaped_response;3740 escaped_response.PutEscapedBytes(response.GetData(), response.GetSize());3741 return SendPacketNoLock(escaped_response.GetString());3742}3743 3744GDBRemoteCommunication::PacketResult3745GDBRemoteCommunicationServerLLGS::Handle_qWatchpointSupportInfo(3746 StringExtractorGDBRemote &packet) {3747 // Fail if we don't have a current process.3748 if (!m_current_process ||3749 m_current_process->GetID() == LLDB_INVALID_PROCESS_ID)3750 return SendErrorResponse(68);3751 3752 packet.SetFilePos(strlen("qWatchpointSupportInfo"));3753 if (packet.GetBytesLeft() == 0)3754 return SendOKResponse();3755 if (packet.GetChar() != ':')3756 return SendErrorResponse(67);3757 3758 auto hw_debug_cap = m_current_process->GetHardwareDebugSupportInfo();3759 3760 StreamGDBRemote response;3761 if (hw_debug_cap == std::nullopt)3762 response.Printf("num:0;");3763 else3764 response.Printf("num:%d;", hw_debug_cap->second);3765 3766 return SendPacketNoLock(response.GetString());3767}3768 3769GDBRemoteCommunication::PacketResult3770GDBRemoteCommunicationServerLLGS::Handle_qFileLoadAddress(3771 StringExtractorGDBRemote &packet) {3772 // Fail if we don't have a current process.3773 if (!m_current_process ||3774 m_current_process->GetID() == LLDB_INVALID_PROCESS_ID)3775 return SendErrorResponse(67);3776 3777 packet.SetFilePos(strlen("qFileLoadAddress:"));3778 if (packet.GetBytesLeft() == 0)3779 return SendErrorResponse(68);3780 3781 std::string file_name;3782 packet.GetHexByteString(file_name);3783 3784 lldb::addr_t file_load_address = LLDB_INVALID_ADDRESS;3785 Status error =3786 m_current_process->GetFileLoadAddress(file_name, file_load_address);3787 if (error.Fail())3788 return SendErrorResponse(69);3789 3790 if (file_load_address == LLDB_INVALID_ADDRESS)3791 return SendErrorResponse(1); // File not loaded3792 3793 StreamGDBRemote response;3794 response.PutHex64(file_load_address);3795 return SendPacketNoLock(response.GetString());3796}3797 3798GDBRemoteCommunication::PacketResult3799GDBRemoteCommunicationServerLLGS::Handle_QPassSignals(3800 StringExtractorGDBRemote &packet) {3801 std::vector<int> signals;3802 packet.SetFilePos(strlen("QPassSignals:"));3803 3804 // Read sequence of hex signal numbers divided by a semicolon and optionally3805 // spaces.3806 while (packet.GetBytesLeft() > 0) {3807 int signal = packet.GetS32(-1, 16);3808 if (signal < 0)3809 return SendIllFormedResponse(packet, "Failed to parse signal number.");3810 signals.push_back(signal);3811 3812 packet.SkipSpaces();3813 char separator = packet.GetChar();3814 if (separator == '\0')3815 break; // End of string3816 if (separator != ';')3817 return SendIllFormedResponse(packet, "Invalid separator,"3818 " expected semicolon.");3819 }3820 3821 // Fail if we don't have a current process.3822 if (!m_current_process)3823 return SendErrorResponse(68);3824 3825 Status error = m_current_process->IgnoreSignals(signals);3826 if (error.Fail())3827 return SendErrorResponse(69);3828 3829 return SendOKResponse();3830}3831 3832GDBRemoteCommunication::PacketResult3833GDBRemoteCommunicationServerLLGS::Handle_qMemTags(3834 StringExtractorGDBRemote &packet) {3835 Log *log = GetLog(LLDBLog::Process);3836 3837 // Ensure we have a process.3838 if (!m_current_process ||3839 (m_current_process->GetID() == LLDB_INVALID_PROCESS_ID)) {3840 LLDB_LOGF(3841 log,3842 "GDBRemoteCommunicationServerLLGS::%s failed, no process available",3843 __FUNCTION__);3844 return SendErrorResponse(1);3845 }3846 3847 // We are expecting3848 // qMemTags:<hex address>,<hex length>:<hex type>3849 3850 // Address3851 packet.SetFilePos(strlen("qMemTags:"));3852 const char *current_char = packet.Peek();3853 if (!current_char || *current_char == ',')3854 return SendIllFormedResponse(packet, "Missing address in qMemTags packet");3855 const lldb::addr_t addr = packet.GetHexMaxU64(/*little_endian=*/false, 0);3856 3857 // Length3858 char previous_char = packet.GetChar();3859 current_char = packet.Peek();3860 // If we don't have a separator or the length field is empty3861 if (previous_char != ',' || (current_char && *current_char == ':'))3862 return SendIllFormedResponse(packet,3863 "Invalid addr,length pair in qMemTags packet");3864 3865 if (packet.GetBytesLeft() < 1)3866 return SendIllFormedResponse(3867 packet, "Too short qMemtags: packet (looking for length)");3868 const size_t length = packet.GetHexMaxU64(/*little_endian=*/false, 0);3869 3870 // Type3871 const char *invalid_type_err = "Invalid type field in qMemTags: packet";3872 if (packet.GetBytesLeft() < 1 || packet.GetChar() != ':')3873 return SendIllFormedResponse(packet, invalid_type_err);3874 3875 // Type is a signed integer but packed into the packet as its raw bytes.3876 // However, our GetU64 uses strtoull which allows +/-. We do not want this.3877 const char *first_type_char = packet.Peek();3878 if (first_type_char && (*first_type_char == '+' || *first_type_char == '-'))3879 return SendIllFormedResponse(packet, invalid_type_err);3880 3881 // Extract type as unsigned then cast to signed.3882 // Using a uint64_t here so that we have some value outside of the 32 bit3883 // range to use as the invalid return value.3884 uint64_t raw_type =3885 packet.GetU64(std::numeric_limits<uint64_t>::max(), /*base=*/16);3886 3887 if ( // Make sure the cast below would be valid3888 raw_type > std::numeric_limits<uint32_t>::max() ||3889 // To catch inputs like "123aardvark" that will parse but clearly aren't3890 // valid in this case.3891 packet.GetBytesLeft()) {3892 return SendIllFormedResponse(packet, invalid_type_err);3893 }3894 3895 // First narrow to 32 bits otherwise the copy into type would take3896 // the wrong 4 bytes on big endian.3897 uint32_t raw_type_32 = raw_type;3898 int32_t type = reinterpret_cast<int32_t &>(raw_type_32);3899 3900 StreamGDBRemote response;3901 std::vector<uint8_t> tags;3902 Status error = m_current_process->ReadMemoryTags(type, addr, length, tags);3903 if (error.Fail())3904 return SendErrorResponse(1);3905 3906 // This m is here in case we want to support multi part replies in the future.3907 // In the same manner as qfThreadInfo/qsThreadInfo.3908 response.PutChar('m');3909 response.PutBytesAsRawHex8(tags.data(), tags.size());3910 return SendPacketNoLock(response.GetString());3911}3912 3913GDBRemoteCommunication::PacketResult3914GDBRemoteCommunicationServerLLGS::Handle_QMemTags(3915 StringExtractorGDBRemote &packet) {3916 Log *log = GetLog(LLDBLog::Process);3917 3918 // Ensure we have a process.3919 if (!m_current_process ||3920 (m_current_process->GetID() == LLDB_INVALID_PROCESS_ID)) {3921 LLDB_LOGF(3922 log,3923 "GDBRemoteCommunicationServerLLGS::%s failed, no process available",3924 __FUNCTION__);3925 return SendErrorResponse(1);3926 }3927 3928 // We are expecting3929 // QMemTags:<hex address>,<hex length>:<hex type>:<tags as hex bytes>3930 3931 // Address3932 packet.SetFilePos(strlen("QMemTags:"));3933 const char *current_char = packet.Peek();3934 if (!current_char || *current_char == ',')3935 return SendIllFormedResponse(packet, "Missing address in QMemTags packet");3936 const lldb::addr_t addr = packet.GetHexMaxU64(/*little_endian=*/false, 0);3937 3938 // Length3939 char previous_char = packet.GetChar();3940 current_char = packet.Peek();3941 // If we don't have a separator or the length field is empty3942 if (previous_char != ',' || (current_char && *current_char == ':'))3943 return SendIllFormedResponse(packet,3944 "Invalid addr,length pair in QMemTags packet");3945 3946 if (packet.GetBytesLeft() < 1)3947 return SendIllFormedResponse(3948 packet, "Too short QMemtags: packet (looking for length)");3949 const size_t length = packet.GetHexMaxU64(/*little_endian=*/false, 0);3950 3951 // Type3952 const char *invalid_type_err = "Invalid type field in QMemTags: packet";3953 if (packet.GetBytesLeft() < 1 || packet.GetChar() != ':')3954 return SendIllFormedResponse(packet, invalid_type_err);3955 3956 // Our GetU64 uses strtoull which allows leading +/-, we don't want that.3957 const char *first_type_char = packet.Peek();3958 if (first_type_char && (*first_type_char == '+' || *first_type_char == '-'))3959 return SendIllFormedResponse(packet, invalid_type_err);3960 3961 // The type is a signed integer but is in the packet as its raw bytes.3962 // So parse first as unsigned then cast to signed later.3963 // We extract to 64 bit, even though we only expect 32, so that we've3964 // got some invalid value we can check for.3965 uint64_t raw_type =3966 packet.GetU64(std::numeric_limits<uint64_t>::max(), /*base=*/16);3967 if (raw_type > std::numeric_limits<uint32_t>::max())3968 return SendIllFormedResponse(packet, invalid_type_err);3969 3970 // First narrow to 32 bits. Otherwise the copy below would get the wrong3971 // 4 bytes on big endian.3972 uint32_t raw_type_32 = raw_type;3973 int32_t type = reinterpret_cast<int32_t &>(raw_type_32);3974 3975 // Tag data3976 if (packet.GetBytesLeft() < 1 || packet.GetChar() != ':')3977 return SendIllFormedResponse(packet,3978 "Missing tag data in QMemTags: packet");3979 3980 // Must be 2 chars per byte3981 const char *invalid_data_err = "Invalid tag data in QMemTags: packet";3982 if (packet.GetBytesLeft() % 2)3983 return SendIllFormedResponse(packet, invalid_data_err);3984 3985 // This is bytes here and is unpacked into target specific tags later3986 // We cannot assume that number of bytes == length here because the server3987 // can repeat tags to fill a given range.3988 std::vector<uint8_t> tag_data;3989 // Zero length writes will not have any tag data3990 // (but we pass them on because it will still check that tagging is enabled)3991 if (packet.GetBytesLeft()) {3992 size_t byte_count = packet.GetBytesLeft() / 2;3993 tag_data.resize(byte_count);3994 size_t converted_bytes = packet.GetHexBytes(tag_data, 0);3995 if (converted_bytes != byte_count) {3996 return SendIllFormedResponse(packet, invalid_data_err);3997 }3998 }3999 4000 Status status =4001 m_current_process->WriteMemoryTags(type, addr, length, tag_data);4002 return status.Success() ? SendOKResponse() : SendErrorResponse(1);4003}4004 4005GDBRemoteCommunication::PacketResult4006GDBRemoteCommunicationServerLLGS::Handle_qSaveCore(4007 StringExtractorGDBRemote &packet) {4008 // Fail if we don't have a current process.4009 if (!m_current_process ||4010 (m_current_process->GetID() == LLDB_INVALID_PROCESS_ID))4011 return SendErrorResponse(Status::FromErrorString("Process not running."));4012 4013 std::string path_hint;4014 4015 StringRef packet_str{packet.GetStringRef()};4016 assert(packet_str.starts_with("qSaveCore"));4017 if (packet_str.consume_front("qSaveCore;")) {4018 for (auto x : llvm::split(packet_str, ';')) {4019 if (x.consume_front("path-hint:"))4020 StringExtractor(x).GetHexByteString(path_hint);4021 else4022 return SendErrorResponse(4023 Status::FromErrorString("Unsupported qSaveCore option"));4024 }4025 }4026 4027 llvm::Expected<std::string> ret = m_current_process->SaveCore(path_hint);4028 if (!ret)4029 return SendErrorResponse(ret.takeError());4030 4031 StreamString response;4032 response.PutCString("core-path:");4033 response.PutStringAsRawHex8(ret.get());4034 return SendPacketNoLock(response.GetString());4035}4036 4037GDBRemoteCommunication::PacketResult4038GDBRemoteCommunicationServerLLGS::Handle_QNonStop(4039 StringExtractorGDBRemote &packet) {4040 Log *log = GetLog(LLDBLog::Process);4041 4042 StringRef packet_str{packet.GetStringRef()};4043 assert(packet_str.starts_with("QNonStop:"));4044 packet_str.consume_front("QNonStop:");4045 if (packet_str == "0") {4046 if (m_non_stop)4047 StopSTDIOForwarding();4048 for (auto &process_it : m_debugged_processes) {4049 if (process_it.second.process_up->IsRunning()) {4050 assert(m_non_stop);4051 Status error = process_it.second.process_up->Interrupt();4052 if (error.Fail()) {4053 LLDB_LOG(log,4054 "while disabling nonstop, failed to halt process {0}: {1}",4055 process_it.first, error);4056 return SendErrorResponse(0x41);4057 }4058 // we must not send stop reasons after QNonStop4059 m_disabling_non_stop = true;4060 }4061 }4062 m_stdio_notification_queue.clear();4063 m_stop_notification_queue.clear();4064 m_non_stop = false;4065 // If we are stopping anything, defer sending the OK response until we're4066 // done.4067 if (m_disabling_non_stop)4068 return PacketResult::Success;4069 } else if (packet_str == "1") {4070 if (!m_non_stop)4071 StartSTDIOForwarding();4072 m_non_stop = true;4073 } else4074 return SendErrorResponse(4075 Status::FromErrorString("Invalid QNonStop packet"));4076 return SendOKResponse();4077}4078 4079GDBRemoteCommunication::PacketResult4080GDBRemoteCommunicationServerLLGS::HandleNotificationAck(4081 std::deque<std::string> &queue) {4082 // Per the protocol, the first message put into the queue is sent4083 // immediately. However, it remains the queue until the client ACKs it --4084 // then we pop it and send the next message. The process repeats until4085 // the last message in the queue is ACK-ed, in which case the packet sends4086 // an OK response.4087 if (queue.empty())4088 return SendErrorResponse(4089 Status::FromErrorString("No pending notification to ack"));4090 queue.pop_front();4091 if (!queue.empty())4092 return SendPacketNoLock(queue.front());4093 return SendOKResponse();4094}4095 4096GDBRemoteCommunication::PacketResult4097GDBRemoteCommunicationServerLLGS::Handle_vStdio(4098 StringExtractorGDBRemote &packet) {4099 return HandleNotificationAck(m_stdio_notification_queue);4100}4101 4102GDBRemoteCommunication::PacketResult4103GDBRemoteCommunicationServerLLGS::Handle_vStopped(4104 StringExtractorGDBRemote &packet) {4105 PacketResult ret = HandleNotificationAck(m_stop_notification_queue);4106 // If this was the last notification and all the processes exited,4107 // terminate the server.4108 if (m_stop_notification_queue.empty() && m_debugged_processes.empty()) {4109 m_exit_now = true;4110 m_mainloop.RequestTermination();4111 }4112 return ret;4113}4114 4115GDBRemoteCommunication::PacketResult4116GDBRemoteCommunicationServerLLGS::Handle_vCtrlC(4117 StringExtractorGDBRemote &packet) {4118 if (!m_non_stop)4119 return SendErrorResponse(4120 Status::FromErrorString("vCtrl is only valid in non-stop mode"));4121 4122 PacketResult interrupt_res = Handle_interrupt(packet);4123 // If interrupting the process failed, pass the result through.4124 if (interrupt_res != PacketResult::Success)4125 return interrupt_res;4126 // Otherwise, vCtrlC should issue an OK response (normal interrupts do not).4127 return SendOKResponse();4128}4129 4130GDBRemoteCommunication::PacketResult4131GDBRemoteCommunicationServerLLGS::Handle_T(StringExtractorGDBRemote &packet) {4132 packet.SetFilePos(strlen("T"));4133 auto pid_tid = packet.GetPidTid(m_current_process ? m_current_process->GetID()4134 : LLDB_INVALID_PROCESS_ID);4135 if (!pid_tid)4136 return SendErrorResponse(llvm::make_error<StringError>(4137 inconvertibleErrorCode(), "Malformed thread-id"));4138 4139 lldb::pid_t pid = pid_tid->first;4140 lldb::tid_t tid = pid_tid->second;4141 4142 // Technically, this would also be caught by the PID check but let's be more4143 // explicit about the error.4144 if (pid == LLDB_INVALID_PROCESS_ID)4145 return SendErrorResponse(llvm::make_error<StringError>(4146 inconvertibleErrorCode(), "No current process and no PID provided"));4147 4148 // Check the process ID and find respective process instance.4149 auto new_process_it = m_debugged_processes.find(pid);4150 if (new_process_it == m_debugged_processes.end())4151 return SendErrorResponse(1);4152 4153 // Check the thread ID4154 if (!new_process_it->second.process_up->GetThreadByID(tid))4155 return SendErrorResponse(2);4156 4157 return SendOKResponse();4158}4159 4160void GDBRemoteCommunicationServerLLGS::MaybeCloseInferiorTerminalConnection() {4161 Log *log = GetLog(LLDBLog::Process);4162 4163 // Tell the stdio connection to shut down.4164 if (m_stdio_communication.IsConnected()) {4165 auto connection = m_stdio_communication.GetConnection();4166 if (connection) {4167 Status error;4168 connection->Disconnect(&error);4169 4170 if (error.Success()) {4171 LLDB_LOGF(log,4172 "GDBRemoteCommunicationServerLLGS::%s disconnect process "4173 "terminal stdio - SUCCESS",4174 __FUNCTION__);4175 } else {4176 LLDB_LOGF(log,4177 "GDBRemoteCommunicationServerLLGS::%s disconnect process "4178 "terminal stdio - FAIL: %s",4179 __FUNCTION__, error.AsCString());4180 }4181 }4182 }4183}4184 4185NativeThreadProtocol *GDBRemoteCommunicationServerLLGS::GetThreadFromSuffix(4186 StringExtractorGDBRemote &packet) {4187 // We have no thread if we don't have a process.4188 if (!m_current_process ||4189 m_current_process->GetID() == LLDB_INVALID_PROCESS_ID)4190 return nullptr;4191 4192 // If the client hasn't asked for thread suffix support, there will not be a4193 // thread suffix. Use the current thread in that case.4194 if (!m_thread_suffix_supported) {4195 const lldb::tid_t current_tid = GetCurrentThreadID();4196 if (current_tid == LLDB_INVALID_THREAD_ID)4197 return nullptr;4198 else if (current_tid == 0) {4199 // Pick a thread.4200 return m_current_process->GetThreadAtIndex(0);4201 } else4202 return m_current_process->GetThreadByID(current_tid);4203 }4204 4205 Log *log = GetLog(LLDBLog::Thread);4206 4207 // Parse out the ';'.4208 if (packet.GetBytesLeft() < 1 || packet.GetChar() != ';') {4209 LLDB_LOGF(log,4210 "GDBRemoteCommunicationServerLLGS::%s gdb-remote parse "4211 "error: expected ';' prior to start of thread suffix: packet "4212 "contents = '%s'",4213 __FUNCTION__, packet.GetStringRef().data());4214 return nullptr;4215 }4216 4217 if (!packet.GetBytesLeft())4218 return nullptr;4219 4220 // Parse out thread: portion.4221 if (strncmp(packet.Peek(), "thread:", strlen("thread:")) != 0) {4222 LLDB_LOGF(log,4223 "GDBRemoteCommunicationServerLLGS::%s gdb-remote parse "4224 "error: expected 'thread:' but not found, packet contents = "4225 "'%s'",4226 __FUNCTION__, packet.GetStringRef().data());4227 return nullptr;4228 }4229 packet.SetFilePos(packet.GetFilePos() + strlen("thread:"));4230 const lldb::tid_t tid = packet.GetHexMaxU64(false, 0);4231 if (tid != 0)4232 return m_current_process->GetThreadByID(tid);4233 4234 return nullptr;4235}4236 4237lldb::tid_t GDBRemoteCommunicationServerLLGS::GetCurrentThreadID() const {4238 if (m_current_tid == 0 || m_current_tid == LLDB_INVALID_THREAD_ID) {4239 // Use whatever the debug process says is the current thread id since the4240 // protocol either didn't specify or specified we want any/all threads4241 // marked as the current thread.4242 if (!m_current_process)4243 return LLDB_INVALID_THREAD_ID;4244 return m_current_process->GetCurrentThreadID();4245 }4246 // Use the specific current thread id set by the gdb remote protocol.4247 return m_current_tid;4248}4249 4250uint32_t GDBRemoteCommunicationServerLLGS::GetNextSavedRegistersID() {4251 std::lock_guard<std::mutex> guard(m_saved_registers_mutex);4252 return m_next_saved_registers_id++;4253}4254 4255void GDBRemoteCommunicationServerLLGS::ClearProcessSpecificData() {4256 Log *log = GetLog(LLDBLog::Process);4257 4258 LLDB_LOG(log, "clearing {0} xfer buffers", m_xfer_buffer_map.size());4259 m_xfer_buffer_map.clear();4260}4261 4262FileSpec4263GDBRemoteCommunicationServerLLGS::FindModuleFile(const std::string &module_path,4264 const ArchSpec &arch) {4265 if (m_current_process) {4266 FileSpec file_spec;4267 if (m_current_process4268 ->GetLoadedModuleFileSpec(module_path.c_str(), file_spec)4269 .Success()) {4270 if (FileSystem::Instance().Exists(file_spec))4271 return file_spec;4272 }4273 }4274 4275 return GDBRemoteCommunicationServerCommon::FindModuleFile(module_path, arch);4276}4277 4278std::string GDBRemoteCommunicationServerLLGS::XMLEncodeAttributeValue(4279 llvm::StringRef value) {4280 std::string result;4281 for (const char &c : value) {4282 switch (c) {4283 case '\'':4284 result += "'";4285 break;4286 case '"':4287 result += """;4288 break;4289 case '<':4290 result += "<";4291 break;4292 case '>':4293 result += ">";4294 break;4295 default:4296 result += c;4297 break;4298 }4299 }4300 return result;4301}4302 4303std::vector<std::string> GDBRemoteCommunicationServerLLGS::HandleFeatures(4304 const llvm::ArrayRef<llvm::StringRef> client_features) {4305 std::vector<std::string> ret =4306 GDBRemoteCommunicationServerCommon::HandleFeatures(client_features);4307 ret.insert(ret.end(), {4308 "QThreadSuffixSupported+",4309 "QListThreadsInStopReply+",4310 "qXfer:features:read+",4311 "QNonStop+",4312 });4313 4314 // report server-only features4315 using Extension = NativeProcessProtocol::Extension;4316 Extension plugin_features = m_process_manager.GetSupportedExtensions();4317 if (bool(plugin_features & Extension::pass_signals))4318 ret.push_back("QPassSignals+");4319 if (bool(plugin_features & Extension::auxv))4320 ret.push_back("qXfer:auxv:read+");4321 if (bool(plugin_features & Extension::libraries_svr4))4322 ret.push_back("qXfer:libraries-svr4:read+");4323 if (bool(plugin_features & Extension::siginfo_read))4324 ret.push_back("qXfer:siginfo:read+");4325 if (bool(plugin_features & Extension::memory_tagging))4326 ret.push_back("memory-tagging+");4327 if (bool(plugin_features & Extension::savecore))4328 ret.push_back("qSaveCore+");4329 4330 // check for client features4331 m_extensions_supported = {};4332 for (llvm::StringRef x : client_features)4333 m_extensions_supported |=4334 llvm::StringSwitch<Extension>(x)4335 .Case("multiprocess+", Extension::multiprocess)4336 .Case("fork-events+", Extension::fork)4337 .Case("vfork-events+", Extension::vfork)4338 .Default({});4339 4340 // We consume lldb's swbreak/hwbreak feature, but it doesn't change the4341 // behaviour of lldb-server. We always adjust the program counter for targets4342 // like x864343 4344 m_extensions_supported &= plugin_features;4345 4346 // fork & vfork require multiprocess4347 if (!bool(m_extensions_supported & Extension::multiprocess))4348 m_extensions_supported &= ~(Extension::fork | Extension::vfork);4349 4350 // report only if actually supported4351 if (bool(m_extensions_supported & Extension::multiprocess))4352 ret.push_back("multiprocess+");4353 if (bool(m_extensions_supported & Extension::fork))4354 ret.push_back("fork-events+");4355 if (bool(m_extensions_supported & Extension::vfork))4356 ret.push_back("vfork-events+");4357 4358 for (auto &x : m_debugged_processes)4359 SetEnabledExtensions(*x.second.process_up);4360 return ret;4361}4362 4363void GDBRemoteCommunicationServerLLGS::SetEnabledExtensions(4364 NativeProcessProtocol &process) {4365 NativeProcessProtocol::Extension flags = m_extensions_supported;4366 assert(!bool(flags & ~m_process_manager.GetSupportedExtensions()));4367 process.SetEnabledExtensions(flags);4368}4369 4370GDBRemoteCommunication::PacketResult4371GDBRemoteCommunicationServerLLGS::SendContinueSuccessResponse() {4372 if (m_non_stop)4373 return SendOKResponse();4374 StartSTDIOForwarding();4375 return PacketResult::Success;4376}4377 4378void GDBRemoteCommunicationServerLLGS::AppendThreadIDToResponse(4379 Stream &response, lldb::pid_t pid, lldb::tid_t tid) {4380 if (bool(m_extensions_supported &4381 NativeProcessProtocol::Extension::multiprocess))4382 response.Format("p{0:x-}.", pid);4383 response.Format("{0:x-}", tid);4384}4385 4386std::string4387lldb_private::process_gdb_remote::LLGSArgToURL(llvm::StringRef url_arg,4388 bool reverse_connect) {4389 // Try parsing the argument as URL.4390 if (std::optional<URI> url = URI::Parse(url_arg)) {4391 if (reverse_connect)4392 return url_arg.str();4393 4394 // Translate the scheme from LLGS notation to ConnectionFileDescriptor.4395 // If the scheme doesn't match any, pass it through to support using CFD4396 // schemes directly.4397 std::string new_url = llvm::StringSwitch<std::string>(url->scheme)4398 .Case("tcp", "listen")4399 .Case("unix", "unix-accept")4400 .Case("unix-abstract", "unix-abstract-accept")4401 .Default(url->scheme.str());4402 llvm::append_range(new_url, url_arg.substr(url->scheme.size()));4403 return new_url;4404 }4405 4406 std::string host_port = url_arg.str();4407 // If host_and_port starts with ':', default the host to be "localhost" and4408 // expect the remainder to be the port.4409 if (url_arg.starts_with(":"))4410 host_port.insert(0, "localhost");4411 4412 // Try parsing the (preprocessed) argument as host:port pair.4413 if (!llvm::errorToBool(Socket::DecodeHostAndPort(host_port).takeError()))4414 return (reverse_connect ? "connect://" : "listen://") + host_port;4415 4416 // If none of the above applied, interpret the argument as UNIX socket path.4417 return (reverse_connect ? "unix-connect://" : "unix-accept://") +4418 url_arg.str();4419}4420