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