xref: /openbsd-src/gnu/llvm/lldb/source/Plugins/Process/gdb-remote/GDBRemoteCommunicationServerLLGS.cpp (revision be691f3bb6417f04a68938fadbcaee2d5795e764)
1dda28197Spatrick //===-- GDBRemoteCommunicationServerLLGS.cpp ------------------------------===//
2061da546Spatrick //
3061da546Spatrick // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4061da546Spatrick // See https://llvm.org/LICENSE.txt for license information.
5061da546Spatrick // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6061da546Spatrick //
7061da546Spatrick //===----------------------------------------------------------------------===//
8061da546Spatrick 
9*be691f3bSpatrick #include <cerrno>
10061da546Spatrick 
11061da546Spatrick #include "lldb/Host/Config.h"
12061da546Spatrick 
13061da546Spatrick 
14061da546Spatrick #include <chrono>
15061da546Spatrick #include <cstring>
16*be691f3bSpatrick #include <limits>
17061da546Spatrick #include <thread>
18061da546Spatrick 
19*be691f3bSpatrick #include "GDBRemoteCommunicationServerLLGS.h"
20061da546Spatrick #include "lldb/Host/ConnectionFileDescriptor.h"
21061da546Spatrick #include "lldb/Host/Debug.h"
22061da546Spatrick #include "lldb/Host/File.h"
23061da546Spatrick #include "lldb/Host/FileAction.h"
24061da546Spatrick #include "lldb/Host/FileSystem.h"
25061da546Spatrick #include "lldb/Host/Host.h"
26061da546Spatrick #include "lldb/Host/HostInfo.h"
27061da546Spatrick #include "lldb/Host/PosixApi.h"
28061da546Spatrick #include "lldb/Host/common/NativeProcessProtocol.h"
29061da546Spatrick #include "lldb/Host/common/NativeRegisterContext.h"
30061da546Spatrick #include "lldb/Host/common/NativeThreadProtocol.h"
31061da546Spatrick #include "lldb/Target/MemoryRegionInfo.h"
32061da546Spatrick #include "lldb/Utility/Args.h"
33061da546Spatrick #include "lldb/Utility/DataBuffer.h"
34061da546Spatrick #include "lldb/Utility/Endian.h"
35*be691f3bSpatrick #include "lldb/Utility/GDBRemote.h"
36061da546Spatrick #include "lldb/Utility/LLDBAssert.h"
37061da546Spatrick #include "lldb/Utility/Log.h"
38061da546Spatrick #include "lldb/Utility/RegisterValue.h"
39061da546Spatrick #include "lldb/Utility/State.h"
40061da546Spatrick #include "lldb/Utility/StreamString.h"
41*be691f3bSpatrick #include "lldb/Utility/UnimplementedError.h"
42061da546Spatrick #include "lldb/Utility/UriParser.h"
43061da546Spatrick #include "llvm/ADT/Triple.h"
44061da546Spatrick #include "llvm/Support/JSON.h"
45061da546Spatrick #include "llvm/Support/ScopedPrinter.h"
46061da546Spatrick 
47061da546Spatrick #include "ProcessGDBRemote.h"
48061da546Spatrick #include "ProcessGDBRemoteLog.h"
49061da546Spatrick #include "lldb/Utility/StringExtractorGDBRemote.h"
50061da546Spatrick 
51061da546Spatrick using namespace lldb;
52061da546Spatrick using namespace lldb_private;
53061da546Spatrick using namespace lldb_private::process_gdb_remote;
54061da546Spatrick using namespace llvm;
55061da546Spatrick 
56061da546Spatrick // GDBRemote Errors
57061da546Spatrick 
58061da546Spatrick namespace {
59061da546Spatrick enum GDBRemoteServerError {
60061da546Spatrick   // Set to the first unused error number in literal form below
61061da546Spatrick   eErrorFirst = 29,
62061da546Spatrick   eErrorNoProcess = eErrorFirst,
63061da546Spatrick   eErrorResume,
64061da546Spatrick   eErrorExitStatus
65061da546Spatrick };
66061da546Spatrick }
67061da546Spatrick 
68061da546Spatrick // GDBRemoteCommunicationServerLLGS constructor
69061da546Spatrick GDBRemoteCommunicationServerLLGS::GDBRemoteCommunicationServerLLGS(
70061da546Spatrick     MainLoop &mainloop, const NativeProcessProtocol::Factory &process_factory)
71061da546Spatrick     : GDBRemoteCommunicationServerCommon("gdb-remote.server",
72061da546Spatrick                                          "gdb-remote.server.rx_packet"),
73061da546Spatrick       m_mainloop(mainloop), m_process_factory(process_factory),
74*be691f3bSpatrick       m_current_process(nullptr), m_continue_process(nullptr),
75061da546Spatrick       m_stdio_communication("process.stdio") {
76061da546Spatrick   RegisterPacketHandlers();
77061da546Spatrick }
78061da546Spatrick 
79061da546Spatrick void GDBRemoteCommunicationServerLLGS::RegisterPacketHandlers() {
80061da546Spatrick   RegisterMemberFunctionHandler(StringExtractorGDBRemote::eServerPacketType_C,
81061da546Spatrick                                 &GDBRemoteCommunicationServerLLGS::Handle_C);
82061da546Spatrick   RegisterMemberFunctionHandler(StringExtractorGDBRemote::eServerPacketType_c,
83061da546Spatrick                                 &GDBRemoteCommunicationServerLLGS::Handle_c);
84061da546Spatrick   RegisterMemberFunctionHandler(StringExtractorGDBRemote::eServerPacketType_D,
85061da546Spatrick                                 &GDBRemoteCommunicationServerLLGS::Handle_D);
86061da546Spatrick   RegisterMemberFunctionHandler(StringExtractorGDBRemote::eServerPacketType_H,
87061da546Spatrick                                 &GDBRemoteCommunicationServerLLGS::Handle_H);
88061da546Spatrick   RegisterMemberFunctionHandler(StringExtractorGDBRemote::eServerPacketType_I,
89061da546Spatrick                                 &GDBRemoteCommunicationServerLLGS::Handle_I);
90061da546Spatrick   RegisterMemberFunctionHandler(
91061da546Spatrick       StringExtractorGDBRemote::eServerPacketType_interrupt,
92061da546Spatrick       &GDBRemoteCommunicationServerLLGS::Handle_interrupt);
93061da546Spatrick   RegisterMemberFunctionHandler(
94061da546Spatrick       StringExtractorGDBRemote::eServerPacketType_m,
95061da546Spatrick       &GDBRemoteCommunicationServerLLGS::Handle_memory_read);
96061da546Spatrick   RegisterMemberFunctionHandler(StringExtractorGDBRemote::eServerPacketType_M,
97061da546Spatrick                                 &GDBRemoteCommunicationServerLLGS::Handle_M);
98*be691f3bSpatrick   RegisterMemberFunctionHandler(StringExtractorGDBRemote::eServerPacketType__M,
99*be691f3bSpatrick                                 &GDBRemoteCommunicationServerLLGS::Handle__M);
100*be691f3bSpatrick   RegisterMemberFunctionHandler(StringExtractorGDBRemote::eServerPacketType__m,
101*be691f3bSpatrick                                 &GDBRemoteCommunicationServerLLGS::Handle__m);
102061da546Spatrick   RegisterMemberFunctionHandler(StringExtractorGDBRemote::eServerPacketType_p,
103061da546Spatrick                                 &GDBRemoteCommunicationServerLLGS::Handle_p);
104061da546Spatrick   RegisterMemberFunctionHandler(StringExtractorGDBRemote::eServerPacketType_P,
105061da546Spatrick                                 &GDBRemoteCommunicationServerLLGS::Handle_P);
106061da546Spatrick   RegisterMemberFunctionHandler(StringExtractorGDBRemote::eServerPacketType_qC,
107061da546Spatrick                                 &GDBRemoteCommunicationServerLLGS::Handle_qC);
108061da546Spatrick   RegisterMemberFunctionHandler(
109061da546Spatrick       StringExtractorGDBRemote::eServerPacketType_qfThreadInfo,
110061da546Spatrick       &GDBRemoteCommunicationServerLLGS::Handle_qfThreadInfo);
111061da546Spatrick   RegisterMemberFunctionHandler(
112061da546Spatrick       StringExtractorGDBRemote::eServerPacketType_qFileLoadAddress,
113061da546Spatrick       &GDBRemoteCommunicationServerLLGS::Handle_qFileLoadAddress);
114061da546Spatrick   RegisterMemberFunctionHandler(
115061da546Spatrick       StringExtractorGDBRemote::eServerPacketType_qGetWorkingDir,
116061da546Spatrick       &GDBRemoteCommunicationServerLLGS::Handle_qGetWorkingDir);
117061da546Spatrick   RegisterMemberFunctionHandler(
118*be691f3bSpatrick       StringExtractorGDBRemote::eServerPacketType_QThreadSuffixSupported,
119*be691f3bSpatrick       &GDBRemoteCommunicationServerLLGS::Handle_QThreadSuffixSupported);
120*be691f3bSpatrick   RegisterMemberFunctionHandler(
121*be691f3bSpatrick       StringExtractorGDBRemote::eServerPacketType_QListThreadsInStopReply,
122*be691f3bSpatrick       &GDBRemoteCommunicationServerLLGS::Handle_QListThreadsInStopReply);
123*be691f3bSpatrick   RegisterMemberFunctionHandler(
124061da546Spatrick       StringExtractorGDBRemote::eServerPacketType_qMemoryRegionInfo,
125061da546Spatrick       &GDBRemoteCommunicationServerLLGS::Handle_qMemoryRegionInfo);
126061da546Spatrick   RegisterMemberFunctionHandler(
127061da546Spatrick       StringExtractorGDBRemote::eServerPacketType_qMemoryRegionInfoSupported,
128061da546Spatrick       &GDBRemoteCommunicationServerLLGS::Handle_qMemoryRegionInfoSupported);
129061da546Spatrick   RegisterMemberFunctionHandler(
130061da546Spatrick       StringExtractorGDBRemote::eServerPacketType_qProcessInfo,
131061da546Spatrick       &GDBRemoteCommunicationServerLLGS::Handle_qProcessInfo);
132061da546Spatrick   RegisterMemberFunctionHandler(
133061da546Spatrick       StringExtractorGDBRemote::eServerPacketType_qRegisterInfo,
134061da546Spatrick       &GDBRemoteCommunicationServerLLGS::Handle_qRegisterInfo);
135061da546Spatrick   RegisterMemberFunctionHandler(
136061da546Spatrick       StringExtractorGDBRemote::eServerPacketType_QRestoreRegisterState,
137061da546Spatrick       &GDBRemoteCommunicationServerLLGS::Handle_QRestoreRegisterState);
138061da546Spatrick   RegisterMemberFunctionHandler(
139061da546Spatrick       StringExtractorGDBRemote::eServerPacketType_QSaveRegisterState,
140061da546Spatrick       &GDBRemoteCommunicationServerLLGS::Handle_QSaveRegisterState);
141061da546Spatrick   RegisterMemberFunctionHandler(
142061da546Spatrick       StringExtractorGDBRemote::eServerPacketType_QSetDisableASLR,
143061da546Spatrick       &GDBRemoteCommunicationServerLLGS::Handle_QSetDisableASLR);
144061da546Spatrick   RegisterMemberFunctionHandler(
145061da546Spatrick       StringExtractorGDBRemote::eServerPacketType_QSetWorkingDir,
146061da546Spatrick       &GDBRemoteCommunicationServerLLGS::Handle_QSetWorkingDir);
147061da546Spatrick   RegisterMemberFunctionHandler(
148061da546Spatrick       StringExtractorGDBRemote::eServerPacketType_qsThreadInfo,
149061da546Spatrick       &GDBRemoteCommunicationServerLLGS::Handle_qsThreadInfo);
150061da546Spatrick   RegisterMemberFunctionHandler(
151061da546Spatrick       StringExtractorGDBRemote::eServerPacketType_qThreadStopInfo,
152061da546Spatrick       &GDBRemoteCommunicationServerLLGS::Handle_qThreadStopInfo);
153061da546Spatrick   RegisterMemberFunctionHandler(
154061da546Spatrick       StringExtractorGDBRemote::eServerPacketType_jThreadsInfo,
155061da546Spatrick       &GDBRemoteCommunicationServerLLGS::Handle_jThreadsInfo);
156061da546Spatrick   RegisterMemberFunctionHandler(
157061da546Spatrick       StringExtractorGDBRemote::eServerPacketType_qWatchpointSupportInfo,
158061da546Spatrick       &GDBRemoteCommunicationServerLLGS::Handle_qWatchpointSupportInfo);
159061da546Spatrick   RegisterMemberFunctionHandler(
160061da546Spatrick       StringExtractorGDBRemote::eServerPacketType_qXfer,
161061da546Spatrick       &GDBRemoteCommunicationServerLLGS::Handle_qXfer);
162061da546Spatrick   RegisterMemberFunctionHandler(StringExtractorGDBRemote::eServerPacketType_s,
163061da546Spatrick                                 &GDBRemoteCommunicationServerLLGS::Handle_s);
164061da546Spatrick   RegisterMemberFunctionHandler(
165061da546Spatrick       StringExtractorGDBRemote::eServerPacketType_stop_reason,
166061da546Spatrick       &GDBRemoteCommunicationServerLLGS::Handle_stop_reason); // ?
167061da546Spatrick   RegisterMemberFunctionHandler(
168061da546Spatrick       StringExtractorGDBRemote::eServerPacketType_vAttach,
169061da546Spatrick       &GDBRemoteCommunicationServerLLGS::Handle_vAttach);
170061da546Spatrick   RegisterMemberFunctionHandler(
171*be691f3bSpatrick       StringExtractorGDBRemote::eServerPacketType_vAttachWait,
172*be691f3bSpatrick       &GDBRemoteCommunicationServerLLGS::Handle_vAttachWait);
173*be691f3bSpatrick   RegisterMemberFunctionHandler(
174*be691f3bSpatrick       StringExtractorGDBRemote::eServerPacketType_qVAttachOrWaitSupported,
175*be691f3bSpatrick       &GDBRemoteCommunicationServerLLGS::Handle_qVAttachOrWaitSupported);
176*be691f3bSpatrick   RegisterMemberFunctionHandler(
177*be691f3bSpatrick       StringExtractorGDBRemote::eServerPacketType_vAttachOrWait,
178*be691f3bSpatrick       &GDBRemoteCommunicationServerLLGS::Handle_vAttachOrWait);
179*be691f3bSpatrick   RegisterMemberFunctionHandler(
180061da546Spatrick       StringExtractorGDBRemote::eServerPacketType_vCont,
181061da546Spatrick       &GDBRemoteCommunicationServerLLGS::Handle_vCont);
182061da546Spatrick   RegisterMemberFunctionHandler(
183061da546Spatrick       StringExtractorGDBRemote::eServerPacketType_vCont_actions,
184061da546Spatrick       &GDBRemoteCommunicationServerLLGS::Handle_vCont_actions);
185061da546Spatrick   RegisterMemberFunctionHandler(
186061da546Spatrick       StringExtractorGDBRemote::eServerPacketType_x,
187061da546Spatrick       &GDBRemoteCommunicationServerLLGS::Handle_memory_read);
188061da546Spatrick   RegisterMemberFunctionHandler(StringExtractorGDBRemote::eServerPacketType_Z,
189061da546Spatrick                                 &GDBRemoteCommunicationServerLLGS::Handle_Z);
190061da546Spatrick   RegisterMemberFunctionHandler(StringExtractorGDBRemote::eServerPacketType_z,
191061da546Spatrick                                 &GDBRemoteCommunicationServerLLGS::Handle_z);
192061da546Spatrick   RegisterMemberFunctionHandler(
193061da546Spatrick       StringExtractorGDBRemote::eServerPacketType_QPassSignals,
194061da546Spatrick       &GDBRemoteCommunicationServerLLGS::Handle_QPassSignals);
195061da546Spatrick 
196061da546Spatrick   RegisterMemberFunctionHandler(
197*be691f3bSpatrick       StringExtractorGDBRemote::eServerPacketType_jLLDBTraceSupported,
198*be691f3bSpatrick       &GDBRemoteCommunicationServerLLGS::Handle_jLLDBTraceSupported);
199061da546Spatrick   RegisterMemberFunctionHandler(
200*be691f3bSpatrick       StringExtractorGDBRemote::eServerPacketType_jLLDBTraceStart,
201*be691f3bSpatrick       &GDBRemoteCommunicationServerLLGS::Handle_jLLDBTraceStart);
202061da546Spatrick   RegisterMemberFunctionHandler(
203*be691f3bSpatrick       StringExtractorGDBRemote::eServerPacketType_jLLDBTraceStop,
204*be691f3bSpatrick       &GDBRemoteCommunicationServerLLGS::Handle_jLLDBTraceStop);
205061da546Spatrick   RegisterMemberFunctionHandler(
206*be691f3bSpatrick       StringExtractorGDBRemote::eServerPacketType_jLLDBTraceGetState,
207*be691f3bSpatrick       &GDBRemoteCommunicationServerLLGS::Handle_jLLDBTraceGetState);
208061da546Spatrick   RegisterMemberFunctionHandler(
209*be691f3bSpatrick       StringExtractorGDBRemote::eServerPacketType_jLLDBTraceGetBinaryData,
210*be691f3bSpatrick       &GDBRemoteCommunicationServerLLGS::Handle_jLLDBTraceGetBinaryData);
211061da546Spatrick 
212061da546Spatrick   RegisterMemberFunctionHandler(StringExtractorGDBRemote::eServerPacketType_g,
213061da546Spatrick                                 &GDBRemoteCommunicationServerLLGS::Handle_g);
214061da546Spatrick 
215*be691f3bSpatrick   RegisterMemberFunctionHandler(
216*be691f3bSpatrick       StringExtractorGDBRemote::eServerPacketType_qMemTags,
217*be691f3bSpatrick       &GDBRemoteCommunicationServerLLGS::Handle_qMemTags);
218*be691f3bSpatrick 
219*be691f3bSpatrick   RegisterMemberFunctionHandler(
220*be691f3bSpatrick       StringExtractorGDBRemote::eServerPacketType_QMemTags,
221*be691f3bSpatrick       &GDBRemoteCommunicationServerLLGS::Handle_QMemTags);
222*be691f3bSpatrick 
223061da546Spatrick   RegisterPacketHandler(StringExtractorGDBRemote::eServerPacketType_k,
224061da546Spatrick                         [this](StringExtractorGDBRemote packet, Status &error,
225061da546Spatrick                                bool &interrupt, bool &quit) {
226061da546Spatrick                           quit = true;
227061da546Spatrick                           return this->Handle_k(packet);
228061da546Spatrick                         });
229061da546Spatrick }
230061da546Spatrick 
231061da546Spatrick void GDBRemoteCommunicationServerLLGS::SetLaunchInfo(const ProcessLaunchInfo &info) {
232061da546Spatrick   m_process_launch_info = info;
233061da546Spatrick }
234061da546Spatrick 
235061da546Spatrick Status GDBRemoteCommunicationServerLLGS::LaunchProcess() {
236061da546Spatrick   Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
237061da546Spatrick 
238061da546Spatrick   if (!m_process_launch_info.GetArguments().GetArgumentCount())
239061da546Spatrick     return Status("%s: no process command line specified to launch",
240061da546Spatrick                   __FUNCTION__);
241061da546Spatrick 
242061da546Spatrick   const bool should_forward_stdio =
243061da546Spatrick       m_process_launch_info.GetFileActionForFD(STDIN_FILENO) == nullptr ||
244061da546Spatrick       m_process_launch_info.GetFileActionForFD(STDOUT_FILENO) == nullptr ||
245061da546Spatrick       m_process_launch_info.GetFileActionForFD(STDERR_FILENO) == nullptr;
246061da546Spatrick   m_process_launch_info.SetLaunchInSeparateProcessGroup(true);
247061da546Spatrick   m_process_launch_info.GetFlags().Set(eLaunchFlagDebug);
248061da546Spatrick 
249061da546Spatrick   if (should_forward_stdio) {
250061da546Spatrick     // Temporarily relax the following for Windows until we can take advantage
251061da546Spatrick     // of the recently added pty support. This doesn't really affect the use of
252061da546Spatrick     // lldb-server on Windows.
253061da546Spatrick #if !defined(_WIN32)
254061da546Spatrick     if (llvm::Error Err = m_process_launch_info.SetUpPtyRedirection())
255061da546Spatrick       return Status(std::move(Err));
256061da546Spatrick #endif
257061da546Spatrick   }
258061da546Spatrick 
259061da546Spatrick   {
260061da546Spatrick     std::lock_guard<std::recursive_mutex> guard(m_debugged_process_mutex);
261*be691f3bSpatrick     assert(m_debugged_processes.empty() && "lldb-server creating debugged "
262061da546Spatrick                                            "process but one already exists");
263061da546Spatrick     auto process_or =
264061da546Spatrick         m_process_factory.Launch(m_process_launch_info, *this, m_mainloop);
265061da546Spatrick     if (!process_or)
266061da546Spatrick       return Status(process_or.takeError());
267*be691f3bSpatrick     m_continue_process = m_current_process = process_or->get();
268*be691f3bSpatrick     m_debugged_processes[m_current_process->GetID()] = std::move(*process_or);
269061da546Spatrick   }
270061da546Spatrick 
271*be691f3bSpatrick   SetEnabledExtensions(*m_current_process);
272*be691f3bSpatrick 
273061da546Spatrick   // Handle mirroring of inferior stdout/stderr over the gdb-remote protocol as
274061da546Spatrick   // needed. llgs local-process debugging may specify PTY paths, which will
275061da546Spatrick   // make these file actions non-null process launch -i/e/o will also make
276061da546Spatrick   // these file actions non-null nullptr means that the traffic is expected to
277061da546Spatrick   // flow over gdb-remote protocol
278061da546Spatrick   if (should_forward_stdio) {
279061da546Spatrick     // nullptr means it's not redirected to file or pty (in case of LLGS local)
280061da546Spatrick     // at least one of stdio will be transferred pty<->gdb-remote we need to
281061da546Spatrick     // give the pty master handle to this object to read and/or write
282061da546Spatrick     LLDB_LOG(log,
283061da546Spatrick              "pid = {0}: setting up stdout/stderr redirection via $O "
284061da546Spatrick              "gdb-remote commands",
285*be691f3bSpatrick              m_current_process->GetID());
286061da546Spatrick 
287061da546Spatrick     // Setup stdout/stderr mapping from inferior to $O
288*be691f3bSpatrick     auto terminal_fd = m_current_process->GetTerminalFileDescriptor();
289061da546Spatrick     if (terminal_fd >= 0) {
290061da546Spatrick       LLDB_LOGF(log,
291061da546Spatrick                 "ProcessGDBRemoteCommunicationServerLLGS::%s setting "
292061da546Spatrick                 "inferior STDIO fd to %d",
293061da546Spatrick                 __FUNCTION__, terminal_fd);
294061da546Spatrick       Status status = SetSTDIOFileDescriptor(terminal_fd);
295061da546Spatrick       if (status.Fail())
296061da546Spatrick         return status;
297061da546Spatrick     } else {
298061da546Spatrick       LLDB_LOGF(log,
299061da546Spatrick                 "ProcessGDBRemoteCommunicationServerLLGS::%s ignoring "
300061da546Spatrick                 "inferior STDIO since terminal fd reported as %d",
301061da546Spatrick                 __FUNCTION__, terminal_fd);
302061da546Spatrick     }
303061da546Spatrick   } else {
304061da546Spatrick     LLDB_LOG(log,
305061da546Spatrick              "pid = {0} skipping stdout/stderr redirection via $O: inferior "
306061da546Spatrick              "will communicate over client-provided file descriptors",
307*be691f3bSpatrick              m_current_process->GetID());
308061da546Spatrick   }
309061da546Spatrick 
310061da546Spatrick   printf("Launched '%s' as process %" PRIu64 "...\n",
311061da546Spatrick          m_process_launch_info.GetArguments().GetArgumentAtIndex(0),
312*be691f3bSpatrick          m_current_process->GetID());
313061da546Spatrick 
314061da546Spatrick   return Status();
315061da546Spatrick }
316061da546Spatrick 
317061da546Spatrick Status GDBRemoteCommunicationServerLLGS::AttachToProcess(lldb::pid_t pid) {
318061da546Spatrick   Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
319061da546Spatrick   LLDB_LOGF(log, "GDBRemoteCommunicationServerLLGS::%s pid %" PRIu64,
320061da546Spatrick             __FUNCTION__, pid);
321061da546Spatrick 
322061da546Spatrick   // Before we try to attach, make sure we aren't already monitoring something
323061da546Spatrick   // else.
324*be691f3bSpatrick   if (!m_debugged_processes.empty())
325061da546Spatrick     return Status("cannot attach to process %" PRIu64
326061da546Spatrick                   " when another process with pid %" PRIu64
327061da546Spatrick                   " is being debugged.",
328*be691f3bSpatrick                   pid, m_current_process->GetID());
329061da546Spatrick 
330061da546Spatrick   // Try to attach.
331061da546Spatrick   auto process_or = m_process_factory.Attach(pid, *this, m_mainloop);
332061da546Spatrick   if (!process_or) {
333061da546Spatrick     Status status(process_or.takeError());
334061da546Spatrick     llvm::errs() << llvm::formatv("failed to attach to process {0}: {1}", pid,
335061da546Spatrick                                   status);
336061da546Spatrick     return status;
337061da546Spatrick   }
338*be691f3bSpatrick   m_continue_process = m_current_process = process_or->get();
339*be691f3bSpatrick   m_debugged_processes[m_current_process->GetID()] = std::move(*process_or);
340*be691f3bSpatrick   SetEnabledExtensions(*m_current_process);
341061da546Spatrick 
342061da546Spatrick   // Setup stdout/stderr mapping from inferior.
343*be691f3bSpatrick   auto terminal_fd = m_current_process->GetTerminalFileDescriptor();
344061da546Spatrick   if (terminal_fd >= 0) {
345061da546Spatrick     LLDB_LOGF(log,
346061da546Spatrick               "ProcessGDBRemoteCommunicationServerLLGS::%s setting "
347061da546Spatrick               "inferior STDIO fd to %d",
348061da546Spatrick               __FUNCTION__, terminal_fd);
349061da546Spatrick     Status status = SetSTDIOFileDescriptor(terminal_fd);
350061da546Spatrick     if (status.Fail())
351061da546Spatrick       return status;
352061da546Spatrick   } else {
353061da546Spatrick     LLDB_LOGF(log,
354061da546Spatrick               "ProcessGDBRemoteCommunicationServerLLGS::%s ignoring "
355061da546Spatrick               "inferior STDIO since terminal fd reported as %d",
356061da546Spatrick               __FUNCTION__, terminal_fd);
357061da546Spatrick   }
358061da546Spatrick 
359061da546Spatrick   printf("Attached to process %" PRIu64 "...\n", pid);
360061da546Spatrick   return Status();
361061da546Spatrick }
362061da546Spatrick 
363*be691f3bSpatrick Status GDBRemoteCommunicationServerLLGS::AttachWaitProcess(
364*be691f3bSpatrick     llvm::StringRef process_name, bool include_existing) {
365*be691f3bSpatrick   Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
366*be691f3bSpatrick 
367*be691f3bSpatrick   std::chrono::milliseconds polling_interval = std::chrono::milliseconds(1);
368*be691f3bSpatrick 
369*be691f3bSpatrick   // Create the matcher used to search the process list.
370*be691f3bSpatrick   ProcessInstanceInfoList exclusion_list;
371*be691f3bSpatrick   ProcessInstanceInfoMatch match_info;
372*be691f3bSpatrick   match_info.GetProcessInfo().GetExecutableFile().SetFile(
373*be691f3bSpatrick       process_name, llvm::sys::path::Style::native);
374*be691f3bSpatrick   match_info.SetNameMatchType(NameMatch::Equals);
375*be691f3bSpatrick 
376*be691f3bSpatrick   if (include_existing) {
377*be691f3bSpatrick     LLDB_LOG(log, "including existing processes in search");
378*be691f3bSpatrick   } else {
379*be691f3bSpatrick     // Create the excluded process list before polling begins.
380*be691f3bSpatrick     Host::FindProcesses(match_info, exclusion_list);
381*be691f3bSpatrick     LLDB_LOG(log, "placed '{0}' processes in the exclusion list.",
382*be691f3bSpatrick              exclusion_list.size());
383*be691f3bSpatrick   }
384*be691f3bSpatrick 
385*be691f3bSpatrick   LLDB_LOG(log, "waiting for '{0}' to appear", process_name);
386*be691f3bSpatrick 
387*be691f3bSpatrick   auto is_in_exclusion_list =
388*be691f3bSpatrick       [&exclusion_list](const ProcessInstanceInfo &info) {
389*be691f3bSpatrick         for (auto &excluded : exclusion_list) {
390*be691f3bSpatrick           if (excluded.GetProcessID() == info.GetProcessID())
391*be691f3bSpatrick             return true;
392*be691f3bSpatrick         }
393*be691f3bSpatrick         return false;
394*be691f3bSpatrick       };
395*be691f3bSpatrick 
396*be691f3bSpatrick   ProcessInstanceInfoList loop_process_list;
397*be691f3bSpatrick   while (true) {
398*be691f3bSpatrick     loop_process_list.clear();
399*be691f3bSpatrick     if (Host::FindProcesses(match_info, loop_process_list)) {
400*be691f3bSpatrick       // Remove all the elements that are in the exclusion list.
401*be691f3bSpatrick       llvm::erase_if(loop_process_list, is_in_exclusion_list);
402*be691f3bSpatrick 
403*be691f3bSpatrick       // One match! We found the desired process.
404*be691f3bSpatrick       if (loop_process_list.size() == 1) {
405*be691f3bSpatrick         auto matching_process_pid = loop_process_list[0].GetProcessID();
406*be691f3bSpatrick         LLDB_LOG(log, "found pid {0}", matching_process_pid);
407*be691f3bSpatrick         return AttachToProcess(matching_process_pid);
408*be691f3bSpatrick       }
409*be691f3bSpatrick 
410*be691f3bSpatrick       // Multiple matches! Return an error reporting the PIDs we found.
411*be691f3bSpatrick       if (loop_process_list.size() > 1) {
412*be691f3bSpatrick         StreamString error_stream;
413*be691f3bSpatrick         error_stream.Format(
414*be691f3bSpatrick             "Multiple executables with name: '{0}' found. Pids: ",
415*be691f3bSpatrick             process_name);
416*be691f3bSpatrick         for (size_t i = 0; i < loop_process_list.size() - 1; ++i) {
417*be691f3bSpatrick           error_stream.Format("{0}, ", loop_process_list[i].GetProcessID());
418*be691f3bSpatrick         }
419*be691f3bSpatrick         error_stream.Format("{0}.", loop_process_list.back().GetProcessID());
420*be691f3bSpatrick 
421*be691f3bSpatrick         Status error;
422*be691f3bSpatrick         error.SetErrorString(error_stream.GetString());
423*be691f3bSpatrick         return error;
424*be691f3bSpatrick       }
425*be691f3bSpatrick     }
426*be691f3bSpatrick     // No matches, we have not found the process. Sleep until next poll.
427*be691f3bSpatrick     LLDB_LOG(log, "sleep {0} seconds", polling_interval);
428*be691f3bSpatrick     std::this_thread::sleep_for(polling_interval);
429*be691f3bSpatrick   }
430*be691f3bSpatrick }
431*be691f3bSpatrick 
432061da546Spatrick void GDBRemoteCommunicationServerLLGS::InitializeDelegate(
433061da546Spatrick     NativeProcessProtocol *process) {
434061da546Spatrick   assert(process && "process cannot be NULL");
435061da546Spatrick   Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
436061da546Spatrick   if (log) {
437061da546Spatrick     LLDB_LOGF(log,
438061da546Spatrick               "GDBRemoteCommunicationServerLLGS::%s called with "
439061da546Spatrick               "NativeProcessProtocol pid %" PRIu64 ", current state: %s",
440061da546Spatrick               __FUNCTION__, process->GetID(),
441061da546Spatrick               StateAsCString(process->GetState()));
442061da546Spatrick   }
443061da546Spatrick }
444061da546Spatrick 
445061da546Spatrick GDBRemoteCommunication::PacketResult
446061da546Spatrick GDBRemoteCommunicationServerLLGS::SendWResponse(
447061da546Spatrick     NativeProcessProtocol *process) {
448061da546Spatrick   assert(process && "process cannot be NULL");
449061da546Spatrick   Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
450061da546Spatrick 
451061da546Spatrick   // send W notification
452061da546Spatrick   auto wait_status = process->GetExitStatus();
453061da546Spatrick   if (!wait_status) {
454061da546Spatrick     LLDB_LOG(log, "pid = {0}, failed to retrieve process exit status",
455061da546Spatrick              process->GetID());
456061da546Spatrick 
457061da546Spatrick     StreamGDBRemote response;
458061da546Spatrick     response.PutChar('E');
459061da546Spatrick     response.PutHex8(GDBRemoteServerError::eErrorExitStatus);
460061da546Spatrick     return SendPacketNoLock(response.GetString());
461061da546Spatrick   }
462061da546Spatrick 
463061da546Spatrick   LLDB_LOG(log, "pid = {0}, returning exit type {1}", process->GetID(),
464061da546Spatrick            *wait_status);
465061da546Spatrick 
466061da546Spatrick   StreamGDBRemote response;
467061da546Spatrick   response.Format("{0:g}", *wait_status);
468061da546Spatrick   return SendPacketNoLock(response.GetString());
469061da546Spatrick }
470061da546Spatrick 
471061da546Spatrick static void AppendHexValue(StreamString &response, const uint8_t *buf,
472061da546Spatrick                            uint32_t buf_size, bool swap) {
473061da546Spatrick   int64_t i;
474061da546Spatrick   if (swap) {
475061da546Spatrick     for (i = buf_size - 1; i >= 0; i--)
476061da546Spatrick       response.PutHex8(buf[i]);
477061da546Spatrick   } else {
478061da546Spatrick     for (i = 0; i < buf_size; i++)
479061da546Spatrick       response.PutHex8(buf[i]);
480061da546Spatrick   }
481061da546Spatrick }
482061da546Spatrick 
483dda28197Spatrick static llvm::StringRef GetEncodingNameOrEmpty(const RegisterInfo &reg_info) {
484dda28197Spatrick   switch (reg_info.encoding) {
485dda28197Spatrick   case eEncodingUint:
486dda28197Spatrick     return "uint";
487dda28197Spatrick   case eEncodingSint:
488dda28197Spatrick     return "sint";
489dda28197Spatrick   case eEncodingIEEE754:
490dda28197Spatrick     return "ieee754";
491dda28197Spatrick   case eEncodingVector:
492dda28197Spatrick     return "vector";
493dda28197Spatrick   default:
494dda28197Spatrick     return "";
495dda28197Spatrick   }
496dda28197Spatrick }
497dda28197Spatrick 
498dda28197Spatrick static llvm::StringRef GetFormatNameOrEmpty(const RegisterInfo &reg_info) {
499dda28197Spatrick   switch (reg_info.format) {
500dda28197Spatrick   case eFormatBinary:
501dda28197Spatrick     return "binary";
502dda28197Spatrick   case eFormatDecimal:
503dda28197Spatrick     return "decimal";
504dda28197Spatrick   case eFormatHex:
505dda28197Spatrick     return "hex";
506dda28197Spatrick   case eFormatFloat:
507dda28197Spatrick     return "float";
508dda28197Spatrick   case eFormatVectorOfSInt8:
509dda28197Spatrick     return "vector-sint8";
510dda28197Spatrick   case eFormatVectorOfUInt8:
511dda28197Spatrick     return "vector-uint8";
512dda28197Spatrick   case eFormatVectorOfSInt16:
513dda28197Spatrick     return "vector-sint16";
514dda28197Spatrick   case eFormatVectorOfUInt16:
515dda28197Spatrick     return "vector-uint16";
516dda28197Spatrick   case eFormatVectorOfSInt32:
517dda28197Spatrick     return "vector-sint32";
518dda28197Spatrick   case eFormatVectorOfUInt32:
519dda28197Spatrick     return "vector-uint32";
520dda28197Spatrick   case eFormatVectorOfFloat32:
521dda28197Spatrick     return "vector-float32";
522dda28197Spatrick   case eFormatVectorOfUInt64:
523dda28197Spatrick     return "vector-uint64";
524dda28197Spatrick   case eFormatVectorOfUInt128:
525dda28197Spatrick     return "vector-uint128";
526dda28197Spatrick   default:
527dda28197Spatrick     return "";
528dda28197Spatrick   };
529dda28197Spatrick }
530dda28197Spatrick 
531dda28197Spatrick static llvm::StringRef GetKindGenericOrEmpty(const RegisterInfo &reg_info) {
532dda28197Spatrick   switch (reg_info.kinds[RegisterKind::eRegisterKindGeneric]) {
533dda28197Spatrick   case LLDB_REGNUM_GENERIC_PC:
534dda28197Spatrick     return "pc";
535dda28197Spatrick   case LLDB_REGNUM_GENERIC_SP:
536dda28197Spatrick     return "sp";
537dda28197Spatrick   case LLDB_REGNUM_GENERIC_FP:
538dda28197Spatrick     return "fp";
539dda28197Spatrick   case LLDB_REGNUM_GENERIC_RA:
540dda28197Spatrick     return "ra";
541dda28197Spatrick   case LLDB_REGNUM_GENERIC_FLAGS:
542dda28197Spatrick     return "flags";
543dda28197Spatrick   case LLDB_REGNUM_GENERIC_ARG1:
544dda28197Spatrick     return "arg1";
545dda28197Spatrick   case LLDB_REGNUM_GENERIC_ARG2:
546dda28197Spatrick     return "arg2";
547dda28197Spatrick   case LLDB_REGNUM_GENERIC_ARG3:
548dda28197Spatrick     return "arg3";
549dda28197Spatrick   case LLDB_REGNUM_GENERIC_ARG4:
550dda28197Spatrick     return "arg4";
551dda28197Spatrick   case LLDB_REGNUM_GENERIC_ARG5:
552dda28197Spatrick     return "arg5";
553dda28197Spatrick   case LLDB_REGNUM_GENERIC_ARG6:
554dda28197Spatrick     return "arg6";
555dda28197Spatrick   case LLDB_REGNUM_GENERIC_ARG7:
556dda28197Spatrick     return "arg7";
557dda28197Spatrick   case LLDB_REGNUM_GENERIC_ARG8:
558dda28197Spatrick     return "arg8";
559dda28197Spatrick   default:
560dda28197Spatrick     return "";
561dda28197Spatrick   }
562dda28197Spatrick }
563dda28197Spatrick 
564dda28197Spatrick static void CollectRegNums(const uint32_t *reg_num, StreamString &response,
565dda28197Spatrick                            bool usehex) {
566dda28197Spatrick   for (int i = 0; *reg_num != LLDB_INVALID_REGNUM; ++reg_num, ++i) {
567dda28197Spatrick     if (i > 0)
568dda28197Spatrick       response.PutChar(',');
569dda28197Spatrick     if (usehex)
570dda28197Spatrick       response.Printf("%" PRIx32, *reg_num);
571dda28197Spatrick     else
572dda28197Spatrick       response.Printf("%" PRIu32, *reg_num);
573dda28197Spatrick   }
574dda28197Spatrick }
575dda28197Spatrick 
576061da546Spatrick static void WriteRegisterValueInHexFixedWidth(
577061da546Spatrick     StreamString &response, NativeRegisterContext &reg_ctx,
578061da546Spatrick     const RegisterInfo &reg_info, const RegisterValue *reg_value_p,
579061da546Spatrick     lldb::ByteOrder byte_order) {
580061da546Spatrick   RegisterValue reg_value;
581061da546Spatrick   if (!reg_value_p) {
582061da546Spatrick     Status error = reg_ctx.ReadRegister(&reg_info, reg_value);
583061da546Spatrick     if (error.Success())
584061da546Spatrick       reg_value_p = &reg_value;
585061da546Spatrick     // else log.
586061da546Spatrick   }
587061da546Spatrick 
588061da546Spatrick   if (reg_value_p) {
589061da546Spatrick     AppendHexValue(response, (const uint8_t *)reg_value_p->GetBytes(),
590061da546Spatrick                    reg_value_p->GetByteSize(),
591061da546Spatrick                    byte_order == lldb::eByteOrderLittle);
592061da546Spatrick   } else {
593061da546Spatrick     // Zero-out any unreadable values.
594061da546Spatrick     if (reg_info.byte_size > 0) {
595061da546Spatrick       std::basic_string<uint8_t> zeros(reg_info.byte_size, '\0');
596061da546Spatrick       AppendHexValue(response, zeros.data(), zeros.size(), false);
597061da546Spatrick     }
598061da546Spatrick   }
599061da546Spatrick }
600061da546Spatrick 
601*be691f3bSpatrick static llvm::Optional<json::Object>
602061da546Spatrick GetRegistersAsJSON(NativeThreadProtocol &thread) {
603061da546Spatrick   Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_THREAD));
604061da546Spatrick 
605061da546Spatrick   NativeRegisterContext& reg_ctx = thread.GetRegisterContext();
606061da546Spatrick 
607061da546Spatrick   json::Object register_object;
608061da546Spatrick 
609061da546Spatrick #ifdef LLDB_JTHREADSINFO_FULL_REGISTER_SET
610*be691f3bSpatrick   const auto expedited_regs =
611*be691f3bSpatrick       reg_ctx.GetExpeditedRegisters(ExpeditedRegs::Full);
612061da546Spatrick #else
613*be691f3bSpatrick   const auto expedited_regs =
614*be691f3bSpatrick       reg_ctx.GetExpeditedRegisters(ExpeditedRegs::Minimal);
615061da546Spatrick #endif
616*be691f3bSpatrick   if (expedited_regs.empty())
617*be691f3bSpatrick     return llvm::None;
618061da546Spatrick 
619*be691f3bSpatrick   for (auto &reg_num : expedited_regs) {
620061da546Spatrick     const RegisterInfo *const reg_info_p =
621061da546Spatrick         reg_ctx.GetRegisterInfoAtIndex(reg_num);
622061da546Spatrick     if (reg_info_p == nullptr) {
623061da546Spatrick       LLDB_LOGF(log,
624061da546Spatrick                 "%s failed to get register info for register index %" PRIu32,
625061da546Spatrick                 __FUNCTION__, reg_num);
626061da546Spatrick       continue;
627061da546Spatrick     }
628061da546Spatrick 
629061da546Spatrick     if (reg_info_p->value_regs != nullptr)
630061da546Spatrick       continue; // Only expedite registers that are not contained in other
631061da546Spatrick                 // registers.
632061da546Spatrick 
633061da546Spatrick     RegisterValue reg_value;
634061da546Spatrick     Status error = reg_ctx.ReadRegister(reg_info_p, reg_value);
635061da546Spatrick     if (error.Fail()) {
636061da546Spatrick       LLDB_LOGF(log, "%s failed to read register '%s' index %" PRIu32 ": %s",
637061da546Spatrick                 __FUNCTION__,
638061da546Spatrick                 reg_info_p->name ? reg_info_p->name : "<unnamed-register>",
639061da546Spatrick                 reg_num, error.AsCString());
640061da546Spatrick       continue;
641061da546Spatrick     }
642061da546Spatrick 
643061da546Spatrick     StreamString stream;
644061da546Spatrick     WriteRegisterValueInHexFixedWidth(stream, reg_ctx, *reg_info_p,
645061da546Spatrick                                       &reg_value, lldb::eByteOrderBig);
646061da546Spatrick 
647061da546Spatrick     register_object.try_emplace(llvm::to_string(reg_num),
648061da546Spatrick                                 stream.GetString().str());
649061da546Spatrick   }
650061da546Spatrick 
651061da546Spatrick   return register_object;
652061da546Spatrick }
653061da546Spatrick 
654061da546Spatrick static const char *GetStopReasonString(StopReason stop_reason) {
655061da546Spatrick   switch (stop_reason) {
656061da546Spatrick   case eStopReasonTrace:
657061da546Spatrick     return "trace";
658061da546Spatrick   case eStopReasonBreakpoint:
659061da546Spatrick     return "breakpoint";
660061da546Spatrick   case eStopReasonWatchpoint:
661061da546Spatrick     return "watchpoint";
662061da546Spatrick   case eStopReasonSignal:
663061da546Spatrick     return "signal";
664061da546Spatrick   case eStopReasonException:
665061da546Spatrick     return "exception";
666061da546Spatrick   case eStopReasonExec:
667061da546Spatrick     return "exec";
668*be691f3bSpatrick   case eStopReasonProcessorTrace:
669*be691f3bSpatrick     return "processor trace";
670*be691f3bSpatrick   case eStopReasonFork:
671*be691f3bSpatrick     return "fork";
672*be691f3bSpatrick   case eStopReasonVFork:
673*be691f3bSpatrick     return "vfork";
674*be691f3bSpatrick   case eStopReasonVForkDone:
675*be691f3bSpatrick     return "vforkdone";
676061da546Spatrick   case eStopReasonInstrumentation:
677061da546Spatrick   case eStopReasonInvalid:
678061da546Spatrick   case eStopReasonPlanComplete:
679061da546Spatrick   case eStopReasonThreadExiting:
680061da546Spatrick   case eStopReasonNone:
681061da546Spatrick     break; // ignored
682061da546Spatrick   }
683061da546Spatrick   return nullptr;
684061da546Spatrick }
685061da546Spatrick 
686061da546Spatrick static llvm::Expected<json::Array>
687061da546Spatrick GetJSONThreadsInfo(NativeProcessProtocol &process, bool abridged) {
688061da546Spatrick   Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS | LIBLLDB_LOG_THREAD));
689061da546Spatrick 
690061da546Spatrick   json::Array threads_array;
691061da546Spatrick 
692061da546Spatrick   // Ensure we can get info on the given thread.
693061da546Spatrick   uint32_t thread_idx = 0;
694061da546Spatrick   for (NativeThreadProtocol *thread;
695061da546Spatrick        (thread = process.GetThreadAtIndex(thread_idx)) != nullptr;
696061da546Spatrick        ++thread_idx) {
697061da546Spatrick 
698061da546Spatrick     lldb::tid_t tid = thread->GetID();
699061da546Spatrick 
700061da546Spatrick     // Grab the reason this thread stopped.
701061da546Spatrick     struct ThreadStopInfo tid_stop_info;
702061da546Spatrick     std::string description;
703061da546Spatrick     if (!thread->GetStopReason(tid_stop_info, description))
704061da546Spatrick       return llvm::make_error<llvm::StringError>(
705061da546Spatrick           "failed to get stop reason", llvm::inconvertibleErrorCode());
706061da546Spatrick 
707061da546Spatrick     const int signum = tid_stop_info.details.signal.signo;
708061da546Spatrick     if (log) {
709061da546Spatrick       LLDB_LOGF(log,
710061da546Spatrick                 "GDBRemoteCommunicationServerLLGS::%s pid %" PRIu64
711061da546Spatrick                 " tid %" PRIu64
712061da546Spatrick                 " got signal signo = %d, reason = %d, exc_type = %" PRIu64,
713061da546Spatrick                 __FUNCTION__, process.GetID(), tid, signum,
714061da546Spatrick                 tid_stop_info.reason, tid_stop_info.details.exception.type);
715061da546Spatrick     }
716061da546Spatrick 
717061da546Spatrick     json::Object thread_obj;
718061da546Spatrick 
719061da546Spatrick     if (!abridged) {
720*be691f3bSpatrick       if (llvm::Optional<json::Object> registers = GetRegistersAsJSON(*thread))
721061da546Spatrick         thread_obj.try_emplace("registers", std::move(*registers));
722061da546Spatrick     }
723061da546Spatrick 
724061da546Spatrick     thread_obj.try_emplace("tid", static_cast<int64_t>(tid));
725061da546Spatrick 
726061da546Spatrick     if (signum != 0)
727061da546Spatrick       thread_obj.try_emplace("signal", signum);
728061da546Spatrick 
729061da546Spatrick     const std::string thread_name = thread->GetName();
730061da546Spatrick     if (!thread_name.empty())
731061da546Spatrick       thread_obj.try_emplace("name", thread_name);
732061da546Spatrick 
733061da546Spatrick     const char *stop_reason = GetStopReasonString(tid_stop_info.reason);
734061da546Spatrick     if (stop_reason)
735061da546Spatrick       thread_obj.try_emplace("reason", stop_reason);
736061da546Spatrick 
737061da546Spatrick     if (!description.empty())
738061da546Spatrick       thread_obj.try_emplace("description", description);
739061da546Spatrick 
740061da546Spatrick     if ((tid_stop_info.reason == eStopReasonException) &&
741061da546Spatrick         tid_stop_info.details.exception.type) {
742061da546Spatrick       thread_obj.try_emplace(
743061da546Spatrick           "metype", static_cast<int64_t>(tid_stop_info.details.exception.type));
744061da546Spatrick 
745061da546Spatrick       json::Array medata_array;
746061da546Spatrick       for (uint32_t i = 0; i < tid_stop_info.details.exception.data_count;
747061da546Spatrick            ++i) {
748061da546Spatrick         medata_array.push_back(
749061da546Spatrick             static_cast<int64_t>(tid_stop_info.details.exception.data[i]));
750061da546Spatrick       }
751061da546Spatrick       thread_obj.try_emplace("medata", std::move(medata_array));
752061da546Spatrick     }
753061da546Spatrick     threads_array.push_back(std::move(thread_obj));
754061da546Spatrick   }
755061da546Spatrick   return threads_array;
756061da546Spatrick }
757061da546Spatrick 
758061da546Spatrick GDBRemoteCommunication::PacketResult
759061da546Spatrick GDBRemoteCommunicationServerLLGS::SendStopReplyPacketForThread(
760061da546Spatrick     lldb::tid_t tid) {
761061da546Spatrick   Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS | LIBLLDB_LOG_THREAD));
762061da546Spatrick 
763061da546Spatrick   // Ensure we have a debugged process.
764*be691f3bSpatrick   if (!m_current_process ||
765*be691f3bSpatrick       (m_current_process->GetID() == LLDB_INVALID_PROCESS_ID))
766061da546Spatrick     return SendErrorResponse(50);
767061da546Spatrick 
768061da546Spatrick   LLDB_LOG(log, "preparing packet for pid {0} tid {1}",
769*be691f3bSpatrick            m_current_process->GetID(), tid);
770061da546Spatrick 
771061da546Spatrick   // Ensure we can get info on the given thread.
772*be691f3bSpatrick   NativeThreadProtocol *thread = m_current_process->GetThreadByID(tid);
773061da546Spatrick   if (!thread)
774061da546Spatrick     return SendErrorResponse(51);
775061da546Spatrick 
776061da546Spatrick   // Grab the reason this thread stopped.
777061da546Spatrick   struct ThreadStopInfo tid_stop_info;
778061da546Spatrick   std::string description;
779061da546Spatrick   if (!thread->GetStopReason(tid_stop_info, description))
780061da546Spatrick     return SendErrorResponse(52);
781061da546Spatrick 
782061da546Spatrick   // FIXME implement register handling for exec'd inferiors.
783061da546Spatrick   // if (tid_stop_info.reason == eStopReasonExec) {
784061da546Spatrick   //     const bool force = true;
785061da546Spatrick   //     InitializeRegisters(force);
786061da546Spatrick   // }
787061da546Spatrick 
788061da546Spatrick   StreamString response;
789061da546Spatrick   // Output the T packet with the thread
790061da546Spatrick   response.PutChar('T');
791061da546Spatrick   int signum = tid_stop_info.details.signal.signo;
792061da546Spatrick   LLDB_LOG(
793061da546Spatrick       log,
794061da546Spatrick       "pid {0}, tid {1}, got signal signo = {2}, reason = {3}, exc_type = {4}",
795*be691f3bSpatrick       m_current_process->GetID(), tid, signum, int(tid_stop_info.reason),
796061da546Spatrick       tid_stop_info.details.exception.type);
797061da546Spatrick 
798061da546Spatrick   // Print the signal number.
799061da546Spatrick   response.PutHex8(signum & 0xff);
800061da546Spatrick 
801061da546Spatrick   // Include the tid.
802061da546Spatrick   response.Printf("thread:%" PRIx64 ";", tid);
803061da546Spatrick 
804061da546Spatrick   // Include the thread name if there is one.
805061da546Spatrick   const std::string thread_name = thread->GetName();
806061da546Spatrick   if (!thread_name.empty()) {
807061da546Spatrick     size_t thread_name_len = thread_name.length();
808061da546Spatrick 
809061da546Spatrick     if (::strcspn(thread_name.c_str(), "$#+-;:") == thread_name_len) {
810061da546Spatrick       response.PutCString("name:");
811061da546Spatrick       response.PutCString(thread_name);
812061da546Spatrick     } else {
813061da546Spatrick       // The thread name contains special chars, send as hex bytes.
814061da546Spatrick       response.PutCString("hexname:");
815061da546Spatrick       response.PutStringAsRawHex8(thread_name);
816061da546Spatrick     }
817061da546Spatrick     response.PutChar(';');
818061da546Spatrick   }
819061da546Spatrick 
820061da546Spatrick   // If a 'QListThreadsInStopReply' was sent to enable this feature, we will
821061da546Spatrick   // send all thread IDs back in the "threads" key whose value is a list of hex
822061da546Spatrick   // thread IDs separated by commas:
823061da546Spatrick   //  "threads:10a,10b,10c;"
824061da546Spatrick   // This will save the debugger from having to send a pair of qfThreadInfo and
825061da546Spatrick   // qsThreadInfo packets, but it also might take a lot of room in the stop
826061da546Spatrick   // reply packet, so it must be enabled only on systems where there are no
827061da546Spatrick   // limits on packet lengths.
828061da546Spatrick   if (m_list_threads_in_stop_reply) {
829061da546Spatrick     response.PutCString("threads:");
830061da546Spatrick 
831061da546Spatrick     uint32_t thread_index = 0;
832061da546Spatrick     NativeThreadProtocol *listed_thread;
833*be691f3bSpatrick     for (listed_thread = m_current_process->GetThreadAtIndex(thread_index);
834061da546Spatrick          listed_thread; ++thread_index,
835*be691f3bSpatrick         listed_thread = m_current_process->GetThreadAtIndex(thread_index)) {
836061da546Spatrick       if (thread_index > 0)
837061da546Spatrick         response.PutChar(',');
838061da546Spatrick       response.Printf("%" PRIx64, listed_thread->GetID());
839061da546Spatrick     }
840061da546Spatrick     response.PutChar(';');
841061da546Spatrick 
842061da546Spatrick     // Include JSON info that describes the stop reason for any threads that
843061da546Spatrick     // actually have stop reasons. We use the new "jstopinfo" key whose values
844061da546Spatrick     // is hex ascii JSON that contains the thread IDs thread stop info only for
845061da546Spatrick     // threads that have stop reasons. Only send this if we have more than one
846061da546Spatrick     // thread otherwise this packet has all the info it needs.
847061da546Spatrick     if (thread_index > 1) {
848061da546Spatrick       const bool threads_with_valid_stop_info_only = true;
849061da546Spatrick       llvm::Expected<json::Array> threads_info = GetJSONThreadsInfo(
850*be691f3bSpatrick           *m_current_process, threads_with_valid_stop_info_only);
851061da546Spatrick       if (threads_info) {
852061da546Spatrick         response.PutCString("jstopinfo:");
853061da546Spatrick         StreamString unescaped_response;
854061da546Spatrick         unescaped_response.AsRawOstream() << std::move(*threads_info);
855061da546Spatrick         response.PutStringAsRawHex8(unescaped_response.GetData());
856061da546Spatrick         response.PutChar(';');
857061da546Spatrick       } else {
858061da546Spatrick         LLDB_LOG_ERROR(log, threads_info.takeError(),
859061da546Spatrick                        "failed to prepare a jstopinfo field for pid {1}: {0}",
860*be691f3bSpatrick                        m_current_process->GetID());
861061da546Spatrick       }
862061da546Spatrick     }
863061da546Spatrick 
864061da546Spatrick     uint32_t i = 0;
865061da546Spatrick     response.PutCString("thread-pcs");
866061da546Spatrick     char delimiter = ':';
867061da546Spatrick     for (NativeThreadProtocol *thread;
868*be691f3bSpatrick          (thread = m_current_process->GetThreadAtIndex(i)) != nullptr; ++i) {
869061da546Spatrick       NativeRegisterContext& reg_ctx = thread->GetRegisterContext();
870061da546Spatrick 
871061da546Spatrick       uint32_t reg_to_read = reg_ctx.ConvertRegisterKindToRegisterNumber(
872061da546Spatrick           eRegisterKindGeneric, LLDB_REGNUM_GENERIC_PC);
873061da546Spatrick       const RegisterInfo *const reg_info_p =
874061da546Spatrick           reg_ctx.GetRegisterInfoAtIndex(reg_to_read);
875061da546Spatrick 
876061da546Spatrick       RegisterValue reg_value;
877061da546Spatrick       Status error = reg_ctx.ReadRegister(reg_info_p, reg_value);
878061da546Spatrick       if (error.Fail()) {
879061da546Spatrick         LLDB_LOGF(log, "%s failed to read register '%s' index %" PRIu32 ": %s",
880061da546Spatrick                   __FUNCTION__,
881061da546Spatrick                   reg_info_p->name ? reg_info_p->name : "<unnamed-register>",
882061da546Spatrick                   reg_to_read, error.AsCString());
883061da546Spatrick         continue;
884061da546Spatrick       }
885061da546Spatrick 
886061da546Spatrick       response.PutChar(delimiter);
887061da546Spatrick       delimiter = ',';
888061da546Spatrick       WriteRegisterValueInHexFixedWidth(response, reg_ctx, *reg_info_p,
889061da546Spatrick                                         &reg_value, endian::InlHostByteOrder());
890061da546Spatrick     }
891061da546Spatrick 
892061da546Spatrick     response.PutChar(';');
893061da546Spatrick   }
894061da546Spatrick 
895061da546Spatrick   //
896061da546Spatrick   // Expedite registers.
897061da546Spatrick   //
898061da546Spatrick 
899061da546Spatrick   // Grab the register context.
900061da546Spatrick   NativeRegisterContext& reg_ctx = thread->GetRegisterContext();
901*be691f3bSpatrick   const auto expedited_regs =
902*be691f3bSpatrick       reg_ctx.GetExpeditedRegisters(ExpeditedRegs::Full);
903061da546Spatrick 
904*be691f3bSpatrick   for (auto &reg_num : expedited_regs) {
905061da546Spatrick     const RegisterInfo *const reg_info_p =
906*be691f3bSpatrick         reg_ctx.GetRegisterInfoAtIndex(reg_num);
907061da546Spatrick     // Only expediate registers that are not contained in other registers.
908*be691f3bSpatrick     if (reg_info_p != nullptr && reg_info_p->value_regs == nullptr) {
909061da546Spatrick       RegisterValue reg_value;
910061da546Spatrick       Status error = reg_ctx.ReadRegister(reg_info_p, reg_value);
911061da546Spatrick       if (error.Success()) {
912*be691f3bSpatrick         response.Printf("%.02x:", reg_num);
913061da546Spatrick         WriteRegisterValueInHexFixedWidth(response, reg_ctx, *reg_info_p,
914061da546Spatrick                                           &reg_value, lldb::eByteOrderBig);
915061da546Spatrick         response.PutChar(';');
916061da546Spatrick       } else {
917*be691f3bSpatrick         LLDB_LOGF(log, "GDBRemoteCommunicationServerLLGS::%s failed to read "
918061da546Spatrick                        "register '%s' index %" PRIu32 ": %s",
919061da546Spatrick                   __FUNCTION__,
920061da546Spatrick                   reg_info_p->name ? reg_info_p->name : "<unnamed-register>",
921*be691f3bSpatrick                   reg_num, error.AsCString());
922061da546Spatrick       }
923061da546Spatrick     }
924061da546Spatrick   }
925061da546Spatrick 
926061da546Spatrick   const char *reason_str = GetStopReasonString(tid_stop_info.reason);
927061da546Spatrick   if (reason_str != nullptr) {
928061da546Spatrick     response.Printf("reason:%s;", reason_str);
929061da546Spatrick   }
930061da546Spatrick 
931061da546Spatrick   if (!description.empty()) {
932061da546Spatrick     // Description may contains special chars, send as hex bytes.
933061da546Spatrick     response.PutCString("description:");
934061da546Spatrick     response.PutStringAsRawHex8(description);
935061da546Spatrick     response.PutChar(';');
936061da546Spatrick   } else if ((tid_stop_info.reason == eStopReasonException) &&
937061da546Spatrick              tid_stop_info.details.exception.type) {
938061da546Spatrick     response.PutCString("metype:");
939061da546Spatrick     response.PutHex64(tid_stop_info.details.exception.type);
940061da546Spatrick     response.PutCString(";mecount:");
941061da546Spatrick     response.PutHex32(tid_stop_info.details.exception.data_count);
942061da546Spatrick     response.PutChar(';');
943061da546Spatrick 
944061da546Spatrick     for (uint32_t i = 0; i < tid_stop_info.details.exception.data_count; ++i) {
945061da546Spatrick       response.PutCString("medata:");
946061da546Spatrick       response.PutHex64(tid_stop_info.details.exception.data[i]);
947061da546Spatrick       response.PutChar(';');
948061da546Spatrick     }
949061da546Spatrick   }
950061da546Spatrick 
951*be691f3bSpatrick   // Include child process PID/TID for forks.
952*be691f3bSpatrick   if (tid_stop_info.reason == eStopReasonFork ||
953*be691f3bSpatrick       tid_stop_info.reason == eStopReasonVFork) {
954*be691f3bSpatrick     assert(bool(m_extensions_supported &
955*be691f3bSpatrick                 NativeProcessProtocol::Extension::multiprocess));
956*be691f3bSpatrick     if (tid_stop_info.reason == eStopReasonFork)
957*be691f3bSpatrick       assert(bool(m_extensions_supported &
958*be691f3bSpatrick                   NativeProcessProtocol::Extension::fork));
959*be691f3bSpatrick     if (tid_stop_info.reason == eStopReasonVFork)
960*be691f3bSpatrick       assert(bool(m_extensions_supported &
961*be691f3bSpatrick                   NativeProcessProtocol::Extension::vfork));
962*be691f3bSpatrick     response.Printf("%s:p%" PRIx64 ".%" PRIx64 ";", reason_str,
963*be691f3bSpatrick                     tid_stop_info.details.fork.child_pid,
964*be691f3bSpatrick                     tid_stop_info.details.fork.child_tid);
965*be691f3bSpatrick   }
966*be691f3bSpatrick 
967061da546Spatrick   return SendPacketNoLock(response.GetString());
968061da546Spatrick }
969061da546Spatrick 
970061da546Spatrick void GDBRemoteCommunicationServerLLGS::HandleInferiorState_Exited(
971061da546Spatrick     NativeProcessProtocol *process) {
972061da546Spatrick   assert(process && "process cannot be NULL");
973061da546Spatrick 
974061da546Spatrick   Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
975061da546Spatrick   LLDB_LOGF(log, "GDBRemoteCommunicationServerLLGS::%s called", __FUNCTION__);
976061da546Spatrick 
977061da546Spatrick   PacketResult result = SendStopReasonForState(StateType::eStateExited);
978061da546Spatrick   if (result != PacketResult::Success) {
979061da546Spatrick     LLDB_LOGF(log,
980061da546Spatrick               "GDBRemoteCommunicationServerLLGS::%s failed to send stop "
981061da546Spatrick               "notification for PID %" PRIu64 ", state: eStateExited",
982061da546Spatrick               __FUNCTION__, process->GetID());
983061da546Spatrick   }
984061da546Spatrick 
985061da546Spatrick   // Close the pipe to the inferior terminal i/o if we launched it and set one
986061da546Spatrick   // up.
987061da546Spatrick   MaybeCloseInferiorTerminalConnection();
988061da546Spatrick 
989061da546Spatrick   // We are ready to exit the debug monitor.
990061da546Spatrick   m_exit_now = true;
991061da546Spatrick   m_mainloop.RequestTermination();
992061da546Spatrick }
993061da546Spatrick 
994061da546Spatrick void GDBRemoteCommunicationServerLLGS::HandleInferiorState_Stopped(
995061da546Spatrick     NativeProcessProtocol *process) {
996061da546Spatrick   assert(process && "process cannot be NULL");
997061da546Spatrick 
998061da546Spatrick   Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
999061da546Spatrick   LLDB_LOGF(log, "GDBRemoteCommunicationServerLLGS::%s called", __FUNCTION__);
1000061da546Spatrick 
1001061da546Spatrick   // Send the stop reason unless this is the stop after the launch or attach.
1002061da546Spatrick   switch (m_inferior_prev_state) {
1003061da546Spatrick   case eStateLaunching:
1004061da546Spatrick   case eStateAttaching:
1005061da546Spatrick     // Don't send anything per debugserver behavior.
1006061da546Spatrick     break;
1007061da546Spatrick   default:
1008061da546Spatrick     // In all other cases, send the stop reason.
1009061da546Spatrick     PacketResult result = SendStopReasonForState(StateType::eStateStopped);
1010061da546Spatrick     if (result != PacketResult::Success) {
1011061da546Spatrick       LLDB_LOGF(log,
1012061da546Spatrick                 "GDBRemoteCommunicationServerLLGS::%s failed to send stop "
1013061da546Spatrick                 "notification for PID %" PRIu64 ", state: eStateExited",
1014061da546Spatrick                 __FUNCTION__, process->GetID());
1015061da546Spatrick     }
1016061da546Spatrick     break;
1017061da546Spatrick   }
1018061da546Spatrick }
1019061da546Spatrick 
1020061da546Spatrick void GDBRemoteCommunicationServerLLGS::ProcessStateChanged(
1021061da546Spatrick     NativeProcessProtocol *process, lldb::StateType state) {
1022061da546Spatrick   assert(process && "process cannot be NULL");
1023061da546Spatrick   Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
1024061da546Spatrick   if (log) {
1025061da546Spatrick     LLDB_LOGF(log,
1026061da546Spatrick               "GDBRemoteCommunicationServerLLGS::%s called with "
1027061da546Spatrick               "NativeProcessProtocol pid %" PRIu64 ", state: %s",
1028061da546Spatrick               __FUNCTION__, process->GetID(), StateAsCString(state));
1029061da546Spatrick   }
1030061da546Spatrick 
1031061da546Spatrick   switch (state) {
1032061da546Spatrick   case StateType::eStateRunning:
1033061da546Spatrick     StartSTDIOForwarding();
1034061da546Spatrick     break;
1035061da546Spatrick 
1036061da546Spatrick   case StateType::eStateStopped:
1037061da546Spatrick     // Make sure we get all of the pending stdout/stderr from the inferior and
1038061da546Spatrick     // send it to the lldb host before we send the state change notification
1039061da546Spatrick     SendProcessOutput();
1040061da546Spatrick     // Then stop the forwarding, so that any late output (see llvm.org/pr25652)
1041061da546Spatrick     // does not interfere with our protocol.
1042061da546Spatrick     StopSTDIOForwarding();
1043061da546Spatrick     HandleInferiorState_Stopped(process);
1044061da546Spatrick     break;
1045061da546Spatrick 
1046061da546Spatrick   case StateType::eStateExited:
1047061da546Spatrick     // Same as above
1048061da546Spatrick     SendProcessOutput();
1049061da546Spatrick     StopSTDIOForwarding();
1050061da546Spatrick     HandleInferiorState_Exited(process);
1051061da546Spatrick     break;
1052061da546Spatrick 
1053061da546Spatrick   default:
1054061da546Spatrick     if (log) {
1055061da546Spatrick       LLDB_LOGF(log,
1056061da546Spatrick                 "GDBRemoteCommunicationServerLLGS::%s didn't handle state "
1057061da546Spatrick                 "change for pid %" PRIu64 ", new state: %s",
1058061da546Spatrick                 __FUNCTION__, process->GetID(), StateAsCString(state));
1059061da546Spatrick     }
1060061da546Spatrick     break;
1061061da546Spatrick   }
1062061da546Spatrick 
1063061da546Spatrick   // Remember the previous state reported to us.
1064061da546Spatrick   m_inferior_prev_state = state;
1065061da546Spatrick }
1066061da546Spatrick 
1067061da546Spatrick void GDBRemoteCommunicationServerLLGS::DidExec(NativeProcessProtocol *process) {
1068061da546Spatrick   ClearProcessSpecificData();
1069061da546Spatrick }
1070061da546Spatrick 
1071*be691f3bSpatrick void GDBRemoteCommunicationServerLLGS::NewSubprocess(
1072*be691f3bSpatrick     NativeProcessProtocol *parent_process,
1073*be691f3bSpatrick     std::unique_ptr<NativeProcessProtocol> child_process) {
1074*be691f3bSpatrick   lldb::pid_t child_pid = child_process->GetID();
1075*be691f3bSpatrick   assert(child_pid != LLDB_INVALID_PROCESS_ID);
1076*be691f3bSpatrick   assert(m_debugged_processes.find(child_pid) == m_debugged_processes.end());
1077*be691f3bSpatrick   m_debugged_processes[child_pid] = std::move(child_process);
1078*be691f3bSpatrick }
1079*be691f3bSpatrick 
1080061da546Spatrick void GDBRemoteCommunicationServerLLGS::DataAvailableCallback() {
1081061da546Spatrick   Log *log(GetLogIfAnyCategoriesSet(GDBR_LOG_COMM));
1082061da546Spatrick 
1083061da546Spatrick   if (!m_handshake_completed) {
1084061da546Spatrick     if (!HandshakeWithClient()) {
1085061da546Spatrick       LLDB_LOGF(log,
1086061da546Spatrick                 "GDBRemoteCommunicationServerLLGS::%s handshake with "
1087061da546Spatrick                 "client failed, exiting",
1088061da546Spatrick                 __FUNCTION__);
1089061da546Spatrick       m_mainloop.RequestTermination();
1090061da546Spatrick       return;
1091061da546Spatrick     }
1092061da546Spatrick     m_handshake_completed = true;
1093061da546Spatrick   }
1094061da546Spatrick 
1095061da546Spatrick   bool interrupt = false;
1096061da546Spatrick   bool done = false;
1097061da546Spatrick   Status error;
1098061da546Spatrick   while (true) {
1099061da546Spatrick     const PacketResult result = GetPacketAndSendResponse(
1100061da546Spatrick         std::chrono::microseconds(0), error, interrupt, done);
1101061da546Spatrick     if (result == PacketResult::ErrorReplyTimeout)
1102061da546Spatrick       break; // No more packets in the queue
1103061da546Spatrick 
1104061da546Spatrick     if ((result != PacketResult::Success)) {
1105061da546Spatrick       LLDB_LOGF(log,
1106061da546Spatrick                 "GDBRemoteCommunicationServerLLGS::%s processing a packet "
1107061da546Spatrick                 "failed: %s",
1108061da546Spatrick                 __FUNCTION__, error.AsCString());
1109061da546Spatrick       m_mainloop.RequestTermination();
1110061da546Spatrick       break;
1111061da546Spatrick     }
1112061da546Spatrick   }
1113061da546Spatrick }
1114061da546Spatrick 
1115061da546Spatrick Status GDBRemoteCommunicationServerLLGS::InitializeConnection(
1116dda28197Spatrick     std::unique_ptr<Connection> connection) {
1117061da546Spatrick   IOObjectSP read_object_sp = connection->GetReadObject();
1118dda28197Spatrick   GDBRemoteCommunicationServer::SetConnection(std::move(connection));
1119061da546Spatrick 
1120061da546Spatrick   Status error;
1121061da546Spatrick   m_network_handle_up = m_mainloop.RegisterReadObject(
1122061da546Spatrick       read_object_sp, [this](MainLoopBase &) { DataAvailableCallback(); },
1123061da546Spatrick       error);
1124061da546Spatrick   return error;
1125061da546Spatrick }
1126061da546Spatrick 
1127061da546Spatrick GDBRemoteCommunication::PacketResult
1128061da546Spatrick GDBRemoteCommunicationServerLLGS::SendONotification(const char *buffer,
1129061da546Spatrick                                                     uint32_t len) {
1130061da546Spatrick   if ((buffer == nullptr) || (len == 0)) {
1131061da546Spatrick     // Nothing to send.
1132061da546Spatrick     return PacketResult::Success;
1133061da546Spatrick   }
1134061da546Spatrick 
1135061da546Spatrick   StreamString response;
1136061da546Spatrick   response.PutChar('O');
1137061da546Spatrick   response.PutBytesAsRawHex8(buffer, len);
1138061da546Spatrick 
1139061da546Spatrick   return SendPacketNoLock(response.GetString());
1140061da546Spatrick }
1141061da546Spatrick 
1142061da546Spatrick Status GDBRemoteCommunicationServerLLGS::SetSTDIOFileDescriptor(int fd) {
1143061da546Spatrick   Status error;
1144061da546Spatrick 
1145061da546Spatrick   // Set up the reading/handling of process I/O
1146061da546Spatrick   std::unique_ptr<ConnectionFileDescriptor> conn_up(
1147061da546Spatrick       new ConnectionFileDescriptor(fd, true));
1148061da546Spatrick   if (!conn_up) {
1149061da546Spatrick     error.SetErrorString("failed to create ConnectionFileDescriptor");
1150061da546Spatrick     return error;
1151061da546Spatrick   }
1152061da546Spatrick 
1153061da546Spatrick   m_stdio_communication.SetCloseOnEOF(false);
1154dda28197Spatrick   m_stdio_communication.SetConnection(std::move(conn_up));
1155061da546Spatrick   if (!m_stdio_communication.IsConnected()) {
1156061da546Spatrick     error.SetErrorString(
1157061da546Spatrick         "failed to set connection for inferior I/O communication");
1158061da546Spatrick     return error;
1159061da546Spatrick   }
1160061da546Spatrick 
1161061da546Spatrick   return Status();
1162061da546Spatrick }
1163061da546Spatrick 
1164061da546Spatrick void GDBRemoteCommunicationServerLLGS::StartSTDIOForwarding() {
1165061da546Spatrick   // Don't forward if not connected (e.g. when attaching).
1166061da546Spatrick   if (!m_stdio_communication.IsConnected())
1167061da546Spatrick     return;
1168061da546Spatrick 
1169061da546Spatrick   Status error;
1170061da546Spatrick   lldbassert(!m_stdio_handle_up);
1171061da546Spatrick   m_stdio_handle_up = m_mainloop.RegisterReadObject(
1172061da546Spatrick       m_stdio_communication.GetConnection()->GetReadObject(),
1173061da546Spatrick       [this](MainLoopBase &) { SendProcessOutput(); }, error);
1174061da546Spatrick 
1175061da546Spatrick   if (!m_stdio_handle_up) {
1176061da546Spatrick     // Not much we can do about the failure. Log it and continue without
1177061da546Spatrick     // forwarding.
1178061da546Spatrick     if (Log *log = GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS))
1179061da546Spatrick       LLDB_LOGF(log,
1180061da546Spatrick                 "GDBRemoteCommunicationServerLLGS::%s Failed to set up stdio "
1181061da546Spatrick                 "forwarding: %s",
1182061da546Spatrick                 __FUNCTION__, error.AsCString());
1183061da546Spatrick   }
1184061da546Spatrick }
1185061da546Spatrick 
1186061da546Spatrick void GDBRemoteCommunicationServerLLGS::StopSTDIOForwarding() {
1187061da546Spatrick   m_stdio_handle_up.reset();
1188061da546Spatrick }
1189061da546Spatrick 
1190061da546Spatrick void GDBRemoteCommunicationServerLLGS::SendProcessOutput() {
1191061da546Spatrick   char buffer[1024];
1192061da546Spatrick   ConnectionStatus status;
1193061da546Spatrick   Status error;
1194061da546Spatrick   while (true) {
1195061da546Spatrick     size_t bytes_read = m_stdio_communication.Read(
1196061da546Spatrick         buffer, sizeof buffer, std::chrono::microseconds(0), status, &error);
1197061da546Spatrick     switch (status) {
1198061da546Spatrick     case eConnectionStatusSuccess:
1199061da546Spatrick       SendONotification(buffer, bytes_read);
1200061da546Spatrick       break;
1201061da546Spatrick     case eConnectionStatusLostConnection:
1202061da546Spatrick     case eConnectionStatusEndOfFile:
1203061da546Spatrick     case eConnectionStatusError:
1204061da546Spatrick     case eConnectionStatusNoConnection:
1205061da546Spatrick       if (Log *log = GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS))
1206061da546Spatrick         LLDB_LOGF(log,
1207061da546Spatrick                   "GDBRemoteCommunicationServerLLGS::%s Stopping stdio "
1208061da546Spatrick                   "forwarding as communication returned status %d (error: "
1209061da546Spatrick                   "%s)",
1210061da546Spatrick                   __FUNCTION__, status, error.AsCString());
1211061da546Spatrick       m_stdio_handle_up.reset();
1212061da546Spatrick       return;
1213061da546Spatrick 
1214061da546Spatrick     case eConnectionStatusInterrupted:
1215061da546Spatrick     case eConnectionStatusTimedOut:
1216061da546Spatrick       return;
1217061da546Spatrick     }
1218061da546Spatrick   }
1219061da546Spatrick }
1220061da546Spatrick 
1221061da546Spatrick GDBRemoteCommunication::PacketResult
1222*be691f3bSpatrick GDBRemoteCommunicationServerLLGS::Handle_jLLDBTraceSupported(
1223061da546Spatrick     StringExtractorGDBRemote &packet) {
1224*be691f3bSpatrick 
1225061da546Spatrick   // Fail if we don't have a current process.
1226*be691f3bSpatrick   if (!m_current_process ||
1227*be691f3bSpatrick       (m_current_process->GetID() == LLDB_INVALID_PROCESS_ID))
1228*be691f3bSpatrick     return SendErrorResponse(Status("Process not running."));
1229061da546Spatrick 
1230*be691f3bSpatrick   return SendJSONResponse(m_current_process->TraceSupported());
1231061da546Spatrick }
1232061da546Spatrick 
1233061da546Spatrick GDBRemoteCommunication::PacketResult
1234*be691f3bSpatrick GDBRemoteCommunicationServerLLGS::Handle_jLLDBTraceStop(
1235061da546Spatrick     StringExtractorGDBRemote &packet) {
1236061da546Spatrick   // Fail if we don't have a current process.
1237*be691f3bSpatrick   if (!m_current_process ||
1238*be691f3bSpatrick       (m_current_process->GetID() == LLDB_INVALID_PROCESS_ID))
1239*be691f3bSpatrick     return SendErrorResponse(Status("Process not running."));
1240061da546Spatrick 
1241*be691f3bSpatrick   packet.ConsumeFront("jLLDBTraceStop:");
1242*be691f3bSpatrick   Expected<TraceStopRequest> stop_request =
1243*be691f3bSpatrick       json::parse<TraceStopRequest>(packet.Peek(), "TraceStopRequest");
1244*be691f3bSpatrick   if (!stop_request)
1245*be691f3bSpatrick     return SendErrorResponse(stop_request.takeError());
1246061da546Spatrick 
1247*be691f3bSpatrick   if (Error err = m_current_process->TraceStop(*stop_request))
1248*be691f3bSpatrick     return SendErrorResponse(std::move(err));
1249061da546Spatrick 
1250061da546Spatrick   return SendOKResponse();
1251061da546Spatrick }
1252061da546Spatrick 
1253061da546Spatrick GDBRemoteCommunication::PacketResult
1254*be691f3bSpatrick GDBRemoteCommunicationServerLLGS::Handle_jLLDBTraceStart(
1255061da546Spatrick     StringExtractorGDBRemote &packet) {
1256061da546Spatrick 
1257061da546Spatrick   // Fail if we don't have a current process.
1258*be691f3bSpatrick   if (!m_current_process ||
1259*be691f3bSpatrick       (m_current_process->GetID() == LLDB_INVALID_PROCESS_ID))
1260*be691f3bSpatrick     return SendErrorResponse(Status("Process not running."));
1261061da546Spatrick 
1262*be691f3bSpatrick   packet.ConsumeFront("jLLDBTraceStart:");
1263*be691f3bSpatrick   Expected<TraceStartRequest> request =
1264*be691f3bSpatrick       json::parse<TraceStartRequest>(packet.Peek(), "TraceStartRequest");
1265*be691f3bSpatrick   if (!request)
1266*be691f3bSpatrick     return SendErrorResponse(request.takeError());
1267061da546Spatrick 
1268*be691f3bSpatrick   if (Error err = m_current_process->TraceStart(packet.Peek(), request->type))
1269*be691f3bSpatrick     return SendErrorResponse(std::move(err));
1270061da546Spatrick 
1271*be691f3bSpatrick   return SendOKResponse();
1272061da546Spatrick }
1273061da546Spatrick 
1274061da546Spatrick GDBRemoteCommunication::PacketResult
1275*be691f3bSpatrick GDBRemoteCommunicationServerLLGS::Handle_jLLDBTraceGetState(
1276061da546Spatrick     StringExtractorGDBRemote &packet) {
1277061da546Spatrick 
1278061da546Spatrick   // Fail if we don't have a current process.
1279*be691f3bSpatrick   if (!m_current_process ||
1280*be691f3bSpatrick       (m_current_process->GetID() == LLDB_INVALID_PROCESS_ID))
1281*be691f3bSpatrick     return SendErrorResponse(Status("Process not running."));
1282061da546Spatrick 
1283*be691f3bSpatrick   packet.ConsumeFront("jLLDBTraceGetState:");
1284*be691f3bSpatrick   Expected<TraceGetStateRequest> request =
1285*be691f3bSpatrick       json::parse<TraceGetStateRequest>(packet.Peek(), "TraceGetStateRequest");
1286*be691f3bSpatrick   if (!request)
1287*be691f3bSpatrick     return SendErrorResponse(request.takeError());
1288061da546Spatrick 
1289*be691f3bSpatrick   return SendJSONResponse(m_current_process->TraceGetState(request->type));
1290061da546Spatrick }
1291061da546Spatrick 
1292*be691f3bSpatrick GDBRemoteCommunication::PacketResult
1293*be691f3bSpatrick GDBRemoteCommunicationServerLLGS::Handle_jLLDBTraceGetBinaryData(
1294*be691f3bSpatrick     StringExtractorGDBRemote &packet) {
1295061da546Spatrick 
1296*be691f3bSpatrick   // Fail if we don't have a current process.
1297*be691f3bSpatrick   if (!m_current_process ||
1298*be691f3bSpatrick       (m_current_process->GetID() == LLDB_INVALID_PROCESS_ID))
1299*be691f3bSpatrick     return SendErrorResponse(Status("Process not running."));
1300061da546Spatrick 
1301*be691f3bSpatrick   packet.ConsumeFront("jLLDBTraceGetBinaryData:");
1302*be691f3bSpatrick   llvm::Expected<TraceGetBinaryDataRequest> request =
1303*be691f3bSpatrick       llvm::json::parse<TraceGetBinaryDataRequest>(packet.Peek(),
1304*be691f3bSpatrick                                                    "TraceGetBinaryDataRequest");
1305*be691f3bSpatrick   if (!request)
1306*be691f3bSpatrick     return SendErrorResponse(Status(request.takeError()));
1307061da546Spatrick 
1308*be691f3bSpatrick   if (Expected<std::vector<uint8_t>> bytes =
1309*be691f3bSpatrick           m_current_process->TraceGetBinaryData(*request)) {
1310061da546Spatrick     StreamGDBRemote response;
1311*be691f3bSpatrick     response.PutEscapedBytes(bytes->data(), bytes->size());
1312*be691f3bSpatrick     return SendPacketNoLock(response.GetString());
1313*be691f3bSpatrick   } else
1314*be691f3bSpatrick     return SendErrorResponse(bytes.takeError());
1315061da546Spatrick }
1316061da546Spatrick 
1317061da546Spatrick GDBRemoteCommunication::PacketResult
1318061da546Spatrick GDBRemoteCommunicationServerLLGS::Handle_qProcessInfo(
1319061da546Spatrick     StringExtractorGDBRemote &packet) {
1320061da546Spatrick   // Fail if we don't have a current process.
1321*be691f3bSpatrick   if (!m_current_process ||
1322*be691f3bSpatrick       (m_current_process->GetID() == LLDB_INVALID_PROCESS_ID))
1323061da546Spatrick     return SendErrorResponse(68);
1324061da546Spatrick 
1325*be691f3bSpatrick   lldb::pid_t pid = m_current_process->GetID();
1326061da546Spatrick 
1327061da546Spatrick   if (pid == LLDB_INVALID_PROCESS_ID)
1328061da546Spatrick     return SendErrorResponse(1);
1329061da546Spatrick 
1330061da546Spatrick   ProcessInstanceInfo proc_info;
1331061da546Spatrick   if (!Host::GetProcessInfo(pid, proc_info))
1332061da546Spatrick     return SendErrorResponse(1);
1333061da546Spatrick 
1334061da546Spatrick   StreamString response;
1335061da546Spatrick   CreateProcessInfoResponse_DebugServerStyle(proc_info, response);
1336061da546Spatrick   return SendPacketNoLock(response.GetString());
1337061da546Spatrick }
1338061da546Spatrick 
1339061da546Spatrick GDBRemoteCommunication::PacketResult
1340061da546Spatrick GDBRemoteCommunicationServerLLGS::Handle_qC(StringExtractorGDBRemote &packet) {
1341061da546Spatrick   // Fail if we don't have a current process.
1342*be691f3bSpatrick   if (!m_current_process ||
1343*be691f3bSpatrick       (m_current_process->GetID() == LLDB_INVALID_PROCESS_ID))
1344061da546Spatrick     return SendErrorResponse(68);
1345061da546Spatrick 
1346061da546Spatrick   // Make sure we set the current thread so g and p packets return the data the
1347061da546Spatrick   // gdb will expect.
1348*be691f3bSpatrick   lldb::tid_t tid = m_current_process->GetCurrentThreadID();
1349061da546Spatrick   SetCurrentThreadID(tid);
1350061da546Spatrick 
1351*be691f3bSpatrick   NativeThreadProtocol *thread = m_current_process->GetCurrentThread();
1352061da546Spatrick   if (!thread)
1353061da546Spatrick     return SendErrorResponse(69);
1354061da546Spatrick 
1355061da546Spatrick   StreamString response;
1356061da546Spatrick   response.Printf("QC%" PRIx64, thread->GetID());
1357061da546Spatrick 
1358061da546Spatrick   return SendPacketNoLock(response.GetString());
1359061da546Spatrick }
1360061da546Spatrick 
1361061da546Spatrick GDBRemoteCommunication::PacketResult
1362061da546Spatrick GDBRemoteCommunicationServerLLGS::Handle_k(StringExtractorGDBRemote &packet) {
1363061da546Spatrick   Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
1364061da546Spatrick 
1365061da546Spatrick   StopSTDIOForwarding();
1366061da546Spatrick 
1367*be691f3bSpatrick   if (!m_current_process) {
1368061da546Spatrick     LLDB_LOG(log, "No debugged process found.");
1369061da546Spatrick     return PacketResult::Success;
1370061da546Spatrick   }
1371061da546Spatrick 
1372*be691f3bSpatrick   Status error = m_current_process->Kill();
1373061da546Spatrick   if (error.Fail())
1374061da546Spatrick     LLDB_LOG(log, "Failed to kill debugged process {0}: {1}",
1375*be691f3bSpatrick              m_current_process->GetID(), error);
1376061da546Spatrick 
1377061da546Spatrick   // No OK response for kill packet.
1378061da546Spatrick   // return SendOKResponse ();
1379061da546Spatrick   return PacketResult::Success;
1380061da546Spatrick }
1381061da546Spatrick 
1382061da546Spatrick GDBRemoteCommunication::PacketResult
1383061da546Spatrick GDBRemoteCommunicationServerLLGS::Handle_QSetDisableASLR(
1384061da546Spatrick     StringExtractorGDBRemote &packet) {
1385061da546Spatrick   packet.SetFilePos(::strlen("QSetDisableASLR:"));
1386061da546Spatrick   if (packet.GetU32(0))
1387061da546Spatrick     m_process_launch_info.GetFlags().Set(eLaunchFlagDisableASLR);
1388061da546Spatrick   else
1389061da546Spatrick     m_process_launch_info.GetFlags().Clear(eLaunchFlagDisableASLR);
1390061da546Spatrick   return SendOKResponse();
1391061da546Spatrick }
1392061da546Spatrick 
1393061da546Spatrick GDBRemoteCommunication::PacketResult
1394061da546Spatrick GDBRemoteCommunicationServerLLGS::Handle_QSetWorkingDir(
1395061da546Spatrick     StringExtractorGDBRemote &packet) {
1396061da546Spatrick   packet.SetFilePos(::strlen("QSetWorkingDir:"));
1397061da546Spatrick   std::string path;
1398061da546Spatrick   packet.GetHexByteString(path);
1399061da546Spatrick   m_process_launch_info.SetWorkingDirectory(FileSpec(path));
1400061da546Spatrick   return SendOKResponse();
1401061da546Spatrick }
1402061da546Spatrick 
1403061da546Spatrick GDBRemoteCommunication::PacketResult
1404061da546Spatrick GDBRemoteCommunicationServerLLGS::Handle_qGetWorkingDir(
1405061da546Spatrick     StringExtractorGDBRemote &packet) {
1406061da546Spatrick   FileSpec working_dir{m_process_launch_info.GetWorkingDirectory()};
1407061da546Spatrick   if (working_dir) {
1408061da546Spatrick     StreamString response;
1409061da546Spatrick     response.PutStringAsRawHex8(working_dir.GetCString());
1410061da546Spatrick     return SendPacketNoLock(response.GetString());
1411061da546Spatrick   }
1412061da546Spatrick 
1413061da546Spatrick   return SendErrorResponse(14);
1414061da546Spatrick }
1415061da546Spatrick 
1416061da546Spatrick GDBRemoteCommunication::PacketResult
1417*be691f3bSpatrick GDBRemoteCommunicationServerLLGS::Handle_QThreadSuffixSupported(
1418*be691f3bSpatrick     StringExtractorGDBRemote &packet) {
1419*be691f3bSpatrick   m_thread_suffix_supported = true;
1420*be691f3bSpatrick   return SendOKResponse();
1421*be691f3bSpatrick }
1422*be691f3bSpatrick 
1423*be691f3bSpatrick GDBRemoteCommunication::PacketResult
1424*be691f3bSpatrick GDBRemoteCommunicationServerLLGS::Handle_QListThreadsInStopReply(
1425*be691f3bSpatrick     StringExtractorGDBRemote &packet) {
1426*be691f3bSpatrick   m_list_threads_in_stop_reply = true;
1427*be691f3bSpatrick   return SendOKResponse();
1428*be691f3bSpatrick }
1429*be691f3bSpatrick 
1430*be691f3bSpatrick GDBRemoteCommunication::PacketResult
1431061da546Spatrick GDBRemoteCommunicationServerLLGS::Handle_C(StringExtractorGDBRemote &packet) {
1432061da546Spatrick   Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS | LIBLLDB_LOG_THREAD));
1433061da546Spatrick   LLDB_LOGF(log, "GDBRemoteCommunicationServerLLGS::%s called", __FUNCTION__);
1434061da546Spatrick 
1435061da546Spatrick   // Ensure we have a native process.
1436*be691f3bSpatrick   if (!m_continue_process) {
1437061da546Spatrick     LLDB_LOGF(log,
1438061da546Spatrick               "GDBRemoteCommunicationServerLLGS::%s no debugged process "
1439061da546Spatrick               "shared pointer",
1440061da546Spatrick               __FUNCTION__);
1441061da546Spatrick     return SendErrorResponse(0x36);
1442061da546Spatrick   }
1443061da546Spatrick 
1444061da546Spatrick   // Pull out the signal number.
1445061da546Spatrick   packet.SetFilePos(::strlen("C"));
1446061da546Spatrick   if (packet.GetBytesLeft() < 1) {
1447061da546Spatrick     // Shouldn't be using a C without a signal.
1448061da546Spatrick     return SendIllFormedResponse(packet, "C packet specified without signal.");
1449061da546Spatrick   }
1450061da546Spatrick   const uint32_t signo =
1451061da546Spatrick       packet.GetHexMaxU32(false, std::numeric_limits<uint32_t>::max());
1452061da546Spatrick   if (signo == std::numeric_limits<uint32_t>::max())
1453061da546Spatrick     return SendIllFormedResponse(packet, "failed to parse signal number");
1454061da546Spatrick 
1455061da546Spatrick   // Handle optional continue address.
1456061da546Spatrick   if (packet.GetBytesLeft() > 0) {
1457061da546Spatrick     // FIXME add continue at address support for $C{signo}[;{continue-address}].
1458061da546Spatrick     if (*packet.Peek() == ';')
1459061da546Spatrick       return SendUnimplementedResponse(packet.GetStringRef().data());
1460061da546Spatrick     else
1461061da546Spatrick       return SendIllFormedResponse(
1462061da546Spatrick           packet, "unexpected content after $C{signal-number}");
1463061da546Spatrick   }
1464061da546Spatrick 
1465061da546Spatrick   ResumeActionList resume_actions(StateType::eStateRunning,
1466061da546Spatrick                                   LLDB_INVALID_SIGNAL_NUMBER);
1467061da546Spatrick   Status error;
1468061da546Spatrick 
1469061da546Spatrick   // We have two branches: what to do if a continue thread is specified (in
1470061da546Spatrick   // which case we target sending the signal to that thread), or when we don't
1471061da546Spatrick   // have a continue thread set (in which case we send a signal to the
1472061da546Spatrick   // process).
1473061da546Spatrick 
1474061da546Spatrick   // TODO discuss with Greg Clayton, make sure this makes sense.
1475061da546Spatrick 
1476061da546Spatrick   lldb::tid_t signal_tid = GetContinueThreadID();
1477061da546Spatrick   if (signal_tid != LLDB_INVALID_THREAD_ID) {
1478061da546Spatrick     // The resume action for the continue thread (or all threads if a continue
1479061da546Spatrick     // thread is not set).
1480061da546Spatrick     ResumeAction action = {GetContinueThreadID(), StateType::eStateRunning,
1481061da546Spatrick                            static_cast<int>(signo)};
1482061da546Spatrick 
1483061da546Spatrick     // Add the action for the continue thread (or all threads when the continue
1484061da546Spatrick     // thread isn't present).
1485061da546Spatrick     resume_actions.Append(action);
1486061da546Spatrick   } else {
1487061da546Spatrick     // Send the signal to the process since we weren't targeting a specific
1488061da546Spatrick     // continue thread with the signal.
1489*be691f3bSpatrick     error = m_continue_process->Signal(signo);
1490061da546Spatrick     if (error.Fail()) {
1491061da546Spatrick       LLDB_LOG(log, "failed to send signal for process {0}: {1}",
1492*be691f3bSpatrick                m_continue_process->GetID(), error);
1493061da546Spatrick 
1494061da546Spatrick       return SendErrorResponse(0x52);
1495061da546Spatrick     }
1496061da546Spatrick   }
1497061da546Spatrick 
1498061da546Spatrick   // Resume the threads.
1499*be691f3bSpatrick   error = m_continue_process->Resume(resume_actions);
1500061da546Spatrick   if (error.Fail()) {
1501061da546Spatrick     LLDB_LOG(log, "failed to resume threads for process {0}: {1}",
1502*be691f3bSpatrick              m_continue_process->GetID(), error);
1503061da546Spatrick 
1504061da546Spatrick     return SendErrorResponse(0x38);
1505061da546Spatrick   }
1506061da546Spatrick 
1507061da546Spatrick   // Don't send an "OK" packet; response is the stopped/exited message.
1508061da546Spatrick   return PacketResult::Success;
1509061da546Spatrick }
1510061da546Spatrick 
1511061da546Spatrick GDBRemoteCommunication::PacketResult
1512061da546Spatrick GDBRemoteCommunicationServerLLGS::Handle_c(StringExtractorGDBRemote &packet) {
1513061da546Spatrick   Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS | LIBLLDB_LOG_THREAD));
1514061da546Spatrick   LLDB_LOGF(log, "GDBRemoteCommunicationServerLLGS::%s called", __FUNCTION__);
1515061da546Spatrick 
1516061da546Spatrick   packet.SetFilePos(packet.GetFilePos() + ::strlen("c"));
1517061da546Spatrick 
1518061da546Spatrick   // For now just support all continue.
1519061da546Spatrick   const bool has_continue_address = (packet.GetBytesLeft() > 0);
1520061da546Spatrick   if (has_continue_address) {
1521061da546Spatrick     LLDB_LOG(log, "not implemented for c[address] variant [{0} remains]",
1522061da546Spatrick              packet.Peek());
1523061da546Spatrick     return SendUnimplementedResponse(packet.GetStringRef().data());
1524061da546Spatrick   }
1525061da546Spatrick 
1526061da546Spatrick   // Ensure we have a native process.
1527*be691f3bSpatrick   if (!m_continue_process) {
1528061da546Spatrick     LLDB_LOGF(log,
1529061da546Spatrick               "GDBRemoteCommunicationServerLLGS::%s no debugged process "
1530061da546Spatrick               "shared pointer",
1531061da546Spatrick               __FUNCTION__);
1532061da546Spatrick     return SendErrorResponse(0x36);
1533061da546Spatrick   }
1534061da546Spatrick 
1535061da546Spatrick   // Build the ResumeActionList
1536061da546Spatrick   ResumeActionList actions(StateType::eStateRunning,
1537061da546Spatrick                            LLDB_INVALID_SIGNAL_NUMBER);
1538061da546Spatrick 
1539*be691f3bSpatrick   Status error = m_continue_process->Resume(actions);
1540061da546Spatrick   if (error.Fail()) {
1541*be691f3bSpatrick     LLDB_LOG(log, "c failed for process {0}: {1}", m_continue_process->GetID(),
1542*be691f3bSpatrick              error);
1543061da546Spatrick     return SendErrorResponse(GDBRemoteServerError::eErrorResume);
1544061da546Spatrick   }
1545061da546Spatrick 
1546*be691f3bSpatrick   LLDB_LOG(log, "continued process {0}", m_continue_process->GetID());
1547061da546Spatrick   // No response required from continue.
1548061da546Spatrick   return PacketResult::Success;
1549061da546Spatrick }
1550061da546Spatrick 
1551061da546Spatrick GDBRemoteCommunication::PacketResult
1552061da546Spatrick GDBRemoteCommunicationServerLLGS::Handle_vCont_actions(
1553061da546Spatrick     StringExtractorGDBRemote &packet) {
1554061da546Spatrick   StreamString response;
1555061da546Spatrick   response.Printf("vCont;c;C;s;S");
1556061da546Spatrick 
1557061da546Spatrick   return SendPacketNoLock(response.GetString());
1558061da546Spatrick }
1559061da546Spatrick 
1560061da546Spatrick GDBRemoteCommunication::PacketResult
1561061da546Spatrick GDBRemoteCommunicationServerLLGS::Handle_vCont(
1562061da546Spatrick     StringExtractorGDBRemote &packet) {
1563061da546Spatrick   Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
1564061da546Spatrick   LLDB_LOGF(log, "GDBRemoteCommunicationServerLLGS::%s handling vCont packet",
1565061da546Spatrick             __FUNCTION__);
1566061da546Spatrick 
1567061da546Spatrick   packet.SetFilePos(::strlen("vCont"));
1568061da546Spatrick 
1569061da546Spatrick   if (packet.GetBytesLeft() == 0) {
1570061da546Spatrick     LLDB_LOGF(log,
1571061da546Spatrick               "GDBRemoteCommunicationServerLLGS::%s missing action from "
1572061da546Spatrick               "vCont package",
1573061da546Spatrick               __FUNCTION__);
1574061da546Spatrick     return SendIllFormedResponse(packet, "Missing action from vCont package");
1575061da546Spatrick   }
1576061da546Spatrick 
1577061da546Spatrick   // Check if this is all continue (no options or ";c").
1578061da546Spatrick   if (::strcmp(packet.Peek(), ";c") == 0) {
1579061da546Spatrick     // Move past the ';', then do a simple 'c'.
1580061da546Spatrick     packet.SetFilePos(packet.GetFilePos() + 1);
1581061da546Spatrick     return Handle_c(packet);
1582061da546Spatrick   } else if (::strcmp(packet.Peek(), ";s") == 0) {
1583061da546Spatrick     // Move past the ';', then do a simple 's'.
1584061da546Spatrick     packet.SetFilePos(packet.GetFilePos() + 1);
1585061da546Spatrick     return Handle_s(packet);
1586061da546Spatrick   }
1587061da546Spatrick 
1588061da546Spatrick   // Ensure we have a native process.
1589*be691f3bSpatrick   if (!m_continue_process) {
1590061da546Spatrick     LLDB_LOG(log, "no debugged process");
1591061da546Spatrick     return SendErrorResponse(0x36);
1592061da546Spatrick   }
1593061da546Spatrick 
1594061da546Spatrick   ResumeActionList thread_actions;
1595061da546Spatrick 
1596061da546Spatrick   while (packet.GetBytesLeft() && *packet.Peek() == ';') {
1597061da546Spatrick     // Skip the semi-colon.
1598061da546Spatrick     packet.GetChar();
1599061da546Spatrick 
1600061da546Spatrick     // Build up the thread action.
1601061da546Spatrick     ResumeAction thread_action;
1602061da546Spatrick     thread_action.tid = LLDB_INVALID_THREAD_ID;
1603061da546Spatrick     thread_action.state = eStateInvalid;
1604061da546Spatrick     thread_action.signal = LLDB_INVALID_SIGNAL_NUMBER;
1605061da546Spatrick 
1606061da546Spatrick     const char action = packet.GetChar();
1607061da546Spatrick     switch (action) {
1608061da546Spatrick     case 'C':
1609061da546Spatrick       thread_action.signal = packet.GetHexMaxU32(false, 0);
1610061da546Spatrick       if (thread_action.signal == 0)
1611061da546Spatrick         return SendIllFormedResponse(
1612061da546Spatrick             packet, "Could not parse signal in vCont packet C action");
1613061da546Spatrick       LLVM_FALLTHROUGH;
1614061da546Spatrick 
1615061da546Spatrick     case 'c':
1616061da546Spatrick       // Continue
1617061da546Spatrick       thread_action.state = eStateRunning;
1618061da546Spatrick       break;
1619061da546Spatrick 
1620061da546Spatrick     case 'S':
1621061da546Spatrick       thread_action.signal = packet.GetHexMaxU32(false, 0);
1622061da546Spatrick       if (thread_action.signal == 0)
1623061da546Spatrick         return SendIllFormedResponse(
1624061da546Spatrick             packet, "Could not parse signal in vCont packet S action");
1625061da546Spatrick       LLVM_FALLTHROUGH;
1626061da546Spatrick 
1627061da546Spatrick     case 's':
1628061da546Spatrick       // Step
1629061da546Spatrick       thread_action.state = eStateStepping;
1630061da546Spatrick       break;
1631061da546Spatrick 
1632061da546Spatrick     default:
1633061da546Spatrick       return SendIllFormedResponse(packet, "Unsupported vCont action");
1634061da546Spatrick       break;
1635061da546Spatrick     }
1636061da546Spatrick 
1637061da546Spatrick     // Parse out optional :{thread-id} value.
1638061da546Spatrick     if (packet.GetBytesLeft() && (*packet.Peek() == ':')) {
1639061da546Spatrick       // Consume the separator.
1640061da546Spatrick       packet.GetChar();
1641061da546Spatrick 
1642*be691f3bSpatrick       llvm::Expected<lldb::tid_t> tid_ret =
1643*be691f3bSpatrick           ReadTid(packet, /*allow_all=*/true, m_continue_process->GetID());
1644*be691f3bSpatrick       if (!tid_ret)
1645*be691f3bSpatrick         return SendErrorResponse(tid_ret.takeError());
1646*be691f3bSpatrick 
1647*be691f3bSpatrick       thread_action.tid = tid_ret.get();
1648*be691f3bSpatrick       if (thread_action.tid == StringExtractorGDBRemote::AllThreads)
1649*be691f3bSpatrick         thread_action.tid = LLDB_INVALID_THREAD_ID;
1650061da546Spatrick     }
1651061da546Spatrick 
1652061da546Spatrick     thread_actions.Append(thread_action);
1653061da546Spatrick   }
1654061da546Spatrick 
1655*be691f3bSpatrick   Status error = m_continue_process->Resume(thread_actions);
1656061da546Spatrick   if (error.Fail()) {
1657061da546Spatrick     LLDB_LOG(log, "vCont failed for process {0}: {1}",
1658*be691f3bSpatrick              m_continue_process->GetID(), error);
1659061da546Spatrick     return SendErrorResponse(GDBRemoteServerError::eErrorResume);
1660061da546Spatrick   }
1661061da546Spatrick 
1662*be691f3bSpatrick   LLDB_LOG(log, "continued process {0}", m_continue_process->GetID());
1663061da546Spatrick   // No response required from vCont.
1664061da546Spatrick   return PacketResult::Success;
1665061da546Spatrick }
1666061da546Spatrick 
1667061da546Spatrick void GDBRemoteCommunicationServerLLGS::SetCurrentThreadID(lldb::tid_t tid) {
1668061da546Spatrick   Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_THREAD));
1669061da546Spatrick   LLDB_LOG(log, "setting current thread id to {0}", tid);
1670061da546Spatrick 
1671061da546Spatrick   m_current_tid = tid;
1672*be691f3bSpatrick   if (m_current_process)
1673*be691f3bSpatrick     m_current_process->SetCurrentThreadID(m_current_tid);
1674061da546Spatrick }
1675061da546Spatrick 
1676061da546Spatrick void GDBRemoteCommunicationServerLLGS::SetContinueThreadID(lldb::tid_t tid) {
1677061da546Spatrick   Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_THREAD));
1678061da546Spatrick   LLDB_LOG(log, "setting continue thread id to {0}", tid);
1679061da546Spatrick 
1680061da546Spatrick   m_continue_tid = tid;
1681061da546Spatrick }
1682061da546Spatrick 
1683061da546Spatrick GDBRemoteCommunication::PacketResult
1684061da546Spatrick GDBRemoteCommunicationServerLLGS::Handle_stop_reason(
1685061da546Spatrick     StringExtractorGDBRemote &packet) {
1686061da546Spatrick   // Handle the $? gdbremote command.
1687061da546Spatrick 
1688061da546Spatrick   // If no process, indicate error
1689*be691f3bSpatrick   if (!m_current_process)
1690061da546Spatrick     return SendErrorResponse(02);
1691061da546Spatrick 
1692*be691f3bSpatrick   return SendStopReasonForState(m_current_process->GetState());
1693061da546Spatrick }
1694061da546Spatrick 
1695061da546Spatrick GDBRemoteCommunication::PacketResult
1696061da546Spatrick GDBRemoteCommunicationServerLLGS::SendStopReasonForState(
1697061da546Spatrick     lldb::StateType process_state) {
1698061da546Spatrick   Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
1699061da546Spatrick 
1700061da546Spatrick   switch (process_state) {
1701061da546Spatrick   case eStateAttaching:
1702061da546Spatrick   case eStateLaunching:
1703061da546Spatrick   case eStateRunning:
1704061da546Spatrick   case eStateStepping:
1705061da546Spatrick   case eStateDetached:
1706061da546Spatrick     // NOTE: gdb protocol doc looks like it should return $OK
1707061da546Spatrick     // when everything is running (i.e. no stopped result).
1708061da546Spatrick     return PacketResult::Success; // Ignore
1709061da546Spatrick 
1710061da546Spatrick   case eStateSuspended:
1711061da546Spatrick   case eStateStopped:
1712061da546Spatrick   case eStateCrashed: {
1713*be691f3bSpatrick     assert(m_current_process != nullptr);
1714*be691f3bSpatrick     lldb::tid_t tid = m_current_process->GetCurrentThreadID();
1715061da546Spatrick     // Make sure we set the current thread so g and p packets return the data
1716061da546Spatrick     // the gdb will expect.
1717061da546Spatrick     SetCurrentThreadID(tid);
1718061da546Spatrick     return SendStopReplyPacketForThread(tid);
1719061da546Spatrick   }
1720061da546Spatrick 
1721061da546Spatrick   case eStateInvalid:
1722061da546Spatrick   case eStateUnloaded:
1723061da546Spatrick   case eStateExited:
1724*be691f3bSpatrick     return SendWResponse(m_current_process);
1725061da546Spatrick 
1726061da546Spatrick   default:
1727061da546Spatrick     LLDB_LOG(log, "pid {0}, current state reporting not handled: {1}",
1728*be691f3bSpatrick              m_current_process->GetID(), process_state);
1729061da546Spatrick     break;
1730061da546Spatrick   }
1731061da546Spatrick 
1732061da546Spatrick   return SendErrorResponse(0);
1733061da546Spatrick }
1734061da546Spatrick 
1735061da546Spatrick GDBRemoteCommunication::PacketResult
1736061da546Spatrick GDBRemoteCommunicationServerLLGS::Handle_qRegisterInfo(
1737061da546Spatrick     StringExtractorGDBRemote &packet) {
1738061da546Spatrick   // Fail if we don't have a current process.
1739*be691f3bSpatrick   if (!m_current_process ||
1740*be691f3bSpatrick       (m_current_process->GetID() == LLDB_INVALID_PROCESS_ID))
1741061da546Spatrick     return SendErrorResponse(68);
1742061da546Spatrick 
1743061da546Spatrick   // Ensure we have a thread.
1744*be691f3bSpatrick   NativeThreadProtocol *thread = m_current_process->GetThreadAtIndex(0);
1745061da546Spatrick   if (!thread)
1746061da546Spatrick     return SendErrorResponse(69);
1747061da546Spatrick 
1748061da546Spatrick   // Get the register context for the first thread.
1749061da546Spatrick   NativeRegisterContext &reg_context = thread->GetRegisterContext();
1750061da546Spatrick 
1751061da546Spatrick   // Parse out the register number from the request.
1752061da546Spatrick   packet.SetFilePos(strlen("qRegisterInfo"));
1753061da546Spatrick   const uint32_t reg_index =
1754061da546Spatrick       packet.GetHexMaxU32(false, std::numeric_limits<uint32_t>::max());
1755061da546Spatrick   if (reg_index == std::numeric_limits<uint32_t>::max())
1756061da546Spatrick     return SendErrorResponse(69);
1757061da546Spatrick 
1758061da546Spatrick   // Return the end of registers response if we've iterated one past the end of
1759061da546Spatrick   // the register set.
1760061da546Spatrick   if (reg_index >= reg_context.GetUserRegisterCount())
1761061da546Spatrick     return SendErrorResponse(69);
1762061da546Spatrick 
1763061da546Spatrick   const RegisterInfo *reg_info = reg_context.GetRegisterInfoAtIndex(reg_index);
1764061da546Spatrick   if (!reg_info)
1765061da546Spatrick     return SendErrorResponse(69);
1766061da546Spatrick 
1767061da546Spatrick   // Build the reginfos response.
1768061da546Spatrick   StreamGDBRemote response;
1769061da546Spatrick 
1770061da546Spatrick   response.PutCString("name:");
1771061da546Spatrick   response.PutCString(reg_info->name);
1772061da546Spatrick   response.PutChar(';');
1773061da546Spatrick 
1774061da546Spatrick   if (reg_info->alt_name && reg_info->alt_name[0]) {
1775061da546Spatrick     response.PutCString("alt-name:");
1776061da546Spatrick     response.PutCString(reg_info->alt_name);
1777061da546Spatrick     response.PutChar(';');
1778061da546Spatrick   }
1779061da546Spatrick 
1780*be691f3bSpatrick   response.Printf("bitsize:%" PRIu32 ";", reg_info->byte_size * 8);
1781*be691f3bSpatrick 
1782*be691f3bSpatrick   if (!reg_context.RegisterOffsetIsDynamic())
1783*be691f3bSpatrick     response.Printf("offset:%" PRIu32 ";", reg_info->byte_offset);
1784061da546Spatrick 
1785dda28197Spatrick   llvm::StringRef encoding = GetEncodingNameOrEmpty(*reg_info);
1786dda28197Spatrick   if (!encoding.empty())
1787dda28197Spatrick     response << "encoding:" << encoding << ';';
1788061da546Spatrick 
1789dda28197Spatrick   llvm::StringRef format = GetFormatNameOrEmpty(*reg_info);
1790dda28197Spatrick   if (!format.empty())
1791dda28197Spatrick     response << "format:" << format << ';';
1792061da546Spatrick 
1793061da546Spatrick   const char *const register_set_name =
1794061da546Spatrick       reg_context.GetRegisterSetNameForRegisterAtIndex(reg_index);
1795dda28197Spatrick   if (register_set_name)
1796dda28197Spatrick     response << "set:" << register_set_name << ';';
1797061da546Spatrick 
1798061da546Spatrick   if (reg_info->kinds[RegisterKind::eRegisterKindEHFrame] !=
1799061da546Spatrick       LLDB_INVALID_REGNUM)
1800061da546Spatrick     response.Printf("ehframe:%" PRIu32 ";",
1801061da546Spatrick                     reg_info->kinds[RegisterKind::eRegisterKindEHFrame]);
1802061da546Spatrick 
1803061da546Spatrick   if (reg_info->kinds[RegisterKind::eRegisterKindDWARF] != LLDB_INVALID_REGNUM)
1804061da546Spatrick     response.Printf("dwarf:%" PRIu32 ";",
1805061da546Spatrick                     reg_info->kinds[RegisterKind::eRegisterKindDWARF]);
1806061da546Spatrick 
1807dda28197Spatrick   llvm::StringRef kind_generic = GetKindGenericOrEmpty(*reg_info);
1808dda28197Spatrick   if (!kind_generic.empty())
1809dda28197Spatrick     response << "generic:" << kind_generic << ';';
1810061da546Spatrick 
1811061da546Spatrick   if (reg_info->value_regs && reg_info->value_regs[0] != LLDB_INVALID_REGNUM) {
1812061da546Spatrick     response.PutCString("container-regs:");
1813dda28197Spatrick     CollectRegNums(reg_info->value_regs, response, true);
1814061da546Spatrick     response.PutChar(';');
1815061da546Spatrick   }
1816061da546Spatrick 
1817061da546Spatrick   if (reg_info->invalidate_regs && reg_info->invalidate_regs[0]) {
1818061da546Spatrick     response.PutCString("invalidate-regs:");
1819dda28197Spatrick     CollectRegNums(reg_info->invalidate_regs, response, true);
1820061da546Spatrick     response.PutChar(';');
1821061da546Spatrick   }
1822061da546Spatrick 
1823061da546Spatrick   if (reg_info->dynamic_size_dwarf_expr_bytes) {
1824061da546Spatrick     const size_t dwarf_opcode_len = reg_info->dynamic_size_dwarf_len;
1825061da546Spatrick     response.PutCString("dynamic_size_dwarf_expr_bytes:");
1826061da546Spatrick     for (uint32_t i = 0; i < dwarf_opcode_len; ++i)
1827061da546Spatrick       response.PutHex8(reg_info->dynamic_size_dwarf_expr_bytes[i]);
1828061da546Spatrick     response.PutChar(';');
1829061da546Spatrick   }
1830061da546Spatrick   return SendPacketNoLock(response.GetString());
1831061da546Spatrick }
1832061da546Spatrick 
1833061da546Spatrick GDBRemoteCommunication::PacketResult
1834061da546Spatrick GDBRemoteCommunicationServerLLGS::Handle_qfThreadInfo(
1835061da546Spatrick     StringExtractorGDBRemote &packet) {
1836061da546Spatrick   Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_THREAD));
1837061da546Spatrick 
1838061da546Spatrick   // Fail if we don't have a current process.
1839*be691f3bSpatrick   if (!m_current_process ||
1840*be691f3bSpatrick       (m_current_process->GetID() == LLDB_INVALID_PROCESS_ID)) {
1841061da546Spatrick     LLDB_LOG(log, "no process ({0}), returning OK",
1842*be691f3bSpatrick              m_current_process ? "invalid process id"
1843*be691f3bSpatrick                                : "null m_current_process");
1844061da546Spatrick     return SendOKResponse();
1845061da546Spatrick   }
1846061da546Spatrick 
1847061da546Spatrick   StreamGDBRemote response;
1848061da546Spatrick   response.PutChar('m');
1849061da546Spatrick 
1850061da546Spatrick   LLDB_LOG(log, "starting thread iteration");
1851061da546Spatrick   NativeThreadProtocol *thread;
1852061da546Spatrick   uint32_t thread_index;
1853061da546Spatrick   for (thread_index = 0,
1854*be691f3bSpatrick       thread = m_current_process->GetThreadAtIndex(thread_index);
1855061da546Spatrick        thread; ++thread_index,
1856*be691f3bSpatrick       thread = m_current_process->GetThreadAtIndex(thread_index)) {
1857061da546Spatrick     LLDB_LOG(log, "iterated thread {0}(tid={2})", thread_index,
1858061da546Spatrick              thread->GetID());
1859061da546Spatrick     if (thread_index > 0)
1860061da546Spatrick       response.PutChar(',');
1861061da546Spatrick     response.Printf("%" PRIx64, thread->GetID());
1862061da546Spatrick   }
1863061da546Spatrick 
1864061da546Spatrick   LLDB_LOG(log, "finished thread iteration");
1865061da546Spatrick   return SendPacketNoLock(response.GetString());
1866061da546Spatrick }
1867061da546Spatrick 
1868061da546Spatrick GDBRemoteCommunication::PacketResult
1869061da546Spatrick GDBRemoteCommunicationServerLLGS::Handle_qsThreadInfo(
1870061da546Spatrick     StringExtractorGDBRemote &packet) {
1871061da546Spatrick   // FIXME for now we return the full thread list in the initial packet and
1872061da546Spatrick   // always do nothing here.
1873061da546Spatrick   return SendPacketNoLock("l");
1874061da546Spatrick }
1875061da546Spatrick 
1876061da546Spatrick GDBRemoteCommunication::PacketResult
1877061da546Spatrick GDBRemoteCommunicationServerLLGS::Handle_g(StringExtractorGDBRemote &packet) {
1878061da546Spatrick   Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_THREAD));
1879061da546Spatrick 
1880061da546Spatrick   // Move past packet name.
1881061da546Spatrick   packet.SetFilePos(strlen("g"));
1882061da546Spatrick 
1883061da546Spatrick   // Get the thread to use.
1884061da546Spatrick   NativeThreadProtocol *thread = GetThreadFromSuffix(packet);
1885061da546Spatrick   if (!thread) {
1886061da546Spatrick     LLDB_LOG(log, "failed, no thread available");
1887061da546Spatrick     return SendErrorResponse(0x15);
1888061da546Spatrick   }
1889061da546Spatrick 
1890061da546Spatrick   // Get the thread's register context.
1891061da546Spatrick   NativeRegisterContext &reg_ctx = thread->GetRegisterContext();
1892061da546Spatrick 
1893061da546Spatrick   std::vector<uint8_t> regs_buffer;
1894061da546Spatrick   for (uint32_t reg_num = 0; reg_num < reg_ctx.GetUserRegisterCount();
1895061da546Spatrick        ++reg_num) {
1896061da546Spatrick     const RegisterInfo *reg_info = reg_ctx.GetRegisterInfoAtIndex(reg_num);
1897061da546Spatrick 
1898061da546Spatrick     if (reg_info == nullptr) {
1899061da546Spatrick       LLDB_LOG(log, "failed to get register info for register index {0}",
1900061da546Spatrick                reg_num);
1901061da546Spatrick       return SendErrorResponse(0x15);
1902061da546Spatrick     }
1903061da546Spatrick 
1904061da546Spatrick     if (reg_info->value_regs != nullptr)
1905061da546Spatrick       continue; // skip registers that are contained in other registers
1906061da546Spatrick 
1907061da546Spatrick     RegisterValue reg_value;
1908061da546Spatrick     Status error = reg_ctx.ReadRegister(reg_info, reg_value);
1909061da546Spatrick     if (error.Fail()) {
1910061da546Spatrick       LLDB_LOG(log, "failed to read register at index {0}", reg_num);
1911061da546Spatrick       return SendErrorResponse(0x15);
1912061da546Spatrick     }
1913061da546Spatrick 
1914061da546Spatrick     if (reg_info->byte_offset + reg_info->byte_size >= regs_buffer.size())
1915061da546Spatrick       // Resize the buffer to guarantee it can store the register offsetted
1916061da546Spatrick       // data.
1917061da546Spatrick       regs_buffer.resize(reg_info->byte_offset + reg_info->byte_size);
1918061da546Spatrick 
1919061da546Spatrick     // Copy the register offsetted data to the buffer.
1920061da546Spatrick     memcpy(regs_buffer.data() + reg_info->byte_offset, reg_value.GetBytes(),
1921061da546Spatrick            reg_info->byte_size);
1922061da546Spatrick   }
1923061da546Spatrick 
1924061da546Spatrick   // Write the response.
1925061da546Spatrick   StreamGDBRemote response;
1926061da546Spatrick   response.PutBytesAsRawHex8(regs_buffer.data(), regs_buffer.size());
1927061da546Spatrick 
1928061da546Spatrick   return SendPacketNoLock(response.GetString());
1929061da546Spatrick }
1930061da546Spatrick 
1931061da546Spatrick GDBRemoteCommunication::PacketResult
1932061da546Spatrick GDBRemoteCommunicationServerLLGS::Handle_p(StringExtractorGDBRemote &packet) {
1933061da546Spatrick   Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_THREAD));
1934061da546Spatrick 
1935061da546Spatrick   // Parse out the register number from the request.
1936061da546Spatrick   packet.SetFilePos(strlen("p"));
1937061da546Spatrick   const uint32_t reg_index =
1938061da546Spatrick       packet.GetHexMaxU32(false, std::numeric_limits<uint32_t>::max());
1939061da546Spatrick   if (reg_index == std::numeric_limits<uint32_t>::max()) {
1940061da546Spatrick     LLDB_LOGF(log,
1941061da546Spatrick               "GDBRemoteCommunicationServerLLGS::%s failed, could not "
1942061da546Spatrick               "parse register number from request \"%s\"",
1943061da546Spatrick               __FUNCTION__, packet.GetStringRef().data());
1944061da546Spatrick     return SendErrorResponse(0x15);
1945061da546Spatrick   }
1946061da546Spatrick 
1947061da546Spatrick   // Get the thread to use.
1948061da546Spatrick   NativeThreadProtocol *thread = GetThreadFromSuffix(packet);
1949061da546Spatrick   if (!thread) {
1950061da546Spatrick     LLDB_LOG(log, "failed, no thread available");
1951061da546Spatrick     return SendErrorResponse(0x15);
1952061da546Spatrick   }
1953061da546Spatrick 
1954061da546Spatrick   // Get the thread's register context.
1955061da546Spatrick   NativeRegisterContext &reg_context = thread->GetRegisterContext();
1956061da546Spatrick 
1957061da546Spatrick   // Return the end of registers response if we've iterated one past the end of
1958061da546Spatrick   // the register set.
1959061da546Spatrick   if (reg_index >= reg_context.GetUserRegisterCount()) {
1960061da546Spatrick     LLDB_LOGF(log,
1961061da546Spatrick               "GDBRemoteCommunicationServerLLGS::%s failed, requested "
1962061da546Spatrick               "register %" PRIu32 " beyond register count %" PRIu32,
1963061da546Spatrick               __FUNCTION__, reg_index, reg_context.GetUserRegisterCount());
1964061da546Spatrick     return SendErrorResponse(0x15);
1965061da546Spatrick   }
1966061da546Spatrick 
1967061da546Spatrick   const RegisterInfo *reg_info = reg_context.GetRegisterInfoAtIndex(reg_index);
1968061da546Spatrick   if (!reg_info) {
1969061da546Spatrick     LLDB_LOGF(log,
1970061da546Spatrick               "GDBRemoteCommunicationServerLLGS::%s failed, requested "
1971061da546Spatrick               "register %" PRIu32 " returned NULL",
1972061da546Spatrick               __FUNCTION__, reg_index);
1973061da546Spatrick     return SendErrorResponse(0x15);
1974061da546Spatrick   }
1975061da546Spatrick 
1976061da546Spatrick   // Build the reginfos response.
1977061da546Spatrick   StreamGDBRemote response;
1978061da546Spatrick 
1979061da546Spatrick   // Retrieve the value
1980061da546Spatrick   RegisterValue reg_value;
1981061da546Spatrick   Status error = reg_context.ReadRegister(reg_info, reg_value);
1982061da546Spatrick   if (error.Fail()) {
1983061da546Spatrick     LLDB_LOGF(log,
1984061da546Spatrick               "GDBRemoteCommunicationServerLLGS::%s failed, read of "
1985061da546Spatrick               "requested register %" PRIu32 " (%s) failed: %s",
1986061da546Spatrick               __FUNCTION__, reg_index, reg_info->name, error.AsCString());
1987061da546Spatrick     return SendErrorResponse(0x15);
1988061da546Spatrick   }
1989061da546Spatrick 
1990061da546Spatrick   const uint8_t *const data =
1991061da546Spatrick       static_cast<const uint8_t *>(reg_value.GetBytes());
1992061da546Spatrick   if (!data) {
1993061da546Spatrick     LLDB_LOGF(log,
1994061da546Spatrick               "GDBRemoteCommunicationServerLLGS::%s failed to get data "
1995061da546Spatrick               "bytes from requested register %" PRIu32,
1996061da546Spatrick               __FUNCTION__, reg_index);
1997061da546Spatrick     return SendErrorResponse(0x15);
1998061da546Spatrick   }
1999061da546Spatrick 
2000061da546Spatrick   // FIXME flip as needed to get data in big/little endian format for this host.
2001061da546Spatrick   for (uint32_t i = 0; i < reg_value.GetByteSize(); ++i)
2002061da546Spatrick     response.PutHex8(data[i]);
2003061da546Spatrick 
2004061da546Spatrick   return SendPacketNoLock(response.GetString());
2005061da546Spatrick }
2006061da546Spatrick 
2007061da546Spatrick GDBRemoteCommunication::PacketResult
2008061da546Spatrick GDBRemoteCommunicationServerLLGS::Handle_P(StringExtractorGDBRemote &packet) {
2009061da546Spatrick   Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_THREAD));
2010061da546Spatrick 
2011061da546Spatrick   // Ensure there is more content.
2012061da546Spatrick   if (packet.GetBytesLeft() < 1)
2013061da546Spatrick     return SendIllFormedResponse(packet, "Empty P packet");
2014061da546Spatrick 
2015061da546Spatrick   // Parse out the register number from the request.
2016061da546Spatrick   packet.SetFilePos(strlen("P"));
2017061da546Spatrick   const uint32_t reg_index =
2018061da546Spatrick       packet.GetHexMaxU32(false, std::numeric_limits<uint32_t>::max());
2019061da546Spatrick   if (reg_index == std::numeric_limits<uint32_t>::max()) {
2020061da546Spatrick     LLDB_LOGF(log,
2021061da546Spatrick               "GDBRemoteCommunicationServerLLGS::%s failed, could not "
2022061da546Spatrick               "parse register number from request \"%s\"",
2023061da546Spatrick               __FUNCTION__, packet.GetStringRef().data());
2024061da546Spatrick     return SendErrorResponse(0x29);
2025061da546Spatrick   }
2026061da546Spatrick 
2027061da546Spatrick   // Note debugserver would send an E30 here.
2028061da546Spatrick   if ((packet.GetBytesLeft() < 1) || (packet.GetChar() != '='))
2029061da546Spatrick     return SendIllFormedResponse(
2030061da546Spatrick         packet, "P packet missing '=' char after register number");
2031061da546Spatrick 
2032061da546Spatrick   // Parse out the value.
2033dda28197Spatrick   uint8_t reg_bytes[RegisterValue::kMaxRegisterByteSize];
2034061da546Spatrick   size_t reg_size = packet.GetHexBytesAvail(reg_bytes);
2035061da546Spatrick 
2036061da546Spatrick   // Get the thread to use.
2037061da546Spatrick   NativeThreadProtocol *thread = GetThreadFromSuffix(packet);
2038061da546Spatrick   if (!thread) {
2039061da546Spatrick     LLDB_LOGF(log,
2040061da546Spatrick               "GDBRemoteCommunicationServerLLGS::%s failed, no thread "
2041061da546Spatrick               "available (thread index 0)",
2042061da546Spatrick               __FUNCTION__);
2043061da546Spatrick     return SendErrorResponse(0x28);
2044061da546Spatrick   }
2045061da546Spatrick 
2046061da546Spatrick   // Get the thread's register context.
2047061da546Spatrick   NativeRegisterContext &reg_context = thread->GetRegisterContext();
2048061da546Spatrick   const RegisterInfo *reg_info = reg_context.GetRegisterInfoAtIndex(reg_index);
2049061da546Spatrick   if (!reg_info) {
2050061da546Spatrick     LLDB_LOGF(log,
2051061da546Spatrick               "GDBRemoteCommunicationServerLLGS::%s failed, requested "
2052061da546Spatrick               "register %" PRIu32 " returned NULL",
2053061da546Spatrick               __FUNCTION__, reg_index);
2054061da546Spatrick     return SendErrorResponse(0x48);
2055061da546Spatrick   }
2056061da546Spatrick 
2057061da546Spatrick   // Return the end of registers response if we've iterated one past the end of
2058061da546Spatrick   // the register set.
2059061da546Spatrick   if (reg_index >= reg_context.GetUserRegisterCount()) {
2060061da546Spatrick     LLDB_LOGF(log,
2061061da546Spatrick               "GDBRemoteCommunicationServerLLGS::%s failed, requested "
2062061da546Spatrick               "register %" PRIu32 " beyond register count %" PRIu32,
2063061da546Spatrick               __FUNCTION__, reg_index, reg_context.GetUserRegisterCount());
2064061da546Spatrick     return SendErrorResponse(0x47);
2065061da546Spatrick   }
2066061da546Spatrick 
2067061da546Spatrick   // The dwarf expression are evaluate on host site which may cause register
2068061da546Spatrick   // size to change Hence the reg_size may not be same as reg_info->bytes_size
2069061da546Spatrick   if ((reg_size != reg_info->byte_size) &&
2070061da546Spatrick       !(reg_info->dynamic_size_dwarf_expr_bytes)) {
2071061da546Spatrick     return SendIllFormedResponse(packet, "P packet register size is incorrect");
2072061da546Spatrick   }
2073061da546Spatrick 
2074061da546Spatrick   // Build the reginfos response.
2075061da546Spatrick   StreamGDBRemote response;
2076061da546Spatrick 
2077*be691f3bSpatrick   RegisterValue reg_value(makeArrayRef(reg_bytes, reg_size),
2078*be691f3bSpatrick                           m_current_process->GetArchitecture().GetByteOrder());
2079061da546Spatrick   Status error = reg_context.WriteRegister(reg_info, reg_value);
2080061da546Spatrick   if (error.Fail()) {
2081061da546Spatrick     LLDB_LOGF(log,
2082061da546Spatrick               "GDBRemoteCommunicationServerLLGS::%s failed, write of "
2083061da546Spatrick               "requested register %" PRIu32 " (%s) failed: %s",
2084061da546Spatrick               __FUNCTION__, reg_index, reg_info->name, error.AsCString());
2085061da546Spatrick     return SendErrorResponse(0x32);
2086061da546Spatrick   }
2087061da546Spatrick 
2088061da546Spatrick   return SendOKResponse();
2089061da546Spatrick }
2090061da546Spatrick 
2091061da546Spatrick GDBRemoteCommunication::PacketResult
2092061da546Spatrick GDBRemoteCommunicationServerLLGS::Handle_H(StringExtractorGDBRemote &packet) {
2093061da546Spatrick   Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_THREAD));
2094061da546Spatrick 
2095061da546Spatrick   // Parse out which variant of $H is requested.
2096061da546Spatrick   packet.SetFilePos(strlen("H"));
2097061da546Spatrick   if (packet.GetBytesLeft() < 1) {
2098061da546Spatrick     LLDB_LOGF(log,
2099061da546Spatrick               "GDBRemoteCommunicationServerLLGS::%s failed, H command "
2100061da546Spatrick               "missing {g,c} variant",
2101061da546Spatrick               __FUNCTION__);
2102061da546Spatrick     return SendIllFormedResponse(packet, "H command missing {g,c} variant");
2103061da546Spatrick   }
2104061da546Spatrick 
2105061da546Spatrick   const char h_variant = packet.GetChar();
2106*be691f3bSpatrick   NativeProcessProtocol *default_process;
2107061da546Spatrick   switch (h_variant) {
2108061da546Spatrick   case 'g':
2109*be691f3bSpatrick     default_process = m_current_process;
2110061da546Spatrick     break;
2111061da546Spatrick 
2112061da546Spatrick   case 'c':
2113*be691f3bSpatrick     default_process = m_continue_process;
2114061da546Spatrick     break;
2115061da546Spatrick 
2116061da546Spatrick   default:
2117061da546Spatrick     LLDB_LOGF(
2118061da546Spatrick         log,
2119061da546Spatrick         "GDBRemoteCommunicationServerLLGS::%s failed, invalid $H variant %c",
2120061da546Spatrick         __FUNCTION__, h_variant);
2121061da546Spatrick     return SendIllFormedResponse(packet,
2122061da546Spatrick                                  "H variant unsupported, should be c or g");
2123061da546Spatrick   }
2124061da546Spatrick 
2125061da546Spatrick   // Parse out the thread number.
2126*be691f3bSpatrick   auto pid_tid = packet.GetPidTid(default_process ? default_process->GetID()
2127*be691f3bSpatrick                                                   : LLDB_INVALID_PROCESS_ID);
2128*be691f3bSpatrick   if (!pid_tid)
2129*be691f3bSpatrick     return SendErrorResponse(llvm::make_error<StringError>(
2130*be691f3bSpatrick         inconvertibleErrorCode(), "Malformed thread-id"));
2131*be691f3bSpatrick 
2132*be691f3bSpatrick   lldb::pid_t pid = pid_tid->first;
2133*be691f3bSpatrick   lldb::tid_t tid = pid_tid->second;
2134*be691f3bSpatrick 
2135*be691f3bSpatrick   if (pid == StringExtractorGDBRemote::AllProcesses)
2136*be691f3bSpatrick     return SendUnimplementedResponse("Selecting all processes not supported");
2137*be691f3bSpatrick   if (pid == LLDB_INVALID_PROCESS_ID)
2138*be691f3bSpatrick     return SendErrorResponse(llvm::make_error<StringError>(
2139*be691f3bSpatrick         inconvertibleErrorCode(), "No current process and no PID provided"));
2140*be691f3bSpatrick 
2141*be691f3bSpatrick   // Check the process ID and find respective process instance.
2142*be691f3bSpatrick   auto new_process_it = m_debugged_processes.find(pid);
2143*be691f3bSpatrick   if (new_process_it == m_debugged_processes.end())
2144*be691f3bSpatrick     return SendErrorResponse(llvm::make_error<StringError>(
2145*be691f3bSpatrick         inconvertibleErrorCode(),
2146*be691f3bSpatrick         llvm::formatv("No process with PID {0} debugged", pid)));
2147061da546Spatrick 
2148061da546Spatrick   // Ensure we have the given thread when not specifying -1 (all threads) or 0
2149061da546Spatrick   // (any thread).
2150061da546Spatrick   if (tid != LLDB_INVALID_THREAD_ID && tid != 0) {
2151*be691f3bSpatrick     NativeThreadProtocol *thread = new_process_it->second->GetThreadByID(tid);
2152061da546Spatrick     if (!thread) {
2153061da546Spatrick       LLDB_LOGF(log,
2154061da546Spatrick                 "GDBRemoteCommunicationServerLLGS::%s failed, tid %" PRIu64
2155061da546Spatrick                 " not found",
2156061da546Spatrick                 __FUNCTION__, tid);
2157061da546Spatrick       return SendErrorResponse(0x15);
2158061da546Spatrick     }
2159061da546Spatrick   }
2160061da546Spatrick 
2161*be691f3bSpatrick   // Now switch the given process and thread type.
2162061da546Spatrick   switch (h_variant) {
2163061da546Spatrick   case 'g':
2164*be691f3bSpatrick     m_current_process = new_process_it->second.get();
2165061da546Spatrick     SetCurrentThreadID(tid);
2166061da546Spatrick     break;
2167061da546Spatrick 
2168061da546Spatrick   case 'c':
2169*be691f3bSpatrick     m_continue_process = new_process_it->second.get();
2170061da546Spatrick     SetContinueThreadID(tid);
2171061da546Spatrick     break;
2172061da546Spatrick 
2173061da546Spatrick   default:
2174061da546Spatrick     assert(false && "unsupported $H variant - shouldn't get here");
2175061da546Spatrick     return SendIllFormedResponse(packet,
2176061da546Spatrick                                  "H variant unsupported, should be c or g");
2177061da546Spatrick   }
2178061da546Spatrick 
2179061da546Spatrick   return SendOKResponse();
2180061da546Spatrick }
2181061da546Spatrick 
2182061da546Spatrick GDBRemoteCommunication::PacketResult
2183061da546Spatrick GDBRemoteCommunicationServerLLGS::Handle_I(StringExtractorGDBRemote &packet) {
2184061da546Spatrick   Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_THREAD));
2185061da546Spatrick 
2186061da546Spatrick   // Fail if we don't have a current process.
2187*be691f3bSpatrick   if (!m_current_process ||
2188*be691f3bSpatrick       (m_current_process->GetID() == LLDB_INVALID_PROCESS_ID)) {
2189061da546Spatrick     LLDB_LOGF(
2190061da546Spatrick         log,
2191061da546Spatrick         "GDBRemoteCommunicationServerLLGS::%s failed, no process available",
2192061da546Spatrick         __FUNCTION__);
2193061da546Spatrick     return SendErrorResponse(0x15);
2194061da546Spatrick   }
2195061da546Spatrick 
2196061da546Spatrick   packet.SetFilePos(::strlen("I"));
2197061da546Spatrick   uint8_t tmp[4096];
2198061da546Spatrick   for (;;) {
2199061da546Spatrick     size_t read = packet.GetHexBytesAvail(tmp);
2200061da546Spatrick     if (read == 0) {
2201061da546Spatrick       break;
2202061da546Spatrick     }
2203061da546Spatrick     // write directly to stdin *this might block if stdin buffer is full*
2204061da546Spatrick     // TODO: enqueue this block in circular buffer and send window size to
2205061da546Spatrick     // remote host
2206061da546Spatrick     ConnectionStatus status;
2207061da546Spatrick     Status error;
2208061da546Spatrick     m_stdio_communication.Write(tmp, read, status, &error);
2209061da546Spatrick     if (error.Fail()) {
2210061da546Spatrick       return SendErrorResponse(0x15);
2211061da546Spatrick     }
2212061da546Spatrick   }
2213061da546Spatrick 
2214061da546Spatrick   return SendOKResponse();
2215061da546Spatrick }
2216061da546Spatrick 
2217061da546Spatrick GDBRemoteCommunication::PacketResult
2218061da546Spatrick GDBRemoteCommunicationServerLLGS::Handle_interrupt(
2219061da546Spatrick     StringExtractorGDBRemote &packet) {
2220061da546Spatrick   Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS | LIBLLDB_LOG_THREAD));
2221061da546Spatrick 
2222061da546Spatrick   // Fail if we don't have a current process.
2223*be691f3bSpatrick   if (!m_current_process ||
2224*be691f3bSpatrick       (m_current_process->GetID() == LLDB_INVALID_PROCESS_ID)) {
2225061da546Spatrick     LLDB_LOG(log, "failed, no process available");
2226061da546Spatrick     return SendErrorResponse(0x15);
2227061da546Spatrick   }
2228061da546Spatrick 
2229061da546Spatrick   // Interrupt the process.
2230*be691f3bSpatrick   Status error = m_current_process->Interrupt();
2231061da546Spatrick   if (error.Fail()) {
2232*be691f3bSpatrick     LLDB_LOG(log, "failed for process {0}: {1}", m_current_process->GetID(),
2233061da546Spatrick              error);
2234061da546Spatrick     return SendErrorResponse(GDBRemoteServerError::eErrorResume);
2235061da546Spatrick   }
2236061da546Spatrick 
2237*be691f3bSpatrick   LLDB_LOG(log, "stopped process {0}", m_current_process->GetID());
2238061da546Spatrick 
2239061da546Spatrick   // No response required from stop all.
2240061da546Spatrick   return PacketResult::Success;
2241061da546Spatrick }
2242061da546Spatrick 
2243061da546Spatrick GDBRemoteCommunication::PacketResult
2244061da546Spatrick GDBRemoteCommunicationServerLLGS::Handle_memory_read(
2245061da546Spatrick     StringExtractorGDBRemote &packet) {
2246061da546Spatrick   Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
2247061da546Spatrick 
2248*be691f3bSpatrick   if (!m_current_process ||
2249*be691f3bSpatrick       (m_current_process->GetID() == LLDB_INVALID_PROCESS_ID)) {
2250061da546Spatrick     LLDB_LOGF(
2251061da546Spatrick         log,
2252061da546Spatrick         "GDBRemoteCommunicationServerLLGS::%s failed, no process available",
2253061da546Spatrick         __FUNCTION__);
2254061da546Spatrick     return SendErrorResponse(0x15);
2255061da546Spatrick   }
2256061da546Spatrick 
2257061da546Spatrick   // Parse out the memory address.
2258061da546Spatrick   packet.SetFilePos(strlen("m"));
2259061da546Spatrick   if (packet.GetBytesLeft() < 1)
2260061da546Spatrick     return SendIllFormedResponse(packet, "Too short m packet");
2261061da546Spatrick 
2262061da546Spatrick   // Read the address.  Punting on validation.
2263061da546Spatrick   // FIXME replace with Hex U64 read with no default value that fails on failed
2264061da546Spatrick   // read.
2265061da546Spatrick   const lldb::addr_t read_addr = packet.GetHexMaxU64(false, 0);
2266061da546Spatrick 
2267061da546Spatrick   // Validate comma.
2268061da546Spatrick   if ((packet.GetBytesLeft() < 1) || (packet.GetChar() != ','))
2269061da546Spatrick     return SendIllFormedResponse(packet, "Comma sep missing in m packet");
2270061da546Spatrick 
2271061da546Spatrick   // Get # bytes to read.
2272061da546Spatrick   if (packet.GetBytesLeft() < 1)
2273061da546Spatrick     return SendIllFormedResponse(packet, "Length missing in m packet");
2274061da546Spatrick 
2275061da546Spatrick   const uint64_t byte_count = packet.GetHexMaxU64(false, 0);
2276061da546Spatrick   if (byte_count == 0) {
2277061da546Spatrick     LLDB_LOGF(log,
2278061da546Spatrick               "GDBRemoteCommunicationServerLLGS::%s nothing to read: "
2279061da546Spatrick               "zero-length packet",
2280061da546Spatrick               __FUNCTION__);
2281061da546Spatrick     return SendOKResponse();
2282061da546Spatrick   }
2283061da546Spatrick 
2284061da546Spatrick   // Allocate the response buffer.
2285061da546Spatrick   std::string buf(byte_count, '\0');
2286061da546Spatrick   if (buf.empty())
2287061da546Spatrick     return SendErrorResponse(0x78);
2288061da546Spatrick 
2289061da546Spatrick   // Retrieve the process memory.
2290061da546Spatrick   size_t bytes_read = 0;
2291*be691f3bSpatrick   Status error = m_current_process->ReadMemoryWithoutTrap(
2292061da546Spatrick       read_addr, &buf[0], byte_count, bytes_read);
2293061da546Spatrick   if (error.Fail()) {
2294061da546Spatrick     LLDB_LOGF(log,
2295061da546Spatrick               "GDBRemoteCommunicationServerLLGS::%s pid %" PRIu64
2296061da546Spatrick               " mem 0x%" PRIx64 ": failed to read. Error: %s",
2297*be691f3bSpatrick               __FUNCTION__, m_current_process->GetID(), read_addr,
2298061da546Spatrick               error.AsCString());
2299061da546Spatrick     return SendErrorResponse(0x08);
2300061da546Spatrick   }
2301061da546Spatrick 
2302061da546Spatrick   if (bytes_read == 0) {
2303061da546Spatrick     LLDB_LOGF(log,
2304061da546Spatrick               "GDBRemoteCommunicationServerLLGS::%s pid %" PRIu64
2305061da546Spatrick               " mem 0x%" PRIx64 ": read 0 of %" PRIu64 " requested bytes",
2306*be691f3bSpatrick               __FUNCTION__, m_current_process->GetID(), read_addr, byte_count);
2307061da546Spatrick     return SendErrorResponse(0x08);
2308061da546Spatrick   }
2309061da546Spatrick 
2310061da546Spatrick   StreamGDBRemote response;
2311061da546Spatrick   packet.SetFilePos(0);
2312061da546Spatrick   char kind = packet.GetChar('?');
2313061da546Spatrick   if (kind == 'x')
2314061da546Spatrick     response.PutEscapedBytes(buf.data(), byte_count);
2315061da546Spatrick   else {
2316061da546Spatrick     assert(kind == 'm');
2317061da546Spatrick     for (size_t i = 0; i < bytes_read; ++i)
2318061da546Spatrick       response.PutHex8(buf[i]);
2319061da546Spatrick   }
2320061da546Spatrick 
2321061da546Spatrick   return SendPacketNoLock(response.GetString());
2322061da546Spatrick }
2323061da546Spatrick 
2324061da546Spatrick GDBRemoteCommunication::PacketResult
2325*be691f3bSpatrick GDBRemoteCommunicationServerLLGS::Handle__M(StringExtractorGDBRemote &packet) {
2326*be691f3bSpatrick   Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
2327*be691f3bSpatrick 
2328*be691f3bSpatrick   if (!m_current_process ||
2329*be691f3bSpatrick       (m_current_process->GetID() == LLDB_INVALID_PROCESS_ID)) {
2330*be691f3bSpatrick     LLDB_LOGF(
2331*be691f3bSpatrick         log,
2332*be691f3bSpatrick         "GDBRemoteCommunicationServerLLGS::%s failed, no process available",
2333*be691f3bSpatrick         __FUNCTION__);
2334*be691f3bSpatrick     return SendErrorResponse(0x15);
2335*be691f3bSpatrick   }
2336*be691f3bSpatrick 
2337*be691f3bSpatrick   // Parse out the memory address.
2338*be691f3bSpatrick   packet.SetFilePos(strlen("_M"));
2339*be691f3bSpatrick   if (packet.GetBytesLeft() < 1)
2340*be691f3bSpatrick     return SendIllFormedResponse(packet, "Too short _M packet");
2341*be691f3bSpatrick 
2342*be691f3bSpatrick   const lldb::addr_t size = packet.GetHexMaxU64(false, LLDB_INVALID_ADDRESS);
2343*be691f3bSpatrick   if (size == LLDB_INVALID_ADDRESS)
2344*be691f3bSpatrick     return SendIllFormedResponse(packet, "Address not valid");
2345*be691f3bSpatrick   if (packet.GetChar() != ',')
2346*be691f3bSpatrick     return SendIllFormedResponse(packet, "Bad packet");
2347*be691f3bSpatrick   Permissions perms = {};
2348*be691f3bSpatrick   while (packet.GetBytesLeft() > 0) {
2349*be691f3bSpatrick     switch (packet.GetChar()) {
2350*be691f3bSpatrick     case 'r':
2351*be691f3bSpatrick       perms |= ePermissionsReadable;
2352*be691f3bSpatrick       break;
2353*be691f3bSpatrick     case 'w':
2354*be691f3bSpatrick       perms |= ePermissionsWritable;
2355*be691f3bSpatrick       break;
2356*be691f3bSpatrick     case 'x':
2357*be691f3bSpatrick       perms |= ePermissionsExecutable;
2358*be691f3bSpatrick       break;
2359*be691f3bSpatrick     default:
2360*be691f3bSpatrick       return SendIllFormedResponse(packet, "Bad permissions");
2361*be691f3bSpatrick     }
2362*be691f3bSpatrick   }
2363*be691f3bSpatrick 
2364*be691f3bSpatrick   llvm::Expected<addr_t> addr = m_current_process->AllocateMemory(size, perms);
2365*be691f3bSpatrick   if (!addr)
2366*be691f3bSpatrick     return SendErrorResponse(addr.takeError());
2367*be691f3bSpatrick 
2368*be691f3bSpatrick   StreamGDBRemote response;
2369*be691f3bSpatrick   response.PutHex64(*addr);
2370*be691f3bSpatrick   return SendPacketNoLock(response.GetString());
2371*be691f3bSpatrick }
2372*be691f3bSpatrick 
2373*be691f3bSpatrick GDBRemoteCommunication::PacketResult
2374*be691f3bSpatrick GDBRemoteCommunicationServerLLGS::Handle__m(StringExtractorGDBRemote &packet) {
2375*be691f3bSpatrick   Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
2376*be691f3bSpatrick 
2377*be691f3bSpatrick   if (!m_current_process ||
2378*be691f3bSpatrick       (m_current_process->GetID() == LLDB_INVALID_PROCESS_ID)) {
2379*be691f3bSpatrick     LLDB_LOGF(
2380*be691f3bSpatrick         log,
2381*be691f3bSpatrick         "GDBRemoteCommunicationServerLLGS::%s failed, no process available",
2382*be691f3bSpatrick         __FUNCTION__);
2383*be691f3bSpatrick     return SendErrorResponse(0x15);
2384*be691f3bSpatrick   }
2385*be691f3bSpatrick 
2386*be691f3bSpatrick   // Parse out the memory address.
2387*be691f3bSpatrick   packet.SetFilePos(strlen("_m"));
2388*be691f3bSpatrick   if (packet.GetBytesLeft() < 1)
2389*be691f3bSpatrick     return SendIllFormedResponse(packet, "Too short m packet");
2390*be691f3bSpatrick 
2391*be691f3bSpatrick   const lldb::addr_t addr = packet.GetHexMaxU64(false, LLDB_INVALID_ADDRESS);
2392*be691f3bSpatrick   if (addr == LLDB_INVALID_ADDRESS)
2393*be691f3bSpatrick     return SendIllFormedResponse(packet, "Address not valid");
2394*be691f3bSpatrick 
2395*be691f3bSpatrick   if (llvm::Error Err = m_current_process->DeallocateMemory(addr))
2396*be691f3bSpatrick     return SendErrorResponse(std::move(Err));
2397*be691f3bSpatrick 
2398*be691f3bSpatrick   return SendOKResponse();
2399*be691f3bSpatrick }
2400*be691f3bSpatrick 
2401*be691f3bSpatrick GDBRemoteCommunication::PacketResult
2402061da546Spatrick GDBRemoteCommunicationServerLLGS::Handle_M(StringExtractorGDBRemote &packet) {
2403061da546Spatrick   Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
2404061da546Spatrick 
2405*be691f3bSpatrick   if (!m_current_process ||
2406*be691f3bSpatrick       (m_current_process->GetID() == LLDB_INVALID_PROCESS_ID)) {
2407061da546Spatrick     LLDB_LOGF(
2408061da546Spatrick         log,
2409061da546Spatrick         "GDBRemoteCommunicationServerLLGS::%s failed, no process available",
2410061da546Spatrick         __FUNCTION__);
2411061da546Spatrick     return SendErrorResponse(0x15);
2412061da546Spatrick   }
2413061da546Spatrick 
2414061da546Spatrick   // Parse out the memory address.
2415061da546Spatrick   packet.SetFilePos(strlen("M"));
2416061da546Spatrick   if (packet.GetBytesLeft() < 1)
2417061da546Spatrick     return SendIllFormedResponse(packet, "Too short M packet");
2418061da546Spatrick 
2419061da546Spatrick   // Read the address.  Punting on validation.
2420061da546Spatrick   // FIXME replace with Hex U64 read with no default value that fails on failed
2421061da546Spatrick   // read.
2422061da546Spatrick   const lldb::addr_t write_addr = packet.GetHexMaxU64(false, 0);
2423061da546Spatrick 
2424061da546Spatrick   // Validate comma.
2425061da546Spatrick   if ((packet.GetBytesLeft() < 1) || (packet.GetChar() != ','))
2426061da546Spatrick     return SendIllFormedResponse(packet, "Comma sep missing in M packet");
2427061da546Spatrick 
2428061da546Spatrick   // Get # bytes to read.
2429061da546Spatrick   if (packet.GetBytesLeft() < 1)
2430061da546Spatrick     return SendIllFormedResponse(packet, "Length missing in M packet");
2431061da546Spatrick 
2432061da546Spatrick   const uint64_t byte_count = packet.GetHexMaxU64(false, 0);
2433061da546Spatrick   if (byte_count == 0) {
2434061da546Spatrick     LLDB_LOG(log, "nothing to write: zero-length packet");
2435061da546Spatrick     return PacketResult::Success;
2436061da546Spatrick   }
2437061da546Spatrick 
2438061da546Spatrick   // Validate colon.
2439061da546Spatrick   if ((packet.GetBytesLeft() < 1) || (packet.GetChar() != ':'))
2440061da546Spatrick     return SendIllFormedResponse(
2441061da546Spatrick         packet, "Comma sep missing in M packet after byte length");
2442061da546Spatrick 
2443061da546Spatrick   // Allocate the conversion buffer.
2444061da546Spatrick   std::vector<uint8_t> buf(byte_count, 0);
2445061da546Spatrick   if (buf.empty())
2446061da546Spatrick     return SendErrorResponse(0x78);
2447061da546Spatrick 
2448061da546Spatrick   // Convert the hex memory write contents to bytes.
2449061da546Spatrick   StreamGDBRemote response;
2450061da546Spatrick   const uint64_t convert_count = packet.GetHexBytes(buf, 0);
2451061da546Spatrick   if (convert_count != byte_count) {
2452061da546Spatrick     LLDB_LOG(log,
2453061da546Spatrick              "pid {0} mem {1:x}: asked to write {2} bytes, but only found {3} "
2454061da546Spatrick              "to convert.",
2455*be691f3bSpatrick              m_current_process->GetID(), write_addr, byte_count, convert_count);
2456061da546Spatrick     return SendIllFormedResponse(packet, "M content byte length specified did "
2457061da546Spatrick                                          "not match hex-encoded content "
2458061da546Spatrick                                          "length");
2459061da546Spatrick   }
2460061da546Spatrick 
2461061da546Spatrick   // Write the process memory.
2462061da546Spatrick   size_t bytes_written = 0;
2463*be691f3bSpatrick   Status error = m_current_process->WriteMemory(write_addr, &buf[0], byte_count,
2464*be691f3bSpatrick                                                 bytes_written);
2465061da546Spatrick   if (error.Fail()) {
2466061da546Spatrick     LLDB_LOG(log, "pid {0} mem {1:x}: failed to write. Error: {2}",
2467*be691f3bSpatrick              m_current_process->GetID(), write_addr, error);
2468061da546Spatrick     return SendErrorResponse(0x09);
2469061da546Spatrick   }
2470061da546Spatrick 
2471061da546Spatrick   if (bytes_written == 0) {
2472061da546Spatrick     LLDB_LOG(log, "pid {0} mem {1:x}: wrote 0 of {2} requested bytes",
2473*be691f3bSpatrick              m_current_process->GetID(), write_addr, byte_count);
2474061da546Spatrick     return SendErrorResponse(0x09);
2475061da546Spatrick   }
2476061da546Spatrick 
2477061da546Spatrick   return SendOKResponse();
2478061da546Spatrick }
2479061da546Spatrick 
2480061da546Spatrick GDBRemoteCommunication::PacketResult
2481061da546Spatrick GDBRemoteCommunicationServerLLGS::Handle_qMemoryRegionInfoSupported(
2482061da546Spatrick     StringExtractorGDBRemote &packet) {
2483061da546Spatrick   Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
2484061da546Spatrick 
2485061da546Spatrick   // Currently only the NativeProcessProtocol knows if it can handle a
2486061da546Spatrick   // qMemoryRegionInfoSupported request, but we're not guaranteed to be
2487061da546Spatrick   // attached to a process.  For now we'll assume the client only asks this
2488061da546Spatrick   // when a process is being debugged.
2489061da546Spatrick 
2490061da546Spatrick   // Ensure we have a process running; otherwise, we can't figure this out
2491061da546Spatrick   // since we won't have a NativeProcessProtocol.
2492*be691f3bSpatrick   if (!m_current_process ||
2493*be691f3bSpatrick       (m_current_process->GetID() == LLDB_INVALID_PROCESS_ID)) {
2494061da546Spatrick     LLDB_LOGF(
2495061da546Spatrick         log,
2496061da546Spatrick         "GDBRemoteCommunicationServerLLGS::%s failed, no process available",
2497061da546Spatrick         __FUNCTION__);
2498061da546Spatrick     return SendErrorResponse(0x15);
2499061da546Spatrick   }
2500061da546Spatrick 
2501061da546Spatrick   // Test if we can get any region back when asking for the region around NULL.
2502061da546Spatrick   MemoryRegionInfo region_info;
2503*be691f3bSpatrick   const Status error = m_current_process->GetMemoryRegionInfo(0, region_info);
2504061da546Spatrick   if (error.Fail()) {
2505061da546Spatrick     // We don't support memory region info collection for this
2506061da546Spatrick     // NativeProcessProtocol.
2507061da546Spatrick     return SendUnimplementedResponse("");
2508061da546Spatrick   }
2509061da546Spatrick 
2510061da546Spatrick   return SendOKResponse();
2511061da546Spatrick }
2512061da546Spatrick 
2513061da546Spatrick GDBRemoteCommunication::PacketResult
2514061da546Spatrick GDBRemoteCommunicationServerLLGS::Handle_qMemoryRegionInfo(
2515061da546Spatrick     StringExtractorGDBRemote &packet) {
2516061da546Spatrick   Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
2517061da546Spatrick 
2518061da546Spatrick   // Ensure we have a process.
2519*be691f3bSpatrick   if (!m_current_process ||
2520*be691f3bSpatrick       (m_current_process->GetID() == LLDB_INVALID_PROCESS_ID)) {
2521061da546Spatrick     LLDB_LOGF(
2522061da546Spatrick         log,
2523061da546Spatrick         "GDBRemoteCommunicationServerLLGS::%s failed, no process available",
2524061da546Spatrick         __FUNCTION__);
2525061da546Spatrick     return SendErrorResponse(0x15);
2526061da546Spatrick   }
2527061da546Spatrick 
2528061da546Spatrick   // Parse out the memory address.
2529061da546Spatrick   packet.SetFilePos(strlen("qMemoryRegionInfo:"));
2530061da546Spatrick   if (packet.GetBytesLeft() < 1)
2531061da546Spatrick     return SendIllFormedResponse(packet, "Too short qMemoryRegionInfo: packet");
2532061da546Spatrick 
2533061da546Spatrick   // Read the address.  Punting on validation.
2534061da546Spatrick   const lldb::addr_t read_addr = packet.GetHexMaxU64(false, 0);
2535061da546Spatrick 
2536061da546Spatrick   StreamGDBRemote response;
2537061da546Spatrick 
2538061da546Spatrick   // Get the memory region info for the target address.
2539061da546Spatrick   MemoryRegionInfo region_info;
2540061da546Spatrick   const Status error =
2541*be691f3bSpatrick       m_current_process->GetMemoryRegionInfo(read_addr, region_info);
2542061da546Spatrick   if (error.Fail()) {
2543061da546Spatrick     // Return the error message.
2544061da546Spatrick 
2545061da546Spatrick     response.PutCString("error:");
2546061da546Spatrick     response.PutStringAsRawHex8(error.AsCString());
2547061da546Spatrick     response.PutChar(';');
2548061da546Spatrick   } else {
2549061da546Spatrick     // Range start and size.
2550061da546Spatrick     response.Printf("start:%" PRIx64 ";size:%" PRIx64 ";",
2551061da546Spatrick                     region_info.GetRange().GetRangeBase(),
2552061da546Spatrick                     region_info.GetRange().GetByteSize());
2553061da546Spatrick 
2554061da546Spatrick     // Permissions.
2555061da546Spatrick     if (region_info.GetReadable() || region_info.GetWritable() ||
2556061da546Spatrick         region_info.GetExecutable()) {
2557061da546Spatrick       // Write permissions info.
2558061da546Spatrick       response.PutCString("permissions:");
2559061da546Spatrick 
2560061da546Spatrick       if (region_info.GetReadable())
2561061da546Spatrick         response.PutChar('r');
2562061da546Spatrick       if (region_info.GetWritable())
2563061da546Spatrick         response.PutChar('w');
2564061da546Spatrick       if (region_info.GetExecutable())
2565061da546Spatrick         response.PutChar('x');
2566061da546Spatrick 
2567061da546Spatrick       response.PutChar(';');
2568061da546Spatrick     }
2569061da546Spatrick 
2570*be691f3bSpatrick     // Flags
2571*be691f3bSpatrick     MemoryRegionInfo::OptionalBool memory_tagged =
2572*be691f3bSpatrick         region_info.GetMemoryTagged();
2573*be691f3bSpatrick     if (memory_tagged != MemoryRegionInfo::eDontKnow) {
2574*be691f3bSpatrick       response.PutCString("flags:");
2575*be691f3bSpatrick       if (memory_tagged == MemoryRegionInfo::eYes) {
2576*be691f3bSpatrick         response.PutCString("mt");
2577*be691f3bSpatrick       }
2578*be691f3bSpatrick       response.PutChar(';');
2579*be691f3bSpatrick     }
2580*be691f3bSpatrick 
2581061da546Spatrick     // Name
2582061da546Spatrick     ConstString name = region_info.GetName();
2583061da546Spatrick     if (name) {
2584061da546Spatrick       response.PutCString("name:");
2585dda28197Spatrick       response.PutStringAsRawHex8(name.GetStringRef());
2586061da546Spatrick       response.PutChar(';');
2587061da546Spatrick     }
2588061da546Spatrick   }
2589061da546Spatrick 
2590061da546Spatrick   return SendPacketNoLock(response.GetString());
2591061da546Spatrick }
2592061da546Spatrick 
2593061da546Spatrick GDBRemoteCommunication::PacketResult
2594061da546Spatrick GDBRemoteCommunicationServerLLGS::Handle_Z(StringExtractorGDBRemote &packet) {
2595061da546Spatrick   // Ensure we have a process.
2596*be691f3bSpatrick   if (!m_current_process ||
2597*be691f3bSpatrick       (m_current_process->GetID() == LLDB_INVALID_PROCESS_ID)) {
2598061da546Spatrick     Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
2599061da546Spatrick     LLDB_LOG(log, "failed, no process available");
2600061da546Spatrick     return SendErrorResponse(0x15);
2601061da546Spatrick   }
2602061da546Spatrick 
2603061da546Spatrick   // Parse out software or hardware breakpoint or watchpoint requested.
2604061da546Spatrick   packet.SetFilePos(strlen("Z"));
2605061da546Spatrick   if (packet.GetBytesLeft() < 1)
2606061da546Spatrick     return SendIllFormedResponse(
2607061da546Spatrick         packet, "Too short Z packet, missing software/hardware specifier");
2608061da546Spatrick 
2609061da546Spatrick   bool want_breakpoint = true;
2610061da546Spatrick   bool want_hardware = false;
2611061da546Spatrick   uint32_t watch_flags = 0;
2612061da546Spatrick 
2613061da546Spatrick   const GDBStoppointType stoppoint_type =
2614061da546Spatrick       GDBStoppointType(packet.GetS32(eStoppointInvalid));
2615061da546Spatrick   switch (stoppoint_type) {
2616061da546Spatrick   case eBreakpointSoftware:
2617061da546Spatrick     want_hardware = false;
2618061da546Spatrick     want_breakpoint = true;
2619061da546Spatrick     break;
2620061da546Spatrick   case eBreakpointHardware:
2621061da546Spatrick     want_hardware = true;
2622061da546Spatrick     want_breakpoint = true;
2623061da546Spatrick     break;
2624061da546Spatrick   case eWatchpointWrite:
2625061da546Spatrick     watch_flags = 1;
2626061da546Spatrick     want_hardware = true;
2627061da546Spatrick     want_breakpoint = false;
2628061da546Spatrick     break;
2629061da546Spatrick   case eWatchpointRead:
2630061da546Spatrick     watch_flags = 2;
2631061da546Spatrick     want_hardware = true;
2632061da546Spatrick     want_breakpoint = false;
2633061da546Spatrick     break;
2634061da546Spatrick   case eWatchpointReadWrite:
2635061da546Spatrick     watch_flags = 3;
2636061da546Spatrick     want_hardware = true;
2637061da546Spatrick     want_breakpoint = false;
2638061da546Spatrick     break;
2639061da546Spatrick   case eStoppointInvalid:
2640061da546Spatrick     return SendIllFormedResponse(
2641061da546Spatrick         packet, "Z packet had invalid software/hardware specifier");
2642061da546Spatrick   }
2643061da546Spatrick 
2644061da546Spatrick   if ((packet.GetBytesLeft() < 1) || packet.GetChar() != ',')
2645061da546Spatrick     return SendIllFormedResponse(
2646061da546Spatrick         packet, "Malformed Z packet, expecting comma after stoppoint type");
2647061da546Spatrick 
2648061da546Spatrick   // Parse out the stoppoint address.
2649061da546Spatrick   if (packet.GetBytesLeft() < 1)
2650061da546Spatrick     return SendIllFormedResponse(packet, "Too short Z packet, missing address");
2651061da546Spatrick   const lldb::addr_t addr = packet.GetHexMaxU64(false, 0);
2652061da546Spatrick 
2653061da546Spatrick   if ((packet.GetBytesLeft() < 1) || packet.GetChar() != ',')
2654061da546Spatrick     return SendIllFormedResponse(
2655061da546Spatrick         packet, "Malformed Z packet, expecting comma after address");
2656061da546Spatrick 
2657061da546Spatrick   // Parse out the stoppoint size (i.e. size hint for opcode size).
2658061da546Spatrick   const uint32_t size =
2659061da546Spatrick       packet.GetHexMaxU32(false, std::numeric_limits<uint32_t>::max());
2660061da546Spatrick   if (size == std::numeric_limits<uint32_t>::max())
2661061da546Spatrick     return SendIllFormedResponse(
2662061da546Spatrick         packet, "Malformed Z packet, failed to parse size argument");
2663061da546Spatrick 
2664061da546Spatrick   if (want_breakpoint) {
2665061da546Spatrick     // Try to set the breakpoint.
2666061da546Spatrick     const Status error =
2667*be691f3bSpatrick         m_current_process->SetBreakpoint(addr, size, want_hardware);
2668061da546Spatrick     if (error.Success())
2669061da546Spatrick       return SendOKResponse();
2670061da546Spatrick     Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_BREAKPOINTS));
2671061da546Spatrick     LLDB_LOG(log, "pid {0} failed to set breakpoint: {1}",
2672*be691f3bSpatrick              m_current_process->GetID(), error);
2673061da546Spatrick     return SendErrorResponse(0x09);
2674061da546Spatrick   } else {
2675061da546Spatrick     // Try to set the watchpoint.
2676*be691f3bSpatrick     const Status error = m_current_process->SetWatchpoint(
2677061da546Spatrick         addr, size, watch_flags, want_hardware);
2678061da546Spatrick     if (error.Success())
2679061da546Spatrick       return SendOKResponse();
2680061da546Spatrick     Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_WATCHPOINTS));
2681061da546Spatrick     LLDB_LOG(log, "pid {0} failed to set watchpoint: {1}",
2682*be691f3bSpatrick              m_current_process->GetID(), error);
2683061da546Spatrick     return SendErrorResponse(0x09);
2684061da546Spatrick   }
2685061da546Spatrick }
2686061da546Spatrick 
2687061da546Spatrick GDBRemoteCommunication::PacketResult
2688061da546Spatrick GDBRemoteCommunicationServerLLGS::Handle_z(StringExtractorGDBRemote &packet) {
2689061da546Spatrick   // Ensure we have a process.
2690*be691f3bSpatrick   if (!m_current_process ||
2691*be691f3bSpatrick       (m_current_process->GetID() == LLDB_INVALID_PROCESS_ID)) {
2692061da546Spatrick     Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
2693061da546Spatrick     LLDB_LOG(log, "failed, no process available");
2694061da546Spatrick     return SendErrorResponse(0x15);
2695061da546Spatrick   }
2696061da546Spatrick 
2697061da546Spatrick   // Parse out software or hardware breakpoint or watchpoint requested.
2698061da546Spatrick   packet.SetFilePos(strlen("z"));
2699061da546Spatrick   if (packet.GetBytesLeft() < 1)
2700061da546Spatrick     return SendIllFormedResponse(
2701061da546Spatrick         packet, "Too short z packet, missing software/hardware specifier");
2702061da546Spatrick 
2703061da546Spatrick   bool want_breakpoint = true;
2704061da546Spatrick   bool want_hardware = false;
2705061da546Spatrick 
2706061da546Spatrick   const GDBStoppointType stoppoint_type =
2707061da546Spatrick       GDBStoppointType(packet.GetS32(eStoppointInvalid));
2708061da546Spatrick   switch (stoppoint_type) {
2709061da546Spatrick   case eBreakpointHardware:
2710061da546Spatrick     want_breakpoint = true;
2711061da546Spatrick     want_hardware = true;
2712061da546Spatrick     break;
2713061da546Spatrick   case eBreakpointSoftware:
2714061da546Spatrick     want_breakpoint = true;
2715061da546Spatrick     break;
2716061da546Spatrick   case eWatchpointWrite:
2717061da546Spatrick     want_breakpoint = false;
2718061da546Spatrick     break;
2719061da546Spatrick   case eWatchpointRead:
2720061da546Spatrick     want_breakpoint = false;
2721061da546Spatrick     break;
2722061da546Spatrick   case eWatchpointReadWrite:
2723061da546Spatrick     want_breakpoint = false;
2724061da546Spatrick     break;
2725061da546Spatrick   default:
2726061da546Spatrick     return SendIllFormedResponse(
2727061da546Spatrick         packet, "z packet had invalid software/hardware specifier");
2728061da546Spatrick   }
2729061da546Spatrick 
2730061da546Spatrick   if ((packet.GetBytesLeft() < 1) || packet.GetChar() != ',')
2731061da546Spatrick     return SendIllFormedResponse(
2732061da546Spatrick         packet, "Malformed z packet, expecting comma after stoppoint type");
2733061da546Spatrick 
2734061da546Spatrick   // Parse out the stoppoint address.
2735061da546Spatrick   if (packet.GetBytesLeft() < 1)
2736061da546Spatrick     return SendIllFormedResponse(packet, "Too short z packet, missing address");
2737061da546Spatrick   const lldb::addr_t addr = packet.GetHexMaxU64(false, 0);
2738061da546Spatrick 
2739061da546Spatrick   if ((packet.GetBytesLeft() < 1) || packet.GetChar() != ',')
2740061da546Spatrick     return SendIllFormedResponse(
2741061da546Spatrick         packet, "Malformed z packet, expecting comma after address");
2742061da546Spatrick 
2743061da546Spatrick   /*
2744061da546Spatrick   // Parse out the stoppoint size (i.e. size hint for opcode size).
2745061da546Spatrick   const uint32_t size = packet.GetHexMaxU32 (false,
2746061da546Spatrick   std::numeric_limits<uint32_t>::max ());
2747061da546Spatrick   if (size == std::numeric_limits<uint32_t>::max ())
2748061da546Spatrick       return SendIllFormedResponse(packet, "Malformed z packet, failed to parse
2749061da546Spatrick   size argument");
2750061da546Spatrick   */
2751061da546Spatrick 
2752061da546Spatrick   if (want_breakpoint) {
2753061da546Spatrick     // Try to clear the breakpoint.
2754061da546Spatrick     const Status error =
2755*be691f3bSpatrick         m_current_process->RemoveBreakpoint(addr, want_hardware);
2756061da546Spatrick     if (error.Success())
2757061da546Spatrick       return SendOKResponse();
2758061da546Spatrick     Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_BREAKPOINTS));
2759061da546Spatrick     LLDB_LOG(log, "pid {0} failed to remove breakpoint: {1}",
2760*be691f3bSpatrick              m_current_process->GetID(), error);
2761061da546Spatrick     return SendErrorResponse(0x09);
2762061da546Spatrick   } else {
2763061da546Spatrick     // Try to clear the watchpoint.
2764*be691f3bSpatrick     const Status error = m_current_process->RemoveWatchpoint(addr);
2765061da546Spatrick     if (error.Success())
2766061da546Spatrick       return SendOKResponse();
2767061da546Spatrick     Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_WATCHPOINTS));
2768061da546Spatrick     LLDB_LOG(log, "pid {0} failed to remove watchpoint: {1}",
2769*be691f3bSpatrick              m_current_process->GetID(), error);
2770061da546Spatrick     return SendErrorResponse(0x09);
2771061da546Spatrick   }
2772061da546Spatrick }
2773061da546Spatrick 
2774061da546Spatrick GDBRemoteCommunication::PacketResult
2775061da546Spatrick GDBRemoteCommunicationServerLLGS::Handle_s(StringExtractorGDBRemote &packet) {
2776061da546Spatrick   Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS | LIBLLDB_LOG_THREAD));
2777061da546Spatrick 
2778061da546Spatrick   // Ensure we have a process.
2779*be691f3bSpatrick   if (!m_continue_process ||
2780*be691f3bSpatrick       (m_continue_process->GetID() == LLDB_INVALID_PROCESS_ID)) {
2781061da546Spatrick     LLDB_LOGF(
2782061da546Spatrick         log,
2783061da546Spatrick         "GDBRemoteCommunicationServerLLGS::%s failed, no process available",
2784061da546Spatrick         __FUNCTION__);
2785061da546Spatrick     return SendErrorResponse(0x32);
2786061da546Spatrick   }
2787061da546Spatrick 
2788061da546Spatrick   // We first try to use a continue thread id.  If any one or any all set, use
2789061da546Spatrick   // the current thread. Bail out if we don't have a thread id.
2790061da546Spatrick   lldb::tid_t tid = GetContinueThreadID();
2791061da546Spatrick   if (tid == 0 || tid == LLDB_INVALID_THREAD_ID)
2792061da546Spatrick     tid = GetCurrentThreadID();
2793061da546Spatrick   if (tid == LLDB_INVALID_THREAD_ID)
2794061da546Spatrick     return SendErrorResponse(0x33);
2795061da546Spatrick 
2796061da546Spatrick   // Double check that we have such a thread.
2797061da546Spatrick   // TODO investigate: on MacOSX we might need to do an UpdateThreads () here.
2798*be691f3bSpatrick   NativeThreadProtocol *thread = m_continue_process->GetThreadByID(tid);
2799061da546Spatrick   if (!thread)
2800061da546Spatrick     return SendErrorResponse(0x33);
2801061da546Spatrick 
2802061da546Spatrick   // Create the step action for the given thread.
2803061da546Spatrick   ResumeAction action = {tid, eStateStepping, LLDB_INVALID_SIGNAL_NUMBER};
2804061da546Spatrick 
2805061da546Spatrick   // Setup the actions list.
2806061da546Spatrick   ResumeActionList actions;
2807061da546Spatrick   actions.Append(action);
2808061da546Spatrick 
2809061da546Spatrick   // All other threads stop while we're single stepping a thread.
2810061da546Spatrick   actions.SetDefaultThreadActionIfNeeded(eStateStopped, 0);
2811*be691f3bSpatrick   Status error = m_continue_process->Resume(actions);
2812061da546Spatrick   if (error.Fail()) {
2813061da546Spatrick     LLDB_LOGF(log,
2814061da546Spatrick               "GDBRemoteCommunicationServerLLGS::%s pid %" PRIu64
2815061da546Spatrick               " tid %" PRIu64 " Resume() failed with error: %s",
2816*be691f3bSpatrick               __FUNCTION__, m_continue_process->GetID(), tid,
2817061da546Spatrick               error.AsCString());
2818061da546Spatrick     return SendErrorResponse(0x49);
2819061da546Spatrick   }
2820061da546Spatrick 
2821061da546Spatrick   // No response here - the stop or exit will come from the resulting action.
2822061da546Spatrick   return PacketResult::Success;
2823061da546Spatrick }
2824061da546Spatrick 
2825061da546Spatrick llvm::Expected<std::unique_ptr<llvm::MemoryBuffer>>
2826dda28197Spatrick GDBRemoteCommunicationServerLLGS::BuildTargetXml() {
2827dda28197Spatrick   // Ensure we have a thread.
2828*be691f3bSpatrick   NativeThreadProtocol *thread = m_current_process->GetThreadAtIndex(0);
2829dda28197Spatrick   if (!thread)
2830dda28197Spatrick     return llvm::createStringError(llvm::inconvertibleErrorCode(),
2831dda28197Spatrick                                    "No thread available");
2832dda28197Spatrick 
2833dda28197Spatrick   Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS | LIBLLDB_LOG_THREAD));
2834dda28197Spatrick   // Get the register context for the first thread.
2835dda28197Spatrick   NativeRegisterContext &reg_context = thread->GetRegisterContext();
2836dda28197Spatrick 
2837dda28197Spatrick   StreamString response;
2838dda28197Spatrick 
2839dda28197Spatrick   response.Printf("<?xml version=\"1.0\"?>");
2840dda28197Spatrick   response.Printf("<target version=\"1.0\">");
2841dda28197Spatrick 
2842dda28197Spatrick   response.Printf("<architecture>%s</architecture>",
2843*be691f3bSpatrick                   m_current_process->GetArchitecture()
2844dda28197Spatrick                       .GetTriple()
2845dda28197Spatrick                       .getArchName()
2846dda28197Spatrick                       .str()
2847dda28197Spatrick                       .c_str());
2848dda28197Spatrick 
2849dda28197Spatrick   response.Printf("<feature>");
2850dda28197Spatrick 
2851dda28197Spatrick   const int registers_count = reg_context.GetUserRegisterCount();
2852dda28197Spatrick   for (int reg_index = 0; reg_index < registers_count; reg_index++) {
2853dda28197Spatrick     const RegisterInfo *reg_info =
2854dda28197Spatrick         reg_context.GetRegisterInfoAtIndex(reg_index);
2855dda28197Spatrick 
2856dda28197Spatrick     if (!reg_info) {
2857dda28197Spatrick       LLDB_LOGF(log,
2858dda28197Spatrick                 "%s failed to get register info for register index %" PRIu32,
2859dda28197Spatrick                 "target.xml", reg_index);
2860dda28197Spatrick       continue;
2861dda28197Spatrick     }
2862dda28197Spatrick 
2863*be691f3bSpatrick     response.Printf("<reg name=\"%s\" bitsize=\"%" PRIu32 "\" regnum=\"%d\" ",
2864*be691f3bSpatrick                     reg_info->name, reg_info->byte_size * 8, reg_index);
2865*be691f3bSpatrick 
2866*be691f3bSpatrick     if (!reg_context.RegisterOffsetIsDynamic())
2867*be691f3bSpatrick       response.Printf("offset=\"%" PRIu32 "\" ", reg_info->byte_offset);
2868dda28197Spatrick 
2869dda28197Spatrick     if (reg_info->alt_name && reg_info->alt_name[0])
2870dda28197Spatrick       response.Printf("altname=\"%s\" ", reg_info->alt_name);
2871dda28197Spatrick 
2872dda28197Spatrick     llvm::StringRef encoding = GetEncodingNameOrEmpty(*reg_info);
2873dda28197Spatrick     if (!encoding.empty())
2874dda28197Spatrick       response << "encoding=\"" << encoding << "\" ";
2875dda28197Spatrick 
2876dda28197Spatrick     llvm::StringRef format = GetFormatNameOrEmpty(*reg_info);
2877dda28197Spatrick     if (!format.empty())
2878dda28197Spatrick       response << "format=\"" << format << "\" ";
2879dda28197Spatrick 
2880dda28197Spatrick     const char *const register_set_name =
2881dda28197Spatrick         reg_context.GetRegisterSetNameForRegisterAtIndex(reg_index);
2882dda28197Spatrick     if (register_set_name)
2883dda28197Spatrick       response << "group=\"" << register_set_name << "\" ";
2884dda28197Spatrick 
2885dda28197Spatrick     if (reg_info->kinds[RegisterKind::eRegisterKindEHFrame] !=
2886dda28197Spatrick         LLDB_INVALID_REGNUM)
2887dda28197Spatrick       response.Printf("ehframe_regnum=\"%" PRIu32 "\" ",
2888dda28197Spatrick                       reg_info->kinds[RegisterKind::eRegisterKindEHFrame]);
2889dda28197Spatrick 
2890dda28197Spatrick     if (reg_info->kinds[RegisterKind::eRegisterKindDWARF] !=
2891dda28197Spatrick         LLDB_INVALID_REGNUM)
2892dda28197Spatrick       response.Printf("dwarf_regnum=\"%" PRIu32 "\" ",
2893dda28197Spatrick                       reg_info->kinds[RegisterKind::eRegisterKindDWARF]);
2894dda28197Spatrick 
2895dda28197Spatrick     llvm::StringRef kind_generic = GetKindGenericOrEmpty(*reg_info);
2896dda28197Spatrick     if (!kind_generic.empty())
2897dda28197Spatrick       response << "generic=\"" << kind_generic << "\" ";
2898dda28197Spatrick 
2899dda28197Spatrick     if (reg_info->value_regs &&
2900dda28197Spatrick         reg_info->value_regs[0] != LLDB_INVALID_REGNUM) {
2901dda28197Spatrick       response.PutCString("value_regnums=\"");
2902dda28197Spatrick       CollectRegNums(reg_info->value_regs, response, false);
2903dda28197Spatrick       response.Printf("\" ");
2904dda28197Spatrick     }
2905dda28197Spatrick 
2906dda28197Spatrick     if (reg_info->invalidate_regs && reg_info->invalidate_regs[0]) {
2907dda28197Spatrick       response.PutCString("invalidate_regnums=\"");
2908dda28197Spatrick       CollectRegNums(reg_info->invalidate_regs, response, false);
2909dda28197Spatrick       response.Printf("\" ");
2910dda28197Spatrick     }
2911dda28197Spatrick 
2912dda28197Spatrick     if (reg_info->dynamic_size_dwarf_expr_bytes) {
2913dda28197Spatrick       const size_t dwarf_opcode_len = reg_info->dynamic_size_dwarf_len;
2914dda28197Spatrick       response.PutCString("dynamic_size_dwarf_expr_bytes=\"");
2915dda28197Spatrick       for (uint32_t i = 0; i < dwarf_opcode_len; ++i)
2916dda28197Spatrick         response.PutHex8(reg_info->dynamic_size_dwarf_expr_bytes[i]);
2917dda28197Spatrick       response.Printf("\" ");
2918dda28197Spatrick     }
2919dda28197Spatrick 
2920dda28197Spatrick     response.Printf("/>");
2921dda28197Spatrick   }
2922dda28197Spatrick 
2923dda28197Spatrick   response.Printf("</feature>");
2924dda28197Spatrick   response.Printf("</target>");
2925dda28197Spatrick   return MemoryBuffer::getMemBufferCopy(response.GetString(), "target.xml");
2926dda28197Spatrick }
2927dda28197Spatrick 
2928dda28197Spatrick llvm::Expected<std::unique_ptr<llvm::MemoryBuffer>>
2929061da546Spatrick GDBRemoteCommunicationServerLLGS::ReadXferObject(llvm::StringRef object,
2930061da546Spatrick                                                  llvm::StringRef annex) {
2931061da546Spatrick   // Make sure we have a valid process.
2932*be691f3bSpatrick   if (!m_current_process ||
2933*be691f3bSpatrick       (m_current_process->GetID() == LLDB_INVALID_PROCESS_ID)) {
2934061da546Spatrick     return llvm::createStringError(llvm::inconvertibleErrorCode(),
2935061da546Spatrick                                    "No process available");
2936061da546Spatrick   }
2937061da546Spatrick 
2938dda28197Spatrick   if (object == "auxv") {
2939061da546Spatrick     // Grab the auxv data.
2940*be691f3bSpatrick     auto buffer_or_error = m_current_process->GetAuxvData();
2941061da546Spatrick     if (!buffer_or_error)
2942061da546Spatrick       return llvm::errorCodeToError(buffer_or_error.getError());
2943061da546Spatrick     return std::move(*buffer_or_error);
2944061da546Spatrick   }
2945061da546Spatrick 
2946061da546Spatrick   if (object == "libraries-svr4") {
2947*be691f3bSpatrick     auto library_list = m_current_process->GetLoadedSVR4Libraries();
2948061da546Spatrick     if (!library_list)
2949061da546Spatrick       return library_list.takeError();
2950061da546Spatrick 
2951061da546Spatrick     StreamString response;
2952061da546Spatrick     response.Printf("<library-list-svr4 version=\"1.0\">");
2953061da546Spatrick     for (auto const &library : *library_list) {
2954061da546Spatrick       response.Printf("<library name=\"%s\" ",
2955061da546Spatrick                       XMLEncodeAttributeValue(library.name.c_str()).c_str());
2956061da546Spatrick       response.Printf("lm=\"0x%" PRIx64 "\" ", library.link_map);
2957061da546Spatrick       response.Printf("l_addr=\"0x%" PRIx64 "\" ", library.base_addr);
2958061da546Spatrick       response.Printf("l_ld=\"0x%" PRIx64 "\" />", library.ld_addr);
2959061da546Spatrick     }
2960061da546Spatrick     response.Printf("</library-list-svr4>");
2961061da546Spatrick     return MemoryBuffer::getMemBufferCopy(response.GetString(), __FUNCTION__);
2962061da546Spatrick   }
2963061da546Spatrick 
2964dda28197Spatrick   if (object == "features" && annex == "target.xml")
2965dda28197Spatrick     return BuildTargetXml();
2966dda28197Spatrick 
2967*be691f3bSpatrick   return llvm::make_error<UnimplementedError>();
2968061da546Spatrick }
2969061da546Spatrick 
2970061da546Spatrick GDBRemoteCommunication::PacketResult
2971061da546Spatrick GDBRemoteCommunicationServerLLGS::Handle_qXfer(
2972061da546Spatrick     StringExtractorGDBRemote &packet) {
2973061da546Spatrick   SmallVector<StringRef, 5> fields;
2974061da546Spatrick   // The packet format is "qXfer:<object>:<action>:<annex>:offset,length"
2975061da546Spatrick   StringRef(packet.GetStringRef()).split(fields, ':', 4);
2976061da546Spatrick   if (fields.size() != 5)
2977061da546Spatrick     return SendIllFormedResponse(packet, "malformed qXfer packet");
2978061da546Spatrick   StringRef &xfer_object = fields[1];
2979061da546Spatrick   StringRef &xfer_action = fields[2];
2980061da546Spatrick   StringRef &xfer_annex = fields[3];
2981061da546Spatrick   StringExtractor offset_data(fields[4]);
2982061da546Spatrick   if (xfer_action != "read")
2983061da546Spatrick     return SendUnimplementedResponse("qXfer action not supported");
2984061da546Spatrick   // Parse offset.
2985061da546Spatrick   const uint64_t xfer_offset =
2986061da546Spatrick       offset_data.GetHexMaxU64(false, std::numeric_limits<uint64_t>::max());
2987061da546Spatrick   if (xfer_offset == std::numeric_limits<uint64_t>::max())
2988061da546Spatrick     return SendIllFormedResponse(packet, "qXfer packet missing offset");
2989061da546Spatrick   // Parse out comma.
2990061da546Spatrick   if (offset_data.GetChar() != ',')
2991061da546Spatrick     return SendIllFormedResponse(packet,
2992061da546Spatrick                                  "qXfer packet missing comma after offset");
2993061da546Spatrick   // Parse out the length.
2994061da546Spatrick   const uint64_t xfer_length =
2995061da546Spatrick       offset_data.GetHexMaxU64(false, std::numeric_limits<uint64_t>::max());
2996061da546Spatrick   if (xfer_length == std::numeric_limits<uint64_t>::max())
2997061da546Spatrick     return SendIllFormedResponse(packet, "qXfer packet missing length");
2998061da546Spatrick 
2999061da546Spatrick   // Get a previously constructed buffer if it exists or create it now.
3000061da546Spatrick   std::string buffer_key = (xfer_object + xfer_action + xfer_annex).str();
3001061da546Spatrick   auto buffer_it = m_xfer_buffer_map.find(buffer_key);
3002061da546Spatrick   if (buffer_it == m_xfer_buffer_map.end()) {
3003061da546Spatrick     auto buffer_up = ReadXferObject(xfer_object, xfer_annex);
3004061da546Spatrick     if (!buffer_up)
3005061da546Spatrick       return SendErrorResponse(buffer_up.takeError());
3006061da546Spatrick     buffer_it = m_xfer_buffer_map
3007061da546Spatrick                     .insert(std::make_pair(buffer_key, std::move(*buffer_up)))
3008061da546Spatrick                     .first;
3009061da546Spatrick   }
3010061da546Spatrick 
3011061da546Spatrick   // Send back the response
3012061da546Spatrick   StreamGDBRemote response;
3013061da546Spatrick   bool done_with_buffer = false;
3014061da546Spatrick   llvm::StringRef buffer = buffer_it->second->getBuffer();
3015061da546Spatrick   if (xfer_offset >= buffer.size()) {
3016061da546Spatrick     // We have nothing left to send.  Mark the buffer as complete.
3017061da546Spatrick     response.PutChar('l');
3018061da546Spatrick     done_with_buffer = true;
3019061da546Spatrick   } else {
3020061da546Spatrick     // Figure out how many bytes are available starting at the given offset.
3021061da546Spatrick     buffer = buffer.drop_front(xfer_offset);
3022061da546Spatrick     // Mark the response type according to whether we're reading the remainder
3023061da546Spatrick     // of the data.
3024061da546Spatrick     if (xfer_length >= buffer.size()) {
3025061da546Spatrick       // There will be nothing left to read after this
3026061da546Spatrick       response.PutChar('l');
3027061da546Spatrick       done_with_buffer = true;
3028061da546Spatrick     } else {
3029061da546Spatrick       // There will still be bytes to read after this request.
3030061da546Spatrick       response.PutChar('m');
3031061da546Spatrick       buffer = buffer.take_front(xfer_length);
3032061da546Spatrick     }
3033061da546Spatrick     // Now write the data in encoded binary form.
3034061da546Spatrick     response.PutEscapedBytes(buffer.data(), buffer.size());
3035061da546Spatrick   }
3036061da546Spatrick 
3037061da546Spatrick   if (done_with_buffer)
3038061da546Spatrick     m_xfer_buffer_map.erase(buffer_it);
3039061da546Spatrick 
3040061da546Spatrick   return SendPacketNoLock(response.GetString());
3041061da546Spatrick }
3042061da546Spatrick 
3043061da546Spatrick GDBRemoteCommunication::PacketResult
3044061da546Spatrick GDBRemoteCommunicationServerLLGS::Handle_QSaveRegisterState(
3045061da546Spatrick     StringExtractorGDBRemote &packet) {
3046061da546Spatrick   Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_THREAD));
3047061da546Spatrick 
3048061da546Spatrick   // Move past packet name.
3049061da546Spatrick   packet.SetFilePos(strlen("QSaveRegisterState"));
3050061da546Spatrick 
3051061da546Spatrick   // Get the thread to use.
3052061da546Spatrick   NativeThreadProtocol *thread = GetThreadFromSuffix(packet);
3053061da546Spatrick   if (!thread) {
3054061da546Spatrick     if (m_thread_suffix_supported)
3055061da546Spatrick       return SendIllFormedResponse(
3056061da546Spatrick           packet, "No thread specified in QSaveRegisterState packet");
3057061da546Spatrick     else
3058061da546Spatrick       return SendIllFormedResponse(packet,
3059061da546Spatrick                                    "No thread was is set with the Hg packet");
3060061da546Spatrick   }
3061061da546Spatrick 
3062061da546Spatrick   // Grab the register context for the thread.
3063061da546Spatrick   NativeRegisterContext& reg_context = thread->GetRegisterContext();
3064061da546Spatrick 
3065061da546Spatrick   // Save registers to a buffer.
3066061da546Spatrick   DataBufferSP register_data_sp;
3067061da546Spatrick   Status error = reg_context.ReadAllRegisterValues(register_data_sp);
3068061da546Spatrick   if (error.Fail()) {
3069061da546Spatrick     LLDB_LOG(log, "pid {0} failed to save all register values: {1}",
3070*be691f3bSpatrick              m_current_process->GetID(), error);
3071061da546Spatrick     return SendErrorResponse(0x75);
3072061da546Spatrick   }
3073061da546Spatrick 
3074061da546Spatrick   // Allocate a new save id.
3075061da546Spatrick   const uint32_t save_id = GetNextSavedRegistersID();
3076061da546Spatrick   assert((m_saved_registers_map.find(save_id) == m_saved_registers_map.end()) &&
3077061da546Spatrick          "GetNextRegisterSaveID() returned an existing register save id");
3078061da546Spatrick 
3079061da546Spatrick   // Save the register data buffer under the save id.
3080061da546Spatrick   {
3081061da546Spatrick     std::lock_guard<std::mutex> guard(m_saved_registers_mutex);
3082061da546Spatrick     m_saved_registers_map[save_id] = register_data_sp;
3083061da546Spatrick   }
3084061da546Spatrick 
3085061da546Spatrick   // Write the response.
3086061da546Spatrick   StreamGDBRemote response;
3087061da546Spatrick   response.Printf("%" PRIu32, save_id);
3088061da546Spatrick   return SendPacketNoLock(response.GetString());
3089061da546Spatrick }
3090061da546Spatrick 
3091061da546Spatrick GDBRemoteCommunication::PacketResult
3092061da546Spatrick GDBRemoteCommunicationServerLLGS::Handle_QRestoreRegisterState(
3093061da546Spatrick     StringExtractorGDBRemote &packet) {
3094061da546Spatrick   Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_THREAD));
3095061da546Spatrick 
3096061da546Spatrick   // Parse out save id.
3097061da546Spatrick   packet.SetFilePos(strlen("QRestoreRegisterState:"));
3098061da546Spatrick   if (packet.GetBytesLeft() < 1)
3099061da546Spatrick     return SendIllFormedResponse(
3100061da546Spatrick         packet, "QRestoreRegisterState packet missing register save id");
3101061da546Spatrick 
3102061da546Spatrick   const uint32_t save_id = packet.GetU32(0);
3103061da546Spatrick   if (save_id == 0) {
3104061da546Spatrick     LLDB_LOG(log, "QRestoreRegisterState packet has malformed save id, "
3105061da546Spatrick                   "expecting decimal uint32_t");
3106061da546Spatrick     return SendErrorResponse(0x76);
3107061da546Spatrick   }
3108061da546Spatrick 
3109061da546Spatrick   // Get the thread to use.
3110061da546Spatrick   NativeThreadProtocol *thread = GetThreadFromSuffix(packet);
3111061da546Spatrick   if (!thread) {
3112061da546Spatrick     if (m_thread_suffix_supported)
3113061da546Spatrick       return SendIllFormedResponse(
3114061da546Spatrick           packet, "No thread specified in QRestoreRegisterState packet");
3115061da546Spatrick     else
3116061da546Spatrick       return SendIllFormedResponse(packet,
3117061da546Spatrick                                    "No thread was is set with the Hg packet");
3118061da546Spatrick   }
3119061da546Spatrick 
3120061da546Spatrick   // Grab the register context for the thread.
3121061da546Spatrick   NativeRegisterContext &reg_context = thread->GetRegisterContext();
3122061da546Spatrick 
3123061da546Spatrick   // Retrieve register state buffer, then remove from the list.
3124061da546Spatrick   DataBufferSP register_data_sp;
3125061da546Spatrick   {
3126061da546Spatrick     std::lock_guard<std::mutex> guard(m_saved_registers_mutex);
3127061da546Spatrick 
3128061da546Spatrick     // Find the register set buffer for the given save id.
3129061da546Spatrick     auto it = m_saved_registers_map.find(save_id);
3130061da546Spatrick     if (it == m_saved_registers_map.end()) {
3131061da546Spatrick       LLDB_LOG(log,
3132061da546Spatrick                "pid {0} does not have a register set save buffer for id {1}",
3133*be691f3bSpatrick                m_current_process->GetID(), save_id);
3134061da546Spatrick       return SendErrorResponse(0x77);
3135061da546Spatrick     }
3136061da546Spatrick     register_data_sp = it->second;
3137061da546Spatrick 
3138061da546Spatrick     // Remove it from the map.
3139061da546Spatrick     m_saved_registers_map.erase(it);
3140061da546Spatrick   }
3141061da546Spatrick 
3142061da546Spatrick   Status error = reg_context.WriteAllRegisterValues(register_data_sp);
3143061da546Spatrick   if (error.Fail()) {
3144061da546Spatrick     LLDB_LOG(log, "pid {0} failed to restore all register values: {1}",
3145*be691f3bSpatrick              m_current_process->GetID(), error);
3146061da546Spatrick     return SendErrorResponse(0x77);
3147061da546Spatrick   }
3148061da546Spatrick 
3149061da546Spatrick   return SendOKResponse();
3150061da546Spatrick }
3151061da546Spatrick 
3152061da546Spatrick GDBRemoteCommunication::PacketResult
3153061da546Spatrick GDBRemoteCommunicationServerLLGS::Handle_vAttach(
3154061da546Spatrick     StringExtractorGDBRemote &packet) {
3155061da546Spatrick   Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
3156061da546Spatrick 
3157061da546Spatrick   // Consume the ';' after vAttach.
3158061da546Spatrick   packet.SetFilePos(strlen("vAttach"));
3159061da546Spatrick   if (!packet.GetBytesLeft() || packet.GetChar() != ';')
3160061da546Spatrick     return SendIllFormedResponse(packet, "vAttach missing expected ';'");
3161061da546Spatrick 
3162061da546Spatrick   // Grab the PID to which we will attach (assume hex encoding).
3163061da546Spatrick   lldb::pid_t pid = packet.GetU32(LLDB_INVALID_PROCESS_ID, 16);
3164061da546Spatrick   if (pid == LLDB_INVALID_PROCESS_ID)
3165061da546Spatrick     return SendIllFormedResponse(packet,
3166061da546Spatrick                                  "vAttach failed to parse the process id");
3167061da546Spatrick 
3168061da546Spatrick   // Attempt to attach.
3169061da546Spatrick   LLDB_LOGF(log,
3170061da546Spatrick             "GDBRemoteCommunicationServerLLGS::%s attempting to attach to "
3171061da546Spatrick             "pid %" PRIu64,
3172061da546Spatrick             __FUNCTION__, pid);
3173061da546Spatrick 
3174061da546Spatrick   Status error = AttachToProcess(pid);
3175061da546Spatrick 
3176061da546Spatrick   if (error.Fail()) {
3177061da546Spatrick     LLDB_LOGF(log,
3178061da546Spatrick               "GDBRemoteCommunicationServerLLGS::%s failed to attach to "
3179061da546Spatrick               "pid %" PRIu64 ": %s\n",
3180061da546Spatrick               __FUNCTION__, pid, error.AsCString());
3181061da546Spatrick     return SendErrorResponse(error);
3182061da546Spatrick   }
3183061da546Spatrick 
3184061da546Spatrick   // Notify we attached by sending a stop packet.
3185*be691f3bSpatrick   return SendStopReasonForState(m_current_process->GetState());
3186*be691f3bSpatrick }
3187*be691f3bSpatrick 
3188*be691f3bSpatrick GDBRemoteCommunication::PacketResult
3189*be691f3bSpatrick GDBRemoteCommunicationServerLLGS::Handle_vAttachWait(
3190*be691f3bSpatrick     StringExtractorGDBRemote &packet) {
3191*be691f3bSpatrick   Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
3192*be691f3bSpatrick 
3193*be691f3bSpatrick   // Consume the ';' after the identifier.
3194*be691f3bSpatrick   packet.SetFilePos(strlen("vAttachWait"));
3195*be691f3bSpatrick 
3196*be691f3bSpatrick   if (!packet.GetBytesLeft() || packet.GetChar() != ';')
3197*be691f3bSpatrick     return SendIllFormedResponse(packet, "vAttachWait missing expected ';'");
3198*be691f3bSpatrick 
3199*be691f3bSpatrick   // Allocate the buffer for the process name from vAttachWait.
3200*be691f3bSpatrick   std::string process_name;
3201*be691f3bSpatrick   if (!packet.GetHexByteString(process_name))
3202*be691f3bSpatrick     return SendIllFormedResponse(packet,
3203*be691f3bSpatrick                                  "vAttachWait failed to parse process name");
3204*be691f3bSpatrick 
3205*be691f3bSpatrick   LLDB_LOG(log, "attempting to attach to process named '{0}'", process_name);
3206*be691f3bSpatrick 
3207*be691f3bSpatrick   Status error = AttachWaitProcess(process_name, false);
3208*be691f3bSpatrick   if (error.Fail()) {
3209*be691f3bSpatrick     LLDB_LOG(log, "failed to attach to process named '{0}': {1}", process_name,
3210*be691f3bSpatrick              error);
3211*be691f3bSpatrick     return SendErrorResponse(error);
3212*be691f3bSpatrick   }
3213*be691f3bSpatrick 
3214*be691f3bSpatrick   // Notify we attached by sending a stop packet.
3215*be691f3bSpatrick   return SendStopReasonForState(m_current_process->GetState());
3216*be691f3bSpatrick }
3217*be691f3bSpatrick 
3218*be691f3bSpatrick GDBRemoteCommunication::PacketResult
3219*be691f3bSpatrick GDBRemoteCommunicationServerLLGS::Handle_qVAttachOrWaitSupported(
3220*be691f3bSpatrick     StringExtractorGDBRemote &packet) {
3221*be691f3bSpatrick   return SendOKResponse();
3222*be691f3bSpatrick }
3223*be691f3bSpatrick 
3224*be691f3bSpatrick GDBRemoteCommunication::PacketResult
3225*be691f3bSpatrick GDBRemoteCommunicationServerLLGS::Handle_vAttachOrWait(
3226*be691f3bSpatrick     StringExtractorGDBRemote &packet) {
3227*be691f3bSpatrick   Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
3228*be691f3bSpatrick 
3229*be691f3bSpatrick   // Consume the ';' after the identifier.
3230*be691f3bSpatrick   packet.SetFilePos(strlen("vAttachOrWait"));
3231*be691f3bSpatrick 
3232*be691f3bSpatrick   if (!packet.GetBytesLeft() || packet.GetChar() != ';')
3233*be691f3bSpatrick     return SendIllFormedResponse(packet, "vAttachOrWait missing expected ';'");
3234*be691f3bSpatrick 
3235*be691f3bSpatrick   // Allocate the buffer for the process name from vAttachWait.
3236*be691f3bSpatrick   std::string process_name;
3237*be691f3bSpatrick   if (!packet.GetHexByteString(process_name))
3238*be691f3bSpatrick     return SendIllFormedResponse(packet,
3239*be691f3bSpatrick                                  "vAttachOrWait failed to parse process name");
3240*be691f3bSpatrick 
3241*be691f3bSpatrick   LLDB_LOG(log, "attempting to attach to process named '{0}'", process_name);
3242*be691f3bSpatrick 
3243*be691f3bSpatrick   Status error = AttachWaitProcess(process_name, true);
3244*be691f3bSpatrick   if (error.Fail()) {
3245*be691f3bSpatrick     LLDB_LOG(log, "failed to attach to process named '{0}': {1}", process_name,
3246*be691f3bSpatrick              error);
3247*be691f3bSpatrick     return SendErrorResponse(error);
3248*be691f3bSpatrick   }
3249*be691f3bSpatrick 
3250*be691f3bSpatrick   // Notify we attached by sending a stop packet.
3251*be691f3bSpatrick   return SendStopReasonForState(m_current_process->GetState());
3252061da546Spatrick }
3253061da546Spatrick 
3254061da546Spatrick GDBRemoteCommunication::PacketResult
3255061da546Spatrick GDBRemoteCommunicationServerLLGS::Handle_D(StringExtractorGDBRemote &packet) {
3256061da546Spatrick   StopSTDIOForwarding();
3257061da546Spatrick 
3258061da546Spatrick   lldb::pid_t pid = LLDB_INVALID_PROCESS_ID;
3259061da546Spatrick 
3260061da546Spatrick   // Consume the ';' after D.
3261061da546Spatrick   packet.SetFilePos(1);
3262061da546Spatrick   if (packet.GetBytesLeft()) {
3263061da546Spatrick     if (packet.GetChar() != ';')
3264061da546Spatrick       return SendIllFormedResponse(packet, "D missing expected ';'");
3265061da546Spatrick 
3266061da546Spatrick     // Grab the PID from which we will detach (assume hex encoding).
3267061da546Spatrick     pid = packet.GetU32(LLDB_INVALID_PROCESS_ID, 16);
3268061da546Spatrick     if (pid == LLDB_INVALID_PROCESS_ID)
3269061da546Spatrick       return SendIllFormedResponse(packet, "D failed to parse the process id");
3270061da546Spatrick   }
3271061da546Spatrick 
3272*be691f3bSpatrick   // Detach forked children if their PID was specified *or* no PID was requested
3273*be691f3bSpatrick   // (i.e. detach-all packet).
3274*be691f3bSpatrick   llvm::Error detach_error = llvm::Error::success();
3275*be691f3bSpatrick   bool detached = false;
3276*be691f3bSpatrick   for (auto it = m_debugged_processes.begin();
3277*be691f3bSpatrick        it != m_debugged_processes.end();) {
3278*be691f3bSpatrick     if (pid == LLDB_INVALID_PROCESS_ID || pid == it->first) {
3279*be691f3bSpatrick       if (llvm::Error e = it->second->Detach().ToError())
3280*be691f3bSpatrick         detach_error = llvm::joinErrors(std::move(detach_error), std::move(e));
3281*be691f3bSpatrick       else {
3282*be691f3bSpatrick         if (it->second.get() == m_current_process)
3283*be691f3bSpatrick           m_current_process = nullptr;
3284*be691f3bSpatrick         if (it->second.get() == m_continue_process)
3285*be691f3bSpatrick           m_continue_process = nullptr;
3286*be691f3bSpatrick         it = m_debugged_processes.erase(it);
3287*be691f3bSpatrick         detached = true;
3288*be691f3bSpatrick         continue;
3289*be691f3bSpatrick       }
3290*be691f3bSpatrick     }
3291*be691f3bSpatrick     ++it;
3292061da546Spatrick   }
3293061da546Spatrick 
3294*be691f3bSpatrick   if (detach_error)
3295*be691f3bSpatrick     return SendErrorResponse(std::move(detach_error));
3296*be691f3bSpatrick   if (!detached)
3297*be691f3bSpatrick     return SendErrorResponse(Status("PID %" PRIu64 " not traced", pid));
3298061da546Spatrick   return SendOKResponse();
3299061da546Spatrick }
3300061da546Spatrick 
3301061da546Spatrick GDBRemoteCommunication::PacketResult
3302061da546Spatrick GDBRemoteCommunicationServerLLGS::Handle_qThreadStopInfo(
3303061da546Spatrick     StringExtractorGDBRemote &packet) {
3304061da546Spatrick   Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_THREAD));
3305061da546Spatrick 
3306061da546Spatrick   packet.SetFilePos(strlen("qThreadStopInfo"));
3307*be691f3bSpatrick   const lldb::tid_t tid = packet.GetHexMaxU64(false, LLDB_INVALID_THREAD_ID);
3308061da546Spatrick   if (tid == LLDB_INVALID_THREAD_ID) {
3309061da546Spatrick     LLDB_LOGF(log,
3310061da546Spatrick               "GDBRemoteCommunicationServerLLGS::%s failed, could not "
3311061da546Spatrick               "parse thread id from request \"%s\"",
3312061da546Spatrick               __FUNCTION__, packet.GetStringRef().data());
3313061da546Spatrick     return SendErrorResponse(0x15);
3314061da546Spatrick   }
3315061da546Spatrick   return SendStopReplyPacketForThread(tid);
3316061da546Spatrick }
3317061da546Spatrick 
3318061da546Spatrick GDBRemoteCommunication::PacketResult
3319061da546Spatrick GDBRemoteCommunicationServerLLGS::Handle_jThreadsInfo(
3320061da546Spatrick     StringExtractorGDBRemote &) {
3321061da546Spatrick   Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS | LIBLLDB_LOG_THREAD));
3322061da546Spatrick 
3323061da546Spatrick   // Ensure we have a debugged process.
3324*be691f3bSpatrick   if (!m_current_process ||
3325*be691f3bSpatrick       (m_current_process->GetID() == LLDB_INVALID_PROCESS_ID))
3326061da546Spatrick     return SendErrorResponse(50);
3327*be691f3bSpatrick   LLDB_LOG(log, "preparing packet for pid {0}", m_current_process->GetID());
3328061da546Spatrick 
3329061da546Spatrick   StreamString response;
3330061da546Spatrick   const bool threads_with_valid_stop_info_only = false;
3331*be691f3bSpatrick   llvm::Expected<json::Value> threads_info =
3332*be691f3bSpatrick       GetJSONThreadsInfo(*m_current_process, threads_with_valid_stop_info_only);
3333061da546Spatrick   if (!threads_info) {
3334061da546Spatrick     LLDB_LOG_ERROR(log, threads_info.takeError(),
3335061da546Spatrick                    "failed to prepare a packet for pid {1}: {0}",
3336*be691f3bSpatrick                    m_current_process->GetID());
3337061da546Spatrick     return SendErrorResponse(52);
3338061da546Spatrick   }
3339061da546Spatrick 
3340061da546Spatrick   response.AsRawOstream() << *threads_info;
3341061da546Spatrick   StreamGDBRemote escaped_response;
3342061da546Spatrick   escaped_response.PutEscapedBytes(response.GetData(), response.GetSize());
3343061da546Spatrick   return SendPacketNoLock(escaped_response.GetString());
3344061da546Spatrick }
3345061da546Spatrick 
3346061da546Spatrick GDBRemoteCommunication::PacketResult
3347061da546Spatrick GDBRemoteCommunicationServerLLGS::Handle_qWatchpointSupportInfo(
3348061da546Spatrick     StringExtractorGDBRemote &packet) {
3349061da546Spatrick   // Fail if we don't have a current process.
3350*be691f3bSpatrick   if (!m_current_process ||
3351*be691f3bSpatrick       m_current_process->GetID() == LLDB_INVALID_PROCESS_ID)
3352061da546Spatrick     return SendErrorResponse(68);
3353061da546Spatrick 
3354061da546Spatrick   packet.SetFilePos(strlen("qWatchpointSupportInfo"));
3355061da546Spatrick   if (packet.GetBytesLeft() == 0)
3356061da546Spatrick     return SendOKResponse();
3357061da546Spatrick   if (packet.GetChar() != ':')
3358061da546Spatrick     return SendErrorResponse(67);
3359061da546Spatrick 
3360*be691f3bSpatrick   auto hw_debug_cap = m_current_process->GetHardwareDebugSupportInfo();
3361061da546Spatrick 
3362061da546Spatrick   StreamGDBRemote response;
3363061da546Spatrick   if (hw_debug_cap == llvm::None)
3364061da546Spatrick     response.Printf("num:0;");
3365061da546Spatrick   else
3366061da546Spatrick     response.Printf("num:%d;", hw_debug_cap->second);
3367061da546Spatrick 
3368061da546Spatrick   return SendPacketNoLock(response.GetString());
3369061da546Spatrick }
3370061da546Spatrick 
3371061da546Spatrick GDBRemoteCommunication::PacketResult
3372061da546Spatrick GDBRemoteCommunicationServerLLGS::Handle_qFileLoadAddress(
3373061da546Spatrick     StringExtractorGDBRemote &packet) {
3374061da546Spatrick   // Fail if we don't have a current process.
3375*be691f3bSpatrick   if (!m_current_process ||
3376*be691f3bSpatrick       m_current_process->GetID() == LLDB_INVALID_PROCESS_ID)
3377061da546Spatrick     return SendErrorResponse(67);
3378061da546Spatrick 
3379061da546Spatrick   packet.SetFilePos(strlen("qFileLoadAddress:"));
3380061da546Spatrick   if (packet.GetBytesLeft() == 0)
3381061da546Spatrick     return SendErrorResponse(68);
3382061da546Spatrick 
3383061da546Spatrick   std::string file_name;
3384061da546Spatrick   packet.GetHexByteString(file_name);
3385061da546Spatrick 
3386061da546Spatrick   lldb::addr_t file_load_address = LLDB_INVALID_ADDRESS;
3387061da546Spatrick   Status error =
3388*be691f3bSpatrick       m_current_process->GetFileLoadAddress(file_name, file_load_address);
3389061da546Spatrick   if (error.Fail())
3390061da546Spatrick     return SendErrorResponse(69);
3391061da546Spatrick 
3392061da546Spatrick   if (file_load_address == LLDB_INVALID_ADDRESS)
3393061da546Spatrick     return SendErrorResponse(1); // File not loaded
3394061da546Spatrick 
3395061da546Spatrick   StreamGDBRemote response;
3396061da546Spatrick   response.PutHex64(file_load_address);
3397061da546Spatrick   return SendPacketNoLock(response.GetString());
3398061da546Spatrick }
3399061da546Spatrick 
3400061da546Spatrick GDBRemoteCommunication::PacketResult
3401061da546Spatrick GDBRemoteCommunicationServerLLGS::Handle_QPassSignals(
3402061da546Spatrick     StringExtractorGDBRemote &packet) {
3403061da546Spatrick   std::vector<int> signals;
3404061da546Spatrick   packet.SetFilePos(strlen("QPassSignals:"));
3405061da546Spatrick 
3406061da546Spatrick   // Read sequence of hex signal numbers divided by a semicolon and optionally
3407061da546Spatrick   // spaces.
3408061da546Spatrick   while (packet.GetBytesLeft() > 0) {
3409061da546Spatrick     int signal = packet.GetS32(-1, 16);
3410061da546Spatrick     if (signal < 0)
3411061da546Spatrick       return SendIllFormedResponse(packet, "Failed to parse signal number.");
3412061da546Spatrick     signals.push_back(signal);
3413061da546Spatrick 
3414061da546Spatrick     packet.SkipSpaces();
3415061da546Spatrick     char separator = packet.GetChar();
3416061da546Spatrick     if (separator == '\0')
3417061da546Spatrick       break; // End of string
3418061da546Spatrick     if (separator != ';')
3419061da546Spatrick       return SendIllFormedResponse(packet, "Invalid separator,"
3420061da546Spatrick                                             " expected semicolon.");
3421061da546Spatrick   }
3422061da546Spatrick 
3423061da546Spatrick   // Fail if we don't have a current process.
3424*be691f3bSpatrick   if (!m_current_process)
3425061da546Spatrick     return SendErrorResponse(68);
3426061da546Spatrick 
3427*be691f3bSpatrick   Status error = m_current_process->IgnoreSignals(signals);
3428061da546Spatrick   if (error.Fail())
3429061da546Spatrick     return SendErrorResponse(69);
3430061da546Spatrick 
3431061da546Spatrick   return SendOKResponse();
3432061da546Spatrick }
3433061da546Spatrick 
3434*be691f3bSpatrick GDBRemoteCommunication::PacketResult
3435*be691f3bSpatrick GDBRemoteCommunicationServerLLGS::Handle_qMemTags(
3436*be691f3bSpatrick     StringExtractorGDBRemote &packet) {
3437*be691f3bSpatrick   Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
3438*be691f3bSpatrick 
3439*be691f3bSpatrick   // Ensure we have a process.
3440*be691f3bSpatrick   if (!m_current_process ||
3441*be691f3bSpatrick       (m_current_process->GetID() == LLDB_INVALID_PROCESS_ID)) {
3442*be691f3bSpatrick     LLDB_LOGF(
3443*be691f3bSpatrick         log,
3444*be691f3bSpatrick         "GDBRemoteCommunicationServerLLGS::%s failed, no process available",
3445*be691f3bSpatrick         __FUNCTION__);
3446*be691f3bSpatrick     return SendErrorResponse(1);
3447*be691f3bSpatrick   }
3448*be691f3bSpatrick 
3449*be691f3bSpatrick   // We are expecting
3450*be691f3bSpatrick   // qMemTags:<hex address>,<hex length>:<hex type>
3451*be691f3bSpatrick 
3452*be691f3bSpatrick   // Address
3453*be691f3bSpatrick   packet.SetFilePos(strlen("qMemTags:"));
3454*be691f3bSpatrick   const char *current_char = packet.Peek();
3455*be691f3bSpatrick   if (!current_char || *current_char == ',')
3456*be691f3bSpatrick     return SendIllFormedResponse(packet, "Missing address in qMemTags packet");
3457*be691f3bSpatrick   const lldb::addr_t addr = packet.GetHexMaxU64(/*little_endian=*/false, 0);
3458*be691f3bSpatrick 
3459*be691f3bSpatrick   // Length
3460*be691f3bSpatrick   char previous_char = packet.GetChar();
3461*be691f3bSpatrick   current_char = packet.Peek();
3462*be691f3bSpatrick   // If we don't have a separator or the length field is empty
3463*be691f3bSpatrick   if (previous_char != ',' || (current_char && *current_char == ':'))
3464*be691f3bSpatrick     return SendIllFormedResponse(packet,
3465*be691f3bSpatrick                                  "Invalid addr,length pair in qMemTags packet");
3466*be691f3bSpatrick 
3467*be691f3bSpatrick   if (packet.GetBytesLeft() < 1)
3468*be691f3bSpatrick     return SendIllFormedResponse(
3469*be691f3bSpatrick         packet, "Too short qMemtags: packet (looking for length)");
3470*be691f3bSpatrick   const size_t length = packet.GetHexMaxU64(/*little_endian=*/false, 0);
3471*be691f3bSpatrick 
3472*be691f3bSpatrick   // Type
3473*be691f3bSpatrick   const char *invalid_type_err = "Invalid type field in qMemTags: packet";
3474*be691f3bSpatrick   if (packet.GetBytesLeft() < 1 || packet.GetChar() != ':')
3475*be691f3bSpatrick     return SendIllFormedResponse(packet, invalid_type_err);
3476*be691f3bSpatrick 
3477*be691f3bSpatrick   // Type is a signed integer but packed into the packet as its raw bytes.
3478*be691f3bSpatrick   // However, our GetU64 uses strtoull which allows +/-. We do not want this.
3479*be691f3bSpatrick   const char *first_type_char = packet.Peek();
3480*be691f3bSpatrick   if (first_type_char && (*first_type_char == '+' || *first_type_char == '-'))
3481*be691f3bSpatrick     return SendIllFormedResponse(packet, invalid_type_err);
3482*be691f3bSpatrick 
3483*be691f3bSpatrick   // Extract type as unsigned then cast to signed.
3484*be691f3bSpatrick   // Using a uint64_t here so that we have some value outside of the 32 bit
3485*be691f3bSpatrick   // range to use as the invalid return value.
3486*be691f3bSpatrick   uint64_t raw_type =
3487*be691f3bSpatrick       packet.GetU64(std::numeric_limits<uint64_t>::max(), /*base=*/16);
3488*be691f3bSpatrick 
3489*be691f3bSpatrick   if ( // Make sure the cast below would be valid
3490*be691f3bSpatrick       raw_type > std::numeric_limits<uint32_t>::max() ||
3491*be691f3bSpatrick       // To catch inputs like "123aardvark" that will parse but clearly aren't
3492*be691f3bSpatrick       // valid in this case.
3493*be691f3bSpatrick       packet.GetBytesLeft()) {
3494*be691f3bSpatrick     return SendIllFormedResponse(packet, invalid_type_err);
3495*be691f3bSpatrick   }
3496*be691f3bSpatrick 
3497*be691f3bSpatrick   // First narrow to 32 bits otherwise the copy into type would take
3498*be691f3bSpatrick   // the wrong 4 bytes on big endian.
3499*be691f3bSpatrick   uint32_t raw_type_32 = raw_type;
3500*be691f3bSpatrick   int32_t type = reinterpret_cast<int32_t &>(raw_type_32);
3501*be691f3bSpatrick 
3502*be691f3bSpatrick   StreamGDBRemote response;
3503*be691f3bSpatrick   std::vector<uint8_t> tags;
3504*be691f3bSpatrick   Status error = m_current_process->ReadMemoryTags(type, addr, length, tags);
3505*be691f3bSpatrick   if (error.Fail())
3506*be691f3bSpatrick     return SendErrorResponse(1);
3507*be691f3bSpatrick 
3508*be691f3bSpatrick   // This m is here in case we want to support multi part replies in the future.
3509*be691f3bSpatrick   // In the same manner as qfThreadInfo/qsThreadInfo.
3510*be691f3bSpatrick   response.PutChar('m');
3511*be691f3bSpatrick   response.PutBytesAsRawHex8(tags.data(), tags.size());
3512*be691f3bSpatrick   return SendPacketNoLock(response.GetString());
3513*be691f3bSpatrick }
3514*be691f3bSpatrick 
3515*be691f3bSpatrick GDBRemoteCommunication::PacketResult
3516*be691f3bSpatrick GDBRemoteCommunicationServerLLGS::Handle_QMemTags(
3517*be691f3bSpatrick     StringExtractorGDBRemote &packet) {
3518*be691f3bSpatrick   Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
3519*be691f3bSpatrick 
3520*be691f3bSpatrick   // Ensure we have a process.
3521*be691f3bSpatrick   if (!m_current_process ||
3522*be691f3bSpatrick       (m_current_process->GetID() == LLDB_INVALID_PROCESS_ID)) {
3523*be691f3bSpatrick     LLDB_LOGF(
3524*be691f3bSpatrick         log,
3525*be691f3bSpatrick         "GDBRemoteCommunicationServerLLGS::%s failed, no process available",
3526*be691f3bSpatrick         __FUNCTION__);
3527*be691f3bSpatrick     return SendErrorResponse(1);
3528*be691f3bSpatrick   }
3529*be691f3bSpatrick 
3530*be691f3bSpatrick   // We are expecting
3531*be691f3bSpatrick   // QMemTags:<hex address>,<hex length>:<hex type>:<tags as hex bytes>
3532*be691f3bSpatrick 
3533*be691f3bSpatrick   // Address
3534*be691f3bSpatrick   packet.SetFilePos(strlen("QMemTags:"));
3535*be691f3bSpatrick   const char *current_char = packet.Peek();
3536*be691f3bSpatrick   if (!current_char || *current_char == ',')
3537*be691f3bSpatrick     return SendIllFormedResponse(packet, "Missing address in QMemTags packet");
3538*be691f3bSpatrick   const lldb::addr_t addr = packet.GetHexMaxU64(/*little_endian=*/false, 0);
3539*be691f3bSpatrick 
3540*be691f3bSpatrick   // Length
3541*be691f3bSpatrick   char previous_char = packet.GetChar();
3542*be691f3bSpatrick   current_char = packet.Peek();
3543*be691f3bSpatrick   // If we don't have a separator or the length field is empty
3544*be691f3bSpatrick   if (previous_char != ',' || (current_char && *current_char == ':'))
3545*be691f3bSpatrick     return SendIllFormedResponse(packet,
3546*be691f3bSpatrick                                  "Invalid addr,length pair in QMemTags packet");
3547*be691f3bSpatrick 
3548*be691f3bSpatrick   if (packet.GetBytesLeft() < 1)
3549*be691f3bSpatrick     return SendIllFormedResponse(
3550*be691f3bSpatrick         packet, "Too short QMemtags: packet (looking for length)");
3551*be691f3bSpatrick   const size_t length = packet.GetHexMaxU64(/*little_endian=*/false, 0);
3552*be691f3bSpatrick 
3553*be691f3bSpatrick   // Type
3554*be691f3bSpatrick   const char *invalid_type_err = "Invalid type field in QMemTags: packet";
3555*be691f3bSpatrick   if (packet.GetBytesLeft() < 1 || packet.GetChar() != ':')
3556*be691f3bSpatrick     return SendIllFormedResponse(packet, invalid_type_err);
3557*be691f3bSpatrick 
3558*be691f3bSpatrick   // Our GetU64 uses strtoull which allows leading +/-, we don't want that.
3559*be691f3bSpatrick   const char *first_type_char = packet.Peek();
3560*be691f3bSpatrick   if (first_type_char && (*first_type_char == '+' || *first_type_char == '-'))
3561*be691f3bSpatrick     return SendIllFormedResponse(packet, invalid_type_err);
3562*be691f3bSpatrick 
3563*be691f3bSpatrick   // The type is a signed integer but is in the packet as its raw bytes.
3564*be691f3bSpatrick   // So parse first as unsigned then cast to signed later.
3565*be691f3bSpatrick   // We extract to 64 bit, even though we only expect 32, so that we've
3566*be691f3bSpatrick   // got some invalid value we can check for.
3567*be691f3bSpatrick   uint64_t raw_type =
3568*be691f3bSpatrick       packet.GetU64(std::numeric_limits<uint64_t>::max(), /*base=*/16);
3569*be691f3bSpatrick   if (raw_type > std::numeric_limits<uint32_t>::max())
3570*be691f3bSpatrick     return SendIllFormedResponse(packet, invalid_type_err);
3571*be691f3bSpatrick 
3572*be691f3bSpatrick   // First narrow to 32 bits. Otherwise the copy below would get the wrong
3573*be691f3bSpatrick   // 4 bytes on big endian.
3574*be691f3bSpatrick   uint32_t raw_type_32 = raw_type;
3575*be691f3bSpatrick   int32_t type = reinterpret_cast<int32_t &>(raw_type_32);
3576*be691f3bSpatrick 
3577*be691f3bSpatrick   // Tag data
3578*be691f3bSpatrick   if (packet.GetBytesLeft() < 1 || packet.GetChar() != ':')
3579*be691f3bSpatrick     return SendIllFormedResponse(packet,
3580*be691f3bSpatrick                                  "Missing tag data in QMemTags: packet");
3581*be691f3bSpatrick 
3582*be691f3bSpatrick   // Must be 2 chars per byte
3583*be691f3bSpatrick   const char *invalid_data_err = "Invalid tag data in QMemTags: packet";
3584*be691f3bSpatrick   if (packet.GetBytesLeft() % 2)
3585*be691f3bSpatrick     return SendIllFormedResponse(packet, invalid_data_err);
3586*be691f3bSpatrick 
3587*be691f3bSpatrick   // This is bytes here and is unpacked into target specific tags later
3588*be691f3bSpatrick   // We cannot assume that number of bytes == length here because the server
3589*be691f3bSpatrick   // can repeat tags to fill a given range.
3590*be691f3bSpatrick   std::vector<uint8_t> tag_data;
3591*be691f3bSpatrick   // Zero length writes will not have any tag data
3592*be691f3bSpatrick   // (but we pass them on because it will still check that tagging is enabled)
3593*be691f3bSpatrick   if (packet.GetBytesLeft()) {
3594*be691f3bSpatrick     size_t byte_count = packet.GetBytesLeft() / 2;
3595*be691f3bSpatrick     tag_data.resize(byte_count);
3596*be691f3bSpatrick     size_t converted_bytes = packet.GetHexBytes(tag_data, 0);
3597*be691f3bSpatrick     if (converted_bytes != byte_count) {
3598*be691f3bSpatrick       return SendIllFormedResponse(packet, invalid_data_err);
3599*be691f3bSpatrick     }
3600*be691f3bSpatrick   }
3601*be691f3bSpatrick 
3602*be691f3bSpatrick   Status status =
3603*be691f3bSpatrick       m_current_process->WriteMemoryTags(type, addr, length, tag_data);
3604*be691f3bSpatrick   return status.Success() ? SendOKResponse() : SendErrorResponse(1);
3605*be691f3bSpatrick }
3606*be691f3bSpatrick 
3607061da546Spatrick void GDBRemoteCommunicationServerLLGS::MaybeCloseInferiorTerminalConnection() {
3608061da546Spatrick   Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
3609061da546Spatrick 
3610061da546Spatrick   // Tell the stdio connection to shut down.
3611061da546Spatrick   if (m_stdio_communication.IsConnected()) {
3612061da546Spatrick     auto connection = m_stdio_communication.GetConnection();
3613061da546Spatrick     if (connection) {
3614061da546Spatrick       Status error;
3615061da546Spatrick       connection->Disconnect(&error);
3616061da546Spatrick 
3617061da546Spatrick       if (error.Success()) {
3618061da546Spatrick         LLDB_LOGF(log,
3619061da546Spatrick                   "GDBRemoteCommunicationServerLLGS::%s disconnect process "
3620061da546Spatrick                   "terminal stdio - SUCCESS",
3621061da546Spatrick                   __FUNCTION__);
3622061da546Spatrick       } else {
3623061da546Spatrick         LLDB_LOGF(log,
3624061da546Spatrick                   "GDBRemoteCommunicationServerLLGS::%s disconnect process "
3625061da546Spatrick                   "terminal stdio - FAIL: %s",
3626061da546Spatrick                   __FUNCTION__, error.AsCString());
3627061da546Spatrick       }
3628061da546Spatrick     }
3629061da546Spatrick   }
3630061da546Spatrick }
3631061da546Spatrick 
3632061da546Spatrick NativeThreadProtocol *GDBRemoteCommunicationServerLLGS::GetThreadFromSuffix(
3633061da546Spatrick     StringExtractorGDBRemote &packet) {
3634061da546Spatrick   // We have no thread if we don't have a process.
3635*be691f3bSpatrick   if (!m_current_process ||
3636*be691f3bSpatrick       m_current_process->GetID() == LLDB_INVALID_PROCESS_ID)
3637061da546Spatrick     return nullptr;
3638061da546Spatrick 
3639061da546Spatrick   // If the client hasn't asked for thread suffix support, there will not be a
3640061da546Spatrick   // thread suffix. Use the current thread in that case.
3641061da546Spatrick   if (!m_thread_suffix_supported) {
3642061da546Spatrick     const lldb::tid_t current_tid = GetCurrentThreadID();
3643061da546Spatrick     if (current_tid == LLDB_INVALID_THREAD_ID)
3644061da546Spatrick       return nullptr;
3645061da546Spatrick     else if (current_tid == 0) {
3646061da546Spatrick       // Pick a thread.
3647*be691f3bSpatrick       return m_current_process->GetThreadAtIndex(0);
3648061da546Spatrick     } else
3649*be691f3bSpatrick       return m_current_process->GetThreadByID(current_tid);
3650061da546Spatrick   }
3651061da546Spatrick 
3652061da546Spatrick   Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_THREAD));
3653061da546Spatrick 
3654061da546Spatrick   // Parse out the ';'.
3655061da546Spatrick   if (packet.GetBytesLeft() < 1 || packet.GetChar() != ';') {
3656061da546Spatrick     LLDB_LOGF(log,
3657061da546Spatrick               "GDBRemoteCommunicationServerLLGS::%s gdb-remote parse "
3658061da546Spatrick               "error: expected ';' prior to start of thread suffix: packet "
3659061da546Spatrick               "contents = '%s'",
3660061da546Spatrick               __FUNCTION__, packet.GetStringRef().data());
3661061da546Spatrick     return nullptr;
3662061da546Spatrick   }
3663061da546Spatrick 
3664061da546Spatrick   if (!packet.GetBytesLeft())
3665061da546Spatrick     return nullptr;
3666061da546Spatrick 
3667061da546Spatrick   // Parse out thread: portion.
3668061da546Spatrick   if (strncmp(packet.Peek(), "thread:", strlen("thread:")) != 0) {
3669061da546Spatrick     LLDB_LOGF(log,
3670061da546Spatrick               "GDBRemoteCommunicationServerLLGS::%s gdb-remote parse "
3671061da546Spatrick               "error: expected 'thread:' but not found, packet contents = "
3672061da546Spatrick               "'%s'",
3673061da546Spatrick               __FUNCTION__, packet.GetStringRef().data());
3674061da546Spatrick     return nullptr;
3675061da546Spatrick   }
3676061da546Spatrick   packet.SetFilePos(packet.GetFilePos() + strlen("thread:"));
3677061da546Spatrick   const lldb::tid_t tid = packet.GetHexMaxU64(false, 0);
3678061da546Spatrick   if (tid != 0)
3679*be691f3bSpatrick     return m_current_process->GetThreadByID(tid);
3680061da546Spatrick 
3681061da546Spatrick   return nullptr;
3682061da546Spatrick }
3683061da546Spatrick 
3684061da546Spatrick lldb::tid_t GDBRemoteCommunicationServerLLGS::GetCurrentThreadID() const {
3685061da546Spatrick   if (m_current_tid == 0 || m_current_tid == LLDB_INVALID_THREAD_ID) {
3686061da546Spatrick     // Use whatever the debug process says is the current thread id since the
3687061da546Spatrick     // protocol either didn't specify or specified we want any/all threads
3688061da546Spatrick     // marked as the current thread.
3689*be691f3bSpatrick     if (!m_current_process)
3690061da546Spatrick       return LLDB_INVALID_THREAD_ID;
3691*be691f3bSpatrick     return m_current_process->GetCurrentThreadID();
3692061da546Spatrick   }
3693061da546Spatrick   // Use the specific current thread id set by the gdb remote protocol.
3694061da546Spatrick   return m_current_tid;
3695061da546Spatrick }
3696061da546Spatrick 
3697061da546Spatrick uint32_t GDBRemoteCommunicationServerLLGS::GetNextSavedRegistersID() {
3698061da546Spatrick   std::lock_guard<std::mutex> guard(m_saved_registers_mutex);
3699061da546Spatrick   return m_next_saved_registers_id++;
3700061da546Spatrick }
3701061da546Spatrick 
3702061da546Spatrick void GDBRemoteCommunicationServerLLGS::ClearProcessSpecificData() {
3703061da546Spatrick   Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
3704061da546Spatrick 
3705061da546Spatrick   LLDB_LOG(log, "clearing {0} xfer buffers", m_xfer_buffer_map.size());
3706061da546Spatrick   m_xfer_buffer_map.clear();
3707061da546Spatrick }
3708061da546Spatrick 
3709061da546Spatrick FileSpec
3710061da546Spatrick GDBRemoteCommunicationServerLLGS::FindModuleFile(const std::string &module_path,
3711061da546Spatrick                                                  const ArchSpec &arch) {
3712*be691f3bSpatrick   if (m_current_process) {
3713061da546Spatrick     FileSpec file_spec;
3714*be691f3bSpatrick     if (m_current_process
3715061da546Spatrick             ->GetLoadedModuleFileSpec(module_path.c_str(), file_spec)
3716061da546Spatrick             .Success()) {
3717061da546Spatrick       if (FileSystem::Instance().Exists(file_spec))
3718061da546Spatrick         return file_spec;
3719061da546Spatrick     }
3720061da546Spatrick   }
3721061da546Spatrick 
3722061da546Spatrick   return GDBRemoteCommunicationServerCommon::FindModuleFile(module_path, arch);
3723061da546Spatrick }
3724061da546Spatrick 
3725061da546Spatrick std::string GDBRemoteCommunicationServerLLGS::XMLEncodeAttributeValue(
3726061da546Spatrick     llvm::StringRef value) {
3727061da546Spatrick   std::string result;
3728061da546Spatrick   for (const char &c : value) {
3729061da546Spatrick     switch (c) {
3730061da546Spatrick     case '\'':
3731061da546Spatrick       result += "&apos;";
3732061da546Spatrick       break;
3733061da546Spatrick     case '"':
3734061da546Spatrick       result += "&quot;";
3735061da546Spatrick       break;
3736061da546Spatrick     case '<':
3737061da546Spatrick       result += "&lt;";
3738061da546Spatrick       break;
3739061da546Spatrick     case '>':
3740061da546Spatrick       result += "&gt;";
3741061da546Spatrick       break;
3742061da546Spatrick     default:
3743061da546Spatrick       result += c;
3744061da546Spatrick       break;
3745061da546Spatrick     }
3746061da546Spatrick   }
3747061da546Spatrick   return result;
3748061da546Spatrick }
3749*be691f3bSpatrick 
3750*be691f3bSpatrick llvm::Expected<lldb::tid_t> GDBRemoteCommunicationServerLLGS::ReadTid(
3751*be691f3bSpatrick     StringExtractorGDBRemote &packet, bool allow_all, lldb::pid_t default_pid) {
3752*be691f3bSpatrick   assert(m_current_process);
3753*be691f3bSpatrick   assert(m_current_process->GetID() != LLDB_INVALID_PROCESS_ID);
3754*be691f3bSpatrick 
3755*be691f3bSpatrick   auto pid_tid = packet.GetPidTid(default_pid);
3756*be691f3bSpatrick   if (!pid_tid)
3757*be691f3bSpatrick     return llvm::make_error<StringError>(inconvertibleErrorCode(),
3758*be691f3bSpatrick                                          "Malformed thread-id");
3759*be691f3bSpatrick 
3760*be691f3bSpatrick   lldb::pid_t pid = pid_tid->first;
3761*be691f3bSpatrick   lldb::tid_t tid = pid_tid->second;
3762*be691f3bSpatrick 
3763*be691f3bSpatrick   if (!allow_all && pid == StringExtractorGDBRemote::AllProcesses)
3764*be691f3bSpatrick     return llvm::make_error<StringError>(
3765*be691f3bSpatrick         inconvertibleErrorCode(),
3766*be691f3bSpatrick         llvm::formatv("PID value {0} not allowed", pid == 0 ? 0 : -1));
3767*be691f3bSpatrick 
3768*be691f3bSpatrick   if (!allow_all && tid == StringExtractorGDBRemote::AllThreads)
3769*be691f3bSpatrick     return llvm::make_error<StringError>(
3770*be691f3bSpatrick         inconvertibleErrorCode(),
3771*be691f3bSpatrick         llvm::formatv("TID value {0} not allowed", tid == 0 ? 0 : -1));
3772*be691f3bSpatrick 
3773*be691f3bSpatrick   if (pid != StringExtractorGDBRemote::AllProcesses) {
3774*be691f3bSpatrick     if (pid != m_current_process->GetID())
3775*be691f3bSpatrick       return llvm::make_error<StringError>(
3776*be691f3bSpatrick           inconvertibleErrorCode(), llvm::formatv("PID {0} not debugged", pid));
3777*be691f3bSpatrick   }
3778*be691f3bSpatrick 
3779*be691f3bSpatrick   return tid;
3780*be691f3bSpatrick }
3781*be691f3bSpatrick 
3782*be691f3bSpatrick std::vector<std::string> GDBRemoteCommunicationServerLLGS::HandleFeatures(
3783*be691f3bSpatrick     const llvm::ArrayRef<llvm::StringRef> client_features) {
3784*be691f3bSpatrick   std::vector<std::string> ret =
3785*be691f3bSpatrick       GDBRemoteCommunicationServerCommon::HandleFeatures(client_features);
3786*be691f3bSpatrick   ret.insert(ret.end(), {
3787*be691f3bSpatrick                             "QThreadSuffixSupported+",
3788*be691f3bSpatrick                             "QListThreadsInStopReply+",
3789*be691f3bSpatrick                             "qXfer:features:read+",
3790*be691f3bSpatrick                         });
3791*be691f3bSpatrick 
3792*be691f3bSpatrick   // report server-only features
3793*be691f3bSpatrick   using Extension = NativeProcessProtocol::Extension;
3794*be691f3bSpatrick   Extension plugin_features = m_process_factory.GetSupportedExtensions();
3795*be691f3bSpatrick   if (bool(plugin_features & Extension::pass_signals))
3796*be691f3bSpatrick     ret.push_back("QPassSignals+");
3797*be691f3bSpatrick   if (bool(plugin_features & Extension::auxv))
3798*be691f3bSpatrick     ret.push_back("qXfer:auxv:read+");
3799*be691f3bSpatrick   if (bool(plugin_features & Extension::libraries_svr4))
3800*be691f3bSpatrick     ret.push_back("qXfer:libraries-svr4:read+");
3801*be691f3bSpatrick   if (bool(plugin_features & Extension::memory_tagging))
3802*be691f3bSpatrick     ret.push_back("memory-tagging+");
3803*be691f3bSpatrick 
3804*be691f3bSpatrick   // check for client features
3805*be691f3bSpatrick   m_extensions_supported = {};
3806*be691f3bSpatrick   for (llvm::StringRef x : client_features)
3807*be691f3bSpatrick     m_extensions_supported |=
3808*be691f3bSpatrick         llvm::StringSwitch<Extension>(x)
3809*be691f3bSpatrick             .Case("multiprocess+", Extension::multiprocess)
3810*be691f3bSpatrick             .Case("fork-events+", Extension::fork)
3811*be691f3bSpatrick             .Case("vfork-events+", Extension::vfork)
3812*be691f3bSpatrick             .Default({});
3813*be691f3bSpatrick 
3814*be691f3bSpatrick   m_extensions_supported &= plugin_features;
3815*be691f3bSpatrick 
3816*be691f3bSpatrick   // fork & vfork require multiprocess
3817*be691f3bSpatrick   if (!bool(m_extensions_supported & Extension::multiprocess))
3818*be691f3bSpatrick     m_extensions_supported &= ~(Extension::fork | Extension::vfork);
3819*be691f3bSpatrick 
3820*be691f3bSpatrick   // report only if actually supported
3821*be691f3bSpatrick   if (bool(m_extensions_supported & Extension::multiprocess))
3822*be691f3bSpatrick     ret.push_back("multiprocess+");
3823*be691f3bSpatrick   if (bool(m_extensions_supported & Extension::fork))
3824*be691f3bSpatrick     ret.push_back("fork-events+");
3825*be691f3bSpatrick   if (bool(m_extensions_supported & Extension::vfork))
3826*be691f3bSpatrick     ret.push_back("vfork-events+");
3827*be691f3bSpatrick 
3828*be691f3bSpatrick   for (auto &x : m_debugged_processes)
3829*be691f3bSpatrick     SetEnabledExtensions(*x.second);
3830*be691f3bSpatrick   return ret;
3831*be691f3bSpatrick }
3832*be691f3bSpatrick 
3833*be691f3bSpatrick void GDBRemoteCommunicationServerLLGS::SetEnabledExtensions(
3834*be691f3bSpatrick     NativeProcessProtocol &process) {
3835*be691f3bSpatrick   NativeProcessProtocol::Extension flags = m_extensions_supported;
3836*be691f3bSpatrick   assert(!bool(flags & ~m_process_factory.GetSupportedExtensions()));
3837*be691f3bSpatrick   process.SetEnabledExtensions(flags);
3838*be691f3bSpatrick }
3839