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