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