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