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