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