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