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