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