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