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