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