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