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