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