xref: /openbsd-src/gnu/llvm/lldb/source/Plugins/Process/gdb-remote/GDBRemoteCommunicationServerLLGS.cpp (revision 061da546b983eb767bad15e67af1174fb0bcf31c)
1*061da546Spatrick //===-- GDBRemoteCommunicationServerLLGS.cpp --------------------*- C++ -*-===//
2*061da546Spatrick //
3*061da546Spatrick // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4*061da546Spatrick // See https://llvm.org/LICENSE.txt for license information.
5*061da546Spatrick // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6*061da546Spatrick //
7*061da546Spatrick //===----------------------------------------------------------------------===//
8*061da546Spatrick 
9*061da546Spatrick #include <errno.h>
10*061da546Spatrick 
11*061da546Spatrick #include "lldb/Host/Config.h"
12*061da546Spatrick 
13*061da546Spatrick #include "GDBRemoteCommunicationServerLLGS.h"
14*061da546Spatrick #include "lldb/Utility/GDBRemote.h"
15*061da546Spatrick 
16*061da546Spatrick #include <chrono>
17*061da546Spatrick #include <cstring>
18*061da546Spatrick #include <thread>
19*061da546Spatrick 
20*061da546Spatrick #include "lldb/Host/ConnectionFileDescriptor.h"
21*061da546Spatrick #include "lldb/Host/Debug.h"
22*061da546Spatrick #include "lldb/Host/File.h"
23*061da546Spatrick #include "lldb/Host/FileAction.h"
24*061da546Spatrick #include "lldb/Host/FileSystem.h"
25*061da546Spatrick #include "lldb/Host/Host.h"
26*061da546Spatrick #include "lldb/Host/HostInfo.h"
27*061da546Spatrick #include "lldb/Host/PosixApi.h"
28*061da546Spatrick #include "lldb/Host/common/NativeProcessProtocol.h"
29*061da546Spatrick #include "lldb/Host/common/NativeRegisterContext.h"
30*061da546Spatrick #include "lldb/Host/common/NativeThreadProtocol.h"
31*061da546Spatrick #include "lldb/Target/MemoryRegionInfo.h"
32*061da546Spatrick #include "lldb/Utility/Args.h"
33*061da546Spatrick #include "lldb/Utility/DataBuffer.h"
34*061da546Spatrick #include "lldb/Utility/Endian.h"
35*061da546Spatrick #include "lldb/Utility/LLDBAssert.h"
36*061da546Spatrick #include "lldb/Utility/Log.h"
37*061da546Spatrick #include "lldb/Utility/RegisterValue.h"
38*061da546Spatrick #include "lldb/Utility/State.h"
39*061da546Spatrick #include "lldb/Utility/StreamString.h"
40*061da546Spatrick #include "lldb/Utility/UriParser.h"
41*061da546Spatrick #include "llvm/ADT/Triple.h"
42*061da546Spatrick #include "llvm/Support/JSON.h"
43*061da546Spatrick #include "llvm/Support/ScopedPrinter.h"
44*061da546Spatrick 
45*061da546Spatrick #include "ProcessGDBRemote.h"
46*061da546Spatrick #include "ProcessGDBRemoteLog.h"
47*061da546Spatrick #include "lldb/Utility/StringExtractorGDBRemote.h"
48*061da546Spatrick 
49*061da546Spatrick using namespace lldb;
50*061da546Spatrick using namespace lldb_private;
51*061da546Spatrick using namespace lldb_private::process_gdb_remote;
52*061da546Spatrick using namespace llvm;
53*061da546Spatrick 
54*061da546Spatrick // GDBRemote Errors
55*061da546Spatrick 
56*061da546Spatrick namespace {
57*061da546Spatrick enum GDBRemoteServerError {
58*061da546Spatrick   // Set to the first unused error number in literal form below
59*061da546Spatrick   eErrorFirst = 29,
60*061da546Spatrick   eErrorNoProcess = eErrorFirst,
61*061da546Spatrick   eErrorResume,
62*061da546Spatrick   eErrorExitStatus
63*061da546Spatrick };
64*061da546Spatrick }
65*061da546Spatrick 
66*061da546Spatrick // GDBRemoteCommunicationServerLLGS constructor
67*061da546Spatrick GDBRemoteCommunicationServerLLGS::GDBRemoteCommunicationServerLLGS(
68*061da546Spatrick     MainLoop &mainloop, const NativeProcessProtocol::Factory &process_factory)
69*061da546Spatrick     : GDBRemoteCommunicationServerCommon("gdb-remote.server",
70*061da546Spatrick                                          "gdb-remote.server.rx_packet"),
71*061da546Spatrick       m_mainloop(mainloop), m_process_factory(process_factory),
72*061da546Spatrick       m_stdio_communication("process.stdio") {
73*061da546Spatrick   RegisterPacketHandlers();
74*061da546Spatrick }
75*061da546Spatrick 
76*061da546Spatrick void GDBRemoteCommunicationServerLLGS::RegisterPacketHandlers() {
77*061da546Spatrick   RegisterMemberFunctionHandler(StringExtractorGDBRemote::eServerPacketType_C,
78*061da546Spatrick                                 &GDBRemoteCommunicationServerLLGS::Handle_C);
79*061da546Spatrick   RegisterMemberFunctionHandler(StringExtractorGDBRemote::eServerPacketType_c,
80*061da546Spatrick                                 &GDBRemoteCommunicationServerLLGS::Handle_c);
81*061da546Spatrick   RegisterMemberFunctionHandler(StringExtractorGDBRemote::eServerPacketType_D,
82*061da546Spatrick                                 &GDBRemoteCommunicationServerLLGS::Handle_D);
83*061da546Spatrick   RegisterMemberFunctionHandler(StringExtractorGDBRemote::eServerPacketType_H,
84*061da546Spatrick                                 &GDBRemoteCommunicationServerLLGS::Handle_H);
85*061da546Spatrick   RegisterMemberFunctionHandler(StringExtractorGDBRemote::eServerPacketType_I,
86*061da546Spatrick                                 &GDBRemoteCommunicationServerLLGS::Handle_I);
87*061da546Spatrick   RegisterMemberFunctionHandler(
88*061da546Spatrick       StringExtractorGDBRemote::eServerPacketType_interrupt,
89*061da546Spatrick       &GDBRemoteCommunicationServerLLGS::Handle_interrupt);
90*061da546Spatrick   RegisterMemberFunctionHandler(
91*061da546Spatrick       StringExtractorGDBRemote::eServerPacketType_m,
92*061da546Spatrick       &GDBRemoteCommunicationServerLLGS::Handle_memory_read);
93*061da546Spatrick   RegisterMemberFunctionHandler(StringExtractorGDBRemote::eServerPacketType_M,
94*061da546Spatrick                                 &GDBRemoteCommunicationServerLLGS::Handle_M);
95*061da546Spatrick   RegisterMemberFunctionHandler(StringExtractorGDBRemote::eServerPacketType_p,
96*061da546Spatrick                                 &GDBRemoteCommunicationServerLLGS::Handle_p);
97*061da546Spatrick   RegisterMemberFunctionHandler(StringExtractorGDBRemote::eServerPacketType_P,
98*061da546Spatrick                                 &GDBRemoteCommunicationServerLLGS::Handle_P);
99*061da546Spatrick   RegisterMemberFunctionHandler(StringExtractorGDBRemote::eServerPacketType_qC,
100*061da546Spatrick                                 &GDBRemoteCommunicationServerLLGS::Handle_qC);
101*061da546Spatrick   RegisterMemberFunctionHandler(
102*061da546Spatrick       StringExtractorGDBRemote::eServerPacketType_qfThreadInfo,
103*061da546Spatrick       &GDBRemoteCommunicationServerLLGS::Handle_qfThreadInfo);
104*061da546Spatrick   RegisterMemberFunctionHandler(
105*061da546Spatrick       StringExtractorGDBRemote::eServerPacketType_qFileLoadAddress,
106*061da546Spatrick       &GDBRemoteCommunicationServerLLGS::Handle_qFileLoadAddress);
107*061da546Spatrick   RegisterMemberFunctionHandler(
108*061da546Spatrick       StringExtractorGDBRemote::eServerPacketType_qGetWorkingDir,
109*061da546Spatrick       &GDBRemoteCommunicationServerLLGS::Handle_qGetWorkingDir);
110*061da546Spatrick   RegisterMemberFunctionHandler(
111*061da546Spatrick       StringExtractorGDBRemote::eServerPacketType_qMemoryRegionInfo,
112*061da546Spatrick       &GDBRemoteCommunicationServerLLGS::Handle_qMemoryRegionInfo);
113*061da546Spatrick   RegisterMemberFunctionHandler(
114*061da546Spatrick       StringExtractorGDBRemote::eServerPacketType_qMemoryRegionInfoSupported,
115*061da546Spatrick       &GDBRemoteCommunicationServerLLGS::Handle_qMemoryRegionInfoSupported);
116*061da546Spatrick   RegisterMemberFunctionHandler(
117*061da546Spatrick       StringExtractorGDBRemote::eServerPacketType_qProcessInfo,
118*061da546Spatrick       &GDBRemoteCommunicationServerLLGS::Handle_qProcessInfo);
119*061da546Spatrick   RegisterMemberFunctionHandler(
120*061da546Spatrick       StringExtractorGDBRemote::eServerPacketType_qRegisterInfo,
121*061da546Spatrick       &GDBRemoteCommunicationServerLLGS::Handle_qRegisterInfo);
122*061da546Spatrick   RegisterMemberFunctionHandler(
123*061da546Spatrick       StringExtractorGDBRemote::eServerPacketType_QRestoreRegisterState,
124*061da546Spatrick       &GDBRemoteCommunicationServerLLGS::Handle_QRestoreRegisterState);
125*061da546Spatrick   RegisterMemberFunctionHandler(
126*061da546Spatrick       StringExtractorGDBRemote::eServerPacketType_QSaveRegisterState,
127*061da546Spatrick       &GDBRemoteCommunicationServerLLGS::Handle_QSaveRegisterState);
128*061da546Spatrick   RegisterMemberFunctionHandler(
129*061da546Spatrick       StringExtractorGDBRemote::eServerPacketType_QSetDisableASLR,
130*061da546Spatrick       &GDBRemoteCommunicationServerLLGS::Handle_QSetDisableASLR);
131*061da546Spatrick   RegisterMemberFunctionHandler(
132*061da546Spatrick       StringExtractorGDBRemote::eServerPacketType_QSetWorkingDir,
133*061da546Spatrick       &GDBRemoteCommunicationServerLLGS::Handle_QSetWorkingDir);
134*061da546Spatrick   RegisterMemberFunctionHandler(
135*061da546Spatrick       StringExtractorGDBRemote::eServerPacketType_qsThreadInfo,
136*061da546Spatrick       &GDBRemoteCommunicationServerLLGS::Handle_qsThreadInfo);
137*061da546Spatrick   RegisterMemberFunctionHandler(
138*061da546Spatrick       StringExtractorGDBRemote::eServerPacketType_qThreadStopInfo,
139*061da546Spatrick       &GDBRemoteCommunicationServerLLGS::Handle_qThreadStopInfo);
140*061da546Spatrick   RegisterMemberFunctionHandler(
141*061da546Spatrick       StringExtractorGDBRemote::eServerPacketType_jThreadsInfo,
142*061da546Spatrick       &GDBRemoteCommunicationServerLLGS::Handle_jThreadsInfo);
143*061da546Spatrick   RegisterMemberFunctionHandler(
144*061da546Spatrick       StringExtractorGDBRemote::eServerPacketType_qWatchpointSupportInfo,
145*061da546Spatrick       &GDBRemoteCommunicationServerLLGS::Handle_qWatchpointSupportInfo);
146*061da546Spatrick   RegisterMemberFunctionHandler(
147*061da546Spatrick       StringExtractorGDBRemote::eServerPacketType_qXfer,
148*061da546Spatrick       &GDBRemoteCommunicationServerLLGS::Handle_qXfer);
149*061da546Spatrick   RegisterMemberFunctionHandler(StringExtractorGDBRemote::eServerPacketType_s,
150*061da546Spatrick                                 &GDBRemoteCommunicationServerLLGS::Handle_s);
151*061da546Spatrick   RegisterMemberFunctionHandler(
152*061da546Spatrick       StringExtractorGDBRemote::eServerPacketType_stop_reason,
153*061da546Spatrick       &GDBRemoteCommunicationServerLLGS::Handle_stop_reason); // ?
154*061da546Spatrick   RegisterMemberFunctionHandler(
155*061da546Spatrick       StringExtractorGDBRemote::eServerPacketType_vAttach,
156*061da546Spatrick       &GDBRemoteCommunicationServerLLGS::Handle_vAttach);
157*061da546Spatrick   RegisterMemberFunctionHandler(
158*061da546Spatrick       StringExtractorGDBRemote::eServerPacketType_vCont,
159*061da546Spatrick       &GDBRemoteCommunicationServerLLGS::Handle_vCont);
160*061da546Spatrick   RegisterMemberFunctionHandler(
161*061da546Spatrick       StringExtractorGDBRemote::eServerPacketType_vCont_actions,
162*061da546Spatrick       &GDBRemoteCommunicationServerLLGS::Handle_vCont_actions);
163*061da546Spatrick   RegisterMemberFunctionHandler(
164*061da546Spatrick       StringExtractorGDBRemote::eServerPacketType_x,
165*061da546Spatrick       &GDBRemoteCommunicationServerLLGS::Handle_memory_read);
166*061da546Spatrick   RegisterMemberFunctionHandler(StringExtractorGDBRemote::eServerPacketType_Z,
167*061da546Spatrick                                 &GDBRemoteCommunicationServerLLGS::Handle_Z);
168*061da546Spatrick   RegisterMemberFunctionHandler(StringExtractorGDBRemote::eServerPacketType_z,
169*061da546Spatrick                                 &GDBRemoteCommunicationServerLLGS::Handle_z);
170*061da546Spatrick   RegisterMemberFunctionHandler(
171*061da546Spatrick       StringExtractorGDBRemote::eServerPacketType_QPassSignals,
172*061da546Spatrick       &GDBRemoteCommunicationServerLLGS::Handle_QPassSignals);
173*061da546Spatrick 
174*061da546Spatrick   RegisterMemberFunctionHandler(
175*061da546Spatrick       StringExtractorGDBRemote::eServerPacketType_jTraceStart,
176*061da546Spatrick       &GDBRemoteCommunicationServerLLGS::Handle_jTraceStart);
177*061da546Spatrick   RegisterMemberFunctionHandler(
178*061da546Spatrick       StringExtractorGDBRemote::eServerPacketType_jTraceBufferRead,
179*061da546Spatrick       &GDBRemoteCommunicationServerLLGS::Handle_jTraceRead);
180*061da546Spatrick   RegisterMemberFunctionHandler(
181*061da546Spatrick       StringExtractorGDBRemote::eServerPacketType_jTraceMetaRead,
182*061da546Spatrick       &GDBRemoteCommunicationServerLLGS::Handle_jTraceRead);
183*061da546Spatrick   RegisterMemberFunctionHandler(
184*061da546Spatrick       StringExtractorGDBRemote::eServerPacketType_jTraceStop,
185*061da546Spatrick       &GDBRemoteCommunicationServerLLGS::Handle_jTraceStop);
186*061da546Spatrick   RegisterMemberFunctionHandler(
187*061da546Spatrick       StringExtractorGDBRemote::eServerPacketType_jTraceConfigRead,
188*061da546Spatrick       &GDBRemoteCommunicationServerLLGS::Handle_jTraceConfigRead);
189*061da546Spatrick 
190*061da546Spatrick   RegisterMemberFunctionHandler(StringExtractorGDBRemote::eServerPacketType_g,
191*061da546Spatrick                                 &GDBRemoteCommunicationServerLLGS::Handle_g);
192*061da546Spatrick 
193*061da546Spatrick   RegisterPacketHandler(StringExtractorGDBRemote::eServerPacketType_k,
194*061da546Spatrick                         [this](StringExtractorGDBRemote packet, Status &error,
195*061da546Spatrick                                bool &interrupt, bool &quit) {
196*061da546Spatrick                           quit = true;
197*061da546Spatrick                           return this->Handle_k(packet);
198*061da546Spatrick                         });
199*061da546Spatrick }
200*061da546Spatrick 
201*061da546Spatrick void GDBRemoteCommunicationServerLLGS::SetLaunchInfo(const ProcessLaunchInfo &info) {
202*061da546Spatrick   m_process_launch_info = info;
203*061da546Spatrick }
204*061da546Spatrick 
205*061da546Spatrick Status GDBRemoteCommunicationServerLLGS::LaunchProcess() {
206*061da546Spatrick   Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
207*061da546Spatrick 
208*061da546Spatrick   if (!m_process_launch_info.GetArguments().GetArgumentCount())
209*061da546Spatrick     return Status("%s: no process command line specified to launch",
210*061da546Spatrick                   __FUNCTION__);
211*061da546Spatrick 
212*061da546Spatrick   const bool should_forward_stdio =
213*061da546Spatrick       m_process_launch_info.GetFileActionForFD(STDIN_FILENO) == nullptr ||
214*061da546Spatrick       m_process_launch_info.GetFileActionForFD(STDOUT_FILENO) == nullptr ||
215*061da546Spatrick       m_process_launch_info.GetFileActionForFD(STDERR_FILENO) == nullptr;
216*061da546Spatrick   m_process_launch_info.SetLaunchInSeparateProcessGroup(true);
217*061da546Spatrick   m_process_launch_info.GetFlags().Set(eLaunchFlagDebug);
218*061da546Spatrick 
219*061da546Spatrick   if (should_forward_stdio) {
220*061da546Spatrick     // Temporarily relax the following for Windows until we can take advantage
221*061da546Spatrick     // of the recently added pty support. This doesn't really affect the use of
222*061da546Spatrick     // lldb-server on Windows.
223*061da546Spatrick #if !defined(_WIN32)
224*061da546Spatrick     if (llvm::Error Err = m_process_launch_info.SetUpPtyRedirection())
225*061da546Spatrick       return Status(std::move(Err));
226*061da546Spatrick #endif
227*061da546Spatrick   }
228*061da546Spatrick 
229*061da546Spatrick   {
230*061da546Spatrick     std::lock_guard<std::recursive_mutex> guard(m_debugged_process_mutex);
231*061da546Spatrick     assert(!m_debugged_process_up && "lldb-server creating debugged "
232*061da546Spatrick                                      "process but one already exists");
233*061da546Spatrick     auto process_or =
234*061da546Spatrick         m_process_factory.Launch(m_process_launch_info, *this, m_mainloop);
235*061da546Spatrick     if (!process_or)
236*061da546Spatrick       return Status(process_or.takeError());
237*061da546Spatrick     m_debugged_process_up = std::move(*process_or);
238*061da546Spatrick   }
239*061da546Spatrick 
240*061da546Spatrick   // Handle mirroring of inferior stdout/stderr over the gdb-remote protocol as
241*061da546Spatrick   // needed. llgs local-process debugging may specify PTY paths, which will
242*061da546Spatrick   // make these file actions non-null process launch -i/e/o will also make
243*061da546Spatrick   // these file actions non-null nullptr means that the traffic is expected to
244*061da546Spatrick   // flow over gdb-remote protocol
245*061da546Spatrick   if (should_forward_stdio) {
246*061da546Spatrick     // nullptr means it's not redirected to file or pty (in case of LLGS local)
247*061da546Spatrick     // at least one of stdio will be transferred pty<->gdb-remote we need to
248*061da546Spatrick     // give the pty master handle to this object to read and/or write
249*061da546Spatrick     LLDB_LOG(log,
250*061da546Spatrick              "pid = {0}: setting up stdout/stderr redirection via $O "
251*061da546Spatrick              "gdb-remote commands",
252*061da546Spatrick              m_debugged_process_up->GetID());
253*061da546Spatrick 
254*061da546Spatrick     // Setup stdout/stderr mapping from inferior to $O
255*061da546Spatrick     auto terminal_fd = m_debugged_process_up->GetTerminalFileDescriptor();
256*061da546Spatrick     if (terminal_fd >= 0) {
257*061da546Spatrick       LLDB_LOGF(log,
258*061da546Spatrick                 "ProcessGDBRemoteCommunicationServerLLGS::%s setting "
259*061da546Spatrick                 "inferior STDIO fd to %d",
260*061da546Spatrick                 __FUNCTION__, terminal_fd);
261*061da546Spatrick       Status status = SetSTDIOFileDescriptor(terminal_fd);
262*061da546Spatrick       if (status.Fail())
263*061da546Spatrick         return status;
264*061da546Spatrick     } else {
265*061da546Spatrick       LLDB_LOGF(log,
266*061da546Spatrick                 "ProcessGDBRemoteCommunicationServerLLGS::%s ignoring "
267*061da546Spatrick                 "inferior STDIO since terminal fd reported as %d",
268*061da546Spatrick                 __FUNCTION__, terminal_fd);
269*061da546Spatrick     }
270*061da546Spatrick   } else {
271*061da546Spatrick     LLDB_LOG(log,
272*061da546Spatrick              "pid = {0} skipping stdout/stderr redirection via $O: inferior "
273*061da546Spatrick              "will communicate over client-provided file descriptors",
274*061da546Spatrick              m_debugged_process_up->GetID());
275*061da546Spatrick   }
276*061da546Spatrick 
277*061da546Spatrick   printf("Launched '%s' as process %" PRIu64 "...\n",
278*061da546Spatrick          m_process_launch_info.GetArguments().GetArgumentAtIndex(0),
279*061da546Spatrick          m_debugged_process_up->GetID());
280*061da546Spatrick 
281*061da546Spatrick   return Status();
282*061da546Spatrick }
283*061da546Spatrick 
284*061da546Spatrick Status GDBRemoteCommunicationServerLLGS::AttachToProcess(lldb::pid_t pid) {
285*061da546Spatrick   Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
286*061da546Spatrick   LLDB_LOGF(log, "GDBRemoteCommunicationServerLLGS::%s pid %" PRIu64,
287*061da546Spatrick             __FUNCTION__, pid);
288*061da546Spatrick 
289*061da546Spatrick   // Before we try to attach, make sure we aren't already monitoring something
290*061da546Spatrick   // else.
291*061da546Spatrick   if (m_debugged_process_up &&
292*061da546Spatrick       m_debugged_process_up->GetID() != LLDB_INVALID_PROCESS_ID)
293*061da546Spatrick     return Status("cannot attach to process %" PRIu64
294*061da546Spatrick                   " when another process with pid %" PRIu64
295*061da546Spatrick                   " is being debugged.",
296*061da546Spatrick                   pid, m_debugged_process_up->GetID());
297*061da546Spatrick 
298*061da546Spatrick   // Try to attach.
299*061da546Spatrick   auto process_or = m_process_factory.Attach(pid, *this, m_mainloop);
300*061da546Spatrick   if (!process_or) {
301*061da546Spatrick     Status status(process_or.takeError());
302*061da546Spatrick     llvm::errs() << llvm::formatv("failed to attach to process {0}: {1}", pid,
303*061da546Spatrick                                   status);
304*061da546Spatrick     return status;
305*061da546Spatrick   }
306*061da546Spatrick   m_debugged_process_up = std::move(*process_or);
307*061da546Spatrick 
308*061da546Spatrick   // Setup stdout/stderr mapping from inferior.
309*061da546Spatrick   auto terminal_fd = m_debugged_process_up->GetTerminalFileDescriptor();
310*061da546Spatrick   if (terminal_fd >= 0) {
311*061da546Spatrick     LLDB_LOGF(log,
312*061da546Spatrick               "ProcessGDBRemoteCommunicationServerLLGS::%s setting "
313*061da546Spatrick               "inferior STDIO fd to %d",
314*061da546Spatrick               __FUNCTION__, terminal_fd);
315*061da546Spatrick     Status status = SetSTDIOFileDescriptor(terminal_fd);
316*061da546Spatrick     if (status.Fail())
317*061da546Spatrick       return status;
318*061da546Spatrick   } else {
319*061da546Spatrick     LLDB_LOGF(log,
320*061da546Spatrick               "ProcessGDBRemoteCommunicationServerLLGS::%s ignoring "
321*061da546Spatrick               "inferior STDIO since terminal fd reported as %d",
322*061da546Spatrick               __FUNCTION__, terminal_fd);
323*061da546Spatrick   }
324*061da546Spatrick 
325*061da546Spatrick   printf("Attached to process %" PRIu64 "...\n", pid);
326*061da546Spatrick   return Status();
327*061da546Spatrick }
328*061da546Spatrick 
329*061da546Spatrick void GDBRemoteCommunicationServerLLGS::InitializeDelegate(
330*061da546Spatrick     NativeProcessProtocol *process) {
331*061da546Spatrick   assert(process && "process cannot be NULL");
332*061da546Spatrick   Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
333*061da546Spatrick   if (log) {
334*061da546Spatrick     LLDB_LOGF(log,
335*061da546Spatrick               "GDBRemoteCommunicationServerLLGS::%s called with "
336*061da546Spatrick               "NativeProcessProtocol pid %" PRIu64 ", current state: %s",
337*061da546Spatrick               __FUNCTION__, process->GetID(),
338*061da546Spatrick               StateAsCString(process->GetState()));
339*061da546Spatrick   }
340*061da546Spatrick }
341*061da546Spatrick 
342*061da546Spatrick GDBRemoteCommunication::PacketResult
343*061da546Spatrick GDBRemoteCommunicationServerLLGS::SendWResponse(
344*061da546Spatrick     NativeProcessProtocol *process) {
345*061da546Spatrick   assert(process && "process cannot be NULL");
346*061da546Spatrick   Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
347*061da546Spatrick 
348*061da546Spatrick   // send W notification
349*061da546Spatrick   auto wait_status = process->GetExitStatus();
350*061da546Spatrick   if (!wait_status) {
351*061da546Spatrick     LLDB_LOG(log, "pid = {0}, failed to retrieve process exit status",
352*061da546Spatrick              process->GetID());
353*061da546Spatrick 
354*061da546Spatrick     StreamGDBRemote response;
355*061da546Spatrick     response.PutChar('E');
356*061da546Spatrick     response.PutHex8(GDBRemoteServerError::eErrorExitStatus);
357*061da546Spatrick     return SendPacketNoLock(response.GetString());
358*061da546Spatrick   }
359*061da546Spatrick 
360*061da546Spatrick   LLDB_LOG(log, "pid = {0}, returning exit type {1}", process->GetID(),
361*061da546Spatrick            *wait_status);
362*061da546Spatrick 
363*061da546Spatrick   StreamGDBRemote response;
364*061da546Spatrick   response.Format("{0:g}", *wait_status);
365*061da546Spatrick   return SendPacketNoLock(response.GetString());
366*061da546Spatrick }
367*061da546Spatrick 
368*061da546Spatrick static void AppendHexValue(StreamString &response, const uint8_t *buf,
369*061da546Spatrick                            uint32_t buf_size, bool swap) {
370*061da546Spatrick   int64_t i;
371*061da546Spatrick   if (swap) {
372*061da546Spatrick     for (i = buf_size - 1; i >= 0; i--)
373*061da546Spatrick       response.PutHex8(buf[i]);
374*061da546Spatrick   } else {
375*061da546Spatrick     for (i = 0; i < buf_size; i++)
376*061da546Spatrick       response.PutHex8(buf[i]);
377*061da546Spatrick   }
378*061da546Spatrick }
379*061da546Spatrick 
380*061da546Spatrick static void WriteRegisterValueInHexFixedWidth(
381*061da546Spatrick     StreamString &response, NativeRegisterContext &reg_ctx,
382*061da546Spatrick     const RegisterInfo &reg_info, const RegisterValue *reg_value_p,
383*061da546Spatrick     lldb::ByteOrder byte_order) {
384*061da546Spatrick   RegisterValue reg_value;
385*061da546Spatrick   if (!reg_value_p) {
386*061da546Spatrick     Status error = reg_ctx.ReadRegister(&reg_info, reg_value);
387*061da546Spatrick     if (error.Success())
388*061da546Spatrick       reg_value_p = &reg_value;
389*061da546Spatrick     // else log.
390*061da546Spatrick   }
391*061da546Spatrick 
392*061da546Spatrick   if (reg_value_p) {
393*061da546Spatrick     AppendHexValue(response, (const uint8_t *)reg_value_p->GetBytes(),
394*061da546Spatrick                    reg_value_p->GetByteSize(),
395*061da546Spatrick                    byte_order == lldb::eByteOrderLittle);
396*061da546Spatrick   } else {
397*061da546Spatrick     // Zero-out any unreadable values.
398*061da546Spatrick     if (reg_info.byte_size > 0) {
399*061da546Spatrick       std::basic_string<uint8_t> zeros(reg_info.byte_size, '\0');
400*061da546Spatrick       AppendHexValue(response, zeros.data(), zeros.size(), false);
401*061da546Spatrick     }
402*061da546Spatrick   }
403*061da546Spatrick }
404*061da546Spatrick 
405*061da546Spatrick static llvm::Expected<json::Object>
406*061da546Spatrick GetRegistersAsJSON(NativeThreadProtocol &thread) {
407*061da546Spatrick   Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_THREAD));
408*061da546Spatrick 
409*061da546Spatrick   NativeRegisterContext& reg_ctx = thread.GetRegisterContext();
410*061da546Spatrick 
411*061da546Spatrick   json::Object register_object;
412*061da546Spatrick 
413*061da546Spatrick #ifdef LLDB_JTHREADSINFO_FULL_REGISTER_SET
414*061da546Spatrick   // Expedite all registers in the first register set (i.e. should be GPRs)
415*061da546Spatrick   // that are not contained in other registers.
416*061da546Spatrick   const RegisterSet *reg_set_p = reg_ctx_sp->GetRegisterSet(0);
417*061da546Spatrick   if (!reg_set_p)
418*061da546Spatrick     return llvm::make_error<llvm::StringError>("failed to get registers",
419*061da546Spatrick                                                llvm::inconvertibleErrorCode());
420*061da546Spatrick   for (const uint32_t *reg_num_p = reg_set_p->registers;
421*061da546Spatrick        *reg_num_p != LLDB_INVALID_REGNUM; ++reg_num_p) {
422*061da546Spatrick     uint32_t reg_num = *reg_num_p;
423*061da546Spatrick #else
424*061da546Spatrick   // Expedite only a couple of registers until we figure out why sending
425*061da546Spatrick   // registers is expensive.
426*061da546Spatrick   static const uint32_t k_expedited_registers[] = {
427*061da546Spatrick       LLDB_REGNUM_GENERIC_PC, LLDB_REGNUM_GENERIC_SP, LLDB_REGNUM_GENERIC_FP,
428*061da546Spatrick       LLDB_REGNUM_GENERIC_RA, LLDB_INVALID_REGNUM};
429*061da546Spatrick 
430*061da546Spatrick   for (const uint32_t *generic_reg_p = k_expedited_registers;
431*061da546Spatrick        *generic_reg_p != LLDB_INVALID_REGNUM; ++generic_reg_p) {
432*061da546Spatrick     uint32_t reg_num = reg_ctx.ConvertRegisterKindToRegisterNumber(
433*061da546Spatrick         eRegisterKindGeneric, *generic_reg_p);
434*061da546Spatrick     if (reg_num == LLDB_INVALID_REGNUM)
435*061da546Spatrick       continue; // Target does not support the given register.
436*061da546Spatrick #endif
437*061da546Spatrick 
438*061da546Spatrick     const RegisterInfo *const reg_info_p =
439*061da546Spatrick         reg_ctx.GetRegisterInfoAtIndex(reg_num);
440*061da546Spatrick     if (reg_info_p == nullptr) {
441*061da546Spatrick       LLDB_LOGF(log,
442*061da546Spatrick                 "%s failed to get register info for register index %" PRIu32,
443*061da546Spatrick                 __FUNCTION__, reg_num);
444*061da546Spatrick       continue;
445*061da546Spatrick     }
446*061da546Spatrick 
447*061da546Spatrick     if (reg_info_p->value_regs != nullptr)
448*061da546Spatrick       continue; // Only expedite registers that are not contained in other
449*061da546Spatrick                 // registers.
450*061da546Spatrick 
451*061da546Spatrick     RegisterValue reg_value;
452*061da546Spatrick     Status error = reg_ctx.ReadRegister(reg_info_p, reg_value);
453*061da546Spatrick     if (error.Fail()) {
454*061da546Spatrick       LLDB_LOGF(log, "%s failed to read register '%s' index %" PRIu32 ": %s",
455*061da546Spatrick                 __FUNCTION__,
456*061da546Spatrick                 reg_info_p->name ? reg_info_p->name : "<unnamed-register>",
457*061da546Spatrick                 reg_num, error.AsCString());
458*061da546Spatrick       continue;
459*061da546Spatrick     }
460*061da546Spatrick 
461*061da546Spatrick     StreamString stream;
462*061da546Spatrick     WriteRegisterValueInHexFixedWidth(stream, reg_ctx, *reg_info_p,
463*061da546Spatrick                                       &reg_value, lldb::eByteOrderBig);
464*061da546Spatrick 
465*061da546Spatrick     register_object.try_emplace(llvm::to_string(reg_num),
466*061da546Spatrick                                 stream.GetString().str());
467*061da546Spatrick   }
468*061da546Spatrick 
469*061da546Spatrick   return register_object;
470*061da546Spatrick }
471*061da546Spatrick 
472*061da546Spatrick static const char *GetStopReasonString(StopReason stop_reason) {
473*061da546Spatrick   switch (stop_reason) {
474*061da546Spatrick   case eStopReasonTrace:
475*061da546Spatrick     return "trace";
476*061da546Spatrick   case eStopReasonBreakpoint:
477*061da546Spatrick     return "breakpoint";
478*061da546Spatrick   case eStopReasonWatchpoint:
479*061da546Spatrick     return "watchpoint";
480*061da546Spatrick   case eStopReasonSignal:
481*061da546Spatrick     return "signal";
482*061da546Spatrick   case eStopReasonException:
483*061da546Spatrick     return "exception";
484*061da546Spatrick   case eStopReasonExec:
485*061da546Spatrick     return "exec";
486*061da546Spatrick   case eStopReasonInstrumentation:
487*061da546Spatrick   case eStopReasonInvalid:
488*061da546Spatrick   case eStopReasonPlanComplete:
489*061da546Spatrick   case eStopReasonThreadExiting:
490*061da546Spatrick   case eStopReasonNone:
491*061da546Spatrick     break; // ignored
492*061da546Spatrick   }
493*061da546Spatrick   return nullptr;
494*061da546Spatrick }
495*061da546Spatrick 
496*061da546Spatrick static llvm::Expected<json::Array>
497*061da546Spatrick GetJSONThreadsInfo(NativeProcessProtocol &process, bool abridged) {
498*061da546Spatrick   Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS | LIBLLDB_LOG_THREAD));
499*061da546Spatrick 
500*061da546Spatrick   json::Array threads_array;
501*061da546Spatrick 
502*061da546Spatrick   // Ensure we can get info on the given thread.
503*061da546Spatrick   uint32_t thread_idx = 0;
504*061da546Spatrick   for (NativeThreadProtocol *thread;
505*061da546Spatrick        (thread = process.GetThreadAtIndex(thread_idx)) != nullptr;
506*061da546Spatrick        ++thread_idx) {
507*061da546Spatrick 
508*061da546Spatrick     lldb::tid_t tid = thread->GetID();
509*061da546Spatrick 
510*061da546Spatrick     // Grab the reason this thread stopped.
511*061da546Spatrick     struct ThreadStopInfo tid_stop_info;
512*061da546Spatrick     std::string description;
513*061da546Spatrick     if (!thread->GetStopReason(tid_stop_info, description))
514*061da546Spatrick       return llvm::make_error<llvm::StringError>(
515*061da546Spatrick           "failed to get stop reason", llvm::inconvertibleErrorCode());
516*061da546Spatrick 
517*061da546Spatrick     const int signum = tid_stop_info.details.signal.signo;
518*061da546Spatrick     if (log) {
519*061da546Spatrick       LLDB_LOGF(log,
520*061da546Spatrick                 "GDBRemoteCommunicationServerLLGS::%s pid %" PRIu64
521*061da546Spatrick                 " tid %" PRIu64
522*061da546Spatrick                 " got signal signo = %d, reason = %d, exc_type = %" PRIu64,
523*061da546Spatrick                 __FUNCTION__, process.GetID(), tid, signum,
524*061da546Spatrick                 tid_stop_info.reason, tid_stop_info.details.exception.type);
525*061da546Spatrick     }
526*061da546Spatrick 
527*061da546Spatrick     json::Object thread_obj;
528*061da546Spatrick 
529*061da546Spatrick     if (!abridged) {
530*061da546Spatrick       if (llvm::Expected<json::Object> registers =
531*061da546Spatrick               GetRegistersAsJSON(*thread)) {
532*061da546Spatrick         thread_obj.try_emplace("registers", std::move(*registers));
533*061da546Spatrick       } else {
534*061da546Spatrick         return registers.takeError();
535*061da546Spatrick       }
536*061da546Spatrick     }
537*061da546Spatrick 
538*061da546Spatrick     thread_obj.try_emplace("tid", static_cast<int64_t>(tid));
539*061da546Spatrick 
540*061da546Spatrick     if (signum != 0)
541*061da546Spatrick       thread_obj.try_emplace("signal", signum);
542*061da546Spatrick 
543*061da546Spatrick     const std::string thread_name = thread->GetName();
544*061da546Spatrick     if (!thread_name.empty())
545*061da546Spatrick       thread_obj.try_emplace("name", thread_name);
546*061da546Spatrick 
547*061da546Spatrick     const char *stop_reason = GetStopReasonString(tid_stop_info.reason);
548*061da546Spatrick     if (stop_reason)
549*061da546Spatrick       thread_obj.try_emplace("reason", stop_reason);
550*061da546Spatrick 
551*061da546Spatrick     if (!description.empty())
552*061da546Spatrick       thread_obj.try_emplace("description", description);
553*061da546Spatrick 
554*061da546Spatrick     if ((tid_stop_info.reason == eStopReasonException) &&
555*061da546Spatrick         tid_stop_info.details.exception.type) {
556*061da546Spatrick       thread_obj.try_emplace(
557*061da546Spatrick           "metype", static_cast<int64_t>(tid_stop_info.details.exception.type));
558*061da546Spatrick 
559*061da546Spatrick       json::Array medata_array;
560*061da546Spatrick       for (uint32_t i = 0; i < tid_stop_info.details.exception.data_count;
561*061da546Spatrick            ++i) {
562*061da546Spatrick         medata_array.push_back(
563*061da546Spatrick             static_cast<int64_t>(tid_stop_info.details.exception.data[i]));
564*061da546Spatrick       }
565*061da546Spatrick       thread_obj.try_emplace("medata", std::move(medata_array));
566*061da546Spatrick     }
567*061da546Spatrick     threads_array.push_back(std::move(thread_obj));
568*061da546Spatrick   }
569*061da546Spatrick   return threads_array;
570*061da546Spatrick }
571*061da546Spatrick 
572*061da546Spatrick GDBRemoteCommunication::PacketResult
573*061da546Spatrick GDBRemoteCommunicationServerLLGS::SendStopReplyPacketForThread(
574*061da546Spatrick     lldb::tid_t tid) {
575*061da546Spatrick   Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS | LIBLLDB_LOG_THREAD));
576*061da546Spatrick 
577*061da546Spatrick   // Ensure we have a debugged process.
578*061da546Spatrick   if (!m_debugged_process_up ||
579*061da546Spatrick       (m_debugged_process_up->GetID() == LLDB_INVALID_PROCESS_ID))
580*061da546Spatrick     return SendErrorResponse(50);
581*061da546Spatrick 
582*061da546Spatrick   LLDB_LOG(log, "preparing packet for pid {0} tid {1}",
583*061da546Spatrick            m_debugged_process_up->GetID(), tid);
584*061da546Spatrick 
585*061da546Spatrick   // Ensure we can get info on the given thread.
586*061da546Spatrick   NativeThreadProtocol *thread = m_debugged_process_up->GetThreadByID(tid);
587*061da546Spatrick   if (!thread)
588*061da546Spatrick     return SendErrorResponse(51);
589*061da546Spatrick 
590*061da546Spatrick   // Grab the reason this thread stopped.
591*061da546Spatrick   struct ThreadStopInfo tid_stop_info;
592*061da546Spatrick   std::string description;
593*061da546Spatrick   if (!thread->GetStopReason(tid_stop_info, description))
594*061da546Spatrick     return SendErrorResponse(52);
595*061da546Spatrick 
596*061da546Spatrick   // FIXME implement register handling for exec'd inferiors.
597*061da546Spatrick   // if (tid_stop_info.reason == eStopReasonExec) {
598*061da546Spatrick   //     const bool force = true;
599*061da546Spatrick   //     InitializeRegisters(force);
600*061da546Spatrick   // }
601*061da546Spatrick 
602*061da546Spatrick   StreamString response;
603*061da546Spatrick   // Output the T packet with the thread
604*061da546Spatrick   response.PutChar('T');
605*061da546Spatrick   int signum = tid_stop_info.details.signal.signo;
606*061da546Spatrick   LLDB_LOG(
607*061da546Spatrick       log,
608*061da546Spatrick       "pid {0}, tid {1}, got signal signo = {2}, reason = {3}, exc_type = {4}",
609*061da546Spatrick       m_debugged_process_up->GetID(), tid, signum, int(tid_stop_info.reason),
610*061da546Spatrick       tid_stop_info.details.exception.type);
611*061da546Spatrick 
612*061da546Spatrick   // Print the signal number.
613*061da546Spatrick   response.PutHex8(signum & 0xff);
614*061da546Spatrick 
615*061da546Spatrick   // Include the tid.
616*061da546Spatrick   response.Printf("thread:%" PRIx64 ";", tid);
617*061da546Spatrick 
618*061da546Spatrick   // Include the thread name if there is one.
619*061da546Spatrick   const std::string thread_name = thread->GetName();
620*061da546Spatrick   if (!thread_name.empty()) {
621*061da546Spatrick     size_t thread_name_len = thread_name.length();
622*061da546Spatrick 
623*061da546Spatrick     if (::strcspn(thread_name.c_str(), "$#+-;:") == thread_name_len) {
624*061da546Spatrick       response.PutCString("name:");
625*061da546Spatrick       response.PutCString(thread_name);
626*061da546Spatrick     } else {
627*061da546Spatrick       // The thread name contains special chars, send as hex bytes.
628*061da546Spatrick       response.PutCString("hexname:");
629*061da546Spatrick       response.PutStringAsRawHex8(thread_name);
630*061da546Spatrick     }
631*061da546Spatrick     response.PutChar(';');
632*061da546Spatrick   }
633*061da546Spatrick 
634*061da546Spatrick   // If a 'QListThreadsInStopReply' was sent to enable this feature, we will
635*061da546Spatrick   // send all thread IDs back in the "threads" key whose value is a list of hex
636*061da546Spatrick   // thread IDs separated by commas:
637*061da546Spatrick   //  "threads:10a,10b,10c;"
638*061da546Spatrick   // This will save the debugger from having to send a pair of qfThreadInfo and
639*061da546Spatrick   // qsThreadInfo packets, but it also might take a lot of room in the stop
640*061da546Spatrick   // reply packet, so it must be enabled only on systems where there are no
641*061da546Spatrick   // limits on packet lengths.
642*061da546Spatrick   if (m_list_threads_in_stop_reply) {
643*061da546Spatrick     response.PutCString("threads:");
644*061da546Spatrick 
645*061da546Spatrick     uint32_t thread_index = 0;
646*061da546Spatrick     NativeThreadProtocol *listed_thread;
647*061da546Spatrick     for (listed_thread = m_debugged_process_up->GetThreadAtIndex(thread_index);
648*061da546Spatrick          listed_thread; ++thread_index,
649*061da546Spatrick         listed_thread = m_debugged_process_up->GetThreadAtIndex(thread_index)) {
650*061da546Spatrick       if (thread_index > 0)
651*061da546Spatrick         response.PutChar(',');
652*061da546Spatrick       response.Printf("%" PRIx64, listed_thread->GetID());
653*061da546Spatrick     }
654*061da546Spatrick     response.PutChar(';');
655*061da546Spatrick 
656*061da546Spatrick     // Include JSON info that describes the stop reason for any threads that
657*061da546Spatrick     // actually have stop reasons. We use the new "jstopinfo" key whose values
658*061da546Spatrick     // is hex ascii JSON that contains the thread IDs thread stop info only for
659*061da546Spatrick     // threads that have stop reasons. Only send this if we have more than one
660*061da546Spatrick     // thread otherwise this packet has all the info it needs.
661*061da546Spatrick     if (thread_index > 1) {
662*061da546Spatrick       const bool threads_with_valid_stop_info_only = true;
663*061da546Spatrick       llvm::Expected<json::Array> threads_info = GetJSONThreadsInfo(
664*061da546Spatrick           *m_debugged_process_up, threads_with_valid_stop_info_only);
665*061da546Spatrick       if (threads_info) {
666*061da546Spatrick         response.PutCString("jstopinfo:");
667*061da546Spatrick         StreamString unescaped_response;
668*061da546Spatrick         unescaped_response.AsRawOstream() << std::move(*threads_info);
669*061da546Spatrick         response.PutStringAsRawHex8(unescaped_response.GetData());
670*061da546Spatrick         response.PutChar(';');
671*061da546Spatrick       } else {
672*061da546Spatrick         LLDB_LOG_ERROR(log, threads_info.takeError(),
673*061da546Spatrick                        "failed to prepare a jstopinfo field for pid {1}: {0}",
674*061da546Spatrick                        m_debugged_process_up->GetID());
675*061da546Spatrick       }
676*061da546Spatrick     }
677*061da546Spatrick 
678*061da546Spatrick     uint32_t i = 0;
679*061da546Spatrick     response.PutCString("thread-pcs");
680*061da546Spatrick     char delimiter = ':';
681*061da546Spatrick     for (NativeThreadProtocol *thread;
682*061da546Spatrick          (thread = m_debugged_process_up->GetThreadAtIndex(i)) != nullptr;
683*061da546Spatrick          ++i) {
684*061da546Spatrick       NativeRegisterContext& reg_ctx = thread->GetRegisterContext();
685*061da546Spatrick 
686*061da546Spatrick       uint32_t reg_to_read = reg_ctx.ConvertRegisterKindToRegisterNumber(
687*061da546Spatrick           eRegisterKindGeneric, LLDB_REGNUM_GENERIC_PC);
688*061da546Spatrick       const RegisterInfo *const reg_info_p =
689*061da546Spatrick           reg_ctx.GetRegisterInfoAtIndex(reg_to_read);
690*061da546Spatrick 
691*061da546Spatrick       RegisterValue reg_value;
692*061da546Spatrick       Status error = reg_ctx.ReadRegister(reg_info_p, reg_value);
693*061da546Spatrick       if (error.Fail()) {
694*061da546Spatrick         LLDB_LOGF(log, "%s failed to read register '%s' index %" PRIu32 ": %s",
695*061da546Spatrick                   __FUNCTION__,
696*061da546Spatrick                   reg_info_p->name ? reg_info_p->name : "<unnamed-register>",
697*061da546Spatrick                   reg_to_read, error.AsCString());
698*061da546Spatrick         continue;
699*061da546Spatrick       }
700*061da546Spatrick 
701*061da546Spatrick       response.PutChar(delimiter);
702*061da546Spatrick       delimiter = ',';
703*061da546Spatrick       WriteRegisterValueInHexFixedWidth(response, reg_ctx, *reg_info_p,
704*061da546Spatrick                                         &reg_value, endian::InlHostByteOrder());
705*061da546Spatrick     }
706*061da546Spatrick 
707*061da546Spatrick     response.PutChar(';');
708*061da546Spatrick   }
709*061da546Spatrick 
710*061da546Spatrick   //
711*061da546Spatrick   // Expedite registers.
712*061da546Spatrick   //
713*061da546Spatrick 
714*061da546Spatrick   // Grab the register context.
715*061da546Spatrick   NativeRegisterContext& reg_ctx = thread->GetRegisterContext();
716*061da546Spatrick   // Expedite all registers in the first register set (i.e. should be GPRs)
717*061da546Spatrick   // that are not contained in other registers.
718*061da546Spatrick   const RegisterSet *reg_set_p;
719*061da546Spatrick   if (reg_ctx.GetRegisterSetCount() > 0 &&
720*061da546Spatrick       ((reg_set_p = reg_ctx.GetRegisterSet(0)) != nullptr)) {
721*061da546Spatrick     LLDB_LOGF(log,
722*061da546Spatrick               "GDBRemoteCommunicationServerLLGS::%s expediting registers "
723*061da546Spatrick               "from set '%s' (registers set count: %zu)",
724*061da546Spatrick               __FUNCTION__, reg_set_p->name ? reg_set_p->name : "<unnamed-set>",
725*061da546Spatrick               reg_set_p->num_registers);
726*061da546Spatrick 
727*061da546Spatrick     for (const uint32_t *reg_num_p = reg_set_p->registers;
728*061da546Spatrick          *reg_num_p != LLDB_INVALID_REGNUM; ++reg_num_p) {
729*061da546Spatrick       const RegisterInfo *const reg_info_p =
730*061da546Spatrick           reg_ctx.GetRegisterInfoAtIndex(*reg_num_p);
731*061da546Spatrick       if (reg_info_p == nullptr) {
732*061da546Spatrick         LLDB_LOGF(log,
733*061da546Spatrick                   "GDBRemoteCommunicationServerLLGS::%s failed to get "
734*061da546Spatrick                   "register info for register set '%s', register index "
735*061da546Spatrick                   "%" PRIu32,
736*061da546Spatrick                   __FUNCTION__,
737*061da546Spatrick                   reg_set_p->name ? reg_set_p->name : "<unnamed-set>",
738*061da546Spatrick                   *reg_num_p);
739*061da546Spatrick       } else if (reg_info_p->value_regs == nullptr) {
740*061da546Spatrick         // Only expediate registers that are not contained in other registers.
741*061da546Spatrick         RegisterValue reg_value;
742*061da546Spatrick         Status error = reg_ctx.ReadRegister(reg_info_p, reg_value);
743*061da546Spatrick         if (error.Success()) {
744*061da546Spatrick           response.Printf("%.02x:", *reg_num_p);
745*061da546Spatrick           WriteRegisterValueInHexFixedWidth(response, reg_ctx, *reg_info_p,
746*061da546Spatrick                                             &reg_value, lldb::eByteOrderBig);
747*061da546Spatrick           response.PutChar(';');
748*061da546Spatrick         } else {
749*061da546Spatrick           LLDB_LOGF(log,
750*061da546Spatrick                     "GDBRemoteCommunicationServerLLGS::%s failed to read "
751*061da546Spatrick                     "register '%s' index %" PRIu32 ": %s",
752*061da546Spatrick                     __FUNCTION__,
753*061da546Spatrick                     reg_info_p->name ? reg_info_p->name : "<unnamed-register>",
754*061da546Spatrick                     *reg_num_p, error.AsCString());
755*061da546Spatrick         }
756*061da546Spatrick       }
757*061da546Spatrick     }
758*061da546Spatrick   }
759*061da546Spatrick 
760*061da546Spatrick   const char *reason_str = GetStopReasonString(tid_stop_info.reason);
761*061da546Spatrick   if (reason_str != nullptr) {
762*061da546Spatrick     response.Printf("reason:%s;", reason_str);
763*061da546Spatrick   }
764*061da546Spatrick 
765*061da546Spatrick   if (!description.empty()) {
766*061da546Spatrick     // Description may contains special chars, send as hex bytes.
767*061da546Spatrick     response.PutCString("description:");
768*061da546Spatrick     response.PutStringAsRawHex8(description);
769*061da546Spatrick     response.PutChar(';');
770*061da546Spatrick   } else if ((tid_stop_info.reason == eStopReasonException) &&
771*061da546Spatrick              tid_stop_info.details.exception.type) {
772*061da546Spatrick     response.PutCString("metype:");
773*061da546Spatrick     response.PutHex64(tid_stop_info.details.exception.type);
774*061da546Spatrick     response.PutCString(";mecount:");
775*061da546Spatrick     response.PutHex32(tid_stop_info.details.exception.data_count);
776*061da546Spatrick     response.PutChar(';');
777*061da546Spatrick 
778*061da546Spatrick     for (uint32_t i = 0; i < tid_stop_info.details.exception.data_count; ++i) {
779*061da546Spatrick       response.PutCString("medata:");
780*061da546Spatrick       response.PutHex64(tid_stop_info.details.exception.data[i]);
781*061da546Spatrick       response.PutChar(';');
782*061da546Spatrick     }
783*061da546Spatrick   }
784*061da546Spatrick 
785*061da546Spatrick   return SendPacketNoLock(response.GetString());
786*061da546Spatrick }
787*061da546Spatrick 
788*061da546Spatrick void GDBRemoteCommunicationServerLLGS::HandleInferiorState_Exited(
789*061da546Spatrick     NativeProcessProtocol *process) {
790*061da546Spatrick   assert(process && "process cannot be NULL");
791*061da546Spatrick 
792*061da546Spatrick   Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
793*061da546Spatrick   LLDB_LOGF(log, "GDBRemoteCommunicationServerLLGS::%s called", __FUNCTION__);
794*061da546Spatrick 
795*061da546Spatrick   PacketResult result = SendStopReasonForState(StateType::eStateExited);
796*061da546Spatrick   if (result != PacketResult::Success) {
797*061da546Spatrick     LLDB_LOGF(log,
798*061da546Spatrick               "GDBRemoteCommunicationServerLLGS::%s failed to send stop "
799*061da546Spatrick               "notification for PID %" PRIu64 ", state: eStateExited",
800*061da546Spatrick               __FUNCTION__, process->GetID());
801*061da546Spatrick   }
802*061da546Spatrick 
803*061da546Spatrick   // Close the pipe to the inferior terminal i/o if we launched it and set one
804*061da546Spatrick   // up.
805*061da546Spatrick   MaybeCloseInferiorTerminalConnection();
806*061da546Spatrick 
807*061da546Spatrick   // We are ready to exit the debug monitor.
808*061da546Spatrick   m_exit_now = true;
809*061da546Spatrick   m_mainloop.RequestTermination();
810*061da546Spatrick }
811*061da546Spatrick 
812*061da546Spatrick void GDBRemoteCommunicationServerLLGS::HandleInferiorState_Stopped(
813*061da546Spatrick     NativeProcessProtocol *process) {
814*061da546Spatrick   assert(process && "process cannot be NULL");
815*061da546Spatrick 
816*061da546Spatrick   Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
817*061da546Spatrick   LLDB_LOGF(log, "GDBRemoteCommunicationServerLLGS::%s called", __FUNCTION__);
818*061da546Spatrick 
819*061da546Spatrick   // Send the stop reason unless this is the stop after the launch or attach.
820*061da546Spatrick   switch (m_inferior_prev_state) {
821*061da546Spatrick   case eStateLaunching:
822*061da546Spatrick   case eStateAttaching:
823*061da546Spatrick     // Don't send anything per debugserver behavior.
824*061da546Spatrick     break;
825*061da546Spatrick   default:
826*061da546Spatrick     // In all other cases, send the stop reason.
827*061da546Spatrick     PacketResult result = SendStopReasonForState(StateType::eStateStopped);
828*061da546Spatrick     if (result != PacketResult::Success) {
829*061da546Spatrick       LLDB_LOGF(log,
830*061da546Spatrick                 "GDBRemoteCommunicationServerLLGS::%s failed to send stop "
831*061da546Spatrick                 "notification for PID %" PRIu64 ", state: eStateExited",
832*061da546Spatrick                 __FUNCTION__, process->GetID());
833*061da546Spatrick     }
834*061da546Spatrick     break;
835*061da546Spatrick   }
836*061da546Spatrick }
837*061da546Spatrick 
838*061da546Spatrick void GDBRemoteCommunicationServerLLGS::ProcessStateChanged(
839*061da546Spatrick     NativeProcessProtocol *process, lldb::StateType state) {
840*061da546Spatrick   assert(process && "process cannot be NULL");
841*061da546Spatrick   Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
842*061da546Spatrick   if (log) {
843*061da546Spatrick     LLDB_LOGF(log,
844*061da546Spatrick               "GDBRemoteCommunicationServerLLGS::%s called with "
845*061da546Spatrick               "NativeProcessProtocol pid %" PRIu64 ", state: %s",
846*061da546Spatrick               __FUNCTION__, process->GetID(), StateAsCString(state));
847*061da546Spatrick   }
848*061da546Spatrick 
849*061da546Spatrick   switch (state) {
850*061da546Spatrick   case StateType::eStateRunning:
851*061da546Spatrick     StartSTDIOForwarding();
852*061da546Spatrick     break;
853*061da546Spatrick 
854*061da546Spatrick   case StateType::eStateStopped:
855*061da546Spatrick     // Make sure we get all of the pending stdout/stderr from the inferior and
856*061da546Spatrick     // send it to the lldb host before we send the state change notification
857*061da546Spatrick     SendProcessOutput();
858*061da546Spatrick     // Then stop the forwarding, so that any late output (see llvm.org/pr25652)
859*061da546Spatrick     // does not interfere with our protocol.
860*061da546Spatrick     StopSTDIOForwarding();
861*061da546Spatrick     HandleInferiorState_Stopped(process);
862*061da546Spatrick     break;
863*061da546Spatrick 
864*061da546Spatrick   case StateType::eStateExited:
865*061da546Spatrick     // Same as above
866*061da546Spatrick     SendProcessOutput();
867*061da546Spatrick     StopSTDIOForwarding();
868*061da546Spatrick     HandleInferiorState_Exited(process);
869*061da546Spatrick     break;
870*061da546Spatrick 
871*061da546Spatrick   default:
872*061da546Spatrick     if (log) {
873*061da546Spatrick       LLDB_LOGF(log,
874*061da546Spatrick                 "GDBRemoteCommunicationServerLLGS::%s didn't handle state "
875*061da546Spatrick                 "change for pid %" PRIu64 ", new state: %s",
876*061da546Spatrick                 __FUNCTION__, process->GetID(), StateAsCString(state));
877*061da546Spatrick     }
878*061da546Spatrick     break;
879*061da546Spatrick   }
880*061da546Spatrick 
881*061da546Spatrick   // Remember the previous state reported to us.
882*061da546Spatrick   m_inferior_prev_state = state;
883*061da546Spatrick }
884*061da546Spatrick 
885*061da546Spatrick void GDBRemoteCommunicationServerLLGS::DidExec(NativeProcessProtocol *process) {
886*061da546Spatrick   ClearProcessSpecificData();
887*061da546Spatrick }
888*061da546Spatrick 
889*061da546Spatrick void GDBRemoteCommunicationServerLLGS::DataAvailableCallback() {
890*061da546Spatrick   Log *log(GetLogIfAnyCategoriesSet(GDBR_LOG_COMM));
891*061da546Spatrick 
892*061da546Spatrick   if (!m_handshake_completed) {
893*061da546Spatrick     if (!HandshakeWithClient()) {
894*061da546Spatrick       LLDB_LOGF(log,
895*061da546Spatrick                 "GDBRemoteCommunicationServerLLGS::%s handshake with "
896*061da546Spatrick                 "client failed, exiting",
897*061da546Spatrick                 __FUNCTION__);
898*061da546Spatrick       m_mainloop.RequestTermination();
899*061da546Spatrick       return;
900*061da546Spatrick     }
901*061da546Spatrick     m_handshake_completed = true;
902*061da546Spatrick   }
903*061da546Spatrick 
904*061da546Spatrick   bool interrupt = false;
905*061da546Spatrick   bool done = false;
906*061da546Spatrick   Status error;
907*061da546Spatrick   while (true) {
908*061da546Spatrick     const PacketResult result = GetPacketAndSendResponse(
909*061da546Spatrick         std::chrono::microseconds(0), error, interrupt, done);
910*061da546Spatrick     if (result == PacketResult::ErrorReplyTimeout)
911*061da546Spatrick       break; // No more packets in the queue
912*061da546Spatrick 
913*061da546Spatrick     if ((result != PacketResult::Success)) {
914*061da546Spatrick       LLDB_LOGF(log,
915*061da546Spatrick                 "GDBRemoteCommunicationServerLLGS::%s processing a packet "
916*061da546Spatrick                 "failed: %s",
917*061da546Spatrick                 __FUNCTION__, error.AsCString());
918*061da546Spatrick       m_mainloop.RequestTermination();
919*061da546Spatrick       break;
920*061da546Spatrick     }
921*061da546Spatrick   }
922*061da546Spatrick }
923*061da546Spatrick 
924*061da546Spatrick Status GDBRemoteCommunicationServerLLGS::InitializeConnection(
925*061da546Spatrick     std::unique_ptr<Connection> &&connection) {
926*061da546Spatrick   IOObjectSP read_object_sp = connection->GetReadObject();
927*061da546Spatrick   GDBRemoteCommunicationServer::SetConnection(connection.release());
928*061da546Spatrick 
929*061da546Spatrick   Status error;
930*061da546Spatrick   m_network_handle_up = m_mainloop.RegisterReadObject(
931*061da546Spatrick       read_object_sp, [this](MainLoopBase &) { DataAvailableCallback(); },
932*061da546Spatrick       error);
933*061da546Spatrick   return error;
934*061da546Spatrick }
935*061da546Spatrick 
936*061da546Spatrick GDBRemoteCommunication::PacketResult
937*061da546Spatrick GDBRemoteCommunicationServerLLGS::SendONotification(const char *buffer,
938*061da546Spatrick                                                     uint32_t len) {
939*061da546Spatrick   if ((buffer == nullptr) || (len == 0)) {
940*061da546Spatrick     // Nothing to send.
941*061da546Spatrick     return PacketResult::Success;
942*061da546Spatrick   }
943*061da546Spatrick 
944*061da546Spatrick   StreamString response;
945*061da546Spatrick   response.PutChar('O');
946*061da546Spatrick   response.PutBytesAsRawHex8(buffer, len);
947*061da546Spatrick 
948*061da546Spatrick   return SendPacketNoLock(response.GetString());
949*061da546Spatrick }
950*061da546Spatrick 
951*061da546Spatrick Status GDBRemoteCommunicationServerLLGS::SetSTDIOFileDescriptor(int fd) {
952*061da546Spatrick   Status error;
953*061da546Spatrick 
954*061da546Spatrick   // Set up the reading/handling of process I/O
955*061da546Spatrick   std::unique_ptr<ConnectionFileDescriptor> conn_up(
956*061da546Spatrick       new ConnectionFileDescriptor(fd, true));
957*061da546Spatrick   if (!conn_up) {
958*061da546Spatrick     error.SetErrorString("failed to create ConnectionFileDescriptor");
959*061da546Spatrick     return error;
960*061da546Spatrick   }
961*061da546Spatrick 
962*061da546Spatrick   m_stdio_communication.SetCloseOnEOF(false);
963*061da546Spatrick   m_stdio_communication.SetConnection(conn_up.release());
964*061da546Spatrick   if (!m_stdio_communication.IsConnected()) {
965*061da546Spatrick     error.SetErrorString(
966*061da546Spatrick         "failed to set connection for inferior I/O communication");
967*061da546Spatrick     return error;
968*061da546Spatrick   }
969*061da546Spatrick 
970*061da546Spatrick   return Status();
971*061da546Spatrick }
972*061da546Spatrick 
973*061da546Spatrick void GDBRemoteCommunicationServerLLGS::StartSTDIOForwarding() {
974*061da546Spatrick   // Don't forward if not connected (e.g. when attaching).
975*061da546Spatrick   if (!m_stdio_communication.IsConnected())
976*061da546Spatrick     return;
977*061da546Spatrick 
978*061da546Spatrick   Status error;
979*061da546Spatrick   lldbassert(!m_stdio_handle_up);
980*061da546Spatrick   m_stdio_handle_up = m_mainloop.RegisterReadObject(
981*061da546Spatrick       m_stdio_communication.GetConnection()->GetReadObject(),
982*061da546Spatrick       [this](MainLoopBase &) { SendProcessOutput(); }, error);
983*061da546Spatrick 
984*061da546Spatrick   if (!m_stdio_handle_up) {
985*061da546Spatrick     // Not much we can do about the failure. Log it and continue without
986*061da546Spatrick     // forwarding.
987*061da546Spatrick     if (Log *log = GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS))
988*061da546Spatrick       LLDB_LOGF(log,
989*061da546Spatrick                 "GDBRemoteCommunicationServerLLGS::%s Failed to set up stdio "
990*061da546Spatrick                 "forwarding: %s",
991*061da546Spatrick                 __FUNCTION__, error.AsCString());
992*061da546Spatrick   }
993*061da546Spatrick }
994*061da546Spatrick 
995*061da546Spatrick void GDBRemoteCommunicationServerLLGS::StopSTDIOForwarding() {
996*061da546Spatrick   m_stdio_handle_up.reset();
997*061da546Spatrick }
998*061da546Spatrick 
999*061da546Spatrick void GDBRemoteCommunicationServerLLGS::SendProcessOutput() {
1000*061da546Spatrick   char buffer[1024];
1001*061da546Spatrick   ConnectionStatus status;
1002*061da546Spatrick   Status error;
1003*061da546Spatrick   while (true) {
1004*061da546Spatrick     size_t bytes_read = m_stdio_communication.Read(
1005*061da546Spatrick         buffer, sizeof buffer, std::chrono::microseconds(0), status, &error);
1006*061da546Spatrick     switch (status) {
1007*061da546Spatrick     case eConnectionStatusSuccess:
1008*061da546Spatrick       SendONotification(buffer, bytes_read);
1009*061da546Spatrick       break;
1010*061da546Spatrick     case eConnectionStatusLostConnection:
1011*061da546Spatrick     case eConnectionStatusEndOfFile:
1012*061da546Spatrick     case eConnectionStatusError:
1013*061da546Spatrick     case eConnectionStatusNoConnection:
1014*061da546Spatrick       if (Log *log = GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS))
1015*061da546Spatrick         LLDB_LOGF(log,
1016*061da546Spatrick                   "GDBRemoteCommunicationServerLLGS::%s Stopping stdio "
1017*061da546Spatrick                   "forwarding as communication returned status %d (error: "
1018*061da546Spatrick                   "%s)",
1019*061da546Spatrick                   __FUNCTION__, status, error.AsCString());
1020*061da546Spatrick       m_stdio_handle_up.reset();
1021*061da546Spatrick       return;
1022*061da546Spatrick 
1023*061da546Spatrick     case eConnectionStatusInterrupted:
1024*061da546Spatrick     case eConnectionStatusTimedOut:
1025*061da546Spatrick       return;
1026*061da546Spatrick     }
1027*061da546Spatrick   }
1028*061da546Spatrick }
1029*061da546Spatrick 
1030*061da546Spatrick GDBRemoteCommunication::PacketResult
1031*061da546Spatrick GDBRemoteCommunicationServerLLGS::Handle_jTraceStart(
1032*061da546Spatrick     StringExtractorGDBRemote &packet) {
1033*061da546Spatrick   Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
1034*061da546Spatrick   // Fail if we don't have a current process.
1035*061da546Spatrick   if (!m_debugged_process_up ||
1036*061da546Spatrick       (m_debugged_process_up->GetID() == LLDB_INVALID_PROCESS_ID))
1037*061da546Spatrick     return SendErrorResponse(68);
1038*061da546Spatrick 
1039*061da546Spatrick   if (!packet.ConsumeFront("jTraceStart:"))
1040*061da546Spatrick     return SendIllFormedResponse(packet, "jTraceStart: Ill formed packet ");
1041*061da546Spatrick 
1042*061da546Spatrick   TraceOptions options;
1043*061da546Spatrick   uint64_t type = std::numeric_limits<uint64_t>::max();
1044*061da546Spatrick   uint64_t buffersize = std::numeric_limits<uint64_t>::max();
1045*061da546Spatrick   lldb::tid_t tid = LLDB_INVALID_THREAD_ID;
1046*061da546Spatrick   uint64_t metabuffersize = std::numeric_limits<uint64_t>::max();
1047*061da546Spatrick 
1048*061da546Spatrick   auto json_object = StructuredData::ParseJSON(packet.Peek());
1049*061da546Spatrick 
1050*061da546Spatrick   if (!json_object ||
1051*061da546Spatrick       json_object->GetType() != lldb::eStructuredDataTypeDictionary)
1052*061da546Spatrick     return SendIllFormedResponse(packet, "jTraceStart: Ill formed packet ");
1053*061da546Spatrick 
1054*061da546Spatrick   auto json_dict = json_object->GetAsDictionary();
1055*061da546Spatrick 
1056*061da546Spatrick   json_dict->GetValueForKeyAsInteger("metabuffersize", metabuffersize);
1057*061da546Spatrick   options.setMetaDataBufferSize(metabuffersize);
1058*061da546Spatrick 
1059*061da546Spatrick   json_dict->GetValueForKeyAsInteger("buffersize", buffersize);
1060*061da546Spatrick   options.setTraceBufferSize(buffersize);
1061*061da546Spatrick 
1062*061da546Spatrick   json_dict->GetValueForKeyAsInteger("type", type);
1063*061da546Spatrick   options.setType(static_cast<lldb::TraceType>(type));
1064*061da546Spatrick 
1065*061da546Spatrick   json_dict->GetValueForKeyAsInteger("threadid", tid);
1066*061da546Spatrick   options.setThreadID(tid);
1067*061da546Spatrick 
1068*061da546Spatrick   StructuredData::ObjectSP custom_params_sp =
1069*061da546Spatrick       json_dict->GetValueForKey("params");
1070*061da546Spatrick   if (custom_params_sp &&
1071*061da546Spatrick       custom_params_sp->GetType() != lldb::eStructuredDataTypeDictionary)
1072*061da546Spatrick     return SendIllFormedResponse(packet, "jTraceStart: Ill formed packet ");
1073*061da546Spatrick 
1074*061da546Spatrick   options.setTraceParams(
1075*061da546Spatrick       static_pointer_cast<StructuredData::Dictionary>(custom_params_sp));
1076*061da546Spatrick 
1077*061da546Spatrick   if (buffersize == std::numeric_limits<uint64_t>::max() ||
1078*061da546Spatrick       type != lldb::TraceType::eTraceTypeProcessorTrace) {
1079*061da546Spatrick     LLDB_LOG(log, "Ill formed packet buffersize = {0} type = {1}", buffersize,
1080*061da546Spatrick              type);
1081*061da546Spatrick     return SendIllFormedResponse(packet, "JTrace:start: Ill formed packet ");
1082*061da546Spatrick   }
1083*061da546Spatrick 
1084*061da546Spatrick   Status error;
1085*061da546Spatrick   lldb::user_id_t uid = LLDB_INVALID_UID;
1086*061da546Spatrick   uid = m_debugged_process_up->StartTrace(options, error);
1087*061da546Spatrick   LLDB_LOG(log, "uid is {0} , error is {1}", uid, error.GetError());
1088*061da546Spatrick   if (error.Fail())
1089*061da546Spatrick     return SendErrorResponse(error);
1090*061da546Spatrick 
1091*061da546Spatrick   StreamGDBRemote response;
1092*061da546Spatrick   response.Printf("%" PRIx64, uid);
1093*061da546Spatrick   return SendPacketNoLock(response.GetString());
1094*061da546Spatrick }
1095*061da546Spatrick 
1096*061da546Spatrick GDBRemoteCommunication::PacketResult
1097*061da546Spatrick GDBRemoteCommunicationServerLLGS::Handle_jTraceStop(
1098*061da546Spatrick     StringExtractorGDBRemote &packet) {
1099*061da546Spatrick   // Fail if we don't have a current process.
1100*061da546Spatrick   if (!m_debugged_process_up ||
1101*061da546Spatrick       (m_debugged_process_up->GetID() == LLDB_INVALID_PROCESS_ID))
1102*061da546Spatrick     return SendErrorResponse(68);
1103*061da546Spatrick 
1104*061da546Spatrick   if (!packet.ConsumeFront("jTraceStop:"))
1105*061da546Spatrick     return SendIllFormedResponse(packet, "jTraceStop: Ill formed packet ");
1106*061da546Spatrick 
1107*061da546Spatrick   lldb::user_id_t uid = LLDB_INVALID_UID;
1108*061da546Spatrick   lldb::tid_t tid = LLDB_INVALID_THREAD_ID;
1109*061da546Spatrick 
1110*061da546Spatrick   auto json_object = StructuredData::ParseJSON(packet.Peek());
1111*061da546Spatrick 
1112*061da546Spatrick   if (!json_object ||
1113*061da546Spatrick       json_object->GetType() != lldb::eStructuredDataTypeDictionary)
1114*061da546Spatrick     return SendIllFormedResponse(packet, "jTraceStop: Ill formed packet ");
1115*061da546Spatrick 
1116*061da546Spatrick   auto json_dict = json_object->GetAsDictionary();
1117*061da546Spatrick 
1118*061da546Spatrick   if (!json_dict->GetValueForKeyAsInteger("traceid", uid))
1119*061da546Spatrick     return SendIllFormedResponse(packet, "jTraceStop: Ill formed packet ");
1120*061da546Spatrick 
1121*061da546Spatrick   json_dict->GetValueForKeyAsInteger("threadid", tid);
1122*061da546Spatrick 
1123*061da546Spatrick   Status error = m_debugged_process_up->StopTrace(uid, tid);
1124*061da546Spatrick 
1125*061da546Spatrick   if (error.Fail())
1126*061da546Spatrick     return SendErrorResponse(error);
1127*061da546Spatrick 
1128*061da546Spatrick   return SendOKResponse();
1129*061da546Spatrick }
1130*061da546Spatrick 
1131*061da546Spatrick GDBRemoteCommunication::PacketResult
1132*061da546Spatrick GDBRemoteCommunicationServerLLGS::Handle_jTraceConfigRead(
1133*061da546Spatrick     StringExtractorGDBRemote &packet) {
1134*061da546Spatrick 
1135*061da546Spatrick   // Fail if we don't have a current process.
1136*061da546Spatrick   if (!m_debugged_process_up ||
1137*061da546Spatrick       (m_debugged_process_up->GetID() == LLDB_INVALID_PROCESS_ID))
1138*061da546Spatrick     return SendErrorResponse(68);
1139*061da546Spatrick 
1140*061da546Spatrick   if (!packet.ConsumeFront("jTraceConfigRead:"))
1141*061da546Spatrick     return SendIllFormedResponse(packet,
1142*061da546Spatrick                                  "jTraceConfigRead: Ill formed packet ");
1143*061da546Spatrick 
1144*061da546Spatrick   lldb::user_id_t uid = LLDB_INVALID_UID;
1145*061da546Spatrick   lldb::tid_t threadid = LLDB_INVALID_THREAD_ID;
1146*061da546Spatrick 
1147*061da546Spatrick   auto json_object = StructuredData::ParseJSON(packet.Peek());
1148*061da546Spatrick 
1149*061da546Spatrick   if (!json_object ||
1150*061da546Spatrick       json_object->GetType() != lldb::eStructuredDataTypeDictionary)
1151*061da546Spatrick     return SendIllFormedResponse(packet,
1152*061da546Spatrick                                  "jTraceConfigRead: Ill formed packet ");
1153*061da546Spatrick 
1154*061da546Spatrick   auto json_dict = json_object->GetAsDictionary();
1155*061da546Spatrick 
1156*061da546Spatrick   if (!json_dict->GetValueForKeyAsInteger("traceid", uid))
1157*061da546Spatrick     return SendIllFormedResponse(packet,
1158*061da546Spatrick                                  "jTraceConfigRead: Ill formed packet ");
1159*061da546Spatrick 
1160*061da546Spatrick   json_dict->GetValueForKeyAsInteger("threadid", threadid);
1161*061da546Spatrick 
1162*061da546Spatrick   TraceOptions options;
1163*061da546Spatrick   StreamGDBRemote response;
1164*061da546Spatrick 
1165*061da546Spatrick   options.setThreadID(threadid);
1166*061da546Spatrick   Status error = m_debugged_process_up->GetTraceConfig(uid, options);
1167*061da546Spatrick 
1168*061da546Spatrick   if (error.Fail())
1169*061da546Spatrick     return SendErrorResponse(error);
1170*061da546Spatrick 
1171*061da546Spatrick   StreamGDBRemote escaped_response;
1172*061da546Spatrick   StructuredData::Dictionary json_packet;
1173*061da546Spatrick 
1174*061da546Spatrick   json_packet.AddIntegerItem("type", options.getType());
1175*061da546Spatrick   json_packet.AddIntegerItem("buffersize", options.getTraceBufferSize());
1176*061da546Spatrick   json_packet.AddIntegerItem("metabuffersize", options.getMetaDataBufferSize());
1177*061da546Spatrick 
1178*061da546Spatrick   StructuredData::DictionarySP custom_params = options.getTraceParams();
1179*061da546Spatrick   if (custom_params)
1180*061da546Spatrick     json_packet.AddItem("params", custom_params);
1181*061da546Spatrick 
1182*061da546Spatrick   StreamString json_string;
1183*061da546Spatrick   json_packet.Dump(json_string, false);
1184*061da546Spatrick   escaped_response.PutEscapedBytes(json_string.GetData(),
1185*061da546Spatrick                                    json_string.GetSize());
1186*061da546Spatrick   return SendPacketNoLock(escaped_response.GetString());
1187*061da546Spatrick }
1188*061da546Spatrick 
1189*061da546Spatrick GDBRemoteCommunication::PacketResult
1190*061da546Spatrick GDBRemoteCommunicationServerLLGS::Handle_jTraceRead(
1191*061da546Spatrick     StringExtractorGDBRemote &packet) {
1192*061da546Spatrick 
1193*061da546Spatrick   // Fail if we don't have a current process.
1194*061da546Spatrick   if (!m_debugged_process_up ||
1195*061da546Spatrick       (m_debugged_process_up->GetID() == LLDB_INVALID_PROCESS_ID))
1196*061da546Spatrick     return SendErrorResponse(68);
1197*061da546Spatrick 
1198*061da546Spatrick   enum PacketType { MetaData, BufferData };
1199*061da546Spatrick   PacketType tracetype = MetaData;
1200*061da546Spatrick 
1201*061da546Spatrick   if (packet.ConsumeFront("jTraceBufferRead:"))
1202*061da546Spatrick     tracetype = BufferData;
1203*061da546Spatrick   else if (packet.ConsumeFront("jTraceMetaRead:"))
1204*061da546Spatrick     tracetype = MetaData;
1205*061da546Spatrick   else {
1206*061da546Spatrick     return SendIllFormedResponse(packet, "jTrace: Ill formed packet ");
1207*061da546Spatrick   }
1208*061da546Spatrick 
1209*061da546Spatrick   lldb::user_id_t uid = LLDB_INVALID_UID;
1210*061da546Spatrick 
1211*061da546Spatrick   uint64_t byte_count = std::numeric_limits<uint64_t>::max();
1212*061da546Spatrick   lldb::tid_t tid = LLDB_INVALID_THREAD_ID;
1213*061da546Spatrick   uint64_t offset = std::numeric_limits<uint64_t>::max();
1214*061da546Spatrick 
1215*061da546Spatrick   auto json_object = StructuredData::ParseJSON(packet.Peek());
1216*061da546Spatrick 
1217*061da546Spatrick   if (!json_object ||
1218*061da546Spatrick       json_object->GetType() != lldb::eStructuredDataTypeDictionary)
1219*061da546Spatrick     return SendIllFormedResponse(packet, "jTrace: Ill formed packet ");
1220*061da546Spatrick 
1221*061da546Spatrick   auto json_dict = json_object->GetAsDictionary();
1222*061da546Spatrick 
1223*061da546Spatrick   if (!json_dict->GetValueForKeyAsInteger("traceid", uid) ||
1224*061da546Spatrick       !json_dict->GetValueForKeyAsInteger("offset", offset) ||
1225*061da546Spatrick       !json_dict->GetValueForKeyAsInteger("buffersize", byte_count))
1226*061da546Spatrick     return SendIllFormedResponse(packet, "jTrace: Ill formed packet ");
1227*061da546Spatrick 
1228*061da546Spatrick   json_dict->GetValueForKeyAsInteger("threadid", tid);
1229*061da546Spatrick 
1230*061da546Spatrick   // Allocate the response buffer.
1231*061da546Spatrick   std::unique_ptr<uint8_t[]> buffer (new (std::nothrow) uint8_t[byte_count]);
1232*061da546Spatrick   if (!buffer)
1233*061da546Spatrick     return SendErrorResponse(0x78);
1234*061da546Spatrick 
1235*061da546Spatrick   StreamGDBRemote response;
1236*061da546Spatrick   Status error;
1237*061da546Spatrick   llvm::MutableArrayRef<uint8_t> buf(buffer.get(), byte_count);
1238*061da546Spatrick 
1239*061da546Spatrick   if (tracetype == BufferData)
1240*061da546Spatrick     error = m_debugged_process_up->GetData(uid, tid, buf, offset);
1241*061da546Spatrick   else if (tracetype == MetaData)
1242*061da546Spatrick     error = m_debugged_process_up->GetMetaData(uid, tid, buf, offset);
1243*061da546Spatrick 
1244*061da546Spatrick   if (error.Fail())
1245*061da546Spatrick     return SendErrorResponse(error);
1246*061da546Spatrick 
1247*061da546Spatrick   for (auto i : buf)
1248*061da546Spatrick     response.PutHex8(i);
1249*061da546Spatrick 
1250*061da546Spatrick   StreamGDBRemote escaped_response;
1251*061da546Spatrick   escaped_response.PutEscapedBytes(response.GetData(), response.GetSize());
1252*061da546Spatrick   return SendPacketNoLock(escaped_response.GetString());
1253*061da546Spatrick }
1254*061da546Spatrick 
1255*061da546Spatrick GDBRemoteCommunication::PacketResult
1256*061da546Spatrick GDBRemoteCommunicationServerLLGS::Handle_qProcessInfo(
1257*061da546Spatrick     StringExtractorGDBRemote &packet) {
1258*061da546Spatrick   // Fail if we don't have a current process.
1259*061da546Spatrick   if (!m_debugged_process_up ||
1260*061da546Spatrick       (m_debugged_process_up->GetID() == LLDB_INVALID_PROCESS_ID))
1261*061da546Spatrick     return SendErrorResponse(68);
1262*061da546Spatrick 
1263*061da546Spatrick   lldb::pid_t pid = m_debugged_process_up->GetID();
1264*061da546Spatrick 
1265*061da546Spatrick   if (pid == LLDB_INVALID_PROCESS_ID)
1266*061da546Spatrick     return SendErrorResponse(1);
1267*061da546Spatrick 
1268*061da546Spatrick   ProcessInstanceInfo proc_info;
1269*061da546Spatrick   if (!Host::GetProcessInfo(pid, proc_info))
1270*061da546Spatrick     return SendErrorResponse(1);
1271*061da546Spatrick 
1272*061da546Spatrick   StreamString response;
1273*061da546Spatrick   CreateProcessInfoResponse_DebugServerStyle(proc_info, response);
1274*061da546Spatrick   return SendPacketNoLock(response.GetString());
1275*061da546Spatrick }
1276*061da546Spatrick 
1277*061da546Spatrick GDBRemoteCommunication::PacketResult
1278*061da546Spatrick GDBRemoteCommunicationServerLLGS::Handle_qC(StringExtractorGDBRemote &packet) {
1279*061da546Spatrick   // Fail if we don't have a current process.
1280*061da546Spatrick   if (!m_debugged_process_up ||
1281*061da546Spatrick       (m_debugged_process_up->GetID() == LLDB_INVALID_PROCESS_ID))
1282*061da546Spatrick     return SendErrorResponse(68);
1283*061da546Spatrick 
1284*061da546Spatrick   // Make sure we set the current thread so g and p packets return the data the
1285*061da546Spatrick   // gdb will expect.
1286*061da546Spatrick   lldb::tid_t tid = m_debugged_process_up->GetCurrentThreadID();
1287*061da546Spatrick   SetCurrentThreadID(tid);
1288*061da546Spatrick 
1289*061da546Spatrick   NativeThreadProtocol *thread = m_debugged_process_up->GetCurrentThread();
1290*061da546Spatrick   if (!thread)
1291*061da546Spatrick     return SendErrorResponse(69);
1292*061da546Spatrick 
1293*061da546Spatrick   StreamString response;
1294*061da546Spatrick   response.Printf("QC%" PRIx64, thread->GetID());
1295*061da546Spatrick 
1296*061da546Spatrick   return SendPacketNoLock(response.GetString());
1297*061da546Spatrick }
1298*061da546Spatrick 
1299*061da546Spatrick GDBRemoteCommunication::PacketResult
1300*061da546Spatrick GDBRemoteCommunicationServerLLGS::Handle_k(StringExtractorGDBRemote &packet) {
1301*061da546Spatrick   Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
1302*061da546Spatrick 
1303*061da546Spatrick   StopSTDIOForwarding();
1304*061da546Spatrick 
1305*061da546Spatrick   if (!m_debugged_process_up) {
1306*061da546Spatrick     LLDB_LOG(log, "No debugged process found.");
1307*061da546Spatrick     return PacketResult::Success;
1308*061da546Spatrick   }
1309*061da546Spatrick 
1310*061da546Spatrick   Status error = m_debugged_process_up->Kill();
1311*061da546Spatrick   if (error.Fail())
1312*061da546Spatrick     LLDB_LOG(log, "Failed to kill debugged process {0}: {1}",
1313*061da546Spatrick              m_debugged_process_up->GetID(), error);
1314*061da546Spatrick 
1315*061da546Spatrick   // No OK response for kill packet.
1316*061da546Spatrick   // return SendOKResponse ();
1317*061da546Spatrick   return PacketResult::Success;
1318*061da546Spatrick }
1319*061da546Spatrick 
1320*061da546Spatrick GDBRemoteCommunication::PacketResult
1321*061da546Spatrick GDBRemoteCommunicationServerLLGS::Handle_QSetDisableASLR(
1322*061da546Spatrick     StringExtractorGDBRemote &packet) {
1323*061da546Spatrick   packet.SetFilePos(::strlen("QSetDisableASLR:"));
1324*061da546Spatrick   if (packet.GetU32(0))
1325*061da546Spatrick     m_process_launch_info.GetFlags().Set(eLaunchFlagDisableASLR);
1326*061da546Spatrick   else
1327*061da546Spatrick     m_process_launch_info.GetFlags().Clear(eLaunchFlagDisableASLR);
1328*061da546Spatrick   return SendOKResponse();
1329*061da546Spatrick }
1330*061da546Spatrick 
1331*061da546Spatrick GDBRemoteCommunication::PacketResult
1332*061da546Spatrick GDBRemoteCommunicationServerLLGS::Handle_QSetWorkingDir(
1333*061da546Spatrick     StringExtractorGDBRemote &packet) {
1334*061da546Spatrick   packet.SetFilePos(::strlen("QSetWorkingDir:"));
1335*061da546Spatrick   std::string path;
1336*061da546Spatrick   packet.GetHexByteString(path);
1337*061da546Spatrick   m_process_launch_info.SetWorkingDirectory(FileSpec(path));
1338*061da546Spatrick   return SendOKResponse();
1339*061da546Spatrick }
1340*061da546Spatrick 
1341*061da546Spatrick GDBRemoteCommunication::PacketResult
1342*061da546Spatrick GDBRemoteCommunicationServerLLGS::Handle_qGetWorkingDir(
1343*061da546Spatrick     StringExtractorGDBRemote &packet) {
1344*061da546Spatrick   FileSpec working_dir{m_process_launch_info.GetWorkingDirectory()};
1345*061da546Spatrick   if (working_dir) {
1346*061da546Spatrick     StreamString response;
1347*061da546Spatrick     response.PutStringAsRawHex8(working_dir.GetCString());
1348*061da546Spatrick     return SendPacketNoLock(response.GetString());
1349*061da546Spatrick   }
1350*061da546Spatrick 
1351*061da546Spatrick   return SendErrorResponse(14);
1352*061da546Spatrick }
1353*061da546Spatrick 
1354*061da546Spatrick GDBRemoteCommunication::PacketResult
1355*061da546Spatrick GDBRemoteCommunicationServerLLGS::Handle_C(StringExtractorGDBRemote &packet) {
1356*061da546Spatrick   Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS | LIBLLDB_LOG_THREAD));
1357*061da546Spatrick   LLDB_LOGF(log, "GDBRemoteCommunicationServerLLGS::%s called", __FUNCTION__);
1358*061da546Spatrick 
1359*061da546Spatrick   // Ensure we have a native process.
1360*061da546Spatrick   if (!m_debugged_process_up) {
1361*061da546Spatrick     LLDB_LOGF(log,
1362*061da546Spatrick               "GDBRemoteCommunicationServerLLGS::%s no debugged process "
1363*061da546Spatrick               "shared pointer",
1364*061da546Spatrick               __FUNCTION__);
1365*061da546Spatrick     return SendErrorResponse(0x36);
1366*061da546Spatrick   }
1367*061da546Spatrick 
1368*061da546Spatrick   // Pull out the signal number.
1369*061da546Spatrick   packet.SetFilePos(::strlen("C"));
1370*061da546Spatrick   if (packet.GetBytesLeft() < 1) {
1371*061da546Spatrick     // Shouldn't be using a C without a signal.
1372*061da546Spatrick     return SendIllFormedResponse(packet, "C packet specified without signal.");
1373*061da546Spatrick   }
1374*061da546Spatrick   const uint32_t signo =
1375*061da546Spatrick       packet.GetHexMaxU32(false, std::numeric_limits<uint32_t>::max());
1376*061da546Spatrick   if (signo == std::numeric_limits<uint32_t>::max())
1377*061da546Spatrick     return SendIllFormedResponse(packet, "failed to parse signal number");
1378*061da546Spatrick 
1379*061da546Spatrick   // Handle optional continue address.
1380*061da546Spatrick   if (packet.GetBytesLeft() > 0) {
1381*061da546Spatrick     // FIXME add continue at address support for $C{signo}[;{continue-address}].
1382*061da546Spatrick     if (*packet.Peek() == ';')
1383*061da546Spatrick       return SendUnimplementedResponse(packet.GetStringRef().data());
1384*061da546Spatrick     else
1385*061da546Spatrick       return SendIllFormedResponse(
1386*061da546Spatrick           packet, "unexpected content after $C{signal-number}");
1387*061da546Spatrick   }
1388*061da546Spatrick 
1389*061da546Spatrick   ResumeActionList resume_actions(StateType::eStateRunning,
1390*061da546Spatrick                                   LLDB_INVALID_SIGNAL_NUMBER);
1391*061da546Spatrick   Status error;
1392*061da546Spatrick 
1393*061da546Spatrick   // We have two branches: what to do if a continue thread is specified (in
1394*061da546Spatrick   // which case we target sending the signal to that thread), or when we don't
1395*061da546Spatrick   // have a continue thread set (in which case we send a signal to the
1396*061da546Spatrick   // process).
1397*061da546Spatrick 
1398*061da546Spatrick   // TODO discuss with Greg Clayton, make sure this makes sense.
1399*061da546Spatrick 
1400*061da546Spatrick   lldb::tid_t signal_tid = GetContinueThreadID();
1401*061da546Spatrick   if (signal_tid != LLDB_INVALID_THREAD_ID) {
1402*061da546Spatrick     // The resume action for the continue thread (or all threads if a continue
1403*061da546Spatrick     // thread is not set).
1404*061da546Spatrick     ResumeAction action = {GetContinueThreadID(), StateType::eStateRunning,
1405*061da546Spatrick                            static_cast<int>(signo)};
1406*061da546Spatrick 
1407*061da546Spatrick     // Add the action for the continue thread (or all threads when the continue
1408*061da546Spatrick     // thread isn't present).
1409*061da546Spatrick     resume_actions.Append(action);
1410*061da546Spatrick   } else {
1411*061da546Spatrick     // Send the signal to the process since we weren't targeting a specific
1412*061da546Spatrick     // continue thread with the signal.
1413*061da546Spatrick     error = m_debugged_process_up->Signal(signo);
1414*061da546Spatrick     if (error.Fail()) {
1415*061da546Spatrick       LLDB_LOG(log, "failed to send signal for process {0}: {1}",
1416*061da546Spatrick                m_debugged_process_up->GetID(), error);
1417*061da546Spatrick 
1418*061da546Spatrick       return SendErrorResponse(0x52);
1419*061da546Spatrick     }
1420*061da546Spatrick   }
1421*061da546Spatrick 
1422*061da546Spatrick   // Resume the threads.
1423*061da546Spatrick   error = m_debugged_process_up->Resume(resume_actions);
1424*061da546Spatrick   if (error.Fail()) {
1425*061da546Spatrick     LLDB_LOG(log, "failed to resume threads for process {0}: {1}",
1426*061da546Spatrick              m_debugged_process_up->GetID(), error);
1427*061da546Spatrick 
1428*061da546Spatrick     return SendErrorResponse(0x38);
1429*061da546Spatrick   }
1430*061da546Spatrick 
1431*061da546Spatrick   // Don't send an "OK" packet; response is the stopped/exited message.
1432*061da546Spatrick   return PacketResult::Success;
1433*061da546Spatrick }
1434*061da546Spatrick 
1435*061da546Spatrick GDBRemoteCommunication::PacketResult
1436*061da546Spatrick GDBRemoteCommunicationServerLLGS::Handle_c(StringExtractorGDBRemote &packet) {
1437*061da546Spatrick   Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS | LIBLLDB_LOG_THREAD));
1438*061da546Spatrick   LLDB_LOGF(log, "GDBRemoteCommunicationServerLLGS::%s called", __FUNCTION__);
1439*061da546Spatrick 
1440*061da546Spatrick   packet.SetFilePos(packet.GetFilePos() + ::strlen("c"));
1441*061da546Spatrick 
1442*061da546Spatrick   // For now just support all continue.
1443*061da546Spatrick   const bool has_continue_address = (packet.GetBytesLeft() > 0);
1444*061da546Spatrick   if (has_continue_address) {
1445*061da546Spatrick     LLDB_LOG(log, "not implemented for c[address] variant [{0} remains]",
1446*061da546Spatrick              packet.Peek());
1447*061da546Spatrick     return SendUnimplementedResponse(packet.GetStringRef().data());
1448*061da546Spatrick   }
1449*061da546Spatrick 
1450*061da546Spatrick   // Ensure we have a native process.
1451*061da546Spatrick   if (!m_debugged_process_up) {
1452*061da546Spatrick     LLDB_LOGF(log,
1453*061da546Spatrick               "GDBRemoteCommunicationServerLLGS::%s no debugged process "
1454*061da546Spatrick               "shared pointer",
1455*061da546Spatrick               __FUNCTION__);
1456*061da546Spatrick     return SendErrorResponse(0x36);
1457*061da546Spatrick   }
1458*061da546Spatrick 
1459*061da546Spatrick   // Build the ResumeActionList
1460*061da546Spatrick   ResumeActionList actions(StateType::eStateRunning,
1461*061da546Spatrick                            LLDB_INVALID_SIGNAL_NUMBER);
1462*061da546Spatrick 
1463*061da546Spatrick   Status error = m_debugged_process_up->Resume(actions);
1464*061da546Spatrick   if (error.Fail()) {
1465*061da546Spatrick     LLDB_LOG(log, "c failed for process {0}: {1}",
1466*061da546Spatrick              m_debugged_process_up->GetID(), error);
1467*061da546Spatrick     return SendErrorResponse(GDBRemoteServerError::eErrorResume);
1468*061da546Spatrick   }
1469*061da546Spatrick 
1470*061da546Spatrick   LLDB_LOG(log, "continued process {0}", m_debugged_process_up->GetID());
1471*061da546Spatrick   // No response required from continue.
1472*061da546Spatrick   return PacketResult::Success;
1473*061da546Spatrick }
1474*061da546Spatrick 
1475*061da546Spatrick GDBRemoteCommunication::PacketResult
1476*061da546Spatrick GDBRemoteCommunicationServerLLGS::Handle_vCont_actions(
1477*061da546Spatrick     StringExtractorGDBRemote &packet) {
1478*061da546Spatrick   StreamString response;
1479*061da546Spatrick   response.Printf("vCont;c;C;s;S");
1480*061da546Spatrick 
1481*061da546Spatrick   return SendPacketNoLock(response.GetString());
1482*061da546Spatrick }
1483*061da546Spatrick 
1484*061da546Spatrick GDBRemoteCommunication::PacketResult
1485*061da546Spatrick GDBRemoteCommunicationServerLLGS::Handle_vCont(
1486*061da546Spatrick     StringExtractorGDBRemote &packet) {
1487*061da546Spatrick   Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
1488*061da546Spatrick   LLDB_LOGF(log, "GDBRemoteCommunicationServerLLGS::%s handling vCont packet",
1489*061da546Spatrick             __FUNCTION__);
1490*061da546Spatrick 
1491*061da546Spatrick   packet.SetFilePos(::strlen("vCont"));
1492*061da546Spatrick 
1493*061da546Spatrick   if (packet.GetBytesLeft() == 0) {
1494*061da546Spatrick     LLDB_LOGF(log,
1495*061da546Spatrick               "GDBRemoteCommunicationServerLLGS::%s missing action from "
1496*061da546Spatrick               "vCont package",
1497*061da546Spatrick               __FUNCTION__);
1498*061da546Spatrick     return SendIllFormedResponse(packet, "Missing action from vCont package");
1499*061da546Spatrick   }
1500*061da546Spatrick 
1501*061da546Spatrick   // Check if this is all continue (no options or ";c").
1502*061da546Spatrick   if (::strcmp(packet.Peek(), ";c") == 0) {
1503*061da546Spatrick     // Move past the ';', then do a simple 'c'.
1504*061da546Spatrick     packet.SetFilePos(packet.GetFilePos() + 1);
1505*061da546Spatrick     return Handle_c(packet);
1506*061da546Spatrick   } else if (::strcmp(packet.Peek(), ";s") == 0) {
1507*061da546Spatrick     // Move past the ';', then do a simple 's'.
1508*061da546Spatrick     packet.SetFilePos(packet.GetFilePos() + 1);
1509*061da546Spatrick     return Handle_s(packet);
1510*061da546Spatrick   }
1511*061da546Spatrick 
1512*061da546Spatrick   // Ensure we have a native process.
1513*061da546Spatrick   if (!m_debugged_process_up) {
1514*061da546Spatrick     LLDB_LOG(log, "no debugged process");
1515*061da546Spatrick     return SendErrorResponse(0x36);
1516*061da546Spatrick   }
1517*061da546Spatrick 
1518*061da546Spatrick   ResumeActionList thread_actions;
1519*061da546Spatrick 
1520*061da546Spatrick   while (packet.GetBytesLeft() && *packet.Peek() == ';') {
1521*061da546Spatrick     // Skip the semi-colon.
1522*061da546Spatrick     packet.GetChar();
1523*061da546Spatrick 
1524*061da546Spatrick     // Build up the thread action.
1525*061da546Spatrick     ResumeAction thread_action;
1526*061da546Spatrick     thread_action.tid = LLDB_INVALID_THREAD_ID;
1527*061da546Spatrick     thread_action.state = eStateInvalid;
1528*061da546Spatrick     thread_action.signal = LLDB_INVALID_SIGNAL_NUMBER;
1529*061da546Spatrick 
1530*061da546Spatrick     const char action = packet.GetChar();
1531*061da546Spatrick     switch (action) {
1532*061da546Spatrick     case 'C':
1533*061da546Spatrick       thread_action.signal = packet.GetHexMaxU32(false, 0);
1534*061da546Spatrick       if (thread_action.signal == 0)
1535*061da546Spatrick         return SendIllFormedResponse(
1536*061da546Spatrick             packet, "Could not parse signal in vCont packet C action");
1537*061da546Spatrick       LLVM_FALLTHROUGH;
1538*061da546Spatrick 
1539*061da546Spatrick     case 'c':
1540*061da546Spatrick       // Continue
1541*061da546Spatrick       thread_action.state = eStateRunning;
1542*061da546Spatrick       break;
1543*061da546Spatrick 
1544*061da546Spatrick     case 'S':
1545*061da546Spatrick       thread_action.signal = packet.GetHexMaxU32(false, 0);
1546*061da546Spatrick       if (thread_action.signal == 0)
1547*061da546Spatrick         return SendIllFormedResponse(
1548*061da546Spatrick             packet, "Could not parse signal in vCont packet S action");
1549*061da546Spatrick       LLVM_FALLTHROUGH;
1550*061da546Spatrick 
1551*061da546Spatrick     case 's':
1552*061da546Spatrick       // Step
1553*061da546Spatrick       thread_action.state = eStateStepping;
1554*061da546Spatrick       break;
1555*061da546Spatrick 
1556*061da546Spatrick     default:
1557*061da546Spatrick       return SendIllFormedResponse(packet, "Unsupported vCont action");
1558*061da546Spatrick       break;
1559*061da546Spatrick     }
1560*061da546Spatrick 
1561*061da546Spatrick     // Parse out optional :{thread-id} value.
1562*061da546Spatrick     if (packet.GetBytesLeft() && (*packet.Peek() == ':')) {
1563*061da546Spatrick       // Consume the separator.
1564*061da546Spatrick       packet.GetChar();
1565*061da546Spatrick 
1566*061da546Spatrick       thread_action.tid = packet.GetHexMaxU32(false, LLDB_INVALID_THREAD_ID);
1567*061da546Spatrick       if (thread_action.tid == LLDB_INVALID_THREAD_ID)
1568*061da546Spatrick         return SendIllFormedResponse(
1569*061da546Spatrick             packet, "Could not parse thread number in vCont packet");
1570*061da546Spatrick     }
1571*061da546Spatrick 
1572*061da546Spatrick     thread_actions.Append(thread_action);
1573*061da546Spatrick   }
1574*061da546Spatrick 
1575*061da546Spatrick   Status error = m_debugged_process_up->Resume(thread_actions);
1576*061da546Spatrick   if (error.Fail()) {
1577*061da546Spatrick     LLDB_LOG(log, "vCont failed for process {0}: {1}",
1578*061da546Spatrick              m_debugged_process_up->GetID(), error);
1579*061da546Spatrick     return SendErrorResponse(GDBRemoteServerError::eErrorResume);
1580*061da546Spatrick   }
1581*061da546Spatrick 
1582*061da546Spatrick   LLDB_LOG(log, "continued process {0}", m_debugged_process_up->GetID());
1583*061da546Spatrick   // No response required from vCont.
1584*061da546Spatrick   return PacketResult::Success;
1585*061da546Spatrick }
1586*061da546Spatrick 
1587*061da546Spatrick void GDBRemoteCommunicationServerLLGS::SetCurrentThreadID(lldb::tid_t tid) {
1588*061da546Spatrick   Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_THREAD));
1589*061da546Spatrick   LLDB_LOG(log, "setting current thread id to {0}", tid);
1590*061da546Spatrick 
1591*061da546Spatrick   m_current_tid = tid;
1592*061da546Spatrick   if (m_debugged_process_up)
1593*061da546Spatrick     m_debugged_process_up->SetCurrentThreadID(m_current_tid);
1594*061da546Spatrick }
1595*061da546Spatrick 
1596*061da546Spatrick void GDBRemoteCommunicationServerLLGS::SetContinueThreadID(lldb::tid_t tid) {
1597*061da546Spatrick   Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_THREAD));
1598*061da546Spatrick   LLDB_LOG(log, "setting continue thread id to {0}", tid);
1599*061da546Spatrick 
1600*061da546Spatrick   m_continue_tid = tid;
1601*061da546Spatrick }
1602*061da546Spatrick 
1603*061da546Spatrick GDBRemoteCommunication::PacketResult
1604*061da546Spatrick GDBRemoteCommunicationServerLLGS::Handle_stop_reason(
1605*061da546Spatrick     StringExtractorGDBRemote &packet) {
1606*061da546Spatrick   // Handle the $? gdbremote command.
1607*061da546Spatrick 
1608*061da546Spatrick   // If no process, indicate error
1609*061da546Spatrick   if (!m_debugged_process_up)
1610*061da546Spatrick     return SendErrorResponse(02);
1611*061da546Spatrick 
1612*061da546Spatrick   return SendStopReasonForState(m_debugged_process_up->GetState());
1613*061da546Spatrick }
1614*061da546Spatrick 
1615*061da546Spatrick GDBRemoteCommunication::PacketResult
1616*061da546Spatrick GDBRemoteCommunicationServerLLGS::SendStopReasonForState(
1617*061da546Spatrick     lldb::StateType process_state) {
1618*061da546Spatrick   Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
1619*061da546Spatrick 
1620*061da546Spatrick   switch (process_state) {
1621*061da546Spatrick   case eStateAttaching:
1622*061da546Spatrick   case eStateLaunching:
1623*061da546Spatrick   case eStateRunning:
1624*061da546Spatrick   case eStateStepping:
1625*061da546Spatrick   case eStateDetached:
1626*061da546Spatrick     // NOTE: gdb protocol doc looks like it should return $OK
1627*061da546Spatrick     // when everything is running (i.e. no stopped result).
1628*061da546Spatrick     return PacketResult::Success; // Ignore
1629*061da546Spatrick 
1630*061da546Spatrick   case eStateSuspended:
1631*061da546Spatrick   case eStateStopped:
1632*061da546Spatrick   case eStateCrashed: {
1633*061da546Spatrick     lldb::tid_t tid = m_debugged_process_up->GetCurrentThreadID();
1634*061da546Spatrick     // Make sure we set the current thread so g and p packets return the data
1635*061da546Spatrick     // the gdb will expect.
1636*061da546Spatrick     SetCurrentThreadID(tid);
1637*061da546Spatrick     return SendStopReplyPacketForThread(tid);
1638*061da546Spatrick   }
1639*061da546Spatrick 
1640*061da546Spatrick   case eStateInvalid:
1641*061da546Spatrick   case eStateUnloaded:
1642*061da546Spatrick   case eStateExited:
1643*061da546Spatrick     return SendWResponse(m_debugged_process_up.get());
1644*061da546Spatrick 
1645*061da546Spatrick   default:
1646*061da546Spatrick     LLDB_LOG(log, "pid {0}, current state reporting not handled: {1}",
1647*061da546Spatrick              m_debugged_process_up->GetID(), process_state);
1648*061da546Spatrick     break;
1649*061da546Spatrick   }
1650*061da546Spatrick 
1651*061da546Spatrick   return SendErrorResponse(0);
1652*061da546Spatrick }
1653*061da546Spatrick 
1654*061da546Spatrick GDBRemoteCommunication::PacketResult
1655*061da546Spatrick GDBRemoteCommunicationServerLLGS::Handle_qRegisterInfo(
1656*061da546Spatrick     StringExtractorGDBRemote &packet) {
1657*061da546Spatrick   // Fail if we don't have a current process.
1658*061da546Spatrick   if (!m_debugged_process_up ||
1659*061da546Spatrick       (m_debugged_process_up->GetID() == LLDB_INVALID_PROCESS_ID))
1660*061da546Spatrick     return SendErrorResponse(68);
1661*061da546Spatrick 
1662*061da546Spatrick   // Ensure we have a thread.
1663*061da546Spatrick   NativeThreadProtocol *thread = m_debugged_process_up->GetThreadAtIndex(0);
1664*061da546Spatrick   if (!thread)
1665*061da546Spatrick     return SendErrorResponse(69);
1666*061da546Spatrick 
1667*061da546Spatrick   // Get the register context for the first thread.
1668*061da546Spatrick   NativeRegisterContext &reg_context = thread->GetRegisterContext();
1669*061da546Spatrick 
1670*061da546Spatrick   // Parse out the register number from the request.
1671*061da546Spatrick   packet.SetFilePos(strlen("qRegisterInfo"));
1672*061da546Spatrick   const uint32_t reg_index =
1673*061da546Spatrick       packet.GetHexMaxU32(false, std::numeric_limits<uint32_t>::max());
1674*061da546Spatrick   if (reg_index == std::numeric_limits<uint32_t>::max())
1675*061da546Spatrick     return SendErrorResponse(69);
1676*061da546Spatrick 
1677*061da546Spatrick   // Return the end of registers response if we've iterated one past the end of
1678*061da546Spatrick   // the register set.
1679*061da546Spatrick   if (reg_index >= reg_context.GetUserRegisterCount())
1680*061da546Spatrick     return SendErrorResponse(69);
1681*061da546Spatrick 
1682*061da546Spatrick   const RegisterInfo *reg_info = reg_context.GetRegisterInfoAtIndex(reg_index);
1683*061da546Spatrick   if (!reg_info)
1684*061da546Spatrick     return SendErrorResponse(69);
1685*061da546Spatrick 
1686*061da546Spatrick   // Build the reginfos response.
1687*061da546Spatrick   StreamGDBRemote response;
1688*061da546Spatrick 
1689*061da546Spatrick   response.PutCString("name:");
1690*061da546Spatrick   response.PutCString(reg_info->name);
1691*061da546Spatrick   response.PutChar(';');
1692*061da546Spatrick 
1693*061da546Spatrick   if (reg_info->alt_name && reg_info->alt_name[0]) {
1694*061da546Spatrick     response.PutCString("alt-name:");
1695*061da546Spatrick     response.PutCString(reg_info->alt_name);
1696*061da546Spatrick     response.PutChar(';');
1697*061da546Spatrick   }
1698*061da546Spatrick 
1699*061da546Spatrick   response.Printf("bitsize:%" PRIu32 ";offset:%" PRIu32 ";",
1700*061da546Spatrick                   reg_info->byte_size * 8, reg_info->byte_offset);
1701*061da546Spatrick 
1702*061da546Spatrick   switch (reg_info->encoding) {
1703*061da546Spatrick   case eEncodingUint:
1704*061da546Spatrick     response.PutCString("encoding:uint;");
1705*061da546Spatrick     break;
1706*061da546Spatrick   case eEncodingSint:
1707*061da546Spatrick     response.PutCString("encoding:sint;");
1708*061da546Spatrick     break;
1709*061da546Spatrick   case eEncodingIEEE754:
1710*061da546Spatrick     response.PutCString("encoding:ieee754;");
1711*061da546Spatrick     break;
1712*061da546Spatrick   case eEncodingVector:
1713*061da546Spatrick     response.PutCString("encoding:vector;");
1714*061da546Spatrick     break;
1715*061da546Spatrick   default:
1716*061da546Spatrick     break;
1717*061da546Spatrick   }
1718*061da546Spatrick 
1719*061da546Spatrick   switch (reg_info->format) {
1720*061da546Spatrick   case eFormatBinary:
1721*061da546Spatrick     response.PutCString("format:binary;");
1722*061da546Spatrick     break;
1723*061da546Spatrick   case eFormatDecimal:
1724*061da546Spatrick     response.PutCString("format:decimal;");
1725*061da546Spatrick     break;
1726*061da546Spatrick   case eFormatHex:
1727*061da546Spatrick     response.PutCString("format:hex;");
1728*061da546Spatrick     break;
1729*061da546Spatrick   case eFormatFloat:
1730*061da546Spatrick     response.PutCString("format:float;");
1731*061da546Spatrick     break;
1732*061da546Spatrick   case eFormatVectorOfSInt8:
1733*061da546Spatrick     response.PutCString("format:vector-sint8;");
1734*061da546Spatrick     break;
1735*061da546Spatrick   case eFormatVectorOfUInt8:
1736*061da546Spatrick     response.PutCString("format:vector-uint8;");
1737*061da546Spatrick     break;
1738*061da546Spatrick   case eFormatVectorOfSInt16:
1739*061da546Spatrick     response.PutCString("format:vector-sint16;");
1740*061da546Spatrick     break;
1741*061da546Spatrick   case eFormatVectorOfUInt16:
1742*061da546Spatrick     response.PutCString("format:vector-uint16;");
1743*061da546Spatrick     break;
1744*061da546Spatrick   case eFormatVectorOfSInt32:
1745*061da546Spatrick     response.PutCString("format:vector-sint32;");
1746*061da546Spatrick     break;
1747*061da546Spatrick   case eFormatVectorOfUInt32:
1748*061da546Spatrick     response.PutCString("format:vector-uint32;");
1749*061da546Spatrick     break;
1750*061da546Spatrick   case eFormatVectorOfFloat32:
1751*061da546Spatrick     response.PutCString("format:vector-float32;");
1752*061da546Spatrick     break;
1753*061da546Spatrick   case eFormatVectorOfUInt64:
1754*061da546Spatrick     response.PutCString("format:vector-uint64;");
1755*061da546Spatrick     break;
1756*061da546Spatrick   case eFormatVectorOfUInt128:
1757*061da546Spatrick     response.PutCString("format:vector-uint128;");
1758*061da546Spatrick     break;
1759*061da546Spatrick   default:
1760*061da546Spatrick     break;
1761*061da546Spatrick   };
1762*061da546Spatrick 
1763*061da546Spatrick   const char *const register_set_name =
1764*061da546Spatrick       reg_context.GetRegisterSetNameForRegisterAtIndex(reg_index);
1765*061da546Spatrick   if (register_set_name) {
1766*061da546Spatrick     response.PutCString("set:");
1767*061da546Spatrick     response.PutCString(register_set_name);
1768*061da546Spatrick     response.PutChar(';');
1769*061da546Spatrick   }
1770*061da546Spatrick 
1771*061da546Spatrick   if (reg_info->kinds[RegisterKind::eRegisterKindEHFrame] !=
1772*061da546Spatrick       LLDB_INVALID_REGNUM)
1773*061da546Spatrick     response.Printf("ehframe:%" PRIu32 ";",
1774*061da546Spatrick                     reg_info->kinds[RegisterKind::eRegisterKindEHFrame]);
1775*061da546Spatrick 
1776*061da546Spatrick   if (reg_info->kinds[RegisterKind::eRegisterKindDWARF] != LLDB_INVALID_REGNUM)
1777*061da546Spatrick     response.Printf("dwarf:%" PRIu32 ";",
1778*061da546Spatrick                     reg_info->kinds[RegisterKind::eRegisterKindDWARF]);
1779*061da546Spatrick 
1780*061da546Spatrick   switch (reg_info->kinds[RegisterKind::eRegisterKindGeneric]) {
1781*061da546Spatrick   case LLDB_REGNUM_GENERIC_PC:
1782*061da546Spatrick     response.PutCString("generic:pc;");
1783*061da546Spatrick     break;
1784*061da546Spatrick   case LLDB_REGNUM_GENERIC_SP:
1785*061da546Spatrick     response.PutCString("generic:sp;");
1786*061da546Spatrick     break;
1787*061da546Spatrick   case LLDB_REGNUM_GENERIC_FP:
1788*061da546Spatrick     response.PutCString("generic:fp;");
1789*061da546Spatrick     break;
1790*061da546Spatrick   case LLDB_REGNUM_GENERIC_RA:
1791*061da546Spatrick     response.PutCString("generic:ra;");
1792*061da546Spatrick     break;
1793*061da546Spatrick   case LLDB_REGNUM_GENERIC_FLAGS:
1794*061da546Spatrick     response.PutCString("generic:flags;");
1795*061da546Spatrick     break;
1796*061da546Spatrick   case LLDB_REGNUM_GENERIC_ARG1:
1797*061da546Spatrick     response.PutCString("generic:arg1;");
1798*061da546Spatrick     break;
1799*061da546Spatrick   case LLDB_REGNUM_GENERIC_ARG2:
1800*061da546Spatrick     response.PutCString("generic:arg2;");
1801*061da546Spatrick     break;
1802*061da546Spatrick   case LLDB_REGNUM_GENERIC_ARG3:
1803*061da546Spatrick     response.PutCString("generic:arg3;");
1804*061da546Spatrick     break;
1805*061da546Spatrick   case LLDB_REGNUM_GENERIC_ARG4:
1806*061da546Spatrick     response.PutCString("generic:arg4;");
1807*061da546Spatrick     break;
1808*061da546Spatrick   case LLDB_REGNUM_GENERIC_ARG5:
1809*061da546Spatrick     response.PutCString("generic:arg5;");
1810*061da546Spatrick     break;
1811*061da546Spatrick   case LLDB_REGNUM_GENERIC_ARG6:
1812*061da546Spatrick     response.PutCString("generic:arg6;");
1813*061da546Spatrick     break;
1814*061da546Spatrick   case LLDB_REGNUM_GENERIC_ARG7:
1815*061da546Spatrick     response.PutCString("generic:arg7;");
1816*061da546Spatrick     break;
1817*061da546Spatrick   case LLDB_REGNUM_GENERIC_ARG8:
1818*061da546Spatrick     response.PutCString("generic:arg8;");
1819*061da546Spatrick     break;
1820*061da546Spatrick   default:
1821*061da546Spatrick     break;
1822*061da546Spatrick   }
1823*061da546Spatrick 
1824*061da546Spatrick   if (reg_info->value_regs && reg_info->value_regs[0] != LLDB_INVALID_REGNUM) {
1825*061da546Spatrick     response.PutCString("container-regs:");
1826*061da546Spatrick     int i = 0;
1827*061da546Spatrick     for (const uint32_t *reg_num = reg_info->value_regs;
1828*061da546Spatrick          *reg_num != LLDB_INVALID_REGNUM; ++reg_num, ++i) {
1829*061da546Spatrick       if (i > 0)
1830*061da546Spatrick         response.PutChar(',');
1831*061da546Spatrick       response.Printf("%" PRIx32, *reg_num);
1832*061da546Spatrick     }
1833*061da546Spatrick     response.PutChar(';');
1834*061da546Spatrick   }
1835*061da546Spatrick 
1836*061da546Spatrick   if (reg_info->invalidate_regs && reg_info->invalidate_regs[0]) {
1837*061da546Spatrick     response.PutCString("invalidate-regs:");
1838*061da546Spatrick     int i = 0;
1839*061da546Spatrick     for (const uint32_t *reg_num = reg_info->invalidate_regs;
1840*061da546Spatrick          *reg_num != LLDB_INVALID_REGNUM; ++reg_num, ++i) {
1841*061da546Spatrick       if (i > 0)
1842*061da546Spatrick         response.PutChar(',');
1843*061da546Spatrick       response.Printf("%" PRIx32, *reg_num);
1844*061da546Spatrick     }
1845*061da546Spatrick     response.PutChar(';');
1846*061da546Spatrick   }
1847*061da546Spatrick 
1848*061da546Spatrick   if (reg_info->dynamic_size_dwarf_expr_bytes) {
1849*061da546Spatrick     const size_t dwarf_opcode_len = reg_info->dynamic_size_dwarf_len;
1850*061da546Spatrick     response.PutCString("dynamic_size_dwarf_expr_bytes:");
1851*061da546Spatrick     for (uint32_t i = 0; i < dwarf_opcode_len; ++i)
1852*061da546Spatrick       response.PutHex8(reg_info->dynamic_size_dwarf_expr_bytes[i]);
1853*061da546Spatrick     response.PutChar(';');
1854*061da546Spatrick   }
1855*061da546Spatrick   return SendPacketNoLock(response.GetString());
1856*061da546Spatrick }
1857*061da546Spatrick 
1858*061da546Spatrick GDBRemoteCommunication::PacketResult
1859*061da546Spatrick GDBRemoteCommunicationServerLLGS::Handle_qfThreadInfo(
1860*061da546Spatrick     StringExtractorGDBRemote &packet) {
1861*061da546Spatrick   Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_THREAD));
1862*061da546Spatrick 
1863*061da546Spatrick   // Fail if we don't have a current process.
1864*061da546Spatrick   if (!m_debugged_process_up ||
1865*061da546Spatrick       (m_debugged_process_up->GetID() == LLDB_INVALID_PROCESS_ID)) {
1866*061da546Spatrick     LLDB_LOG(log, "no process ({0}), returning OK",
1867*061da546Spatrick              m_debugged_process_up ? "invalid process id"
1868*061da546Spatrick                                    : "null m_debugged_process_up");
1869*061da546Spatrick     return SendOKResponse();
1870*061da546Spatrick   }
1871*061da546Spatrick 
1872*061da546Spatrick   StreamGDBRemote response;
1873*061da546Spatrick   response.PutChar('m');
1874*061da546Spatrick 
1875*061da546Spatrick   LLDB_LOG(log, "starting thread iteration");
1876*061da546Spatrick   NativeThreadProtocol *thread;
1877*061da546Spatrick   uint32_t thread_index;
1878*061da546Spatrick   for (thread_index = 0,
1879*061da546Spatrick       thread = m_debugged_process_up->GetThreadAtIndex(thread_index);
1880*061da546Spatrick        thread; ++thread_index,
1881*061da546Spatrick       thread = m_debugged_process_up->GetThreadAtIndex(thread_index)) {
1882*061da546Spatrick     LLDB_LOG(log, "iterated thread {0}(tid={2})", thread_index,
1883*061da546Spatrick              thread->GetID());
1884*061da546Spatrick     if (thread_index > 0)
1885*061da546Spatrick       response.PutChar(',');
1886*061da546Spatrick     response.Printf("%" PRIx64, thread->GetID());
1887*061da546Spatrick   }
1888*061da546Spatrick 
1889*061da546Spatrick   LLDB_LOG(log, "finished thread iteration");
1890*061da546Spatrick   return SendPacketNoLock(response.GetString());
1891*061da546Spatrick }
1892*061da546Spatrick 
1893*061da546Spatrick GDBRemoteCommunication::PacketResult
1894*061da546Spatrick GDBRemoteCommunicationServerLLGS::Handle_qsThreadInfo(
1895*061da546Spatrick     StringExtractorGDBRemote &packet) {
1896*061da546Spatrick   // FIXME for now we return the full thread list in the initial packet and
1897*061da546Spatrick   // always do nothing here.
1898*061da546Spatrick   return SendPacketNoLock("l");
1899*061da546Spatrick }
1900*061da546Spatrick 
1901*061da546Spatrick GDBRemoteCommunication::PacketResult
1902*061da546Spatrick GDBRemoteCommunicationServerLLGS::Handle_g(StringExtractorGDBRemote &packet) {
1903*061da546Spatrick   Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_THREAD));
1904*061da546Spatrick 
1905*061da546Spatrick   // Move past packet name.
1906*061da546Spatrick   packet.SetFilePos(strlen("g"));
1907*061da546Spatrick 
1908*061da546Spatrick   // Get the thread to use.
1909*061da546Spatrick   NativeThreadProtocol *thread = GetThreadFromSuffix(packet);
1910*061da546Spatrick   if (!thread) {
1911*061da546Spatrick     LLDB_LOG(log, "failed, no thread available");
1912*061da546Spatrick     return SendErrorResponse(0x15);
1913*061da546Spatrick   }
1914*061da546Spatrick 
1915*061da546Spatrick   // Get the thread's register context.
1916*061da546Spatrick   NativeRegisterContext &reg_ctx = thread->GetRegisterContext();
1917*061da546Spatrick 
1918*061da546Spatrick   std::vector<uint8_t> regs_buffer;
1919*061da546Spatrick   for (uint32_t reg_num = 0; reg_num < reg_ctx.GetUserRegisterCount();
1920*061da546Spatrick        ++reg_num) {
1921*061da546Spatrick     const RegisterInfo *reg_info = reg_ctx.GetRegisterInfoAtIndex(reg_num);
1922*061da546Spatrick 
1923*061da546Spatrick     if (reg_info == nullptr) {
1924*061da546Spatrick       LLDB_LOG(log, "failed to get register info for register index {0}",
1925*061da546Spatrick                reg_num);
1926*061da546Spatrick       return SendErrorResponse(0x15);
1927*061da546Spatrick     }
1928*061da546Spatrick 
1929*061da546Spatrick     if (reg_info->value_regs != nullptr)
1930*061da546Spatrick       continue; // skip registers that are contained in other registers
1931*061da546Spatrick 
1932*061da546Spatrick     RegisterValue reg_value;
1933*061da546Spatrick     Status error = reg_ctx.ReadRegister(reg_info, reg_value);
1934*061da546Spatrick     if (error.Fail()) {
1935*061da546Spatrick       LLDB_LOG(log, "failed to read register at index {0}", reg_num);
1936*061da546Spatrick       return SendErrorResponse(0x15);
1937*061da546Spatrick     }
1938*061da546Spatrick 
1939*061da546Spatrick     if (reg_info->byte_offset + reg_info->byte_size >= regs_buffer.size())
1940*061da546Spatrick       // Resize the buffer to guarantee it can store the register offsetted
1941*061da546Spatrick       // data.
1942*061da546Spatrick       regs_buffer.resize(reg_info->byte_offset + reg_info->byte_size);
1943*061da546Spatrick 
1944*061da546Spatrick     // Copy the register offsetted data to the buffer.
1945*061da546Spatrick     memcpy(regs_buffer.data() + reg_info->byte_offset, reg_value.GetBytes(),
1946*061da546Spatrick            reg_info->byte_size);
1947*061da546Spatrick   }
1948*061da546Spatrick 
1949*061da546Spatrick   // Write the response.
1950*061da546Spatrick   StreamGDBRemote response;
1951*061da546Spatrick   response.PutBytesAsRawHex8(regs_buffer.data(), regs_buffer.size());
1952*061da546Spatrick 
1953*061da546Spatrick   return SendPacketNoLock(response.GetString());
1954*061da546Spatrick }
1955*061da546Spatrick 
1956*061da546Spatrick GDBRemoteCommunication::PacketResult
1957*061da546Spatrick GDBRemoteCommunicationServerLLGS::Handle_p(StringExtractorGDBRemote &packet) {
1958*061da546Spatrick   Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_THREAD));
1959*061da546Spatrick 
1960*061da546Spatrick   // Parse out the register number from the request.
1961*061da546Spatrick   packet.SetFilePos(strlen("p"));
1962*061da546Spatrick   const uint32_t reg_index =
1963*061da546Spatrick       packet.GetHexMaxU32(false, std::numeric_limits<uint32_t>::max());
1964*061da546Spatrick   if (reg_index == std::numeric_limits<uint32_t>::max()) {
1965*061da546Spatrick     LLDB_LOGF(log,
1966*061da546Spatrick               "GDBRemoteCommunicationServerLLGS::%s failed, could not "
1967*061da546Spatrick               "parse register number from request \"%s\"",
1968*061da546Spatrick               __FUNCTION__, packet.GetStringRef().data());
1969*061da546Spatrick     return SendErrorResponse(0x15);
1970*061da546Spatrick   }
1971*061da546Spatrick 
1972*061da546Spatrick   // Get the thread to use.
1973*061da546Spatrick   NativeThreadProtocol *thread = GetThreadFromSuffix(packet);
1974*061da546Spatrick   if (!thread) {
1975*061da546Spatrick     LLDB_LOG(log, "failed, no thread available");
1976*061da546Spatrick     return SendErrorResponse(0x15);
1977*061da546Spatrick   }
1978*061da546Spatrick 
1979*061da546Spatrick   // Get the thread's register context.
1980*061da546Spatrick   NativeRegisterContext &reg_context = thread->GetRegisterContext();
1981*061da546Spatrick 
1982*061da546Spatrick   // Return the end of registers response if we've iterated one past the end of
1983*061da546Spatrick   // the register set.
1984*061da546Spatrick   if (reg_index >= reg_context.GetUserRegisterCount()) {
1985*061da546Spatrick     LLDB_LOGF(log,
1986*061da546Spatrick               "GDBRemoteCommunicationServerLLGS::%s failed, requested "
1987*061da546Spatrick               "register %" PRIu32 " beyond register count %" PRIu32,
1988*061da546Spatrick               __FUNCTION__, reg_index, reg_context.GetUserRegisterCount());
1989*061da546Spatrick     return SendErrorResponse(0x15);
1990*061da546Spatrick   }
1991*061da546Spatrick 
1992*061da546Spatrick   const RegisterInfo *reg_info = reg_context.GetRegisterInfoAtIndex(reg_index);
1993*061da546Spatrick   if (!reg_info) {
1994*061da546Spatrick     LLDB_LOGF(log,
1995*061da546Spatrick               "GDBRemoteCommunicationServerLLGS::%s failed, requested "
1996*061da546Spatrick               "register %" PRIu32 " returned NULL",
1997*061da546Spatrick               __FUNCTION__, reg_index);
1998*061da546Spatrick     return SendErrorResponse(0x15);
1999*061da546Spatrick   }
2000*061da546Spatrick 
2001*061da546Spatrick   // Build the reginfos response.
2002*061da546Spatrick   StreamGDBRemote response;
2003*061da546Spatrick 
2004*061da546Spatrick   // Retrieve the value
2005*061da546Spatrick   RegisterValue reg_value;
2006*061da546Spatrick   Status error = reg_context.ReadRegister(reg_info, reg_value);
2007*061da546Spatrick   if (error.Fail()) {
2008*061da546Spatrick     LLDB_LOGF(log,
2009*061da546Spatrick               "GDBRemoteCommunicationServerLLGS::%s failed, read of "
2010*061da546Spatrick               "requested register %" PRIu32 " (%s) failed: %s",
2011*061da546Spatrick               __FUNCTION__, reg_index, reg_info->name, error.AsCString());
2012*061da546Spatrick     return SendErrorResponse(0x15);
2013*061da546Spatrick   }
2014*061da546Spatrick 
2015*061da546Spatrick   const uint8_t *const data =
2016*061da546Spatrick       static_cast<const uint8_t *>(reg_value.GetBytes());
2017*061da546Spatrick   if (!data) {
2018*061da546Spatrick     LLDB_LOGF(log,
2019*061da546Spatrick               "GDBRemoteCommunicationServerLLGS::%s failed to get data "
2020*061da546Spatrick               "bytes from requested register %" PRIu32,
2021*061da546Spatrick               __FUNCTION__, reg_index);
2022*061da546Spatrick     return SendErrorResponse(0x15);
2023*061da546Spatrick   }
2024*061da546Spatrick 
2025*061da546Spatrick   // FIXME flip as needed to get data in big/little endian format for this host.
2026*061da546Spatrick   for (uint32_t i = 0; i < reg_value.GetByteSize(); ++i)
2027*061da546Spatrick     response.PutHex8(data[i]);
2028*061da546Spatrick 
2029*061da546Spatrick   return SendPacketNoLock(response.GetString());
2030*061da546Spatrick }
2031*061da546Spatrick 
2032*061da546Spatrick GDBRemoteCommunication::PacketResult
2033*061da546Spatrick GDBRemoteCommunicationServerLLGS::Handle_P(StringExtractorGDBRemote &packet) {
2034*061da546Spatrick   Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_THREAD));
2035*061da546Spatrick 
2036*061da546Spatrick   // Ensure there is more content.
2037*061da546Spatrick   if (packet.GetBytesLeft() < 1)
2038*061da546Spatrick     return SendIllFormedResponse(packet, "Empty P packet");
2039*061da546Spatrick 
2040*061da546Spatrick   // Parse out the register number from the request.
2041*061da546Spatrick   packet.SetFilePos(strlen("P"));
2042*061da546Spatrick   const uint32_t reg_index =
2043*061da546Spatrick       packet.GetHexMaxU32(false, std::numeric_limits<uint32_t>::max());
2044*061da546Spatrick   if (reg_index == std::numeric_limits<uint32_t>::max()) {
2045*061da546Spatrick     LLDB_LOGF(log,
2046*061da546Spatrick               "GDBRemoteCommunicationServerLLGS::%s failed, could not "
2047*061da546Spatrick               "parse register number from request \"%s\"",
2048*061da546Spatrick               __FUNCTION__, packet.GetStringRef().data());
2049*061da546Spatrick     return SendErrorResponse(0x29);
2050*061da546Spatrick   }
2051*061da546Spatrick 
2052*061da546Spatrick   // Note debugserver would send an E30 here.
2053*061da546Spatrick   if ((packet.GetBytesLeft() < 1) || (packet.GetChar() != '='))
2054*061da546Spatrick     return SendIllFormedResponse(
2055*061da546Spatrick         packet, "P packet missing '=' char after register number");
2056*061da546Spatrick 
2057*061da546Spatrick   // Parse out the value.
2058*061da546Spatrick   uint8_t reg_bytes[32]; // big enough to support up to 256 bit ymmN register
2059*061da546Spatrick   size_t reg_size = packet.GetHexBytesAvail(reg_bytes);
2060*061da546Spatrick 
2061*061da546Spatrick   // Get the thread to use.
2062*061da546Spatrick   NativeThreadProtocol *thread = GetThreadFromSuffix(packet);
2063*061da546Spatrick   if (!thread) {
2064*061da546Spatrick     LLDB_LOGF(log,
2065*061da546Spatrick               "GDBRemoteCommunicationServerLLGS::%s failed, no thread "
2066*061da546Spatrick               "available (thread index 0)",
2067*061da546Spatrick               __FUNCTION__);
2068*061da546Spatrick     return SendErrorResponse(0x28);
2069*061da546Spatrick   }
2070*061da546Spatrick 
2071*061da546Spatrick   // Get the thread's register context.
2072*061da546Spatrick   NativeRegisterContext &reg_context = thread->GetRegisterContext();
2073*061da546Spatrick   const RegisterInfo *reg_info = reg_context.GetRegisterInfoAtIndex(reg_index);
2074*061da546Spatrick   if (!reg_info) {
2075*061da546Spatrick     LLDB_LOGF(log,
2076*061da546Spatrick               "GDBRemoteCommunicationServerLLGS::%s failed, requested "
2077*061da546Spatrick               "register %" PRIu32 " returned NULL",
2078*061da546Spatrick               __FUNCTION__, reg_index);
2079*061da546Spatrick     return SendErrorResponse(0x48);
2080*061da546Spatrick   }
2081*061da546Spatrick 
2082*061da546Spatrick   // Return the end of registers response if we've iterated one past the end of
2083*061da546Spatrick   // the register set.
2084*061da546Spatrick   if (reg_index >= reg_context.GetUserRegisterCount()) {
2085*061da546Spatrick     LLDB_LOGF(log,
2086*061da546Spatrick               "GDBRemoteCommunicationServerLLGS::%s failed, requested "
2087*061da546Spatrick               "register %" PRIu32 " beyond register count %" PRIu32,
2088*061da546Spatrick               __FUNCTION__, reg_index, reg_context.GetUserRegisterCount());
2089*061da546Spatrick     return SendErrorResponse(0x47);
2090*061da546Spatrick   }
2091*061da546Spatrick 
2092*061da546Spatrick   // The dwarf expression are evaluate on host site which may cause register
2093*061da546Spatrick   // size to change Hence the reg_size may not be same as reg_info->bytes_size
2094*061da546Spatrick   if ((reg_size != reg_info->byte_size) &&
2095*061da546Spatrick       !(reg_info->dynamic_size_dwarf_expr_bytes)) {
2096*061da546Spatrick     return SendIllFormedResponse(packet, "P packet register size is incorrect");
2097*061da546Spatrick   }
2098*061da546Spatrick 
2099*061da546Spatrick   // Build the reginfos response.
2100*061da546Spatrick   StreamGDBRemote response;
2101*061da546Spatrick 
2102*061da546Spatrick   RegisterValue reg_value(
2103*061da546Spatrick       reg_bytes, reg_size,
2104*061da546Spatrick       m_debugged_process_up->GetArchitecture().GetByteOrder());
2105*061da546Spatrick   Status error = reg_context.WriteRegister(reg_info, reg_value);
2106*061da546Spatrick   if (error.Fail()) {
2107*061da546Spatrick     LLDB_LOGF(log,
2108*061da546Spatrick               "GDBRemoteCommunicationServerLLGS::%s failed, write of "
2109*061da546Spatrick               "requested register %" PRIu32 " (%s) failed: %s",
2110*061da546Spatrick               __FUNCTION__, reg_index, reg_info->name, error.AsCString());
2111*061da546Spatrick     return SendErrorResponse(0x32);
2112*061da546Spatrick   }
2113*061da546Spatrick 
2114*061da546Spatrick   return SendOKResponse();
2115*061da546Spatrick }
2116*061da546Spatrick 
2117*061da546Spatrick GDBRemoteCommunication::PacketResult
2118*061da546Spatrick GDBRemoteCommunicationServerLLGS::Handle_H(StringExtractorGDBRemote &packet) {
2119*061da546Spatrick   Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_THREAD));
2120*061da546Spatrick 
2121*061da546Spatrick   // Fail if we don't have a current process.
2122*061da546Spatrick   if (!m_debugged_process_up ||
2123*061da546Spatrick       (m_debugged_process_up->GetID() == LLDB_INVALID_PROCESS_ID)) {
2124*061da546Spatrick     LLDB_LOGF(
2125*061da546Spatrick         log,
2126*061da546Spatrick         "GDBRemoteCommunicationServerLLGS::%s failed, no process available",
2127*061da546Spatrick         __FUNCTION__);
2128*061da546Spatrick     return SendErrorResponse(0x15);
2129*061da546Spatrick   }
2130*061da546Spatrick 
2131*061da546Spatrick   // Parse out which variant of $H is requested.
2132*061da546Spatrick   packet.SetFilePos(strlen("H"));
2133*061da546Spatrick   if (packet.GetBytesLeft() < 1) {
2134*061da546Spatrick     LLDB_LOGF(log,
2135*061da546Spatrick               "GDBRemoteCommunicationServerLLGS::%s failed, H command "
2136*061da546Spatrick               "missing {g,c} variant",
2137*061da546Spatrick               __FUNCTION__);
2138*061da546Spatrick     return SendIllFormedResponse(packet, "H command missing {g,c} variant");
2139*061da546Spatrick   }
2140*061da546Spatrick 
2141*061da546Spatrick   const char h_variant = packet.GetChar();
2142*061da546Spatrick   switch (h_variant) {
2143*061da546Spatrick   case 'g':
2144*061da546Spatrick     break;
2145*061da546Spatrick 
2146*061da546Spatrick   case 'c':
2147*061da546Spatrick     break;
2148*061da546Spatrick 
2149*061da546Spatrick   default:
2150*061da546Spatrick     LLDB_LOGF(
2151*061da546Spatrick         log,
2152*061da546Spatrick         "GDBRemoteCommunicationServerLLGS::%s failed, invalid $H variant %c",
2153*061da546Spatrick         __FUNCTION__, h_variant);
2154*061da546Spatrick     return SendIllFormedResponse(packet,
2155*061da546Spatrick                                  "H variant unsupported, should be c or g");
2156*061da546Spatrick   }
2157*061da546Spatrick 
2158*061da546Spatrick   // Parse out the thread number.
2159*061da546Spatrick   // FIXME return a parse success/fail value.  All values are valid here.
2160*061da546Spatrick   const lldb::tid_t tid =
2161*061da546Spatrick       packet.GetHexMaxU64(false, std::numeric_limits<lldb::tid_t>::max());
2162*061da546Spatrick 
2163*061da546Spatrick   // Ensure we have the given thread when not specifying -1 (all threads) or 0
2164*061da546Spatrick   // (any thread).
2165*061da546Spatrick   if (tid != LLDB_INVALID_THREAD_ID && tid != 0) {
2166*061da546Spatrick     NativeThreadProtocol *thread = m_debugged_process_up->GetThreadByID(tid);
2167*061da546Spatrick     if (!thread) {
2168*061da546Spatrick       LLDB_LOGF(log,
2169*061da546Spatrick                 "GDBRemoteCommunicationServerLLGS::%s failed, tid %" PRIu64
2170*061da546Spatrick                 " not found",
2171*061da546Spatrick                 __FUNCTION__, tid);
2172*061da546Spatrick       return SendErrorResponse(0x15);
2173*061da546Spatrick     }
2174*061da546Spatrick   }
2175*061da546Spatrick 
2176*061da546Spatrick   // Now switch the given thread type.
2177*061da546Spatrick   switch (h_variant) {
2178*061da546Spatrick   case 'g':
2179*061da546Spatrick     SetCurrentThreadID(tid);
2180*061da546Spatrick     break;
2181*061da546Spatrick 
2182*061da546Spatrick   case 'c':
2183*061da546Spatrick     SetContinueThreadID(tid);
2184*061da546Spatrick     break;
2185*061da546Spatrick 
2186*061da546Spatrick   default:
2187*061da546Spatrick     assert(false && "unsupported $H variant - shouldn't get here");
2188*061da546Spatrick     return SendIllFormedResponse(packet,
2189*061da546Spatrick                                  "H variant unsupported, should be c or g");
2190*061da546Spatrick   }
2191*061da546Spatrick 
2192*061da546Spatrick   return SendOKResponse();
2193*061da546Spatrick }
2194*061da546Spatrick 
2195*061da546Spatrick GDBRemoteCommunication::PacketResult
2196*061da546Spatrick GDBRemoteCommunicationServerLLGS::Handle_I(StringExtractorGDBRemote &packet) {
2197*061da546Spatrick   Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_THREAD));
2198*061da546Spatrick 
2199*061da546Spatrick   // Fail if we don't have a current process.
2200*061da546Spatrick   if (!m_debugged_process_up ||
2201*061da546Spatrick       (m_debugged_process_up->GetID() == LLDB_INVALID_PROCESS_ID)) {
2202*061da546Spatrick     LLDB_LOGF(
2203*061da546Spatrick         log,
2204*061da546Spatrick         "GDBRemoteCommunicationServerLLGS::%s failed, no process available",
2205*061da546Spatrick         __FUNCTION__);
2206*061da546Spatrick     return SendErrorResponse(0x15);
2207*061da546Spatrick   }
2208*061da546Spatrick 
2209*061da546Spatrick   packet.SetFilePos(::strlen("I"));
2210*061da546Spatrick   uint8_t tmp[4096];
2211*061da546Spatrick   for (;;) {
2212*061da546Spatrick     size_t read = packet.GetHexBytesAvail(tmp);
2213*061da546Spatrick     if (read == 0) {
2214*061da546Spatrick       break;
2215*061da546Spatrick     }
2216*061da546Spatrick     // write directly to stdin *this might block if stdin buffer is full*
2217*061da546Spatrick     // TODO: enqueue this block in circular buffer and send window size to
2218*061da546Spatrick     // remote host
2219*061da546Spatrick     ConnectionStatus status;
2220*061da546Spatrick     Status error;
2221*061da546Spatrick     m_stdio_communication.Write(tmp, read, status, &error);
2222*061da546Spatrick     if (error.Fail()) {
2223*061da546Spatrick       return SendErrorResponse(0x15);
2224*061da546Spatrick     }
2225*061da546Spatrick   }
2226*061da546Spatrick 
2227*061da546Spatrick   return SendOKResponse();
2228*061da546Spatrick }
2229*061da546Spatrick 
2230*061da546Spatrick GDBRemoteCommunication::PacketResult
2231*061da546Spatrick GDBRemoteCommunicationServerLLGS::Handle_interrupt(
2232*061da546Spatrick     StringExtractorGDBRemote &packet) {
2233*061da546Spatrick   Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS | LIBLLDB_LOG_THREAD));
2234*061da546Spatrick 
2235*061da546Spatrick   // Fail if we don't have a current process.
2236*061da546Spatrick   if (!m_debugged_process_up ||
2237*061da546Spatrick       (m_debugged_process_up->GetID() == LLDB_INVALID_PROCESS_ID)) {
2238*061da546Spatrick     LLDB_LOG(log, "failed, no process available");
2239*061da546Spatrick     return SendErrorResponse(0x15);
2240*061da546Spatrick   }
2241*061da546Spatrick 
2242*061da546Spatrick   // Interrupt the process.
2243*061da546Spatrick   Status error = m_debugged_process_up->Interrupt();
2244*061da546Spatrick   if (error.Fail()) {
2245*061da546Spatrick     LLDB_LOG(log, "failed for process {0}: {1}", m_debugged_process_up->GetID(),
2246*061da546Spatrick              error);
2247*061da546Spatrick     return SendErrorResponse(GDBRemoteServerError::eErrorResume);
2248*061da546Spatrick   }
2249*061da546Spatrick 
2250*061da546Spatrick   LLDB_LOG(log, "stopped process {0}", m_debugged_process_up->GetID());
2251*061da546Spatrick 
2252*061da546Spatrick   // No response required from stop all.
2253*061da546Spatrick   return PacketResult::Success;
2254*061da546Spatrick }
2255*061da546Spatrick 
2256*061da546Spatrick GDBRemoteCommunication::PacketResult
2257*061da546Spatrick GDBRemoteCommunicationServerLLGS::Handle_memory_read(
2258*061da546Spatrick     StringExtractorGDBRemote &packet) {
2259*061da546Spatrick   Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
2260*061da546Spatrick 
2261*061da546Spatrick   if (!m_debugged_process_up ||
2262*061da546Spatrick       (m_debugged_process_up->GetID() == LLDB_INVALID_PROCESS_ID)) {
2263*061da546Spatrick     LLDB_LOGF(
2264*061da546Spatrick         log,
2265*061da546Spatrick         "GDBRemoteCommunicationServerLLGS::%s failed, no process available",
2266*061da546Spatrick         __FUNCTION__);
2267*061da546Spatrick     return SendErrorResponse(0x15);
2268*061da546Spatrick   }
2269*061da546Spatrick 
2270*061da546Spatrick   // Parse out the memory address.
2271*061da546Spatrick   packet.SetFilePos(strlen("m"));
2272*061da546Spatrick   if (packet.GetBytesLeft() < 1)
2273*061da546Spatrick     return SendIllFormedResponse(packet, "Too short m packet");
2274*061da546Spatrick 
2275*061da546Spatrick   // Read the address.  Punting on validation.
2276*061da546Spatrick   // FIXME replace with Hex U64 read with no default value that fails on failed
2277*061da546Spatrick   // read.
2278*061da546Spatrick   const lldb::addr_t read_addr = packet.GetHexMaxU64(false, 0);
2279*061da546Spatrick 
2280*061da546Spatrick   // Validate comma.
2281*061da546Spatrick   if ((packet.GetBytesLeft() < 1) || (packet.GetChar() != ','))
2282*061da546Spatrick     return SendIllFormedResponse(packet, "Comma sep missing in m packet");
2283*061da546Spatrick 
2284*061da546Spatrick   // Get # bytes to read.
2285*061da546Spatrick   if (packet.GetBytesLeft() < 1)
2286*061da546Spatrick     return SendIllFormedResponse(packet, "Length missing in m packet");
2287*061da546Spatrick 
2288*061da546Spatrick   const uint64_t byte_count = packet.GetHexMaxU64(false, 0);
2289*061da546Spatrick   if (byte_count == 0) {
2290*061da546Spatrick     LLDB_LOGF(log,
2291*061da546Spatrick               "GDBRemoteCommunicationServerLLGS::%s nothing to read: "
2292*061da546Spatrick               "zero-length packet",
2293*061da546Spatrick               __FUNCTION__);
2294*061da546Spatrick     return SendOKResponse();
2295*061da546Spatrick   }
2296*061da546Spatrick 
2297*061da546Spatrick   // Allocate the response buffer.
2298*061da546Spatrick   std::string buf(byte_count, '\0');
2299*061da546Spatrick   if (buf.empty())
2300*061da546Spatrick     return SendErrorResponse(0x78);
2301*061da546Spatrick 
2302*061da546Spatrick   // Retrieve the process memory.
2303*061da546Spatrick   size_t bytes_read = 0;
2304*061da546Spatrick   Status error = m_debugged_process_up->ReadMemoryWithoutTrap(
2305*061da546Spatrick       read_addr, &buf[0], byte_count, bytes_read);
2306*061da546Spatrick   if (error.Fail()) {
2307*061da546Spatrick     LLDB_LOGF(log,
2308*061da546Spatrick               "GDBRemoteCommunicationServerLLGS::%s pid %" PRIu64
2309*061da546Spatrick               " mem 0x%" PRIx64 ": failed to read. Error: %s",
2310*061da546Spatrick               __FUNCTION__, m_debugged_process_up->GetID(), read_addr,
2311*061da546Spatrick               error.AsCString());
2312*061da546Spatrick     return SendErrorResponse(0x08);
2313*061da546Spatrick   }
2314*061da546Spatrick 
2315*061da546Spatrick   if (bytes_read == 0) {
2316*061da546Spatrick     LLDB_LOGF(log,
2317*061da546Spatrick               "GDBRemoteCommunicationServerLLGS::%s pid %" PRIu64
2318*061da546Spatrick               " mem 0x%" PRIx64 ": read 0 of %" PRIu64 " requested bytes",
2319*061da546Spatrick               __FUNCTION__, m_debugged_process_up->GetID(), read_addr,
2320*061da546Spatrick               byte_count);
2321*061da546Spatrick     return SendErrorResponse(0x08);
2322*061da546Spatrick   }
2323*061da546Spatrick 
2324*061da546Spatrick   StreamGDBRemote response;
2325*061da546Spatrick   packet.SetFilePos(0);
2326*061da546Spatrick   char kind = packet.GetChar('?');
2327*061da546Spatrick   if (kind == 'x')
2328*061da546Spatrick     response.PutEscapedBytes(buf.data(), byte_count);
2329*061da546Spatrick   else {
2330*061da546Spatrick     assert(kind == 'm');
2331*061da546Spatrick     for (size_t i = 0; i < bytes_read; ++i)
2332*061da546Spatrick       response.PutHex8(buf[i]);
2333*061da546Spatrick   }
2334*061da546Spatrick 
2335*061da546Spatrick   return SendPacketNoLock(response.GetString());
2336*061da546Spatrick }
2337*061da546Spatrick 
2338*061da546Spatrick GDBRemoteCommunication::PacketResult
2339*061da546Spatrick GDBRemoteCommunicationServerLLGS::Handle_M(StringExtractorGDBRemote &packet) {
2340*061da546Spatrick   Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
2341*061da546Spatrick 
2342*061da546Spatrick   if (!m_debugged_process_up ||
2343*061da546Spatrick       (m_debugged_process_up->GetID() == LLDB_INVALID_PROCESS_ID)) {
2344*061da546Spatrick     LLDB_LOGF(
2345*061da546Spatrick         log,
2346*061da546Spatrick         "GDBRemoteCommunicationServerLLGS::%s failed, no process available",
2347*061da546Spatrick         __FUNCTION__);
2348*061da546Spatrick     return SendErrorResponse(0x15);
2349*061da546Spatrick   }
2350*061da546Spatrick 
2351*061da546Spatrick   // Parse out the memory address.
2352*061da546Spatrick   packet.SetFilePos(strlen("M"));
2353*061da546Spatrick   if (packet.GetBytesLeft() < 1)
2354*061da546Spatrick     return SendIllFormedResponse(packet, "Too short M packet");
2355*061da546Spatrick 
2356*061da546Spatrick   // Read the address.  Punting on validation.
2357*061da546Spatrick   // FIXME replace with Hex U64 read with no default value that fails on failed
2358*061da546Spatrick   // read.
2359*061da546Spatrick   const lldb::addr_t write_addr = packet.GetHexMaxU64(false, 0);
2360*061da546Spatrick 
2361*061da546Spatrick   // Validate comma.
2362*061da546Spatrick   if ((packet.GetBytesLeft() < 1) || (packet.GetChar() != ','))
2363*061da546Spatrick     return SendIllFormedResponse(packet, "Comma sep missing in M packet");
2364*061da546Spatrick 
2365*061da546Spatrick   // Get # bytes to read.
2366*061da546Spatrick   if (packet.GetBytesLeft() < 1)
2367*061da546Spatrick     return SendIllFormedResponse(packet, "Length missing in M packet");
2368*061da546Spatrick 
2369*061da546Spatrick   const uint64_t byte_count = packet.GetHexMaxU64(false, 0);
2370*061da546Spatrick   if (byte_count == 0) {
2371*061da546Spatrick     LLDB_LOG(log, "nothing to write: zero-length packet");
2372*061da546Spatrick     return PacketResult::Success;
2373*061da546Spatrick   }
2374*061da546Spatrick 
2375*061da546Spatrick   // Validate colon.
2376*061da546Spatrick   if ((packet.GetBytesLeft() < 1) || (packet.GetChar() != ':'))
2377*061da546Spatrick     return SendIllFormedResponse(
2378*061da546Spatrick         packet, "Comma sep missing in M packet after byte length");
2379*061da546Spatrick 
2380*061da546Spatrick   // Allocate the conversion buffer.
2381*061da546Spatrick   std::vector<uint8_t> buf(byte_count, 0);
2382*061da546Spatrick   if (buf.empty())
2383*061da546Spatrick     return SendErrorResponse(0x78);
2384*061da546Spatrick 
2385*061da546Spatrick   // Convert the hex memory write contents to bytes.
2386*061da546Spatrick   StreamGDBRemote response;
2387*061da546Spatrick   const uint64_t convert_count = packet.GetHexBytes(buf, 0);
2388*061da546Spatrick   if (convert_count != byte_count) {
2389*061da546Spatrick     LLDB_LOG(log,
2390*061da546Spatrick              "pid {0} mem {1:x}: asked to write {2} bytes, but only found {3} "
2391*061da546Spatrick              "to convert.",
2392*061da546Spatrick              m_debugged_process_up->GetID(), write_addr, byte_count,
2393*061da546Spatrick              convert_count);
2394*061da546Spatrick     return SendIllFormedResponse(packet, "M content byte length specified did "
2395*061da546Spatrick                                          "not match hex-encoded content "
2396*061da546Spatrick                                          "length");
2397*061da546Spatrick   }
2398*061da546Spatrick 
2399*061da546Spatrick   // Write the process memory.
2400*061da546Spatrick   size_t bytes_written = 0;
2401*061da546Spatrick   Status error = m_debugged_process_up->WriteMemory(write_addr, &buf[0],
2402*061da546Spatrick                                                     byte_count, bytes_written);
2403*061da546Spatrick   if (error.Fail()) {
2404*061da546Spatrick     LLDB_LOG(log, "pid {0} mem {1:x}: failed to write. Error: {2}",
2405*061da546Spatrick              m_debugged_process_up->GetID(), write_addr, error);
2406*061da546Spatrick     return SendErrorResponse(0x09);
2407*061da546Spatrick   }
2408*061da546Spatrick 
2409*061da546Spatrick   if (bytes_written == 0) {
2410*061da546Spatrick     LLDB_LOG(log, "pid {0} mem {1:x}: wrote 0 of {2} requested bytes",
2411*061da546Spatrick              m_debugged_process_up->GetID(), write_addr, byte_count);
2412*061da546Spatrick     return SendErrorResponse(0x09);
2413*061da546Spatrick   }
2414*061da546Spatrick 
2415*061da546Spatrick   return SendOKResponse();
2416*061da546Spatrick }
2417*061da546Spatrick 
2418*061da546Spatrick GDBRemoteCommunication::PacketResult
2419*061da546Spatrick GDBRemoteCommunicationServerLLGS::Handle_qMemoryRegionInfoSupported(
2420*061da546Spatrick     StringExtractorGDBRemote &packet) {
2421*061da546Spatrick   Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
2422*061da546Spatrick 
2423*061da546Spatrick   // Currently only the NativeProcessProtocol knows if it can handle a
2424*061da546Spatrick   // qMemoryRegionInfoSupported request, but we're not guaranteed to be
2425*061da546Spatrick   // attached to a process.  For now we'll assume the client only asks this
2426*061da546Spatrick   // when a process is being debugged.
2427*061da546Spatrick 
2428*061da546Spatrick   // Ensure we have a process running; otherwise, we can't figure this out
2429*061da546Spatrick   // since we won't have a NativeProcessProtocol.
2430*061da546Spatrick   if (!m_debugged_process_up ||
2431*061da546Spatrick       (m_debugged_process_up->GetID() == LLDB_INVALID_PROCESS_ID)) {
2432*061da546Spatrick     LLDB_LOGF(
2433*061da546Spatrick         log,
2434*061da546Spatrick         "GDBRemoteCommunicationServerLLGS::%s failed, no process available",
2435*061da546Spatrick         __FUNCTION__);
2436*061da546Spatrick     return SendErrorResponse(0x15);
2437*061da546Spatrick   }
2438*061da546Spatrick 
2439*061da546Spatrick   // Test if we can get any region back when asking for the region around NULL.
2440*061da546Spatrick   MemoryRegionInfo region_info;
2441*061da546Spatrick   const Status error =
2442*061da546Spatrick       m_debugged_process_up->GetMemoryRegionInfo(0, region_info);
2443*061da546Spatrick   if (error.Fail()) {
2444*061da546Spatrick     // We don't support memory region info collection for this
2445*061da546Spatrick     // NativeProcessProtocol.
2446*061da546Spatrick     return SendUnimplementedResponse("");
2447*061da546Spatrick   }
2448*061da546Spatrick 
2449*061da546Spatrick   return SendOKResponse();
2450*061da546Spatrick }
2451*061da546Spatrick 
2452*061da546Spatrick GDBRemoteCommunication::PacketResult
2453*061da546Spatrick GDBRemoteCommunicationServerLLGS::Handle_qMemoryRegionInfo(
2454*061da546Spatrick     StringExtractorGDBRemote &packet) {
2455*061da546Spatrick   Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
2456*061da546Spatrick 
2457*061da546Spatrick   // Ensure we have a process.
2458*061da546Spatrick   if (!m_debugged_process_up ||
2459*061da546Spatrick       (m_debugged_process_up->GetID() == LLDB_INVALID_PROCESS_ID)) {
2460*061da546Spatrick     LLDB_LOGF(
2461*061da546Spatrick         log,
2462*061da546Spatrick         "GDBRemoteCommunicationServerLLGS::%s failed, no process available",
2463*061da546Spatrick         __FUNCTION__);
2464*061da546Spatrick     return SendErrorResponse(0x15);
2465*061da546Spatrick   }
2466*061da546Spatrick 
2467*061da546Spatrick   // Parse out the memory address.
2468*061da546Spatrick   packet.SetFilePos(strlen("qMemoryRegionInfo:"));
2469*061da546Spatrick   if (packet.GetBytesLeft() < 1)
2470*061da546Spatrick     return SendIllFormedResponse(packet, "Too short qMemoryRegionInfo: packet");
2471*061da546Spatrick 
2472*061da546Spatrick   // Read the address.  Punting on validation.
2473*061da546Spatrick   const lldb::addr_t read_addr = packet.GetHexMaxU64(false, 0);
2474*061da546Spatrick 
2475*061da546Spatrick   StreamGDBRemote response;
2476*061da546Spatrick 
2477*061da546Spatrick   // Get the memory region info for the target address.
2478*061da546Spatrick   MemoryRegionInfo region_info;
2479*061da546Spatrick   const Status error =
2480*061da546Spatrick       m_debugged_process_up->GetMemoryRegionInfo(read_addr, region_info);
2481*061da546Spatrick   if (error.Fail()) {
2482*061da546Spatrick     // Return the error message.
2483*061da546Spatrick 
2484*061da546Spatrick     response.PutCString("error:");
2485*061da546Spatrick     response.PutStringAsRawHex8(error.AsCString());
2486*061da546Spatrick     response.PutChar(';');
2487*061da546Spatrick   } else {
2488*061da546Spatrick     // Range start and size.
2489*061da546Spatrick     response.Printf("start:%" PRIx64 ";size:%" PRIx64 ";",
2490*061da546Spatrick                     region_info.GetRange().GetRangeBase(),
2491*061da546Spatrick                     region_info.GetRange().GetByteSize());
2492*061da546Spatrick 
2493*061da546Spatrick     // Permissions.
2494*061da546Spatrick     if (region_info.GetReadable() || region_info.GetWritable() ||
2495*061da546Spatrick         region_info.GetExecutable()) {
2496*061da546Spatrick       // Write permissions info.
2497*061da546Spatrick       response.PutCString("permissions:");
2498*061da546Spatrick 
2499*061da546Spatrick       if (region_info.GetReadable())
2500*061da546Spatrick         response.PutChar('r');
2501*061da546Spatrick       if (region_info.GetWritable())
2502*061da546Spatrick         response.PutChar('w');
2503*061da546Spatrick       if (region_info.GetExecutable())
2504*061da546Spatrick         response.PutChar('x');
2505*061da546Spatrick 
2506*061da546Spatrick       response.PutChar(';');
2507*061da546Spatrick     }
2508*061da546Spatrick 
2509*061da546Spatrick     // Name
2510*061da546Spatrick     ConstString name = region_info.GetName();
2511*061da546Spatrick     if (name) {
2512*061da546Spatrick       response.PutCString("name:");
2513*061da546Spatrick       response.PutStringAsRawHex8(name.AsCString());
2514*061da546Spatrick       response.PutChar(';');
2515*061da546Spatrick     }
2516*061da546Spatrick   }
2517*061da546Spatrick 
2518*061da546Spatrick   return SendPacketNoLock(response.GetString());
2519*061da546Spatrick }
2520*061da546Spatrick 
2521*061da546Spatrick GDBRemoteCommunication::PacketResult
2522*061da546Spatrick GDBRemoteCommunicationServerLLGS::Handle_Z(StringExtractorGDBRemote &packet) {
2523*061da546Spatrick   // Ensure we have a process.
2524*061da546Spatrick   if (!m_debugged_process_up ||
2525*061da546Spatrick       (m_debugged_process_up->GetID() == LLDB_INVALID_PROCESS_ID)) {
2526*061da546Spatrick     Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
2527*061da546Spatrick     LLDB_LOG(log, "failed, no process available");
2528*061da546Spatrick     return SendErrorResponse(0x15);
2529*061da546Spatrick   }
2530*061da546Spatrick 
2531*061da546Spatrick   // Parse out software or hardware breakpoint or watchpoint requested.
2532*061da546Spatrick   packet.SetFilePos(strlen("Z"));
2533*061da546Spatrick   if (packet.GetBytesLeft() < 1)
2534*061da546Spatrick     return SendIllFormedResponse(
2535*061da546Spatrick         packet, "Too short Z packet, missing software/hardware specifier");
2536*061da546Spatrick 
2537*061da546Spatrick   bool want_breakpoint = true;
2538*061da546Spatrick   bool want_hardware = false;
2539*061da546Spatrick   uint32_t watch_flags = 0;
2540*061da546Spatrick 
2541*061da546Spatrick   const GDBStoppointType stoppoint_type =
2542*061da546Spatrick       GDBStoppointType(packet.GetS32(eStoppointInvalid));
2543*061da546Spatrick   switch (stoppoint_type) {
2544*061da546Spatrick   case eBreakpointSoftware:
2545*061da546Spatrick     want_hardware = false;
2546*061da546Spatrick     want_breakpoint = true;
2547*061da546Spatrick     break;
2548*061da546Spatrick   case eBreakpointHardware:
2549*061da546Spatrick     want_hardware = true;
2550*061da546Spatrick     want_breakpoint = true;
2551*061da546Spatrick     break;
2552*061da546Spatrick   case eWatchpointWrite:
2553*061da546Spatrick     watch_flags = 1;
2554*061da546Spatrick     want_hardware = true;
2555*061da546Spatrick     want_breakpoint = false;
2556*061da546Spatrick     break;
2557*061da546Spatrick   case eWatchpointRead:
2558*061da546Spatrick     watch_flags = 2;
2559*061da546Spatrick     want_hardware = true;
2560*061da546Spatrick     want_breakpoint = false;
2561*061da546Spatrick     break;
2562*061da546Spatrick   case eWatchpointReadWrite:
2563*061da546Spatrick     watch_flags = 3;
2564*061da546Spatrick     want_hardware = true;
2565*061da546Spatrick     want_breakpoint = false;
2566*061da546Spatrick     break;
2567*061da546Spatrick   case eStoppointInvalid:
2568*061da546Spatrick     return SendIllFormedResponse(
2569*061da546Spatrick         packet, "Z packet had invalid software/hardware specifier");
2570*061da546Spatrick   }
2571*061da546Spatrick 
2572*061da546Spatrick   if ((packet.GetBytesLeft() < 1) || packet.GetChar() != ',')
2573*061da546Spatrick     return SendIllFormedResponse(
2574*061da546Spatrick         packet, "Malformed Z packet, expecting comma after stoppoint type");
2575*061da546Spatrick 
2576*061da546Spatrick   // Parse out the stoppoint address.
2577*061da546Spatrick   if (packet.GetBytesLeft() < 1)
2578*061da546Spatrick     return SendIllFormedResponse(packet, "Too short Z packet, missing address");
2579*061da546Spatrick   const lldb::addr_t addr = packet.GetHexMaxU64(false, 0);
2580*061da546Spatrick 
2581*061da546Spatrick   if ((packet.GetBytesLeft() < 1) || packet.GetChar() != ',')
2582*061da546Spatrick     return SendIllFormedResponse(
2583*061da546Spatrick         packet, "Malformed Z packet, expecting comma after address");
2584*061da546Spatrick 
2585*061da546Spatrick   // Parse out the stoppoint size (i.e. size hint for opcode size).
2586*061da546Spatrick   const uint32_t size =
2587*061da546Spatrick       packet.GetHexMaxU32(false, std::numeric_limits<uint32_t>::max());
2588*061da546Spatrick   if (size == std::numeric_limits<uint32_t>::max())
2589*061da546Spatrick     return SendIllFormedResponse(
2590*061da546Spatrick         packet, "Malformed Z packet, failed to parse size argument");
2591*061da546Spatrick 
2592*061da546Spatrick   if (want_breakpoint) {
2593*061da546Spatrick     // Try to set the breakpoint.
2594*061da546Spatrick     const Status error =
2595*061da546Spatrick         m_debugged_process_up->SetBreakpoint(addr, size, want_hardware);
2596*061da546Spatrick     if (error.Success())
2597*061da546Spatrick       return SendOKResponse();
2598*061da546Spatrick     Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_BREAKPOINTS));
2599*061da546Spatrick     LLDB_LOG(log, "pid {0} failed to set breakpoint: {1}",
2600*061da546Spatrick              m_debugged_process_up->GetID(), error);
2601*061da546Spatrick     return SendErrorResponse(0x09);
2602*061da546Spatrick   } else {
2603*061da546Spatrick     // Try to set the watchpoint.
2604*061da546Spatrick     const Status error = m_debugged_process_up->SetWatchpoint(
2605*061da546Spatrick         addr, size, watch_flags, want_hardware);
2606*061da546Spatrick     if (error.Success())
2607*061da546Spatrick       return SendOKResponse();
2608*061da546Spatrick     Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_WATCHPOINTS));
2609*061da546Spatrick     LLDB_LOG(log, "pid {0} failed to set watchpoint: {1}",
2610*061da546Spatrick              m_debugged_process_up->GetID(), error);
2611*061da546Spatrick     return SendErrorResponse(0x09);
2612*061da546Spatrick   }
2613*061da546Spatrick }
2614*061da546Spatrick 
2615*061da546Spatrick GDBRemoteCommunication::PacketResult
2616*061da546Spatrick GDBRemoteCommunicationServerLLGS::Handle_z(StringExtractorGDBRemote &packet) {
2617*061da546Spatrick   // Ensure we have a process.
2618*061da546Spatrick   if (!m_debugged_process_up ||
2619*061da546Spatrick       (m_debugged_process_up->GetID() == LLDB_INVALID_PROCESS_ID)) {
2620*061da546Spatrick     Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
2621*061da546Spatrick     LLDB_LOG(log, "failed, no process available");
2622*061da546Spatrick     return SendErrorResponse(0x15);
2623*061da546Spatrick   }
2624*061da546Spatrick 
2625*061da546Spatrick   // Parse out software or hardware breakpoint or watchpoint requested.
2626*061da546Spatrick   packet.SetFilePos(strlen("z"));
2627*061da546Spatrick   if (packet.GetBytesLeft() < 1)
2628*061da546Spatrick     return SendIllFormedResponse(
2629*061da546Spatrick         packet, "Too short z packet, missing software/hardware specifier");
2630*061da546Spatrick 
2631*061da546Spatrick   bool want_breakpoint = true;
2632*061da546Spatrick   bool want_hardware = false;
2633*061da546Spatrick 
2634*061da546Spatrick   const GDBStoppointType stoppoint_type =
2635*061da546Spatrick       GDBStoppointType(packet.GetS32(eStoppointInvalid));
2636*061da546Spatrick   switch (stoppoint_type) {
2637*061da546Spatrick   case eBreakpointHardware:
2638*061da546Spatrick     want_breakpoint = true;
2639*061da546Spatrick     want_hardware = true;
2640*061da546Spatrick     break;
2641*061da546Spatrick   case eBreakpointSoftware:
2642*061da546Spatrick     want_breakpoint = true;
2643*061da546Spatrick     break;
2644*061da546Spatrick   case eWatchpointWrite:
2645*061da546Spatrick     want_breakpoint = false;
2646*061da546Spatrick     break;
2647*061da546Spatrick   case eWatchpointRead:
2648*061da546Spatrick     want_breakpoint = false;
2649*061da546Spatrick     break;
2650*061da546Spatrick   case eWatchpointReadWrite:
2651*061da546Spatrick     want_breakpoint = false;
2652*061da546Spatrick     break;
2653*061da546Spatrick   default:
2654*061da546Spatrick     return SendIllFormedResponse(
2655*061da546Spatrick         packet, "z packet had invalid software/hardware specifier");
2656*061da546Spatrick   }
2657*061da546Spatrick 
2658*061da546Spatrick   if ((packet.GetBytesLeft() < 1) || packet.GetChar() != ',')
2659*061da546Spatrick     return SendIllFormedResponse(
2660*061da546Spatrick         packet, "Malformed z packet, expecting comma after stoppoint type");
2661*061da546Spatrick 
2662*061da546Spatrick   // Parse out the stoppoint address.
2663*061da546Spatrick   if (packet.GetBytesLeft() < 1)
2664*061da546Spatrick     return SendIllFormedResponse(packet, "Too short z packet, missing address");
2665*061da546Spatrick   const lldb::addr_t addr = packet.GetHexMaxU64(false, 0);
2666*061da546Spatrick 
2667*061da546Spatrick   if ((packet.GetBytesLeft() < 1) || packet.GetChar() != ',')
2668*061da546Spatrick     return SendIllFormedResponse(
2669*061da546Spatrick         packet, "Malformed z packet, expecting comma after address");
2670*061da546Spatrick 
2671*061da546Spatrick   /*
2672*061da546Spatrick   // Parse out the stoppoint size (i.e. size hint for opcode size).
2673*061da546Spatrick   const uint32_t size = packet.GetHexMaxU32 (false,
2674*061da546Spatrick   std::numeric_limits<uint32_t>::max ());
2675*061da546Spatrick   if (size == std::numeric_limits<uint32_t>::max ())
2676*061da546Spatrick       return SendIllFormedResponse(packet, "Malformed z packet, failed to parse
2677*061da546Spatrick   size argument");
2678*061da546Spatrick   */
2679*061da546Spatrick 
2680*061da546Spatrick   if (want_breakpoint) {
2681*061da546Spatrick     // Try to clear the breakpoint.
2682*061da546Spatrick     const Status error =
2683*061da546Spatrick         m_debugged_process_up->RemoveBreakpoint(addr, want_hardware);
2684*061da546Spatrick     if (error.Success())
2685*061da546Spatrick       return SendOKResponse();
2686*061da546Spatrick     Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_BREAKPOINTS));
2687*061da546Spatrick     LLDB_LOG(log, "pid {0} failed to remove breakpoint: {1}",
2688*061da546Spatrick              m_debugged_process_up->GetID(), error);
2689*061da546Spatrick     return SendErrorResponse(0x09);
2690*061da546Spatrick   } else {
2691*061da546Spatrick     // Try to clear the watchpoint.
2692*061da546Spatrick     const Status error = m_debugged_process_up->RemoveWatchpoint(addr);
2693*061da546Spatrick     if (error.Success())
2694*061da546Spatrick       return SendOKResponse();
2695*061da546Spatrick     Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_WATCHPOINTS));
2696*061da546Spatrick     LLDB_LOG(log, "pid {0} failed to remove watchpoint: {1}",
2697*061da546Spatrick              m_debugged_process_up->GetID(), error);
2698*061da546Spatrick     return SendErrorResponse(0x09);
2699*061da546Spatrick   }
2700*061da546Spatrick }
2701*061da546Spatrick 
2702*061da546Spatrick GDBRemoteCommunication::PacketResult
2703*061da546Spatrick GDBRemoteCommunicationServerLLGS::Handle_s(StringExtractorGDBRemote &packet) {
2704*061da546Spatrick   Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS | LIBLLDB_LOG_THREAD));
2705*061da546Spatrick 
2706*061da546Spatrick   // Ensure we have a process.
2707*061da546Spatrick   if (!m_debugged_process_up ||
2708*061da546Spatrick       (m_debugged_process_up->GetID() == LLDB_INVALID_PROCESS_ID)) {
2709*061da546Spatrick     LLDB_LOGF(
2710*061da546Spatrick         log,
2711*061da546Spatrick         "GDBRemoteCommunicationServerLLGS::%s failed, no process available",
2712*061da546Spatrick         __FUNCTION__);
2713*061da546Spatrick     return SendErrorResponse(0x32);
2714*061da546Spatrick   }
2715*061da546Spatrick 
2716*061da546Spatrick   // We first try to use a continue thread id.  If any one or any all set, use
2717*061da546Spatrick   // the current thread. Bail out if we don't have a thread id.
2718*061da546Spatrick   lldb::tid_t tid = GetContinueThreadID();
2719*061da546Spatrick   if (tid == 0 || tid == LLDB_INVALID_THREAD_ID)
2720*061da546Spatrick     tid = GetCurrentThreadID();
2721*061da546Spatrick   if (tid == LLDB_INVALID_THREAD_ID)
2722*061da546Spatrick     return SendErrorResponse(0x33);
2723*061da546Spatrick 
2724*061da546Spatrick   // Double check that we have such a thread.
2725*061da546Spatrick   // TODO investigate: on MacOSX we might need to do an UpdateThreads () here.
2726*061da546Spatrick   NativeThreadProtocol *thread = m_debugged_process_up->GetThreadByID(tid);
2727*061da546Spatrick   if (!thread)
2728*061da546Spatrick     return SendErrorResponse(0x33);
2729*061da546Spatrick 
2730*061da546Spatrick   // Create the step action for the given thread.
2731*061da546Spatrick   ResumeAction action = {tid, eStateStepping, LLDB_INVALID_SIGNAL_NUMBER};
2732*061da546Spatrick 
2733*061da546Spatrick   // Setup the actions list.
2734*061da546Spatrick   ResumeActionList actions;
2735*061da546Spatrick   actions.Append(action);
2736*061da546Spatrick 
2737*061da546Spatrick   // All other threads stop while we're single stepping a thread.
2738*061da546Spatrick   actions.SetDefaultThreadActionIfNeeded(eStateStopped, 0);
2739*061da546Spatrick   Status error = m_debugged_process_up->Resume(actions);
2740*061da546Spatrick   if (error.Fail()) {
2741*061da546Spatrick     LLDB_LOGF(log,
2742*061da546Spatrick               "GDBRemoteCommunicationServerLLGS::%s pid %" PRIu64
2743*061da546Spatrick               " tid %" PRIu64 " Resume() failed with error: %s",
2744*061da546Spatrick               __FUNCTION__, m_debugged_process_up->GetID(), tid,
2745*061da546Spatrick               error.AsCString());
2746*061da546Spatrick     return SendErrorResponse(0x49);
2747*061da546Spatrick   }
2748*061da546Spatrick 
2749*061da546Spatrick   // No response here - the stop or exit will come from the resulting action.
2750*061da546Spatrick   return PacketResult::Success;
2751*061da546Spatrick }
2752*061da546Spatrick 
2753*061da546Spatrick llvm::Expected<std::unique_ptr<llvm::MemoryBuffer>>
2754*061da546Spatrick GDBRemoteCommunicationServerLLGS::ReadXferObject(llvm::StringRef object,
2755*061da546Spatrick                                                  llvm::StringRef annex) {
2756*061da546Spatrick   if (object == "auxv") {
2757*061da546Spatrick     // Make sure we have a valid process.
2758*061da546Spatrick     if (!m_debugged_process_up ||
2759*061da546Spatrick         (m_debugged_process_up->GetID() == LLDB_INVALID_PROCESS_ID)) {
2760*061da546Spatrick       return llvm::createStringError(llvm::inconvertibleErrorCode(),
2761*061da546Spatrick                                      "No process available");
2762*061da546Spatrick     }
2763*061da546Spatrick 
2764*061da546Spatrick     // Grab the auxv data.
2765*061da546Spatrick     auto buffer_or_error = m_debugged_process_up->GetAuxvData();
2766*061da546Spatrick     if (!buffer_or_error)
2767*061da546Spatrick       return llvm::errorCodeToError(buffer_or_error.getError());
2768*061da546Spatrick     return std::move(*buffer_or_error);
2769*061da546Spatrick   }
2770*061da546Spatrick 
2771*061da546Spatrick   if (object == "libraries-svr4") {
2772*061da546Spatrick     auto library_list = m_debugged_process_up->GetLoadedSVR4Libraries();
2773*061da546Spatrick     if (!library_list)
2774*061da546Spatrick       return library_list.takeError();
2775*061da546Spatrick 
2776*061da546Spatrick     StreamString response;
2777*061da546Spatrick     response.Printf("<library-list-svr4 version=\"1.0\">");
2778*061da546Spatrick     for (auto const &library : *library_list) {
2779*061da546Spatrick       response.Printf("<library name=\"%s\" ",
2780*061da546Spatrick                       XMLEncodeAttributeValue(library.name.c_str()).c_str());
2781*061da546Spatrick       response.Printf("lm=\"0x%" PRIx64 "\" ", library.link_map);
2782*061da546Spatrick       response.Printf("l_addr=\"0x%" PRIx64 "\" ", library.base_addr);
2783*061da546Spatrick       response.Printf("l_ld=\"0x%" PRIx64 "\" />", library.ld_addr);
2784*061da546Spatrick     }
2785*061da546Spatrick     response.Printf("</library-list-svr4>");
2786*061da546Spatrick     return MemoryBuffer::getMemBufferCopy(response.GetString(), __FUNCTION__);
2787*061da546Spatrick   }
2788*061da546Spatrick 
2789*061da546Spatrick   return llvm::make_error<PacketUnimplementedError>(
2790*061da546Spatrick       "Xfer object not supported");
2791*061da546Spatrick }
2792*061da546Spatrick 
2793*061da546Spatrick GDBRemoteCommunication::PacketResult
2794*061da546Spatrick GDBRemoteCommunicationServerLLGS::Handle_qXfer(
2795*061da546Spatrick     StringExtractorGDBRemote &packet) {
2796*061da546Spatrick   SmallVector<StringRef, 5> fields;
2797*061da546Spatrick   // The packet format is "qXfer:<object>:<action>:<annex>:offset,length"
2798*061da546Spatrick   StringRef(packet.GetStringRef()).split(fields, ':', 4);
2799*061da546Spatrick   if (fields.size() != 5)
2800*061da546Spatrick     return SendIllFormedResponse(packet, "malformed qXfer packet");
2801*061da546Spatrick   StringRef &xfer_object = fields[1];
2802*061da546Spatrick   StringRef &xfer_action = fields[2];
2803*061da546Spatrick   StringRef &xfer_annex = fields[3];
2804*061da546Spatrick   StringExtractor offset_data(fields[4]);
2805*061da546Spatrick   if (xfer_action != "read")
2806*061da546Spatrick     return SendUnimplementedResponse("qXfer action not supported");
2807*061da546Spatrick   // Parse offset.
2808*061da546Spatrick   const uint64_t xfer_offset =
2809*061da546Spatrick       offset_data.GetHexMaxU64(false, std::numeric_limits<uint64_t>::max());
2810*061da546Spatrick   if (xfer_offset == std::numeric_limits<uint64_t>::max())
2811*061da546Spatrick     return SendIllFormedResponse(packet, "qXfer packet missing offset");
2812*061da546Spatrick   // Parse out comma.
2813*061da546Spatrick   if (offset_data.GetChar() != ',')
2814*061da546Spatrick     return SendIllFormedResponse(packet,
2815*061da546Spatrick                                  "qXfer packet missing comma after offset");
2816*061da546Spatrick   // Parse out the length.
2817*061da546Spatrick   const uint64_t xfer_length =
2818*061da546Spatrick       offset_data.GetHexMaxU64(false, std::numeric_limits<uint64_t>::max());
2819*061da546Spatrick   if (xfer_length == std::numeric_limits<uint64_t>::max())
2820*061da546Spatrick     return SendIllFormedResponse(packet, "qXfer packet missing length");
2821*061da546Spatrick 
2822*061da546Spatrick   // Get a previously constructed buffer if it exists or create it now.
2823*061da546Spatrick   std::string buffer_key = (xfer_object + xfer_action + xfer_annex).str();
2824*061da546Spatrick   auto buffer_it = m_xfer_buffer_map.find(buffer_key);
2825*061da546Spatrick   if (buffer_it == m_xfer_buffer_map.end()) {
2826*061da546Spatrick     auto buffer_up = ReadXferObject(xfer_object, xfer_annex);
2827*061da546Spatrick     if (!buffer_up)
2828*061da546Spatrick       return SendErrorResponse(buffer_up.takeError());
2829*061da546Spatrick     buffer_it = m_xfer_buffer_map
2830*061da546Spatrick                     .insert(std::make_pair(buffer_key, std::move(*buffer_up)))
2831*061da546Spatrick                     .first;
2832*061da546Spatrick   }
2833*061da546Spatrick 
2834*061da546Spatrick   // Send back the response
2835*061da546Spatrick   StreamGDBRemote response;
2836*061da546Spatrick   bool done_with_buffer = false;
2837*061da546Spatrick   llvm::StringRef buffer = buffer_it->second->getBuffer();
2838*061da546Spatrick   if (xfer_offset >= buffer.size()) {
2839*061da546Spatrick     // We have nothing left to send.  Mark the buffer as complete.
2840*061da546Spatrick     response.PutChar('l');
2841*061da546Spatrick     done_with_buffer = true;
2842*061da546Spatrick   } else {
2843*061da546Spatrick     // Figure out how many bytes are available starting at the given offset.
2844*061da546Spatrick     buffer = buffer.drop_front(xfer_offset);
2845*061da546Spatrick     // Mark the response type according to whether we're reading the remainder
2846*061da546Spatrick     // of the data.
2847*061da546Spatrick     if (xfer_length >= buffer.size()) {
2848*061da546Spatrick       // There will be nothing left to read after this
2849*061da546Spatrick       response.PutChar('l');
2850*061da546Spatrick       done_with_buffer = true;
2851*061da546Spatrick     } else {
2852*061da546Spatrick       // There will still be bytes to read after this request.
2853*061da546Spatrick       response.PutChar('m');
2854*061da546Spatrick       buffer = buffer.take_front(xfer_length);
2855*061da546Spatrick     }
2856*061da546Spatrick     // Now write the data in encoded binary form.
2857*061da546Spatrick     response.PutEscapedBytes(buffer.data(), buffer.size());
2858*061da546Spatrick   }
2859*061da546Spatrick 
2860*061da546Spatrick   if (done_with_buffer)
2861*061da546Spatrick     m_xfer_buffer_map.erase(buffer_it);
2862*061da546Spatrick 
2863*061da546Spatrick   return SendPacketNoLock(response.GetString());
2864*061da546Spatrick }
2865*061da546Spatrick 
2866*061da546Spatrick GDBRemoteCommunication::PacketResult
2867*061da546Spatrick GDBRemoteCommunicationServerLLGS::Handle_QSaveRegisterState(
2868*061da546Spatrick     StringExtractorGDBRemote &packet) {
2869*061da546Spatrick   Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_THREAD));
2870*061da546Spatrick 
2871*061da546Spatrick   // Move past packet name.
2872*061da546Spatrick   packet.SetFilePos(strlen("QSaveRegisterState"));
2873*061da546Spatrick 
2874*061da546Spatrick   // Get the thread to use.
2875*061da546Spatrick   NativeThreadProtocol *thread = GetThreadFromSuffix(packet);
2876*061da546Spatrick   if (!thread) {
2877*061da546Spatrick     if (m_thread_suffix_supported)
2878*061da546Spatrick       return SendIllFormedResponse(
2879*061da546Spatrick           packet, "No thread specified in QSaveRegisterState packet");
2880*061da546Spatrick     else
2881*061da546Spatrick       return SendIllFormedResponse(packet,
2882*061da546Spatrick                                    "No thread was is set with the Hg packet");
2883*061da546Spatrick   }
2884*061da546Spatrick 
2885*061da546Spatrick   // Grab the register context for the thread.
2886*061da546Spatrick   NativeRegisterContext& reg_context = thread->GetRegisterContext();
2887*061da546Spatrick 
2888*061da546Spatrick   // Save registers to a buffer.
2889*061da546Spatrick   DataBufferSP register_data_sp;
2890*061da546Spatrick   Status error = reg_context.ReadAllRegisterValues(register_data_sp);
2891*061da546Spatrick   if (error.Fail()) {
2892*061da546Spatrick     LLDB_LOG(log, "pid {0} failed to save all register values: {1}",
2893*061da546Spatrick              m_debugged_process_up->GetID(), error);
2894*061da546Spatrick     return SendErrorResponse(0x75);
2895*061da546Spatrick   }
2896*061da546Spatrick 
2897*061da546Spatrick   // Allocate a new save id.
2898*061da546Spatrick   const uint32_t save_id = GetNextSavedRegistersID();
2899*061da546Spatrick   assert((m_saved_registers_map.find(save_id) == m_saved_registers_map.end()) &&
2900*061da546Spatrick          "GetNextRegisterSaveID() returned an existing register save id");
2901*061da546Spatrick 
2902*061da546Spatrick   // Save the register data buffer under the save id.
2903*061da546Spatrick   {
2904*061da546Spatrick     std::lock_guard<std::mutex> guard(m_saved_registers_mutex);
2905*061da546Spatrick     m_saved_registers_map[save_id] = register_data_sp;
2906*061da546Spatrick   }
2907*061da546Spatrick 
2908*061da546Spatrick   // Write the response.
2909*061da546Spatrick   StreamGDBRemote response;
2910*061da546Spatrick   response.Printf("%" PRIu32, save_id);
2911*061da546Spatrick   return SendPacketNoLock(response.GetString());
2912*061da546Spatrick }
2913*061da546Spatrick 
2914*061da546Spatrick GDBRemoteCommunication::PacketResult
2915*061da546Spatrick GDBRemoteCommunicationServerLLGS::Handle_QRestoreRegisterState(
2916*061da546Spatrick     StringExtractorGDBRemote &packet) {
2917*061da546Spatrick   Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_THREAD));
2918*061da546Spatrick 
2919*061da546Spatrick   // Parse out save id.
2920*061da546Spatrick   packet.SetFilePos(strlen("QRestoreRegisterState:"));
2921*061da546Spatrick   if (packet.GetBytesLeft() < 1)
2922*061da546Spatrick     return SendIllFormedResponse(
2923*061da546Spatrick         packet, "QRestoreRegisterState packet missing register save id");
2924*061da546Spatrick 
2925*061da546Spatrick   const uint32_t save_id = packet.GetU32(0);
2926*061da546Spatrick   if (save_id == 0) {
2927*061da546Spatrick     LLDB_LOG(log, "QRestoreRegisterState packet has malformed save id, "
2928*061da546Spatrick                   "expecting decimal uint32_t");
2929*061da546Spatrick     return SendErrorResponse(0x76);
2930*061da546Spatrick   }
2931*061da546Spatrick 
2932*061da546Spatrick   // Get the thread to use.
2933*061da546Spatrick   NativeThreadProtocol *thread = GetThreadFromSuffix(packet);
2934*061da546Spatrick   if (!thread) {
2935*061da546Spatrick     if (m_thread_suffix_supported)
2936*061da546Spatrick       return SendIllFormedResponse(
2937*061da546Spatrick           packet, "No thread specified in QRestoreRegisterState packet");
2938*061da546Spatrick     else
2939*061da546Spatrick       return SendIllFormedResponse(packet,
2940*061da546Spatrick                                    "No thread was is set with the Hg packet");
2941*061da546Spatrick   }
2942*061da546Spatrick 
2943*061da546Spatrick   // Grab the register context for the thread.
2944*061da546Spatrick   NativeRegisterContext &reg_context = thread->GetRegisterContext();
2945*061da546Spatrick 
2946*061da546Spatrick   // Retrieve register state buffer, then remove from the list.
2947*061da546Spatrick   DataBufferSP register_data_sp;
2948*061da546Spatrick   {
2949*061da546Spatrick     std::lock_guard<std::mutex> guard(m_saved_registers_mutex);
2950*061da546Spatrick 
2951*061da546Spatrick     // Find the register set buffer for the given save id.
2952*061da546Spatrick     auto it = m_saved_registers_map.find(save_id);
2953*061da546Spatrick     if (it == m_saved_registers_map.end()) {
2954*061da546Spatrick       LLDB_LOG(log,
2955*061da546Spatrick                "pid {0} does not have a register set save buffer for id {1}",
2956*061da546Spatrick                m_debugged_process_up->GetID(), save_id);
2957*061da546Spatrick       return SendErrorResponse(0x77);
2958*061da546Spatrick     }
2959*061da546Spatrick     register_data_sp = it->second;
2960*061da546Spatrick 
2961*061da546Spatrick     // Remove it from the map.
2962*061da546Spatrick     m_saved_registers_map.erase(it);
2963*061da546Spatrick   }
2964*061da546Spatrick 
2965*061da546Spatrick   Status error = reg_context.WriteAllRegisterValues(register_data_sp);
2966*061da546Spatrick   if (error.Fail()) {
2967*061da546Spatrick     LLDB_LOG(log, "pid {0} failed to restore all register values: {1}",
2968*061da546Spatrick              m_debugged_process_up->GetID(), error);
2969*061da546Spatrick     return SendErrorResponse(0x77);
2970*061da546Spatrick   }
2971*061da546Spatrick 
2972*061da546Spatrick   return SendOKResponse();
2973*061da546Spatrick }
2974*061da546Spatrick 
2975*061da546Spatrick GDBRemoteCommunication::PacketResult
2976*061da546Spatrick GDBRemoteCommunicationServerLLGS::Handle_vAttach(
2977*061da546Spatrick     StringExtractorGDBRemote &packet) {
2978*061da546Spatrick   Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
2979*061da546Spatrick 
2980*061da546Spatrick   // Consume the ';' after vAttach.
2981*061da546Spatrick   packet.SetFilePos(strlen("vAttach"));
2982*061da546Spatrick   if (!packet.GetBytesLeft() || packet.GetChar() != ';')
2983*061da546Spatrick     return SendIllFormedResponse(packet, "vAttach missing expected ';'");
2984*061da546Spatrick 
2985*061da546Spatrick   // Grab the PID to which we will attach (assume hex encoding).
2986*061da546Spatrick   lldb::pid_t pid = packet.GetU32(LLDB_INVALID_PROCESS_ID, 16);
2987*061da546Spatrick   if (pid == LLDB_INVALID_PROCESS_ID)
2988*061da546Spatrick     return SendIllFormedResponse(packet,
2989*061da546Spatrick                                  "vAttach failed to parse the process id");
2990*061da546Spatrick 
2991*061da546Spatrick   // Attempt to attach.
2992*061da546Spatrick   LLDB_LOGF(log,
2993*061da546Spatrick             "GDBRemoteCommunicationServerLLGS::%s attempting to attach to "
2994*061da546Spatrick             "pid %" PRIu64,
2995*061da546Spatrick             __FUNCTION__, pid);
2996*061da546Spatrick 
2997*061da546Spatrick   Status error = AttachToProcess(pid);
2998*061da546Spatrick 
2999*061da546Spatrick   if (error.Fail()) {
3000*061da546Spatrick     LLDB_LOGF(log,
3001*061da546Spatrick               "GDBRemoteCommunicationServerLLGS::%s failed to attach to "
3002*061da546Spatrick               "pid %" PRIu64 ": %s\n",
3003*061da546Spatrick               __FUNCTION__, pid, error.AsCString());
3004*061da546Spatrick     return SendErrorResponse(error);
3005*061da546Spatrick   }
3006*061da546Spatrick 
3007*061da546Spatrick   // Notify we attached by sending a stop packet.
3008*061da546Spatrick   return SendStopReasonForState(m_debugged_process_up->GetState());
3009*061da546Spatrick }
3010*061da546Spatrick 
3011*061da546Spatrick GDBRemoteCommunication::PacketResult
3012*061da546Spatrick GDBRemoteCommunicationServerLLGS::Handle_D(StringExtractorGDBRemote &packet) {
3013*061da546Spatrick   Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
3014*061da546Spatrick 
3015*061da546Spatrick   StopSTDIOForwarding();
3016*061da546Spatrick 
3017*061da546Spatrick   // Fail if we don't have a current process.
3018*061da546Spatrick   if (!m_debugged_process_up ||
3019*061da546Spatrick       (m_debugged_process_up->GetID() == LLDB_INVALID_PROCESS_ID)) {
3020*061da546Spatrick     LLDB_LOGF(
3021*061da546Spatrick         log,
3022*061da546Spatrick         "GDBRemoteCommunicationServerLLGS::%s failed, no process available",
3023*061da546Spatrick         __FUNCTION__);
3024*061da546Spatrick     return SendErrorResponse(0x15);
3025*061da546Spatrick   }
3026*061da546Spatrick 
3027*061da546Spatrick   lldb::pid_t pid = LLDB_INVALID_PROCESS_ID;
3028*061da546Spatrick 
3029*061da546Spatrick   // Consume the ';' after D.
3030*061da546Spatrick   packet.SetFilePos(1);
3031*061da546Spatrick   if (packet.GetBytesLeft()) {
3032*061da546Spatrick     if (packet.GetChar() != ';')
3033*061da546Spatrick       return SendIllFormedResponse(packet, "D missing expected ';'");
3034*061da546Spatrick 
3035*061da546Spatrick     // Grab the PID from which we will detach (assume hex encoding).
3036*061da546Spatrick     pid = packet.GetU32(LLDB_INVALID_PROCESS_ID, 16);
3037*061da546Spatrick     if (pid == LLDB_INVALID_PROCESS_ID)
3038*061da546Spatrick       return SendIllFormedResponse(packet, "D failed to parse the process id");
3039*061da546Spatrick   }
3040*061da546Spatrick 
3041*061da546Spatrick   if (pid != LLDB_INVALID_PROCESS_ID && m_debugged_process_up->GetID() != pid) {
3042*061da546Spatrick     return SendIllFormedResponse(packet, "Invalid pid");
3043*061da546Spatrick   }
3044*061da546Spatrick 
3045*061da546Spatrick   const Status error = m_debugged_process_up->Detach();
3046*061da546Spatrick   if (error.Fail()) {
3047*061da546Spatrick     LLDB_LOGF(log,
3048*061da546Spatrick               "GDBRemoteCommunicationServerLLGS::%s failed to detach from "
3049*061da546Spatrick               "pid %" PRIu64 ": %s\n",
3050*061da546Spatrick               __FUNCTION__, m_debugged_process_up->GetID(), error.AsCString());
3051*061da546Spatrick     return SendErrorResponse(0x01);
3052*061da546Spatrick   }
3053*061da546Spatrick 
3054*061da546Spatrick   return SendOKResponse();
3055*061da546Spatrick }
3056*061da546Spatrick 
3057*061da546Spatrick GDBRemoteCommunication::PacketResult
3058*061da546Spatrick GDBRemoteCommunicationServerLLGS::Handle_qThreadStopInfo(
3059*061da546Spatrick     StringExtractorGDBRemote &packet) {
3060*061da546Spatrick   Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_THREAD));
3061*061da546Spatrick 
3062*061da546Spatrick   packet.SetFilePos(strlen("qThreadStopInfo"));
3063*061da546Spatrick   const lldb::tid_t tid = packet.GetHexMaxU32(false, LLDB_INVALID_THREAD_ID);
3064*061da546Spatrick   if (tid == LLDB_INVALID_THREAD_ID) {
3065*061da546Spatrick     LLDB_LOGF(log,
3066*061da546Spatrick               "GDBRemoteCommunicationServerLLGS::%s failed, could not "
3067*061da546Spatrick               "parse thread id from request \"%s\"",
3068*061da546Spatrick               __FUNCTION__, packet.GetStringRef().data());
3069*061da546Spatrick     return SendErrorResponse(0x15);
3070*061da546Spatrick   }
3071*061da546Spatrick   return SendStopReplyPacketForThread(tid);
3072*061da546Spatrick }
3073*061da546Spatrick 
3074*061da546Spatrick GDBRemoteCommunication::PacketResult
3075*061da546Spatrick GDBRemoteCommunicationServerLLGS::Handle_jThreadsInfo(
3076*061da546Spatrick     StringExtractorGDBRemote &) {
3077*061da546Spatrick   Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS | LIBLLDB_LOG_THREAD));
3078*061da546Spatrick 
3079*061da546Spatrick   // Ensure we have a debugged process.
3080*061da546Spatrick   if (!m_debugged_process_up ||
3081*061da546Spatrick       (m_debugged_process_up->GetID() == LLDB_INVALID_PROCESS_ID))
3082*061da546Spatrick     return SendErrorResponse(50);
3083*061da546Spatrick   LLDB_LOG(log, "preparing packet for pid {0}", m_debugged_process_up->GetID());
3084*061da546Spatrick 
3085*061da546Spatrick   StreamString response;
3086*061da546Spatrick   const bool threads_with_valid_stop_info_only = false;
3087*061da546Spatrick   llvm::Expected<json::Value> threads_info = GetJSONThreadsInfo(
3088*061da546Spatrick       *m_debugged_process_up, threads_with_valid_stop_info_only);
3089*061da546Spatrick   if (!threads_info) {
3090*061da546Spatrick     LLDB_LOG_ERROR(log, threads_info.takeError(),
3091*061da546Spatrick                    "failed to prepare a packet for pid {1}: {0}",
3092*061da546Spatrick                    m_debugged_process_up->GetID());
3093*061da546Spatrick     return SendErrorResponse(52);
3094*061da546Spatrick   }
3095*061da546Spatrick 
3096*061da546Spatrick   response.AsRawOstream() << *threads_info;
3097*061da546Spatrick   StreamGDBRemote escaped_response;
3098*061da546Spatrick   escaped_response.PutEscapedBytes(response.GetData(), response.GetSize());
3099*061da546Spatrick   return SendPacketNoLock(escaped_response.GetString());
3100*061da546Spatrick }
3101*061da546Spatrick 
3102*061da546Spatrick GDBRemoteCommunication::PacketResult
3103*061da546Spatrick GDBRemoteCommunicationServerLLGS::Handle_qWatchpointSupportInfo(
3104*061da546Spatrick     StringExtractorGDBRemote &packet) {
3105*061da546Spatrick   // Fail if we don't have a current process.
3106*061da546Spatrick   if (!m_debugged_process_up ||
3107*061da546Spatrick       m_debugged_process_up->GetID() == LLDB_INVALID_PROCESS_ID)
3108*061da546Spatrick     return SendErrorResponse(68);
3109*061da546Spatrick 
3110*061da546Spatrick   packet.SetFilePos(strlen("qWatchpointSupportInfo"));
3111*061da546Spatrick   if (packet.GetBytesLeft() == 0)
3112*061da546Spatrick     return SendOKResponse();
3113*061da546Spatrick   if (packet.GetChar() != ':')
3114*061da546Spatrick     return SendErrorResponse(67);
3115*061da546Spatrick 
3116*061da546Spatrick   auto hw_debug_cap = m_debugged_process_up->GetHardwareDebugSupportInfo();
3117*061da546Spatrick 
3118*061da546Spatrick   StreamGDBRemote response;
3119*061da546Spatrick   if (hw_debug_cap == llvm::None)
3120*061da546Spatrick     response.Printf("num:0;");
3121*061da546Spatrick   else
3122*061da546Spatrick     response.Printf("num:%d;", hw_debug_cap->second);
3123*061da546Spatrick 
3124*061da546Spatrick   return SendPacketNoLock(response.GetString());
3125*061da546Spatrick }
3126*061da546Spatrick 
3127*061da546Spatrick GDBRemoteCommunication::PacketResult
3128*061da546Spatrick GDBRemoteCommunicationServerLLGS::Handle_qFileLoadAddress(
3129*061da546Spatrick     StringExtractorGDBRemote &packet) {
3130*061da546Spatrick   // Fail if we don't have a current process.
3131*061da546Spatrick   if (!m_debugged_process_up ||
3132*061da546Spatrick       m_debugged_process_up->GetID() == LLDB_INVALID_PROCESS_ID)
3133*061da546Spatrick     return SendErrorResponse(67);
3134*061da546Spatrick 
3135*061da546Spatrick   packet.SetFilePos(strlen("qFileLoadAddress:"));
3136*061da546Spatrick   if (packet.GetBytesLeft() == 0)
3137*061da546Spatrick     return SendErrorResponse(68);
3138*061da546Spatrick 
3139*061da546Spatrick   std::string file_name;
3140*061da546Spatrick   packet.GetHexByteString(file_name);
3141*061da546Spatrick 
3142*061da546Spatrick   lldb::addr_t file_load_address = LLDB_INVALID_ADDRESS;
3143*061da546Spatrick   Status error =
3144*061da546Spatrick       m_debugged_process_up->GetFileLoadAddress(file_name, file_load_address);
3145*061da546Spatrick   if (error.Fail())
3146*061da546Spatrick     return SendErrorResponse(69);
3147*061da546Spatrick 
3148*061da546Spatrick   if (file_load_address == LLDB_INVALID_ADDRESS)
3149*061da546Spatrick     return SendErrorResponse(1); // File not loaded
3150*061da546Spatrick 
3151*061da546Spatrick   StreamGDBRemote response;
3152*061da546Spatrick   response.PutHex64(file_load_address);
3153*061da546Spatrick   return SendPacketNoLock(response.GetString());
3154*061da546Spatrick }
3155*061da546Spatrick 
3156*061da546Spatrick GDBRemoteCommunication::PacketResult
3157*061da546Spatrick GDBRemoteCommunicationServerLLGS::Handle_QPassSignals(
3158*061da546Spatrick     StringExtractorGDBRemote &packet) {
3159*061da546Spatrick   std::vector<int> signals;
3160*061da546Spatrick   packet.SetFilePos(strlen("QPassSignals:"));
3161*061da546Spatrick 
3162*061da546Spatrick   // Read sequence of hex signal numbers divided by a semicolon and optionally
3163*061da546Spatrick   // spaces.
3164*061da546Spatrick   while (packet.GetBytesLeft() > 0) {
3165*061da546Spatrick     int signal = packet.GetS32(-1, 16);
3166*061da546Spatrick     if (signal < 0)
3167*061da546Spatrick       return SendIllFormedResponse(packet, "Failed to parse signal number.");
3168*061da546Spatrick     signals.push_back(signal);
3169*061da546Spatrick 
3170*061da546Spatrick     packet.SkipSpaces();
3171*061da546Spatrick     char separator = packet.GetChar();
3172*061da546Spatrick     if (separator == '\0')
3173*061da546Spatrick       break; // End of string
3174*061da546Spatrick     if (separator != ';')
3175*061da546Spatrick       return SendIllFormedResponse(packet, "Invalid separator,"
3176*061da546Spatrick                                             " expected semicolon.");
3177*061da546Spatrick   }
3178*061da546Spatrick 
3179*061da546Spatrick   // Fail if we don't have a current process.
3180*061da546Spatrick   if (!m_debugged_process_up)
3181*061da546Spatrick     return SendErrorResponse(68);
3182*061da546Spatrick 
3183*061da546Spatrick   Status error = m_debugged_process_up->IgnoreSignals(signals);
3184*061da546Spatrick   if (error.Fail())
3185*061da546Spatrick     return SendErrorResponse(69);
3186*061da546Spatrick 
3187*061da546Spatrick   return SendOKResponse();
3188*061da546Spatrick }
3189*061da546Spatrick 
3190*061da546Spatrick void GDBRemoteCommunicationServerLLGS::MaybeCloseInferiorTerminalConnection() {
3191*061da546Spatrick   Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
3192*061da546Spatrick 
3193*061da546Spatrick   // Tell the stdio connection to shut down.
3194*061da546Spatrick   if (m_stdio_communication.IsConnected()) {
3195*061da546Spatrick     auto connection = m_stdio_communication.GetConnection();
3196*061da546Spatrick     if (connection) {
3197*061da546Spatrick       Status error;
3198*061da546Spatrick       connection->Disconnect(&error);
3199*061da546Spatrick 
3200*061da546Spatrick       if (error.Success()) {
3201*061da546Spatrick         LLDB_LOGF(log,
3202*061da546Spatrick                   "GDBRemoteCommunicationServerLLGS::%s disconnect process "
3203*061da546Spatrick                   "terminal stdio - SUCCESS",
3204*061da546Spatrick                   __FUNCTION__);
3205*061da546Spatrick       } else {
3206*061da546Spatrick         LLDB_LOGF(log,
3207*061da546Spatrick                   "GDBRemoteCommunicationServerLLGS::%s disconnect process "
3208*061da546Spatrick                   "terminal stdio - FAIL: %s",
3209*061da546Spatrick                   __FUNCTION__, error.AsCString());
3210*061da546Spatrick       }
3211*061da546Spatrick     }
3212*061da546Spatrick   }
3213*061da546Spatrick }
3214*061da546Spatrick 
3215*061da546Spatrick NativeThreadProtocol *GDBRemoteCommunicationServerLLGS::GetThreadFromSuffix(
3216*061da546Spatrick     StringExtractorGDBRemote &packet) {
3217*061da546Spatrick   // We have no thread if we don't have a process.
3218*061da546Spatrick   if (!m_debugged_process_up ||
3219*061da546Spatrick       m_debugged_process_up->GetID() == LLDB_INVALID_PROCESS_ID)
3220*061da546Spatrick     return nullptr;
3221*061da546Spatrick 
3222*061da546Spatrick   // If the client hasn't asked for thread suffix support, there will not be a
3223*061da546Spatrick   // thread suffix. Use the current thread in that case.
3224*061da546Spatrick   if (!m_thread_suffix_supported) {
3225*061da546Spatrick     const lldb::tid_t current_tid = GetCurrentThreadID();
3226*061da546Spatrick     if (current_tid == LLDB_INVALID_THREAD_ID)
3227*061da546Spatrick       return nullptr;
3228*061da546Spatrick     else if (current_tid == 0) {
3229*061da546Spatrick       // Pick a thread.
3230*061da546Spatrick       return m_debugged_process_up->GetThreadAtIndex(0);
3231*061da546Spatrick     } else
3232*061da546Spatrick       return m_debugged_process_up->GetThreadByID(current_tid);
3233*061da546Spatrick   }
3234*061da546Spatrick 
3235*061da546Spatrick   Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_THREAD));
3236*061da546Spatrick 
3237*061da546Spatrick   // Parse out the ';'.
3238*061da546Spatrick   if (packet.GetBytesLeft() < 1 || packet.GetChar() != ';') {
3239*061da546Spatrick     LLDB_LOGF(log,
3240*061da546Spatrick               "GDBRemoteCommunicationServerLLGS::%s gdb-remote parse "
3241*061da546Spatrick               "error: expected ';' prior to start of thread suffix: packet "
3242*061da546Spatrick               "contents = '%s'",
3243*061da546Spatrick               __FUNCTION__, packet.GetStringRef().data());
3244*061da546Spatrick     return nullptr;
3245*061da546Spatrick   }
3246*061da546Spatrick 
3247*061da546Spatrick   if (!packet.GetBytesLeft())
3248*061da546Spatrick     return nullptr;
3249*061da546Spatrick 
3250*061da546Spatrick   // Parse out thread: portion.
3251*061da546Spatrick   if (strncmp(packet.Peek(), "thread:", strlen("thread:")) != 0) {
3252*061da546Spatrick     LLDB_LOGF(log,
3253*061da546Spatrick               "GDBRemoteCommunicationServerLLGS::%s gdb-remote parse "
3254*061da546Spatrick               "error: expected 'thread:' but not found, packet contents = "
3255*061da546Spatrick               "'%s'",
3256*061da546Spatrick               __FUNCTION__, packet.GetStringRef().data());
3257*061da546Spatrick     return nullptr;
3258*061da546Spatrick   }
3259*061da546Spatrick   packet.SetFilePos(packet.GetFilePos() + strlen("thread:"));
3260*061da546Spatrick   const lldb::tid_t tid = packet.GetHexMaxU64(false, 0);
3261*061da546Spatrick   if (tid != 0)
3262*061da546Spatrick     return m_debugged_process_up->GetThreadByID(tid);
3263*061da546Spatrick 
3264*061da546Spatrick   return nullptr;
3265*061da546Spatrick }
3266*061da546Spatrick 
3267*061da546Spatrick lldb::tid_t GDBRemoteCommunicationServerLLGS::GetCurrentThreadID() const {
3268*061da546Spatrick   if (m_current_tid == 0 || m_current_tid == LLDB_INVALID_THREAD_ID) {
3269*061da546Spatrick     // Use whatever the debug process says is the current thread id since the
3270*061da546Spatrick     // protocol either didn't specify or specified we want any/all threads
3271*061da546Spatrick     // marked as the current thread.
3272*061da546Spatrick     if (!m_debugged_process_up)
3273*061da546Spatrick       return LLDB_INVALID_THREAD_ID;
3274*061da546Spatrick     return m_debugged_process_up->GetCurrentThreadID();
3275*061da546Spatrick   }
3276*061da546Spatrick   // Use the specific current thread id set by the gdb remote protocol.
3277*061da546Spatrick   return m_current_tid;
3278*061da546Spatrick }
3279*061da546Spatrick 
3280*061da546Spatrick uint32_t GDBRemoteCommunicationServerLLGS::GetNextSavedRegistersID() {
3281*061da546Spatrick   std::lock_guard<std::mutex> guard(m_saved_registers_mutex);
3282*061da546Spatrick   return m_next_saved_registers_id++;
3283*061da546Spatrick }
3284*061da546Spatrick 
3285*061da546Spatrick void GDBRemoteCommunicationServerLLGS::ClearProcessSpecificData() {
3286*061da546Spatrick   Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
3287*061da546Spatrick 
3288*061da546Spatrick   LLDB_LOG(log, "clearing {0} xfer buffers", m_xfer_buffer_map.size());
3289*061da546Spatrick   m_xfer_buffer_map.clear();
3290*061da546Spatrick }
3291*061da546Spatrick 
3292*061da546Spatrick FileSpec
3293*061da546Spatrick GDBRemoteCommunicationServerLLGS::FindModuleFile(const std::string &module_path,
3294*061da546Spatrick                                                  const ArchSpec &arch) {
3295*061da546Spatrick   if (m_debugged_process_up) {
3296*061da546Spatrick     FileSpec file_spec;
3297*061da546Spatrick     if (m_debugged_process_up
3298*061da546Spatrick             ->GetLoadedModuleFileSpec(module_path.c_str(), file_spec)
3299*061da546Spatrick             .Success()) {
3300*061da546Spatrick       if (FileSystem::Instance().Exists(file_spec))
3301*061da546Spatrick         return file_spec;
3302*061da546Spatrick     }
3303*061da546Spatrick   }
3304*061da546Spatrick 
3305*061da546Spatrick   return GDBRemoteCommunicationServerCommon::FindModuleFile(module_path, arch);
3306*061da546Spatrick }
3307*061da546Spatrick 
3308*061da546Spatrick std::string GDBRemoteCommunicationServerLLGS::XMLEncodeAttributeValue(
3309*061da546Spatrick     llvm::StringRef value) {
3310*061da546Spatrick   std::string result;
3311*061da546Spatrick   for (const char &c : value) {
3312*061da546Spatrick     switch (c) {
3313*061da546Spatrick     case '\'':
3314*061da546Spatrick       result += "&apos;";
3315*061da546Spatrick       break;
3316*061da546Spatrick     case '"':
3317*061da546Spatrick       result += "&quot;";
3318*061da546Spatrick       break;
3319*061da546Spatrick     case '<':
3320*061da546Spatrick       result += "&lt;";
3321*061da546Spatrick       break;
3322*061da546Spatrick     case '>':
3323*061da546Spatrick       result += "&gt;";
3324*061da546Spatrick       break;
3325*061da546Spatrick     default:
3326*061da546Spatrick       result += c;
3327*061da546Spatrick       break;
3328*061da546Spatrick     }
3329*061da546Spatrick   }
3330*061da546Spatrick   return result;
3331*061da546Spatrick }
3332