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