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