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