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