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