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