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