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