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