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