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