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