1dda28197Spatrick //===-- GDBRemoteCommunicationServerLLGS.cpp ------------------------------===//
2061da546Spatrick //
3061da546Spatrick // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4061da546Spatrick // See https://llvm.org/LICENSE.txt for license information.
5061da546Spatrick // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6061da546Spatrick //
7061da546Spatrick //===----------------------------------------------------------------------===//
8061da546Spatrick
9be691f3bSpatrick #include <cerrno>
10061da546Spatrick
11061da546Spatrick #include "lldb/Host/Config.h"
12061da546Spatrick
13061da546Spatrick #include <chrono>
14061da546Spatrick #include <cstring>
15be691f3bSpatrick #include <limits>
16*f6aab3d8Srobert #include <optional>
17061da546Spatrick #include <thread>
18061da546Spatrick
19be691f3bSpatrick #include "GDBRemoteCommunicationServerLLGS.h"
20061da546Spatrick #include "lldb/Host/ConnectionFileDescriptor.h"
21061da546Spatrick #include "lldb/Host/Debug.h"
22061da546Spatrick #include "lldb/Host/File.h"
23061da546Spatrick #include "lldb/Host/FileAction.h"
24061da546Spatrick #include "lldb/Host/FileSystem.h"
25061da546Spatrick #include "lldb/Host/Host.h"
26061da546Spatrick #include "lldb/Host/HostInfo.h"
27061da546Spatrick #include "lldb/Host/PosixApi.h"
28*f6aab3d8Srobert #include "lldb/Host/Socket.h"
29061da546Spatrick #include "lldb/Host/common/NativeProcessProtocol.h"
30061da546Spatrick #include "lldb/Host/common/NativeRegisterContext.h"
31061da546Spatrick #include "lldb/Host/common/NativeThreadProtocol.h"
32061da546Spatrick #include "lldb/Target/MemoryRegionInfo.h"
33061da546Spatrick #include "lldb/Utility/Args.h"
34061da546Spatrick #include "lldb/Utility/DataBuffer.h"
35061da546Spatrick #include "lldb/Utility/Endian.h"
36be691f3bSpatrick #include "lldb/Utility/GDBRemote.h"
37061da546Spatrick #include "lldb/Utility/LLDBAssert.h"
38*f6aab3d8Srobert #include "lldb/Utility/LLDBLog.h"
39061da546Spatrick #include "lldb/Utility/Log.h"
40061da546Spatrick #include "lldb/Utility/RegisterValue.h"
41061da546Spatrick #include "lldb/Utility/State.h"
42061da546Spatrick #include "lldb/Utility/StreamString.h"
43be691f3bSpatrick #include "lldb/Utility/UnimplementedError.h"
44061da546Spatrick #include "lldb/Utility/UriParser.h"
45061da546Spatrick #include "llvm/ADT/Triple.h"
46061da546Spatrick #include "llvm/Support/JSON.h"
47061da546Spatrick #include "llvm/Support/ScopedPrinter.h"
48061da546Spatrick
49061da546Spatrick #include "ProcessGDBRemote.h"
50061da546Spatrick #include "ProcessGDBRemoteLog.h"
51061da546Spatrick #include "lldb/Utility/StringExtractorGDBRemote.h"
52061da546Spatrick
53061da546Spatrick using namespace lldb;
54061da546Spatrick using namespace lldb_private;
55061da546Spatrick using namespace lldb_private::process_gdb_remote;
56061da546Spatrick using namespace llvm;
57061da546Spatrick
58061da546Spatrick // GDBRemote Errors
59061da546Spatrick
60061da546Spatrick namespace {
61061da546Spatrick enum GDBRemoteServerError {
62061da546Spatrick // Set to the first unused error number in literal form below
63061da546Spatrick eErrorFirst = 29,
64061da546Spatrick eErrorNoProcess = eErrorFirst,
65061da546Spatrick eErrorResume,
66061da546Spatrick eErrorExitStatus
67061da546Spatrick };
68061da546Spatrick }
69061da546Spatrick
70061da546Spatrick // GDBRemoteCommunicationServerLLGS constructor
GDBRemoteCommunicationServerLLGS(MainLoop & mainloop,const NativeProcessProtocol::Factory & process_factory)71061da546Spatrick GDBRemoteCommunicationServerLLGS::GDBRemoteCommunicationServerLLGS(
72061da546Spatrick MainLoop &mainloop, const NativeProcessProtocol::Factory &process_factory)
73*f6aab3d8Srobert : GDBRemoteCommunicationServerCommon(), m_mainloop(mainloop),
74*f6aab3d8Srobert m_process_factory(process_factory), m_current_process(nullptr),
75*f6aab3d8Srobert m_continue_process(nullptr), m_stdio_communication() {
76061da546Spatrick RegisterPacketHandlers();
77061da546Spatrick }
78061da546Spatrick
RegisterPacketHandlers()79061da546Spatrick void GDBRemoteCommunicationServerLLGS::RegisterPacketHandlers() {
80061da546Spatrick RegisterMemberFunctionHandler(StringExtractorGDBRemote::eServerPacketType_C,
81061da546Spatrick &GDBRemoteCommunicationServerLLGS::Handle_C);
82061da546Spatrick RegisterMemberFunctionHandler(StringExtractorGDBRemote::eServerPacketType_c,
83061da546Spatrick &GDBRemoteCommunicationServerLLGS::Handle_c);
84061da546Spatrick RegisterMemberFunctionHandler(StringExtractorGDBRemote::eServerPacketType_D,
85061da546Spatrick &GDBRemoteCommunicationServerLLGS::Handle_D);
86061da546Spatrick RegisterMemberFunctionHandler(StringExtractorGDBRemote::eServerPacketType_H,
87061da546Spatrick &GDBRemoteCommunicationServerLLGS::Handle_H);
88061da546Spatrick RegisterMemberFunctionHandler(StringExtractorGDBRemote::eServerPacketType_I,
89061da546Spatrick &GDBRemoteCommunicationServerLLGS::Handle_I);
90061da546Spatrick RegisterMemberFunctionHandler(
91061da546Spatrick StringExtractorGDBRemote::eServerPacketType_interrupt,
92061da546Spatrick &GDBRemoteCommunicationServerLLGS::Handle_interrupt);
93061da546Spatrick RegisterMemberFunctionHandler(
94061da546Spatrick StringExtractorGDBRemote::eServerPacketType_m,
95061da546Spatrick &GDBRemoteCommunicationServerLLGS::Handle_memory_read);
96061da546Spatrick RegisterMemberFunctionHandler(StringExtractorGDBRemote::eServerPacketType_M,
97061da546Spatrick &GDBRemoteCommunicationServerLLGS::Handle_M);
98be691f3bSpatrick RegisterMemberFunctionHandler(StringExtractorGDBRemote::eServerPacketType__M,
99be691f3bSpatrick &GDBRemoteCommunicationServerLLGS::Handle__M);
100be691f3bSpatrick RegisterMemberFunctionHandler(StringExtractorGDBRemote::eServerPacketType__m,
101be691f3bSpatrick &GDBRemoteCommunicationServerLLGS::Handle__m);
102061da546Spatrick RegisterMemberFunctionHandler(StringExtractorGDBRemote::eServerPacketType_p,
103061da546Spatrick &GDBRemoteCommunicationServerLLGS::Handle_p);
104061da546Spatrick RegisterMemberFunctionHandler(StringExtractorGDBRemote::eServerPacketType_P,
105061da546Spatrick &GDBRemoteCommunicationServerLLGS::Handle_P);
106061da546Spatrick RegisterMemberFunctionHandler(StringExtractorGDBRemote::eServerPacketType_qC,
107061da546Spatrick &GDBRemoteCommunicationServerLLGS::Handle_qC);
108*f6aab3d8Srobert RegisterMemberFunctionHandler(StringExtractorGDBRemote::eServerPacketType_T,
109*f6aab3d8Srobert &GDBRemoteCommunicationServerLLGS::Handle_T);
110061da546Spatrick RegisterMemberFunctionHandler(
111061da546Spatrick StringExtractorGDBRemote::eServerPacketType_qfThreadInfo,
112061da546Spatrick &GDBRemoteCommunicationServerLLGS::Handle_qfThreadInfo);
113061da546Spatrick RegisterMemberFunctionHandler(
114061da546Spatrick StringExtractorGDBRemote::eServerPacketType_qFileLoadAddress,
115061da546Spatrick &GDBRemoteCommunicationServerLLGS::Handle_qFileLoadAddress);
116061da546Spatrick RegisterMemberFunctionHandler(
117061da546Spatrick StringExtractorGDBRemote::eServerPacketType_qGetWorkingDir,
118061da546Spatrick &GDBRemoteCommunicationServerLLGS::Handle_qGetWorkingDir);
119061da546Spatrick RegisterMemberFunctionHandler(
120be691f3bSpatrick StringExtractorGDBRemote::eServerPacketType_QThreadSuffixSupported,
121be691f3bSpatrick &GDBRemoteCommunicationServerLLGS::Handle_QThreadSuffixSupported);
122be691f3bSpatrick RegisterMemberFunctionHandler(
123be691f3bSpatrick StringExtractorGDBRemote::eServerPacketType_QListThreadsInStopReply,
124be691f3bSpatrick &GDBRemoteCommunicationServerLLGS::Handle_QListThreadsInStopReply);
125be691f3bSpatrick RegisterMemberFunctionHandler(
126061da546Spatrick StringExtractorGDBRemote::eServerPacketType_qMemoryRegionInfo,
127061da546Spatrick &GDBRemoteCommunicationServerLLGS::Handle_qMemoryRegionInfo);
128061da546Spatrick RegisterMemberFunctionHandler(
129061da546Spatrick StringExtractorGDBRemote::eServerPacketType_qMemoryRegionInfoSupported,
130061da546Spatrick &GDBRemoteCommunicationServerLLGS::Handle_qMemoryRegionInfoSupported);
131061da546Spatrick RegisterMemberFunctionHandler(
132061da546Spatrick StringExtractorGDBRemote::eServerPacketType_qProcessInfo,
133061da546Spatrick &GDBRemoteCommunicationServerLLGS::Handle_qProcessInfo);
134061da546Spatrick RegisterMemberFunctionHandler(
135061da546Spatrick StringExtractorGDBRemote::eServerPacketType_qRegisterInfo,
136061da546Spatrick &GDBRemoteCommunicationServerLLGS::Handle_qRegisterInfo);
137061da546Spatrick RegisterMemberFunctionHandler(
138061da546Spatrick StringExtractorGDBRemote::eServerPacketType_QRestoreRegisterState,
139061da546Spatrick &GDBRemoteCommunicationServerLLGS::Handle_QRestoreRegisterState);
140061da546Spatrick RegisterMemberFunctionHandler(
141061da546Spatrick StringExtractorGDBRemote::eServerPacketType_QSaveRegisterState,
142061da546Spatrick &GDBRemoteCommunicationServerLLGS::Handle_QSaveRegisterState);
143061da546Spatrick RegisterMemberFunctionHandler(
144061da546Spatrick StringExtractorGDBRemote::eServerPacketType_QSetDisableASLR,
145061da546Spatrick &GDBRemoteCommunicationServerLLGS::Handle_QSetDisableASLR);
146061da546Spatrick RegisterMemberFunctionHandler(
147061da546Spatrick StringExtractorGDBRemote::eServerPacketType_QSetWorkingDir,
148061da546Spatrick &GDBRemoteCommunicationServerLLGS::Handle_QSetWorkingDir);
149061da546Spatrick RegisterMemberFunctionHandler(
150061da546Spatrick StringExtractorGDBRemote::eServerPacketType_qsThreadInfo,
151061da546Spatrick &GDBRemoteCommunicationServerLLGS::Handle_qsThreadInfo);
152061da546Spatrick RegisterMemberFunctionHandler(
153061da546Spatrick StringExtractorGDBRemote::eServerPacketType_qThreadStopInfo,
154061da546Spatrick &GDBRemoteCommunicationServerLLGS::Handle_qThreadStopInfo);
155061da546Spatrick RegisterMemberFunctionHandler(
156061da546Spatrick StringExtractorGDBRemote::eServerPacketType_jThreadsInfo,
157061da546Spatrick &GDBRemoteCommunicationServerLLGS::Handle_jThreadsInfo);
158061da546Spatrick RegisterMemberFunctionHandler(
159061da546Spatrick StringExtractorGDBRemote::eServerPacketType_qWatchpointSupportInfo,
160061da546Spatrick &GDBRemoteCommunicationServerLLGS::Handle_qWatchpointSupportInfo);
161061da546Spatrick RegisterMemberFunctionHandler(
162061da546Spatrick StringExtractorGDBRemote::eServerPacketType_qXfer,
163061da546Spatrick &GDBRemoteCommunicationServerLLGS::Handle_qXfer);
164061da546Spatrick RegisterMemberFunctionHandler(StringExtractorGDBRemote::eServerPacketType_s,
165061da546Spatrick &GDBRemoteCommunicationServerLLGS::Handle_s);
166061da546Spatrick RegisterMemberFunctionHandler(
167061da546Spatrick StringExtractorGDBRemote::eServerPacketType_stop_reason,
168061da546Spatrick &GDBRemoteCommunicationServerLLGS::Handle_stop_reason); // ?
169061da546Spatrick RegisterMemberFunctionHandler(
170061da546Spatrick StringExtractorGDBRemote::eServerPacketType_vAttach,
171061da546Spatrick &GDBRemoteCommunicationServerLLGS::Handle_vAttach);
172061da546Spatrick RegisterMemberFunctionHandler(
173be691f3bSpatrick StringExtractorGDBRemote::eServerPacketType_vAttachWait,
174be691f3bSpatrick &GDBRemoteCommunicationServerLLGS::Handle_vAttachWait);
175be691f3bSpatrick RegisterMemberFunctionHandler(
176be691f3bSpatrick StringExtractorGDBRemote::eServerPacketType_qVAttachOrWaitSupported,
177be691f3bSpatrick &GDBRemoteCommunicationServerLLGS::Handle_qVAttachOrWaitSupported);
178be691f3bSpatrick RegisterMemberFunctionHandler(
179be691f3bSpatrick StringExtractorGDBRemote::eServerPacketType_vAttachOrWait,
180be691f3bSpatrick &GDBRemoteCommunicationServerLLGS::Handle_vAttachOrWait);
181be691f3bSpatrick RegisterMemberFunctionHandler(
182061da546Spatrick StringExtractorGDBRemote::eServerPacketType_vCont,
183061da546Spatrick &GDBRemoteCommunicationServerLLGS::Handle_vCont);
184061da546Spatrick RegisterMemberFunctionHandler(
185061da546Spatrick StringExtractorGDBRemote::eServerPacketType_vCont_actions,
186061da546Spatrick &GDBRemoteCommunicationServerLLGS::Handle_vCont_actions);
187061da546Spatrick RegisterMemberFunctionHandler(
188*f6aab3d8Srobert StringExtractorGDBRemote::eServerPacketType_vRun,
189*f6aab3d8Srobert &GDBRemoteCommunicationServerLLGS::Handle_vRun);
190*f6aab3d8Srobert RegisterMemberFunctionHandler(
191061da546Spatrick StringExtractorGDBRemote::eServerPacketType_x,
192061da546Spatrick &GDBRemoteCommunicationServerLLGS::Handle_memory_read);
193061da546Spatrick RegisterMemberFunctionHandler(StringExtractorGDBRemote::eServerPacketType_Z,
194061da546Spatrick &GDBRemoteCommunicationServerLLGS::Handle_Z);
195061da546Spatrick RegisterMemberFunctionHandler(StringExtractorGDBRemote::eServerPacketType_z,
196061da546Spatrick &GDBRemoteCommunicationServerLLGS::Handle_z);
197061da546Spatrick RegisterMemberFunctionHandler(
198061da546Spatrick StringExtractorGDBRemote::eServerPacketType_QPassSignals,
199061da546Spatrick &GDBRemoteCommunicationServerLLGS::Handle_QPassSignals);
200061da546Spatrick
201061da546Spatrick RegisterMemberFunctionHandler(
202be691f3bSpatrick StringExtractorGDBRemote::eServerPacketType_jLLDBTraceSupported,
203be691f3bSpatrick &GDBRemoteCommunicationServerLLGS::Handle_jLLDBTraceSupported);
204061da546Spatrick RegisterMemberFunctionHandler(
205be691f3bSpatrick StringExtractorGDBRemote::eServerPacketType_jLLDBTraceStart,
206be691f3bSpatrick &GDBRemoteCommunicationServerLLGS::Handle_jLLDBTraceStart);
207061da546Spatrick RegisterMemberFunctionHandler(
208be691f3bSpatrick StringExtractorGDBRemote::eServerPacketType_jLLDBTraceStop,
209be691f3bSpatrick &GDBRemoteCommunicationServerLLGS::Handle_jLLDBTraceStop);
210061da546Spatrick RegisterMemberFunctionHandler(
211be691f3bSpatrick StringExtractorGDBRemote::eServerPacketType_jLLDBTraceGetState,
212be691f3bSpatrick &GDBRemoteCommunicationServerLLGS::Handle_jLLDBTraceGetState);
213061da546Spatrick RegisterMemberFunctionHandler(
214be691f3bSpatrick StringExtractorGDBRemote::eServerPacketType_jLLDBTraceGetBinaryData,
215be691f3bSpatrick &GDBRemoteCommunicationServerLLGS::Handle_jLLDBTraceGetBinaryData);
216061da546Spatrick
217061da546Spatrick RegisterMemberFunctionHandler(StringExtractorGDBRemote::eServerPacketType_g,
218061da546Spatrick &GDBRemoteCommunicationServerLLGS::Handle_g);
219061da546Spatrick
220be691f3bSpatrick RegisterMemberFunctionHandler(
221be691f3bSpatrick StringExtractorGDBRemote::eServerPacketType_qMemTags,
222be691f3bSpatrick &GDBRemoteCommunicationServerLLGS::Handle_qMemTags);
223be691f3bSpatrick
224be691f3bSpatrick RegisterMemberFunctionHandler(
225be691f3bSpatrick StringExtractorGDBRemote::eServerPacketType_QMemTags,
226be691f3bSpatrick &GDBRemoteCommunicationServerLLGS::Handle_QMemTags);
227be691f3bSpatrick
228061da546Spatrick RegisterPacketHandler(StringExtractorGDBRemote::eServerPacketType_k,
229061da546Spatrick [this](StringExtractorGDBRemote packet, Status &error,
230061da546Spatrick bool &interrupt, bool &quit) {
231061da546Spatrick quit = true;
232061da546Spatrick return this->Handle_k(packet);
233061da546Spatrick });
234*f6aab3d8Srobert
235*f6aab3d8Srobert RegisterMemberFunctionHandler(
236*f6aab3d8Srobert StringExtractorGDBRemote::eServerPacketType_vKill,
237*f6aab3d8Srobert &GDBRemoteCommunicationServerLLGS::Handle_vKill);
238*f6aab3d8Srobert
239*f6aab3d8Srobert RegisterMemberFunctionHandler(
240*f6aab3d8Srobert StringExtractorGDBRemote::eServerPacketType_qLLDBSaveCore,
241*f6aab3d8Srobert &GDBRemoteCommunicationServerLLGS::Handle_qSaveCore);
242*f6aab3d8Srobert
243*f6aab3d8Srobert RegisterMemberFunctionHandler(
244*f6aab3d8Srobert StringExtractorGDBRemote::eServerPacketType_QNonStop,
245*f6aab3d8Srobert &GDBRemoteCommunicationServerLLGS::Handle_QNonStop);
246*f6aab3d8Srobert RegisterMemberFunctionHandler(
247*f6aab3d8Srobert StringExtractorGDBRemote::eServerPacketType_vStdio,
248*f6aab3d8Srobert &GDBRemoteCommunicationServerLLGS::Handle_vStdio);
249*f6aab3d8Srobert RegisterMemberFunctionHandler(
250*f6aab3d8Srobert StringExtractorGDBRemote::eServerPacketType_vStopped,
251*f6aab3d8Srobert &GDBRemoteCommunicationServerLLGS::Handle_vStopped);
252*f6aab3d8Srobert RegisterMemberFunctionHandler(
253*f6aab3d8Srobert StringExtractorGDBRemote::eServerPacketType_vCtrlC,
254*f6aab3d8Srobert &GDBRemoteCommunicationServerLLGS::Handle_vCtrlC);
255061da546Spatrick }
256061da546Spatrick
SetLaunchInfo(const ProcessLaunchInfo & info)257061da546Spatrick void GDBRemoteCommunicationServerLLGS::SetLaunchInfo(const ProcessLaunchInfo &info) {
258061da546Spatrick m_process_launch_info = info;
259061da546Spatrick }
260061da546Spatrick
LaunchProcess()261061da546Spatrick Status GDBRemoteCommunicationServerLLGS::LaunchProcess() {
262*f6aab3d8Srobert Log *log = GetLog(LLDBLog::Process);
263061da546Spatrick
264061da546Spatrick if (!m_process_launch_info.GetArguments().GetArgumentCount())
265061da546Spatrick return Status("%s: no process command line specified to launch",
266061da546Spatrick __FUNCTION__);
267061da546Spatrick
268061da546Spatrick const bool should_forward_stdio =
269061da546Spatrick m_process_launch_info.GetFileActionForFD(STDIN_FILENO) == nullptr ||
270061da546Spatrick m_process_launch_info.GetFileActionForFD(STDOUT_FILENO) == nullptr ||
271061da546Spatrick m_process_launch_info.GetFileActionForFD(STDERR_FILENO) == nullptr;
272061da546Spatrick m_process_launch_info.SetLaunchInSeparateProcessGroup(true);
273061da546Spatrick m_process_launch_info.GetFlags().Set(eLaunchFlagDebug);
274061da546Spatrick
275061da546Spatrick if (should_forward_stdio) {
276061da546Spatrick // Temporarily relax the following for Windows until we can take advantage
277061da546Spatrick // of the recently added pty support. This doesn't really affect the use of
278061da546Spatrick // lldb-server on Windows.
279061da546Spatrick #if !defined(_WIN32)
280061da546Spatrick if (llvm::Error Err = m_process_launch_info.SetUpPtyRedirection())
281061da546Spatrick return Status(std::move(Err));
282061da546Spatrick #endif
283061da546Spatrick }
284061da546Spatrick
285061da546Spatrick {
286061da546Spatrick std::lock_guard<std::recursive_mutex> guard(m_debugged_process_mutex);
287be691f3bSpatrick assert(m_debugged_processes.empty() && "lldb-server creating debugged "
288061da546Spatrick "process but one already exists");
289061da546Spatrick auto process_or =
290061da546Spatrick m_process_factory.Launch(m_process_launch_info, *this, m_mainloop);
291061da546Spatrick if (!process_or)
292061da546Spatrick return Status(process_or.takeError());
293be691f3bSpatrick m_continue_process = m_current_process = process_or->get();
294*f6aab3d8Srobert m_debugged_processes.emplace(
295*f6aab3d8Srobert m_current_process->GetID(),
296*f6aab3d8Srobert DebuggedProcess{std::move(*process_or), DebuggedProcess::Flag{}});
297061da546Spatrick }
298061da546Spatrick
299be691f3bSpatrick SetEnabledExtensions(*m_current_process);
300be691f3bSpatrick
301061da546Spatrick // Handle mirroring of inferior stdout/stderr over the gdb-remote protocol as
302061da546Spatrick // needed. llgs local-process debugging may specify PTY paths, which will
303061da546Spatrick // make these file actions non-null process launch -i/e/o will also make
304061da546Spatrick // these file actions non-null nullptr means that the traffic is expected to
305061da546Spatrick // flow over gdb-remote protocol
306061da546Spatrick if (should_forward_stdio) {
307061da546Spatrick // nullptr means it's not redirected to file or pty (in case of LLGS local)
308061da546Spatrick // at least one of stdio will be transferred pty<->gdb-remote we need to
309*f6aab3d8Srobert // give the pty primary handle to this object to read and/or write
310061da546Spatrick LLDB_LOG(log,
311061da546Spatrick "pid = {0}: setting up stdout/stderr redirection via $O "
312061da546Spatrick "gdb-remote commands",
313be691f3bSpatrick m_current_process->GetID());
314061da546Spatrick
315061da546Spatrick // Setup stdout/stderr mapping from inferior to $O
316be691f3bSpatrick auto terminal_fd = m_current_process->GetTerminalFileDescriptor();
317061da546Spatrick if (terminal_fd >= 0) {
318061da546Spatrick LLDB_LOGF(log,
319061da546Spatrick "ProcessGDBRemoteCommunicationServerLLGS::%s setting "
320061da546Spatrick "inferior STDIO fd to %d",
321061da546Spatrick __FUNCTION__, terminal_fd);
322061da546Spatrick Status status = SetSTDIOFileDescriptor(terminal_fd);
323061da546Spatrick if (status.Fail())
324061da546Spatrick return status;
325061da546Spatrick } else {
326061da546Spatrick LLDB_LOGF(log,
327061da546Spatrick "ProcessGDBRemoteCommunicationServerLLGS::%s ignoring "
328061da546Spatrick "inferior STDIO since terminal fd reported as %d",
329061da546Spatrick __FUNCTION__, terminal_fd);
330061da546Spatrick }
331061da546Spatrick } else {
332061da546Spatrick LLDB_LOG(log,
333061da546Spatrick "pid = {0} skipping stdout/stderr redirection via $O: inferior "
334061da546Spatrick "will communicate over client-provided file descriptors",
335be691f3bSpatrick m_current_process->GetID());
336061da546Spatrick }
337061da546Spatrick
338061da546Spatrick printf("Launched '%s' as process %" PRIu64 "...\n",
339061da546Spatrick m_process_launch_info.GetArguments().GetArgumentAtIndex(0),
340be691f3bSpatrick m_current_process->GetID());
341061da546Spatrick
342061da546Spatrick return Status();
343061da546Spatrick }
344061da546Spatrick
AttachToProcess(lldb::pid_t pid)345061da546Spatrick Status GDBRemoteCommunicationServerLLGS::AttachToProcess(lldb::pid_t pid) {
346*f6aab3d8Srobert Log *log = GetLog(LLDBLog::Process);
347061da546Spatrick LLDB_LOGF(log, "GDBRemoteCommunicationServerLLGS::%s pid %" PRIu64,
348061da546Spatrick __FUNCTION__, pid);
349061da546Spatrick
350061da546Spatrick // Before we try to attach, make sure we aren't already monitoring something
351061da546Spatrick // else.
352be691f3bSpatrick if (!m_debugged_processes.empty())
353061da546Spatrick return Status("cannot attach to process %" PRIu64
354061da546Spatrick " when another process with pid %" PRIu64
355061da546Spatrick " is being debugged.",
356be691f3bSpatrick pid, m_current_process->GetID());
357061da546Spatrick
358061da546Spatrick // Try to attach.
359061da546Spatrick auto process_or = m_process_factory.Attach(pid, *this, m_mainloop);
360061da546Spatrick if (!process_or) {
361061da546Spatrick Status status(process_or.takeError());
362*f6aab3d8Srobert llvm::errs() << llvm::formatv("failed to attach to process {0}: {1}\n", pid,
363061da546Spatrick status);
364061da546Spatrick return status;
365061da546Spatrick }
366be691f3bSpatrick m_continue_process = m_current_process = process_or->get();
367*f6aab3d8Srobert m_debugged_processes.emplace(
368*f6aab3d8Srobert m_current_process->GetID(),
369*f6aab3d8Srobert DebuggedProcess{std::move(*process_or), DebuggedProcess::Flag{}});
370be691f3bSpatrick SetEnabledExtensions(*m_current_process);
371061da546Spatrick
372061da546Spatrick // Setup stdout/stderr mapping from inferior.
373be691f3bSpatrick auto terminal_fd = m_current_process->GetTerminalFileDescriptor();
374061da546Spatrick if (terminal_fd >= 0) {
375061da546Spatrick LLDB_LOGF(log,
376061da546Spatrick "ProcessGDBRemoteCommunicationServerLLGS::%s setting "
377061da546Spatrick "inferior STDIO fd to %d",
378061da546Spatrick __FUNCTION__, terminal_fd);
379061da546Spatrick Status status = SetSTDIOFileDescriptor(terminal_fd);
380061da546Spatrick if (status.Fail())
381061da546Spatrick return status;
382061da546Spatrick } else {
383061da546Spatrick LLDB_LOGF(log,
384061da546Spatrick "ProcessGDBRemoteCommunicationServerLLGS::%s ignoring "
385061da546Spatrick "inferior STDIO since terminal fd reported as %d",
386061da546Spatrick __FUNCTION__, terminal_fd);
387061da546Spatrick }
388061da546Spatrick
389061da546Spatrick printf("Attached to process %" PRIu64 "...\n", pid);
390061da546Spatrick return Status();
391061da546Spatrick }
392061da546Spatrick
AttachWaitProcess(llvm::StringRef process_name,bool include_existing)393be691f3bSpatrick Status GDBRemoteCommunicationServerLLGS::AttachWaitProcess(
394be691f3bSpatrick llvm::StringRef process_name, bool include_existing) {
395*f6aab3d8Srobert Log *log = GetLog(LLDBLog::Process);
396be691f3bSpatrick
397be691f3bSpatrick std::chrono::milliseconds polling_interval = std::chrono::milliseconds(1);
398be691f3bSpatrick
399be691f3bSpatrick // Create the matcher used to search the process list.
400be691f3bSpatrick ProcessInstanceInfoList exclusion_list;
401be691f3bSpatrick ProcessInstanceInfoMatch match_info;
402be691f3bSpatrick match_info.GetProcessInfo().GetExecutableFile().SetFile(
403be691f3bSpatrick process_name, llvm::sys::path::Style::native);
404be691f3bSpatrick match_info.SetNameMatchType(NameMatch::Equals);
405be691f3bSpatrick
406be691f3bSpatrick if (include_existing) {
407be691f3bSpatrick LLDB_LOG(log, "including existing processes in search");
408be691f3bSpatrick } else {
409be691f3bSpatrick // Create the excluded process list before polling begins.
410be691f3bSpatrick Host::FindProcesses(match_info, exclusion_list);
411be691f3bSpatrick LLDB_LOG(log, "placed '{0}' processes in the exclusion list.",
412be691f3bSpatrick exclusion_list.size());
413be691f3bSpatrick }
414be691f3bSpatrick
415be691f3bSpatrick LLDB_LOG(log, "waiting for '{0}' to appear", process_name);
416be691f3bSpatrick
417be691f3bSpatrick auto is_in_exclusion_list =
418be691f3bSpatrick [&exclusion_list](const ProcessInstanceInfo &info) {
419be691f3bSpatrick for (auto &excluded : exclusion_list) {
420be691f3bSpatrick if (excluded.GetProcessID() == info.GetProcessID())
421be691f3bSpatrick return true;
422be691f3bSpatrick }
423be691f3bSpatrick return false;
424be691f3bSpatrick };
425be691f3bSpatrick
426be691f3bSpatrick ProcessInstanceInfoList loop_process_list;
427be691f3bSpatrick while (true) {
428be691f3bSpatrick loop_process_list.clear();
429be691f3bSpatrick if (Host::FindProcesses(match_info, loop_process_list)) {
430be691f3bSpatrick // Remove all the elements that are in the exclusion list.
431be691f3bSpatrick llvm::erase_if(loop_process_list, is_in_exclusion_list);
432be691f3bSpatrick
433be691f3bSpatrick // One match! We found the desired process.
434be691f3bSpatrick if (loop_process_list.size() == 1) {
435be691f3bSpatrick auto matching_process_pid = loop_process_list[0].GetProcessID();
436be691f3bSpatrick LLDB_LOG(log, "found pid {0}", matching_process_pid);
437be691f3bSpatrick return AttachToProcess(matching_process_pid);
438be691f3bSpatrick }
439be691f3bSpatrick
440be691f3bSpatrick // Multiple matches! Return an error reporting the PIDs we found.
441be691f3bSpatrick if (loop_process_list.size() > 1) {
442be691f3bSpatrick StreamString error_stream;
443be691f3bSpatrick error_stream.Format(
444be691f3bSpatrick "Multiple executables with name: '{0}' found. Pids: ",
445be691f3bSpatrick process_name);
446be691f3bSpatrick for (size_t i = 0; i < loop_process_list.size() - 1; ++i) {
447be691f3bSpatrick error_stream.Format("{0}, ", loop_process_list[i].GetProcessID());
448be691f3bSpatrick }
449be691f3bSpatrick error_stream.Format("{0}.", loop_process_list.back().GetProcessID());
450be691f3bSpatrick
451be691f3bSpatrick Status error;
452be691f3bSpatrick error.SetErrorString(error_stream.GetString());
453be691f3bSpatrick return error;
454be691f3bSpatrick }
455be691f3bSpatrick }
456be691f3bSpatrick // No matches, we have not found the process. Sleep until next poll.
457be691f3bSpatrick LLDB_LOG(log, "sleep {0} seconds", polling_interval);
458be691f3bSpatrick std::this_thread::sleep_for(polling_interval);
459be691f3bSpatrick }
460be691f3bSpatrick }
461be691f3bSpatrick
InitializeDelegate(NativeProcessProtocol * process)462061da546Spatrick void GDBRemoteCommunicationServerLLGS::InitializeDelegate(
463061da546Spatrick NativeProcessProtocol *process) {
464061da546Spatrick assert(process && "process cannot be NULL");
465*f6aab3d8Srobert Log *log = GetLog(LLDBLog::Process);
466061da546Spatrick if (log) {
467061da546Spatrick LLDB_LOGF(log,
468061da546Spatrick "GDBRemoteCommunicationServerLLGS::%s called with "
469061da546Spatrick "NativeProcessProtocol pid %" PRIu64 ", current state: %s",
470061da546Spatrick __FUNCTION__, process->GetID(),
471061da546Spatrick StateAsCString(process->GetState()));
472061da546Spatrick }
473061da546Spatrick }
474061da546Spatrick
475061da546Spatrick GDBRemoteCommunication::PacketResult
SendWResponse(NativeProcessProtocol * process)476061da546Spatrick GDBRemoteCommunicationServerLLGS::SendWResponse(
477061da546Spatrick NativeProcessProtocol *process) {
478061da546Spatrick assert(process && "process cannot be NULL");
479*f6aab3d8Srobert Log *log = GetLog(LLDBLog::Process);
480061da546Spatrick
481061da546Spatrick // send W notification
482061da546Spatrick auto wait_status = process->GetExitStatus();
483061da546Spatrick if (!wait_status) {
484061da546Spatrick LLDB_LOG(log, "pid = {0}, failed to retrieve process exit status",
485061da546Spatrick process->GetID());
486061da546Spatrick
487061da546Spatrick StreamGDBRemote response;
488061da546Spatrick response.PutChar('E');
489061da546Spatrick response.PutHex8(GDBRemoteServerError::eErrorExitStatus);
490061da546Spatrick return SendPacketNoLock(response.GetString());
491061da546Spatrick }
492061da546Spatrick
493061da546Spatrick LLDB_LOG(log, "pid = {0}, returning exit type {1}", process->GetID(),
494061da546Spatrick *wait_status);
495061da546Spatrick
496*f6aab3d8Srobert // If the process was killed through vKill, return "OK".
497*f6aab3d8Srobert if (bool(m_debugged_processes.at(process->GetID()).flags &
498*f6aab3d8Srobert DebuggedProcess::Flag::vkilled))
499*f6aab3d8Srobert return SendOKResponse();
500*f6aab3d8Srobert
501061da546Spatrick StreamGDBRemote response;
502061da546Spatrick response.Format("{0:g}", *wait_status);
503*f6aab3d8Srobert if (bool(m_extensions_supported &
504*f6aab3d8Srobert NativeProcessProtocol::Extension::multiprocess))
505*f6aab3d8Srobert response.Format(";process:{0:x-}", process->GetID());
506*f6aab3d8Srobert if (m_non_stop)
507*f6aab3d8Srobert return SendNotificationPacketNoLock("Stop", m_stop_notification_queue,
508*f6aab3d8Srobert response.GetString());
509061da546Spatrick return SendPacketNoLock(response.GetString());
510061da546Spatrick }
511061da546Spatrick
AppendHexValue(StreamString & response,const uint8_t * buf,uint32_t buf_size,bool swap)512061da546Spatrick static void AppendHexValue(StreamString &response, const uint8_t *buf,
513061da546Spatrick uint32_t buf_size, bool swap) {
514061da546Spatrick int64_t i;
515061da546Spatrick if (swap) {
516061da546Spatrick for (i = buf_size - 1; i >= 0; i--)
517061da546Spatrick response.PutHex8(buf[i]);
518061da546Spatrick } else {
519061da546Spatrick for (i = 0; i < buf_size; i++)
520061da546Spatrick response.PutHex8(buf[i]);
521061da546Spatrick }
522061da546Spatrick }
523061da546Spatrick
GetEncodingNameOrEmpty(const RegisterInfo & reg_info)524dda28197Spatrick static llvm::StringRef GetEncodingNameOrEmpty(const RegisterInfo ®_info) {
525dda28197Spatrick switch (reg_info.encoding) {
526dda28197Spatrick case eEncodingUint:
527dda28197Spatrick return "uint";
528dda28197Spatrick case eEncodingSint:
529dda28197Spatrick return "sint";
530dda28197Spatrick case eEncodingIEEE754:
531dda28197Spatrick return "ieee754";
532dda28197Spatrick case eEncodingVector:
533dda28197Spatrick return "vector";
534dda28197Spatrick default:
535dda28197Spatrick return "";
536dda28197Spatrick }
537dda28197Spatrick }
538dda28197Spatrick
GetFormatNameOrEmpty(const RegisterInfo & reg_info)539dda28197Spatrick static llvm::StringRef GetFormatNameOrEmpty(const RegisterInfo ®_info) {
540dda28197Spatrick switch (reg_info.format) {
541dda28197Spatrick case eFormatBinary:
542dda28197Spatrick return "binary";
543dda28197Spatrick case eFormatDecimal:
544dda28197Spatrick return "decimal";
545dda28197Spatrick case eFormatHex:
546dda28197Spatrick return "hex";
547dda28197Spatrick case eFormatFloat:
548dda28197Spatrick return "float";
549dda28197Spatrick case eFormatVectorOfSInt8:
550dda28197Spatrick return "vector-sint8";
551dda28197Spatrick case eFormatVectorOfUInt8:
552dda28197Spatrick return "vector-uint8";
553dda28197Spatrick case eFormatVectorOfSInt16:
554dda28197Spatrick return "vector-sint16";
555dda28197Spatrick case eFormatVectorOfUInt16:
556dda28197Spatrick return "vector-uint16";
557dda28197Spatrick case eFormatVectorOfSInt32:
558dda28197Spatrick return "vector-sint32";
559dda28197Spatrick case eFormatVectorOfUInt32:
560dda28197Spatrick return "vector-uint32";
561dda28197Spatrick case eFormatVectorOfFloat32:
562dda28197Spatrick return "vector-float32";
563dda28197Spatrick case eFormatVectorOfUInt64:
564dda28197Spatrick return "vector-uint64";
565dda28197Spatrick case eFormatVectorOfUInt128:
566dda28197Spatrick return "vector-uint128";
567dda28197Spatrick default:
568dda28197Spatrick return "";
569dda28197Spatrick };
570dda28197Spatrick }
571dda28197Spatrick
GetKindGenericOrEmpty(const RegisterInfo & reg_info)572dda28197Spatrick static llvm::StringRef GetKindGenericOrEmpty(const RegisterInfo ®_info) {
573dda28197Spatrick switch (reg_info.kinds[RegisterKind::eRegisterKindGeneric]) {
574dda28197Spatrick case LLDB_REGNUM_GENERIC_PC:
575dda28197Spatrick return "pc";
576dda28197Spatrick case LLDB_REGNUM_GENERIC_SP:
577dda28197Spatrick return "sp";
578dda28197Spatrick case LLDB_REGNUM_GENERIC_FP:
579dda28197Spatrick return "fp";
580dda28197Spatrick case LLDB_REGNUM_GENERIC_RA:
581dda28197Spatrick return "ra";
582dda28197Spatrick case LLDB_REGNUM_GENERIC_FLAGS:
583dda28197Spatrick return "flags";
584dda28197Spatrick case LLDB_REGNUM_GENERIC_ARG1:
585dda28197Spatrick return "arg1";
586dda28197Spatrick case LLDB_REGNUM_GENERIC_ARG2:
587dda28197Spatrick return "arg2";
588dda28197Spatrick case LLDB_REGNUM_GENERIC_ARG3:
589dda28197Spatrick return "arg3";
590dda28197Spatrick case LLDB_REGNUM_GENERIC_ARG4:
591dda28197Spatrick return "arg4";
592dda28197Spatrick case LLDB_REGNUM_GENERIC_ARG5:
593dda28197Spatrick return "arg5";
594dda28197Spatrick case LLDB_REGNUM_GENERIC_ARG6:
595dda28197Spatrick return "arg6";
596dda28197Spatrick case LLDB_REGNUM_GENERIC_ARG7:
597dda28197Spatrick return "arg7";
598dda28197Spatrick case LLDB_REGNUM_GENERIC_ARG8:
599dda28197Spatrick return "arg8";
600dda28197Spatrick default:
601dda28197Spatrick return "";
602dda28197Spatrick }
603dda28197Spatrick }
604dda28197Spatrick
CollectRegNums(const uint32_t * reg_num,StreamString & response,bool usehex)605dda28197Spatrick static void CollectRegNums(const uint32_t *reg_num, StreamString &response,
606dda28197Spatrick bool usehex) {
607dda28197Spatrick for (int i = 0; *reg_num != LLDB_INVALID_REGNUM; ++reg_num, ++i) {
608dda28197Spatrick if (i > 0)
609dda28197Spatrick response.PutChar(',');
610dda28197Spatrick if (usehex)
611dda28197Spatrick response.Printf("%" PRIx32, *reg_num);
612dda28197Spatrick else
613dda28197Spatrick response.Printf("%" PRIu32, *reg_num);
614dda28197Spatrick }
615dda28197Spatrick }
616dda28197Spatrick
WriteRegisterValueInHexFixedWidth(StreamString & response,NativeRegisterContext & reg_ctx,const RegisterInfo & reg_info,const RegisterValue * reg_value_p,lldb::ByteOrder byte_order)617061da546Spatrick static void WriteRegisterValueInHexFixedWidth(
618061da546Spatrick StreamString &response, NativeRegisterContext ®_ctx,
619061da546Spatrick const RegisterInfo ®_info, const RegisterValue *reg_value_p,
620061da546Spatrick lldb::ByteOrder byte_order) {
621061da546Spatrick RegisterValue reg_value;
622061da546Spatrick if (!reg_value_p) {
623061da546Spatrick Status error = reg_ctx.ReadRegister(®_info, reg_value);
624061da546Spatrick if (error.Success())
625061da546Spatrick reg_value_p = ®_value;
626061da546Spatrick // else log.
627061da546Spatrick }
628061da546Spatrick
629061da546Spatrick if (reg_value_p) {
630061da546Spatrick AppendHexValue(response, (const uint8_t *)reg_value_p->GetBytes(),
631061da546Spatrick reg_value_p->GetByteSize(),
632061da546Spatrick byte_order == lldb::eByteOrderLittle);
633061da546Spatrick } else {
634061da546Spatrick // Zero-out any unreadable values.
635061da546Spatrick if (reg_info.byte_size > 0) {
636061da546Spatrick std::basic_string<uint8_t> zeros(reg_info.byte_size, '\0');
637061da546Spatrick AppendHexValue(response, zeros.data(), zeros.size(), false);
638061da546Spatrick }
639061da546Spatrick }
640061da546Spatrick }
641061da546Spatrick
642*f6aab3d8Srobert static std::optional<json::Object>
GetRegistersAsJSON(NativeThreadProtocol & thread)643061da546Spatrick GetRegistersAsJSON(NativeThreadProtocol &thread) {
644*f6aab3d8Srobert Log *log = GetLog(LLDBLog::Thread);
645061da546Spatrick
646061da546Spatrick NativeRegisterContext& reg_ctx = thread.GetRegisterContext();
647061da546Spatrick
648061da546Spatrick json::Object register_object;
649061da546Spatrick
650061da546Spatrick #ifdef LLDB_JTHREADSINFO_FULL_REGISTER_SET
651be691f3bSpatrick const auto expedited_regs =
652be691f3bSpatrick reg_ctx.GetExpeditedRegisters(ExpeditedRegs::Full);
653061da546Spatrick #else
654be691f3bSpatrick const auto expedited_regs =
655be691f3bSpatrick reg_ctx.GetExpeditedRegisters(ExpeditedRegs::Minimal);
656061da546Spatrick #endif
657be691f3bSpatrick if (expedited_regs.empty())
658*f6aab3d8Srobert return std::nullopt;
659061da546Spatrick
660be691f3bSpatrick for (auto ®_num : expedited_regs) {
661061da546Spatrick const RegisterInfo *const reg_info_p =
662061da546Spatrick reg_ctx.GetRegisterInfoAtIndex(reg_num);
663061da546Spatrick if (reg_info_p == nullptr) {
664061da546Spatrick LLDB_LOGF(log,
665061da546Spatrick "%s failed to get register info for register index %" PRIu32,
666061da546Spatrick __FUNCTION__, reg_num);
667061da546Spatrick continue;
668061da546Spatrick }
669061da546Spatrick
670061da546Spatrick if (reg_info_p->value_regs != nullptr)
671061da546Spatrick continue; // Only expedite registers that are not contained in other
672061da546Spatrick // registers.
673061da546Spatrick
674061da546Spatrick RegisterValue reg_value;
675061da546Spatrick Status error = reg_ctx.ReadRegister(reg_info_p, reg_value);
676061da546Spatrick if (error.Fail()) {
677061da546Spatrick LLDB_LOGF(log, "%s failed to read register '%s' index %" PRIu32 ": %s",
678061da546Spatrick __FUNCTION__,
679061da546Spatrick reg_info_p->name ? reg_info_p->name : "<unnamed-register>",
680061da546Spatrick reg_num, error.AsCString());
681061da546Spatrick continue;
682061da546Spatrick }
683061da546Spatrick
684061da546Spatrick StreamString stream;
685061da546Spatrick WriteRegisterValueInHexFixedWidth(stream, reg_ctx, *reg_info_p,
686061da546Spatrick ®_value, lldb::eByteOrderBig);
687061da546Spatrick
688061da546Spatrick register_object.try_emplace(llvm::to_string(reg_num),
689061da546Spatrick stream.GetString().str());
690061da546Spatrick }
691061da546Spatrick
692061da546Spatrick return register_object;
693061da546Spatrick }
694061da546Spatrick
GetStopReasonString(StopReason stop_reason)695061da546Spatrick static const char *GetStopReasonString(StopReason stop_reason) {
696061da546Spatrick switch (stop_reason) {
697061da546Spatrick case eStopReasonTrace:
698061da546Spatrick return "trace";
699061da546Spatrick case eStopReasonBreakpoint:
700061da546Spatrick return "breakpoint";
701061da546Spatrick case eStopReasonWatchpoint:
702061da546Spatrick return "watchpoint";
703061da546Spatrick case eStopReasonSignal:
704061da546Spatrick return "signal";
705061da546Spatrick case eStopReasonException:
706061da546Spatrick return "exception";
707061da546Spatrick case eStopReasonExec:
708061da546Spatrick return "exec";
709be691f3bSpatrick case eStopReasonProcessorTrace:
710be691f3bSpatrick return "processor trace";
711be691f3bSpatrick case eStopReasonFork:
712be691f3bSpatrick return "fork";
713be691f3bSpatrick case eStopReasonVFork:
714be691f3bSpatrick return "vfork";
715be691f3bSpatrick case eStopReasonVForkDone:
716be691f3bSpatrick return "vforkdone";
717061da546Spatrick case eStopReasonInstrumentation:
718061da546Spatrick case eStopReasonInvalid:
719061da546Spatrick case eStopReasonPlanComplete:
720061da546Spatrick case eStopReasonThreadExiting:
721061da546Spatrick case eStopReasonNone:
722061da546Spatrick break; // ignored
723061da546Spatrick }
724061da546Spatrick return nullptr;
725061da546Spatrick }
726061da546Spatrick
727061da546Spatrick static llvm::Expected<json::Array>
GetJSONThreadsInfo(NativeProcessProtocol & process,bool abridged)728061da546Spatrick GetJSONThreadsInfo(NativeProcessProtocol &process, bool abridged) {
729*f6aab3d8Srobert Log *log = GetLog(LLDBLog::Process | LLDBLog::Thread);
730061da546Spatrick
731061da546Spatrick json::Array threads_array;
732061da546Spatrick
733061da546Spatrick // Ensure we can get info on the given thread.
734*f6aab3d8Srobert for (NativeThreadProtocol &thread : process.Threads()) {
735*f6aab3d8Srobert lldb::tid_t tid = thread.GetID();
736061da546Spatrick // Grab the reason this thread stopped.
737061da546Spatrick struct ThreadStopInfo tid_stop_info;
738061da546Spatrick std::string description;
739*f6aab3d8Srobert if (!thread.GetStopReason(tid_stop_info, description))
740061da546Spatrick return llvm::make_error<llvm::StringError>(
741061da546Spatrick "failed to get stop reason", llvm::inconvertibleErrorCode());
742061da546Spatrick
743*f6aab3d8Srobert const int signum = tid_stop_info.signo;
744061da546Spatrick if (log) {
745061da546Spatrick LLDB_LOGF(log,
746061da546Spatrick "GDBRemoteCommunicationServerLLGS::%s pid %" PRIu64
747061da546Spatrick " tid %" PRIu64
748061da546Spatrick " got signal signo = %d, reason = %d, exc_type = %" PRIu64,
749061da546Spatrick __FUNCTION__, process.GetID(), tid, signum,
750061da546Spatrick tid_stop_info.reason, tid_stop_info.details.exception.type);
751061da546Spatrick }
752061da546Spatrick
753061da546Spatrick json::Object thread_obj;
754061da546Spatrick
755061da546Spatrick if (!abridged) {
756*f6aab3d8Srobert if (std::optional<json::Object> registers = GetRegistersAsJSON(thread))
757061da546Spatrick thread_obj.try_emplace("registers", std::move(*registers));
758061da546Spatrick }
759061da546Spatrick
760061da546Spatrick thread_obj.try_emplace("tid", static_cast<int64_t>(tid));
761061da546Spatrick
762061da546Spatrick if (signum != 0)
763061da546Spatrick thread_obj.try_emplace("signal", signum);
764061da546Spatrick
765*f6aab3d8Srobert const std::string thread_name = thread.GetName();
766061da546Spatrick if (!thread_name.empty())
767061da546Spatrick thread_obj.try_emplace("name", thread_name);
768061da546Spatrick
769061da546Spatrick const char *stop_reason = GetStopReasonString(tid_stop_info.reason);
770061da546Spatrick if (stop_reason)
771061da546Spatrick thread_obj.try_emplace("reason", stop_reason);
772061da546Spatrick
773061da546Spatrick if (!description.empty())
774061da546Spatrick thread_obj.try_emplace("description", description);
775061da546Spatrick
776061da546Spatrick if ((tid_stop_info.reason == eStopReasonException) &&
777061da546Spatrick tid_stop_info.details.exception.type) {
778061da546Spatrick thread_obj.try_emplace(
779061da546Spatrick "metype", static_cast<int64_t>(tid_stop_info.details.exception.type));
780061da546Spatrick
781061da546Spatrick json::Array medata_array;
782061da546Spatrick for (uint32_t i = 0; i < tid_stop_info.details.exception.data_count;
783061da546Spatrick ++i) {
784061da546Spatrick medata_array.push_back(
785061da546Spatrick static_cast<int64_t>(tid_stop_info.details.exception.data[i]));
786061da546Spatrick }
787061da546Spatrick thread_obj.try_emplace("medata", std::move(medata_array));
788061da546Spatrick }
789061da546Spatrick threads_array.push_back(std::move(thread_obj));
790061da546Spatrick }
791061da546Spatrick return threads_array;
792061da546Spatrick }
793061da546Spatrick
794*f6aab3d8Srobert StreamString
PrepareStopReplyPacketForThread(NativeThreadProtocol & thread)795*f6aab3d8Srobert GDBRemoteCommunicationServerLLGS::PrepareStopReplyPacketForThread(
796*f6aab3d8Srobert NativeThreadProtocol &thread) {
797*f6aab3d8Srobert Log *log = GetLog(LLDBLog::Process | LLDBLog::Thread);
798061da546Spatrick
799*f6aab3d8Srobert NativeProcessProtocol &process = thread.GetProcess();
800061da546Spatrick
801*f6aab3d8Srobert LLDB_LOG(log, "preparing packet for pid {0} tid {1}", process.GetID(),
802*f6aab3d8Srobert thread.GetID());
803061da546Spatrick
804061da546Spatrick // Grab the reason this thread stopped.
805*f6aab3d8Srobert StreamString response;
806061da546Spatrick struct ThreadStopInfo tid_stop_info;
807061da546Spatrick std::string description;
808*f6aab3d8Srobert if (!thread.GetStopReason(tid_stop_info, description))
809*f6aab3d8Srobert return response;
810061da546Spatrick
811061da546Spatrick // FIXME implement register handling for exec'd inferiors.
812061da546Spatrick // if (tid_stop_info.reason == eStopReasonExec) {
813061da546Spatrick // const bool force = true;
814061da546Spatrick // InitializeRegisters(force);
815061da546Spatrick // }
816061da546Spatrick
817061da546Spatrick // Output the T packet with the thread
818061da546Spatrick response.PutChar('T');
819*f6aab3d8Srobert int signum = tid_stop_info.signo;
820061da546Spatrick LLDB_LOG(
821061da546Spatrick log,
822061da546Spatrick "pid {0}, tid {1}, got signal signo = {2}, reason = {3}, exc_type = {4}",
823*f6aab3d8Srobert process.GetID(), thread.GetID(), signum, int(tid_stop_info.reason),
824061da546Spatrick tid_stop_info.details.exception.type);
825061da546Spatrick
826061da546Spatrick // Print the signal number.
827061da546Spatrick response.PutHex8(signum & 0xff);
828061da546Spatrick
829*f6aab3d8Srobert // Include the (pid and) tid.
830*f6aab3d8Srobert response.PutCString("thread:");
831*f6aab3d8Srobert AppendThreadIDToResponse(response, process.GetID(), thread.GetID());
832*f6aab3d8Srobert response.PutChar(';');
833061da546Spatrick
834061da546Spatrick // Include the thread name if there is one.
835*f6aab3d8Srobert const std::string thread_name = thread.GetName();
836061da546Spatrick if (!thread_name.empty()) {
837061da546Spatrick size_t thread_name_len = thread_name.length();
838061da546Spatrick
839061da546Spatrick if (::strcspn(thread_name.c_str(), "$#+-;:") == thread_name_len) {
840061da546Spatrick response.PutCString("name:");
841061da546Spatrick response.PutCString(thread_name);
842061da546Spatrick } else {
843061da546Spatrick // The thread name contains special chars, send as hex bytes.
844061da546Spatrick response.PutCString("hexname:");
845061da546Spatrick response.PutStringAsRawHex8(thread_name);
846061da546Spatrick }
847061da546Spatrick response.PutChar(';');
848061da546Spatrick }
849061da546Spatrick
850061da546Spatrick // If a 'QListThreadsInStopReply' was sent to enable this feature, we will
851061da546Spatrick // send all thread IDs back in the "threads" key whose value is a list of hex
852061da546Spatrick // thread IDs separated by commas:
853061da546Spatrick // "threads:10a,10b,10c;"
854061da546Spatrick // This will save the debugger from having to send a pair of qfThreadInfo and
855061da546Spatrick // qsThreadInfo packets, but it also might take a lot of room in the stop
856061da546Spatrick // reply packet, so it must be enabled only on systems where there are no
857061da546Spatrick // limits on packet lengths.
858061da546Spatrick if (m_list_threads_in_stop_reply) {
859061da546Spatrick response.PutCString("threads:");
860061da546Spatrick
861*f6aab3d8Srobert uint32_t thread_num = 0;
862*f6aab3d8Srobert for (NativeThreadProtocol &listed_thread : process.Threads()) {
863*f6aab3d8Srobert if (thread_num > 0)
864061da546Spatrick response.PutChar(',');
865*f6aab3d8Srobert response.Printf("%" PRIx64, listed_thread.GetID());
866*f6aab3d8Srobert ++thread_num;
867061da546Spatrick }
868061da546Spatrick response.PutChar(';');
869061da546Spatrick
870061da546Spatrick // Include JSON info that describes the stop reason for any threads that
871061da546Spatrick // actually have stop reasons. We use the new "jstopinfo" key whose values
872061da546Spatrick // is hex ascii JSON that contains the thread IDs thread stop info only for
873061da546Spatrick // threads that have stop reasons. Only send this if we have more than one
874061da546Spatrick // thread otherwise this packet has all the info it needs.
875*f6aab3d8Srobert if (thread_num > 1) {
876061da546Spatrick const bool threads_with_valid_stop_info_only = true;
877061da546Spatrick llvm::Expected<json::Array> threads_info = GetJSONThreadsInfo(
878be691f3bSpatrick *m_current_process, threads_with_valid_stop_info_only);
879061da546Spatrick if (threads_info) {
880061da546Spatrick response.PutCString("jstopinfo:");
881061da546Spatrick StreamString unescaped_response;
882061da546Spatrick unescaped_response.AsRawOstream() << std::move(*threads_info);
883061da546Spatrick response.PutStringAsRawHex8(unescaped_response.GetData());
884061da546Spatrick response.PutChar(';');
885061da546Spatrick } else {
886061da546Spatrick LLDB_LOG_ERROR(log, threads_info.takeError(),
887061da546Spatrick "failed to prepare a jstopinfo field for pid {1}: {0}",
888*f6aab3d8Srobert process.GetID());
889061da546Spatrick }
890061da546Spatrick }
891061da546Spatrick
892061da546Spatrick response.PutCString("thread-pcs");
893061da546Spatrick char delimiter = ':';
894*f6aab3d8Srobert for (NativeThreadProtocol &thread : process.Threads()) {
895*f6aab3d8Srobert NativeRegisterContext ®_ctx = thread.GetRegisterContext();
896061da546Spatrick
897061da546Spatrick uint32_t reg_to_read = reg_ctx.ConvertRegisterKindToRegisterNumber(
898061da546Spatrick eRegisterKindGeneric, LLDB_REGNUM_GENERIC_PC);
899061da546Spatrick const RegisterInfo *const reg_info_p =
900061da546Spatrick reg_ctx.GetRegisterInfoAtIndex(reg_to_read);
901061da546Spatrick
902061da546Spatrick RegisterValue reg_value;
903061da546Spatrick Status error = reg_ctx.ReadRegister(reg_info_p, reg_value);
904061da546Spatrick if (error.Fail()) {
905061da546Spatrick LLDB_LOGF(log, "%s failed to read register '%s' index %" PRIu32 ": %s",
906061da546Spatrick __FUNCTION__,
907061da546Spatrick reg_info_p->name ? reg_info_p->name : "<unnamed-register>",
908061da546Spatrick reg_to_read, error.AsCString());
909061da546Spatrick continue;
910061da546Spatrick }
911061da546Spatrick
912061da546Spatrick response.PutChar(delimiter);
913061da546Spatrick delimiter = ',';
914061da546Spatrick WriteRegisterValueInHexFixedWidth(response, reg_ctx, *reg_info_p,
915061da546Spatrick ®_value, endian::InlHostByteOrder());
916061da546Spatrick }
917061da546Spatrick
918061da546Spatrick response.PutChar(';');
919061da546Spatrick }
920061da546Spatrick
921061da546Spatrick //
922061da546Spatrick // Expedite registers.
923061da546Spatrick //
924061da546Spatrick
925061da546Spatrick // Grab the register context.
926*f6aab3d8Srobert NativeRegisterContext ®_ctx = thread.GetRegisterContext();
927be691f3bSpatrick const auto expedited_regs =
928be691f3bSpatrick reg_ctx.GetExpeditedRegisters(ExpeditedRegs::Full);
929061da546Spatrick
930be691f3bSpatrick for (auto ®_num : expedited_regs) {
931061da546Spatrick const RegisterInfo *const reg_info_p =
932be691f3bSpatrick reg_ctx.GetRegisterInfoAtIndex(reg_num);
933061da546Spatrick // Only expediate registers that are not contained in other registers.
934be691f3bSpatrick if (reg_info_p != nullptr && reg_info_p->value_regs == nullptr) {
935061da546Spatrick RegisterValue reg_value;
936061da546Spatrick Status error = reg_ctx.ReadRegister(reg_info_p, reg_value);
937061da546Spatrick if (error.Success()) {
938be691f3bSpatrick response.Printf("%.02x:", reg_num);
939061da546Spatrick WriteRegisterValueInHexFixedWidth(response, reg_ctx, *reg_info_p,
940061da546Spatrick ®_value, lldb::eByteOrderBig);
941061da546Spatrick response.PutChar(';');
942061da546Spatrick } else {
943*f6aab3d8Srobert LLDB_LOGF(log,
944*f6aab3d8Srobert "GDBRemoteCommunicationServerLLGS::%s failed to read "
945061da546Spatrick "register '%s' index %" PRIu32 ": %s",
946061da546Spatrick __FUNCTION__,
947061da546Spatrick reg_info_p->name ? reg_info_p->name : "<unnamed-register>",
948be691f3bSpatrick reg_num, error.AsCString());
949061da546Spatrick }
950061da546Spatrick }
951061da546Spatrick }
952061da546Spatrick
953061da546Spatrick const char *reason_str = GetStopReasonString(tid_stop_info.reason);
954061da546Spatrick if (reason_str != nullptr) {
955061da546Spatrick response.Printf("reason:%s;", reason_str);
956061da546Spatrick }
957061da546Spatrick
958061da546Spatrick if (!description.empty()) {
959061da546Spatrick // Description may contains special chars, send as hex bytes.
960061da546Spatrick response.PutCString("description:");
961061da546Spatrick response.PutStringAsRawHex8(description);
962061da546Spatrick response.PutChar(';');
963061da546Spatrick } else if ((tid_stop_info.reason == eStopReasonException) &&
964061da546Spatrick tid_stop_info.details.exception.type) {
965061da546Spatrick response.PutCString("metype:");
966061da546Spatrick response.PutHex64(tid_stop_info.details.exception.type);
967061da546Spatrick response.PutCString(";mecount:");
968061da546Spatrick response.PutHex32(tid_stop_info.details.exception.data_count);
969061da546Spatrick response.PutChar(';');
970061da546Spatrick
971061da546Spatrick for (uint32_t i = 0; i < tid_stop_info.details.exception.data_count; ++i) {
972061da546Spatrick response.PutCString("medata:");
973061da546Spatrick response.PutHex64(tid_stop_info.details.exception.data[i]);
974061da546Spatrick response.PutChar(';');
975061da546Spatrick }
976061da546Spatrick }
977061da546Spatrick
978be691f3bSpatrick // Include child process PID/TID for forks.
979be691f3bSpatrick if (tid_stop_info.reason == eStopReasonFork ||
980be691f3bSpatrick tid_stop_info.reason == eStopReasonVFork) {
981be691f3bSpatrick assert(bool(m_extensions_supported &
982be691f3bSpatrick NativeProcessProtocol::Extension::multiprocess));
983be691f3bSpatrick if (tid_stop_info.reason == eStopReasonFork)
984be691f3bSpatrick assert(bool(m_extensions_supported &
985be691f3bSpatrick NativeProcessProtocol::Extension::fork));
986be691f3bSpatrick if (tid_stop_info.reason == eStopReasonVFork)
987be691f3bSpatrick assert(bool(m_extensions_supported &
988be691f3bSpatrick NativeProcessProtocol::Extension::vfork));
989be691f3bSpatrick response.Printf("%s:p%" PRIx64 ".%" PRIx64 ";", reason_str,
990be691f3bSpatrick tid_stop_info.details.fork.child_pid,
991be691f3bSpatrick tid_stop_info.details.fork.child_tid);
992be691f3bSpatrick }
993be691f3bSpatrick
994*f6aab3d8Srobert return response;
995*f6aab3d8Srobert }
996*f6aab3d8Srobert
997*f6aab3d8Srobert GDBRemoteCommunication::PacketResult
SendStopReplyPacketForThread(NativeProcessProtocol & process,lldb::tid_t tid,bool force_synchronous)998*f6aab3d8Srobert GDBRemoteCommunicationServerLLGS::SendStopReplyPacketForThread(
999*f6aab3d8Srobert NativeProcessProtocol &process, lldb::tid_t tid, bool force_synchronous) {
1000*f6aab3d8Srobert // Ensure we can get info on the given thread.
1001*f6aab3d8Srobert NativeThreadProtocol *thread = process.GetThreadByID(tid);
1002*f6aab3d8Srobert if (!thread)
1003*f6aab3d8Srobert return SendErrorResponse(51);
1004*f6aab3d8Srobert
1005*f6aab3d8Srobert StreamString response = PrepareStopReplyPacketForThread(*thread);
1006*f6aab3d8Srobert if (response.Empty())
1007*f6aab3d8Srobert return SendErrorResponse(42);
1008*f6aab3d8Srobert
1009*f6aab3d8Srobert if (m_non_stop && !force_synchronous) {
1010*f6aab3d8Srobert PacketResult ret = SendNotificationPacketNoLock(
1011*f6aab3d8Srobert "Stop", m_stop_notification_queue, response.GetString());
1012*f6aab3d8Srobert // Queue notification events for the remaining threads.
1013*f6aab3d8Srobert EnqueueStopReplyPackets(tid);
1014*f6aab3d8Srobert return ret;
1015*f6aab3d8Srobert }
1016*f6aab3d8Srobert
1017061da546Spatrick return SendPacketNoLock(response.GetString());
1018061da546Spatrick }
1019061da546Spatrick
EnqueueStopReplyPackets(lldb::tid_t thread_to_skip)1020*f6aab3d8Srobert void GDBRemoteCommunicationServerLLGS::EnqueueStopReplyPackets(
1021*f6aab3d8Srobert lldb::tid_t thread_to_skip) {
1022*f6aab3d8Srobert if (!m_non_stop)
1023*f6aab3d8Srobert return;
1024*f6aab3d8Srobert
1025*f6aab3d8Srobert for (NativeThreadProtocol &listed_thread : m_current_process->Threads()) {
1026*f6aab3d8Srobert if (listed_thread.GetID() != thread_to_skip) {
1027*f6aab3d8Srobert StreamString stop_reply = PrepareStopReplyPacketForThread(listed_thread);
1028*f6aab3d8Srobert if (!stop_reply.Empty())
1029*f6aab3d8Srobert m_stop_notification_queue.push_back(stop_reply.GetString().str());
1030*f6aab3d8Srobert }
1031*f6aab3d8Srobert }
1032*f6aab3d8Srobert }
1033*f6aab3d8Srobert
HandleInferiorState_Exited(NativeProcessProtocol * process)1034061da546Spatrick void GDBRemoteCommunicationServerLLGS::HandleInferiorState_Exited(
1035061da546Spatrick NativeProcessProtocol *process) {
1036061da546Spatrick assert(process && "process cannot be NULL");
1037061da546Spatrick
1038*f6aab3d8Srobert Log *log = GetLog(LLDBLog::Process);
1039061da546Spatrick LLDB_LOGF(log, "GDBRemoteCommunicationServerLLGS::%s called", __FUNCTION__);
1040061da546Spatrick
1041*f6aab3d8Srobert PacketResult result = SendStopReasonForState(
1042*f6aab3d8Srobert *process, StateType::eStateExited, /*force_synchronous=*/false);
1043061da546Spatrick if (result != PacketResult::Success) {
1044061da546Spatrick LLDB_LOGF(log,
1045061da546Spatrick "GDBRemoteCommunicationServerLLGS::%s failed to send stop "
1046061da546Spatrick "notification for PID %" PRIu64 ", state: eStateExited",
1047061da546Spatrick __FUNCTION__, process->GetID());
1048061da546Spatrick }
1049061da546Spatrick
1050*f6aab3d8Srobert if (m_current_process == process)
1051*f6aab3d8Srobert m_current_process = nullptr;
1052*f6aab3d8Srobert if (m_continue_process == process)
1053*f6aab3d8Srobert m_continue_process = nullptr;
1054*f6aab3d8Srobert
1055*f6aab3d8Srobert lldb::pid_t pid = process->GetID();
1056*f6aab3d8Srobert m_mainloop.AddPendingCallback([this, pid](MainLoopBase &loop) {
1057*f6aab3d8Srobert auto find_it = m_debugged_processes.find(pid);
1058*f6aab3d8Srobert assert(find_it != m_debugged_processes.end());
1059*f6aab3d8Srobert bool vkilled = bool(find_it->second.flags & DebuggedProcess::Flag::vkilled);
1060*f6aab3d8Srobert m_debugged_processes.erase(find_it);
1061*f6aab3d8Srobert // Terminate the main loop only if vKill has not been used.
1062*f6aab3d8Srobert // When running in non-stop mode, wait for the vStopped to clear
1063*f6aab3d8Srobert // the notification queue.
1064*f6aab3d8Srobert if (m_debugged_processes.empty() && !m_non_stop && !vkilled) {
1065*f6aab3d8Srobert // Close the pipe to the inferior terminal i/o if we launched it and set
1066*f6aab3d8Srobert // one up.
1067061da546Spatrick MaybeCloseInferiorTerminalConnection();
1068061da546Spatrick
1069061da546Spatrick // We are ready to exit the debug monitor.
1070061da546Spatrick m_exit_now = true;
1071*f6aab3d8Srobert loop.RequestTermination();
1072*f6aab3d8Srobert }
1073*f6aab3d8Srobert });
1074061da546Spatrick }
1075061da546Spatrick
HandleInferiorState_Stopped(NativeProcessProtocol * process)1076061da546Spatrick void GDBRemoteCommunicationServerLLGS::HandleInferiorState_Stopped(
1077061da546Spatrick NativeProcessProtocol *process) {
1078061da546Spatrick assert(process && "process cannot be NULL");
1079061da546Spatrick
1080*f6aab3d8Srobert Log *log = GetLog(LLDBLog::Process);
1081061da546Spatrick LLDB_LOGF(log, "GDBRemoteCommunicationServerLLGS::%s called", __FUNCTION__);
1082061da546Spatrick
1083*f6aab3d8Srobert PacketResult result = SendStopReasonForState(
1084*f6aab3d8Srobert *process, StateType::eStateStopped, /*force_synchronous=*/false);
1085061da546Spatrick if (result != PacketResult::Success) {
1086061da546Spatrick LLDB_LOGF(log,
1087061da546Spatrick "GDBRemoteCommunicationServerLLGS::%s failed to send stop "
1088061da546Spatrick "notification for PID %" PRIu64 ", state: eStateExited",
1089061da546Spatrick __FUNCTION__, process->GetID());
1090061da546Spatrick }
1091061da546Spatrick }
1092061da546Spatrick
ProcessStateChanged(NativeProcessProtocol * process,lldb::StateType state)1093061da546Spatrick void GDBRemoteCommunicationServerLLGS::ProcessStateChanged(
1094061da546Spatrick NativeProcessProtocol *process, lldb::StateType state) {
1095061da546Spatrick assert(process && "process cannot be NULL");
1096*f6aab3d8Srobert Log *log = GetLog(LLDBLog::Process);
1097061da546Spatrick if (log) {
1098061da546Spatrick LLDB_LOGF(log,
1099061da546Spatrick "GDBRemoteCommunicationServerLLGS::%s called with "
1100061da546Spatrick "NativeProcessProtocol pid %" PRIu64 ", state: %s",
1101061da546Spatrick __FUNCTION__, process->GetID(), StateAsCString(state));
1102061da546Spatrick }
1103061da546Spatrick
1104061da546Spatrick switch (state) {
1105061da546Spatrick case StateType::eStateRunning:
1106061da546Spatrick break;
1107061da546Spatrick
1108061da546Spatrick case StateType::eStateStopped:
1109061da546Spatrick // Make sure we get all of the pending stdout/stderr from the inferior and
1110061da546Spatrick // send it to the lldb host before we send the state change notification
1111061da546Spatrick SendProcessOutput();
1112061da546Spatrick // Then stop the forwarding, so that any late output (see llvm.org/pr25652)
1113061da546Spatrick // does not interfere with our protocol.
1114*f6aab3d8Srobert if (!m_non_stop)
1115061da546Spatrick StopSTDIOForwarding();
1116061da546Spatrick HandleInferiorState_Stopped(process);
1117061da546Spatrick break;
1118061da546Spatrick
1119061da546Spatrick case StateType::eStateExited:
1120061da546Spatrick // Same as above
1121061da546Spatrick SendProcessOutput();
1122*f6aab3d8Srobert if (!m_non_stop)
1123061da546Spatrick StopSTDIOForwarding();
1124061da546Spatrick HandleInferiorState_Exited(process);
1125061da546Spatrick break;
1126061da546Spatrick
1127061da546Spatrick default:
1128061da546Spatrick if (log) {
1129061da546Spatrick LLDB_LOGF(log,
1130061da546Spatrick "GDBRemoteCommunicationServerLLGS::%s didn't handle state "
1131061da546Spatrick "change for pid %" PRIu64 ", new state: %s",
1132061da546Spatrick __FUNCTION__, process->GetID(), StateAsCString(state));
1133061da546Spatrick }
1134061da546Spatrick break;
1135061da546Spatrick }
1136061da546Spatrick }
1137061da546Spatrick
DidExec(NativeProcessProtocol * process)1138061da546Spatrick void GDBRemoteCommunicationServerLLGS::DidExec(NativeProcessProtocol *process) {
1139061da546Spatrick ClearProcessSpecificData();
1140061da546Spatrick }
1141061da546Spatrick
NewSubprocess(NativeProcessProtocol * parent_process,std::unique_ptr<NativeProcessProtocol> child_process)1142be691f3bSpatrick void GDBRemoteCommunicationServerLLGS::NewSubprocess(
1143be691f3bSpatrick NativeProcessProtocol *parent_process,
1144be691f3bSpatrick std::unique_ptr<NativeProcessProtocol> child_process) {
1145be691f3bSpatrick lldb::pid_t child_pid = child_process->GetID();
1146be691f3bSpatrick assert(child_pid != LLDB_INVALID_PROCESS_ID);
1147be691f3bSpatrick assert(m_debugged_processes.find(child_pid) == m_debugged_processes.end());
1148*f6aab3d8Srobert m_debugged_processes.emplace(
1149*f6aab3d8Srobert child_pid,
1150*f6aab3d8Srobert DebuggedProcess{std::move(child_process), DebuggedProcess::Flag{}});
1151be691f3bSpatrick }
1152be691f3bSpatrick
DataAvailableCallback()1153061da546Spatrick void GDBRemoteCommunicationServerLLGS::DataAvailableCallback() {
1154*f6aab3d8Srobert Log *log = GetLog(GDBRLog::Comm);
1155061da546Spatrick
1156061da546Spatrick bool interrupt = false;
1157061da546Spatrick bool done = false;
1158061da546Spatrick Status error;
1159061da546Spatrick while (true) {
1160061da546Spatrick const PacketResult result = GetPacketAndSendResponse(
1161061da546Spatrick std::chrono::microseconds(0), error, interrupt, done);
1162061da546Spatrick if (result == PacketResult::ErrorReplyTimeout)
1163061da546Spatrick break; // No more packets in the queue
1164061da546Spatrick
1165061da546Spatrick if ((result != PacketResult::Success)) {
1166061da546Spatrick LLDB_LOGF(log,
1167061da546Spatrick "GDBRemoteCommunicationServerLLGS::%s processing a packet "
1168061da546Spatrick "failed: %s",
1169061da546Spatrick __FUNCTION__, error.AsCString());
1170061da546Spatrick m_mainloop.RequestTermination();
1171061da546Spatrick break;
1172061da546Spatrick }
1173061da546Spatrick }
1174061da546Spatrick }
1175061da546Spatrick
InitializeConnection(std::unique_ptr<Connection> connection)1176061da546Spatrick Status GDBRemoteCommunicationServerLLGS::InitializeConnection(
1177dda28197Spatrick std::unique_ptr<Connection> connection) {
1178061da546Spatrick IOObjectSP read_object_sp = connection->GetReadObject();
1179dda28197Spatrick GDBRemoteCommunicationServer::SetConnection(std::move(connection));
1180061da546Spatrick
1181061da546Spatrick Status error;
1182061da546Spatrick m_network_handle_up = m_mainloop.RegisterReadObject(
1183061da546Spatrick read_object_sp, [this](MainLoopBase &) { DataAvailableCallback(); },
1184061da546Spatrick error);
1185061da546Spatrick return error;
1186061da546Spatrick }
1187061da546Spatrick
1188061da546Spatrick GDBRemoteCommunication::PacketResult
SendONotification(const char * buffer,uint32_t len)1189061da546Spatrick GDBRemoteCommunicationServerLLGS::SendONotification(const char *buffer,
1190061da546Spatrick uint32_t len) {
1191061da546Spatrick if ((buffer == nullptr) || (len == 0)) {
1192061da546Spatrick // Nothing to send.
1193061da546Spatrick return PacketResult::Success;
1194061da546Spatrick }
1195061da546Spatrick
1196061da546Spatrick StreamString response;
1197061da546Spatrick response.PutChar('O');
1198061da546Spatrick response.PutBytesAsRawHex8(buffer, len);
1199061da546Spatrick
1200*f6aab3d8Srobert if (m_non_stop)
1201*f6aab3d8Srobert return SendNotificationPacketNoLock("Stdio", m_stdio_notification_queue,
1202*f6aab3d8Srobert response.GetString());
1203061da546Spatrick return SendPacketNoLock(response.GetString());
1204061da546Spatrick }
1205061da546Spatrick
SetSTDIOFileDescriptor(int fd)1206061da546Spatrick Status GDBRemoteCommunicationServerLLGS::SetSTDIOFileDescriptor(int fd) {
1207061da546Spatrick Status error;
1208061da546Spatrick
1209061da546Spatrick // Set up the reading/handling of process I/O
1210061da546Spatrick std::unique_ptr<ConnectionFileDescriptor> conn_up(
1211061da546Spatrick new ConnectionFileDescriptor(fd, true));
1212061da546Spatrick if (!conn_up) {
1213061da546Spatrick error.SetErrorString("failed to create ConnectionFileDescriptor");
1214061da546Spatrick return error;
1215061da546Spatrick }
1216061da546Spatrick
1217061da546Spatrick m_stdio_communication.SetCloseOnEOF(false);
1218dda28197Spatrick m_stdio_communication.SetConnection(std::move(conn_up));
1219061da546Spatrick if (!m_stdio_communication.IsConnected()) {
1220061da546Spatrick error.SetErrorString(
1221061da546Spatrick "failed to set connection for inferior I/O communication");
1222061da546Spatrick return error;
1223061da546Spatrick }
1224061da546Spatrick
1225061da546Spatrick return Status();
1226061da546Spatrick }
1227061da546Spatrick
StartSTDIOForwarding()1228061da546Spatrick void GDBRemoteCommunicationServerLLGS::StartSTDIOForwarding() {
1229061da546Spatrick // Don't forward if not connected (e.g. when attaching).
1230061da546Spatrick if (!m_stdio_communication.IsConnected())
1231061da546Spatrick return;
1232061da546Spatrick
1233061da546Spatrick Status error;
1234*f6aab3d8Srobert assert(!m_stdio_handle_up);
1235061da546Spatrick m_stdio_handle_up = m_mainloop.RegisterReadObject(
1236061da546Spatrick m_stdio_communication.GetConnection()->GetReadObject(),
1237061da546Spatrick [this](MainLoopBase &) { SendProcessOutput(); }, error);
1238061da546Spatrick
1239061da546Spatrick if (!m_stdio_handle_up) {
1240061da546Spatrick // Not much we can do about the failure. Log it and continue without
1241061da546Spatrick // forwarding.
1242*f6aab3d8Srobert if (Log *log = GetLog(LLDBLog::Process))
1243*f6aab3d8Srobert LLDB_LOG(log, "Failed to set up stdio forwarding: {0}", error);
1244061da546Spatrick }
1245061da546Spatrick }
1246061da546Spatrick
StopSTDIOForwarding()1247061da546Spatrick void GDBRemoteCommunicationServerLLGS::StopSTDIOForwarding() {
1248061da546Spatrick m_stdio_handle_up.reset();
1249061da546Spatrick }
1250061da546Spatrick
SendProcessOutput()1251061da546Spatrick void GDBRemoteCommunicationServerLLGS::SendProcessOutput() {
1252061da546Spatrick char buffer[1024];
1253061da546Spatrick ConnectionStatus status;
1254061da546Spatrick Status error;
1255061da546Spatrick while (true) {
1256061da546Spatrick size_t bytes_read = m_stdio_communication.Read(
1257061da546Spatrick buffer, sizeof buffer, std::chrono::microseconds(0), status, &error);
1258061da546Spatrick switch (status) {
1259061da546Spatrick case eConnectionStatusSuccess:
1260061da546Spatrick SendONotification(buffer, bytes_read);
1261061da546Spatrick break;
1262061da546Spatrick case eConnectionStatusLostConnection:
1263061da546Spatrick case eConnectionStatusEndOfFile:
1264061da546Spatrick case eConnectionStatusError:
1265061da546Spatrick case eConnectionStatusNoConnection:
1266*f6aab3d8Srobert if (Log *log = GetLog(LLDBLog::Process))
1267061da546Spatrick LLDB_LOGF(log,
1268061da546Spatrick "GDBRemoteCommunicationServerLLGS::%s Stopping stdio "
1269061da546Spatrick "forwarding as communication returned status %d (error: "
1270061da546Spatrick "%s)",
1271061da546Spatrick __FUNCTION__, status, error.AsCString());
1272061da546Spatrick m_stdio_handle_up.reset();
1273061da546Spatrick return;
1274061da546Spatrick
1275061da546Spatrick case eConnectionStatusInterrupted:
1276061da546Spatrick case eConnectionStatusTimedOut:
1277061da546Spatrick return;
1278061da546Spatrick }
1279061da546Spatrick }
1280061da546Spatrick }
1281061da546Spatrick
1282061da546Spatrick GDBRemoteCommunication::PacketResult
Handle_jLLDBTraceSupported(StringExtractorGDBRemote & packet)1283be691f3bSpatrick GDBRemoteCommunicationServerLLGS::Handle_jLLDBTraceSupported(
1284061da546Spatrick StringExtractorGDBRemote &packet) {
1285be691f3bSpatrick
1286061da546Spatrick // Fail if we don't have a current process.
1287be691f3bSpatrick if (!m_current_process ||
1288be691f3bSpatrick (m_current_process->GetID() == LLDB_INVALID_PROCESS_ID))
1289be691f3bSpatrick return SendErrorResponse(Status("Process not running."));
1290061da546Spatrick
1291be691f3bSpatrick return SendJSONResponse(m_current_process->TraceSupported());
1292061da546Spatrick }
1293061da546Spatrick
1294061da546Spatrick GDBRemoteCommunication::PacketResult
Handle_jLLDBTraceStop(StringExtractorGDBRemote & packet)1295be691f3bSpatrick GDBRemoteCommunicationServerLLGS::Handle_jLLDBTraceStop(
1296061da546Spatrick StringExtractorGDBRemote &packet) {
1297061da546Spatrick // Fail if we don't have a current process.
1298be691f3bSpatrick if (!m_current_process ||
1299be691f3bSpatrick (m_current_process->GetID() == LLDB_INVALID_PROCESS_ID))
1300be691f3bSpatrick return SendErrorResponse(Status("Process not running."));
1301061da546Spatrick
1302be691f3bSpatrick packet.ConsumeFront("jLLDBTraceStop:");
1303be691f3bSpatrick Expected<TraceStopRequest> stop_request =
1304be691f3bSpatrick json::parse<TraceStopRequest>(packet.Peek(), "TraceStopRequest");
1305be691f3bSpatrick if (!stop_request)
1306be691f3bSpatrick return SendErrorResponse(stop_request.takeError());
1307061da546Spatrick
1308be691f3bSpatrick if (Error err = m_current_process->TraceStop(*stop_request))
1309be691f3bSpatrick return SendErrorResponse(std::move(err));
1310061da546Spatrick
1311061da546Spatrick return SendOKResponse();
1312061da546Spatrick }
1313061da546Spatrick
1314061da546Spatrick GDBRemoteCommunication::PacketResult
Handle_jLLDBTraceStart(StringExtractorGDBRemote & packet)1315be691f3bSpatrick GDBRemoteCommunicationServerLLGS::Handle_jLLDBTraceStart(
1316061da546Spatrick StringExtractorGDBRemote &packet) {
1317061da546Spatrick
1318061da546Spatrick // Fail if we don't have a current process.
1319be691f3bSpatrick if (!m_current_process ||
1320be691f3bSpatrick (m_current_process->GetID() == LLDB_INVALID_PROCESS_ID))
1321be691f3bSpatrick return SendErrorResponse(Status("Process not running."));
1322061da546Spatrick
1323be691f3bSpatrick packet.ConsumeFront("jLLDBTraceStart:");
1324be691f3bSpatrick Expected<TraceStartRequest> request =
1325be691f3bSpatrick json::parse<TraceStartRequest>(packet.Peek(), "TraceStartRequest");
1326be691f3bSpatrick if (!request)
1327be691f3bSpatrick return SendErrorResponse(request.takeError());
1328061da546Spatrick
1329be691f3bSpatrick if (Error err = m_current_process->TraceStart(packet.Peek(), request->type))
1330be691f3bSpatrick return SendErrorResponse(std::move(err));
1331061da546Spatrick
1332be691f3bSpatrick return SendOKResponse();
1333061da546Spatrick }
1334061da546Spatrick
1335061da546Spatrick GDBRemoteCommunication::PacketResult
Handle_jLLDBTraceGetState(StringExtractorGDBRemote & packet)1336be691f3bSpatrick GDBRemoteCommunicationServerLLGS::Handle_jLLDBTraceGetState(
1337061da546Spatrick StringExtractorGDBRemote &packet) {
1338061da546Spatrick
1339061da546Spatrick // Fail if we don't have a current process.
1340be691f3bSpatrick if (!m_current_process ||
1341be691f3bSpatrick (m_current_process->GetID() == LLDB_INVALID_PROCESS_ID))
1342be691f3bSpatrick return SendErrorResponse(Status("Process not running."));
1343061da546Spatrick
1344be691f3bSpatrick packet.ConsumeFront("jLLDBTraceGetState:");
1345be691f3bSpatrick Expected<TraceGetStateRequest> request =
1346be691f3bSpatrick json::parse<TraceGetStateRequest>(packet.Peek(), "TraceGetStateRequest");
1347be691f3bSpatrick if (!request)
1348be691f3bSpatrick return SendErrorResponse(request.takeError());
1349061da546Spatrick
1350be691f3bSpatrick return SendJSONResponse(m_current_process->TraceGetState(request->type));
1351061da546Spatrick }
1352061da546Spatrick
1353be691f3bSpatrick GDBRemoteCommunication::PacketResult
Handle_jLLDBTraceGetBinaryData(StringExtractorGDBRemote & packet)1354be691f3bSpatrick GDBRemoteCommunicationServerLLGS::Handle_jLLDBTraceGetBinaryData(
1355be691f3bSpatrick StringExtractorGDBRemote &packet) {
1356061da546Spatrick
1357be691f3bSpatrick // Fail if we don't have a current process.
1358be691f3bSpatrick if (!m_current_process ||
1359be691f3bSpatrick (m_current_process->GetID() == LLDB_INVALID_PROCESS_ID))
1360be691f3bSpatrick return SendErrorResponse(Status("Process not running."));
1361061da546Spatrick
1362be691f3bSpatrick packet.ConsumeFront("jLLDBTraceGetBinaryData:");
1363be691f3bSpatrick llvm::Expected<TraceGetBinaryDataRequest> request =
1364be691f3bSpatrick llvm::json::parse<TraceGetBinaryDataRequest>(packet.Peek(),
1365be691f3bSpatrick "TraceGetBinaryDataRequest");
1366be691f3bSpatrick if (!request)
1367be691f3bSpatrick return SendErrorResponse(Status(request.takeError()));
1368061da546Spatrick
1369be691f3bSpatrick if (Expected<std::vector<uint8_t>> bytes =
1370be691f3bSpatrick m_current_process->TraceGetBinaryData(*request)) {
1371061da546Spatrick StreamGDBRemote response;
1372be691f3bSpatrick response.PutEscapedBytes(bytes->data(), bytes->size());
1373be691f3bSpatrick return SendPacketNoLock(response.GetString());
1374be691f3bSpatrick } else
1375be691f3bSpatrick return SendErrorResponse(bytes.takeError());
1376061da546Spatrick }
1377061da546Spatrick
1378061da546Spatrick GDBRemoteCommunication::PacketResult
Handle_qProcessInfo(StringExtractorGDBRemote & packet)1379061da546Spatrick GDBRemoteCommunicationServerLLGS::Handle_qProcessInfo(
1380061da546Spatrick StringExtractorGDBRemote &packet) {
1381061da546Spatrick // Fail if we don't have a current process.
1382be691f3bSpatrick if (!m_current_process ||
1383be691f3bSpatrick (m_current_process->GetID() == LLDB_INVALID_PROCESS_ID))
1384061da546Spatrick return SendErrorResponse(68);
1385061da546Spatrick
1386be691f3bSpatrick lldb::pid_t pid = m_current_process->GetID();
1387061da546Spatrick
1388061da546Spatrick if (pid == LLDB_INVALID_PROCESS_ID)
1389061da546Spatrick return SendErrorResponse(1);
1390061da546Spatrick
1391061da546Spatrick ProcessInstanceInfo proc_info;
1392061da546Spatrick if (!Host::GetProcessInfo(pid, proc_info))
1393061da546Spatrick return SendErrorResponse(1);
1394061da546Spatrick
1395061da546Spatrick StreamString response;
1396061da546Spatrick CreateProcessInfoResponse_DebugServerStyle(proc_info, response);
1397061da546Spatrick return SendPacketNoLock(response.GetString());
1398061da546Spatrick }
1399061da546Spatrick
1400061da546Spatrick GDBRemoteCommunication::PacketResult
Handle_qC(StringExtractorGDBRemote & packet)1401061da546Spatrick GDBRemoteCommunicationServerLLGS::Handle_qC(StringExtractorGDBRemote &packet) {
1402061da546Spatrick // Fail if we don't have a current process.
1403be691f3bSpatrick if (!m_current_process ||
1404be691f3bSpatrick (m_current_process->GetID() == LLDB_INVALID_PROCESS_ID))
1405061da546Spatrick return SendErrorResponse(68);
1406061da546Spatrick
1407061da546Spatrick // Make sure we set the current thread so g and p packets return the data the
1408061da546Spatrick // gdb will expect.
1409be691f3bSpatrick lldb::tid_t tid = m_current_process->GetCurrentThreadID();
1410061da546Spatrick SetCurrentThreadID(tid);
1411061da546Spatrick
1412be691f3bSpatrick NativeThreadProtocol *thread = m_current_process->GetCurrentThread();
1413061da546Spatrick if (!thread)
1414061da546Spatrick return SendErrorResponse(69);
1415061da546Spatrick
1416061da546Spatrick StreamString response;
1417*f6aab3d8Srobert response.PutCString("QC");
1418*f6aab3d8Srobert AppendThreadIDToResponse(response, m_current_process->GetID(),
1419*f6aab3d8Srobert thread->GetID());
1420061da546Spatrick
1421061da546Spatrick return SendPacketNoLock(response.GetString());
1422061da546Spatrick }
1423061da546Spatrick
1424061da546Spatrick GDBRemoteCommunication::PacketResult
Handle_k(StringExtractorGDBRemote & packet)1425061da546Spatrick GDBRemoteCommunicationServerLLGS::Handle_k(StringExtractorGDBRemote &packet) {
1426*f6aab3d8Srobert Log *log = GetLog(LLDBLog::Process);
1427061da546Spatrick
1428*f6aab3d8Srobert if (!m_non_stop)
1429061da546Spatrick StopSTDIOForwarding();
1430061da546Spatrick
1431*f6aab3d8Srobert if (m_debugged_processes.empty()) {
1432061da546Spatrick LLDB_LOG(log, "No debugged process found.");
1433061da546Spatrick return PacketResult::Success;
1434061da546Spatrick }
1435061da546Spatrick
1436*f6aab3d8Srobert for (auto it = m_debugged_processes.begin(); it != m_debugged_processes.end();
1437*f6aab3d8Srobert ++it) {
1438*f6aab3d8Srobert LLDB_LOG(log, "Killing process {0}", it->first);
1439*f6aab3d8Srobert Status error = it->second.process_up->Kill();
1440061da546Spatrick if (error.Fail())
1441*f6aab3d8Srobert LLDB_LOG(log, "Failed to kill debugged process {0}: {1}", it->first,
1442*f6aab3d8Srobert error);
1443*f6aab3d8Srobert }
1444061da546Spatrick
1445*f6aab3d8Srobert // The response to kill packet is undefined per the spec. LLDB
1446*f6aab3d8Srobert // follows the same rules as for continue packets, i.e. no response
1447*f6aab3d8Srobert // in all-stop mode, and "OK" in non-stop mode; in both cases this
1448*f6aab3d8Srobert // is followed by the actual stop reason.
1449*f6aab3d8Srobert return SendContinueSuccessResponse();
1450*f6aab3d8Srobert }
1451*f6aab3d8Srobert
1452*f6aab3d8Srobert GDBRemoteCommunication::PacketResult
Handle_vKill(StringExtractorGDBRemote & packet)1453*f6aab3d8Srobert GDBRemoteCommunicationServerLLGS::Handle_vKill(
1454*f6aab3d8Srobert StringExtractorGDBRemote &packet) {
1455*f6aab3d8Srobert if (!m_non_stop)
1456*f6aab3d8Srobert StopSTDIOForwarding();
1457*f6aab3d8Srobert
1458*f6aab3d8Srobert packet.SetFilePos(6); // vKill;
1459*f6aab3d8Srobert uint32_t pid = packet.GetU32(LLDB_INVALID_PROCESS_ID, 16);
1460*f6aab3d8Srobert if (pid == LLDB_INVALID_PROCESS_ID)
1461*f6aab3d8Srobert return SendIllFormedResponse(packet,
1462*f6aab3d8Srobert "vKill failed to parse the process id");
1463*f6aab3d8Srobert
1464*f6aab3d8Srobert auto it = m_debugged_processes.find(pid);
1465*f6aab3d8Srobert if (it == m_debugged_processes.end())
1466*f6aab3d8Srobert return SendErrorResponse(42);
1467*f6aab3d8Srobert
1468*f6aab3d8Srobert Status error = it->second.process_up->Kill();
1469*f6aab3d8Srobert if (error.Fail())
1470*f6aab3d8Srobert return SendErrorResponse(error.ToError());
1471*f6aab3d8Srobert
1472*f6aab3d8Srobert // OK response is sent when the process dies.
1473*f6aab3d8Srobert it->second.flags |= DebuggedProcess::Flag::vkilled;
1474061da546Spatrick return PacketResult::Success;
1475061da546Spatrick }
1476061da546Spatrick
1477061da546Spatrick GDBRemoteCommunication::PacketResult
Handle_QSetDisableASLR(StringExtractorGDBRemote & packet)1478061da546Spatrick GDBRemoteCommunicationServerLLGS::Handle_QSetDisableASLR(
1479061da546Spatrick StringExtractorGDBRemote &packet) {
1480061da546Spatrick packet.SetFilePos(::strlen("QSetDisableASLR:"));
1481061da546Spatrick if (packet.GetU32(0))
1482061da546Spatrick m_process_launch_info.GetFlags().Set(eLaunchFlagDisableASLR);
1483061da546Spatrick else
1484061da546Spatrick m_process_launch_info.GetFlags().Clear(eLaunchFlagDisableASLR);
1485061da546Spatrick return SendOKResponse();
1486061da546Spatrick }
1487061da546Spatrick
1488061da546Spatrick GDBRemoteCommunication::PacketResult
Handle_QSetWorkingDir(StringExtractorGDBRemote & packet)1489061da546Spatrick GDBRemoteCommunicationServerLLGS::Handle_QSetWorkingDir(
1490061da546Spatrick StringExtractorGDBRemote &packet) {
1491061da546Spatrick packet.SetFilePos(::strlen("QSetWorkingDir:"));
1492061da546Spatrick std::string path;
1493061da546Spatrick packet.GetHexByteString(path);
1494061da546Spatrick m_process_launch_info.SetWorkingDirectory(FileSpec(path));
1495061da546Spatrick return SendOKResponse();
1496061da546Spatrick }
1497061da546Spatrick
1498061da546Spatrick GDBRemoteCommunication::PacketResult
Handle_qGetWorkingDir(StringExtractorGDBRemote & packet)1499061da546Spatrick GDBRemoteCommunicationServerLLGS::Handle_qGetWorkingDir(
1500061da546Spatrick StringExtractorGDBRemote &packet) {
1501061da546Spatrick FileSpec working_dir{m_process_launch_info.GetWorkingDirectory()};
1502061da546Spatrick if (working_dir) {
1503061da546Spatrick StreamString response;
1504*f6aab3d8Srobert response.PutStringAsRawHex8(working_dir.GetPath().c_str());
1505061da546Spatrick return SendPacketNoLock(response.GetString());
1506061da546Spatrick }
1507061da546Spatrick
1508061da546Spatrick return SendErrorResponse(14);
1509061da546Spatrick }
1510061da546Spatrick
1511061da546Spatrick GDBRemoteCommunication::PacketResult
Handle_QThreadSuffixSupported(StringExtractorGDBRemote & packet)1512be691f3bSpatrick GDBRemoteCommunicationServerLLGS::Handle_QThreadSuffixSupported(
1513be691f3bSpatrick StringExtractorGDBRemote &packet) {
1514be691f3bSpatrick m_thread_suffix_supported = true;
1515be691f3bSpatrick return SendOKResponse();
1516be691f3bSpatrick }
1517be691f3bSpatrick
1518be691f3bSpatrick GDBRemoteCommunication::PacketResult
Handle_QListThreadsInStopReply(StringExtractorGDBRemote & packet)1519be691f3bSpatrick GDBRemoteCommunicationServerLLGS::Handle_QListThreadsInStopReply(
1520be691f3bSpatrick StringExtractorGDBRemote &packet) {
1521be691f3bSpatrick m_list_threads_in_stop_reply = true;
1522be691f3bSpatrick return SendOKResponse();
1523be691f3bSpatrick }
1524be691f3bSpatrick
1525be691f3bSpatrick GDBRemoteCommunication::PacketResult
ResumeProcess(NativeProcessProtocol & process,const ResumeActionList & actions)1526*f6aab3d8Srobert GDBRemoteCommunicationServerLLGS::ResumeProcess(
1527*f6aab3d8Srobert NativeProcessProtocol &process, const ResumeActionList &actions) {
1528*f6aab3d8Srobert Log *log = GetLog(LLDBLog::Process | LLDBLog::Thread);
1529*f6aab3d8Srobert
1530*f6aab3d8Srobert // In non-stop protocol mode, the process could be running already.
1531*f6aab3d8Srobert // We do not support resuming threads independently, so just error out.
1532*f6aab3d8Srobert if (!process.CanResume()) {
1533*f6aab3d8Srobert LLDB_LOG(log, "process {0} cannot be resumed (state={1})", process.GetID(),
1534*f6aab3d8Srobert process.GetState());
1535*f6aab3d8Srobert return SendErrorResponse(0x37);
1536*f6aab3d8Srobert }
1537*f6aab3d8Srobert
1538*f6aab3d8Srobert Status error = process.Resume(actions);
1539*f6aab3d8Srobert if (error.Fail()) {
1540*f6aab3d8Srobert LLDB_LOG(log, "process {0} failed to resume: {1}", process.GetID(), error);
1541*f6aab3d8Srobert return SendErrorResponse(GDBRemoteServerError::eErrorResume);
1542*f6aab3d8Srobert }
1543*f6aab3d8Srobert
1544*f6aab3d8Srobert LLDB_LOG(log, "process {0} resumed", process.GetID());
1545*f6aab3d8Srobert
1546*f6aab3d8Srobert return PacketResult::Success;
1547*f6aab3d8Srobert }
1548*f6aab3d8Srobert
1549*f6aab3d8Srobert GDBRemoteCommunication::PacketResult
Handle_C(StringExtractorGDBRemote & packet)1550061da546Spatrick GDBRemoteCommunicationServerLLGS::Handle_C(StringExtractorGDBRemote &packet) {
1551*f6aab3d8Srobert Log *log = GetLog(LLDBLog::Process | LLDBLog::Thread);
1552061da546Spatrick LLDB_LOGF(log, "GDBRemoteCommunicationServerLLGS::%s called", __FUNCTION__);
1553061da546Spatrick
1554061da546Spatrick // Ensure we have a native process.
1555be691f3bSpatrick if (!m_continue_process) {
1556061da546Spatrick LLDB_LOGF(log,
1557061da546Spatrick "GDBRemoteCommunicationServerLLGS::%s no debugged process "
1558061da546Spatrick "shared pointer",
1559061da546Spatrick __FUNCTION__);
1560061da546Spatrick return SendErrorResponse(0x36);
1561061da546Spatrick }
1562061da546Spatrick
1563061da546Spatrick // Pull out the signal number.
1564061da546Spatrick packet.SetFilePos(::strlen("C"));
1565061da546Spatrick if (packet.GetBytesLeft() < 1) {
1566061da546Spatrick // Shouldn't be using a C without a signal.
1567061da546Spatrick return SendIllFormedResponse(packet, "C packet specified without signal.");
1568061da546Spatrick }
1569061da546Spatrick const uint32_t signo =
1570061da546Spatrick packet.GetHexMaxU32(false, std::numeric_limits<uint32_t>::max());
1571061da546Spatrick if (signo == std::numeric_limits<uint32_t>::max())
1572061da546Spatrick return SendIllFormedResponse(packet, "failed to parse signal number");
1573061da546Spatrick
1574061da546Spatrick // Handle optional continue address.
1575061da546Spatrick if (packet.GetBytesLeft() > 0) {
1576061da546Spatrick // FIXME add continue at address support for $C{signo}[;{continue-address}].
1577061da546Spatrick if (*packet.Peek() == ';')
1578061da546Spatrick return SendUnimplementedResponse(packet.GetStringRef().data());
1579061da546Spatrick else
1580061da546Spatrick return SendIllFormedResponse(
1581061da546Spatrick packet, "unexpected content after $C{signal-number}");
1582061da546Spatrick }
1583061da546Spatrick
1584*f6aab3d8Srobert // In non-stop protocol mode, the process could be running already.
1585*f6aab3d8Srobert // We do not support resuming threads independently, so just error out.
1586*f6aab3d8Srobert if (!m_continue_process->CanResume()) {
1587*f6aab3d8Srobert LLDB_LOG(log, "process cannot be resumed (state={0})",
1588*f6aab3d8Srobert m_continue_process->GetState());
1589*f6aab3d8Srobert return SendErrorResponse(0x37);
1590*f6aab3d8Srobert }
1591*f6aab3d8Srobert
1592061da546Spatrick ResumeActionList resume_actions(StateType::eStateRunning,
1593061da546Spatrick LLDB_INVALID_SIGNAL_NUMBER);
1594061da546Spatrick Status error;
1595061da546Spatrick
1596061da546Spatrick // We have two branches: what to do if a continue thread is specified (in
1597061da546Spatrick // which case we target sending the signal to that thread), or when we don't
1598061da546Spatrick // have a continue thread set (in which case we send a signal to the
1599061da546Spatrick // process).
1600061da546Spatrick
1601061da546Spatrick // TODO discuss with Greg Clayton, make sure this makes sense.
1602061da546Spatrick
1603061da546Spatrick lldb::tid_t signal_tid = GetContinueThreadID();
1604061da546Spatrick if (signal_tid != LLDB_INVALID_THREAD_ID) {
1605061da546Spatrick // The resume action for the continue thread (or all threads if a continue
1606061da546Spatrick // thread is not set).
1607061da546Spatrick ResumeAction action = {GetContinueThreadID(), StateType::eStateRunning,
1608061da546Spatrick static_cast<int>(signo)};
1609061da546Spatrick
1610061da546Spatrick // Add the action for the continue thread (or all threads when the continue
1611061da546Spatrick // thread isn't present).
1612061da546Spatrick resume_actions.Append(action);
1613061da546Spatrick } else {
1614061da546Spatrick // Send the signal to the process since we weren't targeting a specific
1615061da546Spatrick // continue thread with the signal.
1616be691f3bSpatrick error = m_continue_process->Signal(signo);
1617061da546Spatrick if (error.Fail()) {
1618061da546Spatrick LLDB_LOG(log, "failed to send signal for process {0}: {1}",
1619be691f3bSpatrick m_continue_process->GetID(), error);
1620061da546Spatrick
1621061da546Spatrick return SendErrorResponse(0x52);
1622061da546Spatrick }
1623061da546Spatrick }
1624061da546Spatrick
1625*f6aab3d8Srobert // NB: this checks CanResume() twice but using a single code path for
1626*f6aab3d8Srobert // resuming still seems worth it.
1627*f6aab3d8Srobert PacketResult resume_res = ResumeProcess(*m_continue_process, resume_actions);
1628*f6aab3d8Srobert if (resume_res != PacketResult::Success)
1629*f6aab3d8Srobert return resume_res;
1630061da546Spatrick
1631*f6aab3d8Srobert // Don't send an "OK" packet, except in non-stop mode;
1632*f6aab3d8Srobert // otherwise, the response is the stopped/exited message.
1633*f6aab3d8Srobert return SendContinueSuccessResponse();
1634061da546Spatrick }
1635061da546Spatrick
1636061da546Spatrick GDBRemoteCommunication::PacketResult
Handle_c(StringExtractorGDBRemote & packet)1637061da546Spatrick GDBRemoteCommunicationServerLLGS::Handle_c(StringExtractorGDBRemote &packet) {
1638*f6aab3d8Srobert Log *log = GetLog(LLDBLog::Process | LLDBLog::Thread);
1639061da546Spatrick LLDB_LOGF(log, "GDBRemoteCommunicationServerLLGS::%s called", __FUNCTION__);
1640061da546Spatrick
1641061da546Spatrick packet.SetFilePos(packet.GetFilePos() + ::strlen("c"));
1642061da546Spatrick
1643061da546Spatrick // For now just support all continue.
1644061da546Spatrick const bool has_continue_address = (packet.GetBytesLeft() > 0);
1645061da546Spatrick if (has_continue_address) {
1646061da546Spatrick LLDB_LOG(log, "not implemented for c[address] variant [{0} remains]",
1647061da546Spatrick packet.Peek());
1648061da546Spatrick return SendUnimplementedResponse(packet.GetStringRef().data());
1649061da546Spatrick }
1650061da546Spatrick
1651061da546Spatrick // Ensure we have a native process.
1652be691f3bSpatrick if (!m_continue_process) {
1653061da546Spatrick LLDB_LOGF(log,
1654061da546Spatrick "GDBRemoteCommunicationServerLLGS::%s no debugged process "
1655061da546Spatrick "shared pointer",
1656061da546Spatrick __FUNCTION__);
1657061da546Spatrick return SendErrorResponse(0x36);
1658061da546Spatrick }
1659061da546Spatrick
1660061da546Spatrick // Build the ResumeActionList
1661061da546Spatrick ResumeActionList actions(StateType::eStateRunning,
1662061da546Spatrick LLDB_INVALID_SIGNAL_NUMBER);
1663061da546Spatrick
1664*f6aab3d8Srobert PacketResult resume_res = ResumeProcess(*m_continue_process, actions);
1665*f6aab3d8Srobert if (resume_res != PacketResult::Success)
1666*f6aab3d8Srobert return resume_res;
1667061da546Spatrick
1668*f6aab3d8Srobert return SendContinueSuccessResponse();
1669061da546Spatrick }
1670061da546Spatrick
1671061da546Spatrick GDBRemoteCommunication::PacketResult
Handle_vCont_actions(StringExtractorGDBRemote & packet)1672061da546Spatrick GDBRemoteCommunicationServerLLGS::Handle_vCont_actions(
1673061da546Spatrick StringExtractorGDBRemote &packet) {
1674061da546Spatrick StreamString response;
1675*f6aab3d8Srobert response.Printf("vCont;c;C;s;S;t");
1676061da546Spatrick
1677061da546Spatrick return SendPacketNoLock(response.GetString());
1678061da546Spatrick }
1679061da546Spatrick
ResumeActionListStopsAllThreads(ResumeActionList & actions)1680*f6aab3d8Srobert static bool ResumeActionListStopsAllThreads(ResumeActionList &actions) {
1681*f6aab3d8Srobert // We're doing a stop-all if and only if our only action is a "t" for all
1682*f6aab3d8Srobert // threads.
1683*f6aab3d8Srobert if (const ResumeAction *default_action =
1684*f6aab3d8Srobert actions.GetActionForThread(LLDB_INVALID_THREAD_ID, false)) {
1685*f6aab3d8Srobert if (default_action->state == eStateSuspended && actions.GetSize() == 1)
1686*f6aab3d8Srobert return true;
1687*f6aab3d8Srobert }
1688*f6aab3d8Srobert
1689*f6aab3d8Srobert return false;
1690*f6aab3d8Srobert }
1691*f6aab3d8Srobert
1692061da546Spatrick GDBRemoteCommunication::PacketResult
Handle_vCont(StringExtractorGDBRemote & packet)1693061da546Spatrick GDBRemoteCommunicationServerLLGS::Handle_vCont(
1694061da546Spatrick StringExtractorGDBRemote &packet) {
1695*f6aab3d8Srobert Log *log = GetLog(LLDBLog::Process);
1696061da546Spatrick LLDB_LOGF(log, "GDBRemoteCommunicationServerLLGS::%s handling vCont packet",
1697061da546Spatrick __FUNCTION__);
1698061da546Spatrick
1699061da546Spatrick packet.SetFilePos(::strlen("vCont"));
1700061da546Spatrick
1701061da546Spatrick if (packet.GetBytesLeft() == 0) {
1702061da546Spatrick LLDB_LOGF(log,
1703061da546Spatrick "GDBRemoteCommunicationServerLLGS::%s missing action from "
1704061da546Spatrick "vCont package",
1705061da546Spatrick __FUNCTION__);
1706061da546Spatrick return SendIllFormedResponse(packet, "Missing action from vCont package");
1707061da546Spatrick }
1708061da546Spatrick
1709*f6aab3d8Srobert if (::strcmp(packet.Peek(), ";s") == 0) {
1710061da546Spatrick // Move past the ';', then do a simple 's'.
1711061da546Spatrick packet.SetFilePos(packet.GetFilePos() + 1);
1712061da546Spatrick return Handle_s(packet);
1713061da546Spatrick }
1714061da546Spatrick
1715*f6aab3d8Srobert std::unordered_map<lldb::pid_t, ResumeActionList> thread_actions;
1716061da546Spatrick
1717061da546Spatrick while (packet.GetBytesLeft() && *packet.Peek() == ';') {
1718061da546Spatrick // Skip the semi-colon.
1719061da546Spatrick packet.GetChar();
1720061da546Spatrick
1721061da546Spatrick // Build up the thread action.
1722061da546Spatrick ResumeAction thread_action;
1723061da546Spatrick thread_action.tid = LLDB_INVALID_THREAD_ID;
1724061da546Spatrick thread_action.state = eStateInvalid;
1725061da546Spatrick thread_action.signal = LLDB_INVALID_SIGNAL_NUMBER;
1726061da546Spatrick
1727061da546Spatrick const char action = packet.GetChar();
1728061da546Spatrick switch (action) {
1729061da546Spatrick case 'C':
1730061da546Spatrick thread_action.signal = packet.GetHexMaxU32(false, 0);
1731061da546Spatrick if (thread_action.signal == 0)
1732061da546Spatrick return SendIllFormedResponse(
1733061da546Spatrick packet, "Could not parse signal in vCont packet C action");
1734*f6aab3d8Srobert [[fallthrough]];
1735061da546Spatrick
1736061da546Spatrick case 'c':
1737061da546Spatrick // Continue
1738061da546Spatrick thread_action.state = eStateRunning;
1739061da546Spatrick break;
1740061da546Spatrick
1741061da546Spatrick case 'S':
1742061da546Spatrick thread_action.signal = packet.GetHexMaxU32(false, 0);
1743061da546Spatrick if (thread_action.signal == 0)
1744061da546Spatrick return SendIllFormedResponse(
1745061da546Spatrick packet, "Could not parse signal in vCont packet S action");
1746*f6aab3d8Srobert [[fallthrough]];
1747061da546Spatrick
1748061da546Spatrick case 's':
1749061da546Spatrick // Step
1750061da546Spatrick thread_action.state = eStateStepping;
1751061da546Spatrick break;
1752061da546Spatrick
1753*f6aab3d8Srobert case 't':
1754*f6aab3d8Srobert // Stop
1755*f6aab3d8Srobert thread_action.state = eStateSuspended;
1756*f6aab3d8Srobert break;
1757*f6aab3d8Srobert
1758061da546Spatrick default:
1759061da546Spatrick return SendIllFormedResponse(packet, "Unsupported vCont action");
1760061da546Spatrick break;
1761061da546Spatrick }
1762061da546Spatrick
1763*f6aab3d8Srobert // If there's no thread-id (e.g. "vCont;c"), it's "p-1.-1".
1764*f6aab3d8Srobert lldb::pid_t pid = StringExtractorGDBRemote::AllProcesses;
1765*f6aab3d8Srobert lldb::tid_t tid = StringExtractorGDBRemote::AllThreads;
1766*f6aab3d8Srobert
1767061da546Spatrick // Parse out optional :{thread-id} value.
1768061da546Spatrick if (packet.GetBytesLeft() && (*packet.Peek() == ':')) {
1769061da546Spatrick // Consume the separator.
1770061da546Spatrick packet.GetChar();
1771061da546Spatrick
1772*f6aab3d8Srobert auto pid_tid = packet.GetPidTid(LLDB_INVALID_PROCESS_ID);
1773*f6aab3d8Srobert if (!pid_tid)
1774*f6aab3d8Srobert return SendIllFormedResponse(packet, "Malformed thread-id");
1775be691f3bSpatrick
1776*f6aab3d8Srobert pid = pid_tid->first;
1777*f6aab3d8Srobert tid = pid_tid->second;
1778061da546Spatrick }
1779061da546Spatrick
1780*f6aab3d8Srobert if (thread_action.state == eStateSuspended &&
1781*f6aab3d8Srobert tid != StringExtractorGDBRemote::AllThreads) {
1782*f6aab3d8Srobert return SendIllFormedResponse(
1783*f6aab3d8Srobert packet, "'t' action not supported for individual threads");
1784061da546Spatrick }
1785061da546Spatrick
1786*f6aab3d8Srobert // If we get TID without PID, it's the current process.
1787*f6aab3d8Srobert if (pid == LLDB_INVALID_PROCESS_ID) {
1788*f6aab3d8Srobert if (!m_continue_process) {
1789*f6aab3d8Srobert LLDB_LOG(log, "no process selected via Hc");
1790*f6aab3d8Srobert return SendErrorResponse(0x36);
1791*f6aab3d8Srobert }
1792*f6aab3d8Srobert pid = m_continue_process->GetID();
1793*f6aab3d8Srobert }
1794*f6aab3d8Srobert
1795*f6aab3d8Srobert assert(pid != LLDB_INVALID_PROCESS_ID);
1796*f6aab3d8Srobert if (tid == StringExtractorGDBRemote::AllThreads)
1797*f6aab3d8Srobert tid = LLDB_INVALID_THREAD_ID;
1798*f6aab3d8Srobert thread_action.tid = tid;
1799*f6aab3d8Srobert
1800*f6aab3d8Srobert if (pid == StringExtractorGDBRemote::AllProcesses) {
1801*f6aab3d8Srobert if (tid != LLDB_INVALID_THREAD_ID)
1802*f6aab3d8Srobert return SendIllFormedResponse(
1803*f6aab3d8Srobert packet, "vCont: p-1 is not valid with a specific tid");
1804*f6aab3d8Srobert for (auto &process_it : m_debugged_processes)
1805*f6aab3d8Srobert thread_actions[process_it.first].Append(thread_action);
1806*f6aab3d8Srobert } else
1807*f6aab3d8Srobert thread_actions[pid].Append(thread_action);
1808*f6aab3d8Srobert }
1809*f6aab3d8Srobert
1810*f6aab3d8Srobert assert(thread_actions.size() >= 1);
1811*f6aab3d8Srobert if (thread_actions.size() > 1 && !m_non_stop)
1812*f6aab3d8Srobert return SendIllFormedResponse(
1813*f6aab3d8Srobert packet,
1814*f6aab3d8Srobert "Resuming multiple processes is supported in non-stop mode only");
1815*f6aab3d8Srobert
1816*f6aab3d8Srobert for (std::pair<lldb::pid_t, ResumeActionList> x : thread_actions) {
1817*f6aab3d8Srobert auto process_it = m_debugged_processes.find(x.first);
1818*f6aab3d8Srobert if (process_it == m_debugged_processes.end()) {
1819*f6aab3d8Srobert LLDB_LOG(log, "vCont failed for process {0}: process not debugged",
1820*f6aab3d8Srobert x.first);
1821061da546Spatrick return SendErrorResponse(GDBRemoteServerError::eErrorResume);
1822061da546Spatrick }
1823061da546Spatrick
1824*f6aab3d8Srobert // There are four possible scenarios here. These are:
1825*f6aab3d8Srobert // 1. vCont on a stopped process that resumes at least one thread.
1826*f6aab3d8Srobert // In this case, we call Resume().
1827*f6aab3d8Srobert // 2. vCont on a stopped process that leaves all threads suspended.
1828*f6aab3d8Srobert // A no-op.
1829*f6aab3d8Srobert // 3. vCont on a running process that requests suspending all
1830*f6aab3d8Srobert // running threads. In this case, we call Interrupt().
1831*f6aab3d8Srobert // 4. vCont on a running process that requests suspending a subset
1832*f6aab3d8Srobert // of running threads or resuming a subset of suspended threads.
1833*f6aab3d8Srobert // Since we do not support full nonstop mode, this is unsupported
1834*f6aab3d8Srobert // and we return an error.
1835*f6aab3d8Srobert
1836*f6aab3d8Srobert assert(process_it->second.process_up);
1837*f6aab3d8Srobert if (ResumeActionListStopsAllThreads(x.second)) {
1838*f6aab3d8Srobert if (process_it->second.process_up->IsRunning()) {
1839*f6aab3d8Srobert assert(m_non_stop);
1840*f6aab3d8Srobert
1841*f6aab3d8Srobert Status error = process_it->second.process_up->Interrupt();
1842*f6aab3d8Srobert if (error.Fail()) {
1843*f6aab3d8Srobert LLDB_LOG(log, "vCont failed to halt process {0}: {1}", x.first,
1844*f6aab3d8Srobert error);
1845*f6aab3d8Srobert return SendErrorResponse(GDBRemoteServerError::eErrorResume);
1846*f6aab3d8Srobert }
1847*f6aab3d8Srobert
1848*f6aab3d8Srobert LLDB_LOG(log, "halted process {0}", x.first);
1849*f6aab3d8Srobert
1850*f6aab3d8Srobert // hack to avoid enabling stdio forwarding after stop
1851*f6aab3d8Srobert // TODO: remove this when we improve stdio forwarding for nonstop
1852*f6aab3d8Srobert assert(thread_actions.size() == 1);
1853*f6aab3d8Srobert return SendOKResponse();
1854*f6aab3d8Srobert }
1855*f6aab3d8Srobert } else {
1856*f6aab3d8Srobert PacketResult resume_res =
1857*f6aab3d8Srobert ResumeProcess(*process_it->second.process_up, x.second);
1858*f6aab3d8Srobert if (resume_res != PacketResult::Success)
1859*f6aab3d8Srobert return resume_res;
1860*f6aab3d8Srobert }
1861*f6aab3d8Srobert }
1862*f6aab3d8Srobert
1863*f6aab3d8Srobert return SendContinueSuccessResponse();
1864061da546Spatrick }
1865061da546Spatrick
SetCurrentThreadID(lldb::tid_t tid)1866061da546Spatrick void GDBRemoteCommunicationServerLLGS::SetCurrentThreadID(lldb::tid_t tid) {
1867*f6aab3d8Srobert Log *log = GetLog(LLDBLog::Thread);
1868061da546Spatrick LLDB_LOG(log, "setting current thread id to {0}", tid);
1869061da546Spatrick
1870061da546Spatrick m_current_tid = tid;
1871be691f3bSpatrick if (m_current_process)
1872be691f3bSpatrick m_current_process->SetCurrentThreadID(m_current_tid);
1873061da546Spatrick }
1874061da546Spatrick
SetContinueThreadID(lldb::tid_t tid)1875061da546Spatrick void GDBRemoteCommunicationServerLLGS::SetContinueThreadID(lldb::tid_t tid) {
1876*f6aab3d8Srobert Log *log = GetLog(LLDBLog::Thread);
1877061da546Spatrick LLDB_LOG(log, "setting continue thread id to {0}", tid);
1878061da546Spatrick
1879061da546Spatrick m_continue_tid = tid;
1880061da546Spatrick }
1881061da546Spatrick
1882061da546Spatrick GDBRemoteCommunication::PacketResult
Handle_stop_reason(StringExtractorGDBRemote & packet)1883061da546Spatrick GDBRemoteCommunicationServerLLGS::Handle_stop_reason(
1884061da546Spatrick StringExtractorGDBRemote &packet) {
1885061da546Spatrick // Handle the $? gdbremote command.
1886061da546Spatrick
1887*f6aab3d8Srobert if (m_non_stop) {
1888*f6aab3d8Srobert // Clear the notification queue first, except for pending exit
1889*f6aab3d8Srobert // notifications.
1890*f6aab3d8Srobert llvm::erase_if(m_stop_notification_queue, [](const std::string &x) {
1891*f6aab3d8Srobert return x.front() != 'W' && x.front() != 'X';
1892*f6aab3d8Srobert });
1893*f6aab3d8Srobert
1894*f6aab3d8Srobert if (m_current_process) {
1895*f6aab3d8Srobert // Queue stop reply packets for all active threads. Start with
1896*f6aab3d8Srobert // the current thread (for clients that don't actually support multiple
1897*f6aab3d8Srobert // stop reasons).
1898*f6aab3d8Srobert NativeThreadProtocol *thread = m_current_process->GetCurrentThread();
1899*f6aab3d8Srobert if (thread) {
1900*f6aab3d8Srobert StreamString stop_reply = PrepareStopReplyPacketForThread(*thread);
1901*f6aab3d8Srobert if (!stop_reply.Empty())
1902*f6aab3d8Srobert m_stop_notification_queue.push_back(stop_reply.GetString().str());
1903*f6aab3d8Srobert }
1904*f6aab3d8Srobert EnqueueStopReplyPackets(thread ? thread->GetID()
1905*f6aab3d8Srobert : LLDB_INVALID_THREAD_ID);
1906*f6aab3d8Srobert }
1907*f6aab3d8Srobert
1908*f6aab3d8Srobert // If the notification queue is empty (i.e. everything is running), send OK.
1909*f6aab3d8Srobert if (m_stop_notification_queue.empty())
1910*f6aab3d8Srobert return SendOKResponse();
1911*f6aab3d8Srobert
1912*f6aab3d8Srobert // Send the first item from the new notification queue synchronously.
1913*f6aab3d8Srobert return SendPacketNoLock(m_stop_notification_queue.front());
1914*f6aab3d8Srobert }
1915*f6aab3d8Srobert
1916061da546Spatrick // If no process, indicate error
1917be691f3bSpatrick if (!m_current_process)
1918061da546Spatrick return SendErrorResponse(02);
1919061da546Spatrick
1920*f6aab3d8Srobert return SendStopReasonForState(*m_current_process,
1921*f6aab3d8Srobert m_current_process->GetState(),
1922*f6aab3d8Srobert /*force_synchronous=*/true);
1923061da546Spatrick }
1924061da546Spatrick
1925061da546Spatrick GDBRemoteCommunication::PacketResult
SendStopReasonForState(NativeProcessProtocol & process,lldb::StateType process_state,bool force_synchronous)1926061da546Spatrick GDBRemoteCommunicationServerLLGS::SendStopReasonForState(
1927*f6aab3d8Srobert NativeProcessProtocol &process, lldb::StateType process_state,
1928*f6aab3d8Srobert bool force_synchronous) {
1929*f6aab3d8Srobert Log *log = GetLog(LLDBLog::Process);
1930*f6aab3d8Srobert
1931*f6aab3d8Srobert if (m_disabling_non_stop) {
1932*f6aab3d8Srobert // Check if we are waiting for any more processes to stop. If we are,
1933*f6aab3d8Srobert // do not send the OK response yet.
1934*f6aab3d8Srobert for (const auto &it : m_debugged_processes) {
1935*f6aab3d8Srobert if (it.second.process_up->IsRunning())
1936*f6aab3d8Srobert return PacketResult::Success;
1937*f6aab3d8Srobert }
1938*f6aab3d8Srobert
1939*f6aab3d8Srobert // If all expected processes were stopped after a QNonStop:0 request,
1940*f6aab3d8Srobert // send the OK response.
1941*f6aab3d8Srobert m_disabling_non_stop = false;
1942*f6aab3d8Srobert return SendOKResponse();
1943*f6aab3d8Srobert }
1944061da546Spatrick
1945061da546Spatrick switch (process_state) {
1946061da546Spatrick case eStateAttaching:
1947061da546Spatrick case eStateLaunching:
1948061da546Spatrick case eStateRunning:
1949061da546Spatrick case eStateStepping:
1950061da546Spatrick case eStateDetached:
1951061da546Spatrick // NOTE: gdb protocol doc looks like it should return $OK
1952061da546Spatrick // when everything is running (i.e. no stopped result).
1953061da546Spatrick return PacketResult::Success; // Ignore
1954061da546Spatrick
1955061da546Spatrick case eStateSuspended:
1956061da546Spatrick case eStateStopped:
1957061da546Spatrick case eStateCrashed: {
1958*f6aab3d8Srobert lldb::tid_t tid = process.GetCurrentThreadID();
1959061da546Spatrick // Make sure we set the current thread so g and p packets return the data
1960061da546Spatrick // the gdb will expect.
1961061da546Spatrick SetCurrentThreadID(tid);
1962*f6aab3d8Srobert return SendStopReplyPacketForThread(process, tid, force_synchronous);
1963061da546Spatrick }
1964061da546Spatrick
1965061da546Spatrick case eStateInvalid:
1966061da546Spatrick case eStateUnloaded:
1967061da546Spatrick case eStateExited:
1968*f6aab3d8Srobert return SendWResponse(&process);
1969061da546Spatrick
1970061da546Spatrick default:
1971061da546Spatrick LLDB_LOG(log, "pid {0}, current state reporting not handled: {1}",
1972*f6aab3d8Srobert process.GetID(), process_state);
1973061da546Spatrick break;
1974061da546Spatrick }
1975061da546Spatrick
1976061da546Spatrick return SendErrorResponse(0);
1977061da546Spatrick }
1978061da546Spatrick
1979061da546Spatrick GDBRemoteCommunication::PacketResult
Handle_qRegisterInfo(StringExtractorGDBRemote & packet)1980061da546Spatrick GDBRemoteCommunicationServerLLGS::Handle_qRegisterInfo(
1981061da546Spatrick StringExtractorGDBRemote &packet) {
1982061da546Spatrick // Fail if we don't have a current process.
1983be691f3bSpatrick if (!m_current_process ||
1984be691f3bSpatrick (m_current_process->GetID() == LLDB_INVALID_PROCESS_ID))
1985061da546Spatrick return SendErrorResponse(68);
1986061da546Spatrick
1987061da546Spatrick // Ensure we have a thread.
1988be691f3bSpatrick NativeThreadProtocol *thread = m_current_process->GetThreadAtIndex(0);
1989061da546Spatrick if (!thread)
1990061da546Spatrick return SendErrorResponse(69);
1991061da546Spatrick
1992061da546Spatrick // Get the register context for the first thread.
1993061da546Spatrick NativeRegisterContext ®_context = thread->GetRegisterContext();
1994061da546Spatrick
1995061da546Spatrick // Parse out the register number from the request.
1996061da546Spatrick packet.SetFilePos(strlen("qRegisterInfo"));
1997061da546Spatrick const uint32_t reg_index =
1998061da546Spatrick packet.GetHexMaxU32(false, std::numeric_limits<uint32_t>::max());
1999061da546Spatrick if (reg_index == std::numeric_limits<uint32_t>::max())
2000061da546Spatrick return SendErrorResponse(69);
2001061da546Spatrick
2002061da546Spatrick // Return the end of registers response if we've iterated one past the end of
2003061da546Spatrick // the register set.
2004061da546Spatrick if (reg_index >= reg_context.GetUserRegisterCount())
2005061da546Spatrick return SendErrorResponse(69);
2006061da546Spatrick
2007061da546Spatrick const RegisterInfo *reg_info = reg_context.GetRegisterInfoAtIndex(reg_index);
2008061da546Spatrick if (!reg_info)
2009061da546Spatrick return SendErrorResponse(69);
2010061da546Spatrick
2011061da546Spatrick // Build the reginfos response.
2012061da546Spatrick StreamGDBRemote response;
2013061da546Spatrick
2014061da546Spatrick response.PutCString("name:");
2015061da546Spatrick response.PutCString(reg_info->name);
2016061da546Spatrick response.PutChar(';');
2017061da546Spatrick
2018061da546Spatrick if (reg_info->alt_name && reg_info->alt_name[0]) {
2019061da546Spatrick response.PutCString("alt-name:");
2020061da546Spatrick response.PutCString(reg_info->alt_name);
2021061da546Spatrick response.PutChar(';');
2022061da546Spatrick }
2023061da546Spatrick
2024be691f3bSpatrick response.Printf("bitsize:%" PRIu32 ";", reg_info->byte_size * 8);
2025be691f3bSpatrick
2026be691f3bSpatrick if (!reg_context.RegisterOffsetIsDynamic())
2027be691f3bSpatrick response.Printf("offset:%" PRIu32 ";", reg_info->byte_offset);
2028061da546Spatrick
2029dda28197Spatrick llvm::StringRef encoding = GetEncodingNameOrEmpty(*reg_info);
2030dda28197Spatrick if (!encoding.empty())
2031dda28197Spatrick response << "encoding:" << encoding << ';';
2032061da546Spatrick
2033dda28197Spatrick llvm::StringRef format = GetFormatNameOrEmpty(*reg_info);
2034dda28197Spatrick if (!format.empty())
2035dda28197Spatrick response << "format:" << format << ';';
2036061da546Spatrick
2037061da546Spatrick const char *const register_set_name =
2038061da546Spatrick reg_context.GetRegisterSetNameForRegisterAtIndex(reg_index);
2039dda28197Spatrick if (register_set_name)
2040dda28197Spatrick response << "set:" << register_set_name << ';';
2041061da546Spatrick
2042061da546Spatrick if (reg_info->kinds[RegisterKind::eRegisterKindEHFrame] !=
2043061da546Spatrick LLDB_INVALID_REGNUM)
2044061da546Spatrick response.Printf("ehframe:%" PRIu32 ";",
2045061da546Spatrick reg_info->kinds[RegisterKind::eRegisterKindEHFrame]);
2046061da546Spatrick
2047061da546Spatrick if (reg_info->kinds[RegisterKind::eRegisterKindDWARF] != LLDB_INVALID_REGNUM)
2048061da546Spatrick response.Printf("dwarf:%" PRIu32 ";",
2049061da546Spatrick reg_info->kinds[RegisterKind::eRegisterKindDWARF]);
2050061da546Spatrick
2051dda28197Spatrick llvm::StringRef kind_generic = GetKindGenericOrEmpty(*reg_info);
2052dda28197Spatrick if (!kind_generic.empty())
2053dda28197Spatrick response << "generic:" << kind_generic << ';';
2054061da546Spatrick
2055061da546Spatrick if (reg_info->value_regs && reg_info->value_regs[0] != LLDB_INVALID_REGNUM) {
2056061da546Spatrick response.PutCString("container-regs:");
2057dda28197Spatrick CollectRegNums(reg_info->value_regs, response, true);
2058061da546Spatrick response.PutChar(';');
2059061da546Spatrick }
2060061da546Spatrick
2061061da546Spatrick if (reg_info->invalidate_regs && reg_info->invalidate_regs[0]) {
2062061da546Spatrick response.PutCString("invalidate-regs:");
2063dda28197Spatrick CollectRegNums(reg_info->invalidate_regs, response, true);
2064061da546Spatrick response.PutChar(';');
2065061da546Spatrick }
2066061da546Spatrick
2067061da546Spatrick return SendPacketNoLock(response.GetString());
2068061da546Spatrick }
2069061da546Spatrick
AddProcessThreads(StreamGDBRemote & response,NativeProcessProtocol & process,bool & had_any)2070*f6aab3d8Srobert void GDBRemoteCommunicationServerLLGS::AddProcessThreads(
2071*f6aab3d8Srobert StreamGDBRemote &response, NativeProcessProtocol &process, bool &had_any) {
2072*f6aab3d8Srobert Log *log = GetLog(LLDBLog::Thread);
2073*f6aab3d8Srobert
2074*f6aab3d8Srobert lldb::pid_t pid = process.GetID();
2075*f6aab3d8Srobert if (pid == LLDB_INVALID_PROCESS_ID)
2076*f6aab3d8Srobert return;
2077*f6aab3d8Srobert
2078*f6aab3d8Srobert LLDB_LOG(log, "iterating over threads of process {0}", process.GetID());
2079*f6aab3d8Srobert for (NativeThreadProtocol &thread : process.Threads()) {
2080*f6aab3d8Srobert LLDB_LOG(log, "iterated thread tid={0}", thread.GetID());
2081*f6aab3d8Srobert response.PutChar(had_any ? ',' : 'm');
2082*f6aab3d8Srobert AppendThreadIDToResponse(response, pid, thread.GetID());
2083*f6aab3d8Srobert had_any = true;
2084*f6aab3d8Srobert }
2085*f6aab3d8Srobert }
2086*f6aab3d8Srobert
2087061da546Spatrick GDBRemoteCommunication::PacketResult
Handle_qfThreadInfo(StringExtractorGDBRemote & packet)2088061da546Spatrick GDBRemoteCommunicationServerLLGS::Handle_qfThreadInfo(
2089061da546Spatrick StringExtractorGDBRemote &packet) {
2090*f6aab3d8Srobert assert(m_debugged_processes.size() == 1 ||
2091*f6aab3d8Srobert bool(m_extensions_supported &
2092*f6aab3d8Srobert NativeProcessProtocol::Extension::multiprocess));
2093061da546Spatrick
2094*f6aab3d8Srobert bool had_any = false;
2095061da546Spatrick StreamGDBRemote response;
2096061da546Spatrick
2097*f6aab3d8Srobert for (auto &pid_ptr : m_debugged_processes)
2098*f6aab3d8Srobert AddProcessThreads(response, *pid_ptr.second.process_up, had_any);
2099061da546Spatrick
2100*f6aab3d8Srobert if (!had_any)
2101*f6aab3d8Srobert return SendOKResponse();
2102061da546Spatrick return SendPacketNoLock(response.GetString());
2103061da546Spatrick }
2104061da546Spatrick
2105061da546Spatrick GDBRemoteCommunication::PacketResult
Handle_qsThreadInfo(StringExtractorGDBRemote & packet)2106061da546Spatrick GDBRemoteCommunicationServerLLGS::Handle_qsThreadInfo(
2107061da546Spatrick StringExtractorGDBRemote &packet) {
2108061da546Spatrick // FIXME for now we return the full thread list in the initial packet and
2109061da546Spatrick // always do nothing here.
2110061da546Spatrick return SendPacketNoLock("l");
2111061da546Spatrick }
2112061da546Spatrick
2113061da546Spatrick GDBRemoteCommunication::PacketResult
Handle_g(StringExtractorGDBRemote & packet)2114061da546Spatrick GDBRemoteCommunicationServerLLGS::Handle_g(StringExtractorGDBRemote &packet) {
2115*f6aab3d8Srobert Log *log = GetLog(LLDBLog::Thread);
2116061da546Spatrick
2117061da546Spatrick // Move past packet name.
2118061da546Spatrick packet.SetFilePos(strlen("g"));
2119061da546Spatrick
2120061da546Spatrick // Get the thread to use.
2121061da546Spatrick NativeThreadProtocol *thread = GetThreadFromSuffix(packet);
2122061da546Spatrick if (!thread) {
2123061da546Spatrick LLDB_LOG(log, "failed, no thread available");
2124061da546Spatrick return SendErrorResponse(0x15);
2125061da546Spatrick }
2126061da546Spatrick
2127061da546Spatrick // Get the thread's register context.
2128061da546Spatrick NativeRegisterContext ®_ctx = thread->GetRegisterContext();
2129061da546Spatrick
2130061da546Spatrick std::vector<uint8_t> regs_buffer;
2131061da546Spatrick for (uint32_t reg_num = 0; reg_num < reg_ctx.GetUserRegisterCount();
2132061da546Spatrick ++reg_num) {
2133061da546Spatrick const RegisterInfo *reg_info = reg_ctx.GetRegisterInfoAtIndex(reg_num);
2134061da546Spatrick
2135061da546Spatrick if (reg_info == nullptr) {
2136061da546Spatrick LLDB_LOG(log, "failed to get register info for register index {0}",
2137061da546Spatrick reg_num);
2138061da546Spatrick return SendErrorResponse(0x15);
2139061da546Spatrick }
2140061da546Spatrick
2141061da546Spatrick if (reg_info->value_regs != nullptr)
2142061da546Spatrick continue; // skip registers that are contained in other registers
2143061da546Spatrick
2144061da546Spatrick RegisterValue reg_value;
2145061da546Spatrick Status error = reg_ctx.ReadRegister(reg_info, reg_value);
2146061da546Spatrick if (error.Fail()) {
2147061da546Spatrick LLDB_LOG(log, "failed to read register at index {0}", reg_num);
2148061da546Spatrick return SendErrorResponse(0x15);
2149061da546Spatrick }
2150061da546Spatrick
2151061da546Spatrick if (reg_info->byte_offset + reg_info->byte_size >= regs_buffer.size())
2152061da546Spatrick // Resize the buffer to guarantee it can store the register offsetted
2153061da546Spatrick // data.
2154061da546Spatrick regs_buffer.resize(reg_info->byte_offset + reg_info->byte_size);
2155061da546Spatrick
2156061da546Spatrick // Copy the register offsetted data to the buffer.
2157061da546Spatrick memcpy(regs_buffer.data() + reg_info->byte_offset, reg_value.GetBytes(),
2158061da546Spatrick reg_info->byte_size);
2159061da546Spatrick }
2160061da546Spatrick
2161061da546Spatrick // Write the response.
2162061da546Spatrick StreamGDBRemote response;
2163061da546Spatrick response.PutBytesAsRawHex8(regs_buffer.data(), regs_buffer.size());
2164061da546Spatrick
2165061da546Spatrick return SendPacketNoLock(response.GetString());
2166061da546Spatrick }
2167061da546Spatrick
2168061da546Spatrick GDBRemoteCommunication::PacketResult
Handle_p(StringExtractorGDBRemote & packet)2169061da546Spatrick GDBRemoteCommunicationServerLLGS::Handle_p(StringExtractorGDBRemote &packet) {
2170*f6aab3d8Srobert Log *log = GetLog(LLDBLog::Thread);
2171061da546Spatrick
2172061da546Spatrick // Parse out the register number from the request.
2173061da546Spatrick packet.SetFilePos(strlen("p"));
2174061da546Spatrick const uint32_t reg_index =
2175061da546Spatrick packet.GetHexMaxU32(false, std::numeric_limits<uint32_t>::max());
2176061da546Spatrick if (reg_index == std::numeric_limits<uint32_t>::max()) {
2177061da546Spatrick LLDB_LOGF(log,
2178061da546Spatrick "GDBRemoteCommunicationServerLLGS::%s failed, could not "
2179061da546Spatrick "parse register number from request \"%s\"",
2180061da546Spatrick __FUNCTION__, packet.GetStringRef().data());
2181061da546Spatrick return SendErrorResponse(0x15);
2182061da546Spatrick }
2183061da546Spatrick
2184061da546Spatrick // Get the thread to use.
2185061da546Spatrick NativeThreadProtocol *thread = GetThreadFromSuffix(packet);
2186061da546Spatrick if (!thread) {
2187061da546Spatrick LLDB_LOG(log, "failed, no thread available");
2188061da546Spatrick return SendErrorResponse(0x15);
2189061da546Spatrick }
2190061da546Spatrick
2191061da546Spatrick // Get the thread's register context.
2192061da546Spatrick NativeRegisterContext ®_context = thread->GetRegisterContext();
2193061da546Spatrick
2194061da546Spatrick // Return the end of registers response if we've iterated one past the end of
2195061da546Spatrick // the register set.
2196061da546Spatrick if (reg_index >= reg_context.GetUserRegisterCount()) {
2197061da546Spatrick LLDB_LOGF(log,
2198061da546Spatrick "GDBRemoteCommunicationServerLLGS::%s failed, requested "
2199061da546Spatrick "register %" PRIu32 " beyond register count %" PRIu32,
2200061da546Spatrick __FUNCTION__, reg_index, reg_context.GetUserRegisterCount());
2201061da546Spatrick return SendErrorResponse(0x15);
2202061da546Spatrick }
2203061da546Spatrick
2204061da546Spatrick const RegisterInfo *reg_info = reg_context.GetRegisterInfoAtIndex(reg_index);
2205061da546Spatrick if (!reg_info) {
2206061da546Spatrick LLDB_LOGF(log,
2207061da546Spatrick "GDBRemoteCommunicationServerLLGS::%s failed, requested "
2208061da546Spatrick "register %" PRIu32 " returned NULL",
2209061da546Spatrick __FUNCTION__, reg_index);
2210061da546Spatrick return SendErrorResponse(0x15);
2211061da546Spatrick }
2212061da546Spatrick
2213061da546Spatrick // Build the reginfos response.
2214061da546Spatrick StreamGDBRemote response;
2215061da546Spatrick
2216061da546Spatrick // Retrieve the value
2217061da546Spatrick RegisterValue reg_value;
2218061da546Spatrick Status error = reg_context.ReadRegister(reg_info, reg_value);
2219061da546Spatrick if (error.Fail()) {
2220061da546Spatrick LLDB_LOGF(log,
2221061da546Spatrick "GDBRemoteCommunicationServerLLGS::%s failed, read of "
2222061da546Spatrick "requested register %" PRIu32 " (%s) failed: %s",
2223061da546Spatrick __FUNCTION__, reg_index, reg_info->name, error.AsCString());
2224061da546Spatrick return SendErrorResponse(0x15);
2225061da546Spatrick }
2226061da546Spatrick
2227061da546Spatrick const uint8_t *const data =
2228061da546Spatrick static_cast<const uint8_t *>(reg_value.GetBytes());
2229061da546Spatrick if (!data) {
2230061da546Spatrick LLDB_LOGF(log,
2231061da546Spatrick "GDBRemoteCommunicationServerLLGS::%s failed to get data "
2232061da546Spatrick "bytes from requested register %" PRIu32,
2233061da546Spatrick __FUNCTION__, reg_index);
2234061da546Spatrick return SendErrorResponse(0x15);
2235061da546Spatrick }
2236061da546Spatrick
2237061da546Spatrick // FIXME flip as needed to get data in big/little endian format for this host.
2238061da546Spatrick for (uint32_t i = 0; i < reg_value.GetByteSize(); ++i)
2239061da546Spatrick response.PutHex8(data[i]);
2240061da546Spatrick
2241061da546Spatrick return SendPacketNoLock(response.GetString());
2242061da546Spatrick }
2243061da546Spatrick
2244061da546Spatrick GDBRemoteCommunication::PacketResult
Handle_P(StringExtractorGDBRemote & packet)2245061da546Spatrick GDBRemoteCommunicationServerLLGS::Handle_P(StringExtractorGDBRemote &packet) {
2246*f6aab3d8Srobert Log *log = GetLog(LLDBLog::Thread);
2247061da546Spatrick
2248061da546Spatrick // Ensure there is more content.
2249061da546Spatrick if (packet.GetBytesLeft() < 1)
2250061da546Spatrick return SendIllFormedResponse(packet, "Empty P packet");
2251061da546Spatrick
2252061da546Spatrick // Parse out the register number from the request.
2253061da546Spatrick packet.SetFilePos(strlen("P"));
2254061da546Spatrick const uint32_t reg_index =
2255061da546Spatrick packet.GetHexMaxU32(false, std::numeric_limits<uint32_t>::max());
2256061da546Spatrick if (reg_index == std::numeric_limits<uint32_t>::max()) {
2257061da546Spatrick LLDB_LOGF(log,
2258061da546Spatrick "GDBRemoteCommunicationServerLLGS::%s failed, could not "
2259061da546Spatrick "parse register number from request \"%s\"",
2260061da546Spatrick __FUNCTION__, packet.GetStringRef().data());
2261061da546Spatrick return SendErrorResponse(0x29);
2262061da546Spatrick }
2263061da546Spatrick
2264061da546Spatrick // Note debugserver would send an E30 here.
2265061da546Spatrick if ((packet.GetBytesLeft() < 1) || (packet.GetChar() != '='))
2266061da546Spatrick return SendIllFormedResponse(
2267061da546Spatrick packet, "P packet missing '=' char after register number");
2268061da546Spatrick
2269061da546Spatrick // Parse out the value.
2270dda28197Spatrick uint8_t reg_bytes[RegisterValue::kMaxRegisterByteSize];
2271061da546Spatrick size_t reg_size = packet.GetHexBytesAvail(reg_bytes);
2272061da546Spatrick
2273061da546Spatrick // Get the thread to use.
2274061da546Spatrick NativeThreadProtocol *thread = GetThreadFromSuffix(packet);
2275061da546Spatrick if (!thread) {
2276061da546Spatrick LLDB_LOGF(log,
2277061da546Spatrick "GDBRemoteCommunicationServerLLGS::%s failed, no thread "
2278061da546Spatrick "available (thread index 0)",
2279061da546Spatrick __FUNCTION__);
2280061da546Spatrick return SendErrorResponse(0x28);
2281061da546Spatrick }
2282061da546Spatrick
2283061da546Spatrick // Get the thread's register context.
2284061da546Spatrick NativeRegisterContext ®_context = thread->GetRegisterContext();
2285061da546Spatrick const RegisterInfo *reg_info = reg_context.GetRegisterInfoAtIndex(reg_index);
2286061da546Spatrick if (!reg_info) {
2287061da546Spatrick LLDB_LOGF(log,
2288061da546Spatrick "GDBRemoteCommunicationServerLLGS::%s failed, requested "
2289061da546Spatrick "register %" PRIu32 " returned NULL",
2290061da546Spatrick __FUNCTION__, reg_index);
2291061da546Spatrick return SendErrorResponse(0x48);
2292061da546Spatrick }
2293061da546Spatrick
2294061da546Spatrick // Return the end of registers response if we've iterated one past the end of
2295061da546Spatrick // the register set.
2296061da546Spatrick if (reg_index >= reg_context.GetUserRegisterCount()) {
2297061da546Spatrick LLDB_LOGF(log,
2298061da546Spatrick "GDBRemoteCommunicationServerLLGS::%s failed, requested "
2299061da546Spatrick "register %" PRIu32 " beyond register count %" PRIu32,
2300061da546Spatrick __FUNCTION__, reg_index, reg_context.GetUserRegisterCount());
2301061da546Spatrick return SendErrorResponse(0x47);
2302061da546Spatrick }
2303061da546Spatrick
2304*f6aab3d8Srobert if (reg_size != reg_info->byte_size)
2305061da546Spatrick return SendIllFormedResponse(packet, "P packet register size is incorrect");
2306061da546Spatrick
2307061da546Spatrick // Build the reginfos response.
2308061da546Spatrick StreamGDBRemote response;
2309061da546Spatrick
2310*f6aab3d8Srobert RegisterValue reg_value(ArrayRef(reg_bytes, reg_size),
2311be691f3bSpatrick m_current_process->GetArchitecture().GetByteOrder());
2312061da546Spatrick Status error = reg_context.WriteRegister(reg_info, reg_value);
2313061da546Spatrick if (error.Fail()) {
2314061da546Spatrick LLDB_LOGF(log,
2315061da546Spatrick "GDBRemoteCommunicationServerLLGS::%s failed, write of "
2316061da546Spatrick "requested register %" PRIu32 " (%s) failed: %s",
2317061da546Spatrick __FUNCTION__, reg_index, reg_info->name, error.AsCString());
2318061da546Spatrick return SendErrorResponse(0x32);
2319061da546Spatrick }
2320061da546Spatrick
2321061da546Spatrick return SendOKResponse();
2322061da546Spatrick }
2323061da546Spatrick
2324061da546Spatrick GDBRemoteCommunication::PacketResult
Handle_H(StringExtractorGDBRemote & packet)2325061da546Spatrick GDBRemoteCommunicationServerLLGS::Handle_H(StringExtractorGDBRemote &packet) {
2326*f6aab3d8Srobert Log *log = GetLog(LLDBLog::Thread);
2327061da546Spatrick
2328061da546Spatrick // Parse out which variant of $H is requested.
2329061da546Spatrick packet.SetFilePos(strlen("H"));
2330061da546Spatrick if (packet.GetBytesLeft() < 1) {
2331061da546Spatrick LLDB_LOGF(log,
2332061da546Spatrick "GDBRemoteCommunicationServerLLGS::%s failed, H command "
2333061da546Spatrick "missing {g,c} variant",
2334061da546Spatrick __FUNCTION__);
2335061da546Spatrick return SendIllFormedResponse(packet, "H command missing {g,c} variant");
2336061da546Spatrick }
2337061da546Spatrick
2338061da546Spatrick const char h_variant = packet.GetChar();
2339be691f3bSpatrick NativeProcessProtocol *default_process;
2340061da546Spatrick switch (h_variant) {
2341061da546Spatrick case 'g':
2342be691f3bSpatrick default_process = m_current_process;
2343061da546Spatrick break;
2344061da546Spatrick
2345061da546Spatrick case 'c':
2346be691f3bSpatrick default_process = m_continue_process;
2347061da546Spatrick break;
2348061da546Spatrick
2349061da546Spatrick default:
2350061da546Spatrick LLDB_LOGF(
2351061da546Spatrick log,
2352061da546Spatrick "GDBRemoteCommunicationServerLLGS::%s failed, invalid $H variant %c",
2353061da546Spatrick __FUNCTION__, h_variant);
2354061da546Spatrick return SendIllFormedResponse(packet,
2355061da546Spatrick "H variant unsupported, should be c or g");
2356061da546Spatrick }
2357061da546Spatrick
2358061da546Spatrick // Parse out the thread number.
2359be691f3bSpatrick auto pid_tid = packet.GetPidTid(default_process ? default_process->GetID()
2360be691f3bSpatrick : LLDB_INVALID_PROCESS_ID);
2361be691f3bSpatrick if (!pid_tid)
2362be691f3bSpatrick return SendErrorResponse(llvm::make_error<StringError>(
2363be691f3bSpatrick inconvertibleErrorCode(), "Malformed thread-id"));
2364be691f3bSpatrick
2365be691f3bSpatrick lldb::pid_t pid = pid_tid->first;
2366be691f3bSpatrick lldb::tid_t tid = pid_tid->second;
2367be691f3bSpatrick
2368be691f3bSpatrick if (pid == StringExtractorGDBRemote::AllProcesses)
2369be691f3bSpatrick return SendUnimplementedResponse("Selecting all processes not supported");
2370be691f3bSpatrick if (pid == LLDB_INVALID_PROCESS_ID)
2371be691f3bSpatrick return SendErrorResponse(llvm::make_error<StringError>(
2372be691f3bSpatrick inconvertibleErrorCode(), "No current process and no PID provided"));
2373be691f3bSpatrick
2374be691f3bSpatrick // Check the process ID and find respective process instance.
2375be691f3bSpatrick auto new_process_it = m_debugged_processes.find(pid);
2376be691f3bSpatrick if (new_process_it == m_debugged_processes.end())
2377be691f3bSpatrick return SendErrorResponse(llvm::make_error<StringError>(
2378be691f3bSpatrick inconvertibleErrorCode(),
2379be691f3bSpatrick llvm::formatv("No process with PID {0} debugged", pid)));
2380061da546Spatrick
2381061da546Spatrick // Ensure we have the given thread when not specifying -1 (all threads) or 0
2382061da546Spatrick // (any thread).
2383061da546Spatrick if (tid != LLDB_INVALID_THREAD_ID && tid != 0) {
2384*f6aab3d8Srobert NativeThreadProtocol *thread =
2385*f6aab3d8Srobert new_process_it->second.process_up->GetThreadByID(tid);
2386061da546Spatrick if (!thread) {
2387061da546Spatrick LLDB_LOGF(log,
2388061da546Spatrick "GDBRemoteCommunicationServerLLGS::%s failed, tid %" PRIu64
2389061da546Spatrick " not found",
2390061da546Spatrick __FUNCTION__, tid);
2391061da546Spatrick return SendErrorResponse(0x15);
2392061da546Spatrick }
2393061da546Spatrick }
2394061da546Spatrick
2395be691f3bSpatrick // Now switch the given process and thread type.
2396061da546Spatrick switch (h_variant) {
2397061da546Spatrick case 'g':
2398*f6aab3d8Srobert m_current_process = new_process_it->second.process_up.get();
2399061da546Spatrick SetCurrentThreadID(tid);
2400061da546Spatrick break;
2401061da546Spatrick
2402061da546Spatrick case 'c':
2403*f6aab3d8Srobert m_continue_process = new_process_it->second.process_up.get();
2404061da546Spatrick SetContinueThreadID(tid);
2405061da546Spatrick break;
2406061da546Spatrick
2407061da546Spatrick default:
2408061da546Spatrick assert(false && "unsupported $H variant - shouldn't get here");
2409061da546Spatrick return SendIllFormedResponse(packet,
2410061da546Spatrick "H variant unsupported, should be c or g");
2411061da546Spatrick }
2412061da546Spatrick
2413061da546Spatrick return SendOKResponse();
2414061da546Spatrick }
2415061da546Spatrick
2416061da546Spatrick GDBRemoteCommunication::PacketResult
Handle_I(StringExtractorGDBRemote & packet)2417061da546Spatrick GDBRemoteCommunicationServerLLGS::Handle_I(StringExtractorGDBRemote &packet) {
2418*f6aab3d8Srobert Log *log = GetLog(LLDBLog::Thread);
2419061da546Spatrick
2420061da546Spatrick // Fail if we don't have a current process.
2421be691f3bSpatrick if (!m_current_process ||
2422be691f3bSpatrick (m_current_process->GetID() == LLDB_INVALID_PROCESS_ID)) {
2423061da546Spatrick LLDB_LOGF(
2424061da546Spatrick log,
2425061da546Spatrick "GDBRemoteCommunicationServerLLGS::%s failed, no process available",
2426061da546Spatrick __FUNCTION__);
2427061da546Spatrick return SendErrorResponse(0x15);
2428061da546Spatrick }
2429061da546Spatrick
2430061da546Spatrick packet.SetFilePos(::strlen("I"));
2431061da546Spatrick uint8_t tmp[4096];
2432061da546Spatrick for (;;) {
2433061da546Spatrick size_t read = packet.GetHexBytesAvail(tmp);
2434061da546Spatrick if (read == 0) {
2435061da546Spatrick break;
2436061da546Spatrick }
2437061da546Spatrick // write directly to stdin *this might block if stdin buffer is full*
2438061da546Spatrick // TODO: enqueue this block in circular buffer and send window size to
2439061da546Spatrick // remote host
2440061da546Spatrick ConnectionStatus status;
2441061da546Spatrick Status error;
2442*f6aab3d8Srobert m_stdio_communication.WriteAll(tmp, read, status, &error);
2443061da546Spatrick if (error.Fail()) {
2444061da546Spatrick return SendErrorResponse(0x15);
2445061da546Spatrick }
2446061da546Spatrick }
2447061da546Spatrick
2448061da546Spatrick return SendOKResponse();
2449061da546Spatrick }
2450061da546Spatrick
2451061da546Spatrick GDBRemoteCommunication::PacketResult
Handle_interrupt(StringExtractorGDBRemote & packet)2452061da546Spatrick GDBRemoteCommunicationServerLLGS::Handle_interrupt(
2453061da546Spatrick StringExtractorGDBRemote &packet) {
2454*f6aab3d8Srobert Log *log = GetLog(LLDBLog::Process | LLDBLog::Thread);
2455061da546Spatrick
2456061da546Spatrick // Fail if we don't have a current process.
2457be691f3bSpatrick if (!m_current_process ||
2458be691f3bSpatrick (m_current_process->GetID() == LLDB_INVALID_PROCESS_ID)) {
2459061da546Spatrick LLDB_LOG(log, "failed, no process available");
2460061da546Spatrick return SendErrorResponse(0x15);
2461061da546Spatrick }
2462061da546Spatrick
2463061da546Spatrick // Interrupt the process.
2464be691f3bSpatrick Status error = m_current_process->Interrupt();
2465061da546Spatrick if (error.Fail()) {
2466be691f3bSpatrick LLDB_LOG(log, "failed for process {0}: {1}", m_current_process->GetID(),
2467061da546Spatrick error);
2468061da546Spatrick return SendErrorResponse(GDBRemoteServerError::eErrorResume);
2469061da546Spatrick }
2470061da546Spatrick
2471be691f3bSpatrick LLDB_LOG(log, "stopped process {0}", m_current_process->GetID());
2472061da546Spatrick
2473061da546Spatrick // No response required from stop all.
2474061da546Spatrick return PacketResult::Success;
2475061da546Spatrick }
2476061da546Spatrick
2477061da546Spatrick GDBRemoteCommunication::PacketResult
Handle_memory_read(StringExtractorGDBRemote & packet)2478061da546Spatrick GDBRemoteCommunicationServerLLGS::Handle_memory_read(
2479061da546Spatrick StringExtractorGDBRemote &packet) {
2480*f6aab3d8Srobert Log *log = GetLog(LLDBLog::Process);
2481061da546Spatrick
2482be691f3bSpatrick if (!m_current_process ||
2483be691f3bSpatrick (m_current_process->GetID() == LLDB_INVALID_PROCESS_ID)) {
2484061da546Spatrick LLDB_LOGF(
2485061da546Spatrick log,
2486061da546Spatrick "GDBRemoteCommunicationServerLLGS::%s failed, no process available",
2487061da546Spatrick __FUNCTION__);
2488061da546Spatrick return SendErrorResponse(0x15);
2489061da546Spatrick }
2490061da546Spatrick
2491061da546Spatrick // Parse out the memory address.
2492061da546Spatrick packet.SetFilePos(strlen("m"));
2493061da546Spatrick if (packet.GetBytesLeft() < 1)
2494061da546Spatrick return SendIllFormedResponse(packet, "Too short m packet");
2495061da546Spatrick
2496061da546Spatrick // Read the address. Punting on validation.
2497061da546Spatrick // FIXME replace with Hex U64 read with no default value that fails on failed
2498061da546Spatrick // read.
2499061da546Spatrick const lldb::addr_t read_addr = packet.GetHexMaxU64(false, 0);
2500061da546Spatrick
2501061da546Spatrick // Validate comma.
2502061da546Spatrick if ((packet.GetBytesLeft() < 1) || (packet.GetChar() != ','))
2503061da546Spatrick return SendIllFormedResponse(packet, "Comma sep missing in m packet");
2504061da546Spatrick
2505061da546Spatrick // Get # bytes to read.
2506061da546Spatrick if (packet.GetBytesLeft() < 1)
2507061da546Spatrick return SendIllFormedResponse(packet, "Length missing in m packet");
2508061da546Spatrick
2509061da546Spatrick const uint64_t byte_count = packet.GetHexMaxU64(false, 0);
2510061da546Spatrick if (byte_count == 0) {
2511061da546Spatrick LLDB_LOGF(log,
2512061da546Spatrick "GDBRemoteCommunicationServerLLGS::%s nothing to read: "
2513061da546Spatrick "zero-length packet",
2514061da546Spatrick __FUNCTION__);
2515061da546Spatrick return SendOKResponse();
2516061da546Spatrick }
2517061da546Spatrick
2518061da546Spatrick // Allocate the response buffer.
2519061da546Spatrick std::string buf(byte_count, '\0');
2520061da546Spatrick if (buf.empty())
2521061da546Spatrick return SendErrorResponse(0x78);
2522061da546Spatrick
2523061da546Spatrick // Retrieve the process memory.
2524061da546Spatrick size_t bytes_read = 0;
2525be691f3bSpatrick Status error = m_current_process->ReadMemoryWithoutTrap(
2526061da546Spatrick read_addr, &buf[0], byte_count, bytes_read);
2527061da546Spatrick if (error.Fail()) {
2528061da546Spatrick LLDB_LOGF(log,
2529061da546Spatrick "GDBRemoteCommunicationServerLLGS::%s pid %" PRIu64
2530061da546Spatrick " mem 0x%" PRIx64 ": failed to read. Error: %s",
2531be691f3bSpatrick __FUNCTION__, m_current_process->GetID(), read_addr,
2532061da546Spatrick error.AsCString());
2533061da546Spatrick return SendErrorResponse(0x08);
2534061da546Spatrick }
2535061da546Spatrick
2536061da546Spatrick if (bytes_read == 0) {
2537061da546Spatrick LLDB_LOGF(log,
2538061da546Spatrick "GDBRemoteCommunicationServerLLGS::%s pid %" PRIu64
2539061da546Spatrick " mem 0x%" PRIx64 ": read 0 of %" PRIu64 " requested bytes",
2540be691f3bSpatrick __FUNCTION__, m_current_process->GetID(), read_addr, byte_count);
2541061da546Spatrick return SendErrorResponse(0x08);
2542061da546Spatrick }
2543061da546Spatrick
2544061da546Spatrick StreamGDBRemote response;
2545061da546Spatrick packet.SetFilePos(0);
2546061da546Spatrick char kind = packet.GetChar('?');
2547061da546Spatrick if (kind == 'x')
2548061da546Spatrick response.PutEscapedBytes(buf.data(), byte_count);
2549061da546Spatrick else {
2550061da546Spatrick assert(kind == 'm');
2551061da546Spatrick for (size_t i = 0; i < bytes_read; ++i)
2552061da546Spatrick response.PutHex8(buf[i]);
2553061da546Spatrick }
2554061da546Spatrick
2555061da546Spatrick return SendPacketNoLock(response.GetString());
2556061da546Spatrick }
2557061da546Spatrick
2558061da546Spatrick GDBRemoteCommunication::PacketResult
Handle__M(StringExtractorGDBRemote & packet)2559be691f3bSpatrick GDBRemoteCommunicationServerLLGS::Handle__M(StringExtractorGDBRemote &packet) {
2560*f6aab3d8Srobert Log *log = GetLog(LLDBLog::Process);
2561be691f3bSpatrick
2562be691f3bSpatrick if (!m_current_process ||
2563be691f3bSpatrick (m_current_process->GetID() == LLDB_INVALID_PROCESS_ID)) {
2564be691f3bSpatrick LLDB_LOGF(
2565be691f3bSpatrick log,
2566be691f3bSpatrick "GDBRemoteCommunicationServerLLGS::%s failed, no process available",
2567be691f3bSpatrick __FUNCTION__);
2568be691f3bSpatrick return SendErrorResponse(0x15);
2569be691f3bSpatrick }
2570be691f3bSpatrick
2571be691f3bSpatrick // Parse out the memory address.
2572be691f3bSpatrick packet.SetFilePos(strlen("_M"));
2573be691f3bSpatrick if (packet.GetBytesLeft() < 1)
2574be691f3bSpatrick return SendIllFormedResponse(packet, "Too short _M packet");
2575be691f3bSpatrick
2576be691f3bSpatrick const lldb::addr_t size = packet.GetHexMaxU64(false, LLDB_INVALID_ADDRESS);
2577be691f3bSpatrick if (size == LLDB_INVALID_ADDRESS)
2578be691f3bSpatrick return SendIllFormedResponse(packet, "Address not valid");
2579be691f3bSpatrick if (packet.GetChar() != ',')
2580be691f3bSpatrick return SendIllFormedResponse(packet, "Bad packet");
2581be691f3bSpatrick Permissions perms = {};
2582be691f3bSpatrick while (packet.GetBytesLeft() > 0) {
2583be691f3bSpatrick switch (packet.GetChar()) {
2584be691f3bSpatrick case 'r':
2585be691f3bSpatrick perms |= ePermissionsReadable;
2586be691f3bSpatrick break;
2587be691f3bSpatrick case 'w':
2588be691f3bSpatrick perms |= ePermissionsWritable;
2589be691f3bSpatrick break;
2590be691f3bSpatrick case 'x':
2591be691f3bSpatrick perms |= ePermissionsExecutable;
2592be691f3bSpatrick break;
2593be691f3bSpatrick default:
2594be691f3bSpatrick return SendIllFormedResponse(packet, "Bad permissions");
2595be691f3bSpatrick }
2596be691f3bSpatrick }
2597be691f3bSpatrick
2598be691f3bSpatrick llvm::Expected<addr_t> addr = m_current_process->AllocateMemory(size, perms);
2599be691f3bSpatrick if (!addr)
2600be691f3bSpatrick return SendErrorResponse(addr.takeError());
2601be691f3bSpatrick
2602be691f3bSpatrick StreamGDBRemote response;
2603be691f3bSpatrick response.PutHex64(*addr);
2604be691f3bSpatrick return SendPacketNoLock(response.GetString());
2605be691f3bSpatrick }
2606be691f3bSpatrick
2607be691f3bSpatrick GDBRemoteCommunication::PacketResult
Handle__m(StringExtractorGDBRemote & packet)2608be691f3bSpatrick GDBRemoteCommunicationServerLLGS::Handle__m(StringExtractorGDBRemote &packet) {
2609*f6aab3d8Srobert Log *log = GetLog(LLDBLog::Process);
2610be691f3bSpatrick
2611be691f3bSpatrick if (!m_current_process ||
2612be691f3bSpatrick (m_current_process->GetID() == LLDB_INVALID_PROCESS_ID)) {
2613be691f3bSpatrick LLDB_LOGF(
2614be691f3bSpatrick log,
2615be691f3bSpatrick "GDBRemoteCommunicationServerLLGS::%s failed, no process available",
2616be691f3bSpatrick __FUNCTION__);
2617be691f3bSpatrick return SendErrorResponse(0x15);
2618be691f3bSpatrick }
2619be691f3bSpatrick
2620be691f3bSpatrick // Parse out the memory address.
2621be691f3bSpatrick packet.SetFilePos(strlen("_m"));
2622be691f3bSpatrick if (packet.GetBytesLeft() < 1)
2623be691f3bSpatrick return SendIllFormedResponse(packet, "Too short m packet");
2624be691f3bSpatrick
2625be691f3bSpatrick const lldb::addr_t addr = packet.GetHexMaxU64(false, LLDB_INVALID_ADDRESS);
2626be691f3bSpatrick if (addr == LLDB_INVALID_ADDRESS)
2627be691f3bSpatrick return SendIllFormedResponse(packet, "Address not valid");
2628be691f3bSpatrick
2629be691f3bSpatrick if (llvm::Error Err = m_current_process->DeallocateMemory(addr))
2630be691f3bSpatrick return SendErrorResponse(std::move(Err));
2631be691f3bSpatrick
2632be691f3bSpatrick return SendOKResponse();
2633be691f3bSpatrick }
2634be691f3bSpatrick
2635be691f3bSpatrick GDBRemoteCommunication::PacketResult
Handle_M(StringExtractorGDBRemote & packet)2636061da546Spatrick GDBRemoteCommunicationServerLLGS::Handle_M(StringExtractorGDBRemote &packet) {
2637*f6aab3d8Srobert Log *log = GetLog(LLDBLog::Process);
2638061da546Spatrick
2639be691f3bSpatrick if (!m_current_process ||
2640be691f3bSpatrick (m_current_process->GetID() == LLDB_INVALID_PROCESS_ID)) {
2641061da546Spatrick LLDB_LOGF(
2642061da546Spatrick log,
2643061da546Spatrick "GDBRemoteCommunicationServerLLGS::%s failed, no process available",
2644061da546Spatrick __FUNCTION__);
2645061da546Spatrick return SendErrorResponse(0x15);
2646061da546Spatrick }
2647061da546Spatrick
2648061da546Spatrick // Parse out the memory address.
2649061da546Spatrick packet.SetFilePos(strlen("M"));
2650061da546Spatrick if (packet.GetBytesLeft() < 1)
2651061da546Spatrick return SendIllFormedResponse(packet, "Too short M packet");
2652061da546Spatrick
2653061da546Spatrick // Read the address. Punting on validation.
2654061da546Spatrick // FIXME replace with Hex U64 read with no default value that fails on failed
2655061da546Spatrick // read.
2656061da546Spatrick const lldb::addr_t write_addr = packet.GetHexMaxU64(false, 0);
2657061da546Spatrick
2658061da546Spatrick // Validate comma.
2659061da546Spatrick if ((packet.GetBytesLeft() < 1) || (packet.GetChar() != ','))
2660061da546Spatrick return SendIllFormedResponse(packet, "Comma sep missing in M packet");
2661061da546Spatrick
2662061da546Spatrick // Get # bytes to read.
2663061da546Spatrick if (packet.GetBytesLeft() < 1)
2664061da546Spatrick return SendIllFormedResponse(packet, "Length missing in M packet");
2665061da546Spatrick
2666061da546Spatrick const uint64_t byte_count = packet.GetHexMaxU64(false, 0);
2667061da546Spatrick if (byte_count == 0) {
2668061da546Spatrick LLDB_LOG(log, "nothing to write: zero-length packet");
2669061da546Spatrick return PacketResult::Success;
2670061da546Spatrick }
2671061da546Spatrick
2672061da546Spatrick // Validate colon.
2673061da546Spatrick if ((packet.GetBytesLeft() < 1) || (packet.GetChar() != ':'))
2674061da546Spatrick return SendIllFormedResponse(
2675061da546Spatrick packet, "Comma sep missing in M packet after byte length");
2676061da546Spatrick
2677061da546Spatrick // Allocate the conversion buffer.
2678061da546Spatrick std::vector<uint8_t> buf(byte_count, 0);
2679061da546Spatrick if (buf.empty())
2680061da546Spatrick return SendErrorResponse(0x78);
2681061da546Spatrick
2682061da546Spatrick // Convert the hex memory write contents to bytes.
2683061da546Spatrick StreamGDBRemote response;
2684061da546Spatrick const uint64_t convert_count = packet.GetHexBytes(buf, 0);
2685061da546Spatrick if (convert_count != byte_count) {
2686061da546Spatrick LLDB_LOG(log,
2687061da546Spatrick "pid {0} mem {1:x}: asked to write {2} bytes, but only found {3} "
2688061da546Spatrick "to convert.",
2689be691f3bSpatrick m_current_process->GetID(), write_addr, byte_count, convert_count);
2690061da546Spatrick return SendIllFormedResponse(packet, "M content byte length specified did "
2691061da546Spatrick "not match hex-encoded content "
2692061da546Spatrick "length");
2693061da546Spatrick }
2694061da546Spatrick
2695061da546Spatrick // Write the process memory.
2696061da546Spatrick size_t bytes_written = 0;
2697be691f3bSpatrick Status error = m_current_process->WriteMemory(write_addr, &buf[0], byte_count,
2698be691f3bSpatrick bytes_written);
2699061da546Spatrick if (error.Fail()) {
2700061da546Spatrick LLDB_LOG(log, "pid {0} mem {1:x}: failed to write. Error: {2}",
2701be691f3bSpatrick m_current_process->GetID(), write_addr, error);
2702061da546Spatrick return SendErrorResponse(0x09);
2703061da546Spatrick }
2704061da546Spatrick
2705061da546Spatrick if (bytes_written == 0) {
2706061da546Spatrick LLDB_LOG(log, "pid {0} mem {1:x}: wrote 0 of {2} requested bytes",
2707be691f3bSpatrick m_current_process->GetID(), write_addr, byte_count);
2708061da546Spatrick return SendErrorResponse(0x09);
2709061da546Spatrick }
2710061da546Spatrick
2711061da546Spatrick return SendOKResponse();
2712061da546Spatrick }
2713061da546Spatrick
2714061da546Spatrick GDBRemoteCommunication::PacketResult
Handle_qMemoryRegionInfoSupported(StringExtractorGDBRemote & packet)2715061da546Spatrick GDBRemoteCommunicationServerLLGS::Handle_qMemoryRegionInfoSupported(
2716061da546Spatrick StringExtractorGDBRemote &packet) {
2717*f6aab3d8Srobert Log *log = GetLog(LLDBLog::Process);
2718061da546Spatrick
2719061da546Spatrick // Currently only the NativeProcessProtocol knows if it can handle a
2720061da546Spatrick // qMemoryRegionInfoSupported request, but we're not guaranteed to be
2721061da546Spatrick // attached to a process. For now we'll assume the client only asks this
2722061da546Spatrick // when a process is being debugged.
2723061da546Spatrick
2724061da546Spatrick // Ensure we have a process running; otherwise, we can't figure this out
2725061da546Spatrick // since we won't have a NativeProcessProtocol.
2726be691f3bSpatrick if (!m_current_process ||
2727be691f3bSpatrick (m_current_process->GetID() == LLDB_INVALID_PROCESS_ID)) {
2728061da546Spatrick LLDB_LOGF(
2729061da546Spatrick log,
2730061da546Spatrick "GDBRemoteCommunicationServerLLGS::%s failed, no process available",
2731061da546Spatrick __FUNCTION__);
2732061da546Spatrick return SendErrorResponse(0x15);
2733061da546Spatrick }
2734061da546Spatrick
2735061da546Spatrick // Test if we can get any region back when asking for the region around NULL.
2736061da546Spatrick MemoryRegionInfo region_info;
2737be691f3bSpatrick const Status error = m_current_process->GetMemoryRegionInfo(0, region_info);
2738061da546Spatrick if (error.Fail()) {
2739061da546Spatrick // We don't support memory region info collection for this
2740061da546Spatrick // NativeProcessProtocol.
2741061da546Spatrick return SendUnimplementedResponse("");
2742061da546Spatrick }
2743061da546Spatrick
2744061da546Spatrick return SendOKResponse();
2745061da546Spatrick }
2746061da546Spatrick
2747061da546Spatrick GDBRemoteCommunication::PacketResult
Handle_qMemoryRegionInfo(StringExtractorGDBRemote & packet)2748061da546Spatrick GDBRemoteCommunicationServerLLGS::Handle_qMemoryRegionInfo(
2749061da546Spatrick StringExtractorGDBRemote &packet) {
2750*f6aab3d8Srobert Log *log = GetLog(LLDBLog::Process);
2751061da546Spatrick
2752061da546Spatrick // Ensure we have a process.
2753be691f3bSpatrick if (!m_current_process ||
2754be691f3bSpatrick (m_current_process->GetID() == LLDB_INVALID_PROCESS_ID)) {
2755061da546Spatrick LLDB_LOGF(
2756061da546Spatrick log,
2757061da546Spatrick "GDBRemoteCommunicationServerLLGS::%s failed, no process available",
2758061da546Spatrick __FUNCTION__);
2759061da546Spatrick return SendErrorResponse(0x15);
2760061da546Spatrick }
2761061da546Spatrick
2762061da546Spatrick // Parse out the memory address.
2763061da546Spatrick packet.SetFilePos(strlen("qMemoryRegionInfo:"));
2764061da546Spatrick if (packet.GetBytesLeft() < 1)
2765061da546Spatrick return SendIllFormedResponse(packet, "Too short qMemoryRegionInfo: packet");
2766061da546Spatrick
2767061da546Spatrick // Read the address. Punting on validation.
2768061da546Spatrick const lldb::addr_t read_addr = packet.GetHexMaxU64(false, 0);
2769061da546Spatrick
2770061da546Spatrick StreamGDBRemote response;
2771061da546Spatrick
2772061da546Spatrick // Get the memory region info for the target address.
2773061da546Spatrick MemoryRegionInfo region_info;
2774061da546Spatrick const Status error =
2775be691f3bSpatrick m_current_process->GetMemoryRegionInfo(read_addr, region_info);
2776061da546Spatrick if (error.Fail()) {
2777061da546Spatrick // Return the error message.
2778061da546Spatrick
2779061da546Spatrick response.PutCString("error:");
2780061da546Spatrick response.PutStringAsRawHex8(error.AsCString());
2781061da546Spatrick response.PutChar(';');
2782061da546Spatrick } else {
2783061da546Spatrick // Range start and size.
2784061da546Spatrick response.Printf("start:%" PRIx64 ";size:%" PRIx64 ";",
2785061da546Spatrick region_info.GetRange().GetRangeBase(),
2786061da546Spatrick region_info.GetRange().GetByteSize());
2787061da546Spatrick
2788061da546Spatrick // Permissions.
2789061da546Spatrick if (region_info.GetReadable() || region_info.GetWritable() ||
2790061da546Spatrick region_info.GetExecutable()) {
2791061da546Spatrick // Write permissions info.
2792061da546Spatrick response.PutCString("permissions:");
2793061da546Spatrick
2794061da546Spatrick if (region_info.GetReadable())
2795061da546Spatrick response.PutChar('r');
2796061da546Spatrick if (region_info.GetWritable())
2797061da546Spatrick response.PutChar('w');
2798061da546Spatrick if (region_info.GetExecutable())
2799061da546Spatrick response.PutChar('x');
2800061da546Spatrick
2801061da546Spatrick response.PutChar(';');
2802061da546Spatrick }
2803061da546Spatrick
2804be691f3bSpatrick // Flags
2805be691f3bSpatrick MemoryRegionInfo::OptionalBool memory_tagged =
2806be691f3bSpatrick region_info.GetMemoryTagged();
2807be691f3bSpatrick if (memory_tagged != MemoryRegionInfo::eDontKnow) {
2808be691f3bSpatrick response.PutCString("flags:");
2809be691f3bSpatrick if (memory_tagged == MemoryRegionInfo::eYes) {
2810be691f3bSpatrick response.PutCString("mt");
2811be691f3bSpatrick }
2812be691f3bSpatrick response.PutChar(';');
2813be691f3bSpatrick }
2814be691f3bSpatrick
2815061da546Spatrick // Name
2816061da546Spatrick ConstString name = region_info.GetName();
2817061da546Spatrick if (name) {
2818061da546Spatrick response.PutCString("name:");
2819dda28197Spatrick response.PutStringAsRawHex8(name.GetStringRef());
2820061da546Spatrick response.PutChar(';');
2821061da546Spatrick }
2822061da546Spatrick }
2823061da546Spatrick
2824061da546Spatrick return SendPacketNoLock(response.GetString());
2825061da546Spatrick }
2826061da546Spatrick
2827061da546Spatrick GDBRemoteCommunication::PacketResult
Handle_Z(StringExtractorGDBRemote & packet)2828061da546Spatrick GDBRemoteCommunicationServerLLGS::Handle_Z(StringExtractorGDBRemote &packet) {
2829061da546Spatrick // Ensure we have a process.
2830be691f3bSpatrick if (!m_current_process ||
2831be691f3bSpatrick (m_current_process->GetID() == LLDB_INVALID_PROCESS_ID)) {
2832*f6aab3d8Srobert Log *log = GetLog(LLDBLog::Process);
2833061da546Spatrick LLDB_LOG(log, "failed, no process available");
2834061da546Spatrick return SendErrorResponse(0x15);
2835061da546Spatrick }
2836061da546Spatrick
2837061da546Spatrick // Parse out software or hardware breakpoint or watchpoint requested.
2838061da546Spatrick packet.SetFilePos(strlen("Z"));
2839061da546Spatrick if (packet.GetBytesLeft() < 1)
2840061da546Spatrick return SendIllFormedResponse(
2841061da546Spatrick packet, "Too short Z packet, missing software/hardware specifier");
2842061da546Spatrick
2843061da546Spatrick bool want_breakpoint = true;
2844061da546Spatrick bool want_hardware = false;
2845061da546Spatrick uint32_t watch_flags = 0;
2846061da546Spatrick
2847061da546Spatrick const GDBStoppointType stoppoint_type =
2848061da546Spatrick GDBStoppointType(packet.GetS32(eStoppointInvalid));
2849061da546Spatrick switch (stoppoint_type) {
2850061da546Spatrick case eBreakpointSoftware:
2851061da546Spatrick want_hardware = false;
2852061da546Spatrick want_breakpoint = true;
2853061da546Spatrick break;
2854061da546Spatrick case eBreakpointHardware:
2855061da546Spatrick want_hardware = true;
2856061da546Spatrick want_breakpoint = true;
2857061da546Spatrick break;
2858061da546Spatrick case eWatchpointWrite:
2859061da546Spatrick watch_flags = 1;
2860061da546Spatrick want_hardware = true;
2861061da546Spatrick want_breakpoint = false;
2862061da546Spatrick break;
2863061da546Spatrick case eWatchpointRead:
2864061da546Spatrick watch_flags = 2;
2865061da546Spatrick want_hardware = true;
2866061da546Spatrick want_breakpoint = false;
2867061da546Spatrick break;
2868061da546Spatrick case eWatchpointReadWrite:
2869061da546Spatrick watch_flags = 3;
2870061da546Spatrick want_hardware = true;
2871061da546Spatrick want_breakpoint = false;
2872061da546Spatrick break;
2873061da546Spatrick case eStoppointInvalid:
2874061da546Spatrick return SendIllFormedResponse(
2875061da546Spatrick packet, "Z packet had invalid software/hardware specifier");
2876061da546Spatrick }
2877061da546Spatrick
2878061da546Spatrick if ((packet.GetBytesLeft() < 1) || packet.GetChar() != ',')
2879061da546Spatrick return SendIllFormedResponse(
2880061da546Spatrick packet, "Malformed Z packet, expecting comma after stoppoint type");
2881061da546Spatrick
2882061da546Spatrick // Parse out the stoppoint address.
2883061da546Spatrick if (packet.GetBytesLeft() < 1)
2884061da546Spatrick return SendIllFormedResponse(packet, "Too short Z packet, missing address");
2885061da546Spatrick const lldb::addr_t addr = packet.GetHexMaxU64(false, 0);
2886061da546Spatrick
2887061da546Spatrick if ((packet.GetBytesLeft() < 1) || packet.GetChar() != ',')
2888061da546Spatrick return SendIllFormedResponse(
2889061da546Spatrick packet, "Malformed Z packet, expecting comma after address");
2890061da546Spatrick
2891061da546Spatrick // Parse out the stoppoint size (i.e. size hint for opcode size).
2892061da546Spatrick const uint32_t size =
2893061da546Spatrick packet.GetHexMaxU32(false, std::numeric_limits<uint32_t>::max());
2894061da546Spatrick if (size == std::numeric_limits<uint32_t>::max())
2895061da546Spatrick return SendIllFormedResponse(
2896061da546Spatrick packet, "Malformed Z packet, failed to parse size argument");
2897061da546Spatrick
2898061da546Spatrick if (want_breakpoint) {
2899061da546Spatrick // Try to set the breakpoint.
2900061da546Spatrick const Status error =
2901be691f3bSpatrick m_current_process->SetBreakpoint(addr, size, want_hardware);
2902061da546Spatrick if (error.Success())
2903061da546Spatrick return SendOKResponse();
2904*f6aab3d8Srobert Log *log = GetLog(LLDBLog::Breakpoints);
2905061da546Spatrick LLDB_LOG(log, "pid {0} failed to set breakpoint: {1}",
2906be691f3bSpatrick m_current_process->GetID(), error);
2907061da546Spatrick return SendErrorResponse(0x09);
2908061da546Spatrick } else {
2909061da546Spatrick // Try to set the watchpoint.
2910be691f3bSpatrick const Status error = m_current_process->SetWatchpoint(
2911061da546Spatrick addr, size, watch_flags, want_hardware);
2912061da546Spatrick if (error.Success())
2913061da546Spatrick return SendOKResponse();
2914*f6aab3d8Srobert Log *log = GetLog(LLDBLog::Watchpoints);
2915061da546Spatrick LLDB_LOG(log, "pid {0} failed to set watchpoint: {1}",
2916be691f3bSpatrick m_current_process->GetID(), error);
2917061da546Spatrick return SendErrorResponse(0x09);
2918061da546Spatrick }
2919061da546Spatrick }
2920061da546Spatrick
2921061da546Spatrick GDBRemoteCommunication::PacketResult
Handle_z(StringExtractorGDBRemote & packet)2922061da546Spatrick GDBRemoteCommunicationServerLLGS::Handle_z(StringExtractorGDBRemote &packet) {
2923061da546Spatrick // Ensure we have a process.
2924be691f3bSpatrick if (!m_current_process ||
2925be691f3bSpatrick (m_current_process->GetID() == LLDB_INVALID_PROCESS_ID)) {
2926*f6aab3d8Srobert Log *log = GetLog(LLDBLog::Process);
2927061da546Spatrick LLDB_LOG(log, "failed, no process available");
2928061da546Spatrick return SendErrorResponse(0x15);
2929061da546Spatrick }
2930061da546Spatrick
2931061da546Spatrick // Parse out software or hardware breakpoint or watchpoint requested.
2932061da546Spatrick packet.SetFilePos(strlen("z"));
2933061da546Spatrick if (packet.GetBytesLeft() < 1)
2934061da546Spatrick return SendIllFormedResponse(
2935061da546Spatrick packet, "Too short z packet, missing software/hardware specifier");
2936061da546Spatrick
2937061da546Spatrick bool want_breakpoint = true;
2938061da546Spatrick bool want_hardware = false;
2939061da546Spatrick
2940061da546Spatrick const GDBStoppointType stoppoint_type =
2941061da546Spatrick GDBStoppointType(packet.GetS32(eStoppointInvalid));
2942061da546Spatrick switch (stoppoint_type) {
2943061da546Spatrick case eBreakpointHardware:
2944061da546Spatrick want_breakpoint = true;
2945061da546Spatrick want_hardware = true;
2946061da546Spatrick break;
2947061da546Spatrick case eBreakpointSoftware:
2948061da546Spatrick want_breakpoint = true;
2949061da546Spatrick break;
2950061da546Spatrick case eWatchpointWrite:
2951061da546Spatrick want_breakpoint = false;
2952061da546Spatrick break;
2953061da546Spatrick case eWatchpointRead:
2954061da546Spatrick want_breakpoint = false;
2955061da546Spatrick break;
2956061da546Spatrick case eWatchpointReadWrite:
2957061da546Spatrick want_breakpoint = false;
2958061da546Spatrick break;
2959061da546Spatrick default:
2960061da546Spatrick return SendIllFormedResponse(
2961061da546Spatrick packet, "z packet had invalid software/hardware specifier");
2962061da546Spatrick }
2963061da546Spatrick
2964061da546Spatrick if ((packet.GetBytesLeft() < 1) || packet.GetChar() != ',')
2965061da546Spatrick return SendIllFormedResponse(
2966061da546Spatrick packet, "Malformed z packet, expecting comma after stoppoint type");
2967061da546Spatrick
2968061da546Spatrick // Parse out the stoppoint address.
2969061da546Spatrick if (packet.GetBytesLeft() < 1)
2970061da546Spatrick return SendIllFormedResponse(packet, "Too short z packet, missing address");
2971061da546Spatrick const lldb::addr_t addr = packet.GetHexMaxU64(false, 0);
2972061da546Spatrick
2973061da546Spatrick if ((packet.GetBytesLeft() < 1) || packet.GetChar() != ',')
2974061da546Spatrick return SendIllFormedResponse(
2975061da546Spatrick packet, "Malformed z packet, expecting comma after address");
2976061da546Spatrick
2977061da546Spatrick /*
2978061da546Spatrick // Parse out the stoppoint size (i.e. size hint for opcode size).
2979061da546Spatrick const uint32_t size = packet.GetHexMaxU32 (false,
2980061da546Spatrick std::numeric_limits<uint32_t>::max ());
2981061da546Spatrick if (size == std::numeric_limits<uint32_t>::max ())
2982061da546Spatrick return SendIllFormedResponse(packet, "Malformed z packet, failed to parse
2983061da546Spatrick size argument");
2984061da546Spatrick */
2985061da546Spatrick
2986061da546Spatrick if (want_breakpoint) {
2987061da546Spatrick // Try to clear the breakpoint.
2988061da546Spatrick const Status error =
2989be691f3bSpatrick m_current_process->RemoveBreakpoint(addr, want_hardware);
2990061da546Spatrick if (error.Success())
2991061da546Spatrick return SendOKResponse();
2992*f6aab3d8Srobert Log *log = GetLog(LLDBLog::Breakpoints);
2993061da546Spatrick LLDB_LOG(log, "pid {0} failed to remove breakpoint: {1}",
2994be691f3bSpatrick m_current_process->GetID(), error);
2995061da546Spatrick return SendErrorResponse(0x09);
2996061da546Spatrick } else {
2997061da546Spatrick // Try to clear the watchpoint.
2998be691f3bSpatrick const Status error = m_current_process->RemoveWatchpoint(addr);
2999061da546Spatrick if (error.Success())
3000061da546Spatrick return SendOKResponse();
3001*f6aab3d8Srobert Log *log = GetLog(LLDBLog::Watchpoints);
3002061da546Spatrick LLDB_LOG(log, "pid {0} failed to remove watchpoint: {1}",
3003be691f3bSpatrick m_current_process->GetID(), error);
3004061da546Spatrick return SendErrorResponse(0x09);
3005061da546Spatrick }
3006061da546Spatrick }
3007061da546Spatrick
3008061da546Spatrick GDBRemoteCommunication::PacketResult
Handle_s(StringExtractorGDBRemote & packet)3009061da546Spatrick GDBRemoteCommunicationServerLLGS::Handle_s(StringExtractorGDBRemote &packet) {
3010*f6aab3d8Srobert Log *log = GetLog(LLDBLog::Process | LLDBLog::Thread);
3011061da546Spatrick
3012061da546Spatrick // Ensure we have a process.
3013be691f3bSpatrick if (!m_continue_process ||
3014be691f3bSpatrick (m_continue_process->GetID() == LLDB_INVALID_PROCESS_ID)) {
3015061da546Spatrick LLDB_LOGF(
3016061da546Spatrick log,
3017061da546Spatrick "GDBRemoteCommunicationServerLLGS::%s failed, no process available",
3018061da546Spatrick __FUNCTION__);
3019061da546Spatrick return SendErrorResponse(0x32);
3020061da546Spatrick }
3021061da546Spatrick
3022061da546Spatrick // We first try to use a continue thread id. If any one or any all set, use
3023061da546Spatrick // the current thread. Bail out if we don't have a thread id.
3024061da546Spatrick lldb::tid_t tid = GetContinueThreadID();
3025061da546Spatrick if (tid == 0 || tid == LLDB_INVALID_THREAD_ID)
3026061da546Spatrick tid = GetCurrentThreadID();
3027061da546Spatrick if (tid == LLDB_INVALID_THREAD_ID)
3028061da546Spatrick return SendErrorResponse(0x33);
3029061da546Spatrick
3030061da546Spatrick // Double check that we have such a thread.
3031061da546Spatrick // TODO investigate: on MacOSX we might need to do an UpdateThreads () here.
3032be691f3bSpatrick NativeThreadProtocol *thread = m_continue_process->GetThreadByID(tid);
3033061da546Spatrick if (!thread)
3034061da546Spatrick return SendErrorResponse(0x33);
3035061da546Spatrick
3036061da546Spatrick // Create the step action for the given thread.
3037061da546Spatrick ResumeAction action = {tid, eStateStepping, LLDB_INVALID_SIGNAL_NUMBER};
3038061da546Spatrick
3039061da546Spatrick // Setup the actions list.
3040061da546Spatrick ResumeActionList actions;
3041061da546Spatrick actions.Append(action);
3042061da546Spatrick
3043061da546Spatrick // All other threads stop while we're single stepping a thread.
3044061da546Spatrick actions.SetDefaultThreadActionIfNeeded(eStateStopped, 0);
3045061da546Spatrick
3046*f6aab3d8Srobert PacketResult resume_res = ResumeProcess(*m_continue_process, actions);
3047*f6aab3d8Srobert if (resume_res != PacketResult::Success)
3048*f6aab3d8Srobert return resume_res;
3049*f6aab3d8Srobert
3050*f6aab3d8Srobert // No response here, unless in non-stop mode.
3051*f6aab3d8Srobert // Otherwise, the stop or exit will come from the resulting action.
3052*f6aab3d8Srobert return SendContinueSuccessResponse();
3053061da546Spatrick }
3054061da546Spatrick
3055061da546Spatrick llvm::Expected<std::unique_ptr<llvm::MemoryBuffer>>
BuildTargetXml()3056dda28197Spatrick GDBRemoteCommunicationServerLLGS::BuildTargetXml() {
3057dda28197Spatrick // Ensure we have a thread.
3058be691f3bSpatrick NativeThreadProtocol *thread = m_current_process->GetThreadAtIndex(0);
3059dda28197Spatrick if (!thread)
3060dda28197Spatrick return llvm::createStringError(llvm::inconvertibleErrorCode(),
3061dda28197Spatrick "No thread available");
3062dda28197Spatrick
3063*f6aab3d8Srobert Log *log = GetLog(LLDBLog::Process | LLDBLog::Thread);
3064dda28197Spatrick // Get the register context for the first thread.
3065dda28197Spatrick NativeRegisterContext ®_context = thread->GetRegisterContext();
3066dda28197Spatrick
3067dda28197Spatrick StreamString response;
3068dda28197Spatrick
3069*f6aab3d8Srobert response.Printf("<?xml version=\"1.0\"?>\n");
3070*f6aab3d8Srobert response.Printf("<target version=\"1.0\">\n");
3071*f6aab3d8Srobert response.IndentMore();
3072dda28197Spatrick
3073*f6aab3d8Srobert response.Indent();
3074*f6aab3d8Srobert response.Printf("<architecture>%s</architecture>\n",
3075be691f3bSpatrick m_current_process->GetArchitecture()
3076dda28197Spatrick .GetTriple()
3077dda28197Spatrick .getArchName()
3078dda28197Spatrick .str()
3079dda28197Spatrick .c_str());
3080dda28197Spatrick
3081*f6aab3d8Srobert response.Indent("<feature>\n");
3082dda28197Spatrick
3083dda28197Spatrick const int registers_count = reg_context.GetUserRegisterCount();
3084*f6aab3d8Srobert if (registers_count)
3085*f6aab3d8Srobert response.IndentMore();
3086*f6aab3d8Srobert
3087dda28197Spatrick for (int reg_index = 0; reg_index < registers_count; reg_index++) {
3088dda28197Spatrick const RegisterInfo *reg_info =
3089dda28197Spatrick reg_context.GetRegisterInfoAtIndex(reg_index);
3090dda28197Spatrick
3091dda28197Spatrick if (!reg_info) {
3092dda28197Spatrick LLDB_LOGF(log,
3093dda28197Spatrick "%s failed to get register info for register index %" PRIu32,
3094dda28197Spatrick "target.xml", reg_index);
3095dda28197Spatrick continue;
3096dda28197Spatrick }
3097dda28197Spatrick
3098*f6aab3d8Srobert response.Indent();
3099*f6aab3d8Srobert response.Printf("<reg name=\"%s\" bitsize=\"%" PRIu32
3100*f6aab3d8Srobert "\" regnum=\"%d\" ",
3101be691f3bSpatrick reg_info->name, reg_info->byte_size * 8, reg_index);
3102be691f3bSpatrick
3103be691f3bSpatrick if (!reg_context.RegisterOffsetIsDynamic())
3104be691f3bSpatrick response.Printf("offset=\"%" PRIu32 "\" ", reg_info->byte_offset);
3105dda28197Spatrick
3106dda28197Spatrick if (reg_info->alt_name && reg_info->alt_name[0])
3107dda28197Spatrick response.Printf("altname=\"%s\" ", reg_info->alt_name);
3108dda28197Spatrick
3109dda28197Spatrick llvm::StringRef encoding = GetEncodingNameOrEmpty(*reg_info);
3110dda28197Spatrick if (!encoding.empty())
3111dda28197Spatrick response << "encoding=\"" << encoding << "\" ";
3112dda28197Spatrick
3113dda28197Spatrick llvm::StringRef format = GetFormatNameOrEmpty(*reg_info);
3114dda28197Spatrick if (!format.empty())
3115dda28197Spatrick response << "format=\"" << format << "\" ";
3116dda28197Spatrick
3117dda28197Spatrick const char *const register_set_name =
3118dda28197Spatrick reg_context.GetRegisterSetNameForRegisterAtIndex(reg_index);
3119dda28197Spatrick if (register_set_name)
3120dda28197Spatrick response << "group=\"" << register_set_name << "\" ";
3121dda28197Spatrick
3122dda28197Spatrick if (reg_info->kinds[RegisterKind::eRegisterKindEHFrame] !=
3123dda28197Spatrick LLDB_INVALID_REGNUM)
3124dda28197Spatrick response.Printf("ehframe_regnum=\"%" PRIu32 "\" ",
3125dda28197Spatrick reg_info->kinds[RegisterKind::eRegisterKindEHFrame]);
3126dda28197Spatrick
3127dda28197Spatrick if (reg_info->kinds[RegisterKind::eRegisterKindDWARF] !=
3128dda28197Spatrick LLDB_INVALID_REGNUM)
3129dda28197Spatrick response.Printf("dwarf_regnum=\"%" PRIu32 "\" ",
3130dda28197Spatrick reg_info->kinds[RegisterKind::eRegisterKindDWARF]);
3131dda28197Spatrick
3132dda28197Spatrick llvm::StringRef kind_generic = GetKindGenericOrEmpty(*reg_info);
3133dda28197Spatrick if (!kind_generic.empty())
3134dda28197Spatrick response << "generic=\"" << kind_generic << "\" ";
3135dda28197Spatrick
3136dda28197Spatrick if (reg_info->value_regs &&
3137dda28197Spatrick reg_info->value_regs[0] != LLDB_INVALID_REGNUM) {
3138dda28197Spatrick response.PutCString("value_regnums=\"");
3139dda28197Spatrick CollectRegNums(reg_info->value_regs, response, false);
3140dda28197Spatrick response.Printf("\" ");
3141dda28197Spatrick }
3142dda28197Spatrick
3143dda28197Spatrick if (reg_info->invalidate_regs && reg_info->invalidate_regs[0]) {
3144dda28197Spatrick response.PutCString("invalidate_regnums=\"");
3145dda28197Spatrick CollectRegNums(reg_info->invalidate_regs, response, false);
3146dda28197Spatrick response.Printf("\" ");
3147dda28197Spatrick }
3148dda28197Spatrick
3149*f6aab3d8Srobert response.Printf("/>\n");
3150dda28197Spatrick }
3151dda28197Spatrick
3152*f6aab3d8Srobert if (registers_count)
3153*f6aab3d8Srobert response.IndentLess();
3154dda28197Spatrick
3155*f6aab3d8Srobert response.Indent("</feature>\n");
3156*f6aab3d8Srobert response.IndentLess();
3157*f6aab3d8Srobert response.Indent("</target>\n");
3158dda28197Spatrick return MemoryBuffer::getMemBufferCopy(response.GetString(), "target.xml");
3159dda28197Spatrick }
3160dda28197Spatrick
3161dda28197Spatrick llvm::Expected<std::unique_ptr<llvm::MemoryBuffer>>
ReadXferObject(llvm::StringRef object,llvm::StringRef annex)3162061da546Spatrick GDBRemoteCommunicationServerLLGS::ReadXferObject(llvm::StringRef object,
3163061da546Spatrick llvm::StringRef annex) {
3164061da546Spatrick // Make sure we have a valid process.
3165be691f3bSpatrick if (!m_current_process ||
3166be691f3bSpatrick (m_current_process->GetID() == LLDB_INVALID_PROCESS_ID)) {
3167061da546Spatrick return llvm::createStringError(llvm::inconvertibleErrorCode(),
3168061da546Spatrick "No process available");
3169061da546Spatrick }
3170061da546Spatrick
3171dda28197Spatrick if (object == "auxv") {
3172061da546Spatrick // Grab the auxv data.
3173be691f3bSpatrick auto buffer_or_error = m_current_process->GetAuxvData();
3174061da546Spatrick if (!buffer_or_error)
3175061da546Spatrick return llvm::errorCodeToError(buffer_or_error.getError());
3176061da546Spatrick return std::move(*buffer_or_error);
3177061da546Spatrick }
3178061da546Spatrick
3179*f6aab3d8Srobert if (object == "siginfo") {
3180*f6aab3d8Srobert NativeThreadProtocol *thread = m_current_process->GetCurrentThread();
3181*f6aab3d8Srobert if (!thread)
3182*f6aab3d8Srobert return llvm::createStringError(llvm::inconvertibleErrorCode(),
3183*f6aab3d8Srobert "no current thread");
3184*f6aab3d8Srobert
3185*f6aab3d8Srobert auto buffer_or_error = thread->GetSiginfo();
3186*f6aab3d8Srobert if (!buffer_or_error)
3187*f6aab3d8Srobert return buffer_or_error.takeError();
3188*f6aab3d8Srobert return std::move(*buffer_or_error);
3189*f6aab3d8Srobert }
3190*f6aab3d8Srobert
3191061da546Spatrick if (object == "libraries-svr4") {
3192be691f3bSpatrick auto library_list = m_current_process->GetLoadedSVR4Libraries();
3193061da546Spatrick if (!library_list)
3194061da546Spatrick return library_list.takeError();
3195061da546Spatrick
3196061da546Spatrick StreamString response;
3197061da546Spatrick response.Printf("<library-list-svr4 version=\"1.0\">");
3198061da546Spatrick for (auto const &library : *library_list) {
3199061da546Spatrick response.Printf("<library name=\"%s\" ",
3200061da546Spatrick XMLEncodeAttributeValue(library.name.c_str()).c_str());
3201061da546Spatrick response.Printf("lm=\"0x%" PRIx64 "\" ", library.link_map);
3202061da546Spatrick response.Printf("l_addr=\"0x%" PRIx64 "\" ", library.base_addr);
3203061da546Spatrick response.Printf("l_ld=\"0x%" PRIx64 "\" />", library.ld_addr);
3204061da546Spatrick }
3205061da546Spatrick response.Printf("</library-list-svr4>");
3206061da546Spatrick return MemoryBuffer::getMemBufferCopy(response.GetString(), __FUNCTION__);
3207061da546Spatrick }
3208061da546Spatrick
3209dda28197Spatrick if (object == "features" && annex == "target.xml")
3210dda28197Spatrick return BuildTargetXml();
3211dda28197Spatrick
3212be691f3bSpatrick return llvm::make_error<UnimplementedError>();
3213061da546Spatrick }
3214061da546Spatrick
3215061da546Spatrick GDBRemoteCommunication::PacketResult
Handle_qXfer(StringExtractorGDBRemote & packet)3216061da546Spatrick GDBRemoteCommunicationServerLLGS::Handle_qXfer(
3217061da546Spatrick StringExtractorGDBRemote &packet) {
3218061da546Spatrick SmallVector<StringRef, 5> fields;
3219061da546Spatrick // The packet format is "qXfer:<object>:<action>:<annex>:offset,length"
3220061da546Spatrick StringRef(packet.GetStringRef()).split(fields, ':', 4);
3221061da546Spatrick if (fields.size() != 5)
3222061da546Spatrick return SendIllFormedResponse(packet, "malformed qXfer packet");
3223061da546Spatrick StringRef &xfer_object = fields[1];
3224061da546Spatrick StringRef &xfer_action = fields[2];
3225061da546Spatrick StringRef &xfer_annex = fields[3];
3226061da546Spatrick StringExtractor offset_data(fields[4]);
3227061da546Spatrick if (xfer_action != "read")
3228061da546Spatrick return SendUnimplementedResponse("qXfer action not supported");
3229061da546Spatrick // Parse offset.
3230061da546Spatrick const uint64_t xfer_offset =
3231061da546Spatrick offset_data.GetHexMaxU64(false, std::numeric_limits<uint64_t>::max());
3232061da546Spatrick if (xfer_offset == std::numeric_limits<uint64_t>::max())
3233061da546Spatrick return SendIllFormedResponse(packet, "qXfer packet missing offset");
3234061da546Spatrick // Parse out comma.
3235061da546Spatrick if (offset_data.GetChar() != ',')
3236061da546Spatrick return SendIllFormedResponse(packet,
3237061da546Spatrick "qXfer packet missing comma after offset");
3238061da546Spatrick // Parse out the length.
3239061da546Spatrick const uint64_t xfer_length =
3240061da546Spatrick offset_data.GetHexMaxU64(false, std::numeric_limits<uint64_t>::max());
3241061da546Spatrick if (xfer_length == std::numeric_limits<uint64_t>::max())
3242061da546Spatrick return SendIllFormedResponse(packet, "qXfer packet missing length");
3243061da546Spatrick
3244061da546Spatrick // Get a previously constructed buffer if it exists or create it now.
3245061da546Spatrick std::string buffer_key = (xfer_object + xfer_action + xfer_annex).str();
3246061da546Spatrick auto buffer_it = m_xfer_buffer_map.find(buffer_key);
3247061da546Spatrick if (buffer_it == m_xfer_buffer_map.end()) {
3248061da546Spatrick auto buffer_up = ReadXferObject(xfer_object, xfer_annex);
3249061da546Spatrick if (!buffer_up)
3250061da546Spatrick return SendErrorResponse(buffer_up.takeError());
3251061da546Spatrick buffer_it = m_xfer_buffer_map
3252061da546Spatrick .insert(std::make_pair(buffer_key, std::move(*buffer_up)))
3253061da546Spatrick .first;
3254061da546Spatrick }
3255061da546Spatrick
3256061da546Spatrick // Send back the response
3257061da546Spatrick StreamGDBRemote response;
3258061da546Spatrick bool done_with_buffer = false;
3259061da546Spatrick llvm::StringRef buffer = buffer_it->second->getBuffer();
3260061da546Spatrick if (xfer_offset >= buffer.size()) {
3261061da546Spatrick // We have nothing left to send. Mark the buffer as complete.
3262061da546Spatrick response.PutChar('l');
3263061da546Spatrick done_with_buffer = true;
3264061da546Spatrick } else {
3265061da546Spatrick // Figure out how many bytes are available starting at the given offset.
3266061da546Spatrick buffer = buffer.drop_front(xfer_offset);
3267061da546Spatrick // Mark the response type according to whether we're reading the remainder
3268061da546Spatrick // of the data.
3269061da546Spatrick if (xfer_length >= buffer.size()) {
3270061da546Spatrick // There will be nothing left to read after this
3271061da546Spatrick response.PutChar('l');
3272061da546Spatrick done_with_buffer = true;
3273061da546Spatrick } else {
3274061da546Spatrick // There will still be bytes to read after this request.
3275061da546Spatrick response.PutChar('m');
3276061da546Spatrick buffer = buffer.take_front(xfer_length);
3277061da546Spatrick }
3278061da546Spatrick // Now write the data in encoded binary form.
3279061da546Spatrick response.PutEscapedBytes(buffer.data(), buffer.size());
3280061da546Spatrick }
3281061da546Spatrick
3282061da546Spatrick if (done_with_buffer)
3283061da546Spatrick m_xfer_buffer_map.erase(buffer_it);
3284061da546Spatrick
3285061da546Spatrick return SendPacketNoLock(response.GetString());
3286061da546Spatrick }
3287061da546Spatrick
3288061da546Spatrick GDBRemoteCommunication::PacketResult
Handle_QSaveRegisterState(StringExtractorGDBRemote & packet)3289061da546Spatrick GDBRemoteCommunicationServerLLGS::Handle_QSaveRegisterState(
3290061da546Spatrick StringExtractorGDBRemote &packet) {
3291*f6aab3d8Srobert Log *log = GetLog(LLDBLog::Thread);
3292061da546Spatrick
3293061da546Spatrick // Move past packet name.
3294061da546Spatrick packet.SetFilePos(strlen("QSaveRegisterState"));
3295061da546Spatrick
3296061da546Spatrick // Get the thread to use.
3297061da546Spatrick NativeThreadProtocol *thread = GetThreadFromSuffix(packet);
3298061da546Spatrick if (!thread) {
3299061da546Spatrick if (m_thread_suffix_supported)
3300061da546Spatrick return SendIllFormedResponse(
3301061da546Spatrick packet, "No thread specified in QSaveRegisterState packet");
3302061da546Spatrick else
3303061da546Spatrick return SendIllFormedResponse(packet,
3304061da546Spatrick "No thread was is set with the Hg packet");
3305061da546Spatrick }
3306061da546Spatrick
3307061da546Spatrick // Grab the register context for the thread.
3308061da546Spatrick NativeRegisterContext& reg_context = thread->GetRegisterContext();
3309061da546Spatrick
3310061da546Spatrick // Save registers to a buffer.
3311*f6aab3d8Srobert WritableDataBufferSP register_data_sp;
3312061da546Spatrick Status error = reg_context.ReadAllRegisterValues(register_data_sp);
3313061da546Spatrick if (error.Fail()) {
3314061da546Spatrick LLDB_LOG(log, "pid {0} failed to save all register values: {1}",
3315be691f3bSpatrick m_current_process->GetID(), error);
3316061da546Spatrick return SendErrorResponse(0x75);
3317061da546Spatrick }
3318061da546Spatrick
3319061da546Spatrick // Allocate a new save id.
3320061da546Spatrick const uint32_t save_id = GetNextSavedRegistersID();
3321061da546Spatrick assert((m_saved_registers_map.find(save_id) == m_saved_registers_map.end()) &&
3322061da546Spatrick "GetNextRegisterSaveID() returned an existing register save id");
3323061da546Spatrick
3324061da546Spatrick // Save the register data buffer under the save id.
3325061da546Spatrick {
3326061da546Spatrick std::lock_guard<std::mutex> guard(m_saved_registers_mutex);
3327061da546Spatrick m_saved_registers_map[save_id] = register_data_sp;
3328061da546Spatrick }
3329061da546Spatrick
3330061da546Spatrick // Write the response.
3331061da546Spatrick StreamGDBRemote response;
3332061da546Spatrick response.Printf("%" PRIu32, save_id);
3333061da546Spatrick return SendPacketNoLock(response.GetString());
3334061da546Spatrick }
3335061da546Spatrick
3336061da546Spatrick GDBRemoteCommunication::PacketResult
Handle_QRestoreRegisterState(StringExtractorGDBRemote & packet)3337061da546Spatrick GDBRemoteCommunicationServerLLGS::Handle_QRestoreRegisterState(
3338061da546Spatrick StringExtractorGDBRemote &packet) {
3339*f6aab3d8Srobert Log *log = GetLog(LLDBLog::Thread);
3340061da546Spatrick
3341061da546Spatrick // Parse out save id.
3342061da546Spatrick packet.SetFilePos(strlen("QRestoreRegisterState:"));
3343061da546Spatrick if (packet.GetBytesLeft() < 1)
3344061da546Spatrick return SendIllFormedResponse(
3345061da546Spatrick packet, "QRestoreRegisterState packet missing register save id");
3346061da546Spatrick
3347061da546Spatrick const uint32_t save_id = packet.GetU32(0);
3348061da546Spatrick if (save_id == 0) {
3349061da546Spatrick LLDB_LOG(log, "QRestoreRegisterState packet has malformed save id, "
3350061da546Spatrick "expecting decimal uint32_t");
3351061da546Spatrick return SendErrorResponse(0x76);
3352061da546Spatrick }
3353061da546Spatrick
3354061da546Spatrick // Get the thread to use.
3355061da546Spatrick NativeThreadProtocol *thread = GetThreadFromSuffix(packet);
3356061da546Spatrick if (!thread) {
3357061da546Spatrick if (m_thread_suffix_supported)
3358061da546Spatrick return SendIllFormedResponse(
3359061da546Spatrick packet, "No thread specified in QRestoreRegisterState packet");
3360061da546Spatrick else
3361061da546Spatrick return SendIllFormedResponse(packet,
3362061da546Spatrick "No thread was is set with the Hg packet");
3363061da546Spatrick }
3364061da546Spatrick
3365061da546Spatrick // Grab the register context for the thread.
3366061da546Spatrick NativeRegisterContext ®_context = thread->GetRegisterContext();
3367061da546Spatrick
3368061da546Spatrick // Retrieve register state buffer, then remove from the list.
3369061da546Spatrick DataBufferSP register_data_sp;
3370061da546Spatrick {
3371061da546Spatrick std::lock_guard<std::mutex> guard(m_saved_registers_mutex);
3372061da546Spatrick
3373061da546Spatrick // Find the register set buffer for the given save id.
3374061da546Spatrick auto it = m_saved_registers_map.find(save_id);
3375061da546Spatrick if (it == m_saved_registers_map.end()) {
3376061da546Spatrick LLDB_LOG(log,
3377061da546Spatrick "pid {0} does not have a register set save buffer for id {1}",
3378be691f3bSpatrick m_current_process->GetID(), save_id);
3379061da546Spatrick return SendErrorResponse(0x77);
3380061da546Spatrick }
3381061da546Spatrick register_data_sp = it->second;
3382061da546Spatrick
3383061da546Spatrick // Remove it from the map.
3384061da546Spatrick m_saved_registers_map.erase(it);
3385061da546Spatrick }
3386061da546Spatrick
3387061da546Spatrick Status error = reg_context.WriteAllRegisterValues(register_data_sp);
3388061da546Spatrick if (error.Fail()) {
3389061da546Spatrick LLDB_LOG(log, "pid {0} failed to restore all register values: {1}",
3390be691f3bSpatrick m_current_process->GetID(), error);
3391061da546Spatrick return SendErrorResponse(0x77);
3392061da546Spatrick }
3393061da546Spatrick
3394061da546Spatrick return SendOKResponse();
3395061da546Spatrick }
3396061da546Spatrick
3397061da546Spatrick GDBRemoteCommunication::PacketResult
Handle_vAttach(StringExtractorGDBRemote & packet)3398061da546Spatrick GDBRemoteCommunicationServerLLGS::Handle_vAttach(
3399061da546Spatrick StringExtractorGDBRemote &packet) {
3400*f6aab3d8Srobert Log *log = GetLog(LLDBLog::Process);
3401061da546Spatrick
3402061da546Spatrick // Consume the ';' after vAttach.
3403061da546Spatrick packet.SetFilePos(strlen("vAttach"));
3404061da546Spatrick if (!packet.GetBytesLeft() || packet.GetChar() != ';')
3405061da546Spatrick return SendIllFormedResponse(packet, "vAttach missing expected ';'");
3406061da546Spatrick
3407061da546Spatrick // Grab the PID to which we will attach (assume hex encoding).
3408061da546Spatrick lldb::pid_t pid = packet.GetU32(LLDB_INVALID_PROCESS_ID, 16);
3409061da546Spatrick if (pid == LLDB_INVALID_PROCESS_ID)
3410061da546Spatrick return SendIllFormedResponse(packet,
3411061da546Spatrick "vAttach failed to parse the process id");
3412061da546Spatrick
3413061da546Spatrick // Attempt to attach.
3414061da546Spatrick LLDB_LOGF(log,
3415061da546Spatrick "GDBRemoteCommunicationServerLLGS::%s attempting to attach to "
3416061da546Spatrick "pid %" PRIu64,
3417061da546Spatrick __FUNCTION__, pid);
3418061da546Spatrick
3419061da546Spatrick Status error = AttachToProcess(pid);
3420061da546Spatrick
3421061da546Spatrick if (error.Fail()) {
3422061da546Spatrick LLDB_LOGF(log,
3423061da546Spatrick "GDBRemoteCommunicationServerLLGS::%s failed to attach to "
3424061da546Spatrick "pid %" PRIu64 ": %s\n",
3425061da546Spatrick __FUNCTION__, pid, error.AsCString());
3426061da546Spatrick return SendErrorResponse(error);
3427061da546Spatrick }
3428061da546Spatrick
3429061da546Spatrick // Notify we attached by sending a stop packet.
3430*f6aab3d8Srobert assert(m_current_process);
3431*f6aab3d8Srobert return SendStopReasonForState(*m_current_process,
3432*f6aab3d8Srobert m_current_process->GetState(),
3433*f6aab3d8Srobert /*force_synchronous=*/false);
3434be691f3bSpatrick }
3435be691f3bSpatrick
3436be691f3bSpatrick GDBRemoteCommunication::PacketResult
Handle_vAttachWait(StringExtractorGDBRemote & packet)3437be691f3bSpatrick GDBRemoteCommunicationServerLLGS::Handle_vAttachWait(
3438be691f3bSpatrick StringExtractorGDBRemote &packet) {
3439*f6aab3d8Srobert Log *log = GetLog(LLDBLog::Process);
3440be691f3bSpatrick
3441be691f3bSpatrick // Consume the ';' after the identifier.
3442be691f3bSpatrick packet.SetFilePos(strlen("vAttachWait"));
3443be691f3bSpatrick
3444be691f3bSpatrick if (!packet.GetBytesLeft() || packet.GetChar() != ';')
3445be691f3bSpatrick return SendIllFormedResponse(packet, "vAttachWait missing expected ';'");
3446be691f3bSpatrick
3447be691f3bSpatrick // Allocate the buffer for the process name from vAttachWait.
3448be691f3bSpatrick std::string process_name;
3449be691f3bSpatrick if (!packet.GetHexByteString(process_name))
3450be691f3bSpatrick return SendIllFormedResponse(packet,
3451be691f3bSpatrick "vAttachWait failed to parse process name");
3452be691f3bSpatrick
3453be691f3bSpatrick LLDB_LOG(log, "attempting to attach to process named '{0}'", process_name);
3454be691f3bSpatrick
3455be691f3bSpatrick Status error = AttachWaitProcess(process_name, false);
3456be691f3bSpatrick if (error.Fail()) {
3457be691f3bSpatrick LLDB_LOG(log, "failed to attach to process named '{0}': {1}", process_name,
3458be691f3bSpatrick error);
3459be691f3bSpatrick return SendErrorResponse(error);
3460be691f3bSpatrick }
3461be691f3bSpatrick
3462be691f3bSpatrick // Notify we attached by sending a stop packet.
3463*f6aab3d8Srobert assert(m_current_process);
3464*f6aab3d8Srobert return SendStopReasonForState(*m_current_process,
3465*f6aab3d8Srobert m_current_process->GetState(),
3466*f6aab3d8Srobert /*force_synchronous=*/false);
3467be691f3bSpatrick }
3468be691f3bSpatrick
3469be691f3bSpatrick GDBRemoteCommunication::PacketResult
Handle_qVAttachOrWaitSupported(StringExtractorGDBRemote & packet)3470be691f3bSpatrick GDBRemoteCommunicationServerLLGS::Handle_qVAttachOrWaitSupported(
3471be691f3bSpatrick StringExtractorGDBRemote &packet) {
3472be691f3bSpatrick return SendOKResponse();
3473be691f3bSpatrick }
3474be691f3bSpatrick
3475be691f3bSpatrick GDBRemoteCommunication::PacketResult
Handle_vAttachOrWait(StringExtractorGDBRemote & packet)3476be691f3bSpatrick GDBRemoteCommunicationServerLLGS::Handle_vAttachOrWait(
3477be691f3bSpatrick StringExtractorGDBRemote &packet) {
3478*f6aab3d8Srobert Log *log = GetLog(LLDBLog::Process);
3479be691f3bSpatrick
3480be691f3bSpatrick // Consume the ';' after the identifier.
3481be691f3bSpatrick packet.SetFilePos(strlen("vAttachOrWait"));
3482be691f3bSpatrick
3483be691f3bSpatrick if (!packet.GetBytesLeft() || packet.GetChar() != ';')
3484be691f3bSpatrick return SendIllFormedResponse(packet, "vAttachOrWait missing expected ';'");
3485be691f3bSpatrick
3486be691f3bSpatrick // Allocate the buffer for the process name from vAttachWait.
3487be691f3bSpatrick std::string process_name;
3488be691f3bSpatrick if (!packet.GetHexByteString(process_name))
3489be691f3bSpatrick return SendIllFormedResponse(packet,
3490be691f3bSpatrick "vAttachOrWait failed to parse process name");
3491be691f3bSpatrick
3492be691f3bSpatrick LLDB_LOG(log, "attempting to attach to process named '{0}'", process_name);
3493be691f3bSpatrick
3494be691f3bSpatrick Status error = AttachWaitProcess(process_name, true);
3495be691f3bSpatrick if (error.Fail()) {
3496be691f3bSpatrick LLDB_LOG(log, "failed to attach to process named '{0}': {1}", process_name,
3497be691f3bSpatrick error);
3498be691f3bSpatrick return SendErrorResponse(error);
3499be691f3bSpatrick }
3500be691f3bSpatrick
3501be691f3bSpatrick // Notify we attached by sending a stop packet.
3502*f6aab3d8Srobert assert(m_current_process);
3503*f6aab3d8Srobert return SendStopReasonForState(*m_current_process,
3504*f6aab3d8Srobert m_current_process->GetState(),
3505*f6aab3d8Srobert /*force_synchronous=*/false);
3506*f6aab3d8Srobert }
3507*f6aab3d8Srobert
3508*f6aab3d8Srobert GDBRemoteCommunication::PacketResult
Handle_vRun(StringExtractorGDBRemote & packet)3509*f6aab3d8Srobert GDBRemoteCommunicationServerLLGS::Handle_vRun(
3510*f6aab3d8Srobert StringExtractorGDBRemote &packet) {
3511*f6aab3d8Srobert Log *log = GetLog(LLDBLog::Process);
3512*f6aab3d8Srobert
3513*f6aab3d8Srobert llvm::StringRef s = packet.GetStringRef();
3514*f6aab3d8Srobert if (!s.consume_front("vRun;"))
3515*f6aab3d8Srobert return SendErrorResponse(8);
3516*f6aab3d8Srobert
3517*f6aab3d8Srobert llvm::SmallVector<llvm::StringRef, 16> argv;
3518*f6aab3d8Srobert s.split(argv, ';');
3519*f6aab3d8Srobert
3520*f6aab3d8Srobert for (llvm::StringRef hex_arg : argv) {
3521*f6aab3d8Srobert StringExtractor arg_ext{hex_arg};
3522*f6aab3d8Srobert std::string arg;
3523*f6aab3d8Srobert arg_ext.GetHexByteString(arg);
3524*f6aab3d8Srobert m_process_launch_info.GetArguments().AppendArgument(arg);
3525*f6aab3d8Srobert LLDB_LOGF(log, "LLGSPacketHandler::%s added arg: \"%s\"", __FUNCTION__,
3526*f6aab3d8Srobert arg.c_str());
3527*f6aab3d8Srobert }
3528*f6aab3d8Srobert
3529*f6aab3d8Srobert if (argv.empty())
3530*f6aab3d8Srobert return SendErrorResponse(Status("No arguments"));
3531*f6aab3d8Srobert m_process_launch_info.GetExecutableFile().SetFile(
3532*f6aab3d8Srobert m_process_launch_info.GetArguments()[0].ref(), FileSpec::Style::native);
3533*f6aab3d8Srobert m_process_launch_error = LaunchProcess();
3534*f6aab3d8Srobert if (m_process_launch_error.Fail())
3535*f6aab3d8Srobert return SendErrorResponse(m_process_launch_error);
3536*f6aab3d8Srobert assert(m_current_process);
3537*f6aab3d8Srobert return SendStopReasonForState(*m_current_process,
3538*f6aab3d8Srobert m_current_process->GetState(),
3539*f6aab3d8Srobert /*force_synchronous=*/true);
3540061da546Spatrick }
3541061da546Spatrick
3542061da546Spatrick GDBRemoteCommunication::PacketResult
Handle_D(StringExtractorGDBRemote & packet)3543061da546Spatrick GDBRemoteCommunicationServerLLGS::Handle_D(StringExtractorGDBRemote &packet) {
3544*f6aab3d8Srobert Log *log = GetLog(LLDBLog::Process);
3545*f6aab3d8Srobert if (!m_non_stop)
3546061da546Spatrick StopSTDIOForwarding();
3547061da546Spatrick
3548061da546Spatrick lldb::pid_t pid = LLDB_INVALID_PROCESS_ID;
3549061da546Spatrick
3550061da546Spatrick // Consume the ';' after D.
3551061da546Spatrick packet.SetFilePos(1);
3552061da546Spatrick if (packet.GetBytesLeft()) {
3553061da546Spatrick if (packet.GetChar() != ';')
3554061da546Spatrick return SendIllFormedResponse(packet, "D missing expected ';'");
3555061da546Spatrick
3556061da546Spatrick // Grab the PID from which we will detach (assume hex encoding).
3557061da546Spatrick pid = packet.GetU32(LLDB_INVALID_PROCESS_ID, 16);
3558061da546Spatrick if (pid == LLDB_INVALID_PROCESS_ID)
3559061da546Spatrick return SendIllFormedResponse(packet, "D failed to parse the process id");
3560061da546Spatrick }
3561061da546Spatrick
3562be691f3bSpatrick // Detach forked children if their PID was specified *or* no PID was requested
3563be691f3bSpatrick // (i.e. detach-all packet).
3564be691f3bSpatrick llvm::Error detach_error = llvm::Error::success();
3565be691f3bSpatrick bool detached = false;
3566be691f3bSpatrick for (auto it = m_debugged_processes.begin();
3567be691f3bSpatrick it != m_debugged_processes.end();) {
3568be691f3bSpatrick if (pid == LLDB_INVALID_PROCESS_ID || pid == it->first) {
3569*f6aab3d8Srobert LLDB_LOGF(log,
3570*f6aab3d8Srobert "GDBRemoteCommunicationServerLLGS::%s detaching %" PRId64,
3571*f6aab3d8Srobert __FUNCTION__, it->first);
3572*f6aab3d8Srobert if (llvm::Error e = it->second.process_up->Detach().ToError())
3573be691f3bSpatrick detach_error = llvm::joinErrors(std::move(detach_error), std::move(e));
3574be691f3bSpatrick else {
3575*f6aab3d8Srobert if (it->second.process_up.get() == m_current_process)
3576be691f3bSpatrick m_current_process = nullptr;
3577*f6aab3d8Srobert if (it->second.process_up.get() == m_continue_process)
3578be691f3bSpatrick m_continue_process = nullptr;
3579be691f3bSpatrick it = m_debugged_processes.erase(it);
3580be691f3bSpatrick detached = true;
3581be691f3bSpatrick continue;
3582be691f3bSpatrick }
3583be691f3bSpatrick }
3584be691f3bSpatrick ++it;
3585061da546Spatrick }
3586061da546Spatrick
3587be691f3bSpatrick if (detach_error)
3588be691f3bSpatrick return SendErrorResponse(std::move(detach_error));
3589be691f3bSpatrick if (!detached)
3590be691f3bSpatrick return SendErrorResponse(Status("PID %" PRIu64 " not traced", pid));
3591061da546Spatrick return SendOKResponse();
3592061da546Spatrick }
3593061da546Spatrick
3594061da546Spatrick GDBRemoteCommunication::PacketResult
Handle_qThreadStopInfo(StringExtractorGDBRemote & packet)3595061da546Spatrick GDBRemoteCommunicationServerLLGS::Handle_qThreadStopInfo(
3596061da546Spatrick StringExtractorGDBRemote &packet) {
3597*f6aab3d8Srobert Log *log = GetLog(LLDBLog::Thread);
3598*f6aab3d8Srobert
3599*f6aab3d8Srobert if (!m_current_process ||
3600*f6aab3d8Srobert (m_current_process->GetID() == LLDB_INVALID_PROCESS_ID))
3601*f6aab3d8Srobert return SendErrorResponse(50);
3602061da546Spatrick
3603061da546Spatrick packet.SetFilePos(strlen("qThreadStopInfo"));
3604be691f3bSpatrick const lldb::tid_t tid = packet.GetHexMaxU64(false, LLDB_INVALID_THREAD_ID);
3605061da546Spatrick if (tid == LLDB_INVALID_THREAD_ID) {
3606061da546Spatrick LLDB_LOGF(log,
3607061da546Spatrick "GDBRemoteCommunicationServerLLGS::%s failed, could not "
3608061da546Spatrick "parse thread id from request \"%s\"",
3609061da546Spatrick __FUNCTION__, packet.GetStringRef().data());
3610061da546Spatrick return SendErrorResponse(0x15);
3611061da546Spatrick }
3612*f6aab3d8Srobert return SendStopReplyPacketForThread(*m_current_process, tid,
3613*f6aab3d8Srobert /*force_synchronous=*/true);
3614061da546Spatrick }
3615061da546Spatrick
3616061da546Spatrick GDBRemoteCommunication::PacketResult
Handle_jThreadsInfo(StringExtractorGDBRemote &)3617061da546Spatrick GDBRemoteCommunicationServerLLGS::Handle_jThreadsInfo(
3618061da546Spatrick StringExtractorGDBRemote &) {
3619*f6aab3d8Srobert Log *log = GetLog(LLDBLog::Process | LLDBLog::Thread);
3620061da546Spatrick
3621061da546Spatrick // Ensure we have a debugged process.
3622be691f3bSpatrick if (!m_current_process ||
3623be691f3bSpatrick (m_current_process->GetID() == LLDB_INVALID_PROCESS_ID))
3624061da546Spatrick return SendErrorResponse(50);
3625be691f3bSpatrick LLDB_LOG(log, "preparing packet for pid {0}", m_current_process->GetID());
3626061da546Spatrick
3627061da546Spatrick StreamString response;
3628061da546Spatrick const bool threads_with_valid_stop_info_only = false;
3629be691f3bSpatrick llvm::Expected<json::Value> threads_info =
3630be691f3bSpatrick GetJSONThreadsInfo(*m_current_process, threads_with_valid_stop_info_only);
3631061da546Spatrick if (!threads_info) {
3632061da546Spatrick LLDB_LOG_ERROR(log, threads_info.takeError(),
3633061da546Spatrick "failed to prepare a packet for pid {1}: {0}",
3634be691f3bSpatrick m_current_process->GetID());
3635061da546Spatrick return SendErrorResponse(52);
3636061da546Spatrick }
3637061da546Spatrick
3638061da546Spatrick response.AsRawOstream() << *threads_info;
3639061da546Spatrick StreamGDBRemote escaped_response;
3640061da546Spatrick escaped_response.PutEscapedBytes(response.GetData(), response.GetSize());
3641061da546Spatrick return SendPacketNoLock(escaped_response.GetString());
3642061da546Spatrick }
3643061da546Spatrick
3644061da546Spatrick GDBRemoteCommunication::PacketResult
Handle_qWatchpointSupportInfo(StringExtractorGDBRemote & packet)3645061da546Spatrick GDBRemoteCommunicationServerLLGS::Handle_qWatchpointSupportInfo(
3646061da546Spatrick StringExtractorGDBRemote &packet) {
3647061da546Spatrick // Fail if we don't have a current process.
3648be691f3bSpatrick if (!m_current_process ||
3649be691f3bSpatrick m_current_process->GetID() == LLDB_INVALID_PROCESS_ID)
3650061da546Spatrick return SendErrorResponse(68);
3651061da546Spatrick
3652061da546Spatrick packet.SetFilePos(strlen("qWatchpointSupportInfo"));
3653061da546Spatrick if (packet.GetBytesLeft() == 0)
3654061da546Spatrick return SendOKResponse();
3655061da546Spatrick if (packet.GetChar() != ':')
3656061da546Spatrick return SendErrorResponse(67);
3657061da546Spatrick
3658be691f3bSpatrick auto hw_debug_cap = m_current_process->GetHardwareDebugSupportInfo();
3659061da546Spatrick
3660061da546Spatrick StreamGDBRemote response;
3661*f6aab3d8Srobert if (hw_debug_cap == std::nullopt)
3662061da546Spatrick response.Printf("num:0;");
3663061da546Spatrick else
3664061da546Spatrick response.Printf("num:%d;", hw_debug_cap->second);
3665061da546Spatrick
3666061da546Spatrick return SendPacketNoLock(response.GetString());
3667061da546Spatrick }
3668061da546Spatrick
3669061da546Spatrick GDBRemoteCommunication::PacketResult
Handle_qFileLoadAddress(StringExtractorGDBRemote & packet)3670061da546Spatrick GDBRemoteCommunicationServerLLGS::Handle_qFileLoadAddress(
3671061da546Spatrick StringExtractorGDBRemote &packet) {
3672061da546Spatrick // Fail if we don't have a current process.
3673be691f3bSpatrick if (!m_current_process ||
3674be691f3bSpatrick m_current_process->GetID() == LLDB_INVALID_PROCESS_ID)
3675061da546Spatrick return SendErrorResponse(67);
3676061da546Spatrick
3677061da546Spatrick packet.SetFilePos(strlen("qFileLoadAddress:"));
3678061da546Spatrick if (packet.GetBytesLeft() == 0)
3679061da546Spatrick return SendErrorResponse(68);
3680061da546Spatrick
3681061da546Spatrick std::string file_name;
3682061da546Spatrick packet.GetHexByteString(file_name);
3683061da546Spatrick
3684061da546Spatrick lldb::addr_t file_load_address = LLDB_INVALID_ADDRESS;
3685061da546Spatrick Status error =
3686be691f3bSpatrick m_current_process->GetFileLoadAddress(file_name, file_load_address);
3687061da546Spatrick if (error.Fail())
3688061da546Spatrick return SendErrorResponse(69);
3689061da546Spatrick
3690061da546Spatrick if (file_load_address == LLDB_INVALID_ADDRESS)
3691061da546Spatrick return SendErrorResponse(1); // File not loaded
3692061da546Spatrick
3693061da546Spatrick StreamGDBRemote response;
3694061da546Spatrick response.PutHex64(file_load_address);
3695061da546Spatrick return SendPacketNoLock(response.GetString());
3696061da546Spatrick }
3697061da546Spatrick
3698061da546Spatrick GDBRemoteCommunication::PacketResult
Handle_QPassSignals(StringExtractorGDBRemote & packet)3699061da546Spatrick GDBRemoteCommunicationServerLLGS::Handle_QPassSignals(
3700061da546Spatrick StringExtractorGDBRemote &packet) {
3701061da546Spatrick std::vector<int> signals;
3702061da546Spatrick packet.SetFilePos(strlen("QPassSignals:"));
3703061da546Spatrick
3704061da546Spatrick // Read sequence of hex signal numbers divided by a semicolon and optionally
3705061da546Spatrick // spaces.
3706061da546Spatrick while (packet.GetBytesLeft() > 0) {
3707061da546Spatrick int signal = packet.GetS32(-1, 16);
3708061da546Spatrick if (signal < 0)
3709061da546Spatrick return SendIllFormedResponse(packet, "Failed to parse signal number.");
3710061da546Spatrick signals.push_back(signal);
3711061da546Spatrick
3712061da546Spatrick packet.SkipSpaces();
3713061da546Spatrick char separator = packet.GetChar();
3714061da546Spatrick if (separator == '\0')
3715061da546Spatrick break; // End of string
3716061da546Spatrick if (separator != ';')
3717061da546Spatrick return SendIllFormedResponse(packet, "Invalid separator,"
3718061da546Spatrick " expected semicolon.");
3719061da546Spatrick }
3720061da546Spatrick
3721061da546Spatrick // Fail if we don't have a current process.
3722be691f3bSpatrick if (!m_current_process)
3723061da546Spatrick return SendErrorResponse(68);
3724061da546Spatrick
3725be691f3bSpatrick Status error = m_current_process->IgnoreSignals(signals);
3726061da546Spatrick if (error.Fail())
3727061da546Spatrick return SendErrorResponse(69);
3728061da546Spatrick
3729061da546Spatrick return SendOKResponse();
3730061da546Spatrick }
3731061da546Spatrick
3732be691f3bSpatrick GDBRemoteCommunication::PacketResult
Handle_qMemTags(StringExtractorGDBRemote & packet)3733be691f3bSpatrick GDBRemoteCommunicationServerLLGS::Handle_qMemTags(
3734be691f3bSpatrick StringExtractorGDBRemote &packet) {
3735*f6aab3d8Srobert Log *log = GetLog(LLDBLog::Process);
3736be691f3bSpatrick
3737be691f3bSpatrick // Ensure we have a process.
3738be691f3bSpatrick if (!m_current_process ||
3739be691f3bSpatrick (m_current_process->GetID() == LLDB_INVALID_PROCESS_ID)) {
3740be691f3bSpatrick LLDB_LOGF(
3741be691f3bSpatrick log,
3742be691f3bSpatrick "GDBRemoteCommunicationServerLLGS::%s failed, no process available",
3743be691f3bSpatrick __FUNCTION__);
3744be691f3bSpatrick return SendErrorResponse(1);
3745be691f3bSpatrick }
3746be691f3bSpatrick
3747be691f3bSpatrick // We are expecting
3748be691f3bSpatrick // qMemTags:<hex address>,<hex length>:<hex type>
3749be691f3bSpatrick
3750be691f3bSpatrick // Address
3751be691f3bSpatrick packet.SetFilePos(strlen("qMemTags:"));
3752be691f3bSpatrick const char *current_char = packet.Peek();
3753be691f3bSpatrick if (!current_char || *current_char == ',')
3754be691f3bSpatrick return SendIllFormedResponse(packet, "Missing address in qMemTags packet");
3755be691f3bSpatrick const lldb::addr_t addr = packet.GetHexMaxU64(/*little_endian=*/false, 0);
3756be691f3bSpatrick
3757be691f3bSpatrick // Length
3758be691f3bSpatrick char previous_char = packet.GetChar();
3759be691f3bSpatrick current_char = packet.Peek();
3760be691f3bSpatrick // If we don't have a separator or the length field is empty
3761be691f3bSpatrick if (previous_char != ',' || (current_char && *current_char == ':'))
3762be691f3bSpatrick return SendIllFormedResponse(packet,
3763be691f3bSpatrick "Invalid addr,length pair in qMemTags packet");
3764be691f3bSpatrick
3765be691f3bSpatrick if (packet.GetBytesLeft() < 1)
3766be691f3bSpatrick return SendIllFormedResponse(
3767be691f3bSpatrick packet, "Too short qMemtags: packet (looking for length)");
3768be691f3bSpatrick const size_t length = packet.GetHexMaxU64(/*little_endian=*/false, 0);
3769be691f3bSpatrick
3770be691f3bSpatrick // Type
3771be691f3bSpatrick const char *invalid_type_err = "Invalid type field in qMemTags: packet";
3772be691f3bSpatrick if (packet.GetBytesLeft() < 1 || packet.GetChar() != ':')
3773be691f3bSpatrick return SendIllFormedResponse(packet, invalid_type_err);
3774be691f3bSpatrick
3775be691f3bSpatrick // Type is a signed integer but packed into the packet as its raw bytes.
3776be691f3bSpatrick // However, our GetU64 uses strtoull which allows +/-. We do not want this.
3777be691f3bSpatrick const char *first_type_char = packet.Peek();
3778be691f3bSpatrick if (first_type_char && (*first_type_char == '+' || *first_type_char == '-'))
3779be691f3bSpatrick return SendIllFormedResponse(packet, invalid_type_err);
3780be691f3bSpatrick
3781be691f3bSpatrick // Extract type as unsigned then cast to signed.
3782be691f3bSpatrick // Using a uint64_t here so that we have some value outside of the 32 bit
3783be691f3bSpatrick // range to use as the invalid return value.
3784be691f3bSpatrick uint64_t raw_type =
3785be691f3bSpatrick packet.GetU64(std::numeric_limits<uint64_t>::max(), /*base=*/16);
3786be691f3bSpatrick
3787be691f3bSpatrick if ( // Make sure the cast below would be valid
3788be691f3bSpatrick raw_type > std::numeric_limits<uint32_t>::max() ||
3789be691f3bSpatrick // To catch inputs like "123aardvark" that will parse but clearly aren't
3790be691f3bSpatrick // valid in this case.
3791be691f3bSpatrick packet.GetBytesLeft()) {
3792be691f3bSpatrick return SendIllFormedResponse(packet, invalid_type_err);
3793be691f3bSpatrick }
3794be691f3bSpatrick
3795be691f3bSpatrick // First narrow to 32 bits otherwise the copy into type would take
3796be691f3bSpatrick // the wrong 4 bytes on big endian.
3797be691f3bSpatrick uint32_t raw_type_32 = raw_type;
3798be691f3bSpatrick int32_t type = reinterpret_cast<int32_t &>(raw_type_32);
3799be691f3bSpatrick
3800be691f3bSpatrick StreamGDBRemote response;
3801be691f3bSpatrick std::vector<uint8_t> tags;
3802be691f3bSpatrick Status error = m_current_process->ReadMemoryTags(type, addr, length, tags);
3803be691f3bSpatrick if (error.Fail())
3804be691f3bSpatrick return SendErrorResponse(1);
3805be691f3bSpatrick
3806be691f3bSpatrick // This m is here in case we want to support multi part replies in the future.
3807be691f3bSpatrick // In the same manner as qfThreadInfo/qsThreadInfo.
3808be691f3bSpatrick response.PutChar('m');
3809be691f3bSpatrick response.PutBytesAsRawHex8(tags.data(), tags.size());
3810be691f3bSpatrick return SendPacketNoLock(response.GetString());
3811be691f3bSpatrick }
3812be691f3bSpatrick
3813be691f3bSpatrick GDBRemoteCommunication::PacketResult
Handle_QMemTags(StringExtractorGDBRemote & packet)3814be691f3bSpatrick GDBRemoteCommunicationServerLLGS::Handle_QMemTags(
3815be691f3bSpatrick StringExtractorGDBRemote &packet) {
3816*f6aab3d8Srobert Log *log = GetLog(LLDBLog::Process);
3817be691f3bSpatrick
3818be691f3bSpatrick // Ensure we have a process.
3819be691f3bSpatrick if (!m_current_process ||
3820be691f3bSpatrick (m_current_process->GetID() == LLDB_INVALID_PROCESS_ID)) {
3821be691f3bSpatrick LLDB_LOGF(
3822be691f3bSpatrick log,
3823be691f3bSpatrick "GDBRemoteCommunicationServerLLGS::%s failed, no process available",
3824be691f3bSpatrick __FUNCTION__);
3825be691f3bSpatrick return SendErrorResponse(1);
3826be691f3bSpatrick }
3827be691f3bSpatrick
3828be691f3bSpatrick // We are expecting
3829be691f3bSpatrick // QMemTags:<hex address>,<hex length>:<hex type>:<tags as hex bytes>
3830be691f3bSpatrick
3831be691f3bSpatrick // Address
3832be691f3bSpatrick packet.SetFilePos(strlen("QMemTags:"));
3833be691f3bSpatrick const char *current_char = packet.Peek();
3834be691f3bSpatrick if (!current_char || *current_char == ',')
3835be691f3bSpatrick return SendIllFormedResponse(packet, "Missing address in QMemTags packet");
3836be691f3bSpatrick const lldb::addr_t addr = packet.GetHexMaxU64(/*little_endian=*/false, 0);
3837be691f3bSpatrick
3838be691f3bSpatrick // Length
3839be691f3bSpatrick char previous_char = packet.GetChar();
3840be691f3bSpatrick current_char = packet.Peek();
3841be691f3bSpatrick // If we don't have a separator or the length field is empty
3842be691f3bSpatrick if (previous_char != ',' || (current_char && *current_char == ':'))
3843be691f3bSpatrick return SendIllFormedResponse(packet,
3844be691f3bSpatrick "Invalid addr,length pair in QMemTags packet");
3845be691f3bSpatrick
3846be691f3bSpatrick if (packet.GetBytesLeft() < 1)
3847be691f3bSpatrick return SendIllFormedResponse(
3848be691f3bSpatrick packet, "Too short QMemtags: packet (looking for length)");
3849be691f3bSpatrick const size_t length = packet.GetHexMaxU64(/*little_endian=*/false, 0);
3850be691f3bSpatrick
3851be691f3bSpatrick // Type
3852be691f3bSpatrick const char *invalid_type_err = "Invalid type field in QMemTags: packet";
3853be691f3bSpatrick if (packet.GetBytesLeft() < 1 || packet.GetChar() != ':')
3854be691f3bSpatrick return SendIllFormedResponse(packet, invalid_type_err);
3855be691f3bSpatrick
3856be691f3bSpatrick // Our GetU64 uses strtoull which allows leading +/-, we don't want that.
3857be691f3bSpatrick const char *first_type_char = packet.Peek();
3858be691f3bSpatrick if (first_type_char && (*first_type_char == '+' || *first_type_char == '-'))
3859be691f3bSpatrick return SendIllFormedResponse(packet, invalid_type_err);
3860be691f3bSpatrick
3861be691f3bSpatrick // The type is a signed integer but is in the packet as its raw bytes.
3862be691f3bSpatrick // So parse first as unsigned then cast to signed later.
3863be691f3bSpatrick // We extract to 64 bit, even though we only expect 32, so that we've
3864be691f3bSpatrick // got some invalid value we can check for.
3865be691f3bSpatrick uint64_t raw_type =
3866be691f3bSpatrick packet.GetU64(std::numeric_limits<uint64_t>::max(), /*base=*/16);
3867be691f3bSpatrick if (raw_type > std::numeric_limits<uint32_t>::max())
3868be691f3bSpatrick return SendIllFormedResponse(packet, invalid_type_err);
3869be691f3bSpatrick
3870be691f3bSpatrick // First narrow to 32 bits. Otherwise the copy below would get the wrong
3871be691f3bSpatrick // 4 bytes on big endian.
3872be691f3bSpatrick uint32_t raw_type_32 = raw_type;
3873be691f3bSpatrick int32_t type = reinterpret_cast<int32_t &>(raw_type_32);
3874be691f3bSpatrick
3875be691f3bSpatrick // Tag data
3876be691f3bSpatrick if (packet.GetBytesLeft() < 1 || packet.GetChar() != ':')
3877be691f3bSpatrick return SendIllFormedResponse(packet,
3878be691f3bSpatrick "Missing tag data in QMemTags: packet");
3879be691f3bSpatrick
3880be691f3bSpatrick // Must be 2 chars per byte
3881be691f3bSpatrick const char *invalid_data_err = "Invalid tag data in QMemTags: packet";
3882be691f3bSpatrick if (packet.GetBytesLeft() % 2)
3883be691f3bSpatrick return SendIllFormedResponse(packet, invalid_data_err);
3884be691f3bSpatrick
3885be691f3bSpatrick // This is bytes here and is unpacked into target specific tags later
3886be691f3bSpatrick // We cannot assume that number of bytes == length here because the server
3887be691f3bSpatrick // can repeat tags to fill a given range.
3888be691f3bSpatrick std::vector<uint8_t> tag_data;
3889be691f3bSpatrick // Zero length writes will not have any tag data
3890be691f3bSpatrick // (but we pass them on because it will still check that tagging is enabled)
3891be691f3bSpatrick if (packet.GetBytesLeft()) {
3892be691f3bSpatrick size_t byte_count = packet.GetBytesLeft() / 2;
3893be691f3bSpatrick tag_data.resize(byte_count);
3894be691f3bSpatrick size_t converted_bytes = packet.GetHexBytes(tag_data, 0);
3895be691f3bSpatrick if (converted_bytes != byte_count) {
3896be691f3bSpatrick return SendIllFormedResponse(packet, invalid_data_err);
3897be691f3bSpatrick }
3898be691f3bSpatrick }
3899be691f3bSpatrick
3900be691f3bSpatrick Status status =
3901be691f3bSpatrick m_current_process->WriteMemoryTags(type, addr, length, tag_data);
3902be691f3bSpatrick return status.Success() ? SendOKResponse() : SendErrorResponse(1);
3903be691f3bSpatrick }
3904be691f3bSpatrick
3905*f6aab3d8Srobert GDBRemoteCommunication::PacketResult
Handle_qSaveCore(StringExtractorGDBRemote & packet)3906*f6aab3d8Srobert GDBRemoteCommunicationServerLLGS::Handle_qSaveCore(
3907*f6aab3d8Srobert StringExtractorGDBRemote &packet) {
3908*f6aab3d8Srobert // Fail if we don't have a current process.
3909*f6aab3d8Srobert if (!m_current_process ||
3910*f6aab3d8Srobert (m_current_process->GetID() == LLDB_INVALID_PROCESS_ID))
3911*f6aab3d8Srobert return SendErrorResponse(Status("Process not running."));
3912*f6aab3d8Srobert
3913*f6aab3d8Srobert std::string path_hint;
3914*f6aab3d8Srobert
3915*f6aab3d8Srobert StringRef packet_str{packet.GetStringRef()};
3916*f6aab3d8Srobert assert(packet_str.startswith("qSaveCore"));
3917*f6aab3d8Srobert if (packet_str.consume_front("qSaveCore;")) {
3918*f6aab3d8Srobert for (auto x : llvm::split(packet_str, ';')) {
3919*f6aab3d8Srobert if (x.consume_front("path-hint:"))
3920*f6aab3d8Srobert StringExtractor(x).GetHexByteString(path_hint);
3921*f6aab3d8Srobert else
3922*f6aab3d8Srobert return SendErrorResponse(Status("Unsupported qSaveCore option"));
3923*f6aab3d8Srobert }
3924*f6aab3d8Srobert }
3925*f6aab3d8Srobert
3926*f6aab3d8Srobert llvm::Expected<std::string> ret = m_current_process->SaveCore(path_hint);
3927*f6aab3d8Srobert if (!ret)
3928*f6aab3d8Srobert return SendErrorResponse(ret.takeError());
3929*f6aab3d8Srobert
3930*f6aab3d8Srobert StreamString response;
3931*f6aab3d8Srobert response.PutCString("core-path:");
3932*f6aab3d8Srobert response.PutStringAsRawHex8(ret.get());
3933*f6aab3d8Srobert return SendPacketNoLock(response.GetString());
3934*f6aab3d8Srobert }
3935*f6aab3d8Srobert
3936*f6aab3d8Srobert GDBRemoteCommunication::PacketResult
Handle_QNonStop(StringExtractorGDBRemote & packet)3937*f6aab3d8Srobert GDBRemoteCommunicationServerLLGS::Handle_QNonStop(
3938*f6aab3d8Srobert StringExtractorGDBRemote &packet) {
3939*f6aab3d8Srobert Log *log = GetLog(LLDBLog::Process);
3940*f6aab3d8Srobert
3941*f6aab3d8Srobert StringRef packet_str{packet.GetStringRef()};
3942*f6aab3d8Srobert assert(packet_str.startswith("QNonStop:"));
3943*f6aab3d8Srobert packet_str.consume_front("QNonStop:");
3944*f6aab3d8Srobert if (packet_str == "0") {
3945*f6aab3d8Srobert if (m_non_stop)
3946*f6aab3d8Srobert StopSTDIOForwarding();
3947*f6aab3d8Srobert for (auto &process_it : m_debugged_processes) {
3948*f6aab3d8Srobert if (process_it.second.process_up->IsRunning()) {
3949*f6aab3d8Srobert assert(m_non_stop);
3950*f6aab3d8Srobert Status error = process_it.second.process_up->Interrupt();
3951*f6aab3d8Srobert if (error.Fail()) {
3952*f6aab3d8Srobert LLDB_LOG(log,
3953*f6aab3d8Srobert "while disabling nonstop, failed to halt process {0}: {1}",
3954*f6aab3d8Srobert process_it.first, error);
3955*f6aab3d8Srobert return SendErrorResponse(0x41);
3956*f6aab3d8Srobert }
3957*f6aab3d8Srobert // we must not send stop reasons after QNonStop
3958*f6aab3d8Srobert m_disabling_non_stop = true;
3959*f6aab3d8Srobert }
3960*f6aab3d8Srobert }
3961*f6aab3d8Srobert m_stdio_notification_queue.clear();
3962*f6aab3d8Srobert m_stop_notification_queue.clear();
3963*f6aab3d8Srobert m_non_stop = false;
3964*f6aab3d8Srobert // If we are stopping anything, defer sending the OK response until we're
3965*f6aab3d8Srobert // done.
3966*f6aab3d8Srobert if (m_disabling_non_stop)
3967*f6aab3d8Srobert return PacketResult::Success;
3968*f6aab3d8Srobert } else if (packet_str == "1") {
3969*f6aab3d8Srobert if (!m_non_stop)
3970*f6aab3d8Srobert StartSTDIOForwarding();
3971*f6aab3d8Srobert m_non_stop = true;
3972*f6aab3d8Srobert } else
3973*f6aab3d8Srobert return SendErrorResponse(Status("Invalid QNonStop packet"));
3974*f6aab3d8Srobert return SendOKResponse();
3975*f6aab3d8Srobert }
3976*f6aab3d8Srobert
3977*f6aab3d8Srobert GDBRemoteCommunication::PacketResult
HandleNotificationAck(std::deque<std::string> & queue)3978*f6aab3d8Srobert GDBRemoteCommunicationServerLLGS::HandleNotificationAck(
3979*f6aab3d8Srobert std::deque<std::string> &queue) {
3980*f6aab3d8Srobert // Per the protocol, the first message put into the queue is sent
3981*f6aab3d8Srobert // immediately. However, it remains the queue until the client ACKs it --
3982*f6aab3d8Srobert // then we pop it and send the next message. The process repeats until
3983*f6aab3d8Srobert // the last message in the queue is ACK-ed, in which case the packet sends
3984*f6aab3d8Srobert // an OK response.
3985*f6aab3d8Srobert if (queue.empty())
3986*f6aab3d8Srobert return SendErrorResponse(Status("No pending notification to ack"));
3987*f6aab3d8Srobert queue.pop_front();
3988*f6aab3d8Srobert if (!queue.empty())
3989*f6aab3d8Srobert return SendPacketNoLock(queue.front());
3990*f6aab3d8Srobert return SendOKResponse();
3991*f6aab3d8Srobert }
3992*f6aab3d8Srobert
3993*f6aab3d8Srobert GDBRemoteCommunication::PacketResult
Handle_vStdio(StringExtractorGDBRemote & packet)3994*f6aab3d8Srobert GDBRemoteCommunicationServerLLGS::Handle_vStdio(
3995*f6aab3d8Srobert StringExtractorGDBRemote &packet) {
3996*f6aab3d8Srobert return HandleNotificationAck(m_stdio_notification_queue);
3997*f6aab3d8Srobert }
3998*f6aab3d8Srobert
3999*f6aab3d8Srobert GDBRemoteCommunication::PacketResult
Handle_vStopped(StringExtractorGDBRemote & packet)4000*f6aab3d8Srobert GDBRemoteCommunicationServerLLGS::Handle_vStopped(
4001*f6aab3d8Srobert StringExtractorGDBRemote &packet) {
4002*f6aab3d8Srobert PacketResult ret = HandleNotificationAck(m_stop_notification_queue);
4003*f6aab3d8Srobert // If this was the last notification and all the processes exited,
4004*f6aab3d8Srobert // terminate the server.
4005*f6aab3d8Srobert if (m_stop_notification_queue.empty() && m_debugged_processes.empty()) {
4006*f6aab3d8Srobert m_exit_now = true;
4007*f6aab3d8Srobert m_mainloop.RequestTermination();
4008*f6aab3d8Srobert }
4009*f6aab3d8Srobert return ret;
4010*f6aab3d8Srobert }
4011*f6aab3d8Srobert
4012*f6aab3d8Srobert GDBRemoteCommunication::PacketResult
Handle_vCtrlC(StringExtractorGDBRemote & packet)4013*f6aab3d8Srobert GDBRemoteCommunicationServerLLGS::Handle_vCtrlC(
4014*f6aab3d8Srobert StringExtractorGDBRemote &packet) {
4015*f6aab3d8Srobert if (!m_non_stop)
4016*f6aab3d8Srobert return SendErrorResponse(Status("vCtrl is only valid in non-stop mode"));
4017*f6aab3d8Srobert
4018*f6aab3d8Srobert PacketResult interrupt_res = Handle_interrupt(packet);
4019*f6aab3d8Srobert // If interrupting the process failed, pass the result through.
4020*f6aab3d8Srobert if (interrupt_res != PacketResult::Success)
4021*f6aab3d8Srobert return interrupt_res;
4022*f6aab3d8Srobert // Otherwise, vCtrlC should issue an OK response (normal interrupts do not).
4023*f6aab3d8Srobert return SendOKResponse();
4024*f6aab3d8Srobert }
4025*f6aab3d8Srobert
4026*f6aab3d8Srobert GDBRemoteCommunication::PacketResult
Handle_T(StringExtractorGDBRemote & packet)4027*f6aab3d8Srobert GDBRemoteCommunicationServerLLGS::Handle_T(StringExtractorGDBRemote &packet) {
4028*f6aab3d8Srobert packet.SetFilePos(strlen("T"));
4029*f6aab3d8Srobert auto pid_tid = packet.GetPidTid(m_current_process ? m_current_process->GetID()
4030*f6aab3d8Srobert : LLDB_INVALID_PROCESS_ID);
4031*f6aab3d8Srobert if (!pid_tid)
4032*f6aab3d8Srobert return SendErrorResponse(llvm::make_error<StringError>(
4033*f6aab3d8Srobert inconvertibleErrorCode(), "Malformed thread-id"));
4034*f6aab3d8Srobert
4035*f6aab3d8Srobert lldb::pid_t pid = pid_tid->first;
4036*f6aab3d8Srobert lldb::tid_t tid = pid_tid->second;
4037*f6aab3d8Srobert
4038*f6aab3d8Srobert // Technically, this would also be caught by the PID check but let's be more
4039*f6aab3d8Srobert // explicit about the error.
4040*f6aab3d8Srobert if (pid == LLDB_INVALID_PROCESS_ID)
4041*f6aab3d8Srobert return SendErrorResponse(llvm::make_error<StringError>(
4042*f6aab3d8Srobert inconvertibleErrorCode(), "No current process and no PID provided"));
4043*f6aab3d8Srobert
4044*f6aab3d8Srobert // Check the process ID and find respective process instance.
4045*f6aab3d8Srobert auto new_process_it = m_debugged_processes.find(pid);
4046*f6aab3d8Srobert if (new_process_it == m_debugged_processes.end())
4047*f6aab3d8Srobert return SendErrorResponse(1);
4048*f6aab3d8Srobert
4049*f6aab3d8Srobert // Check the thread ID
4050*f6aab3d8Srobert if (!new_process_it->second.process_up->GetThreadByID(tid))
4051*f6aab3d8Srobert return SendErrorResponse(2);
4052*f6aab3d8Srobert
4053*f6aab3d8Srobert return SendOKResponse();
4054*f6aab3d8Srobert }
4055*f6aab3d8Srobert
MaybeCloseInferiorTerminalConnection()4056061da546Spatrick void GDBRemoteCommunicationServerLLGS::MaybeCloseInferiorTerminalConnection() {
4057*f6aab3d8Srobert Log *log = GetLog(LLDBLog::Process);
4058061da546Spatrick
4059061da546Spatrick // Tell the stdio connection to shut down.
4060061da546Spatrick if (m_stdio_communication.IsConnected()) {
4061061da546Spatrick auto connection = m_stdio_communication.GetConnection();
4062061da546Spatrick if (connection) {
4063061da546Spatrick Status error;
4064061da546Spatrick connection->Disconnect(&error);
4065061da546Spatrick
4066061da546Spatrick if (error.Success()) {
4067061da546Spatrick LLDB_LOGF(log,
4068061da546Spatrick "GDBRemoteCommunicationServerLLGS::%s disconnect process "
4069061da546Spatrick "terminal stdio - SUCCESS",
4070061da546Spatrick __FUNCTION__);
4071061da546Spatrick } else {
4072061da546Spatrick LLDB_LOGF(log,
4073061da546Spatrick "GDBRemoteCommunicationServerLLGS::%s disconnect process "
4074061da546Spatrick "terminal stdio - FAIL: %s",
4075061da546Spatrick __FUNCTION__, error.AsCString());
4076061da546Spatrick }
4077061da546Spatrick }
4078061da546Spatrick }
4079061da546Spatrick }
4080061da546Spatrick
GetThreadFromSuffix(StringExtractorGDBRemote & packet)4081061da546Spatrick NativeThreadProtocol *GDBRemoteCommunicationServerLLGS::GetThreadFromSuffix(
4082061da546Spatrick StringExtractorGDBRemote &packet) {
4083061da546Spatrick // We have no thread if we don't have a process.
4084be691f3bSpatrick if (!m_current_process ||
4085be691f3bSpatrick m_current_process->GetID() == LLDB_INVALID_PROCESS_ID)
4086061da546Spatrick return nullptr;
4087061da546Spatrick
4088061da546Spatrick // If the client hasn't asked for thread suffix support, there will not be a
4089061da546Spatrick // thread suffix. Use the current thread in that case.
4090061da546Spatrick if (!m_thread_suffix_supported) {
4091061da546Spatrick const lldb::tid_t current_tid = GetCurrentThreadID();
4092061da546Spatrick if (current_tid == LLDB_INVALID_THREAD_ID)
4093061da546Spatrick return nullptr;
4094061da546Spatrick else if (current_tid == 0) {
4095061da546Spatrick // Pick a thread.
4096be691f3bSpatrick return m_current_process->GetThreadAtIndex(0);
4097061da546Spatrick } else
4098be691f3bSpatrick return m_current_process->GetThreadByID(current_tid);
4099061da546Spatrick }
4100061da546Spatrick
4101*f6aab3d8Srobert Log *log = GetLog(LLDBLog::Thread);
4102061da546Spatrick
4103061da546Spatrick // Parse out the ';'.
4104061da546Spatrick if (packet.GetBytesLeft() < 1 || packet.GetChar() != ';') {
4105061da546Spatrick LLDB_LOGF(log,
4106061da546Spatrick "GDBRemoteCommunicationServerLLGS::%s gdb-remote parse "
4107061da546Spatrick "error: expected ';' prior to start of thread suffix: packet "
4108061da546Spatrick "contents = '%s'",
4109061da546Spatrick __FUNCTION__, packet.GetStringRef().data());
4110061da546Spatrick return nullptr;
4111061da546Spatrick }
4112061da546Spatrick
4113061da546Spatrick if (!packet.GetBytesLeft())
4114061da546Spatrick return nullptr;
4115061da546Spatrick
4116061da546Spatrick // Parse out thread: portion.
4117061da546Spatrick if (strncmp(packet.Peek(), "thread:", strlen("thread:")) != 0) {
4118061da546Spatrick LLDB_LOGF(log,
4119061da546Spatrick "GDBRemoteCommunicationServerLLGS::%s gdb-remote parse "
4120061da546Spatrick "error: expected 'thread:' but not found, packet contents = "
4121061da546Spatrick "'%s'",
4122061da546Spatrick __FUNCTION__, packet.GetStringRef().data());
4123061da546Spatrick return nullptr;
4124061da546Spatrick }
4125061da546Spatrick packet.SetFilePos(packet.GetFilePos() + strlen("thread:"));
4126061da546Spatrick const lldb::tid_t tid = packet.GetHexMaxU64(false, 0);
4127061da546Spatrick if (tid != 0)
4128be691f3bSpatrick return m_current_process->GetThreadByID(tid);
4129061da546Spatrick
4130061da546Spatrick return nullptr;
4131061da546Spatrick }
4132061da546Spatrick
GetCurrentThreadID() const4133061da546Spatrick lldb::tid_t GDBRemoteCommunicationServerLLGS::GetCurrentThreadID() const {
4134061da546Spatrick if (m_current_tid == 0 || m_current_tid == LLDB_INVALID_THREAD_ID) {
4135061da546Spatrick // Use whatever the debug process says is the current thread id since the
4136061da546Spatrick // protocol either didn't specify or specified we want any/all threads
4137061da546Spatrick // marked as the current thread.
4138be691f3bSpatrick if (!m_current_process)
4139061da546Spatrick return LLDB_INVALID_THREAD_ID;
4140be691f3bSpatrick return m_current_process->GetCurrentThreadID();
4141061da546Spatrick }
4142061da546Spatrick // Use the specific current thread id set by the gdb remote protocol.
4143061da546Spatrick return m_current_tid;
4144061da546Spatrick }
4145061da546Spatrick
GetNextSavedRegistersID()4146061da546Spatrick uint32_t GDBRemoteCommunicationServerLLGS::GetNextSavedRegistersID() {
4147061da546Spatrick std::lock_guard<std::mutex> guard(m_saved_registers_mutex);
4148061da546Spatrick return m_next_saved_registers_id++;
4149061da546Spatrick }
4150061da546Spatrick
ClearProcessSpecificData()4151061da546Spatrick void GDBRemoteCommunicationServerLLGS::ClearProcessSpecificData() {
4152*f6aab3d8Srobert Log *log = GetLog(LLDBLog::Process);
4153061da546Spatrick
4154061da546Spatrick LLDB_LOG(log, "clearing {0} xfer buffers", m_xfer_buffer_map.size());
4155061da546Spatrick m_xfer_buffer_map.clear();
4156061da546Spatrick }
4157061da546Spatrick
4158061da546Spatrick FileSpec
FindModuleFile(const std::string & module_path,const ArchSpec & arch)4159061da546Spatrick GDBRemoteCommunicationServerLLGS::FindModuleFile(const std::string &module_path,
4160061da546Spatrick const ArchSpec &arch) {
4161be691f3bSpatrick if (m_current_process) {
4162061da546Spatrick FileSpec file_spec;
4163be691f3bSpatrick if (m_current_process
4164061da546Spatrick ->GetLoadedModuleFileSpec(module_path.c_str(), file_spec)
4165061da546Spatrick .Success()) {
4166061da546Spatrick if (FileSystem::Instance().Exists(file_spec))
4167061da546Spatrick return file_spec;
4168061da546Spatrick }
4169061da546Spatrick }
4170061da546Spatrick
4171061da546Spatrick return GDBRemoteCommunicationServerCommon::FindModuleFile(module_path, arch);
4172061da546Spatrick }
4173061da546Spatrick
XMLEncodeAttributeValue(llvm::StringRef value)4174061da546Spatrick std::string GDBRemoteCommunicationServerLLGS::XMLEncodeAttributeValue(
4175061da546Spatrick llvm::StringRef value) {
4176061da546Spatrick std::string result;
4177061da546Spatrick for (const char &c : value) {
4178061da546Spatrick switch (c) {
4179061da546Spatrick case '\'':
4180061da546Spatrick result += "'";
4181061da546Spatrick break;
4182061da546Spatrick case '"':
4183061da546Spatrick result += """;
4184061da546Spatrick break;
4185061da546Spatrick case '<':
4186061da546Spatrick result += "<";
4187061da546Spatrick break;
4188061da546Spatrick case '>':
4189061da546Spatrick result += ">";
4190061da546Spatrick break;
4191061da546Spatrick default:
4192061da546Spatrick result += c;
4193061da546Spatrick break;
4194061da546Spatrick }
4195061da546Spatrick }
4196061da546Spatrick return result;
4197061da546Spatrick }
4198be691f3bSpatrick
HandleFeatures(const llvm::ArrayRef<llvm::StringRef> client_features)4199be691f3bSpatrick std::vector<std::string> GDBRemoteCommunicationServerLLGS::HandleFeatures(
4200be691f3bSpatrick const llvm::ArrayRef<llvm::StringRef> client_features) {
4201be691f3bSpatrick std::vector<std::string> ret =
4202be691f3bSpatrick GDBRemoteCommunicationServerCommon::HandleFeatures(client_features);
4203be691f3bSpatrick ret.insert(ret.end(), {
4204be691f3bSpatrick "QThreadSuffixSupported+",
4205be691f3bSpatrick "QListThreadsInStopReply+",
4206be691f3bSpatrick "qXfer:features:read+",
4207*f6aab3d8Srobert "QNonStop+",
4208be691f3bSpatrick });
4209be691f3bSpatrick
4210be691f3bSpatrick // report server-only features
4211be691f3bSpatrick using Extension = NativeProcessProtocol::Extension;
4212be691f3bSpatrick Extension plugin_features = m_process_factory.GetSupportedExtensions();
4213be691f3bSpatrick if (bool(plugin_features & Extension::pass_signals))
4214be691f3bSpatrick ret.push_back("QPassSignals+");
4215be691f3bSpatrick if (bool(plugin_features & Extension::auxv))
4216be691f3bSpatrick ret.push_back("qXfer:auxv:read+");
4217be691f3bSpatrick if (bool(plugin_features & Extension::libraries_svr4))
4218be691f3bSpatrick ret.push_back("qXfer:libraries-svr4:read+");
4219*f6aab3d8Srobert if (bool(plugin_features & Extension::siginfo_read))
4220*f6aab3d8Srobert ret.push_back("qXfer:siginfo:read+");
4221be691f3bSpatrick if (bool(plugin_features & Extension::memory_tagging))
4222be691f3bSpatrick ret.push_back("memory-tagging+");
4223*f6aab3d8Srobert if (bool(plugin_features & Extension::savecore))
4224*f6aab3d8Srobert ret.push_back("qSaveCore+");
4225be691f3bSpatrick
4226be691f3bSpatrick // check for client features
4227be691f3bSpatrick m_extensions_supported = {};
4228be691f3bSpatrick for (llvm::StringRef x : client_features)
4229be691f3bSpatrick m_extensions_supported |=
4230be691f3bSpatrick llvm::StringSwitch<Extension>(x)
4231be691f3bSpatrick .Case("multiprocess+", Extension::multiprocess)
4232be691f3bSpatrick .Case("fork-events+", Extension::fork)
4233be691f3bSpatrick .Case("vfork-events+", Extension::vfork)
4234be691f3bSpatrick .Default({});
4235be691f3bSpatrick
4236be691f3bSpatrick m_extensions_supported &= plugin_features;
4237be691f3bSpatrick
4238be691f3bSpatrick // fork & vfork require multiprocess
4239be691f3bSpatrick if (!bool(m_extensions_supported & Extension::multiprocess))
4240be691f3bSpatrick m_extensions_supported &= ~(Extension::fork | Extension::vfork);
4241be691f3bSpatrick
4242be691f3bSpatrick // report only if actually supported
4243be691f3bSpatrick if (bool(m_extensions_supported & Extension::multiprocess))
4244be691f3bSpatrick ret.push_back("multiprocess+");
4245be691f3bSpatrick if (bool(m_extensions_supported & Extension::fork))
4246be691f3bSpatrick ret.push_back("fork-events+");
4247be691f3bSpatrick if (bool(m_extensions_supported & Extension::vfork))
4248be691f3bSpatrick ret.push_back("vfork-events+");
4249be691f3bSpatrick
4250be691f3bSpatrick for (auto &x : m_debugged_processes)
4251*f6aab3d8Srobert SetEnabledExtensions(*x.second.process_up);
4252be691f3bSpatrick return ret;
4253be691f3bSpatrick }
4254be691f3bSpatrick
SetEnabledExtensions(NativeProcessProtocol & process)4255be691f3bSpatrick void GDBRemoteCommunicationServerLLGS::SetEnabledExtensions(
4256be691f3bSpatrick NativeProcessProtocol &process) {
4257be691f3bSpatrick NativeProcessProtocol::Extension flags = m_extensions_supported;
4258be691f3bSpatrick assert(!bool(flags & ~m_process_factory.GetSupportedExtensions()));
4259be691f3bSpatrick process.SetEnabledExtensions(flags);
4260be691f3bSpatrick }
4261*f6aab3d8Srobert
4262*f6aab3d8Srobert GDBRemoteCommunication::PacketResult
SendContinueSuccessResponse()4263*f6aab3d8Srobert GDBRemoteCommunicationServerLLGS::SendContinueSuccessResponse() {
4264*f6aab3d8Srobert if (m_non_stop)
4265*f6aab3d8Srobert return SendOKResponse();
4266*f6aab3d8Srobert StartSTDIOForwarding();
4267*f6aab3d8Srobert return PacketResult::Success;
4268*f6aab3d8Srobert }
4269*f6aab3d8Srobert
AppendThreadIDToResponse(Stream & response,lldb::pid_t pid,lldb::tid_t tid)4270*f6aab3d8Srobert void GDBRemoteCommunicationServerLLGS::AppendThreadIDToResponse(
4271*f6aab3d8Srobert Stream &response, lldb::pid_t pid, lldb::tid_t tid) {
4272*f6aab3d8Srobert if (bool(m_extensions_supported &
4273*f6aab3d8Srobert NativeProcessProtocol::Extension::multiprocess))
4274*f6aab3d8Srobert response.Format("p{0:x-}.", pid);
4275*f6aab3d8Srobert response.Format("{0:x-}", tid);
4276*f6aab3d8Srobert }
4277*f6aab3d8Srobert
4278*f6aab3d8Srobert std::string
LLGSArgToURL(llvm::StringRef url_arg,bool reverse_connect)4279*f6aab3d8Srobert lldb_private::process_gdb_remote::LLGSArgToURL(llvm::StringRef url_arg,
4280*f6aab3d8Srobert bool reverse_connect) {
4281*f6aab3d8Srobert // Try parsing the argument as URL.
4282*f6aab3d8Srobert if (std::optional<URI> url = URI::Parse(url_arg)) {
4283*f6aab3d8Srobert if (reverse_connect)
4284*f6aab3d8Srobert return url_arg.str();
4285*f6aab3d8Srobert
4286*f6aab3d8Srobert // Translate the scheme from LLGS notation to ConnectionFileDescriptor.
4287*f6aab3d8Srobert // If the scheme doesn't match any, pass it through to support using CFD
4288*f6aab3d8Srobert // schemes directly.
4289*f6aab3d8Srobert std::string new_url = llvm::StringSwitch<std::string>(url->scheme)
4290*f6aab3d8Srobert .Case("tcp", "listen")
4291*f6aab3d8Srobert .Case("unix", "unix-accept")
4292*f6aab3d8Srobert .Case("unix-abstract", "unix-abstract-accept")
4293*f6aab3d8Srobert .Default(url->scheme.str());
4294*f6aab3d8Srobert llvm::append_range(new_url, url_arg.substr(url->scheme.size()));
4295*f6aab3d8Srobert return new_url;
4296*f6aab3d8Srobert }
4297*f6aab3d8Srobert
4298*f6aab3d8Srobert std::string host_port = url_arg.str();
4299*f6aab3d8Srobert // If host_and_port starts with ':', default the host to be "localhost" and
4300*f6aab3d8Srobert // expect the remainder to be the port.
4301*f6aab3d8Srobert if (url_arg.startswith(":"))
4302*f6aab3d8Srobert host_port.insert(0, "localhost");
4303*f6aab3d8Srobert
4304*f6aab3d8Srobert // Try parsing the (preprocessed) argument as host:port pair.
4305*f6aab3d8Srobert if (!llvm::errorToBool(Socket::DecodeHostAndPort(host_port).takeError()))
4306*f6aab3d8Srobert return (reverse_connect ? "connect://" : "listen://") + host_port;
4307*f6aab3d8Srobert
4308*f6aab3d8Srobert // If none of the above applied, interpret the argument as UNIX socket path.
4309*f6aab3d8Srobert return (reverse_connect ? "unix-connect://" : "unix-accept://") +
4310*f6aab3d8Srobert url_arg.str();
4311*f6aab3d8Srobert }
4312