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