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