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