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