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