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 void GDBRemoteCommunicationServerLLGS::AddProcessThreads(
1978     StreamGDBRemote &response, NativeProcessProtocol &process, bool &had_any) {
1979   Log *log = GetLog(LLDBLog::Thread);
1980 
1981   lldb::pid_t pid = process.GetID();
1982   if (pid == LLDB_INVALID_PROCESS_ID)
1983     return;
1984 
1985   LLDB_LOG(log, "iterating over threads of process {0}", process.GetID());
1986   NativeThreadProtocol *thread;
1987   uint32_t thread_index;
1988   for (thread_index = 0, thread = process.GetThreadAtIndex(thread_index);
1989        thread;
1990        ++thread_index, thread = process.GetThreadAtIndex(thread_index)) {
1991     LLDB_LOG(log, "iterated thread {0} (tid={1})", thread_index,
1992              thread->GetID());
1993     response.PutChar(had_any ? ',' : 'm');
1994     if (bool(m_extensions_supported &
1995              NativeProcessProtocol::Extension::multiprocess))
1996       response.Format("p{0:x-}.", pid);
1997     response.Format("{0:x-}", thread->GetID());
1998     had_any = true;
1999   }
2000 }
2001 
2002 GDBRemoteCommunication::PacketResult
2003 GDBRemoteCommunicationServerLLGS::Handle_qfThreadInfo(
2004     StringExtractorGDBRemote &packet) {
2005   assert(m_debugged_processes.size() == 1 ||
2006          bool(m_extensions_supported &
2007               NativeProcessProtocol::Extension::multiprocess));
2008 
2009   bool had_any = false;
2010   StreamGDBRemote response;
2011 
2012   for (auto &pid_ptr : m_debugged_processes)
2013     AddProcessThreads(response, *pid_ptr.second, had_any);
2014 
2015   if (!had_any)
2016     response.PutChar('l');
2017   return SendPacketNoLock(response.GetString());
2018 }
2019 
2020 GDBRemoteCommunication::PacketResult
2021 GDBRemoteCommunicationServerLLGS::Handle_qsThreadInfo(
2022     StringExtractorGDBRemote &packet) {
2023   // FIXME for now we return the full thread list in the initial packet and
2024   // always do nothing here.
2025   return SendPacketNoLock("l");
2026 }
2027 
2028 GDBRemoteCommunication::PacketResult
2029 GDBRemoteCommunicationServerLLGS::Handle_g(StringExtractorGDBRemote &packet) {
2030   Log *log = GetLog(LLDBLog::Thread);
2031 
2032   // Move past packet name.
2033   packet.SetFilePos(strlen("g"));
2034 
2035   // Get the thread to use.
2036   NativeThreadProtocol *thread = GetThreadFromSuffix(packet);
2037   if (!thread) {
2038     LLDB_LOG(log, "failed, no thread available");
2039     return SendErrorResponse(0x15);
2040   }
2041 
2042   // Get the thread's register context.
2043   NativeRegisterContext &reg_ctx = thread->GetRegisterContext();
2044 
2045   std::vector<uint8_t> regs_buffer;
2046   for (uint32_t reg_num = 0; reg_num < reg_ctx.GetUserRegisterCount();
2047        ++reg_num) {
2048     const RegisterInfo *reg_info = reg_ctx.GetRegisterInfoAtIndex(reg_num);
2049 
2050     if (reg_info == nullptr) {
2051       LLDB_LOG(log, "failed to get register info for register index {0}",
2052                reg_num);
2053       return SendErrorResponse(0x15);
2054     }
2055 
2056     if (reg_info->value_regs != nullptr)
2057       continue; // skip registers that are contained in other registers
2058 
2059     RegisterValue reg_value;
2060     Status error = reg_ctx.ReadRegister(reg_info, reg_value);
2061     if (error.Fail()) {
2062       LLDB_LOG(log, "failed to read register at index {0}", reg_num);
2063       return SendErrorResponse(0x15);
2064     }
2065 
2066     if (reg_info->byte_offset + reg_info->byte_size >= regs_buffer.size())
2067       // Resize the buffer to guarantee it can store the register offsetted
2068       // data.
2069       regs_buffer.resize(reg_info->byte_offset + reg_info->byte_size);
2070 
2071     // Copy the register offsetted data to the buffer.
2072     memcpy(regs_buffer.data() + reg_info->byte_offset, reg_value.GetBytes(),
2073            reg_info->byte_size);
2074   }
2075 
2076   // Write the response.
2077   StreamGDBRemote response;
2078   response.PutBytesAsRawHex8(regs_buffer.data(), regs_buffer.size());
2079 
2080   return SendPacketNoLock(response.GetString());
2081 }
2082 
2083 GDBRemoteCommunication::PacketResult
2084 GDBRemoteCommunicationServerLLGS::Handle_p(StringExtractorGDBRemote &packet) {
2085   Log *log = GetLog(LLDBLog::Thread);
2086 
2087   // Parse out the register number from the request.
2088   packet.SetFilePos(strlen("p"));
2089   const uint32_t reg_index =
2090       packet.GetHexMaxU32(false, std::numeric_limits<uint32_t>::max());
2091   if (reg_index == std::numeric_limits<uint32_t>::max()) {
2092     LLDB_LOGF(log,
2093               "GDBRemoteCommunicationServerLLGS::%s failed, could not "
2094               "parse register number from request \"%s\"",
2095               __FUNCTION__, packet.GetStringRef().data());
2096     return SendErrorResponse(0x15);
2097   }
2098 
2099   // Get the thread to use.
2100   NativeThreadProtocol *thread = GetThreadFromSuffix(packet);
2101   if (!thread) {
2102     LLDB_LOG(log, "failed, no thread available");
2103     return SendErrorResponse(0x15);
2104   }
2105 
2106   // Get the thread's register context.
2107   NativeRegisterContext &reg_context = thread->GetRegisterContext();
2108 
2109   // Return the end of registers response if we've iterated one past the end of
2110   // the register set.
2111   if (reg_index >= reg_context.GetUserRegisterCount()) {
2112     LLDB_LOGF(log,
2113               "GDBRemoteCommunicationServerLLGS::%s failed, requested "
2114               "register %" PRIu32 " beyond register count %" PRIu32,
2115               __FUNCTION__, reg_index, reg_context.GetUserRegisterCount());
2116     return SendErrorResponse(0x15);
2117   }
2118 
2119   const RegisterInfo *reg_info = reg_context.GetRegisterInfoAtIndex(reg_index);
2120   if (!reg_info) {
2121     LLDB_LOGF(log,
2122               "GDBRemoteCommunicationServerLLGS::%s failed, requested "
2123               "register %" PRIu32 " returned NULL",
2124               __FUNCTION__, reg_index);
2125     return SendErrorResponse(0x15);
2126   }
2127 
2128   // Build the reginfos response.
2129   StreamGDBRemote response;
2130 
2131   // Retrieve the value
2132   RegisterValue reg_value;
2133   Status error = reg_context.ReadRegister(reg_info, reg_value);
2134   if (error.Fail()) {
2135     LLDB_LOGF(log,
2136               "GDBRemoteCommunicationServerLLGS::%s failed, read of "
2137               "requested register %" PRIu32 " (%s) failed: %s",
2138               __FUNCTION__, reg_index, reg_info->name, error.AsCString());
2139     return SendErrorResponse(0x15);
2140   }
2141 
2142   const uint8_t *const data =
2143       static_cast<const uint8_t *>(reg_value.GetBytes());
2144   if (!data) {
2145     LLDB_LOGF(log,
2146               "GDBRemoteCommunicationServerLLGS::%s failed to get data "
2147               "bytes from requested register %" PRIu32,
2148               __FUNCTION__, reg_index);
2149     return SendErrorResponse(0x15);
2150   }
2151 
2152   // FIXME flip as needed to get data in big/little endian format for this host.
2153   for (uint32_t i = 0; i < reg_value.GetByteSize(); ++i)
2154     response.PutHex8(data[i]);
2155 
2156   return SendPacketNoLock(response.GetString());
2157 }
2158 
2159 GDBRemoteCommunication::PacketResult
2160 GDBRemoteCommunicationServerLLGS::Handle_P(StringExtractorGDBRemote &packet) {
2161   Log *log = GetLog(LLDBLog::Thread);
2162 
2163   // Ensure there is more content.
2164   if (packet.GetBytesLeft() < 1)
2165     return SendIllFormedResponse(packet, "Empty P packet");
2166 
2167   // Parse out the register number from the request.
2168   packet.SetFilePos(strlen("P"));
2169   const uint32_t reg_index =
2170       packet.GetHexMaxU32(false, std::numeric_limits<uint32_t>::max());
2171   if (reg_index == std::numeric_limits<uint32_t>::max()) {
2172     LLDB_LOGF(log,
2173               "GDBRemoteCommunicationServerLLGS::%s failed, could not "
2174               "parse register number from request \"%s\"",
2175               __FUNCTION__, packet.GetStringRef().data());
2176     return SendErrorResponse(0x29);
2177   }
2178 
2179   // Note debugserver would send an E30 here.
2180   if ((packet.GetBytesLeft() < 1) || (packet.GetChar() != '='))
2181     return SendIllFormedResponse(
2182         packet, "P packet missing '=' char after register number");
2183 
2184   // Parse out the value.
2185   uint8_t reg_bytes[RegisterValue::kMaxRegisterByteSize];
2186   size_t reg_size = packet.GetHexBytesAvail(reg_bytes);
2187 
2188   // Get the thread to use.
2189   NativeThreadProtocol *thread = GetThreadFromSuffix(packet);
2190   if (!thread) {
2191     LLDB_LOGF(log,
2192               "GDBRemoteCommunicationServerLLGS::%s failed, no thread "
2193               "available (thread index 0)",
2194               __FUNCTION__);
2195     return SendErrorResponse(0x28);
2196   }
2197 
2198   // Get the thread's register context.
2199   NativeRegisterContext &reg_context = thread->GetRegisterContext();
2200   const RegisterInfo *reg_info = reg_context.GetRegisterInfoAtIndex(reg_index);
2201   if (!reg_info) {
2202     LLDB_LOGF(log,
2203               "GDBRemoteCommunicationServerLLGS::%s failed, requested "
2204               "register %" PRIu32 " returned NULL",
2205               __FUNCTION__, reg_index);
2206     return SendErrorResponse(0x48);
2207   }
2208 
2209   // Return the end of registers response if we've iterated one past the end of
2210   // the register set.
2211   if (reg_index >= reg_context.GetUserRegisterCount()) {
2212     LLDB_LOGF(log,
2213               "GDBRemoteCommunicationServerLLGS::%s failed, requested "
2214               "register %" PRIu32 " beyond register count %" PRIu32,
2215               __FUNCTION__, reg_index, reg_context.GetUserRegisterCount());
2216     return SendErrorResponse(0x47);
2217   }
2218 
2219   if (reg_size != reg_info->byte_size)
2220     return SendIllFormedResponse(packet, "P packet register size is incorrect");
2221 
2222   // Build the reginfos response.
2223   StreamGDBRemote response;
2224 
2225   RegisterValue reg_value(makeArrayRef(reg_bytes, reg_size),
2226                           m_current_process->GetArchitecture().GetByteOrder());
2227   Status error = reg_context.WriteRegister(reg_info, reg_value);
2228   if (error.Fail()) {
2229     LLDB_LOGF(log,
2230               "GDBRemoteCommunicationServerLLGS::%s failed, write of "
2231               "requested register %" PRIu32 " (%s) failed: %s",
2232               __FUNCTION__, reg_index, reg_info->name, error.AsCString());
2233     return SendErrorResponse(0x32);
2234   }
2235 
2236   return SendOKResponse();
2237 }
2238 
2239 GDBRemoteCommunication::PacketResult
2240 GDBRemoteCommunicationServerLLGS::Handle_H(StringExtractorGDBRemote &packet) {
2241   Log *log = GetLog(LLDBLog::Thread);
2242 
2243   // Parse out which variant of $H is requested.
2244   packet.SetFilePos(strlen("H"));
2245   if (packet.GetBytesLeft() < 1) {
2246     LLDB_LOGF(log,
2247               "GDBRemoteCommunicationServerLLGS::%s failed, H command "
2248               "missing {g,c} variant",
2249               __FUNCTION__);
2250     return SendIllFormedResponse(packet, "H command missing {g,c} variant");
2251   }
2252 
2253   const char h_variant = packet.GetChar();
2254   NativeProcessProtocol *default_process;
2255   switch (h_variant) {
2256   case 'g':
2257     default_process = m_current_process;
2258     break;
2259 
2260   case 'c':
2261     default_process = m_continue_process;
2262     break;
2263 
2264   default:
2265     LLDB_LOGF(
2266         log,
2267         "GDBRemoteCommunicationServerLLGS::%s failed, invalid $H variant %c",
2268         __FUNCTION__, h_variant);
2269     return SendIllFormedResponse(packet,
2270                                  "H variant unsupported, should be c or g");
2271   }
2272 
2273   // Parse out the thread number.
2274   auto pid_tid = packet.GetPidTid(default_process ? default_process->GetID()
2275                                                   : LLDB_INVALID_PROCESS_ID);
2276   if (!pid_tid)
2277     return SendErrorResponse(llvm::make_error<StringError>(
2278         inconvertibleErrorCode(), "Malformed thread-id"));
2279 
2280   lldb::pid_t pid = pid_tid->first;
2281   lldb::tid_t tid = pid_tid->second;
2282 
2283   if (pid == StringExtractorGDBRemote::AllProcesses)
2284     return SendUnimplementedResponse("Selecting all processes not supported");
2285   if (pid == LLDB_INVALID_PROCESS_ID)
2286     return SendErrorResponse(llvm::make_error<StringError>(
2287         inconvertibleErrorCode(), "No current process and no PID provided"));
2288 
2289   // Check the process ID and find respective process instance.
2290   auto new_process_it = m_debugged_processes.find(pid);
2291   if (new_process_it == m_debugged_processes.end())
2292     return SendErrorResponse(llvm::make_error<StringError>(
2293         inconvertibleErrorCode(),
2294         llvm::formatv("No process with PID {0} debugged", pid)));
2295 
2296   // Ensure we have the given thread when not specifying -1 (all threads) or 0
2297   // (any thread).
2298   if (tid != LLDB_INVALID_THREAD_ID && tid != 0) {
2299     NativeThreadProtocol *thread = new_process_it->second->GetThreadByID(tid);
2300     if (!thread) {
2301       LLDB_LOGF(log,
2302                 "GDBRemoteCommunicationServerLLGS::%s failed, tid %" PRIu64
2303                 " not found",
2304                 __FUNCTION__, tid);
2305       return SendErrorResponse(0x15);
2306     }
2307   }
2308 
2309   // Now switch the given process and thread type.
2310   switch (h_variant) {
2311   case 'g':
2312     m_current_process = new_process_it->second.get();
2313     SetCurrentThreadID(tid);
2314     break;
2315 
2316   case 'c':
2317     m_continue_process = new_process_it->second.get();
2318     SetContinueThreadID(tid);
2319     break;
2320 
2321   default:
2322     assert(false && "unsupported $H variant - shouldn't get here");
2323     return SendIllFormedResponse(packet,
2324                                  "H variant unsupported, should be c or g");
2325   }
2326 
2327   return SendOKResponse();
2328 }
2329 
2330 GDBRemoteCommunication::PacketResult
2331 GDBRemoteCommunicationServerLLGS::Handle_I(StringExtractorGDBRemote &packet) {
2332   Log *log = GetLog(LLDBLog::Thread);
2333 
2334   // Fail if we don't have a current process.
2335   if (!m_current_process ||
2336       (m_current_process->GetID() == LLDB_INVALID_PROCESS_ID)) {
2337     LLDB_LOGF(
2338         log,
2339         "GDBRemoteCommunicationServerLLGS::%s failed, no process available",
2340         __FUNCTION__);
2341     return SendErrorResponse(0x15);
2342   }
2343 
2344   packet.SetFilePos(::strlen("I"));
2345   uint8_t tmp[4096];
2346   for (;;) {
2347     size_t read = packet.GetHexBytesAvail(tmp);
2348     if (read == 0) {
2349       break;
2350     }
2351     // write directly to stdin *this might block if stdin buffer is full*
2352     // TODO: enqueue this block in circular buffer and send window size to
2353     // remote host
2354     ConnectionStatus status;
2355     Status error;
2356     m_stdio_communication.Write(tmp, read, status, &error);
2357     if (error.Fail()) {
2358       return SendErrorResponse(0x15);
2359     }
2360   }
2361 
2362   return SendOKResponse();
2363 }
2364 
2365 GDBRemoteCommunication::PacketResult
2366 GDBRemoteCommunicationServerLLGS::Handle_interrupt(
2367     StringExtractorGDBRemote &packet) {
2368   Log *log = GetLog(LLDBLog::Process | LLDBLog::Thread);
2369 
2370   // Fail if we don't have a current process.
2371   if (!m_current_process ||
2372       (m_current_process->GetID() == LLDB_INVALID_PROCESS_ID)) {
2373     LLDB_LOG(log, "failed, no process available");
2374     return SendErrorResponse(0x15);
2375   }
2376 
2377   // Interrupt the process.
2378   Status error = m_current_process->Interrupt();
2379   if (error.Fail()) {
2380     LLDB_LOG(log, "failed for process {0}: {1}", m_current_process->GetID(),
2381              error);
2382     return SendErrorResponse(GDBRemoteServerError::eErrorResume);
2383   }
2384 
2385   LLDB_LOG(log, "stopped process {0}", m_current_process->GetID());
2386 
2387   // No response required from stop all.
2388   return PacketResult::Success;
2389 }
2390 
2391 GDBRemoteCommunication::PacketResult
2392 GDBRemoteCommunicationServerLLGS::Handle_memory_read(
2393     StringExtractorGDBRemote &packet) {
2394   Log *log = GetLog(LLDBLog::Process);
2395 
2396   if (!m_current_process ||
2397       (m_current_process->GetID() == LLDB_INVALID_PROCESS_ID)) {
2398     LLDB_LOGF(
2399         log,
2400         "GDBRemoteCommunicationServerLLGS::%s failed, no process available",
2401         __FUNCTION__);
2402     return SendErrorResponse(0x15);
2403   }
2404 
2405   // Parse out the memory address.
2406   packet.SetFilePos(strlen("m"));
2407   if (packet.GetBytesLeft() < 1)
2408     return SendIllFormedResponse(packet, "Too short m packet");
2409 
2410   // Read the address.  Punting on validation.
2411   // FIXME replace with Hex U64 read with no default value that fails on failed
2412   // read.
2413   const lldb::addr_t read_addr = packet.GetHexMaxU64(false, 0);
2414 
2415   // Validate comma.
2416   if ((packet.GetBytesLeft() < 1) || (packet.GetChar() != ','))
2417     return SendIllFormedResponse(packet, "Comma sep missing in m packet");
2418 
2419   // Get # bytes to read.
2420   if (packet.GetBytesLeft() < 1)
2421     return SendIllFormedResponse(packet, "Length missing in m packet");
2422 
2423   const uint64_t byte_count = packet.GetHexMaxU64(false, 0);
2424   if (byte_count == 0) {
2425     LLDB_LOGF(log,
2426               "GDBRemoteCommunicationServerLLGS::%s nothing to read: "
2427               "zero-length packet",
2428               __FUNCTION__);
2429     return SendOKResponse();
2430   }
2431 
2432   // Allocate the response buffer.
2433   std::string buf(byte_count, '\0');
2434   if (buf.empty())
2435     return SendErrorResponse(0x78);
2436 
2437   // Retrieve the process memory.
2438   size_t bytes_read = 0;
2439   Status error = m_current_process->ReadMemoryWithoutTrap(
2440       read_addr, &buf[0], byte_count, bytes_read);
2441   if (error.Fail()) {
2442     LLDB_LOGF(log,
2443               "GDBRemoteCommunicationServerLLGS::%s pid %" PRIu64
2444               " mem 0x%" PRIx64 ": failed to read. Error: %s",
2445               __FUNCTION__, m_current_process->GetID(), read_addr,
2446               error.AsCString());
2447     return SendErrorResponse(0x08);
2448   }
2449 
2450   if (bytes_read == 0) {
2451     LLDB_LOGF(log,
2452               "GDBRemoteCommunicationServerLLGS::%s pid %" PRIu64
2453               " mem 0x%" PRIx64 ": read 0 of %" PRIu64 " requested bytes",
2454               __FUNCTION__, m_current_process->GetID(), read_addr, byte_count);
2455     return SendErrorResponse(0x08);
2456   }
2457 
2458   StreamGDBRemote response;
2459   packet.SetFilePos(0);
2460   char kind = packet.GetChar('?');
2461   if (kind == 'x')
2462     response.PutEscapedBytes(buf.data(), byte_count);
2463   else {
2464     assert(kind == 'm');
2465     for (size_t i = 0; i < bytes_read; ++i)
2466       response.PutHex8(buf[i]);
2467   }
2468 
2469   return SendPacketNoLock(response.GetString());
2470 }
2471 
2472 GDBRemoteCommunication::PacketResult
2473 GDBRemoteCommunicationServerLLGS::Handle__M(StringExtractorGDBRemote &packet) {
2474   Log *log = GetLog(LLDBLog::Process);
2475 
2476   if (!m_current_process ||
2477       (m_current_process->GetID() == LLDB_INVALID_PROCESS_ID)) {
2478     LLDB_LOGF(
2479         log,
2480         "GDBRemoteCommunicationServerLLGS::%s failed, no process available",
2481         __FUNCTION__);
2482     return SendErrorResponse(0x15);
2483   }
2484 
2485   // Parse out the memory address.
2486   packet.SetFilePos(strlen("_M"));
2487   if (packet.GetBytesLeft() < 1)
2488     return SendIllFormedResponse(packet, "Too short _M packet");
2489 
2490   const lldb::addr_t size = packet.GetHexMaxU64(false, LLDB_INVALID_ADDRESS);
2491   if (size == LLDB_INVALID_ADDRESS)
2492     return SendIllFormedResponse(packet, "Address not valid");
2493   if (packet.GetChar() != ',')
2494     return SendIllFormedResponse(packet, "Bad packet");
2495   Permissions perms = {};
2496   while (packet.GetBytesLeft() > 0) {
2497     switch (packet.GetChar()) {
2498     case 'r':
2499       perms |= ePermissionsReadable;
2500       break;
2501     case 'w':
2502       perms |= ePermissionsWritable;
2503       break;
2504     case 'x':
2505       perms |= ePermissionsExecutable;
2506       break;
2507     default:
2508       return SendIllFormedResponse(packet, "Bad permissions");
2509     }
2510   }
2511 
2512   llvm::Expected<addr_t> addr = m_current_process->AllocateMemory(size, perms);
2513   if (!addr)
2514     return SendErrorResponse(addr.takeError());
2515 
2516   StreamGDBRemote response;
2517   response.PutHex64(*addr);
2518   return SendPacketNoLock(response.GetString());
2519 }
2520 
2521 GDBRemoteCommunication::PacketResult
2522 GDBRemoteCommunicationServerLLGS::Handle__m(StringExtractorGDBRemote &packet) {
2523   Log *log = GetLog(LLDBLog::Process);
2524 
2525   if (!m_current_process ||
2526       (m_current_process->GetID() == LLDB_INVALID_PROCESS_ID)) {
2527     LLDB_LOGF(
2528         log,
2529         "GDBRemoteCommunicationServerLLGS::%s failed, no process available",
2530         __FUNCTION__);
2531     return SendErrorResponse(0x15);
2532   }
2533 
2534   // Parse out the memory address.
2535   packet.SetFilePos(strlen("_m"));
2536   if (packet.GetBytesLeft() < 1)
2537     return SendIllFormedResponse(packet, "Too short m packet");
2538 
2539   const lldb::addr_t addr = packet.GetHexMaxU64(false, LLDB_INVALID_ADDRESS);
2540   if (addr == LLDB_INVALID_ADDRESS)
2541     return SendIllFormedResponse(packet, "Address not valid");
2542 
2543   if (llvm::Error Err = m_current_process->DeallocateMemory(addr))
2544     return SendErrorResponse(std::move(Err));
2545 
2546   return SendOKResponse();
2547 }
2548 
2549 GDBRemoteCommunication::PacketResult
2550 GDBRemoteCommunicationServerLLGS::Handle_M(StringExtractorGDBRemote &packet) {
2551   Log *log = GetLog(LLDBLog::Process);
2552 
2553   if (!m_current_process ||
2554       (m_current_process->GetID() == LLDB_INVALID_PROCESS_ID)) {
2555     LLDB_LOGF(
2556         log,
2557         "GDBRemoteCommunicationServerLLGS::%s failed, no process available",
2558         __FUNCTION__);
2559     return SendErrorResponse(0x15);
2560   }
2561 
2562   // Parse out the memory address.
2563   packet.SetFilePos(strlen("M"));
2564   if (packet.GetBytesLeft() < 1)
2565     return SendIllFormedResponse(packet, "Too short M packet");
2566 
2567   // Read the address.  Punting on validation.
2568   // FIXME replace with Hex U64 read with no default value that fails on failed
2569   // read.
2570   const lldb::addr_t write_addr = packet.GetHexMaxU64(false, 0);
2571 
2572   // Validate comma.
2573   if ((packet.GetBytesLeft() < 1) || (packet.GetChar() != ','))
2574     return SendIllFormedResponse(packet, "Comma sep missing in M packet");
2575 
2576   // Get # bytes to read.
2577   if (packet.GetBytesLeft() < 1)
2578     return SendIllFormedResponse(packet, "Length missing in M packet");
2579 
2580   const uint64_t byte_count = packet.GetHexMaxU64(false, 0);
2581   if (byte_count == 0) {
2582     LLDB_LOG(log, "nothing to write: zero-length packet");
2583     return PacketResult::Success;
2584   }
2585 
2586   // Validate colon.
2587   if ((packet.GetBytesLeft() < 1) || (packet.GetChar() != ':'))
2588     return SendIllFormedResponse(
2589         packet, "Comma sep missing in M packet after byte length");
2590 
2591   // Allocate the conversion buffer.
2592   std::vector<uint8_t> buf(byte_count, 0);
2593   if (buf.empty())
2594     return SendErrorResponse(0x78);
2595 
2596   // Convert the hex memory write contents to bytes.
2597   StreamGDBRemote response;
2598   const uint64_t convert_count = packet.GetHexBytes(buf, 0);
2599   if (convert_count != byte_count) {
2600     LLDB_LOG(log,
2601              "pid {0} mem {1:x}: asked to write {2} bytes, but only found {3} "
2602              "to convert.",
2603              m_current_process->GetID(), write_addr, byte_count, convert_count);
2604     return SendIllFormedResponse(packet, "M content byte length specified did "
2605                                          "not match hex-encoded content "
2606                                          "length");
2607   }
2608 
2609   // Write the process memory.
2610   size_t bytes_written = 0;
2611   Status error = m_current_process->WriteMemory(write_addr, &buf[0], byte_count,
2612                                                 bytes_written);
2613   if (error.Fail()) {
2614     LLDB_LOG(log, "pid {0} mem {1:x}: failed to write. Error: {2}",
2615              m_current_process->GetID(), write_addr, error);
2616     return SendErrorResponse(0x09);
2617   }
2618 
2619   if (bytes_written == 0) {
2620     LLDB_LOG(log, "pid {0} mem {1:x}: wrote 0 of {2} requested bytes",
2621              m_current_process->GetID(), write_addr, byte_count);
2622     return SendErrorResponse(0x09);
2623   }
2624 
2625   return SendOKResponse();
2626 }
2627 
2628 GDBRemoteCommunication::PacketResult
2629 GDBRemoteCommunicationServerLLGS::Handle_qMemoryRegionInfoSupported(
2630     StringExtractorGDBRemote &packet) {
2631   Log *log = GetLog(LLDBLog::Process);
2632 
2633   // Currently only the NativeProcessProtocol knows if it can handle a
2634   // qMemoryRegionInfoSupported request, but we're not guaranteed to be
2635   // attached to a process.  For now we'll assume the client only asks this
2636   // when a process is being debugged.
2637 
2638   // Ensure we have a process running; otherwise, we can't figure this out
2639   // since we won't have a NativeProcessProtocol.
2640   if (!m_current_process ||
2641       (m_current_process->GetID() == LLDB_INVALID_PROCESS_ID)) {
2642     LLDB_LOGF(
2643         log,
2644         "GDBRemoteCommunicationServerLLGS::%s failed, no process available",
2645         __FUNCTION__);
2646     return SendErrorResponse(0x15);
2647   }
2648 
2649   // Test if we can get any region back when asking for the region around NULL.
2650   MemoryRegionInfo region_info;
2651   const Status error = m_current_process->GetMemoryRegionInfo(0, region_info);
2652   if (error.Fail()) {
2653     // We don't support memory region info collection for this
2654     // NativeProcessProtocol.
2655     return SendUnimplementedResponse("");
2656   }
2657 
2658   return SendOKResponse();
2659 }
2660 
2661 GDBRemoteCommunication::PacketResult
2662 GDBRemoteCommunicationServerLLGS::Handle_qMemoryRegionInfo(
2663     StringExtractorGDBRemote &packet) {
2664   Log *log = GetLog(LLDBLog::Process);
2665 
2666   // Ensure we have a process.
2667   if (!m_current_process ||
2668       (m_current_process->GetID() == LLDB_INVALID_PROCESS_ID)) {
2669     LLDB_LOGF(
2670         log,
2671         "GDBRemoteCommunicationServerLLGS::%s failed, no process available",
2672         __FUNCTION__);
2673     return SendErrorResponse(0x15);
2674   }
2675 
2676   // Parse out the memory address.
2677   packet.SetFilePos(strlen("qMemoryRegionInfo:"));
2678   if (packet.GetBytesLeft() < 1)
2679     return SendIllFormedResponse(packet, "Too short qMemoryRegionInfo: packet");
2680 
2681   // Read the address.  Punting on validation.
2682   const lldb::addr_t read_addr = packet.GetHexMaxU64(false, 0);
2683 
2684   StreamGDBRemote response;
2685 
2686   // Get the memory region info for the target address.
2687   MemoryRegionInfo region_info;
2688   const Status error =
2689       m_current_process->GetMemoryRegionInfo(read_addr, region_info);
2690   if (error.Fail()) {
2691     // Return the error message.
2692 
2693     response.PutCString("error:");
2694     response.PutStringAsRawHex8(error.AsCString());
2695     response.PutChar(';');
2696   } else {
2697     // Range start and size.
2698     response.Printf("start:%" PRIx64 ";size:%" PRIx64 ";",
2699                     region_info.GetRange().GetRangeBase(),
2700                     region_info.GetRange().GetByteSize());
2701 
2702     // Permissions.
2703     if (region_info.GetReadable() || region_info.GetWritable() ||
2704         region_info.GetExecutable()) {
2705       // Write permissions info.
2706       response.PutCString("permissions:");
2707 
2708       if (region_info.GetReadable())
2709         response.PutChar('r');
2710       if (region_info.GetWritable())
2711         response.PutChar('w');
2712       if (region_info.GetExecutable())
2713         response.PutChar('x');
2714 
2715       response.PutChar(';');
2716     }
2717 
2718     // Flags
2719     MemoryRegionInfo::OptionalBool memory_tagged =
2720         region_info.GetMemoryTagged();
2721     if (memory_tagged != MemoryRegionInfo::eDontKnow) {
2722       response.PutCString("flags:");
2723       if (memory_tagged == MemoryRegionInfo::eYes) {
2724         response.PutCString("mt");
2725       }
2726       response.PutChar(';');
2727     }
2728 
2729     // Name
2730     ConstString name = region_info.GetName();
2731     if (name) {
2732       response.PutCString("name:");
2733       response.PutStringAsRawHex8(name.GetStringRef());
2734       response.PutChar(';');
2735     }
2736   }
2737 
2738   return SendPacketNoLock(response.GetString());
2739 }
2740 
2741 GDBRemoteCommunication::PacketResult
2742 GDBRemoteCommunicationServerLLGS::Handle_Z(StringExtractorGDBRemote &packet) {
2743   // Ensure we have a process.
2744   if (!m_current_process ||
2745       (m_current_process->GetID() == LLDB_INVALID_PROCESS_ID)) {
2746     Log *log = GetLog(LLDBLog::Process);
2747     LLDB_LOG(log, "failed, no process available");
2748     return SendErrorResponse(0x15);
2749   }
2750 
2751   // Parse out software or hardware breakpoint or watchpoint requested.
2752   packet.SetFilePos(strlen("Z"));
2753   if (packet.GetBytesLeft() < 1)
2754     return SendIllFormedResponse(
2755         packet, "Too short Z packet, missing software/hardware specifier");
2756 
2757   bool want_breakpoint = true;
2758   bool want_hardware = false;
2759   uint32_t watch_flags = 0;
2760 
2761   const GDBStoppointType stoppoint_type =
2762       GDBStoppointType(packet.GetS32(eStoppointInvalid));
2763   switch (stoppoint_type) {
2764   case eBreakpointSoftware:
2765     want_hardware = false;
2766     want_breakpoint = true;
2767     break;
2768   case eBreakpointHardware:
2769     want_hardware = true;
2770     want_breakpoint = true;
2771     break;
2772   case eWatchpointWrite:
2773     watch_flags = 1;
2774     want_hardware = true;
2775     want_breakpoint = false;
2776     break;
2777   case eWatchpointRead:
2778     watch_flags = 2;
2779     want_hardware = true;
2780     want_breakpoint = false;
2781     break;
2782   case eWatchpointReadWrite:
2783     watch_flags = 3;
2784     want_hardware = true;
2785     want_breakpoint = false;
2786     break;
2787   case eStoppointInvalid:
2788     return SendIllFormedResponse(
2789         packet, "Z packet had invalid software/hardware specifier");
2790   }
2791 
2792   if ((packet.GetBytesLeft() < 1) || packet.GetChar() != ',')
2793     return SendIllFormedResponse(
2794         packet, "Malformed Z packet, expecting comma after stoppoint type");
2795 
2796   // Parse out the stoppoint address.
2797   if (packet.GetBytesLeft() < 1)
2798     return SendIllFormedResponse(packet, "Too short Z packet, missing address");
2799   const lldb::addr_t addr = packet.GetHexMaxU64(false, 0);
2800 
2801   if ((packet.GetBytesLeft() < 1) || packet.GetChar() != ',')
2802     return SendIllFormedResponse(
2803         packet, "Malformed Z packet, expecting comma after address");
2804 
2805   // Parse out the stoppoint size (i.e. size hint for opcode size).
2806   const uint32_t size =
2807       packet.GetHexMaxU32(false, std::numeric_limits<uint32_t>::max());
2808   if (size == std::numeric_limits<uint32_t>::max())
2809     return SendIllFormedResponse(
2810         packet, "Malformed Z packet, failed to parse size argument");
2811 
2812   if (want_breakpoint) {
2813     // Try to set the breakpoint.
2814     const Status error =
2815         m_current_process->SetBreakpoint(addr, size, want_hardware);
2816     if (error.Success())
2817       return SendOKResponse();
2818     Log *log = GetLog(LLDBLog::Breakpoints);
2819     LLDB_LOG(log, "pid {0} failed to set breakpoint: {1}",
2820              m_current_process->GetID(), error);
2821     return SendErrorResponse(0x09);
2822   } else {
2823     // Try to set the watchpoint.
2824     const Status error = m_current_process->SetWatchpoint(
2825         addr, size, watch_flags, want_hardware);
2826     if (error.Success())
2827       return SendOKResponse();
2828     Log *log = GetLog(LLDBLog::Watchpoints);
2829     LLDB_LOG(log, "pid {0} failed to set watchpoint: {1}",
2830              m_current_process->GetID(), error);
2831     return SendErrorResponse(0x09);
2832   }
2833 }
2834 
2835 GDBRemoteCommunication::PacketResult
2836 GDBRemoteCommunicationServerLLGS::Handle_z(StringExtractorGDBRemote &packet) {
2837   // Ensure we have a process.
2838   if (!m_current_process ||
2839       (m_current_process->GetID() == LLDB_INVALID_PROCESS_ID)) {
2840     Log *log = GetLog(LLDBLog::Process);
2841     LLDB_LOG(log, "failed, no process available");
2842     return SendErrorResponse(0x15);
2843   }
2844 
2845   // Parse out software or hardware breakpoint or watchpoint requested.
2846   packet.SetFilePos(strlen("z"));
2847   if (packet.GetBytesLeft() < 1)
2848     return SendIllFormedResponse(
2849         packet, "Too short z packet, missing software/hardware specifier");
2850 
2851   bool want_breakpoint = true;
2852   bool want_hardware = false;
2853 
2854   const GDBStoppointType stoppoint_type =
2855       GDBStoppointType(packet.GetS32(eStoppointInvalid));
2856   switch (stoppoint_type) {
2857   case eBreakpointHardware:
2858     want_breakpoint = true;
2859     want_hardware = true;
2860     break;
2861   case eBreakpointSoftware:
2862     want_breakpoint = true;
2863     break;
2864   case eWatchpointWrite:
2865     want_breakpoint = false;
2866     break;
2867   case eWatchpointRead:
2868     want_breakpoint = false;
2869     break;
2870   case eWatchpointReadWrite:
2871     want_breakpoint = false;
2872     break;
2873   default:
2874     return SendIllFormedResponse(
2875         packet, "z packet had invalid software/hardware specifier");
2876   }
2877 
2878   if ((packet.GetBytesLeft() < 1) || packet.GetChar() != ',')
2879     return SendIllFormedResponse(
2880         packet, "Malformed z packet, expecting comma after stoppoint type");
2881 
2882   // Parse out the stoppoint address.
2883   if (packet.GetBytesLeft() < 1)
2884     return SendIllFormedResponse(packet, "Too short z packet, missing address");
2885   const lldb::addr_t addr = packet.GetHexMaxU64(false, 0);
2886 
2887   if ((packet.GetBytesLeft() < 1) || packet.GetChar() != ',')
2888     return SendIllFormedResponse(
2889         packet, "Malformed z packet, expecting comma after address");
2890 
2891   /*
2892   // Parse out the stoppoint size (i.e. size hint for opcode size).
2893   const uint32_t size = packet.GetHexMaxU32 (false,
2894   std::numeric_limits<uint32_t>::max ());
2895   if (size == std::numeric_limits<uint32_t>::max ())
2896       return SendIllFormedResponse(packet, "Malformed z packet, failed to parse
2897   size argument");
2898   */
2899 
2900   if (want_breakpoint) {
2901     // Try to clear the breakpoint.
2902     const Status error =
2903         m_current_process->RemoveBreakpoint(addr, want_hardware);
2904     if (error.Success())
2905       return SendOKResponse();
2906     Log *log = GetLog(LLDBLog::Breakpoints);
2907     LLDB_LOG(log, "pid {0} failed to remove breakpoint: {1}",
2908              m_current_process->GetID(), error);
2909     return SendErrorResponse(0x09);
2910   } else {
2911     // Try to clear the watchpoint.
2912     const Status error = m_current_process->RemoveWatchpoint(addr);
2913     if (error.Success())
2914       return SendOKResponse();
2915     Log *log = GetLog(LLDBLog::Watchpoints);
2916     LLDB_LOG(log, "pid {0} failed to remove watchpoint: {1}",
2917              m_current_process->GetID(), error);
2918     return SendErrorResponse(0x09);
2919   }
2920 }
2921 
2922 GDBRemoteCommunication::PacketResult
2923 GDBRemoteCommunicationServerLLGS::Handle_s(StringExtractorGDBRemote &packet) {
2924   Log *log = GetLog(LLDBLog::Process | LLDBLog::Thread);
2925 
2926   // Ensure we have a process.
2927   if (!m_continue_process ||
2928       (m_continue_process->GetID() == LLDB_INVALID_PROCESS_ID)) {
2929     LLDB_LOGF(
2930         log,
2931         "GDBRemoteCommunicationServerLLGS::%s failed, no process available",
2932         __FUNCTION__);
2933     return SendErrorResponse(0x32);
2934   }
2935 
2936   // We first try to use a continue thread id.  If any one or any all set, use
2937   // the current thread. Bail out if we don't have a thread id.
2938   lldb::tid_t tid = GetContinueThreadID();
2939   if (tid == 0 || tid == LLDB_INVALID_THREAD_ID)
2940     tid = GetCurrentThreadID();
2941   if (tid == LLDB_INVALID_THREAD_ID)
2942     return SendErrorResponse(0x33);
2943 
2944   // Double check that we have such a thread.
2945   // TODO investigate: on MacOSX we might need to do an UpdateThreads () here.
2946   NativeThreadProtocol *thread = m_continue_process->GetThreadByID(tid);
2947   if (!thread)
2948     return SendErrorResponse(0x33);
2949 
2950   // Create the step action for the given thread.
2951   ResumeAction action = {tid, eStateStepping, LLDB_INVALID_SIGNAL_NUMBER};
2952 
2953   // Setup the actions list.
2954   ResumeActionList actions;
2955   actions.Append(action);
2956 
2957   // All other threads stop while we're single stepping a thread.
2958   actions.SetDefaultThreadActionIfNeeded(eStateStopped, 0);
2959   Status error = m_continue_process->Resume(actions);
2960   if (error.Fail()) {
2961     LLDB_LOGF(log,
2962               "GDBRemoteCommunicationServerLLGS::%s pid %" PRIu64
2963               " tid %" PRIu64 " Resume() failed with error: %s",
2964               __FUNCTION__, m_continue_process->GetID(), tid,
2965               error.AsCString());
2966     return SendErrorResponse(0x49);
2967   }
2968 
2969   // No response here, unless in non-stop mode.
2970   // Otherwise, the stop or exit will come from the resulting action.
2971   return SendContinueSuccessResponse();
2972 }
2973 
2974 llvm::Expected<std::unique_ptr<llvm::MemoryBuffer>>
2975 GDBRemoteCommunicationServerLLGS::BuildTargetXml() {
2976   // Ensure we have a thread.
2977   NativeThreadProtocol *thread = m_current_process->GetThreadAtIndex(0);
2978   if (!thread)
2979     return llvm::createStringError(llvm::inconvertibleErrorCode(),
2980                                    "No thread available");
2981 
2982   Log *log = GetLog(LLDBLog::Process | LLDBLog::Thread);
2983   // Get the register context for the first thread.
2984   NativeRegisterContext &reg_context = thread->GetRegisterContext();
2985 
2986   StreamString response;
2987 
2988   response.Printf("<?xml version=\"1.0\"?>");
2989   response.Printf("<target version=\"1.0\">");
2990 
2991   response.Printf("<architecture>%s</architecture>",
2992                   m_current_process->GetArchitecture()
2993                       .GetTriple()
2994                       .getArchName()
2995                       .str()
2996                       .c_str());
2997 
2998   response.Printf("<feature>");
2999 
3000   const int registers_count = reg_context.GetUserRegisterCount();
3001   for (int reg_index = 0; reg_index < registers_count; reg_index++) {
3002     const RegisterInfo *reg_info =
3003         reg_context.GetRegisterInfoAtIndex(reg_index);
3004 
3005     if (!reg_info) {
3006       LLDB_LOGF(log,
3007                 "%s failed to get register info for register index %" PRIu32,
3008                 "target.xml", reg_index);
3009       continue;
3010     }
3011 
3012     response.Printf("<reg name=\"%s\" bitsize=\"%" PRIu32 "\" regnum=\"%d\" ",
3013                     reg_info->name, reg_info->byte_size * 8, reg_index);
3014 
3015     if (!reg_context.RegisterOffsetIsDynamic())
3016       response.Printf("offset=\"%" PRIu32 "\" ", reg_info->byte_offset);
3017 
3018     if (reg_info->alt_name && reg_info->alt_name[0])
3019       response.Printf("altname=\"%s\" ", reg_info->alt_name);
3020 
3021     llvm::StringRef encoding = GetEncodingNameOrEmpty(*reg_info);
3022     if (!encoding.empty())
3023       response << "encoding=\"" << encoding << "\" ";
3024 
3025     llvm::StringRef format = GetFormatNameOrEmpty(*reg_info);
3026     if (!format.empty())
3027       response << "format=\"" << format << "\" ";
3028 
3029     const char *const register_set_name =
3030         reg_context.GetRegisterSetNameForRegisterAtIndex(reg_index);
3031     if (register_set_name)
3032       response << "group=\"" << register_set_name << "\" ";
3033 
3034     if (reg_info->kinds[RegisterKind::eRegisterKindEHFrame] !=
3035         LLDB_INVALID_REGNUM)
3036       response.Printf("ehframe_regnum=\"%" PRIu32 "\" ",
3037                       reg_info->kinds[RegisterKind::eRegisterKindEHFrame]);
3038 
3039     if (reg_info->kinds[RegisterKind::eRegisterKindDWARF] !=
3040         LLDB_INVALID_REGNUM)
3041       response.Printf("dwarf_regnum=\"%" PRIu32 "\" ",
3042                       reg_info->kinds[RegisterKind::eRegisterKindDWARF]);
3043 
3044     llvm::StringRef kind_generic = GetKindGenericOrEmpty(*reg_info);
3045     if (!kind_generic.empty())
3046       response << "generic=\"" << kind_generic << "\" ";
3047 
3048     if (reg_info->value_regs &&
3049         reg_info->value_regs[0] != LLDB_INVALID_REGNUM) {
3050       response.PutCString("value_regnums=\"");
3051       CollectRegNums(reg_info->value_regs, response, false);
3052       response.Printf("\" ");
3053     }
3054 
3055     if (reg_info->invalidate_regs && reg_info->invalidate_regs[0]) {
3056       response.PutCString("invalidate_regnums=\"");
3057       CollectRegNums(reg_info->invalidate_regs, response, false);
3058       response.Printf("\" ");
3059     }
3060 
3061     response.Printf("/>");
3062   }
3063 
3064   response.Printf("</feature>");
3065   response.Printf("</target>");
3066   return MemoryBuffer::getMemBufferCopy(response.GetString(), "target.xml");
3067 }
3068 
3069 llvm::Expected<std::unique_ptr<llvm::MemoryBuffer>>
3070 GDBRemoteCommunicationServerLLGS::ReadXferObject(llvm::StringRef object,
3071                                                  llvm::StringRef annex) {
3072   // Make sure we have a valid process.
3073   if (!m_current_process ||
3074       (m_current_process->GetID() == LLDB_INVALID_PROCESS_ID)) {
3075     return llvm::createStringError(llvm::inconvertibleErrorCode(),
3076                                    "No process available");
3077   }
3078 
3079   if (object == "auxv") {
3080     // Grab the auxv data.
3081     auto buffer_or_error = m_current_process->GetAuxvData();
3082     if (!buffer_or_error)
3083       return llvm::errorCodeToError(buffer_or_error.getError());
3084     return std::move(*buffer_or_error);
3085   }
3086 
3087   if (object == "siginfo") {
3088     NativeThreadProtocol *thread = m_current_process->GetCurrentThread();
3089     if (!thread)
3090       return llvm::createStringError(llvm::inconvertibleErrorCode(),
3091                                      "no current thread");
3092 
3093     auto buffer_or_error = thread->GetSiginfo();
3094     if (!buffer_or_error)
3095       return buffer_or_error.takeError();
3096     return std::move(*buffer_or_error);
3097   }
3098 
3099   if (object == "libraries-svr4") {
3100     auto library_list = m_current_process->GetLoadedSVR4Libraries();
3101     if (!library_list)
3102       return library_list.takeError();
3103 
3104     StreamString response;
3105     response.Printf("<library-list-svr4 version=\"1.0\">");
3106     for (auto const &library : *library_list) {
3107       response.Printf("<library name=\"%s\" ",
3108                       XMLEncodeAttributeValue(library.name.c_str()).c_str());
3109       response.Printf("lm=\"0x%" PRIx64 "\" ", library.link_map);
3110       response.Printf("l_addr=\"0x%" PRIx64 "\" ", library.base_addr);
3111       response.Printf("l_ld=\"0x%" PRIx64 "\" />", library.ld_addr);
3112     }
3113     response.Printf("</library-list-svr4>");
3114     return MemoryBuffer::getMemBufferCopy(response.GetString(), __FUNCTION__);
3115   }
3116 
3117   if (object == "features" && annex == "target.xml")
3118     return BuildTargetXml();
3119 
3120   return llvm::make_error<UnimplementedError>();
3121 }
3122 
3123 GDBRemoteCommunication::PacketResult
3124 GDBRemoteCommunicationServerLLGS::Handle_qXfer(
3125     StringExtractorGDBRemote &packet) {
3126   SmallVector<StringRef, 5> fields;
3127   // The packet format is "qXfer:<object>:<action>:<annex>:offset,length"
3128   StringRef(packet.GetStringRef()).split(fields, ':', 4);
3129   if (fields.size() != 5)
3130     return SendIllFormedResponse(packet, "malformed qXfer packet");
3131   StringRef &xfer_object = fields[1];
3132   StringRef &xfer_action = fields[2];
3133   StringRef &xfer_annex = fields[3];
3134   StringExtractor offset_data(fields[4]);
3135   if (xfer_action != "read")
3136     return SendUnimplementedResponse("qXfer action not supported");
3137   // Parse offset.
3138   const uint64_t xfer_offset =
3139       offset_data.GetHexMaxU64(false, std::numeric_limits<uint64_t>::max());
3140   if (xfer_offset == std::numeric_limits<uint64_t>::max())
3141     return SendIllFormedResponse(packet, "qXfer packet missing offset");
3142   // Parse out comma.
3143   if (offset_data.GetChar() != ',')
3144     return SendIllFormedResponse(packet,
3145                                  "qXfer packet missing comma after offset");
3146   // Parse out the length.
3147   const uint64_t xfer_length =
3148       offset_data.GetHexMaxU64(false, std::numeric_limits<uint64_t>::max());
3149   if (xfer_length == std::numeric_limits<uint64_t>::max())
3150     return SendIllFormedResponse(packet, "qXfer packet missing length");
3151 
3152   // Get a previously constructed buffer if it exists or create it now.
3153   std::string buffer_key = (xfer_object + xfer_action + xfer_annex).str();
3154   auto buffer_it = m_xfer_buffer_map.find(buffer_key);
3155   if (buffer_it == m_xfer_buffer_map.end()) {
3156     auto buffer_up = ReadXferObject(xfer_object, xfer_annex);
3157     if (!buffer_up)
3158       return SendErrorResponse(buffer_up.takeError());
3159     buffer_it = m_xfer_buffer_map
3160                     .insert(std::make_pair(buffer_key, std::move(*buffer_up)))
3161                     .first;
3162   }
3163 
3164   // Send back the response
3165   StreamGDBRemote response;
3166   bool done_with_buffer = false;
3167   llvm::StringRef buffer = buffer_it->second->getBuffer();
3168   if (xfer_offset >= buffer.size()) {
3169     // We have nothing left to send.  Mark the buffer as complete.
3170     response.PutChar('l');
3171     done_with_buffer = true;
3172   } else {
3173     // Figure out how many bytes are available starting at the given offset.
3174     buffer = buffer.drop_front(xfer_offset);
3175     // Mark the response type according to whether we're reading the remainder
3176     // of the data.
3177     if (xfer_length >= buffer.size()) {
3178       // There will be nothing left to read after this
3179       response.PutChar('l');
3180       done_with_buffer = true;
3181     } else {
3182       // There will still be bytes to read after this request.
3183       response.PutChar('m');
3184       buffer = buffer.take_front(xfer_length);
3185     }
3186     // Now write the data in encoded binary form.
3187     response.PutEscapedBytes(buffer.data(), buffer.size());
3188   }
3189 
3190   if (done_with_buffer)
3191     m_xfer_buffer_map.erase(buffer_it);
3192 
3193   return SendPacketNoLock(response.GetString());
3194 }
3195 
3196 GDBRemoteCommunication::PacketResult
3197 GDBRemoteCommunicationServerLLGS::Handle_QSaveRegisterState(
3198     StringExtractorGDBRemote &packet) {
3199   Log *log = GetLog(LLDBLog::Thread);
3200 
3201   // Move past packet name.
3202   packet.SetFilePos(strlen("QSaveRegisterState"));
3203 
3204   // Get the thread to use.
3205   NativeThreadProtocol *thread = GetThreadFromSuffix(packet);
3206   if (!thread) {
3207     if (m_thread_suffix_supported)
3208       return SendIllFormedResponse(
3209           packet, "No thread specified in QSaveRegisterState packet");
3210     else
3211       return SendIllFormedResponse(packet,
3212                                    "No thread was is set with the Hg packet");
3213   }
3214 
3215   // Grab the register context for the thread.
3216   NativeRegisterContext& reg_context = thread->GetRegisterContext();
3217 
3218   // Save registers to a buffer.
3219   WritableDataBufferSP register_data_sp;
3220   Status error = reg_context.ReadAllRegisterValues(register_data_sp);
3221   if (error.Fail()) {
3222     LLDB_LOG(log, "pid {0} failed to save all register values: {1}",
3223              m_current_process->GetID(), error);
3224     return SendErrorResponse(0x75);
3225   }
3226 
3227   // Allocate a new save id.
3228   const uint32_t save_id = GetNextSavedRegistersID();
3229   assert((m_saved_registers_map.find(save_id) == m_saved_registers_map.end()) &&
3230          "GetNextRegisterSaveID() returned an existing register save id");
3231 
3232   // Save the register data buffer under the save id.
3233   {
3234     std::lock_guard<std::mutex> guard(m_saved_registers_mutex);
3235     m_saved_registers_map[save_id] = register_data_sp;
3236   }
3237 
3238   // Write the response.
3239   StreamGDBRemote response;
3240   response.Printf("%" PRIu32, save_id);
3241   return SendPacketNoLock(response.GetString());
3242 }
3243 
3244 GDBRemoteCommunication::PacketResult
3245 GDBRemoteCommunicationServerLLGS::Handle_QRestoreRegisterState(
3246     StringExtractorGDBRemote &packet) {
3247   Log *log = GetLog(LLDBLog::Thread);
3248 
3249   // Parse out save id.
3250   packet.SetFilePos(strlen("QRestoreRegisterState:"));
3251   if (packet.GetBytesLeft() < 1)
3252     return SendIllFormedResponse(
3253         packet, "QRestoreRegisterState packet missing register save id");
3254 
3255   const uint32_t save_id = packet.GetU32(0);
3256   if (save_id == 0) {
3257     LLDB_LOG(log, "QRestoreRegisterState packet has malformed save id, "
3258                   "expecting decimal uint32_t");
3259     return SendErrorResponse(0x76);
3260   }
3261 
3262   // Get the thread to use.
3263   NativeThreadProtocol *thread = GetThreadFromSuffix(packet);
3264   if (!thread) {
3265     if (m_thread_suffix_supported)
3266       return SendIllFormedResponse(
3267           packet, "No thread specified in QRestoreRegisterState packet");
3268     else
3269       return SendIllFormedResponse(packet,
3270                                    "No thread was is set with the Hg packet");
3271   }
3272 
3273   // Grab the register context for the thread.
3274   NativeRegisterContext &reg_context = thread->GetRegisterContext();
3275 
3276   // Retrieve register state buffer, then remove from the list.
3277   DataBufferSP register_data_sp;
3278   {
3279     std::lock_guard<std::mutex> guard(m_saved_registers_mutex);
3280 
3281     // Find the register set buffer for the given save id.
3282     auto it = m_saved_registers_map.find(save_id);
3283     if (it == m_saved_registers_map.end()) {
3284       LLDB_LOG(log,
3285                "pid {0} does not have a register set save buffer for id {1}",
3286                m_current_process->GetID(), save_id);
3287       return SendErrorResponse(0x77);
3288     }
3289     register_data_sp = it->second;
3290 
3291     // Remove it from the map.
3292     m_saved_registers_map.erase(it);
3293   }
3294 
3295   Status error = reg_context.WriteAllRegisterValues(register_data_sp);
3296   if (error.Fail()) {
3297     LLDB_LOG(log, "pid {0} failed to restore all register values: {1}",
3298              m_current_process->GetID(), error);
3299     return SendErrorResponse(0x77);
3300   }
3301 
3302   return SendOKResponse();
3303 }
3304 
3305 GDBRemoteCommunication::PacketResult
3306 GDBRemoteCommunicationServerLLGS::Handle_vAttach(
3307     StringExtractorGDBRemote &packet) {
3308   Log *log = GetLog(LLDBLog::Process);
3309 
3310   // Consume the ';' after vAttach.
3311   packet.SetFilePos(strlen("vAttach"));
3312   if (!packet.GetBytesLeft() || packet.GetChar() != ';')
3313     return SendIllFormedResponse(packet, "vAttach missing expected ';'");
3314 
3315   // Grab the PID to which we will attach (assume hex encoding).
3316   lldb::pid_t pid = packet.GetU32(LLDB_INVALID_PROCESS_ID, 16);
3317   if (pid == LLDB_INVALID_PROCESS_ID)
3318     return SendIllFormedResponse(packet,
3319                                  "vAttach failed to parse the process id");
3320 
3321   // Attempt to attach.
3322   LLDB_LOGF(log,
3323             "GDBRemoteCommunicationServerLLGS::%s attempting to attach to "
3324             "pid %" PRIu64,
3325             __FUNCTION__, pid);
3326 
3327   Status error = AttachToProcess(pid);
3328 
3329   if (error.Fail()) {
3330     LLDB_LOGF(log,
3331               "GDBRemoteCommunicationServerLLGS::%s failed to attach to "
3332               "pid %" PRIu64 ": %s\n",
3333               __FUNCTION__, pid, error.AsCString());
3334     return SendErrorResponse(error);
3335   }
3336 
3337   // Notify we attached by sending a stop packet.
3338   assert(m_current_process);
3339   return SendStopReasonForState(*m_current_process,
3340                                 m_current_process->GetState(),
3341                                 /*force_synchronous=*/false);
3342 }
3343 
3344 GDBRemoteCommunication::PacketResult
3345 GDBRemoteCommunicationServerLLGS::Handle_vAttachWait(
3346     StringExtractorGDBRemote &packet) {
3347   Log *log = GetLog(LLDBLog::Process);
3348 
3349   // Consume the ';' after the identifier.
3350   packet.SetFilePos(strlen("vAttachWait"));
3351 
3352   if (!packet.GetBytesLeft() || packet.GetChar() != ';')
3353     return SendIllFormedResponse(packet, "vAttachWait missing expected ';'");
3354 
3355   // Allocate the buffer for the process name from vAttachWait.
3356   std::string process_name;
3357   if (!packet.GetHexByteString(process_name))
3358     return SendIllFormedResponse(packet,
3359                                  "vAttachWait failed to parse process name");
3360 
3361   LLDB_LOG(log, "attempting to attach to process named '{0}'", process_name);
3362 
3363   Status error = AttachWaitProcess(process_name, false);
3364   if (error.Fail()) {
3365     LLDB_LOG(log, "failed to attach to process named '{0}': {1}", process_name,
3366              error);
3367     return SendErrorResponse(error);
3368   }
3369 
3370   // Notify we attached by sending a stop packet.
3371   assert(m_current_process);
3372   return SendStopReasonForState(*m_current_process,
3373                                 m_current_process->GetState(),
3374                                 /*force_synchronous=*/false);
3375 }
3376 
3377 GDBRemoteCommunication::PacketResult
3378 GDBRemoteCommunicationServerLLGS::Handle_qVAttachOrWaitSupported(
3379     StringExtractorGDBRemote &packet) {
3380   return SendOKResponse();
3381 }
3382 
3383 GDBRemoteCommunication::PacketResult
3384 GDBRemoteCommunicationServerLLGS::Handle_vAttachOrWait(
3385     StringExtractorGDBRemote &packet) {
3386   Log *log = GetLog(LLDBLog::Process);
3387 
3388   // Consume the ';' after the identifier.
3389   packet.SetFilePos(strlen("vAttachOrWait"));
3390 
3391   if (!packet.GetBytesLeft() || packet.GetChar() != ';')
3392     return SendIllFormedResponse(packet, "vAttachOrWait missing expected ';'");
3393 
3394   // Allocate the buffer for the process name from vAttachWait.
3395   std::string process_name;
3396   if (!packet.GetHexByteString(process_name))
3397     return SendIllFormedResponse(packet,
3398                                  "vAttachOrWait failed to parse process name");
3399 
3400   LLDB_LOG(log, "attempting to attach to process named '{0}'", process_name);
3401 
3402   Status error = AttachWaitProcess(process_name, true);
3403   if (error.Fail()) {
3404     LLDB_LOG(log, "failed to attach to process named '{0}': {1}", process_name,
3405              error);
3406     return SendErrorResponse(error);
3407   }
3408 
3409   // Notify we attached by sending a stop packet.
3410   assert(m_current_process);
3411   return SendStopReasonForState(*m_current_process,
3412                                 m_current_process->GetState(),
3413                                 /*force_synchronous=*/false);
3414 }
3415 
3416 GDBRemoteCommunication::PacketResult
3417 GDBRemoteCommunicationServerLLGS::Handle_vRun(
3418     StringExtractorGDBRemote &packet) {
3419   Log *log = GetLog(LLDBLog::Process);
3420 
3421   llvm::StringRef s = packet.GetStringRef();
3422   if (!s.consume_front("vRun;"))
3423     return SendErrorResponse(8);
3424 
3425   llvm::SmallVector<llvm::StringRef, 16> argv;
3426   s.split(argv, ';');
3427 
3428   for (llvm::StringRef hex_arg : argv) {
3429     StringExtractor arg_ext{hex_arg};
3430     std::string arg;
3431     arg_ext.GetHexByteString(arg);
3432     m_process_launch_info.GetArguments().AppendArgument(arg);
3433     LLDB_LOGF(log, "LLGSPacketHandler::%s added arg: \"%s\"", __FUNCTION__,
3434               arg.c_str());
3435   }
3436 
3437   if (!argv.empty()) {
3438     m_process_launch_info.GetExecutableFile().SetFile(
3439         m_process_launch_info.GetArguments()[0].ref(), FileSpec::Style::native);
3440     m_process_launch_error = LaunchProcess();
3441     if (m_process_launch_error.Success()) {
3442       assert(m_current_process);
3443       return SendStopReasonForState(*m_current_process,
3444                                     m_current_process->GetState(),
3445                                     /*force_synchronous=*/true);
3446     }
3447     LLDB_LOG(log, "failed to launch exe: {0}", m_process_launch_error);
3448   }
3449   return SendErrorResponse(8);
3450 }
3451 
3452 GDBRemoteCommunication::PacketResult
3453 GDBRemoteCommunicationServerLLGS::Handle_D(StringExtractorGDBRemote &packet) {
3454   Log *log = GetLog(LLDBLog::Process);
3455   StopSTDIOForwarding();
3456 
3457   lldb::pid_t pid = LLDB_INVALID_PROCESS_ID;
3458 
3459   // Consume the ';' after D.
3460   packet.SetFilePos(1);
3461   if (packet.GetBytesLeft()) {
3462     if (packet.GetChar() != ';')
3463       return SendIllFormedResponse(packet, "D missing expected ';'");
3464 
3465     // Grab the PID from which we will detach (assume hex encoding).
3466     pid = packet.GetU32(LLDB_INVALID_PROCESS_ID, 16);
3467     if (pid == LLDB_INVALID_PROCESS_ID)
3468       return SendIllFormedResponse(packet, "D failed to parse the process id");
3469   }
3470 
3471   // Detach forked children if their PID was specified *or* no PID was requested
3472   // (i.e. detach-all packet).
3473   llvm::Error detach_error = llvm::Error::success();
3474   bool detached = false;
3475   for (auto it = m_debugged_processes.begin();
3476        it != m_debugged_processes.end();) {
3477     if (pid == LLDB_INVALID_PROCESS_ID || pid == it->first) {
3478       LLDB_LOGF(log,
3479                 "GDBRemoteCommunicationServerLLGS::%s detaching %" PRId64,
3480                 __FUNCTION__, it->first);
3481       if (llvm::Error e = it->second->Detach().ToError())
3482         detach_error = llvm::joinErrors(std::move(detach_error), std::move(e));
3483       else {
3484         if (it->second.get() == m_current_process)
3485           m_current_process = nullptr;
3486         if (it->second.get() == m_continue_process)
3487           m_continue_process = nullptr;
3488         it = m_debugged_processes.erase(it);
3489         detached = true;
3490         continue;
3491       }
3492     }
3493     ++it;
3494   }
3495 
3496   if (detach_error)
3497     return SendErrorResponse(std::move(detach_error));
3498   if (!detached)
3499     return SendErrorResponse(Status("PID %" PRIu64 " not traced", pid));
3500   return SendOKResponse();
3501 }
3502 
3503 GDBRemoteCommunication::PacketResult
3504 GDBRemoteCommunicationServerLLGS::Handle_qThreadStopInfo(
3505     StringExtractorGDBRemote &packet) {
3506   Log *log = GetLog(LLDBLog::Thread);
3507 
3508   if (!m_current_process ||
3509       (m_current_process->GetID() == LLDB_INVALID_PROCESS_ID))
3510     return SendErrorResponse(50);
3511 
3512   packet.SetFilePos(strlen("qThreadStopInfo"));
3513   const lldb::tid_t tid = packet.GetHexMaxU64(false, LLDB_INVALID_THREAD_ID);
3514   if (tid == LLDB_INVALID_THREAD_ID) {
3515     LLDB_LOGF(log,
3516               "GDBRemoteCommunicationServerLLGS::%s failed, could not "
3517               "parse thread id from request \"%s\"",
3518               __FUNCTION__, packet.GetStringRef().data());
3519     return SendErrorResponse(0x15);
3520   }
3521   return SendStopReplyPacketForThread(*m_current_process, tid,
3522                                       /*force_synchronous=*/true);
3523 }
3524 
3525 GDBRemoteCommunication::PacketResult
3526 GDBRemoteCommunicationServerLLGS::Handle_jThreadsInfo(
3527     StringExtractorGDBRemote &) {
3528   Log *log = GetLog(LLDBLog::Process | LLDBLog::Thread);
3529 
3530   // Ensure we have a debugged process.
3531   if (!m_current_process ||
3532       (m_current_process->GetID() == LLDB_INVALID_PROCESS_ID))
3533     return SendErrorResponse(50);
3534   LLDB_LOG(log, "preparing packet for pid {0}", m_current_process->GetID());
3535 
3536   StreamString response;
3537   const bool threads_with_valid_stop_info_only = false;
3538   llvm::Expected<json::Value> threads_info =
3539       GetJSONThreadsInfo(*m_current_process, threads_with_valid_stop_info_only);
3540   if (!threads_info) {
3541     LLDB_LOG_ERROR(log, threads_info.takeError(),
3542                    "failed to prepare a packet for pid {1}: {0}",
3543                    m_current_process->GetID());
3544     return SendErrorResponse(52);
3545   }
3546 
3547   response.AsRawOstream() << *threads_info;
3548   StreamGDBRemote escaped_response;
3549   escaped_response.PutEscapedBytes(response.GetData(), response.GetSize());
3550   return SendPacketNoLock(escaped_response.GetString());
3551 }
3552 
3553 GDBRemoteCommunication::PacketResult
3554 GDBRemoteCommunicationServerLLGS::Handle_qWatchpointSupportInfo(
3555     StringExtractorGDBRemote &packet) {
3556   // Fail if we don't have a current process.
3557   if (!m_current_process ||
3558       m_current_process->GetID() == LLDB_INVALID_PROCESS_ID)
3559     return SendErrorResponse(68);
3560 
3561   packet.SetFilePos(strlen("qWatchpointSupportInfo"));
3562   if (packet.GetBytesLeft() == 0)
3563     return SendOKResponse();
3564   if (packet.GetChar() != ':')
3565     return SendErrorResponse(67);
3566 
3567   auto hw_debug_cap = m_current_process->GetHardwareDebugSupportInfo();
3568 
3569   StreamGDBRemote response;
3570   if (hw_debug_cap == llvm::None)
3571     response.Printf("num:0;");
3572   else
3573     response.Printf("num:%d;", hw_debug_cap->second);
3574 
3575   return SendPacketNoLock(response.GetString());
3576 }
3577 
3578 GDBRemoteCommunication::PacketResult
3579 GDBRemoteCommunicationServerLLGS::Handle_qFileLoadAddress(
3580     StringExtractorGDBRemote &packet) {
3581   // Fail if we don't have a current process.
3582   if (!m_current_process ||
3583       m_current_process->GetID() == LLDB_INVALID_PROCESS_ID)
3584     return SendErrorResponse(67);
3585 
3586   packet.SetFilePos(strlen("qFileLoadAddress:"));
3587   if (packet.GetBytesLeft() == 0)
3588     return SendErrorResponse(68);
3589 
3590   std::string file_name;
3591   packet.GetHexByteString(file_name);
3592 
3593   lldb::addr_t file_load_address = LLDB_INVALID_ADDRESS;
3594   Status error =
3595       m_current_process->GetFileLoadAddress(file_name, file_load_address);
3596   if (error.Fail())
3597     return SendErrorResponse(69);
3598 
3599   if (file_load_address == LLDB_INVALID_ADDRESS)
3600     return SendErrorResponse(1); // File not loaded
3601 
3602   StreamGDBRemote response;
3603   response.PutHex64(file_load_address);
3604   return SendPacketNoLock(response.GetString());
3605 }
3606 
3607 GDBRemoteCommunication::PacketResult
3608 GDBRemoteCommunicationServerLLGS::Handle_QPassSignals(
3609     StringExtractorGDBRemote &packet) {
3610   std::vector<int> signals;
3611   packet.SetFilePos(strlen("QPassSignals:"));
3612 
3613   // Read sequence of hex signal numbers divided by a semicolon and optionally
3614   // spaces.
3615   while (packet.GetBytesLeft() > 0) {
3616     int signal = packet.GetS32(-1, 16);
3617     if (signal < 0)
3618       return SendIllFormedResponse(packet, "Failed to parse signal number.");
3619     signals.push_back(signal);
3620 
3621     packet.SkipSpaces();
3622     char separator = packet.GetChar();
3623     if (separator == '\0')
3624       break; // End of string
3625     if (separator != ';')
3626       return SendIllFormedResponse(packet, "Invalid separator,"
3627                                             " expected semicolon.");
3628   }
3629 
3630   // Fail if we don't have a current process.
3631   if (!m_current_process)
3632     return SendErrorResponse(68);
3633 
3634   Status error = m_current_process->IgnoreSignals(signals);
3635   if (error.Fail())
3636     return SendErrorResponse(69);
3637 
3638   return SendOKResponse();
3639 }
3640 
3641 GDBRemoteCommunication::PacketResult
3642 GDBRemoteCommunicationServerLLGS::Handle_qMemTags(
3643     StringExtractorGDBRemote &packet) {
3644   Log *log = GetLog(LLDBLog::Process);
3645 
3646   // Ensure we have a process.
3647   if (!m_current_process ||
3648       (m_current_process->GetID() == LLDB_INVALID_PROCESS_ID)) {
3649     LLDB_LOGF(
3650         log,
3651         "GDBRemoteCommunicationServerLLGS::%s failed, no process available",
3652         __FUNCTION__);
3653     return SendErrorResponse(1);
3654   }
3655 
3656   // We are expecting
3657   // qMemTags:<hex address>,<hex length>:<hex type>
3658 
3659   // Address
3660   packet.SetFilePos(strlen("qMemTags:"));
3661   const char *current_char = packet.Peek();
3662   if (!current_char || *current_char == ',')
3663     return SendIllFormedResponse(packet, "Missing address in qMemTags packet");
3664   const lldb::addr_t addr = packet.GetHexMaxU64(/*little_endian=*/false, 0);
3665 
3666   // Length
3667   char previous_char = packet.GetChar();
3668   current_char = packet.Peek();
3669   // If we don't have a separator or the length field is empty
3670   if (previous_char != ',' || (current_char && *current_char == ':'))
3671     return SendIllFormedResponse(packet,
3672                                  "Invalid addr,length pair in qMemTags packet");
3673 
3674   if (packet.GetBytesLeft() < 1)
3675     return SendIllFormedResponse(
3676         packet, "Too short qMemtags: packet (looking for length)");
3677   const size_t length = packet.GetHexMaxU64(/*little_endian=*/false, 0);
3678 
3679   // Type
3680   const char *invalid_type_err = "Invalid type field in qMemTags: packet";
3681   if (packet.GetBytesLeft() < 1 || packet.GetChar() != ':')
3682     return SendIllFormedResponse(packet, invalid_type_err);
3683 
3684   // Type is a signed integer but packed into the packet as its raw bytes.
3685   // However, our GetU64 uses strtoull which allows +/-. We do not want this.
3686   const char *first_type_char = packet.Peek();
3687   if (first_type_char && (*first_type_char == '+' || *first_type_char == '-'))
3688     return SendIllFormedResponse(packet, invalid_type_err);
3689 
3690   // Extract type as unsigned then cast to signed.
3691   // Using a uint64_t here so that we have some value outside of the 32 bit
3692   // range to use as the invalid return value.
3693   uint64_t raw_type =
3694       packet.GetU64(std::numeric_limits<uint64_t>::max(), /*base=*/16);
3695 
3696   if ( // Make sure the cast below would be valid
3697       raw_type > std::numeric_limits<uint32_t>::max() ||
3698       // To catch inputs like "123aardvark" that will parse but clearly aren't
3699       // valid in this case.
3700       packet.GetBytesLeft()) {
3701     return SendIllFormedResponse(packet, invalid_type_err);
3702   }
3703 
3704   // First narrow to 32 bits otherwise the copy into type would take
3705   // the wrong 4 bytes on big endian.
3706   uint32_t raw_type_32 = raw_type;
3707   int32_t type = reinterpret_cast<int32_t &>(raw_type_32);
3708 
3709   StreamGDBRemote response;
3710   std::vector<uint8_t> tags;
3711   Status error = m_current_process->ReadMemoryTags(type, addr, length, tags);
3712   if (error.Fail())
3713     return SendErrorResponse(1);
3714 
3715   // This m is here in case we want to support multi part replies in the future.
3716   // In the same manner as qfThreadInfo/qsThreadInfo.
3717   response.PutChar('m');
3718   response.PutBytesAsRawHex8(tags.data(), tags.size());
3719   return SendPacketNoLock(response.GetString());
3720 }
3721 
3722 GDBRemoteCommunication::PacketResult
3723 GDBRemoteCommunicationServerLLGS::Handle_QMemTags(
3724     StringExtractorGDBRemote &packet) {
3725   Log *log = GetLog(LLDBLog::Process);
3726 
3727   // Ensure we have a process.
3728   if (!m_current_process ||
3729       (m_current_process->GetID() == LLDB_INVALID_PROCESS_ID)) {
3730     LLDB_LOGF(
3731         log,
3732         "GDBRemoteCommunicationServerLLGS::%s failed, no process available",
3733         __FUNCTION__);
3734     return SendErrorResponse(1);
3735   }
3736 
3737   // We are expecting
3738   // QMemTags:<hex address>,<hex length>:<hex type>:<tags as hex bytes>
3739 
3740   // Address
3741   packet.SetFilePos(strlen("QMemTags:"));
3742   const char *current_char = packet.Peek();
3743   if (!current_char || *current_char == ',')
3744     return SendIllFormedResponse(packet, "Missing address in QMemTags packet");
3745   const lldb::addr_t addr = packet.GetHexMaxU64(/*little_endian=*/false, 0);
3746 
3747   // Length
3748   char previous_char = packet.GetChar();
3749   current_char = packet.Peek();
3750   // If we don't have a separator or the length field is empty
3751   if (previous_char != ',' || (current_char && *current_char == ':'))
3752     return SendIllFormedResponse(packet,
3753                                  "Invalid addr,length pair in QMemTags packet");
3754 
3755   if (packet.GetBytesLeft() < 1)
3756     return SendIllFormedResponse(
3757         packet, "Too short QMemtags: packet (looking for length)");
3758   const size_t length = packet.GetHexMaxU64(/*little_endian=*/false, 0);
3759 
3760   // Type
3761   const char *invalid_type_err = "Invalid type field in QMemTags: packet";
3762   if (packet.GetBytesLeft() < 1 || packet.GetChar() != ':')
3763     return SendIllFormedResponse(packet, invalid_type_err);
3764 
3765   // Our GetU64 uses strtoull which allows leading +/-, we don't want that.
3766   const char *first_type_char = packet.Peek();
3767   if (first_type_char && (*first_type_char == '+' || *first_type_char == '-'))
3768     return SendIllFormedResponse(packet, invalid_type_err);
3769 
3770   // The type is a signed integer but is in the packet as its raw bytes.
3771   // So parse first as unsigned then cast to signed later.
3772   // We extract to 64 bit, even though we only expect 32, so that we've
3773   // got some invalid value we can check for.
3774   uint64_t raw_type =
3775       packet.GetU64(std::numeric_limits<uint64_t>::max(), /*base=*/16);
3776   if (raw_type > std::numeric_limits<uint32_t>::max())
3777     return SendIllFormedResponse(packet, invalid_type_err);
3778 
3779   // First narrow to 32 bits. Otherwise the copy below would get the wrong
3780   // 4 bytes on big endian.
3781   uint32_t raw_type_32 = raw_type;
3782   int32_t type = reinterpret_cast<int32_t &>(raw_type_32);
3783 
3784   // Tag data
3785   if (packet.GetBytesLeft() < 1 || packet.GetChar() != ':')
3786     return SendIllFormedResponse(packet,
3787                                  "Missing tag data in QMemTags: packet");
3788 
3789   // Must be 2 chars per byte
3790   const char *invalid_data_err = "Invalid tag data in QMemTags: packet";
3791   if (packet.GetBytesLeft() % 2)
3792     return SendIllFormedResponse(packet, invalid_data_err);
3793 
3794   // This is bytes here and is unpacked into target specific tags later
3795   // We cannot assume that number of bytes == length here because the server
3796   // can repeat tags to fill a given range.
3797   std::vector<uint8_t> tag_data;
3798   // Zero length writes will not have any tag data
3799   // (but we pass them on because it will still check that tagging is enabled)
3800   if (packet.GetBytesLeft()) {
3801     size_t byte_count = packet.GetBytesLeft() / 2;
3802     tag_data.resize(byte_count);
3803     size_t converted_bytes = packet.GetHexBytes(tag_data, 0);
3804     if (converted_bytes != byte_count) {
3805       return SendIllFormedResponse(packet, invalid_data_err);
3806     }
3807   }
3808 
3809   Status status =
3810       m_current_process->WriteMemoryTags(type, addr, length, tag_data);
3811   return status.Success() ? SendOKResponse() : SendErrorResponse(1);
3812 }
3813 
3814 GDBRemoteCommunication::PacketResult
3815 GDBRemoteCommunicationServerLLGS::Handle_qSaveCore(
3816     StringExtractorGDBRemote &packet) {
3817   // Fail if we don't have a current process.
3818   if (!m_current_process ||
3819       (m_current_process->GetID() == LLDB_INVALID_PROCESS_ID))
3820     return SendErrorResponse(Status("Process not running."));
3821 
3822   std::string path_hint;
3823 
3824   StringRef packet_str{packet.GetStringRef()};
3825   assert(packet_str.startswith("qSaveCore"));
3826   if (packet_str.consume_front("qSaveCore;")) {
3827     for (auto x : llvm::split(packet_str, ';')) {
3828       if (x.consume_front("path-hint:"))
3829         StringExtractor(x).GetHexByteString(path_hint);
3830       else
3831         return SendErrorResponse(Status("Unsupported qSaveCore option"));
3832     }
3833   }
3834 
3835   llvm::Expected<std::string> ret = m_current_process->SaveCore(path_hint);
3836   if (!ret)
3837     return SendErrorResponse(ret.takeError());
3838 
3839   StreamString response;
3840   response.PutCString("core-path:");
3841   response.PutStringAsRawHex8(ret.get());
3842   return SendPacketNoLock(response.GetString());
3843 }
3844 
3845 GDBRemoteCommunication::PacketResult
3846 GDBRemoteCommunicationServerLLGS::Handle_QNonStop(
3847     StringExtractorGDBRemote &packet) {
3848   StringRef packet_str{packet.GetStringRef()};
3849   assert(packet_str.startswith("QNonStop:"));
3850   packet_str.consume_front("QNonStop:");
3851   if (packet_str == "0") {
3852     m_non_stop = false;
3853     // TODO: stop all threads
3854   } else if (packet_str == "1") {
3855     m_non_stop = true;
3856   } else
3857     return SendErrorResponse(Status("Invalid QNonStop packet"));
3858   return SendOKResponse();
3859 }
3860 
3861 GDBRemoteCommunication::PacketResult
3862 GDBRemoteCommunicationServerLLGS::Handle_vStopped(
3863     StringExtractorGDBRemote &packet) {
3864   // Per the protocol, the first message put into the queue is sent
3865   // immediately.  However, it remains the queue until the client ACKs
3866   // it via vStopped -- then we pop it and send the next message.
3867   // The process repeats until the last message in the queue is ACK-ed,
3868   // in which case the vStopped packet sends an OK response.
3869 
3870   if (m_stop_notification_queue.empty())
3871     return SendErrorResponse(Status("No pending notification to ack"));
3872   m_stop_notification_queue.pop_front();
3873   if (!m_stop_notification_queue.empty())
3874     return SendPacketNoLock(m_stop_notification_queue.front());
3875   // If this was the last notification and the process exited, terminate
3876   // the server.
3877   if (m_inferior_prev_state == eStateExited) {
3878     m_exit_now = true;
3879     m_mainloop.RequestTermination();
3880   }
3881   return SendOKResponse();
3882 }
3883 
3884 GDBRemoteCommunication::PacketResult
3885 GDBRemoteCommunicationServerLLGS::Handle_vCtrlC(
3886     StringExtractorGDBRemote &packet) {
3887   if (!m_non_stop)
3888     return SendErrorResponse(Status("vCtrl is only valid in non-stop mode"));
3889 
3890   PacketResult interrupt_res = Handle_interrupt(packet);
3891   // If interrupting the process failed, pass the result through.
3892   if (interrupt_res != PacketResult::Success)
3893     return interrupt_res;
3894   // Otherwise, vCtrlC should issue an OK response (normal interrupts do not).
3895   return SendOKResponse();
3896 }
3897 
3898 void GDBRemoteCommunicationServerLLGS::MaybeCloseInferiorTerminalConnection() {
3899   Log *log = GetLog(LLDBLog::Process);
3900 
3901   // Tell the stdio connection to shut down.
3902   if (m_stdio_communication.IsConnected()) {
3903     auto connection = m_stdio_communication.GetConnection();
3904     if (connection) {
3905       Status error;
3906       connection->Disconnect(&error);
3907 
3908       if (error.Success()) {
3909         LLDB_LOGF(log,
3910                   "GDBRemoteCommunicationServerLLGS::%s disconnect process "
3911                   "terminal stdio - SUCCESS",
3912                   __FUNCTION__);
3913       } else {
3914         LLDB_LOGF(log,
3915                   "GDBRemoteCommunicationServerLLGS::%s disconnect process "
3916                   "terminal stdio - FAIL: %s",
3917                   __FUNCTION__, error.AsCString());
3918       }
3919     }
3920   }
3921 }
3922 
3923 NativeThreadProtocol *GDBRemoteCommunicationServerLLGS::GetThreadFromSuffix(
3924     StringExtractorGDBRemote &packet) {
3925   // We have no thread if we don't have a process.
3926   if (!m_current_process ||
3927       m_current_process->GetID() == LLDB_INVALID_PROCESS_ID)
3928     return nullptr;
3929 
3930   // If the client hasn't asked for thread suffix support, there will not be a
3931   // thread suffix. Use the current thread in that case.
3932   if (!m_thread_suffix_supported) {
3933     const lldb::tid_t current_tid = GetCurrentThreadID();
3934     if (current_tid == LLDB_INVALID_THREAD_ID)
3935       return nullptr;
3936     else if (current_tid == 0) {
3937       // Pick a thread.
3938       return m_current_process->GetThreadAtIndex(0);
3939     } else
3940       return m_current_process->GetThreadByID(current_tid);
3941   }
3942 
3943   Log *log = GetLog(LLDBLog::Thread);
3944 
3945   // Parse out the ';'.
3946   if (packet.GetBytesLeft() < 1 || packet.GetChar() != ';') {
3947     LLDB_LOGF(log,
3948               "GDBRemoteCommunicationServerLLGS::%s gdb-remote parse "
3949               "error: expected ';' prior to start of thread suffix: packet "
3950               "contents = '%s'",
3951               __FUNCTION__, packet.GetStringRef().data());
3952     return nullptr;
3953   }
3954 
3955   if (!packet.GetBytesLeft())
3956     return nullptr;
3957 
3958   // Parse out thread: portion.
3959   if (strncmp(packet.Peek(), "thread:", strlen("thread:")) != 0) {
3960     LLDB_LOGF(log,
3961               "GDBRemoteCommunicationServerLLGS::%s gdb-remote parse "
3962               "error: expected 'thread:' but not found, packet contents = "
3963               "'%s'",
3964               __FUNCTION__, packet.GetStringRef().data());
3965     return nullptr;
3966   }
3967   packet.SetFilePos(packet.GetFilePos() + strlen("thread:"));
3968   const lldb::tid_t tid = packet.GetHexMaxU64(false, 0);
3969   if (tid != 0)
3970     return m_current_process->GetThreadByID(tid);
3971 
3972   return nullptr;
3973 }
3974 
3975 lldb::tid_t GDBRemoteCommunicationServerLLGS::GetCurrentThreadID() const {
3976   if (m_current_tid == 0 || m_current_tid == LLDB_INVALID_THREAD_ID) {
3977     // Use whatever the debug process says is the current thread id since the
3978     // protocol either didn't specify or specified we want any/all threads
3979     // marked as the current thread.
3980     if (!m_current_process)
3981       return LLDB_INVALID_THREAD_ID;
3982     return m_current_process->GetCurrentThreadID();
3983   }
3984   // Use the specific current thread id set by the gdb remote protocol.
3985   return m_current_tid;
3986 }
3987 
3988 uint32_t GDBRemoteCommunicationServerLLGS::GetNextSavedRegistersID() {
3989   std::lock_guard<std::mutex> guard(m_saved_registers_mutex);
3990   return m_next_saved_registers_id++;
3991 }
3992 
3993 void GDBRemoteCommunicationServerLLGS::ClearProcessSpecificData() {
3994   Log *log = GetLog(LLDBLog::Process);
3995 
3996   LLDB_LOG(log, "clearing {0} xfer buffers", m_xfer_buffer_map.size());
3997   m_xfer_buffer_map.clear();
3998 }
3999 
4000 FileSpec
4001 GDBRemoteCommunicationServerLLGS::FindModuleFile(const std::string &module_path,
4002                                                  const ArchSpec &arch) {
4003   if (m_current_process) {
4004     FileSpec file_spec;
4005     if (m_current_process
4006             ->GetLoadedModuleFileSpec(module_path.c_str(), file_spec)
4007             .Success()) {
4008       if (FileSystem::Instance().Exists(file_spec))
4009         return file_spec;
4010     }
4011   }
4012 
4013   return GDBRemoteCommunicationServerCommon::FindModuleFile(module_path, arch);
4014 }
4015 
4016 std::string GDBRemoteCommunicationServerLLGS::XMLEncodeAttributeValue(
4017     llvm::StringRef value) {
4018   std::string result;
4019   for (const char &c : value) {
4020     switch (c) {
4021     case '\'':
4022       result += "&apos;";
4023       break;
4024     case '"':
4025       result += "&quot;";
4026       break;
4027     case '<':
4028       result += "&lt;";
4029       break;
4030     case '>':
4031       result += "&gt;";
4032       break;
4033     default:
4034       result += c;
4035       break;
4036     }
4037   }
4038   return result;
4039 }
4040 
4041 std::vector<std::string> GDBRemoteCommunicationServerLLGS::HandleFeatures(
4042     const llvm::ArrayRef<llvm::StringRef> client_features) {
4043   std::vector<std::string> ret =
4044       GDBRemoteCommunicationServerCommon::HandleFeatures(client_features);
4045   ret.insert(ret.end(), {
4046                             "QThreadSuffixSupported+",
4047                             "QListThreadsInStopReply+",
4048                             "qXfer:features:read+",
4049                             "QNonStop+",
4050                         });
4051 
4052   // report server-only features
4053   using Extension = NativeProcessProtocol::Extension;
4054   Extension plugin_features = m_process_factory.GetSupportedExtensions();
4055   if (bool(plugin_features & Extension::pass_signals))
4056     ret.push_back("QPassSignals+");
4057   if (bool(plugin_features & Extension::auxv))
4058     ret.push_back("qXfer:auxv:read+");
4059   if (bool(plugin_features & Extension::libraries_svr4))
4060     ret.push_back("qXfer:libraries-svr4:read+");
4061   if (bool(plugin_features & Extension::siginfo_read))
4062     ret.push_back("qXfer:siginfo:read+");
4063   if (bool(plugin_features & Extension::memory_tagging))
4064     ret.push_back("memory-tagging+");
4065   if (bool(plugin_features & Extension::savecore))
4066     ret.push_back("qSaveCore+");
4067 
4068   // check for client features
4069   m_extensions_supported = {};
4070   for (llvm::StringRef x : client_features)
4071     m_extensions_supported |=
4072         llvm::StringSwitch<Extension>(x)
4073             .Case("multiprocess+", Extension::multiprocess)
4074             .Case("fork-events+", Extension::fork)
4075             .Case("vfork-events+", Extension::vfork)
4076             .Default({});
4077 
4078   m_extensions_supported &= plugin_features;
4079 
4080   // fork & vfork require multiprocess
4081   if (!bool(m_extensions_supported & Extension::multiprocess))
4082     m_extensions_supported &= ~(Extension::fork | Extension::vfork);
4083 
4084   // report only if actually supported
4085   if (bool(m_extensions_supported & Extension::multiprocess))
4086     ret.push_back("multiprocess+");
4087   if (bool(m_extensions_supported & Extension::fork))
4088     ret.push_back("fork-events+");
4089   if (bool(m_extensions_supported & Extension::vfork))
4090     ret.push_back("vfork-events+");
4091 
4092   for (auto &x : m_debugged_processes)
4093     SetEnabledExtensions(*x.second);
4094   return ret;
4095 }
4096 
4097 void GDBRemoteCommunicationServerLLGS::SetEnabledExtensions(
4098     NativeProcessProtocol &process) {
4099   NativeProcessProtocol::Extension flags = m_extensions_supported;
4100   assert(!bool(flags & ~m_process_factory.GetSupportedExtensions()));
4101   process.SetEnabledExtensions(flags);
4102 }
4103 
4104 GDBRemoteCommunication::PacketResult
4105 GDBRemoteCommunicationServerLLGS::SendContinueSuccessResponse() {
4106   // TODO: how to handle forwarding in non-stop mode?
4107   StartSTDIOForwarding();
4108   return m_non_stop ? SendOKResponse() : PacketResult::Success;
4109 }
4110 
4111 std::string
4112 lldb_private::process_gdb_remote::LLGSArgToURL(llvm::StringRef url_arg,
4113                                                bool reverse_connect) {
4114   // Try parsing the argument as URL.
4115   if (llvm::Optional<URI> url = URI::Parse(url_arg)) {
4116     if (reverse_connect)
4117       return url_arg.str();
4118 
4119     // Translate the scheme from LLGS notation to ConnectionFileDescriptor.
4120     // If the scheme doesn't match any, pass it through to support using CFD
4121     // schemes directly.
4122     std::string new_url = llvm::StringSwitch<std::string>(url->scheme)
4123                               .Case("tcp", "listen")
4124                               .Case("unix", "unix-accept")
4125                               .Case("unix-abstract", "unix-abstract-accept")
4126                               .Default(url->scheme.str());
4127     llvm::append_range(new_url, url_arg.substr(url->scheme.size()));
4128     return new_url;
4129   }
4130 
4131   std::string host_port = url_arg.str();
4132   // If host_and_port starts with ':', default the host to be "localhost" and
4133   // expect the remainder to be the port.
4134   if (url_arg.startswith(":"))
4135     host_port.insert(0, "localhost");
4136 
4137   // Try parsing the (preprocessed) argument as host:port pair.
4138   if (!llvm::errorToBool(Socket::DecodeHostAndPort(host_port).takeError()))
4139     return (reverse_connect ? "connect://" : "listen://") + host_port;
4140 
4141   // If none of the above applied, interpret the argument as UNIX socket path.
4142   return (reverse_connect ? "unix-connect://" : "unix-accept://") +
4143          url_arg.str();
4144 }
4145