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