• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 //===-- ProcessGDBRemote.cpp ----------------------------------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 
9 #include "lldb/Host/Config.h"
10 
11 #include <errno.h>
12 #include <stdlib.h>
13 #if LLDB_ENABLE_POSIX
14 #include <netinet/in.h>
15 #include <sys/mman.h>
16 #include <sys/socket.h>
17 #include <unistd.h>
18 #endif
19 #include <sys/stat.h>
20 #if defined(__APPLE__)
21 #include <sys/sysctl.h>
22 #endif
23 #include <sys/types.h>
24 #include <time.h>
25 
26 #include <algorithm>
27 #include <csignal>
28 #include <map>
29 #include <memory>
30 #include <mutex>
31 #include <sstream>
32 
33 #include "lldb/Breakpoint/Watchpoint.h"
34 #include "lldb/Core/Debugger.h"
35 #include "lldb/Core/Module.h"
36 #include "lldb/Core/ModuleSpec.h"
37 #include "lldb/Core/PluginManager.h"
38 #include "lldb/Core/StreamFile.h"
39 #include "lldb/Core/Value.h"
40 #include "lldb/DataFormatters/FormatManager.h"
41 #include "lldb/Host/ConnectionFileDescriptor.h"
42 #include "lldb/Host/FileSystem.h"
43 #include "lldb/Host/HostThread.h"
44 #include "lldb/Host/PosixApi.h"
45 #include "lldb/Host/PseudoTerminal.h"
46 #include "lldb/Host/StringConvert.h"
47 #include "lldb/Host/ThreadLauncher.h"
48 #include "lldb/Host/XML.h"
49 #include "lldb/Interpreter/CommandInterpreter.h"
50 #include "lldb/Interpreter/CommandObject.h"
51 #include "lldb/Interpreter/CommandObjectMultiword.h"
52 #include "lldb/Interpreter/CommandReturnObject.h"
53 #include "lldb/Interpreter/OptionArgParser.h"
54 #include "lldb/Interpreter/OptionGroupBoolean.h"
55 #include "lldb/Interpreter/OptionGroupUInt64.h"
56 #include "lldb/Interpreter/OptionValueProperties.h"
57 #include "lldb/Interpreter/Options.h"
58 #include "lldb/Interpreter/Property.h"
59 #include "lldb/Symbol/LocateSymbolFile.h"
60 #include "lldb/Symbol/ObjectFile.h"
61 #include "lldb/Target/ABI.h"
62 #include "lldb/Target/DynamicLoader.h"
63 #include "lldb/Target/MemoryRegionInfo.h"
64 #include "lldb/Target/SystemRuntime.h"
65 #include "lldb/Target/Target.h"
66 #include "lldb/Target/TargetList.h"
67 #include "lldb/Target/ThreadPlanCallFunction.h"
68 #include "lldb/Utility/Args.h"
69 #include "lldb/Utility/FileSpec.h"
70 #include "lldb/Utility/Reproducer.h"
71 #include "lldb/Utility/State.h"
72 #include "lldb/Utility/StreamString.h"
73 #include "lldb/Utility/Timer.h"
74 
75 #include "GDBRemoteRegisterContext.h"
76 #include "Plugins/Platform/MacOSX/PlatformRemoteiOS.h"
77 #include "Plugins/Process/Utility/GDBRemoteSignals.h"
78 #include "Plugins/Process/Utility/InferiorCallPOSIX.h"
79 #include "Plugins/Process/Utility/StopInfoMachException.h"
80 #include "ProcessGDBRemote.h"
81 #include "ProcessGDBRemoteLog.h"
82 #include "ThreadGDBRemote.h"
83 #include "lldb/Host/Host.h"
84 #include "lldb/Utility/StringExtractorGDBRemote.h"
85 
86 #include "llvm/ADT/ScopeExit.h"
87 #include "llvm/ADT/StringSwitch.h"
88 #include "llvm/Support/Threading.h"
89 #include "llvm/Support/raw_ostream.h"
90 
91 #define DEBUGSERVER_BASENAME "debugserver"
92 using namespace lldb;
93 using namespace lldb_private;
94 using namespace lldb_private::process_gdb_remote;
95 
96 LLDB_PLUGIN_DEFINE(ProcessGDBRemote)
97 
98 namespace lldb {
99 // Provide a function that can easily dump the packet history if we know a
100 // ProcessGDBRemote * value (which we can get from logs or from debugging). We
101 // need the function in the lldb namespace so it makes it into the final
102 // executable since the LLDB shared library only exports stuff in the lldb
103 // namespace. This allows you to attach with a debugger and call this function
104 // and get the packet history dumped to a file.
DumpProcessGDBRemotePacketHistory(void * p,const char * path)105 void DumpProcessGDBRemotePacketHistory(void *p, const char *path) {
106   auto file = FileSystem::Instance().Open(
107       FileSpec(path), File::eOpenOptionWrite | File::eOpenOptionCanCreate);
108   if (!file) {
109     llvm::consumeError(file.takeError());
110     return;
111   }
112   StreamFile stream(std::move(file.get()));
113   ((ProcessGDBRemote *)p)->GetGDBRemote().DumpHistory(stream);
114 }
115 } // namespace lldb
116 
117 namespace {
118 
119 #define LLDB_PROPERTIES_processgdbremote
120 #include "ProcessGDBRemoteProperties.inc"
121 
122 enum {
123 #define LLDB_PROPERTIES_processgdbremote
124 #include "ProcessGDBRemotePropertiesEnum.inc"
125 };
126 
127 class PluginProperties : public Properties {
128 public:
GetSettingName()129   static ConstString GetSettingName() {
130     return ProcessGDBRemote::GetPluginNameStatic();
131   }
132 
PluginProperties()133   PluginProperties() : Properties() {
134     m_collection_sp = std::make_shared<OptionValueProperties>(GetSettingName());
135     m_collection_sp->Initialize(g_processgdbremote_properties);
136   }
137 
~PluginProperties()138   ~PluginProperties() override {}
139 
GetPacketTimeout()140   uint64_t GetPacketTimeout() {
141     const uint32_t idx = ePropertyPacketTimeout;
142     return m_collection_sp->GetPropertyAtIndexAsUInt64(
143         nullptr, idx, g_processgdbremote_properties[idx].default_uint_value);
144   }
145 
SetPacketTimeout(uint64_t timeout)146   bool SetPacketTimeout(uint64_t timeout) {
147     const uint32_t idx = ePropertyPacketTimeout;
148     return m_collection_sp->SetPropertyAtIndexAsUInt64(nullptr, idx, timeout);
149   }
150 
GetTargetDefinitionFile() const151   FileSpec GetTargetDefinitionFile() const {
152     const uint32_t idx = ePropertyTargetDefinitionFile;
153     return m_collection_sp->GetPropertyAtIndexAsFileSpec(nullptr, idx);
154   }
155 
GetUseSVR4() const156   bool GetUseSVR4() const {
157     const uint32_t idx = ePropertyUseSVR4;
158     return m_collection_sp->GetPropertyAtIndexAsBoolean(
159         nullptr, idx,
160         g_processgdbremote_properties[idx].default_uint_value != 0);
161   }
162 
GetUseGPacketForReading() const163   bool GetUseGPacketForReading() const {
164     const uint32_t idx = ePropertyUseGPacketForReading;
165     return m_collection_sp->GetPropertyAtIndexAsBoolean(nullptr, idx, true);
166   }
167 };
168 
169 typedef std::shared_ptr<PluginProperties> ProcessKDPPropertiesSP;
170 
GetGlobalPluginProperties()171 static const ProcessKDPPropertiesSP &GetGlobalPluginProperties() {
172   static ProcessKDPPropertiesSP g_settings_sp;
173   if (!g_settings_sp)
174     g_settings_sp = std::make_shared<PluginProperties>();
175   return g_settings_sp;
176 }
177 
178 } // namespace
179 
180 // TODO Randomly assigning a port is unsafe.  We should get an unused
181 // ephemeral port from the kernel and make sure we reserve it before passing it
182 // to debugserver.
183 
184 #if defined(__APPLE__)
185 #define LOW_PORT (IPPORT_RESERVED)
186 #define HIGH_PORT (IPPORT_HIFIRSTAUTO)
187 #else
188 #define LOW_PORT (1024u)
189 #define HIGH_PORT (49151u)
190 #endif
191 
GetPluginNameStatic()192 ConstString ProcessGDBRemote::GetPluginNameStatic() {
193   static ConstString g_name("gdb-remote");
194   return g_name;
195 }
196 
GetPluginDescriptionStatic()197 const char *ProcessGDBRemote::GetPluginDescriptionStatic() {
198   return "GDB Remote protocol based debugging plug-in.";
199 }
200 
Terminate()201 void ProcessGDBRemote::Terminate() {
202   PluginManager::UnregisterPlugin(ProcessGDBRemote::CreateInstance);
203 }
204 
205 lldb::ProcessSP
CreateInstance(lldb::TargetSP target_sp,ListenerSP listener_sp,const FileSpec * crash_file_path,bool can_connect)206 ProcessGDBRemote::CreateInstance(lldb::TargetSP target_sp,
207                                  ListenerSP listener_sp,
208                                  const FileSpec *crash_file_path,
209                                  bool can_connect) {
210   lldb::ProcessSP process_sp;
211   if (crash_file_path == nullptr)
212     process_sp = std::make_shared<ProcessGDBRemote>(target_sp, listener_sp);
213   return process_sp;
214 }
215 
CanDebug(lldb::TargetSP target_sp,bool plugin_specified_by_name)216 bool ProcessGDBRemote::CanDebug(lldb::TargetSP target_sp,
217                                 bool plugin_specified_by_name) {
218   if (plugin_specified_by_name)
219     return true;
220 
221   // For now we are just making sure the file exists for a given module
222   Module *exe_module = target_sp->GetExecutableModulePointer();
223   if (exe_module) {
224     ObjectFile *exe_objfile = exe_module->GetObjectFile();
225     // We can't debug core files...
226     switch (exe_objfile->GetType()) {
227     case ObjectFile::eTypeInvalid:
228     case ObjectFile::eTypeCoreFile:
229     case ObjectFile::eTypeDebugInfo:
230     case ObjectFile::eTypeObjectFile:
231     case ObjectFile::eTypeSharedLibrary:
232     case ObjectFile::eTypeStubLibrary:
233     case ObjectFile::eTypeJIT:
234       return false;
235     case ObjectFile::eTypeExecutable:
236     case ObjectFile::eTypeDynamicLinker:
237     case ObjectFile::eTypeUnknown:
238       break;
239     }
240     return FileSystem::Instance().Exists(exe_module->GetFileSpec());
241   }
242   // However, if there is no executable module, we return true since we might
243   // be preparing to attach.
244   return true;
245 }
246 
247 // ProcessGDBRemote constructor
ProcessGDBRemote(lldb::TargetSP target_sp,ListenerSP listener_sp)248 ProcessGDBRemote::ProcessGDBRemote(lldb::TargetSP target_sp,
249                                    ListenerSP listener_sp)
250     : Process(target_sp, listener_sp),
251       m_debugserver_pid(LLDB_INVALID_PROCESS_ID), m_last_stop_packet_mutex(),
252       m_register_info(),
253       m_async_broadcaster(nullptr, "lldb.process.gdb-remote.async-broadcaster"),
254       m_async_listener_sp(
255           Listener::MakeListener("lldb.process.gdb-remote.async-listener")),
256       m_async_thread_state_mutex(), m_thread_ids(), m_thread_pcs(),
257       m_jstopinfo_sp(), m_jthreadsinfo_sp(), m_continue_c_tids(),
258       m_continue_C_tids(), m_continue_s_tids(), m_continue_S_tids(),
259       m_max_memory_size(0), m_remote_stub_max_memory_size(0),
260       m_addr_to_mmap_size(), m_thread_create_bp_sp(),
261       m_waiting_for_attach(false), m_destroy_tried_resuming(false),
262       m_command_sp(), m_breakpoint_pc_offset(0),
263       m_initial_tid(LLDB_INVALID_THREAD_ID), m_replay_mode(false),
264       m_allow_flash_writes(false), m_erased_flash_ranges() {
265   m_async_broadcaster.SetEventName(eBroadcastBitAsyncThreadShouldExit,
266                                    "async thread should exit");
267   m_async_broadcaster.SetEventName(eBroadcastBitAsyncContinue,
268                                    "async thread continue");
269   m_async_broadcaster.SetEventName(eBroadcastBitAsyncThreadDidExit,
270                                    "async thread did exit");
271 
272   if (repro::Generator *g = repro::Reproducer::Instance().GetGenerator()) {
273     repro::GDBRemoteProvider &provider =
274         g->GetOrCreate<repro::GDBRemoteProvider>();
275     m_gdb_comm.SetPacketRecorder(provider.GetNewPacketRecorder());
276   }
277 
278   Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_ASYNC));
279 
280   const uint32_t async_event_mask =
281       eBroadcastBitAsyncContinue | eBroadcastBitAsyncThreadShouldExit;
282 
283   if (m_async_listener_sp->StartListeningForEvents(
284           &m_async_broadcaster, async_event_mask) != async_event_mask) {
285     LLDB_LOGF(log,
286               "ProcessGDBRemote::%s failed to listen for "
287               "m_async_broadcaster events",
288               __FUNCTION__);
289   }
290 
291   const uint32_t gdb_event_mask =
292       Communication::eBroadcastBitReadThreadDidExit |
293       GDBRemoteCommunication::eBroadcastBitGdbReadThreadGotNotify;
294   if (m_async_listener_sp->StartListeningForEvents(
295           &m_gdb_comm, gdb_event_mask) != gdb_event_mask) {
296     LLDB_LOGF(log,
297               "ProcessGDBRemote::%s failed to listen for m_gdb_comm events",
298               __FUNCTION__);
299   }
300 
301   const uint64_t timeout_seconds =
302       GetGlobalPluginProperties()->GetPacketTimeout();
303   if (timeout_seconds > 0)
304     m_gdb_comm.SetPacketTimeout(std::chrono::seconds(timeout_seconds));
305 
306   m_use_g_packet_for_reading =
307       GetGlobalPluginProperties()->GetUseGPacketForReading();
308 }
309 
310 // Destructor
~ProcessGDBRemote()311 ProcessGDBRemote::~ProcessGDBRemote() {
312   //  m_mach_process.UnregisterNotificationCallbacks (this);
313   Clear();
314   // We need to call finalize on the process before destroying ourselves to
315   // make sure all of the broadcaster cleanup goes as planned. If we destruct
316   // this class, then Process::~Process() might have problems trying to fully
317   // destroy the broadcaster.
318   Finalize();
319 
320   // The general Finalize is going to try to destroy the process and that
321   // SHOULD shut down the async thread.  However, if we don't kill it it will
322   // get stranded and its connection will go away so when it wakes up it will
323   // crash.  So kill it for sure here.
324   StopAsyncThread();
325   KillDebugserverProcess();
326 }
327 
328 // PluginInterface
GetPluginName()329 ConstString ProcessGDBRemote::GetPluginName() { return GetPluginNameStatic(); }
330 
GetPluginVersion()331 uint32_t ProcessGDBRemote::GetPluginVersion() { return 1; }
332 
ParsePythonTargetDefinition(const FileSpec & target_definition_fspec)333 bool ProcessGDBRemote::ParsePythonTargetDefinition(
334     const FileSpec &target_definition_fspec) {
335   ScriptInterpreter *interpreter =
336       GetTarget().GetDebugger().GetScriptInterpreter();
337   Status error;
338   StructuredData::ObjectSP module_object_sp(
339       interpreter->LoadPluginModule(target_definition_fspec, error));
340   if (module_object_sp) {
341     StructuredData::DictionarySP target_definition_sp(
342         interpreter->GetDynamicSettings(module_object_sp, &GetTarget(),
343                                         "gdb-server-target-definition", error));
344 
345     if (target_definition_sp) {
346       StructuredData::ObjectSP target_object(
347           target_definition_sp->GetValueForKey("host-info"));
348       if (target_object) {
349         if (auto host_info_dict = target_object->GetAsDictionary()) {
350           StructuredData::ObjectSP triple_value =
351               host_info_dict->GetValueForKey("triple");
352           if (auto triple_string_value = triple_value->GetAsString()) {
353             std::string triple_string =
354                 std::string(triple_string_value->GetValue());
355             ArchSpec host_arch(triple_string.c_str());
356             if (!host_arch.IsCompatibleMatch(GetTarget().GetArchitecture())) {
357               GetTarget().SetArchitecture(host_arch);
358             }
359           }
360         }
361       }
362       m_breakpoint_pc_offset = 0;
363       StructuredData::ObjectSP breakpoint_pc_offset_value =
364           target_definition_sp->GetValueForKey("breakpoint-pc-offset");
365       if (breakpoint_pc_offset_value) {
366         if (auto breakpoint_pc_int_value =
367                 breakpoint_pc_offset_value->GetAsInteger())
368           m_breakpoint_pc_offset = breakpoint_pc_int_value->GetValue();
369       }
370 
371       if (m_register_info.SetRegisterInfo(*target_definition_sp,
372                                           GetTarget().GetArchitecture()) > 0) {
373         return true;
374       }
375     }
376   }
377   return false;
378 }
379 
SplitCommaSeparatedRegisterNumberString(const llvm::StringRef & comma_separated_regiter_numbers,std::vector<uint32_t> & regnums,int base)380 static size_t SplitCommaSeparatedRegisterNumberString(
381     const llvm::StringRef &comma_separated_regiter_numbers,
382     std::vector<uint32_t> &regnums, int base) {
383   regnums.clear();
384   std::pair<llvm::StringRef, llvm::StringRef> value_pair;
385   value_pair.second = comma_separated_regiter_numbers;
386   do {
387     value_pair = value_pair.second.split(',');
388     if (!value_pair.first.empty()) {
389       uint32_t reg = StringConvert::ToUInt32(value_pair.first.str().c_str(),
390                                              LLDB_INVALID_REGNUM, base);
391       if (reg != LLDB_INVALID_REGNUM)
392         regnums.push_back(reg);
393     }
394   } while (!value_pair.second.empty());
395   return regnums.size();
396 }
397 
BuildDynamicRegisterInfo(bool force)398 void ProcessGDBRemote::BuildDynamicRegisterInfo(bool force) {
399   if (!force && m_register_info.GetNumRegisters() > 0)
400     return;
401 
402   m_register_info.Clear();
403 
404   // Check if qHostInfo specified a specific packet timeout for this
405   // connection. If so then lets update our setting so the user knows what the
406   // timeout is and can see it.
407   const auto host_packet_timeout = m_gdb_comm.GetHostDefaultPacketTimeout();
408   if (host_packet_timeout > std::chrono::seconds(0)) {
409     GetGlobalPluginProperties()->SetPacketTimeout(host_packet_timeout.count());
410   }
411 
412   // Register info search order:
413   //     1 - Use the target definition python file if one is specified.
414   //     2 - If the target definition doesn't have any of the info from the
415   //     target.xml (registers) then proceed to read the target.xml.
416   //     3 - Fall back on the qRegisterInfo packets.
417 
418   FileSpec target_definition_fspec =
419       GetGlobalPluginProperties()->GetTargetDefinitionFile();
420   if (!FileSystem::Instance().Exists(target_definition_fspec)) {
421     // If the filename doesn't exist, it may be a ~ not having been expanded -
422     // try to resolve it.
423     FileSystem::Instance().Resolve(target_definition_fspec);
424   }
425   if (target_definition_fspec) {
426     // See if we can get register definitions from a python file
427     if (ParsePythonTargetDefinition(target_definition_fspec)) {
428       return;
429     } else {
430       StreamSP stream_sp = GetTarget().GetDebugger().GetAsyncOutputStream();
431       stream_sp->Printf("ERROR: target description file %s failed to parse.\n",
432                         target_definition_fspec.GetPath().c_str());
433     }
434   }
435 
436   const ArchSpec &target_arch = GetTarget().GetArchitecture();
437   const ArchSpec &remote_host_arch = m_gdb_comm.GetHostArchitecture();
438   const ArchSpec &remote_process_arch = m_gdb_comm.GetProcessArchitecture();
439 
440   // Use the process' architecture instead of the host arch, if available
441   ArchSpec arch_to_use;
442   if (remote_process_arch.IsValid())
443     arch_to_use = remote_process_arch;
444   else
445     arch_to_use = remote_host_arch;
446 
447   if (!arch_to_use.IsValid())
448     arch_to_use = target_arch;
449 
450   if (GetGDBServerRegisterInfo(arch_to_use))
451     return;
452 
453   char packet[128];
454   uint32_t reg_offset = LLDB_INVALID_INDEX32;
455   uint32_t reg_num = 0;
456   for (StringExtractorGDBRemote::ResponseType response_type =
457            StringExtractorGDBRemote::eResponse;
458        response_type == StringExtractorGDBRemote::eResponse; ++reg_num) {
459     const int packet_len =
460         ::snprintf(packet, sizeof(packet), "qRegisterInfo%x", reg_num);
461     assert(packet_len < (int)sizeof(packet));
462     UNUSED_IF_ASSERT_DISABLED(packet_len);
463     StringExtractorGDBRemote response;
464     if (m_gdb_comm.SendPacketAndWaitForResponse(packet, response, false) ==
465         GDBRemoteCommunication::PacketResult::Success) {
466       response_type = response.GetResponseType();
467       if (response_type == StringExtractorGDBRemote::eResponse) {
468         llvm::StringRef name;
469         llvm::StringRef value;
470         ConstString reg_name;
471         ConstString alt_name;
472         ConstString set_name;
473         std::vector<uint32_t> value_regs;
474         std::vector<uint32_t> invalidate_regs;
475         std::vector<uint8_t> dwarf_opcode_bytes;
476         RegisterInfo reg_info = {
477             nullptr,       // Name
478             nullptr,       // Alt name
479             0,             // byte size
480             reg_offset,    // offset
481             eEncodingUint, // encoding
482             eFormatHex,    // format
483             {
484                 LLDB_INVALID_REGNUM, // eh_frame reg num
485                 LLDB_INVALID_REGNUM, // DWARF reg num
486                 LLDB_INVALID_REGNUM, // generic reg num
487                 reg_num,             // process plugin reg num
488                 reg_num              // native register number
489             },
490             nullptr,
491             nullptr,
492             nullptr, // Dwarf expression opcode bytes pointer
493             0        // Dwarf expression opcode bytes length
494         };
495 
496         while (response.GetNameColonValue(name, value)) {
497           if (name.equals("name")) {
498             reg_name.SetString(value);
499           } else if (name.equals("alt-name")) {
500             alt_name.SetString(value);
501           } else if (name.equals("bitsize")) {
502             value.getAsInteger(0, reg_info.byte_size);
503             reg_info.byte_size /= CHAR_BIT;
504           } else if (name.equals("offset")) {
505             if (value.getAsInteger(0, reg_offset))
506               reg_offset = UINT32_MAX;
507           } else if (name.equals("encoding")) {
508             const Encoding encoding = Args::StringToEncoding(value);
509             if (encoding != eEncodingInvalid)
510               reg_info.encoding = encoding;
511           } else if (name.equals("format")) {
512             Format format = eFormatInvalid;
513             if (OptionArgParser::ToFormat(value.str().c_str(), format, nullptr)
514                     .Success())
515               reg_info.format = format;
516             else {
517               reg_info.format =
518                   llvm::StringSwitch<Format>(value)
519                       .Case("binary", eFormatBinary)
520                       .Case("decimal", eFormatDecimal)
521                       .Case("hex", eFormatHex)
522                       .Case("float", eFormatFloat)
523                       .Case("vector-sint8", eFormatVectorOfSInt8)
524                       .Case("vector-uint8", eFormatVectorOfUInt8)
525                       .Case("vector-sint16", eFormatVectorOfSInt16)
526                       .Case("vector-uint16", eFormatVectorOfUInt16)
527                       .Case("vector-sint32", eFormatVectorOfSInt32)
528                       .Case("vector-uint32", eFormatVectorOfUInt32)
529                       .Case("vector-float32", eFormatVectorOfFloat32)
530                       .Case("vector-uint64", eFormatVectorOfUInt64)
531                       .Case("vector-uint128", eFormatVectorOfUInt128)
532                       .Default(eFormatInvalid);
533             }
534           } else if (name.equals("set")) {
535             set_name.SetString(value);
536           } else if (name.equals("gcc") || name.equals("ehframe")) {
537             if (value.getAsInteger(0, reg_info.kinds[eRegisterKindEHFrame]))
538               reg_info.kinds[eRegisterKindEHFrame] = LLDB_INVALID_REGNUM;
539           } else if (name.equals("dwarf")) {
540             if (value.getAsInteger(0, reg_info.kinds[eRegisterKindDWARF]))
541               reg_info.kinds[eRegisterKindDWARF] = LLDB_INVALID_REGNUM;
542           } else if (name.equals("generic")) {
543             reg_info.kinds[eRegisterKindGeneric] =
544                 Args::StringToGenericRegister(value);
545           } else if (name.equals("container-regs")) {
546             SplitCommaSeparatedRegisterNumberString(value, value_regs, 16);
547           } else if (name.equals("invalidate-regs")) {
548             SplitCommaSeparatedRegisterNumberString(value, invalidate_regs, 16);
549           } else if (name.equals("dynamic_size_dwarf_expr_bytes")) {
550             size_t dwarf_opcode_len = value.size() / 2;
551             assert(dwarf_opcode_len > 0);
552 
553             dwarf_opcode_bytes.resize(dwarf_opcode_len);
554             reg_info.dynamic_size_dwarf_len = dwarf_opcode_len;
555 
556             StringExtractor opcode_extractor(value);
557             uint32_t ret_val =
558                 opcode_extractor.GetHexBytesAvail(dwarf_opcode_bytes);
559             assert(dwarf_opcode_len == ret_val);
560             UNUSED_IF_ASSERT_DISABLED(ret_val);
561             reg_info.dynamic_size_dwarf_expr_bytes = dwarf_opcode_bytes.data();
562           }
563         }
564 
565         reg_info.byte_offset = reg_offset;
566         assert(reg_info.byte_size != 0);
567         reg_offset = LLDB_INVALID_INDEX32;
568         if (!value_regs.empty()) {
569           value_regs.push_back(LLDB_INVALID_REGNUM);
570           reg_info.value_regs = value_regs.data();
571         }
572         if (!invalidate_regs.empty()) {
573           invalidate_regs.push_back(LLDB_INVALID_REGNUM);
574           reg_info.invalidate_regs = invalidate_regs.data();
575         }
576 
577         reg_info.name = reg_name.AsCString();
578         // We have to make a temporary ABI here, and not use the GetABI because
579         // this code gets called in DidAttach, when the target architecture
580         // (and consequently the ABI we'll get from the process) may be wrong.
581         if (ABISP abi_sp = ABI::FindPlugin(shared_from_this(), arch_to_use))
582           abi_sp->AugmentRegisterInfo(reg_info);
583 
584         m_register_info.AddRegister(reg_info, reg_name, alt_name, set_name);
585       } else {
586         break; // ensure exit before reg_num is incremented
587       }
588     } else {
589       break;
590     }
591   }
592 
593   if (m_register_info.GetNumRegisters() > 0) {
594     m_register_info.Finalize(GetTarget().GetArchitecture());
595     return;
596   }
597 
598   // We didn't get anything if the accumulated reg_num is zero.  See if we are
599   // debugging ARM and fill with a hard coded register set until we can get an
600   // updated debugserver down on the devices. On the other hand, if the
601   // accumulated reg_num is positive, see if we can add composite registers to
602   // the existing primordial ones.
603   bool from_scratch = (m_register_info.GetNumRegisters() == 0);
604 
605   if (!target_arch.IsValid()) {
606     if (arch_to_use.IsValid() &&
607         (arch_to_use.GetMachine() == llvm::Triple::arm ||
608          arch_to_use.GetMachine() == llvm::Triple::thumb) &&
609         arch_to_use.GetTriple().getVendor() == llvm::Triple::Apple)
610       m_register_info.HardcodeARMRegisters(from_scratch);
611   } else if (target_arch.GetMachine() == llvm::Triple::arm ||
612              target_arch.GetMachine() == llvm::Triple::thumb) {
613     m_register_info.HardcodeARMRegisters(from_scratch);
614   }
615 
616   // At this point, we can finalize our register info.
617   m_register_info.Finalize(GetTarget().GetArchitecture());
618 }
619 
WillLaunch(lldb_private::Module * module)620 Status ProcessGDBRemote::WillLaunch(lldb_private::Module *module) {
621   return WillLaunchOrAttach();
622 }
623 
WillAttachToProcessWithID(lldb::pid_t pid)624 Status ProcessGDBRemote::WillAttachToProcessWithID(lldb::pid_t pid) {
625   return WillLaunchOrAttach();
626 }
627 
WillAttachToProcessWithName(const char * process_name,bool wait_for_launch)628 Status ProcessGDBRemote::WillAttachToProcessWithName(const char *process_name,
629                                                      bool wait_for_launch) {
630   return WillLaunchOrAttach();
631 }
632 
DoConnectRemote(llvm::StringRef remote_url)633 Status ProcessGDBRemote::DoConnectRemote(llvm::StringRef remote_url) {
634   Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
635   Status error(WillLaunchOrAttach());
636 
637   if (error.Fail())
638     return error;
639 
640   if (repro::Reproducer::Instance().IsReplaying())
641     error = ConnectToReplayServer();
642   else
643     error = ConnectToDebugserver(remote_url);
644 
645   if (error.Fail())
646     return error;
647   StartAsyncThread();
648 
649   lldb::pid_t pid = m_gdb_comm.GetCurrentProcessID();
650   if (pid == LLDB_INVALID_PROCESS_ID) {
651     // We don't have a valid process ID, so note that we are connected and
652     // could now request to launch or attach, or get remote process listings...
653     SetPrivateState(eStateConnected);
654   } else {
655     // We have a valid process
656     SetID(pid);
657     GetThreadList();
658     StringExtractorGDBRemote response;
659     if (m_gdb_comm.GetStopReply(response)) {
660       SetLastStopPacket(response);
661 
662       // '?' Packets must be handled differently in non-stop mode
663       if (GetTarget().GetNonStopModeEnabled())
664         HandleStopReplySequence();
665 
666       Target &target = GetTarget();
667       if (!target.GetArchitecture().IsValid()) {
668         if (m_gdb_comm.GetProcessArchitecture().IsValid()) {
669           target.SetArchitecture(m_gdb_comm.GetProcessArchitecture());
670         } else {
671           if (m_gdb_comm.GetHostArchitecture().IsValid()) {
672             target.SetArchitecture(m_gdb_comm.GetHostArchitecture());
673           }
674         }
675       }
676 
677       const StateType state = SetThreadStopInfo(response);
678       if (state != eStateInvalid) {
679         SetPrivateState(state);
680       } else
681         error.SetErrorStringWithFormat(
682             "Process %" PRIu64 " was reported after connecting to "
683             "'%s', but state was not stopped: %s",
684             pid, remote_url.str().c_str(), StateAsCString(state));
685     } else
686       error.SetErrorStringWithFormat("Process %" PRIu64
687                                      " was reported after connecting to '%s', "
688                                      "but no stop reply packet was received",
689                                      pid, remote_url.str().c_str());
690   }
691 
692   LLDB_LOGF(log,
693             "ProcessGDBRemote::%s pid %" PRIu64
694             ": normalizing target architecture initial triple: %s "
695             "(GetTarget().GetArchitecture().IsValid() %s, "
696             "m_gdb_comm.GetHostArchitecture().IsValid(): %s)",
697             __FUNCTION__, GetID(),
698             GetTarget().GetArchitecture().GetTriple().getTriple().c_str(),
699             GetTarget().GetArchitecture().IsValid() ? "true" : "false",
700             m_gdb_comm.GetHostArchitecture().IsValid() ? "true" : "false");
701 
702   if (error.Success() && !GetTarget().GetArchitecture().IsValid() &&
703       m_gdb_comm.GetHostArchitecture().IsValid()) {
704     // Prefer the *process'* architecture over that of the *host*, if
705     // available.
706     if (m_gdb_comm.GetProcessArchitecture().IsValid())
707       GetTarget().SetArchitecture(m_gdb_comm.GetProcessArchitecture());
708     else
709       GetTarget().SetArchitecture(m_gdb_comm.GetHostArchitecture());
710   }
711 
712   LLDB_LOGF(log,
713             "ProcessGDBRemote::%s pid %" PRIu64
714             ": normalized target architecture triple: %s",
715             __FUNCTION__, GetID(),
716             GetTarget().GetArchitecture().GetTriple().getTriple().c_str());
717 
718   if (error.Success()) {
719     PlatformSP platform_sp = GetTarget().GetPlatform();
720     if (platform_sp && platform_sp->IsConnected())
721       SetUnixSignals(platform_sp->GetUnixSignals());
722     else
723       SetUnixSignals(UnixSignals::Create(GetTarget().GetArchitecture()));
724   }
725 
726   return error;
727 }
728 
WillLaunchOrAttach()729 Status ProcessGDBRemote::WillLaunchOrAttach() {
730   Status error;
731   m_stdio_communication.Clear();
732   return error;
733 }
734 
735 // Process Control
DoLaunch(lldb_private::Module * exe_module,ProcessLaunchInfo & launch_info)736 Status ProcessGDBRemote::DoLaunch(lldb_private::Module *exe_module,
737                                   ProcessLaunchInfo &launch_info) {
738   Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
739   Status error;
740 
741   LLDB_LOGF(log, "ProcessGDBRemote::%s() entered", __FUNCTION__);
742 
743   uint32_t launch_flags = launch_info.GetFlags().Get();
744   FileSpec stdin_file_spec{};
745   FileSpec stdout_file_spec{};
746   FileSpec stderr_file_spec{};
747   FileSpec working_dir = launch_info.GetWorkingDirectory();
748 
749   const FileAction *file_action;
750   file_action = launch_info.GetFileActionForFD(STDIN_FILENO);
751   if (file_action) {
752     if (file_action->GetAction() == FileAction::eFileActionOpen)
753       stdin_file_spec = file_action->GetFileSpec();
754   }
755   file_action = launch_info.GetFileActionForFD(STDOUT_FILENO);
756   if (file_action) {
757     if (file_action->GetAction() == FileAction::eFileActionOpen)
758       stdout_file_spec = file_action->GetFileSpec();
759   }
760   file_action = launch_info.GetFileActionForFD(STDERR_FILENO);
761   if (file_action) {
762     if (file_action->GetAction() == FileAction::eFileActionOpen)
763       stderr_file_spec = file_action->GetFileSpec();
764   }
765 
766   if (log) {
767     if (stdin_file_spec || stdout_file_spec || stderr_file_spec)
768       LLDB_LOGF(log,
769                 "ProcessGDBRemote::%s provided with STDIO paths via "
770                 "launch_info: stdin=%s, stdout=%s, stderr=%s",
771                 __FUNCTION__,
772                 stdin_file_spec ? stdin_file_spec.GetCString() : "<null>",
773                 stdout_file_spec ? stdout_file_spec.GetCString() : "<null>",
774                 stderr_file_spec ? stderr_file_spec.GetCString() : "<null>");
775     else
776       LLDB_LOGF(log,
777                 "ProcessGDBRemote::%s no STDIO paths given via launch_info",
778                 __FUNCTION__);
779   }
780 
781   const bool disable_stdio = (launch_flags & eLaunchFlagDisableSTDIO) != 0;
782   if (stdin_file_spec || disable_stdio) {
783     // the inferior will be reading stdin from the specified file or stdio is
784     // completely disabled
785     m_stdin_forward = false;
786   } else {
787     m_stdin_forward = true;
788   }
789 
790   //  ::LogSetBitMask (GDBR_LOG_DEFAULT);
791   //  ::LogSetOptions (LLDB_LOG_OPTION_THREADSAFE |
792   //  LLDB_LOG_OPTION_PREPEND_TIMESTAMP |
793   //  LLDB_LOG_OPTION_PREPEND_PROC_AND_THREAD);
794   //  ::LogSetLogFile ("/dev/stdout");
795 
796   ObjectFile *object_file = exe_module->GetObjectFile();
797   if (object_file) {
798     error = EstablishConnectionIfNeeded(launch_info);
799     if (error.Success()) {
800       PseudoTerminal pty;
801       const bool disable_stdio = (launch_flags & eLaunchFlagDisableSTDIO) != 0;
802 
803       PlatformSP platform_sp(GetTarget().GetPlatform());
804       if (disable_stdio) {
805         // set to /dev/null unless redirected to a file above
806         if (!stdin_file_spec)
807           stdin_file_spec.SetFile(FileSystem::DEV_NULL,
808                                   FileSpec::Style::native);
809         if (!stdout_file_spec)
810           stdout_file_spec.SetFile(FileSystem::DEV_NULL,
811                                    FileSpec::Style::native);
812         if (!stderr_file_spec)
813           stderr_file_spec.SetFile(FileSystem::DEV_NULL,
814                                    FileSpec::Style::native);
815       } else if (platform_sp && platform_sp->IsHost()) {
816         // If the debugserver is local and we aren't disabling STDIO, lets use
817         // a pseudo terminal to instead of relying on the 'O' packets for stdio
818         // since 'O' packets can really slow down debugging if the inferior
819         // does a lot of output.
820         if ((!stdin_file_spec || !stdout_file_spec || !stderr_file_spec) &&
821             !errorToBool(pty.OpenFirstAvailablePrimary(O_RDWR | O_NOCTTY))) {
822           FileSpec secondary_name(pty.GetSecondaryName());
823 
824           if (!stdin_file_spec)
825             stdin_file_spec = secondary_name;
826 
827           if (!stdout_file_spec)
828             stdout_file_spec = secondary_name;
829 
830           if (!stderr_file_spec)
831             stderr_file_spec = secondary_name;
832         }
833         LLDB_LOGF(
834             log,
835             "ProcessGDBRemote::%s adjusted STDIO paths for local platform "
836             "(IsHost() is true) using secondary: stdin=%s, stdout=%s, "
837             "stderr=%s",
838             __FUNCTION__,
839             stdin_file_spec ? stdin_file_spec.GetCString() : "<null>",
840             stdout_file_spec ? stdout_file_spec.GetCString() : "<null>",
841             stderr_file_spec ? stderr_file_spec.GetCString() : "<null>");
842       }
843 
844       LLDB_LOGF(log,
845                 "ProcessGDBRemote::%s final STDIO paths after all "
846                 "adjustments: stdin=%s, stdout=%s, stderr=%s",
847                 __FUNCTION__,
848                 stdin_file_spec ? stdin_file_spec.GetCString() : "<null>",
849                 stdout_file_spec ? stdout_file_spec.GetCString() : "<null>",
850                 stderr_file_spec ? stderr_file_spec.GetCString() : "<null>");
851 
852       if (stdin_file_spec)
853         m_gdb_comm.SetSTDIN(stdin_file_spec);
854       if (stdout_file_spec)
855         m_gdb_comm.SetSTDOUT(stdout_file_spec);
856       if (stderr_file_spec)
857         m_gdb_comm.SetSTDERR(stderr_file_spec);
858 
859       m_gdb_comm.SetDisableASLR(launch_flags & eLaunchFlagDisableASLR);
860       m_gdb_comm.SetDetachOnError(launch_flags & eLaunchFlagDetachOnError);
861 
862       m_gdb_comm.SendLaunchArchPacket(
863           GetTarget().GetArchitecture().GetArchitectureName());
864 
865       const char *launch_event_data = launch_info.GetLaunchEventData();
866       if (launch_event_data != nullptr && *launch_event_data != '\0')
867         m_gdb_comm.SendLaunchEventDataPacket(launch_event_data);
868 
869       if (working_dir) {
870         m_gdb_comm.SetWorkingDir(working_dir);
871       }
872 
873       // Send the environment and the program + arguments after we connect
874       m_gdb_comm.SendEnvironment(launch_info.GetEnvironment());
875 
876       {
877         // Scope for the scoped timeout object
878         GDBRemoteCommunication::ScopedTimeout timeout(m_gdb_comm,
879                                                       std::chrono::seconds(10));
880 
881         int arg_packet_err = m_gdb_comm.SendArgumentsPacket(launch_info);
882         if (arg_packet_err == 0) {
883           std::string error_str;
884           if (m_gdb_comm.GetLaunchSuccess(error_str)) {
885             SetID(m_gdb_comm.GetCurrentProcessID());
886           } else {
887             error.SetErrorString(error_str.c_str());
888           }
889         } else {
890           error.SetErrorStringWithFormat("'A' packet returned an error: %i",
891                                          arg_packet_err);
892         }
893       }
894 
895       if (GetID() == LLDB_INVALID_PROCESS_ID) {
896         LLDB_LOGF(log, "failed to connect to debugserver: %s",
897                   error.AsCString());
898         KillDebugserverProcess();
899         return error;
900       }
901 
902       StringExtractorGDBRemote response;
903       if (m_gdb_comm.GetStopReply(response)) {
904         SetLastStopPacket(response);
905         // '?' Packets must be handled differently in non-stop mode
906         if (GetTarget().GetNonStopModeEnabled())
907           HandleStopReplySequence();
908 
909         const ArchSpec &process_arch = m_gdb_comm.GetProcessArchitecture();
910 
911         if (process_arch.IsValid()) {
912           GetTarget().MergeArchitecture(process_arch);
913         } else {
914           const ArchSpec &host_arch = m_gdb_comm.GetHostArchitecture();
915           if (host_arch.IsValid())
916             GetTarget().MergeArchitecture(host_arch);
917         }
918 
919         SetPrivateState(SetThreadStopInfo(response));
920 
921         if (!disable_stdio) {
922           if (pty.GetPrimaryFileDescriptor() != PseudoTerminal::invalid_fd)
923             SetSTDIOFileDescriptor(pty.ReleasePrimaryFileDescriptor());
924         }
925       }
926     } else {
927       LLDB_LOGF(log, "failed to connect to debugserver: %s", error.AsCString());
928     }
929   } else {
930     // Set our user ID to an invalid process ID.
931     SetID(LLDB_INVALID_PROCESS_ID);
932     error.SetErrorStringWithFormat(
933         "failed to get object file from '%s' for arch %s",
934         exe_module->GetFileSpec().GetFilename().AsCString(),
935         exe_module->GetArchitecture().GetArchitectureName());
936   }
937   return error;
938 }
939 
ConnectToDebugserver(llvm::StringRef connect_url)940 Status ProcessGDBRemote::ConnectToDebugserver(llvm::StringRef connect_url) {
941   Status error;
942   // Only connect if we have a valid connect URL
943   Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
944 
945   if (!connect_url.empty()) {
946     LLDB_LOGF(log, "ProcessGDBRemote::%s Connecting to %s", __FUNCTION__,
947               connect_url.str().c_str());
948     std::unique_ptr<ConnectionFileDescriptor> conn_up(
949         new ConnectionFileDescriptor());
950     if (conn_up) {
951       const uint32_t max_retry_count = 50;
952       uint32_t retry_count = 0;
953       while (!m_gdb_comm.IsConnected()) {
954         if (conn_up->Connect(connect_url, &error) == eConnectionStatusSuccess) {
955           m_gdb_comm.SetConnection(std::move(conn_up));
956           break;
957         } else if (error.WasInterrupted()) {
958           // If we were interrupted, don't keep retrying.
959           break;
960         }
961 
962         retry_count++;
963 
964         if (retry_count >= max_retry_count)
965           break;
966 
967         std::this_thread::sleep_for(std::chrono::milliseconds(100));
968       }
969     }
970   }
971 
972   if (!m_gdb_comm.IsConnected()) {
973     if (error.Success())
974       error.SetErrorString("not connected to remote gdb server");
975     return error;
976   }
977 
978   // Start the communications read thread so all incoming data can be parsed
979   // into packets and queued as they arrive.
980   if (GetTarget().GetNonStopModeEnabled())
981     m_gdb_comm.StartReadThread();
982 
983   // We always seem to be able to open a connection to a local port so we need
984   // to make sure we can then send data to it. If we can't then we aren't
985   // actually connected to anything, so try and do the handshake with the
986   // remote GDB server and make sure that goes alright.
987   if (!m_gdb_comm.HandshakeWithServer(&error)) {
988     m_gdb_comm.Disconnect();
989     if (error.Success())
990       error.SetErrorString("not connected to remote gdb server");
991     return error;
992   }
993 
994   // Send $QNonStop:1 packet on startup if required
995   if (GetTarget().GetNonStopModeEnabled())
996     GetTarget().SetNonStopModeEnabled(m_gdb_comm.SetNonStopMode(true));
997 
998   m_gdb_comm.GetEchoSupported();
999   m_gdb_comm.GetThreadSuffixSupported();
1000   m_gdb_comm.GetListThreadsInStopReplySupported();
1001   m_gdb_comm.GetHostInfo();
1002   m_gdb_comm.GetVContSupported('c');
1003   m_gdb_comm.GetVAttachOrWaitSupported();
1004   m_gdb_comm.EnableErrorStringInPacket();
1005 
1006   // Ask the remote server for the default thread id
1007   if (GetTarget().GetNonStopModeEnabled())
1008     m_gdb_comm.GetDefaultThreadId(m_initial_tid);
1009 
1010   size_t num_cmds = GetExtraStartupCommands().GetArgumentCount();
1011   for (size_t idx = 0; idx < num_cmds; idx++) {
1012     StringExtractorGDBRemote response;
1013     m_gdb_comm.SendPacketAndWaitForResponse(
1014         GetExtraStartupCommands().GetArgumentAtIndex(idx), response, false);
1015   }
1016   return error;
1017 }
1018 
DidLaunchOrAttach(ArchSpec & process_arch)1019 void ProcessGDBRemote::DidLaunchOrAttach(ArchSpec &process_arch) {
1020   Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
1021   BuildDynamicRegisterInfo(false);
1022 
1023   // See if the GDB server supports qHostInfo or qProcessInfo packets. Prefer
1024   // qProcessInfo as it will be more specific to our process.
1025 
1026   const ArchSpec &remote_process_arch = m_gdb_comm.GetProcessArchitecture();
1027   if (remote_process_arch.IsValid()) {
1028     process_arch = remote_process_arch;
1029     LLDB_LOG(log, "gdb-remote had process architecture, using {0} {1}",
1030              process_arch.GetArchitectureName(),
1031              process_arch.GetTriple().getTriple());
1032   } else {
1033     process_arch = m_gdb_comm.GetHostArchitecture();
1034     LLDB_LOG(log,
1035              "gdb-remote did not have process architecture, using gdb-remote "
1036              "host architecture {0} {1}",
1037              process_arch.GetArchitectureName(),
1038              process_arch.GetTriple().getTriple());
1039   }
1040 
1041   if (process_arch.IsValid()) {
1042     const ArchSpec &target_arch = GetTarget().GetArchitecture();
1043     if (target_arch.IsValid()) {
1044       LLDB_LOG(log, "analyzing target arch, currently {0} {1}",
1045                target_arch.GetArchitectureName(),
1046                target_arch.GetTriple().getTriple());
1047 
1048       // If the remote host is ARM and we have apple as the vendor, then
1049       // ARM executables and shared libraries can have mixed ARM
1050       // architectures.
1051       // You can have an armv6 executable, and if the host is armv7, then the
1052       // system will load the best possible architecture for all shared
1053       // libraries it has, so we really need to take the remote host
1054       // architecture as our defacto architecture in this case.
1055 
1056       if ((process_arch.GetMachine() == llvm::Triple::arm ||
1057            process_arch.GetMachine() == llvm::Triple::thumb) &&
1058           process_arch.GetTriple().getVendor() == llvm::Triple::Apple) {
1059         GetTarget().SetArchitecture(process_arch);
1060         LLDB_LOG(log,
1061                  "remote process is ARM/Apple, "
1062                  "setting target arch to {0} {1}",
1063                  process_arch.GetArchitectureName(),
1064                  process_arch.GetTriple().getTriple());
1065       } else {
1066         // Fill in what is missing in the triple
1067         const llvm::Triple &remote_triple = process_arch.GetTriple();
1068         llvm::Triple new_target_triple = target_arch.GetTriple();
1069         if (new_target_triple.getVendorName().size() == 0) {
1070           new_target_triple.setVendor(remote_triple.getVendor());
1071 
1072           if (new_target_triple.getOSName().size() == 0) {
1073             new_target_triple.setOS(remote_triple.getOS());
1074 
1075             if (new_target_triple.getEnvironmentName().size() == 0)
1076               new_target_triple.setEnvironment(remote_triple.getEnvironment());
1077           }
1078 
1079           ArchSpec new_target_arch = target_arch;
1080           new_target_arch.SetTriple(new_target_triple);
1081           GetTarget().SetArchitecture(new_target_arch);
1082         }
1083       }
1084 
1085       LLDB_LOG(log,
1086                "final target arch after adjustments for remote architecture: "
1087                "{0} {1}",
1088                target_arch.GetArchitectureName(),
1089                target_arch.GetTriple().getTriple());
1090     } else {
1091       // The target doesn't have a valid architecture yet, set it from the
1092       // architecture we got from the remote GDB server
1093       GetTarget().SetArchitecture(process_arch);
1094     }
1095   }
1096 
1097   MaybeLoadExecutableModule();
1098 
1099   // Find out which StructuredDataPlugins are supported by the debug monitor.
1100   // These plugins transmit data over async $J packets.
1101   if (StructuredData::Array *supported_packets =
1102           m_gdb_comm.GetSupportedStructuredDataPlugins())
1103     MapSupportedStructuredDataPlugins(*supported_packets);
1104 }
1105 
MaybeLoadExecutableModule()1106 void ProcessGDBRemote::MaybeLoadExecutableModule() {
1107   ModuleSP module_sp = GetTarget().GetExecutableModule();
1108   if (!module_sp)
1109     return;
1110 
1111   llvm::Optional<QOffsets> offsets = m_gdb_comm.GetQOffsets();
1112   if (!offsets)
1113     return;
1114 
1115   bool is_uniform =
1116       size_t(llvm::count(offsets->offsets, offsets->offsets[0])) ==
1117       offsets->offsets.size();
1118   if (!is_uniform)
1119     return; // TODO: Handle non-uniform responses.
1120 
1121   bool changed = false;
1122   module_sp->SetLoadAddress(GetTarget(), offsets->offsets[0],
1123                             /*value_is_offset=*/true, changed);
1124   if (changed) {
1125     ModuleList list;
1126     list.Append(module_sp);
1127     m_process->GetTarget().ModulesDidLoad(list);
1128   }
1129 }
1130 
DidLaunch()1131 void ProcessGDBRemote::DidLaunch() {
1132   ArchSpec process_arch;
1133   DidLaunchOrAttach(process_arch);
1134 }
1135 
DoAttachToProcessWithID(lldb::pid_t attach_pid,const ProcessAttachInfo & attach_info)1136 Status ProcessGDBRemote::DoAttachToProcessWithID(
1137     lldb::pid_t attach_pid, const ProcessAttachInfo &attach_info) {
1138   Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
1139   Status error;
1140 
1141   LLDB_LOGF(log, "ProcessGDBRemote::%s()", __FUNCTION__);
1142 
1143   // Clear out and clean up from any current state
1144   Clear();
1145   if (attach_pid != LLDB_INVALID_PROCESS_ID) {
1146     error = EstablishConnectionIfNeeded(attach_info);
1147     if (error.Success()) {
1148       m_gdb_comm.SetDetachOnError(attach_info.GetDetachOnError());
1149 
1150       char packet[64];
1151       const int packet_len =
1152           ::snprintf(packet, sizeof(packet), "vAttach;%" PRIx64, attach_pid);
1153       SetID(attach_pid);
1154       m_async_broadcaster.BroadcastEvent(
1155           eBroadcastBitAsyncContinue, new EventDataBytes(packet, packet_len));
1156     } else
1157       SetExitStatus(-1, error.AsCString());
1158   }
1159 
1160   return error;
1161 }
1162 
DoAttachToProcessWithName(const char * process_name,const ProcessAttachInfo & attach_info)1163 Status ProcessGDBRemote::DoAttachToProcessWithName(
1164     const char *process_name, const ProcessAttachInfo &attach_info) {
1165   Status error;
1166   // Clear out and clean up from any current state
1167   Clear();
1168 
1169   if (process_name && process_name[0]) {
1170     error = EstablishConnectionIfNeeded(attach_info);
1171     if (error.Success()) {
1172       StreamString packet;
1173 
1174       m_gdb_comm.SetDetachOnError(attach_info.GetDetachOnError());
1175 
1176       if (attach_info.GetWaitForLaunch()) {
1177         if (!m_gdb_comm.GetVAttachOrWaitSupported()) {
1178           packet.PutCString("vAttachWait");
1179         } else {
1180           if (attach_info.GetIgnoreExisting())
1181             packet.PutCString("vAttachWait");
1182           else
1183             packet.PutCString("vAttachOrWait");
1184         }
1185       } else
1186         packet.PutCString("vAttachName");
1187       packet.PutChar(';');
1188       packet.PutBytesAsRawHex8(process_name, strlen(process_name),
1189                                endian::InlHostByteOrder(),
1190                                endian::InlHostByteOrder());
1191 
1192       m_async_broadcaster.BroadcastEvent(
1193           eBroadcastBitAsyncContinue,
1194           new EventDataBytes(packet.GetString().data(), packet.GetSize()));
1195 
1196     } else
1197       SetExitStatus(-1, error.AsCString());
1198   }
1199   return error;
1200 }
1201 
StartTrace(const TraceOptions & options,Status & error)1202 lldb::user_id_t ProcessGDBRemote::StartTrace(const TraceOptions &options,
1203                                              Status &error) {
1204   return m_gdb_comm.SendStartTracePacket(options, error);
1205 }
1206 
StopTrace(lldb::user_id_t uid,lldb::tid_t thread_id)1207 Status ProcessGDBRemote::StopTrace(lldb::user_id_t uid, lldb::tid_t thread_id) {
1208   return m_gdb_comm.SendStopTracePacket(uid, thread_id);
1209 }
1210 
GetData(lldb::user_id_t uid,lldb::tid_t thread_id,llvm::MutableArrayRef<uint8_t> & buffer,size_t offset)1211 Status ProcessGDBRemote::GetData(lldb::user_id_t uid, lldb::tid_t thread_id,
1212                                  llvm::MutableArrayRef<uint8_t> &buffer,
1213                                  size_t offset) {
1214   return m_gdb_comm.SendGetDataPacket(uid, thread_id, buffer, offset);
1215 }
1216 
GetMetaData(lldb::user_id_t uid,lldb::tid_t thread_id,llvm::MutableArrayRef<uint8_t> & buffer,size_t offset)1217 Status ProcessGDBRemote::GetMetaData(lldb::user_id_t uid, lldb::tid_t thread_id,
1218                                      llvm::MutableArrayRef<uint8_t> &buffer,
1219                                      size_t offset) {
1220   return m_gdb_comm.SendGetMetaDataPacket(uid, thread_id, buffer, offset);
1221 }
1222 
GetTraceConfig(lldb::user_id_t uid,TraceOptions & options)1223 Status ProcessGDBRemote::GetTraceConfig(lldb::user_id_t uid,
1224                                         TraceOptions &options) {
1225   return m_gdb_comm.SendGetTraceConfigPacket(uid, options);
1226 }
1227 
GetSupportedTraceType()1228 llvm::Expected<TraceTypeInfo> ProcessGDBRemote::GetSupportedTraceType() {
1229   return m_gdb_comm.SendGetSupportedTraceType();
1230 }
1231 
DidExit()1232 void ProcessGDBRemote::DidExit() {
1233   // When we exit, disconnect from the GDB server communications
1234   m_gdb_comm.Disconnect();
1235 }
1236 
DidAttach(ArchSpec & process_arch)1237 void ProcessGDBRemote::DidAttach(ArchSpec &process_arch) {
1238   // If you can figure out what the architecture is, fill it in here.
1239   process_arch.Clear();
1240   DidLaunchOrAttach(process_arch);
1241 }
1242 
WillResume()1243 Status ProcessGDBRemote::WillResume() {
1244   m_continue_c_tids.clear();
1245   m_continue_C_tids.clear();
1246   m_continue_s_tids.clear();
1247   m_continue_S_tids.clear();
1248   m_jstopinfo_sp.reset();
1249   m_jthreadsinfo_sp.reset();
1250   return Status();
1251 }
1252 
DoResume()1253 Status ProcessGDBRemote::DoResume() {
1254   Status error;
1255   Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
1256   LLDB_LOGF(log, "ProcessGDBRemote::Resume()");
1257 
1258   ListenerSP listener_sp(
1259       Listener::MakeListener("gdb-remote.resume-packet-sent"));
1260   if (listener_sp->StartListeningForEvents(
1261           &m_gdb_comm, GDBRemoteCommunication::eBroadcastBitRunPacketSent)) {
1262     listener_sp->StartListeningForEvents(
1263         &m_async_broadcaster,
1264         ProcessGDBRemote::eBroadcastBitAsyncThreadDidExit);
1265 
1266     const size_t num_threads = GetThreadList().GetSize();
1267 
1268     StreamString continue_packet;
1269     bool continue_packet_error = false;
1270     if (m_gdb_comm.HasAnyVContSupport()) {
1271       if (!GetTarget().GetNonStopModeEnabled() &&
1272           (m_continue_c_tids.size() == num_threads ||
1273            (m_continue_c_tids.empty() && m_continue_C_tids.empty() &&
1274             m_continue_s_tids.empty() && m_continue_S_tids.empty()))) {
1275         // All threads are continuing, just send a "c" packet
1276         continue_packet.PutCString("c");
1277       } else {
1278         continue_packet.PutCString("vCont");
1279 
1280         if (!m_continue_c_tids.empty()) {
1281           if (m_gdb_comm.GetVContSupported('c')) {
1282             for (tid_collection::const_iterator
1283                      t_pos = m_continue_c_tids.begin(),
1284                      t_end = m_continue_c_tids.end();
1285                  t_pos != t_end; ++t_pos)
1286               continue_packet.Printf(";c:%4.4" PRIx64, *t_pos);
1287           } else
1288             continue_packet_error = true;
1289         }
1290 
1291         if (!continue_packet_error && !m_continue_C_tids.empty()) {
1292           if (m_gdb_comm.GetVContSupported('C')) {
1293             for (tid_sig_collection::const_iterator
1294                      s_pos = m_continue_C_tids.begin(),
1295                      s_end = m_continue_C_tids.end();
1296                  s_pos != s_end; ++s_pos)
1297               continue_packet.Printf(";C%2.2x:%4.4" PRIx64, s_pos->second,
1298                                      s_pos->first);
1299           } else
1300             continue_packet_error = true;
1301         }
1302 
1303         if (!continue_packet_error && !m_continue_s_tids.empty()) {
1304           if (m_gdb_comm.GetVContSupported('s')) {
1305             for (tid_collection::const_iterator
1306                      t_pos = m_continue_s_tids.begin(),
1307                      t_end = m_continue_s_tids.end();
1308                  t_pos != t_end; ++t_pos)
1309               continue_packet.Printf(";s:%4.4" PRIx64, *t_pos);
1310           } else
1311             continue_packet_error = true;
1312         }
1313 
1314         if (!continue_packet_error && !m_continue_S_tids.empty()) {
1315           if (m_gdb_comm.GetVContSupported('S')) {
1316             for (tid_sig_collection::const_iterator
1317                      s_pos = m_continue_S_tids.begin(),
1318                      s_end = m_continue_S_tids.end();
1319                  s_pos != s_end; ++s_pos)
1320               continue_packet.Printf(";S%2.2x:%4.4" PRIx64, s_pos->second,
1321                                      s_pos->first);
1322           } else
1323             continue_packet_error = true;
1324         }
1325 
1326         if (continue_packet_error)
1327           continue_packet.Clear();
1328       }
1329     } else
1330       continue_packet_error = true;
1331 
1332     if (continue_packet_error) {
1333       // Either no vCont support, or we tried to use part of the vCont packet
1334       // that wasn't supported by the remote GDB server. We need to try and
1335       // make a simple packet that can do our continue
1336       const size_t num_continue_c_tids = m_continue_c_tids.size();
1337       const size_t num_continue_C_tids = m_continue_C_tids.size();
1338       const size_t num_continue_s_tids = m_continue_s_tids.size();
1339       const size_t num_continue_S_tids = m_continue_S_tids.size();
1340       if (num_continue_c_tids > 0) {
1341         if (num_continue_c_tids == num_threads) {
1342           // All threads are resuming...
1343           m_gdb_comm.SetCurrentThreadForRun(-1);
1344           continue_packet.PutChar('c');
1345           continue_packet_error = false;
1346         } else if (num_continue_c_tids == 1 && num_continue_C_tids == 0 &&
1347                    num_continue_s_tids == 0 && num_continue_S_tids == 0) {
1348           // Only one thread is continuing
1349           m_gdb_comm.SetCurrentThreadForRun(m_continue_c_tids.front());
1350           continue_packet.PutChar('c');
1351           continue_packet_error = false;
1352         }
1353       }
1354 
1355       if (continue_packet_error && num_continue_C_tids > 0) {
1356         if ((num_continue_C_tids + num_continue_c_tids) == num_threads &&
1357             num_continue_C_tids > 0 && num_continue_s_tids == 0 &&
1358             num_continue_S_tids == 0) {
1359           const int continue_signo = m_continue_C_tids.front().second;
1360           // Only one thread is continuing
1361           if (num_continue_C_tids > 1) {
1362             // More that one thread with a signal, yet we don't have vCont
1363             // support and we are being asked to resume each thread with a
1364             // signal, we need to make sure they are all the same signal, or we
1365             // can't issue the continue accurately with the current support...
1366             if (num_continue_C_tids > 1) {
1367               continue_packet_error = false;
1368               for (size_t i = 1; i < m_continue_C_tids.size(); ++i) {
1369                 if (m_continue_C_tids[i].second != continue_signo)
1370                   continue_packet_error = true;
1371               }
1372             }
1373             if (!continue_packet_error)
1374               m_gdb_comm.SetCurrentThreadForRun(-1);
1375           } else {
1376             // Set the continue thread ID
1377             continue_packet_error = false;
1378             m_gdb_comm.SetCurrentThreadForRun(m_continue_C_tids.front().first);
1379           }
1380           if (!continue_packet_error) {
1381             // Add threads continuing with the same signo...
1382             continue_packet.Printf("C%2.2x", continue_signo);
1383           }
1384         }
1385       }
1386 
1387       if (continue_packet_error && num_continue_s_tids > 0) {
1388         if (num_continue_s_tids == num_threads) {
1389           // All threads are resuming...
1390           m_gdb_comm.SetCurrentThreadForRun(-1);
1391 
1392           // If in Non-Stop-Mode use vCont when stepping
1393           if (GetTarget().GetNonStopModeEnabled()) {
1394             if (m_gdb_comm.GetVContSupported('s'))
1395               continue_packet.PutCString("vCont;s");
1396             else
1397               continue_packet.PutChar('s');
1398           } else
1399             continue_packet.PutChar('s');
1400 
1401           continue_packet_error = false;
1402         } else if (num_continue_c_tids == 0 && num_continue_C_tids == 0 &&
1403                    num_continue_s_tids == 1 && num_continue_S_tids == 0) {
1404           // Only one thread is stepping
1405           m_gdb_comm.SetCurrentThreadForRun(m_continue_s_tids.front());
1406           continue_packet.PutChar('s');
1407           continue_packet_error = false;
1408         }
1409       }
1410 
1411       if (!continue_packet_error && num_continue_S_tids > 0) {
1412         if (num_continue_S_tids == num_threads) {
1413           const int step_signo = m_continue_S_tids.front().second;
1414           // Are all threads trying to step with the same signal?
1415           continue_packet_error = false;
1416           if (num_continue_S_tids > 1) {
1417             for (size_t i = 1; i < num_threads; ++i) {
1418               if (m_continue_S_tids[i].second != step_signo)
1419                 continue_packet_error = true;
1420             }
1421           }
1422           if (!continue_packet_error) {
1423             // Add threads stepping with the same signo...
1424             m_gdb_comm.SetCurrentThreadForRun(-1);
1425             continue_packet.Printf("S%2.2x", step_signo);
1426           }
1427         } else if (num_continue_c_tids == 0 && num_continue_C_tids == 0 &&
1428                    num_continue_s_tids == 0 && num_continue_S_tids == 1) {
1429           // Only one thread is stepping with signal
1430           m_gdb_comm.SetCurrentThreadForRun(m_continue_S_tids.front().first);
1431           continue_packet.Printf("S%2.2x", m_continue_S_tids.front().second);
1432           continue_packet_error = false;
1433         }
1434       }
1435     }
1436 
1437     if (continue_packet_error) {
1438       error.SetErrorString("can't make continue packet for this resume");
1439     } else {
1440       EventSP event_sp;
1441       if (!m_async_thread.IsJoinable()) {
1442         error.SetErrorString("Trying to resume but the async thread is dead.");
1443         LLDB_LOGF(log, "ProcessGDBRemote::DoResume: Trying to resume but the "
1444                        "async thread is dead.");
1445         return error;
1446       }
1447 
1448       m_async_broadcaster.BroadcastEvent(
1449           eBroadcastBitAsyncContinue,
1450           new EventDataBytes(continue_packet.GetString().data(),
1451                              continue_packet.GetSize()));
1452 
1453       if (!listener_sp->GetEvent(event_sp, std::chrono::seconds(5))) {
1454         error.SetErrorString("Resume timed out.");
1455         LLDB_LOGF(log, "ProcessGDBRemote::DoResume: Resume timed out.");
1456       } else if (event_sp->BroadcasterIs(&m_async_broadcaster)) {
1457         error.SetErrorString("Broadcast continue, but the async thread was "
1458                              "killed before we got an ack back.");
1459         LLDB_LOGF(log,
1460                   "ProcessGDBRemote::DoResume: Broadcast continue, but the "
1461                   "async thread was killed before we got an ack back.");
1462         return error;
1463       }
1464     }
1465   }
1466 
1467   return error;
1468 }
1469 
HandleStopReplySequence()1470 void ProcessGDBRemote::HandleStopReplySequence() {
1471   while (true) {
1472     // Send vStopped
1473     StringExtractorGDBRemote response;
1474     m_gdb_comm.SendPacketAndWaitForResponse("vStopped", response, false);
1475 
1476     // OK represents end of signal list
1477     if (response.IsOKResponse())
1478       break;
1479 
1480     // If not OK or a normal packet we have a problem
1481     if (!response.IsNormalResponse())
1482       break;
1483 
1484     SetLastStopPacket(response);
1485   }
1486 }
1487 
ClearThreadIDList()1488 void ProcessGDBRemote::ClearThreadIDList() {
1489   std::lock_guard<std::recursive_mutex> guard(m_thread_list_real.GetMutex());
1490   m_thread_ids.clear();
1491   m_thread_pcs.clear();
1492 }
1493 
1494 size_t
UpdateThreadIDsFromStopReplyThreadsValue(std::string & value)1495 ProcessGDBRemote::UpdateThreadIDsFromStopReplyThreadsValue(std::string &value) {
1496   m_thread_ids.clear();
1497   size_t comma_pos;
1498   lldb::tid_t tid;
1499   while ((comma_pos = value.find(',')) != std::string::npos) {
1500     value[comma_pos] = '\0';
1501     // thread in big endian hex
1502     tid = StringConvert::ToUInt64(value.c_str(), LLDB_INVALID_THREAD_ID, 16);
1503     if (tid != LLDB_INVALID_THREAD_ID)
1504       m_thread_ids.push_back(tid);
1505     value.erase(0, comma_pos + 1);
1506   }
1507   tid = StringConvert::ToUInt64(value.c_str(), LLDB_INVALID_THREAD_ID, 16);
1508   if (tid != LLDB_INVALID_THREAD_ID)
1509     m_thread_ids.push_back(tid);
1510   return m_thread_ids.size();
1511 }
1512 
1513 size_t
UpdateThreadPCsFromStopReplyThreadsValue(std::string & value)1514 ProcessGDBRemote::UpdateThreadPCsFromStopReplyThreadsValue(std::string &value) {
1515   m_thread_pcs.clear();
1516   size_t comma_pos;
1517   lldb::addr_t pc;
1518   while ((comma_pos = value.find(',')) != std::string::npos) {
1519     value[comma_pos] = '\0';
1520     pc = StringConvert::ToUInt64(value.c_str(), LLDB_INVALID_ADDRESS, 16);
1521     if (pc != LLDB_INVALID_ADDRESS)
1522       m_thread_pcs.push_back(pc);
1523     value.erase(0, comma_pos + 1);
1524   }
1525   pc = StringConvert::ToUInt64(value.c_str(), LLDB_INVALID_ADDRESS, 16);
1526   if (pc != LLDB_INVALID_THREAD_ID)
1527     m_thread_pcs.push_back(pc);
1528   return m_thread_pcs.size();
1529 }
1530 
UpdateThreadIDList()1531 bool ProcessGDBRemote::UpdateThreadIDList() {
1532   std::lock_guard<std::recursive_mutex> guard(m_thread_list_real.GetMutex());
1533 
1534   if (m_jthreadsinfo_sp) {
1535     // If we have the JSON threads info, we can get the thread list from that
1536     StructuredData::Array *thread_infos = m_jthreadsinfo_sp->GetAsArray();
1537     if (thread_infos && thread_infos->GetSize() > 0) {
1538       m_thread_ids.clear();
1539       m_thread_pcs.clear();
1540       thread_infos->ForEach([this](StructuredData::Object *object) -> bool {
1541         StructuredData::Dictionary *thread_dict = object->GetAsDictionary();
1542         if (thread_dict) {
1543           // Set the thread stop info from the JSON dictionary
1544           SetThreadStopInfo(thread_dict);
1545           lldb::tid_t tid = LLDB_INVALID_THREAD_ID;
1546           if (thread_dict->GetValueForKeyAsInteger<lldb::tid_t>("tid", tid))
1547             m_thread_ids.push_back(tid);
1548         }
1549         return true; // Keep iterating through all thread_info objects
1550       });
1551     }
1552     if (!m_thread_ids.empty())
1553       return true;
1554   } else {
1555     // See if we can get the thread IDs from the current stop reply packets
1556     // that might contain a "threads" key/value pair
1557 
1558     // Lock the thread stack while we access it
1559     // Mutex::Locker stop_stack_lock(m_last_stop_packet_mutex);
1560     std::unique_lock<std::recursive_mutex> stop_stack_lock(
1561         m_last_stop_packet_mutex, std::defer_lock);
1562     if (stop_stack_lock.try_lock()) {
1563       // Get the number of stop packets on the stack
1564       int nItems = m_stop_packet_stack.size();
1565       // Iterate over them
1566       for (int i = 0; i < nItems; i++) {
1567         // Get the thread stop info
1568         StringExtractorGDBRemote &stop_info = m_stop_packet_stack[i];
1569         const std::string &stop_info_str =
1570             std::string(stop_info.GetStringRef());
1571 
1572         m_thread_pcs.clear();
1573         const size_t thread_pcs_pos = stop_info_str.find(";thread-pcs:");
1574         if (thread_pcs_pos != std::string::npos) {
1575           const size_t start = thread_pcs_pos + strlen(";thread-pcs:");
1576           const size_t end = stop_info_str.find(';', start);
1577           if (end != std::string::npos) {
1578             std::string value = stop_info_str.substr(start, end - start);
1579             UpdateThreadPCsFromStopReplyThreadsValue(value);
1580           }
1581         }
1582 
1583         const size_t threads_pos = stop_info_str.find(";threads:");
1584         if (threads_pos != std::string::npos) {
1585           const size_t start = threads_pos + strlen(";threads:");
1586           const size_t end = stop_info_str.find(';', start);
1587           if (end != std::string::npos) {
1588             std::string value = stop_info_str.substr(start, end - start);
1589             if (UpdateThreadIDsFromStopReplyThreadsValue(value))
1590               return true;
1591           }
1592         }
1593       }
1594     }
1595   }
1596 
1597   bool sequence_mutex_unavailable = false;
1598   m_gdb_comm.GetCurrentThreadIDs(m_thread_ids, sequence_mutex_unavailable);
1599   if (sequence_mutex_unavailable) {
1600     return false; // We just didn't get the list
1601   }
1602   return true;
1603 }
1604 
UpdateThreadList(ThreadList & old_thread_list,ThreadList & new_thread_list)1605 bool ProcessGDBRemote::UpdateThreadList(ThreadList &old_thread_list,
1606                                         ThreadList &new_thread_list) {
1607   // locker will keep a mutex locked until it goes out of scope
1608   Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_THREAD));
1609   LLDB_LOGV(log, "pid = {0}", GetID());
1610 
1611   size_t num_thread_ids = m_thread_ids.size();
1612   // The "m_thread_ids" thread ID list should always be updated after each stop
1613   // reply packet, but in case it isn't, update it here.
1614   if (num_thread_ids == 0) {
1615     if (!UpdateThreadIDList())
1616       return false;
1617     num_thread_ids = m_thread_ids.size();
1618   }
1619 
1620   ThreadList old_thread_list_copy(old_thread_list);
1621   if (num_thread_ids > 0) {
1622     for (size_t i = 0; i < num_thread_ids; ++i) {
1623       tid_t tid = m_thread_ids[i];
1624       ThreadSP thread_sp(
1625           old_thread_list_copy.RemoveThreadByProtocolID(tid, false));
1626       if (!thread_sp) {
1627         thread_sp = std::make_shared<ThreadGDBRemote>(*this, tid);
1628         LLDB_LOGV(log, "Making new thread: {0} for thread ID: {1:x}.",
1629                   thread_sp.get(), thread_sp->GetID());
1630       } else {
1631         LLDB_LOGV(log, "Found old thread: {0} for thread ID: {1:x}.",
1632                   thread_sp.get(), thread_sp->GetID());
1633       }
1634 
1635       SetThreadPc(thread_sp, i);
1636       new_thread_list.AddThreadSortedByIndexID(thread_sp);
1637     }
1638   }
1639 
1640   // Whatever that is left in old_thread_list_copy are not present in
1641   // new_thread_list. Remove non-existent threads from internal id table.
1642   size_t old_num_thread_ids = old_thread_list_copy.GetSize(false);
1643   for (size_t i = 0; i < old_num_thread_ids; i++) {
1644     ThreadSP old_thread_sp(old_thread_list_copy.GetThreadAtIndex(i, false));
1645     if (old_thread_sp) {
1646       lldb::tid_t old_thread_id = old_thread_sp->GetProtocolID();
1647       m_thread_id_to_index_id_map.erase(old_thread_id);
1648     }
1649   }
1650 
1651   return true;
1652 }
1653 
SetThreadPc(const ThreadSP & thread_sp,uint64_t index)1654 void ProcessGDBRemote::SetThreadPc(const ThreadSP &thread_sp, uint64_t index) {
1655   if (m_thread_ids.size() == m_thread_pcs.size() && thread_sp.get() &&
1656       GetByteOrder() != eByteOrderInvalid) {
1657     ThreadGDBRemote *gdb_thread =
1658         static_cast<ThreadGDBRemote *>(thread_sp.get());
1659     RegisterContextSP reg_ctx_sp(thread_sp->GetRegisterContext());
1660     if (reg_ctx_sp) {
1661       uint32_t pc_regnum = reg_ctx_sp->ConvertRegisterKindToRegisterNumber(
1662           eRegisterKindGeneric, LLDB_REGNUM_GENERIC_PC);
1663       if (pc_regnum != LLDB_INVALID_REGNUM) {
1664         gdb_thread->PrivateSetRegisterValue(pc_regnum, m_thread_pcs[index]);
1665       }
1666     }
1667   }
1668 }
1669 
GetThreadStopInfoFromJSON(ThreadGDBRemote * thread,const StructuredData::ObjectSP & thread_infos_sp)1670 bool ProcessGDBRemote::GetThreadStopInfoFromJSON(
1671     ThreadGDBRemote *thread, const StructuredData::ObjectSP &thread_infos_sp) {
1672   // See if we got thread stop infos for all threads via the "jThreadsInfo"
1673   // packet
1674   if (thread_infos_sp) {
1675     StructuredData::Array *thread_infos = thread_infos_sp->GetAsArray();
1676     if (thread_infos) {
1677       lldb::tid_t tid;
1678       const size_t n = thread_infos->GetSize();
1679       for (size_t i = 0; i < n; ++i) {
1680         StructuredData::Dictionary *thread_dict =
1681             thread_infos->GetItemAtIndex(i)->GetAsDictionary();
1682         if (thread_dict) {
1683           if (thread_dict->GetValueForKeyAsInteger<lldb::tid_t>(
1684                   "tid", tid, LLDB_INVALID_THREAD_ID)) {
1685             if (tid == thread->GetID())
1686               return (bool)SetThreadStopInfo(thread_dict);
1687           }
1688         }
1689       }
1690     }
1691   }
1692   return false;
1693 }
1694 
CalculateThreadStopInfo(ThreadGDBRemote * thread)1695 bool ProcessGDBRemote::CalculateThreadStopInfo(ThreadGDBRemote *thread) {
1696   // See if we got thread stop infos for all threads via the "jThreadsInfo"
1697   // packet
1698   if (GetThreadStopInfoFromJSON(thread, m_jthreadsinfo_sp))
1699     return true;
1700 
1701   // See if we got thread stop info for any threads valid stop info reasons
1702   // threads via the "jstopinfo" packet stop reply packet key/value pair?
1703   if (m_jstopinfo_sp) {
1704     // If we have "jstopinfo" then we have stop descriptions for all threads
1705     // that have stop reasons, and if there is no entry for a thread, then it
1706     // has no stop reason.
1707     thread->GetRegisterContext()->InvalidateIfNeeded(true);
1708     if (!GetThreadStopInfoFromJSON(thread, m_jstopinfo_sp)) {
1709       thread->SetStopInfo(StopInfoSP());
1710     }
1711     return true;
1712   }
1713 
1714   // Fall back to using the qThreadStopInfo packet
1715   StringExtractorGDBRemote stop_packet;
1716   if (GetGDBRemote().GetThreadStopInfo(thread->GetProtocolID(), stop_packet))
1717     return SetThreadStopInfo(stop_packet) == eStateStopped;
1718   return false;
1719 }
1720 
SetThreadStopInfo(lldb::tid_t tid,ExpeditedRegisterMap & expedited_register_map,uint8_t signo,const std::string & thread_name,const std::string & reason,const std::string & description,uint32_t exc_type,const std::vector<addr_t> & exc_data,addr_t thread_dispatch_qaddr,bool queue_vars_valid,LazyBool associated_with_dispatch_queue,addr_t dispatch_queue_t,std::string & queue_name,QueueKind queue_kind,uint64_t queue_serial)1721 ThreadSP ProcessGDBRemote::SetThreadStopInfo(
1722     lldb::tid_t tid, ExpeditedRegisterMap &expedited_register_map,
1723     uint8_t signo, const std::string &thread_name, const std::string &reason,
1724     const std::string &description, uint32_t exc_type,
1725     const std::vector<addr_t> &exc_data, addr_t thread_dispatch_qaddr,
1726     bool queue_vars_valid, // Set to true if queue_name, queue_kind and
1727                            // queue_serial are valid
1728     LazyBool associated_with_dispatch_queue, addr_t dispatch_queue_t,
1729     std::string &queue_name, QueueKind queue_kind, uint64_t queue_serial) {
1730   ThreadSP thread_sp;
1731   if (tid != LLDB_INVALID_THREAD_ID) {
1732     // Scope for "locker" below
1733     {
1734       // m_thread_list_real does have its own mutex, but we need to hold onto
1735       // the mutex between the call to m_thread_list_real.FindThreadByID(...)
1736       // and the m_thread_list_real.AddThread(...) so it doesn't change on us
1737       std::lock_guard<std::recursive_mutex> guard(
1738           m_thread_list_real.GetMutex());
1739       thread_sp = m_thread_list_real.FindThreadByProtocolID(tid, false);
1740 
1741       if (!thread_sp) {
1742         // Create the thread if we need to
1743         thread_sp = std::make_shared<ThreadGDBRemote>(*this, tid);
1744         m_thread_list_real.AddThread(thread_sp);
1745       }
1746     }
1747 
1748     if (thread_sp) {
1749       ThreadGDBRemote *gdb_thread =
1750           static_cast<ThreadGDBRemote *>(thread_sp.get());
1751       gdb_thread->GetRegisterContext()->InvalidateIfNeeded(true);
1752 
1753       auto iter = std::find(m_thread_ids.begin(), m_thread_ids.end(), tid);
1754       if (iter != m_thread_ids.end()) {
1755         SetThreadPc(thread_sp, iter - m_thread_ids.begin());
1756       }
1757 
1758       for (const auto &pair : expedited_register_map) {
1759         StringExtractor reg_value_extractor(pair.second);
1760         DataBufferSP buffer_sp(new DataBufferHeap(
1761             reg_value_extractor.GetStringRef().size() / 2, 0));
1762         reg_value_extractor.GetHexBytes(buffer_sp->GetData(), '\xcc');
1763         gdb_thread->PrivateSetRegisterValue(pair.first, buffer_sp->GetData());
1764       }
1765 
1766       thread_sp->SetName(thread_name.empty() ? nullptr : thread_name.c_str());
1767 
1768       gdb_thread->SetThreadDispatchQAddr(thread_dispatch_qaddr);
1769       // Check if the GDB server was able to provide the queue name, kind and
1770       // serial number
1771       if (queue_vars_valid)
1772         gdb_thread->SetQueueInfo(std::move(queue_name), queue_kind,
1773                                  queue_serial, dispatch_queue_t,
1774                                  associated_with_dispatch_queue);
1775       else
1776         gdb_thread->ClearQueueInfo();
1777 
1778       gdb_thread->SetAssociatedWithLibdispatchQueue(
1779           associated_with_dispatch_queue);
1780 
1781       if (dispatch_queue_t != LLDB_INVALID_ADDRESS)
1782         gdb_thread->SetQueueLibdispatchQueueAddress(dispatch_queue_t);
1783 
1784       // Make sure we update our thread stop reason just once
1785       if (!thread_sp->StopInfoIsUpToDate()) {
1786         thread_sp->SetStopInfo(StopInfoSP());
1787         // If there's a memory thread backed by this thread, we need to use it
1788         // to calculate StopInfo.
1789         if (ThreadSP memory_thread_sp =
1790                 m_thread_list.GetBackingThread(thread_sp))
1791           thread_sp = memory_thread_sp;
1792 
1793         if (exc_type != 0) {
1794           const size_t exc_data_size = exc_data.size();
1795 
1796           thread_sp->SetStopInfo(
1797               StopInfoMachException::CreateStopReasonWithMachException(
1798                   *thread_sp, exc_type, exc_data_size,
1799                   exc_data_size >= 1 ? exc_data[0] : 0,
1800                   exc_data_size >= 2 ? exc_data[1] : 0,
1801                   exc_data_size >= 3 ? exc_data[2] : 0));
1802         } else {
1803           bool handled = false;
1804           bool did_exec = false;
1805           if (!reason.empty()) {
1806             if (reason == "trace") {
1807               addr_t pc = thread_sp->GetRegisterContext()->GetPC();
1808               lldb::BreakpointSiteSP bp_site_sp = thread_sp->GetProcess()
1809                                                       ->GetBreakpointSiteList()
1810                                                       .FindByAddress(pc);
1811 
1812               // If the current pc is a breakpoint site then the StopInfo
1813               // should be set to Breakpoint Otherwise, it will be set to
1814               // Trace.
1815               if (bp_site_sp &&
1816                   bp_site_sp->ValidForThisThread(thread_sp.get())) {
1817                 thread_sp->SetStopInfo(
1818                     StopInfo::CreateStopReasonWithBreakpointSiteID(
1819                         *thread_sp, bp_site_sp->GetID()));
1820               } else
1821                 thread_sp->SetStopInfo(
1822                     StopInfo::CreateStopReasonToTrace(*thread_sp));
1823               handled = true;
1824             } else if (reason == "breakpoint") {
1825               addr_t pc = thread_sp->GetRegisterContext()->GetPC();
1826               lldb::BreakpointSiteSP bp_site_sp = thread_sp->GetProcess()
1827                                                       ->GetBreakpointSiteList()
1828                                                       .FindByAddress(pc);
1829               if (bp_site_sp) {
1830                 // If the breakpoint is for this thread, then we'll report the
1831                 // hit, but if it is for another thread, we can just report no
1832                 // reason.  We don't need to worry about stepping over the
1833                 // breakpoint here, that will be taken care of when the thread
1834                 // resumes and notices that there's a breakpoint under the pc.
1835                 handled = true;
1836                 if (bp_site_sp->ValidForThisThread(thread_sp.get())) {
1837                   thread_sp->SetStopInfo(
1838                       StopInfo::CreateStopReasonWithBreakpointSiteID(
1839                           *thread_sp, bp_site_sp->GetID()));
1840                 } else {
1841                   StopInfoSP invalid_stop_info_sp;
1842                   thread_sp->SetStopInfo(invalid_stop_info_sp);
1843                 }
1844               }
1845             } else if (reason == "trap") {
1846               // Let the trap just use the standard signal stop reason below...
1847             } else if (reason == "watchpoint") {
1848               StringExtractor desc_extractor(description.c_str());
1849               addr_t wp_addr = desc_extractor.GetU64(LLDB_INVALID_ADDRESS);
1850               uint32_t wp_index = desc_extractor.GetU32(LLDB_INVALID_INDEX32);
1851               addr_t wp_hit_addr = desc_extractor.GetU64(LLDB_INVALID_ADDRESS);
1852               watch_id_t watch_id = LLDB_INVALID_WATCH_ID;
1853               if (wp_addr != LLDB_INVALID_ADDRESS) {
1854                 WatchpointSP wp_sp;
1855                 ArchSpec::Core core = GetTarget().GetArchitecture().GetCore();
1856                 if ((core >= ArchSpec::kCore_mips_first &&
1857                      core <= ArchSpec::kCore_mips_last) ||
1858                     (core >= ArchSpec::eCore_arm_generic &&
1859                      core <= ArchSpec::eCore_arm_aarch64))
1860                   wp_sp = GetTarget().GetWatchpointList().FindByAddress(
1861                       wp_hit_addr);
1862                 if (!wp_sp)
1863                   wp_sp =
1864                       GetTarget().GetWatchpointList().FindByAddress(wp_addr);
1865                 if (wp_sp) {
1866                   wp_sp->SetHardwareIndex(wp_index);
1867                   watch_id = wp_sp->GetID();
1868                 }
1869               }
1870               if (watch_id == LLDB_INVALID_WATCH_ID) {
1871                 Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(
1872                     GDBR_LOG_WATCHPOINTS));
1873                 LLDB_LOGF(log, "failed to find watchpoint");
1874               }
1875               thread_sp->SetStopInfo(StopInfo::CreateStopReasonWithWatchpointID(
1876                   *thread_sp, watch_id, wp_hit_addr));
1877               handled = true;
1878             } else if (reason == "exception") {
1879               thread_sp->SetStopInfo(StopInfo::CreateStopReasonWithException(
1880                   *thread_sp, description.c_str()));
1881               handled = true;
1882             } else if (reason == "exec") {
1883               did_exec = true;
1884               thread_sp->SetStopInfo(
1885                   StopInfo::CreateStopReasonWithExec(*thread_sp));
1886               handled = true;
1887             }
1888           } else if (!signo) {
1889             addr_t pc = thread_sp->GetRegisterContext()->GetPC();
1890             lldb::BreakpointSiteSP bp_site_sp =
1891                 thread_sp->GetProcess()->GetBreakpointSiteList().FindByAddress(
1892                     pc);
1893 
1894             // If the current pc is a breakpoint site then the StopInfo should
1895             // be set to Breakpoint even though the remote stub did not set it
1896             // as such. This can happen when the thread is involuntarily
1897             // interrupted (e.g. due to stops on other threads) just as it is
1898             // about to execute the breakpoint instruction.
1899             if (bp_site_sp && bp_site_sp->ValidForThisThread(thread_sp.get())) {
1900               thread_sp->SetStopInfo(
1901                   StopInfo::CreateStopReasonWithBreakpointSiteID(
1902                       *thread_sp, bp_site_sp->GetID()));
1903               handled = true;
1904             }
1905           }
1906 
1907           if (!handled && signo && !did_exec) {
1908             if (signo == SIGTRAP) {
1909               // Currently we are going to assume SIGTRAP means we are either
1910               // hitting a breakpoint or hardware single stepping.
1911               handled = true;
1912               addr_t pc = thread_sp->GetRegisterContext()->GetPC() +
1913                           m_breakpoint_pc_offset;
1914               lldb::BreakpointSiteSP bp_site_sp = thread_sp->GetProcess()
1915                                                       ->GetBreakpointSiteList()
1916                                                       .FindByAddress(pc);
1917 
1918               if (bp_site_sp) {
1919                 // If the breakpoint is for this thread, then we'll report the
1920                 // hit, but if it is for another thread, we can just report no
1921                 // reason.  We don't need to worry about stepping over the
1922                 // breakpoint here, that will be taken care of when the thread
1923                 // resumes and notices that there's a breakpoint under the pc.
1924                 if (bp_site_sp->ValidForThisThread(thread_sp.get())) {
1925                   if (m_breakpoint_pc_offset != 0)
1926                     thread_sp->GetRegisterContext()->SetPC(pc);
1927                   thread_sp->SetStopInfo(
1928                       StopInfo::CreateStopReasonWithBreakpointSiteID(
1929                           *thread_sp, bp_site_sp->GetID()));
1930                 } else {
1931                   StopInfoSP invalid_stop_info_sp;
1932                   thread_sp->SetStopInfo(invalid_stop_info_sp);
1933                 }
1934               } else {
1935                 // If we were stepping then assume the stop was the result of
1936                 // the trace.  If we were not stepping then report the SIGTRAP.
1937                 // FIXME: We are still missing the case where we single step
1938                 // over a trap instruction.
1939                 if (thread_sp->GetTemporaryResumeState() == eStateStepping)
1940                   thread_sp->SetStopInfo(
1941                       StopInfo::CreateStopReasonToTrace(*thread_sp));
1942                 else
1943                   thread_sp->SetStopInfo(StopInfo::CreateStopReasonWithSignal(
1944                       *thread_sp, signo, description.c_str()));
1945               }
1946             }
1947             if (!handled)
1948               thread_sp->SetStopInfo(StopInfo::CreateStopReasonWithSignal(
1949                   *thread_sp, signo, description.c_str()));
1950           }
1951 
1952           if (!description.empty()) {
1953             lldb::StopInfoSP stop_info_sp(thread_sp->GetStopInfo());
1954             if (stop_info_sp) {
1955               const char *stop_info_desc = stop_info_sp->GetDescription();
1956               if (!stop_info_desc || !stop_info_desc[0])
1957                 stop_info_sp->SetDescription(description.c_str());
1958             } else {
1959               thread_sp->SetStopInfo(StopInfo::CreateStopReasonWithException(
1960                   *thread_sp, description.c_str()));
1961             }
1962           }
1963         }
1964       }
1965     }
1966   }
1967   return thread_sp;
1968 }
1969 
1970 lldb::ThreadSP
SetThreadStopInfo(StructuredData::Dictionary * thread_dict)1971 ProcessGDBRemote::SetThreadStopInfo(StructuredData::Dictionary *thread_dict) {
1972   static ConstString g_key_tid("tid");
1973   static ConstString g_key_name("name");
1974   static ConstString g_key_reason("reason");
1975   static ConstString g_key_metype("metype");
1976   static ConstString g_key_medata("medata");
1977   static ConstString g_key_qaddr("qaddr");
1978   static ConstString g_key_dispatch_queue_t("dispatch_queue_t");
1979   static ConstString g_key_associated_with_dispatch_queue(
1980       "associated_with_dispatch_queue");
1981   static ConstString g_key_queue_name("qname");
1982   static ConstString g_key_queue_kind("qkind");
1983   static ConstString g_key_queue_serial_number("qserialnum");
1984   static ConstString g_key_registers("registers");
1985   static ConstString g_key_memory("memory");
1986   static ConstString g_key_address("address");
1987   static ConstString g_key_bytes("bytes");
1988   static ConstString g_key_description("description");
1989   static ConstString g_key_signal("signal");
1990 
1991   // Stop with signal and thread info
1992   lldb::tid_t tid = LLDB_INVALID_THREAD_ID;
1993   uint8_t signo = 0;
1994   std::string value;
1995   std::string thread_name;
1996   std::string reason;
1997   std::string description;
1998   uint32_t exc_type = 0;
1999   std::vector<addr_t> exc_data;
2000   addr_t thread_dispatch_qaddr = LLDB_INVALID_ADDRESS;
2001   ExpeditedRegisterMap expedited_register_map;
2002   bool queue_vars_valid = false;
2003   addr_t dispatch_queue_t = LLDB_INVALID_ADDRESS;
2004   LazyBool associated_with_dispatch_queue = eLazyBoolCalculate;
2005   std::string queue_name;
2006   QueueKind queue_kind = eQueueKindUnknown;
2007   uint64_t queue_serial_number = 0;
2008   // Iterate through all of the thread dictionary key/value pairs from the
2009   // structured data dictionary
2010 
2011   thread_dict->ForEach([this, &tid, &expedited_register_map, &thread_name,
2012                         &signo, &reason, &description, &exc_type, &exc_data,
2013                         &thread_dispatch_qaddr, &queue_vars_valid,
2014                         &associated_with_dispatch_queue, &dispatch_queue_t,
2015                         &queue_name, &queue_kind, &queue_serial_number](
2016                            ConstString key,
2017                            StructuredData::Object *object) -> bool {
2018     if (key == g_key_tid) {
2019       // thread in big endian hex
2020       tid = object->GetIntegerValue(LLDB_INVALID_THREAD_ID);
2021     } else if (key == g_key_metype) {
2022       // exception type in big endian hex
2023       exc_type = object->GetIntegerValue(0);
2024     } else if (key == g_key_medata) {
2025       // exception data in big endian hex
2026       StructuredData::Array *array = object->GetAsArray();
2027       if (array) {
2028         array->ForEach([&exc_data](StructuredData::Object *object) -> bool {
2029           exc_data.push_back(object->GetIntegerValue());
2030           return true; // Keep iterating through all array items
2031         });
2032       }
2033     } else if (key == g_key_name) {
2034       thread_name = std::string(object->GetStringValue());
2035     } else if (key == g_key_qaddr) {
2036       thread_dispatch_qaddr = object->GetIntegerValue(LLDB_INVALID_ADDRESS);
2037     } else if (key == g_key_queue_name) {
2038       queue_vars_valid = true;
2039       queue_name = std::string(object->GetStringValue());
2040     } else if (key == g_key_queue_kind) {
2041       std::string queue_kind_str = std::string(object->GetStringValue());
2042       if (queue_kind_str == "serial") {
2043         queue_vars_valid = true;
2044         queue_kind = eQueueKindSerial;
2045       } else if (queue_kind_str == "concurrent") {
2046         queue_vars_valid = true;
2047         queue_kind = eQueueKindConcurrent;
2048       }
2049     } else if (key == g_key_queue_serial_number) {
2050       queue_serial_number = object->GetIntegerValue(0);
2051       if (queue_serial_number != 0)
2052         queue_vars_valid = true;
2053     } else if (key == g_key_dispatch_queue_t) {
2054       dispatch_queue_t = object->GetIntegerValue(0);
2055       if (dispatch_queue_t != 0 && dispatch_queue_t != LLDB_INVALID_ADDRESS)
2056         queue_vars_valid = true;
2057     } else if (key == g_key_associated_with_dispatch_queue) {
2058       queue_vars_valid = true;
2059       bool associated = object->GetBooleanValue();
2060       if (associated)
2061         associated_with_dispatch_queue = eLazyBoolYes;
2062       else
2063         associated_with_dispatch_queue = eLazyBoolNo;
2064     } else if (key == g_key_reason) {
2065       reason = std::string(object->GetStringValue());
2066     } else if (key == g_key_description) {
2067       description = std::string(object->GetStringValue());
2068     } else if (key == g_key_registers) {
2069       StructuredData::Dictionary *registers_dict = object->GetAsDictionary();
2070 
2071       if (registers_dict) {
2072         registers_dict->ForEach(
2073             [&expedited_register_map](ConstString key,
2074                                       StructuredData::Object *object) -> bool {
2075               const uint32_t reg =
2076                   StringConvert::ToUInt32(key.GetCString(), UINT32_MAX, 10);
2077               if (reg != UINT32_MAX)
2078                 expedited_register_map[reg] =
2079                     std::string(object->GetStringValue());
2080               return true; // Keep iterating through all array items
2081             });
2082       }
2083     } else if (key == g_key_memory) {
2084       StructuredData::Array *array = object->GetAsArray();
2085       if (array) {
2086         array->ForEach([this](StructuredData::Object *object) -> bool {
2087           StructuredData::Dictionary *mem_cache_dict =
2088               object->GetAsDictionary();
2089           if (mem_cache_dict) {
2090             lldb::addr_t mem_cache_addr = LLDB_INVALID_ADDRESS;
2091             if (mem_cache_dict->GetValueForKeyAsInteger<lldb::addr_t>(
2092                     "address", mem_cache_addr)) {
2093               if (mem_cache_addr != LLDB_INVALID_ADDRESS) {
2094                 llvm::StringRef str;
2095                 if (mem_cache_dict->GetValueForKeyAsString("bytes", str)) {
2096                   StringExtractor bytes(str);
2097                   bytes.SetFilePos(0);
2098 
2099                   const size_t byte_size = bytes.GetStringRef().size() / 2;
2100                   DataBufferSP data_buffer_sp(new DataBufferHeap(byte_size, 0));
2101                   const size_t bytes_copied =
2102                       bytes.GetHexBytes(data_buffer_sp->GetData(), 0);
2103                   if (bytes_copied == byte_size)
2104                     m_memory_cache.AddL1CacheData(mem_cache_addr,
2105                                                   data_buffer_sp);
2106                 }
2107               }
2108             }
2109           }
2110           return true; // Keep iterating through all array items
2111         });
2112       }
2113 
2114     } else if (key == g_key_signal)
2115       signo = object->GetIntegerValue(LLDB_INVALID_SIGNAL_NUMBER);
2116     return true; // Keep iterating through all dictionary key/value pairs
2117   });
2118 
2119   return SetThreadStopInfo(tid, expedited_register_map, signo, thread_name,
2120                            reason, description, exc_type, exc_data,
2121                            thread_dispatch_qaddr, queue_vars_valid,
2122                            associated_with_dispatch_queue, dispatch_queue_t,
2123                            queue_name, queue_kind, queue_serial_number);
2124 }
2125 
SetThreadStopInfo(StringExtractor & stop_packet)2126 StateType ProcessGDBRemote::SetThreadStopInfo(StringExtractor &stop_packet) {
2127   stop_packet.SetFilePos(0);
2128   const char stop_type = stop_packet.GetChar();
2129   switch (stop_type) {
2130   case 'T':
2131   case 'S': {
2132     // This is a bit of a hack, but is is required. If we did exec, we need to
2133     // clear our thread lists and also know to rebuild our dynamic register
2134     // info before we lookup and threads and populate the expedited register
2135     // values so we need to know this right away so we can cleanup and update
2136     // our registers.
2137     const uint32_t stop_id = GetStopID();
2138     if (stop_id == 0) {
2139       // Our first stop, make sure we have a process ID, and also make sure we
2140       // know about our registers
2141       if (GetID() == LLDB_INVALID_PROCESS_ID) {
2142         lldb::pid_t pid = m_gdb_comm.GetCurrentProcessID();
2143         if (pid != LLDB_INVALID_PROCESS_ID)
2144           SetID(pid);
2145       }
2146       BuildDynamicRegisterInfo(true);
2147     }
2148     // Stop with signal and thread info
2149     lldb::tid_t tid = LLDB_INVALID_THREAD_ID;
2150     const uint8_t signo = stop_packet.GetHexU8();
2151     llvm::StringRef key;
2152     llvm::StringRef value;
2153     std::string thread_name;
2154     std::string reason;
2155     std::string description;
2156     uint32_t exc_type = 0;
2157     std::vector<addr_t> exc_data;
2158     addr_t thread_dispatch_qaddr = LLDB_INVALID_ADDRESS;
2159     bool queue_vars_valid =
2160         false; // says if locals below that start with "queue_" are valid
2161     addr_t dispatch_queue_t = LLDB_INVALID_ADDRESS;
2162     LazyBool associated_with_dispatch_queue = eLazyBoolCalculate;
2163     std::string queue_name;
2164     QueueKind queue_kind = eQueueKindUnknown;
2165     uint64_t queue_serial_number = 0;
2166     ExpeditedRegisterMap expedited_register_map;
2167     while (stop_packet.GetNameColonValue(key, value)) {
2168       if (key.compare("metype") == 0) {
2169         // exception type in big endian hex
2170         value.getAsInteger(16, exc_type);
2171       } else if (key.compare("medata") == 0) {
2172         // exception data in big endian hex
2173         uint64_t x;
2174         value.getAsInteger(16, x);
2175         exc_data.push_back(x);
2176       } else if (key.compare("thread") == 0) {
2177         // thread in big endian hex
2178         if (value.getAsInteger(16, tid))
2179           tid = LLDB_INVALID_THREAD_ID;
2180       } else if (key.compare("threads") == 0) {
2181         std::lock_guard<std::recursive_mutex> guard(
2182             m_thread_list_real.GetMutex());
2183 
2184         m_thread_ids.clear();
2185         // A comma separated list of all threads in the current
2186         // process that includes the thread for this stop reply packet
2187         lldb::tid_t tid;
2188         while (!value.empty()) {
2189           llvm::StringRef tid_str;
2190           std::tie(tid_str, value) = value.split(',');
2191           if (tid_str.getAsInteger(16, tid))
2192             tid = LLDB_INVALID_THREAD_ID;
2193           m_thread_ids.push_back(tid);
2194         }
2195       } else if (key.compare("thread-pcs") == 0) {
2196         m_thread_pcs.clear();
2197         // A comma separated list of all threads in the current
2198         // process that includes the thread for this stop reply packet
2199         lldb::addr_t pc;
2200         while (!value.empty()) {
2201           llvm::StringRef pc_str;
2202           std::tie(pc_str, value) = value.split(',');
2203           if (pc_str.getAsInteger(16, pc))
2204             pc = LLDB_INVALID_ADDRESS;
2205           m_thread_pcs.push_back(pc);
2206         }
2207       } else if (key.compare("jstopinfo") == 0) {
2208         StringExtractor json_extractor(value);
2209         std::string json;
2210         // Now convert the HEX bytes into a string value
2211         json_extractor.GetHexByteString(json);
2212 
2213         // This JSON contains thread IDs and thread stop info for all threads.
2214         // It doesn't contain expedited registers, memory or queue info.
2215         m_jstopinfo_sp = StructuredData::ParseJSON(json);
2216       } else if (key.compare("hexname") == 0) {
2217         StringExtractor name_extractor(value);
2218         std::string name;
2219         // Now convert the HEX bytes into a string value
2220         name_extractor.GetHexByteString(thread_name);
2221       } else if (key.compare("name") == 0) {
2222         thread_name = std::string(value);
2223       } else if (key.compare("qaddr") == 0) {
2224         value.getAsInteger(16, thread_dispatch_qaddr);
2225       } else if (key.compare("dispatch_queue_t") == 0) {
2226         queue_vars_valid = true;
2227         value.getAsInteger(16, dispatch_queue_t);
2228       } else if (key.compare("qname") == 0) {
2229         queue_vars_valid = true;
2230         StringExtractor name_extractor(value);
2231         // Now convert the HEX bytes into a string value
2232         name_extractor.GetHexByteString(queue_name);
2233       } else if (key.compare("qkind") == 0) {
2234         queue_kind = llvm::StringSwitch<QueueKind>(value)
2235                          .Case("serial", eQueueKindSerial)
2236                          .Case("concurrent", eQueueKindConcurrent)
2237                          .Default(eQueueKindUnknown);
2238         queue_vars_valid = queue_kind != eQueueKindUnknown;
2239       } else if (key.compare("qserialnum") == 0) {
2240         if (!value.getAsInteger(0, queue_serial_number))
2241           queue_vars_valid = true;
2242       } else if (key.compare("reason") == 0) {
2243         reason = std::string(value);
2244       } else if (key.compare("description") == 0) {
2245         StringExtractor desc_extractor(value);
2246         // Now convert the HEX bytes into a string value
2247         desc_extractor.GetHexByteString(description);
2248       } else if (key.compare("memory") == 0) {
2249         // Expedited memory. GDB servers can choose to send back expedited
2250         // memory that can populate the L1 memory cache in the process so that
2251         // things like the frame pointer backchain can be expedited. This will
2252         // help stack backtracing be more efficient by not having to send as
2253         // many memory read requests down the remote GDB server.
2254 
2255         // Key/value pair format: memory:<addr>=<bytes>;
2256         // <addr> is a number whose base will be interpreted by the prefix:
2257         //      "0x[0-9a-fA-F]+" for hex
2258         //      "0[0-7]+" for octal
2259         //      "[1-9]+" for decimal
2260         // <bytes> is native endian ASCII hex bytes just like the register
2261         // values
2262         llvm::StringRef addr_str, bytes_str;
2263         std::tie(addr_str, bytes_str) = value.split('=');
2264         if (!addr_str.empty() && !bytes_str.empty()) {
2265           lldb::addr_t mem_cache_addr = LLDB_INVALID_ADDRESS;
2266           if (!addr_str.getAsInteger(0, mem_cache_addr)) {
2267             StringExtractor bytes(bytes_str);
2268             const size_t byte_size = bytes.GetBytesLeft() / 2;
2269             DataBufferSP data_buffer_sp(new DataBufferHeap(byte_size, 0));
2270             const size_t bytes_copied =
2271                 bytes.GetHexBytes(data_buffer_sp->GetData(), 0);
2272             if (bytes_copied == byte_size)
2273               m_memory_cache.AddL1CacheData(mem_cache_addr, data_buffer_sp);
2274           }
2275         }
2276       } else if (key.compare("watch") == 0 || key.compare("rwatch") == 0 ||
2277                  key.compare("awatch") == 0) {
2278         // Support standard GDB remote stop reply packet 'TAAwatch:addr'
2279         lldb::addr_t wp_addr = LLDB_INVALID_ADDRESS;
2280         value.getAsInteger(16, wp_addr);
2281 
2282         WatchpointSP wp_sp =
2283             GetTarget().GetWatchpointList().FindByAddress(wp_addr);
2284         uint32_t wp_index = LLDB_INVALID_INDEX32;
2285 
2286         if (wp_sp)
2287           wp_index = wp_sp->GetHardwareIndex();
2288 
2289         reason = "watchpoint";
2290         StreamString ostr;
2291         ostr.Printf("%" PRIu64 " %" PRIu32, wp_addr, wp_index);
2292         description = std::string(ostr.GetString());
2293       } else if (key.compare("library") == 0) {
2294         auto error = LoadModules();
2295         if (error) {
2296           Log *log(
2297               ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
2298           LLDB_LOG_ERROR(log, std::move(error), "Failed to load modules: {0}");
2299         }
2300       } else if (key.size() == 2 && ::isxdigit(key[0]) && ::isxdigit(key[1])) {
2301         uint32_t reg = UINT32_MAX;
2302         if (!key.getAsInteger(16, reg))
2303           expedited_register_map[reg] = std::string(std::move(value));
2304       }
2305     }
2306 
2307     if (tid == LLDB_INVALID_THREAD_ID) {
2308       // A thread id may be invalid if the response is old style 'S' packet
2309       // which does not provide the
2310       // thread information. So update the thread list and choose the first
2311       // one.
2312       UpdateThreadIDList();
2313 
2314       if (!m_thread_ids.empty()) {
2315         tid = m_thread_ids.front();
2316       }
2317     }
2318 
2319     ThreadSP thread_sp = SetThreadStopInfo(
2320         tid, expedited_register_map, signo, thread_name, reason, description,
2321         exc_type, exc_data, thread_dispatch_qaddr, queue_vars_valid,
2322         associated_with_dispatch_queue, dispatch_queue_t, queue_name,
2323         queue_kind, queue_serial_number);
2324 
2325     return eStateStopped;
2326   } break;
2327 
2328   case 'W':
2329   case 'X':
2330     // process exited
2331     return eStateExited;
2332 
2333   default:
2334     break;
2335   }
2336   return eStateInvalid;
2337 }
2338 
RefreshStateAfterStop()2339 void ProcessGDBRemote::RefreshStateAfterStop() {
2340   std::lock_guard<std::recursive_mutex> guard(m_thread_list_real.GetMutex());
2341 
2342   m_thread_ids.clear();
2343   m_thread_pcs.clear();
2344 
2345   // Set the thread stop info. It might have a "threads" key whose value is a
2346   // list of all thread IDs in the current process, so m_thread_ids might get
2347   // set.
2348   // Check to see if SetThreadStopInfo() filled in m_thread_ids?
2349   if (m_thread_ids.empty()) {
2350       // No, we need to fetch the thread list manually
2351       UpdateThreadIDList();
2352   }
2353 
2354   // We might set some stop info's so make sure the thread list is up to
2355   // date before we do that or we might overwrite what was computed here.
2356   UpdateThreadListIfNeeded();
2357 
2358   // Scope for the lock
2359   {
2360     // Lock the thread stack while we access it
2361     std::lock_guard<std::recursive_mutex> guard(m_last_stop_packet_mutex);
2362     // Get the number of stop packets on the stack
2363     int nItems = m_stop_packet_stack.size();
2364     // Iterate over them
2365     for (int i = 0; i < nItems; i++) {
2366       // Get the thread stop info
2367       StringExtractorGDBRemote stop_info = m_stop_packet_stack[i];
2368       // Process thread stop info
2369       SetThreadStopInfo(stop_info);
2370     }
2371     // Clear the thread stop stack
2372     m_stop_packet_stack.clear();
2373   }
2374 
2375   // If we have queried for a default thread id
2376   if (m_initial_tid != LLDB_INVALID_THREAD_ID) {
2377     m_thread_list.SetSelectedThreadByID(m_initial_tid);
2378     m_initial_tid = LLDB_INVALID_THREAD_ID;
2379   }
2380 
2381   // Let all threads recover from stopping and do any clean up based on the
2382   // previous thread state (if any).
2383   m_thread_list_real.RefreshStateAfterStop();
2384 }
2385 
DoHalt(bool & caused_stop)2386 Status ProcessGDBRemote::DoHalt(bool &caused_stop) {
2387   Status error;
2388 
2389   if (m_public_state.GetValue() == eStateAttaching) {
2390     // We are being asked to halt during an attach. We need to just close our
2391     // file handle and debugserver will go away, and we can be done...
2392     m_gdb_comm.Disconnect();
2393   } else
2394     caused_stop = m_gdb_comm.Interrupt();
2395   return error;
2396 }
2397 
DoDetach(bool keep_stopped)2398 Status ProcessGDBRemote::DoDetach(bool keep_stopped) {
2399   Status error;
2400   Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
2401   LLDB_LOGF(log, "ProcessGDBRemote::DoDetach(keep_stopped: %i)", keep_stopped);
2402 
2403   error = m_gdb_comm.Detach(keep_stopped);
2404   if (log) {
2405     if (error.Success())
2406       log->PutCString(
2407           "ProcessGDBRemote::DoDetach() detach packet sent successfully");
2408     else
2409       LLDB_LOGF(log,
2410                 "ProcessGDBRemote::DoDetach() detach packet send failed: %s",
2411                 error.AsCString() ? error.AsCString() : "<unknown error>");
2412   }
2413 
2414   if (!error.Success())
2415     return error;
2416 
2417   // Sleep for one second to let the process get all detached...
2418   StopAsyncThread();
2419 
2420   SetPrivateState(eStateDetached);
2421   ResumePrivateStateThread();
2422 
2423   // KillDebugserverProcess ();
2424   return error;
2425 }
2426 
DoDestroy()2427 Status ProcessGDBRemote::DoDestroy() {
2428   Status error;
2429   Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
2430   LLDB_LOGF(log, "ProcessGDBRemote::DoDestroy()");
2431 
2432   // There is a bug in older iOS debugservers where they don't shut down the
2433   // process they are debugging properly.  If the process is sitting at a
2434   // breakpoint or an exception, this can cause problems with restarting.  So
2435   // we check to see if any of our threads are stopped at a breakpoint, and if
2436   // so we remove all the breakpoints, resume the process, and THEN destroy it
2437   // again.
2438   //
2439   // Note, we don't have a good way to test the version of debugserver, but I
2440   // happen to know that the set of all the iOS debugservers which don't
2441   // support GetThreadSuffixSupported() and that of the debugservers with this
2442   // bug are equal.  There really should be a better way to test this!
2443   //
2444   // We also use m_destroy_tried_resuming to make sure we only do this once, if
2445   // we resume and then halt and get called here to destroy again and we're
2446   // still at a breakpoint or exception, then we should just do the straight-
2447   // forward kill.
2448   //
2449   // And of course, if we weren't able to stop the process by the time we get
2450   // here, it isn't necessary (or helpful) to do any of this.
2451 
2452   if (!m_gdb_comm.GetThreadSuffixSupported() &&
2453       m_public_state.GetValue() != eStateRunning) {
2454     PlatformSP platform_sp = GetTarget().GetPlatform();
2455 
2456     // FIXME: These should be ConstStrings so we aren't doing strcmp'ing.
2457     if (platform_sp && platform_sp->GetName() &&
2458         platform_sp->GetName() == PlatformRemoteiOS::GetPluginNameStatic()) {
2459       if (m_destroy_tried_resuming) {
2460         if (log)
2461           log->PutCString("ProcessGDBRemote::DoDestroy() - Tried resuming to "
2462                           "destroy once already, not doing it again.");
2463       } else {
2464         // At present, the plans are discarded and the breakpoints disabled
2465         // Process::Destroy, but we really need it to happen here and it
2466         // doesn't matter if we do it twice.
2467         m_thread_list.DiscardThreadPlans();
2468         DisableAllBreakpointSites();
2469 
2470         bool stop_looks_like_crash = false;
2471         ThreadList &threads = GetThreadList();
2472 
2473         {
2474           std::lock_guard<std::recursive_mutex> guard(threads.GetMutex());
2475 
2476           size_t num_threads = threads.GetSize();
2477           for (size_t i = 0; i < num_threads; i++) {
2478             ThreadSP thread_sp = threads.GetThreadAtIndex(i);
2479             StopInfoSP stop_info_sp = thread_sp->GetPrivateStopInfo();
2480             StopReason reason = eStopReasonInvalid;
2481             if (stop_info_sp)
2482               reason = stop_info_sp->GetStopReason();
2483             if (reason == eStopReasonBreakpoint ||
2484                 reason == eStopReasonException) {
2485               LLDB_LOGF(log,
2486                         "ProcessGDBRemote::DoDestroy() - thread: 0x%4.4" PRIx64
2487                         " stopped with reason: %s.",
2488                         thread_sp->GetProtocolID(),
2489                         stop_info_sp->GetDescription());
2490               stop_looks_like_crash = true;
2491               break;
2492             }
2493           }
2494         }
2495 
2496         if (stop_looks_like_crash) {
2497           if (log)
2498             log->PutCString("ProcessGDBRemote::DoDestroy() - Stopped at a "
2499                             "breakpoint, continue and then kill.");
2500           m_destroy_tried_resuming = true;
2501 
2502           // If we are going to run again before killing, it would be good to
2503           // suspend all the threads before resuming so they won't get into
2504           // more trouble.  Sadly, for the threads stopped with the breakpoint
2505           // or exception, the exception doesn't get cleared if it is
2506           // suspended, so we do have to run the risk of letting those threads
2507           // proceed a bit.
2508 
2509           {
2510             std::lock_guard<std::recursive_mutex> guard(threads.GetMutex());
2511 
2512             size_t num_threads = threads.GetSize();
2513             for (size_t i = 0; i < num_threads; i++) {
2514               ThreadSP thread_sp = threads.GetThreadAtIndex(i);
2515               StopInfoSP stop_info_sp = thread_sp->GetPrivateStopInfo();
2516               StopReason reason = eStopReasonInvalid;
2517               if (stop_info_sp)
2518                 reason = stop_info_sp->GetStopReason();
2519               if (reason != eStopReasonBreakpoint &&
2520                   reason != eStopReasonException) {
2521                 LLDB_LOGF(log,
2522                           "ProcessGDBRemote::DoDestroy() - Suspending "
2523                           "thread: 0x%4.4" PRIx64 " before running.",
2524                           thread_sp->GetProtocolID());
2525                 thread_sp->SetResumeState(eStateSuspended);
2526               }
2527             }
2528           }
2529           Resume();
2530           return Destroy(false);
2531         }
2532       }
2533     }
2534   }
2535 
2536   // Interrupt if our inferior is running...
2537   int exit_status = SIGABRT;
2538   std::string exit_string;
2539 
2540   if (m_gdb_comm.IsConnected()) {
2541     if (m_public_state.GetValue() != eStateAttaching) {
2542       StringExtractorGDBRemote response;
2543       bool send_async = true;
2544       GDBRemoteCommunication::ScopedTimeout(m_gdb_comm,
2545                                             std::chrono::seconds(3));
2546 
2547       if (m_gdb_comm.SendPacketAndWaitForResponse("k", response, send_async) ==
2548           GDBRemoteCommunication::PacketResult::Success) {
2549         char packet_cmd = response.GetChar(0);
2550 
2551         if (packet_cmd == 'W' || packet_cmd == 'X') {
2552 #if defined(__APPLE__)
2553           // For Native processes on Mac OS X, we launch through the Host
2554           // Platform, then hand the process off to debugserver, which becomes
2555           // the parent process through "PT_ATTACH".  Then when we go to kill
2556           // the process on Mac OS X we call ptrace(PT_KILL) to kill it, then
2557           // we call waitpid which returns with no error and the correct
2558           // status.  But amusingly enough that doesn't seem to actually reap
2559           // the process, but instead it is left around as a Zombie.  Probably
2560           // the kernel is in the process of switching ownership back to lldb
2561           // which was the original parent, and gets confused in the handoff.
2562           // Anyway, so call waitpid here to finally reap it.
2563           PlatformSP platform_sp(GetTarget().GetPlatform());
2564           if (platform_sp && platform_sp->IsHost()) {
2565             int status;
2566             ::pid_t reap_pid;
2567             reap_pid = waitpid(GetID(), &status, WNOHANG);
2568             LLDB_LOGF(log, "Reaped pid: %d, status: %d.\n", reap_pid, status);
2569           }
2570 #endif
2571           SetLastStopPacket(response);
2572           ClearThreadIDList();
2573           exit_status = response.GetHexU8();
2574         } else {
2575           LLDB_LOGF(log,
2576                     "ProcessGDBRemote::DoDestroy - got unexpected response "
2577                     "to k packet: %s",
2578                     response.GetStringRef().data());
2579           exit_string.assign("got unexpected response to k packet: ");
2580           exit_string.append(std::string(response.GetStringRef()));
2581         }
2582       } else {
2583         LLDB_LOGF(log, "ProcessGDBRemote::DoDestroy - failed to send k packet");
2584         exit_string.assign("failed to send the k packet");
2585       }
2586     } else {
2587       LLDB_LOGF(log,
2588                 "ProcessGDBRemote::DoDestroy - killed or interrupted while "
2589                 "attaching");
2590       exit_string.assign("killed or interrupted while attaching.");
2591     }
2592   } else {
2593     // If we missed setting the exit status on the way out, do it here.
2594     // NB set exit status can be called multiple times, the first one sets the
2595     // status.
2596     exit_string.assign("destroying when not connected to debugserver");
2597   }
2598 
2599   SetExitStatus(exit_status, exit_string.c_str());
2600 
2601   StopAsyncThread();
2602   KillDebugserverProcess();
2603   return error;
2604 }
2605 
SetLastStopPacket(const StringExtractorGDBRemote & response)2606 void ProcessGDBRemote::SetLastStopPacket(
2607     const StringExtractorGDBRemote &response) {
2608   const bool did_exec =
2609       response.GetStringRef().find(";reason:exec;") != std::string::npos;
2610   if (did_exec) {
2611     Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
2612     LLDB_LOGF(log, "ProcessGDBRemote::SetLastStopPacket () - detected exec");
2613 
2614     m_thread_list_real.Clear();
2615     m_thread_list.Clear();
2616     BuildDynamicRegisterInfo(true);
2617     m_gdb_comm.ResetDiscoverableSettings(did_exec);
2618   }
2619 
2620   // Scope the lock
2621   {
2622     // Lock the thread stack while we access it
2623     std::lock_guard<std::recursive_mutex> guard(m_last_stop_packet_mutex);
2624 
2625     // We are are not using non-stop mode, there can only be one last stop
2626     // reply packet, so clear the list.
2627     if (!GetTarget().GetNonStopModeEnabled())
2628       m_stop_packet_stack.clear();
2629 
2630     // Add this stop packet to the stop packet stack This stack will get popped
2631     // and examined when we switch to the Stopped state
2632     m_stop_packet_stack.push_back(response);
2633   }
2634 }
2635 
SetUnixSignals(const UnixSignalsSP & signals_sp)2636 void ProcessGDBRemote::SetUnixSignals(const UnixSignalsSP &signals_sp) {
2637   Process::SetUnixSignals(std::make_shared<GDBRemoteSignals>(signals_sp));
2638 }
2639 
2640 // Process Queries
2641 
IsAlive()2642 bool ProcessGDBRemote::IsAlive() {
2643   return m_gdb_comm.IsConnected() && Process::IsAlive();
2644 }
2645 
GetImageInfoAddress()2646 addr_t ProcessGDBRemote::GetImageInfoAddress() {
2647   // request the link map address via the $qShlibInfoAddr packet
2648   lldb::addr_t addr = m_gdb_comm.GetShlibInfoAddr();
2649 
2650   // the loaded module list can also provides a link map address
2651   if (addr == LLDB_INVALID_ADDRESS) {
2652     llvm::Expected<LoadedModuleInfoList> list = GetLoadedModuleList();
2653     if (!list) {
2654       Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
2655       LLDB_LOG_ERROR(log, list.takeError(), "Failed to read module list: {0}.");
2656     } else {
2657       addr = list->m_link_map;
2658     }
2659   }
2660 
2661   return addr;
2662 }
2663 
WillPublicStop()2664 void ProcessGDBRemote::WillPublicStop() {
2665   // See if the GDB remote client supports the JSON threads info. If so, we
2666   // gather stop info for all threads, expedited registers, expedited memory,
2667   // runtime queue information (iOS and MacOSX only), and more. Expediting
2668   // memory will help stack backtracing be much faster. Expediting registers
2669   // will make sure we don't have to read the thread registers for GPRs.
2670   m_jthreadsinfo_sp = m_gdb_comm.GetThreadsInfo();
2671 
2672   if (m_jthreadsinfo_sp) {
2673     // Now set the stop info for each thread and also expedite any registers
2674     // and memory that was in the jThreadsInfo response.
2675     StructuredData::Array *thread_infos = m_jthreadsinfo_sp->GetAsArray();
2676     if (thread_infos) {
2677       const size_t n = thread_infos->GetSize();
2678       for (size_t i = 0; i < n; ++i) {
2679         StructuredData::Dictionary *thread_dict =
2680             thread_infos->GetItemAtIndex(i)->GetAsDictionary();
2681         if (thread_dict)
2682           SetThreadStopInfo(thread_dict);
2683       }
2684     }
2685   }
2686 }
2687 
2688 // Process Memory
DoReadMemory(addr_t addr,void * buf,size_t size,Status & error)2689 size_t ProcessGDBRemote::DoReadMemory(addr_t addr, void *buf, size_t size,
2690                                       Status &error) {
2691   GetMaxMemorySize();
2692   bool binary_memory_read = m_gdb_comm.GetxPacketSupported();
2693   // M and m packets take 2 bytes for 1 byte of memory
2694   size_t max_memory_size =
2695       binary_memory_read ? m_max_memory_size : m_max_memory_size / 2;
2696   if (size > max_memory_size) {
2697     // Keep memory read sizes down to a sane limit. This function will be
2698     // called multiple times in order to complete the task by
2699     // lldb_private::Process so it is ok to do this.
2700     size = max_memory_size;
2701   }
2702 
2703   char packet[64];
2704   int packet_len;
2705   packet_len = ::snprintf(packet, sizeof(packet), "%c%" PRIx64 ",%" PRIx64,
2706                           binary_memory_read ? 'x' : 'm', (uint64_t)addr,
2707                           (uint64_t)size);
2708   assert(packet_len + 1 < (int)sizeof(packet));
2709   UNUSED_IF_ASSERT_DISABLED(packet_len);
2710   StringExtractorGDBRemote response;
2711   if (m_gdb_comm.SendPacketAndWaitForResponse(packet, response, true) ==
2712       GDBRemoteCommunication::PacketResult::Success) {
2713     if (response.IsNormalResponse()) {
2714       error.Clear();
2715       if (binary_memory_read) {
2716         // The lower level GDBRemoteCommunication packet receive layer has
2717         // already de-quoted any 0x7d character escaping that was present in
2718         // the packet
2719 
2720         size_t data_received_size = response.GetBytesLeft();
2721         if (data_received_size > size) {
2722           // Don't write past the end of BUF if the remote debug server gave us
2723           // too much data for some reason.
2724           data_received_size = size;
2725         }
2726         memcpy(buf, response.GetStringRef().data(), data_received_size);
2727         return data_received_size;
2728       } else {
2729         return response.GetHexBytes(
2730             llvm::MutableArrayRef<uint8_t>((uint8_t *)buf, size), '\xdd');
2731       }
2732     } else if (response.IsErrorResponse())
2733       error.SetErrorStringWithFormat("memory read failed for 0x%" PRIx64, addr);
2734     else if (response.IsUnsupportedResponse())
2735       error.SetErrorStringWithFormat(
2736           "GDB server does not support reading memory");
2737     else
2738       error.SetErrorStringWithFormat(
2739           "unexpected response to GDB server memory read packet '%s': '%s'",
2740           packet, response.GetStringRef().data());
2741   } else {
2742     error.SetErrorStringWithFormat("failed to send packet: '%s'", packet);
2743   }
2744   return 0;
2745 }
2746 
WriteObjectFile(std::vector<ObjectFile::LoadableData> entries)2747 Status ProcessGDBRemote::WriteObjectFile(
2748     std::vector<ObjectFile::LoadableData> entries) {
2749   Status error;
2750   // Sort the entries by address because some writes, like those to flash
2751   // memory, must happen in order of increasing address.
2752   std::stable_sort(
2753       std::begin(entries), std::end(entries),
2754       [](const ObjectFile::LoadableData a, const ObjectFile::LoadableData b) {
2755         return a.Dest < b.Dest;
2756       });
2757   m_allow_flash_writes = true;
2758   error = Process::WriteObjectFile(entries);
2759   if (error.Success())
2760     error = FlashDone();
2761   else
2762     // Even though some of the writing failed, try to send a flash done if some
2763     // of the writing succeeded so the flash state is reset to normal, but
2764     // don't stomp on the error status that was set in the write failure since
2765     // that's the one we want to report back.
2766     FlashDone();
2767   m_allow_flash_writes = false;
2768   return error;
2769 }
2770 
HasErased(FlashRange range)2771 bool ProcessGDBRemote::HasErased(FlashRange range) {
2772   auto size = m_erased_flash_ranges.GetSize();
2773   for (size_t i = 0; i < size; ++i)
2774     if (m_erased_flash_ranges.GetEntryAtIndex(i)->Contains(range))
2775       return true;
2776   return false;
2777 }
2778 
FlashErase(lldb::addr_t addr,size_t size)2779 Status ProcessGDBRemote::FlashErase(lldb::addr_t addr, size_t size) {
2780   Status status;
2781 
2782   MemoryRegionInfo region;
2783   status = GetMemoryRegionInfo(addr, region);
2784   if (!status.Success())
2785     return status;
2786 
2787   // The gdb spec doesn't say if erasures are allowed across multiple regions,
2788   // but we'll disallow it to be safe and to keep the logic simple by worring
2789   // about only one region's block size.  DoMemoryWrite is this function's
2790   // primary user, and it can easily keep writes within a single memory region
2791   if (addr + size > region.GetRange().GetRangeEnd()) {
2792     status.SetErrorString("Unable to erase flash in multiple regions");
2793     return status;
2794   }
2795 
2796   uint64_t blocksize = region.GetBlocksize();
2797   if (blocksize == 0) {
2798     status.SetErrorString("Unable to erase flash because blocksize is 0");
2799     return status;
2800   }
2801 
2802   // Erasures can only be done on block boundary adresses, so round down addr
2803   // and round up size
2804   lldb::addr_t block_start_addr = addr - (addr % blocksize);
2805   size += (addr - block_start_addr);
2806   if ((size % blocksize) != 0)
2807     size += (blocksize - size % blocksize);
2808 
2809   FlashRange range(block_start_addr, size);
2810 
2811   if (HasErased(range))
2812     return status;
2813 
2814   // We haven't erased the entire range, but we may have erased part of it.
2815   // (e.g., block A is already erased and range starts in A and ends in B). So,
2816   // adjust range if necessary to exclude already erased blocks.
2817   if (!m_erased_flash_ranges.IsEmpty()) {
2818     // Assuming that writes and erasures are done in increasing addr order,
2819     // because that is a requirement of the vFlashWrite command.  Therefore, we
2820     // only need to look at the last range in the list for overlap.
2821     const auto &last_range = *m_erased_flash_ranges.Back();
2822     if (range.GetRangeBase() < last_range.GetRangeEnd()) {
2823       auto overlap = last_range.GetRangeEnd() - range.GetRangeBase();
2824       // overlap will be less than range.GetByteSize() or else HasErased()
2825       // would have been true
2826       range.SetByteSize(range.GetByteSize() - overlap);
2827       range.SetRangeBase(range.GetRangeBase() + overlap);
2828     }
2829   }
2830 
2831   StreamString packet;
2832   packet.Printf("vFlashErase:%" PRIx64 ",%" PRIx64, range.GetRangeBase(),
2833                 (uint64_t)range.GetByteSize());
2834 
2835   StringExtractorGDBRemote response;
2836   if (m_gdb_comm.SendPacketAndWaitForResponse(packet.GetString(), response,
2837                                               true) ==
2838       GDBRemoteCommunication::PacketResult::Success) {
2839     if (response.IsOKResponse()) {
2840       m_erased_flash_ranges.Insert(range, true);
2841     } else {
2842       if (response.IsErrorResponse())
2843         status.SetErrorStringWithFormat("flash erase failed for 0x%" PRIx64,
2844                                         addr);
2845       else if (response.IsUnsupportedResponse())
2846         status.SetErrorStringWithFormat("GDB server does not support flashing");
2847       else
2848         status.SetErrorStringWithFormat(
2849             "unexpected response to GDB server flash erase packet '%s': '%s'",
2850             packet.GetData(), response.GetStringRef().data());
2851     }
2852   } else {
2853     status.SetErrorStringWithFormat("failed to send packet: '%s'",
2854                                     packet.GetData());
2855   }
2856   return status;
2857 }
2858 
FlashDone()2859 Status ProcessGDBRemote::FlashDone() {
2860   Status status;
2861   // If we haven't erased any blocks, then we must not have written anything
2862   // either, so there is no need to actually send a vFlashDone command
2863   if (m_erased_flash_ranges.IsEmpty())
2864     return status;
2865   StringExtractorGDBRemote response;
2866   if (m_gdb_comm.SendPacketAndWaitForResponse("vFlashDone", response, true) ==
2867       GDBRemoteCommunication::PacketResult::Success) {
2868     if (response.IsOKResponse()) {
2869       m_erased_flash_ranges.Clear();
2870     } else {
2871       if (response.IsErrorResponse())
2872         status.SetErrorStringWithFormat("flash done failed");
2873       else if (response.IsUnsupportedResponse())
2874         status.SetErrorStringWithFormat("GDB server does not support flashing");
2875       else
2876         status.SetErrorStringWithFormat(
2877             "unexpected response to GDB server flash done packet: '%s'",
2878             response.GetStringRef().data());
2879     }
2880   } else {
2881     status.SetErrorStringWithFormat("failed to send flash done packet");
2882   }
2883   return status;
2884 }
2885 
DoWriteMemory(addr_t addr,const void * buf,size_t size,Status & error)2886 size_t ProcessGDBRemote::DoWriteMemory(addr_t addr, const void *buf,
2887                                        size_t size, Status &error) {
2888   GetMaxMemorySize();
2889   // M and m packets take 2 bytes for 1 byte of memory
2890   size_t max_memory_size = m_max_memory_size / 2;
2891   if (size > max_memory_size) {
2892     // Keep memory read sizes down to a sane limit. This function will be
2893     // called multiple times in order to complete the task by
2894     // lldb_private::Process so it is ok to do this.
2895     size = max_memory_size;
2896   }
2897 
2898   StreamGDBRemote packet;
2899 
2900   MemoryRegionInfo region;
2901   Status region_status = GetMemoryRegionInfo(addr, region);
2902 
2903   bool is_flash =
2904       region_status.Success() && region.GetFlash() == MemoryRegionInfo::eYes;
2905 
2906   if (is_flash) {
2907     if (!m_allow_flash_writes) {
2908       error.SetErrorString("Writing to flash memory is not allowed");
2909       return 0;
2910     }
2911     // Keep the write within a flash memory region
2912     if (addr + size > region.GetRange().GetRangeEnd())
2913       size = region.GetRange().GetRangeEnd() - addr;
2914     // Flash memory must be erased before it can be written
2915     error = FlashErase(addr, size);
2916     if (!error.Success())
2917       return 0;
2918     packet.Printf("vFlashWrite:%" PRIx64 ":", addr);
2919     packet.PutEscapedBytes(buf, size);
2920   } else {
2921     packet.Printf("M%" PRIx64 ",%" PRIx64 ":", addr, (uint64_t)size);
2922     packet.PutBytesAsRawHex8(buf, size, endian::InlHostByteOrder(),
2923                              endian::InlHostByteOrder());
2924   }
2925   StringExtractorGDBRemote response;
2926   if (m_gdb_comm.SendPacketAndWaitForResponse(packet.GetString(), response,
2927                                               true) ==
2928       GDBRemoteCommunication::PacketResult::Success) {
2929     if (response.IsOKResponse()) {
2930       error.Clear();
2931       return size;
2932     } else if (response.IsErrorResponse())
2933       error.SetErrorStringWithFormat("memory write failed for 0x%" PRIx64,
2934                                      addr);
2935     else if (response.IsUnsupportedResponse())
2936       error.SetErrorStringWithFormat(
2937           "GDB server does not support writing memory");
2938     else
2939       error.SetErrorStringWithFormat(
2940           "unexpected response to GDB server memory write packet '%s': '%s'",
2941           packet.GetData(), response.GetStringRef().data());
2942   } else {
2943     error.SetErrorStringWithFormat("failed to send packet: '%s'",
2944                                    packet.GetData());
2945   }
2946   return 0;
2947 }
2948 
DoAllocateMemory(size_t size,uint32_t permissions,Status & error)2949 lldb::addr_t ProcessGDBRemote::DoAllocateMemory(size_t size,
2950                                                 uint32_t permissions,
2951                                                 Status &error) {
2952   Log *log(
2953       GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS | LIBLLDB_LOG_EXPRESSIONS));
2954   addr_t allocated_addr = LLDB_INVALID_ADDRESS;
2955 
2956   if (m_gdb_comm.SupportsAllocDeallocMemory() != eLazyBoolNo) {
2957     allocated_addr = m_gdb_comm.AllocateMemory(size, permissions);
2958     if (allocated_addr != LLDB_INVALID_ADDRESS ||
2959         m_gdb_comm.SupportsAllocDeallocMemory() == eLazyBoolYes)
2960       return allocated_addr;
2961   }
2962 
2963   if (m_gdb_comm.SupportsAllocDeallocMemory() == eLazyBoolNo) {
2964     // Call mmap() to create memory in the inferior..
2965     unsigned prot = 0;
2966     if (permissions & lldb::ePermissionsReadable)
2967       prot |= eMmapProtRead;
2968     if (permissions & lldb::ePermissionsWritable)
2969       prot |= eMmapProtWrite;
2970     if (permissions & lldb::ePermissionsExecutable)
2971       prot |= eMmapProtExec;
2972 
2973     if (InferiorCallMmap(this, allocated_addr, 0, size, prot,
2974                          eMmapFlagsAnon | eMmapFlagsPrivate, -1, 0))
2975       m_addr_to_mmap_size[allocated_addr] = size;
2976     else {
2977       allocated_addr = LLDB_INVALID_ADDRESS;
2978       LLDB_LOGF(log,
2979                 "ProcessGDBRemote::%s no direct stub support for memory "
2980                 "allocation, and InferiorCallMmap also failed - is stub "
2981                 "missing register context save/restore capability?",
2982                 __FUNCTION__);
2983     }
2984   }
2985 
2986   if (allocated_addr == LLDB_INVALID_ADDRESS)
2987     error.SetErrorStringWithFormat(
2988         "unable to allocate %" PRIu64 " bytes of memory with permissions %s",
2989         (uint64_t)size, GetPermissionsAsCString(permissions));
2990   else
2991     error.Clear();
2992   return allocated_addr;
2993 }
2994 
GetMemoryRegionInfo(addr_t load_addr,MemoryRegionInfo & region_info)2995 Status ProcessGDBRemote::GetMemoryRegionInfo(addr_t load_addr,
2996                                              MemoryRegionInfo &region_info) {
2997 
2998   Status error(m_gdb_comm.GetMemoryRegionInfo(load_addr, region_info));
2999   return error;
3000 }
3001 
GetWatchpointSupportInfo(uint32_t & num)3002 Status ProcessGDBRemote::GetWatchpointSupportInfo(uint32_t &num) {
3003 
3004   Status error(m_gdb_comm.GetWatchpointSupportInfo(num));
3005   return error;
3006 }
3007 
GetWatchpointSupportInfo(uint32_t & num,bool & after)3008 Status ProcessGDBRemote::GetWatchpointSupportInfo(uint32_t &num, bool &after) {
3009   Status error(m_gdb_comm.GetWatchpointSupportInfo(
3010       num, after, GetTarget().GetArchitecture()));
3011   return error;
3012 }
3013 
DoDeallocateMemory(lldb::addr_t addr)3014 Status ProcessGDBRemote::DoDeallocateMemory(lldb::addr_t addr) {
3015   Status error;
3016   LazyBool supported = m_gdb_comm.SupportsAllocDeallocMemory();
3017 
3018   switch (supported) {
3019   case eLazyBoolCalculate:
3020     // We should never be deallocating memory without allocating memory first
3021     // so we should never get eLazyBoolCalculate
3022     error.SetErrorString(
3023         "tried to deallocate memory without ever allocating memory");
3024     break;
3025 
3026   case eLazyBoolYes:
3027     if (!m_gdb_comm.DeallocateMemory(addr))
3028       error.SetErrorStringWithFormat(
3029           "unable to deallocate memory at 0x%" PRIx64, addr);
3030     break;
3031 
3032   case eLazyBoolNo:
3033     // Call munmap() to deallocate memory in the inferior..
3034     {
3035       MMapMap::iterator pos = m_addr_to_mmap_size.find(addr);
3036       if (pos != m_addr_to_mmap_size.end() &&
3037           InferiorCallMunmap(this, addr, pos->second))
3038         m_addr_to_mmap_size.erase(pos);
3039       else
3040         error.SetErrorStringWithFormat(
3041             "unable to deallocate memory at 0x%" PRIx64, addr);
3042     }
3043     break;
3044   }
3045 
3046   return error;
3047 }
3048 
3049 // Process STDIO
PutSTDIN(const char * src,size_t src_len,Status & error)3050 size_t ProcessGDBRemote::PutSTDIN(const char *src, size_t src_len,
3051                                   Status &error) {
3052   if (m_stdio_communication.IsConnected()) {
3053     ConnectionStatus status;
3054     m_stdio_communication.Write(src, src_len, status, nullptr);
3055   } else if (m_stdin_forward) {
3056     m_gdb_comm.SendStdinNotification(src, src_len);
3057   }
3058   return 0;
3059 }
3060 
EnableBreakpointSite(BreakpointSite * bp_site)3061 Status ProcessGDBRemote::EnableBreakpointSite(BreakpointSite *bp_site) {
3062   Status error;
3063   assert(bp_site != nullptr);
3064 
3065   // Get logging info
3066   Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_BREAKPOINTS));
3067   user_id_t site_id = bp_site->GetID();
3068 
3069   // Get the breakpoint address
3070   const addr_t addr = bp_site->GetLoadAddress();
3071 
3072   // Log that a breakpoint was requested
3073   LLDB_LOGF(log,
3074             "ProcessGDBRemote::EnableBreakpointSite (size_id = %" PRIu64
3075             ") address = 0x%" PRIx64,
3076             site_id, (uint64_t)addr);
3077 
3078   // Breakpoint already exists and is enabled
3079   if (bp_site->IsEnabled()) {
3080     LLDB_LOGF(log,
3081               "ProcessGDBRemote::EnableBreakpointSite (size_id = %" PRIu64
3082               ") address = 0x%" PRIx64 " -- SUCCESS (already enabled)",
3083               site_id, (uint64_t)addr);
3084     return error;
3085   }
3086 
3087   // Get the software breakpoint trap opcode size
3088   const size_t bp_op_size = GetSoftwareBreakpointTrapOpcode(bp_site);
3089 
3090   // SupportsGDBStoppointPacket() simply checks a boolean, indicating if this
3091   // breakpoint type is supported by the remote stub. These are set to true by
3092   // default, and later set to false only after we receive an unimplemented
3093   // response when sending a breakpoint packet. This means initially that
3094   // unless we were specifically instructed to use a hardware breakpoint, LLDB
3095   // will attempt to set a software breakpoint. HardwareRequired() also queries
3096   // a boolean variable which indicates if the user specifically asked for
3097   // hardware breakpoints.  If true then we will skip over software
3098   // breakpoints.
3099   if (m_gdb_comm.SupportsGDBStoppointPacket(eBreakpointSoftware) &&
3100       (!bp_site->HardwareRequired())) {
3101     // Try to send off a software breakpoint packet ($Z0)
3102     uint8_t error_no = m_gdb_comm.SendGDBStoppointTypePacket(
3103         eBreakpointSoftware, true, addr, bp_op_size);
3104     if (error_no == 0) {
3105       // The breakpoint was placed successfully
3106       bp_site->SetEnabled(true);
3107       bp_site->SetType(BreakpointSite::eExternal);
3108       return error;
3109     }
3110 
3111     // SendGDBStoppointTypePacket() will return an error if it was unable to
3112     // set this breakpoint. We need to differentiate between a error specific
3113     // to placing this breakpoint or if we have learned that this breakpoint
3114     // type is unsupported. To do this, we must test the support boolean for
3115     // this breakpoint type to see if it now indicates that this breakpoint
3116     // type is unsupported.  If they are still supported then we should return
3117     // with the error code.  If they are now unsupported, then we would like to
3118     // fall through and try another form of breakpoint.
3119     if (m_gdb_comm.SupportsGDBStoppointPacket(eBreakpointSoftware)) {
3120       if (error_no != UINT8_MAX)
3121         error.SetErrorStringWithFormat(
3122             "error: %d sending the breakpoint request", error_no);
3123       else
3124         error.SetErrorString("error sending the breakpoint request");
3125       return error;
3126     }
3127 
3128     // We reach here when software breakpoints have been found to be
3129     // unsupported. For future calls to set a breakpoint, we will not attempt
3130     // to set a breakpoint with a type that is known not to be supported.
3131     LLDB_LOGF(log, "Software breakpoints are unsupported");
3132 
3133     // So we will fall through and try a hardware breakpoint
3134   }
3135 
3136   // The process of setting a hardware breakpoint is much the same as above.
3137   // We check the supported boolean for this breakpoint type, and if it is
3138   // thought to be supported then we will try to set this breakpoint with a
3139   // hardware breakpoint.
3140   if (m_gdb_comm.SupportsGDBStoppointPacket(eBreakpointHardware)) {
3141     // Try to send off a hardware breakpoint packet ($Z1)
3142     uint8_t error_no = m_gdb_comm.SendGDBStoppointTypePacket(
3143         eBreakpointHardware, true, addr, bp_op_size);
3144     if (error_no == 0) {
3145       // The breakpoint was placed successfully
3146       bp_site->SetEnabled(true);
3147       bp_site->SetType(BreakpointSite::eHardware);
3148       return error;
3149     }
3150 
3151     // Check if the error was something other then an unsupported breakpoint
3152     // type
3153     if (m_gdb_comm.SupportsGDBStoppointPacket(eBreakpointHardware)) {
3154       // Unable to set this hardware breakpoint
3155       if (error_no != UINT8_MAX)
3156         error.SetErrorStringWithFormat(
3157             "error: %d sending the hardware breakpoint request "
3158             "(hardware breakpoint resources might be exhausted or unavailable)",
3159             error_no);
3160       else
3161         error.SetErrorString("error sending the hardware breakpoint request "
3162                              "(hardware breakpoint resources "
3163                              "might be exhausted or unavailable)");
3164       return error;
3165     }
3166 
3167     // We will reach here when the stub gives an unsupported response to a
3168     // hardware breakpoint
3169     LLDB_LOGF(log, "Hardware breakpoints are unsupported");
3170 
3171     // Finally we will falling through to a #trap style breakpoint
3172   }
3173 
3174   // Don't fall through when hardware breakpoints were specifically requested
3175   if (bp_site->HardwareRequired()) {
3176     error.SetErrorString("hardware breakpoints are not supported");
3177     return error;
3178   }
3179 
3180   // As a last resort we want to place a manual breakpoint. An instruction is
3181   // placed into the process memory using memory write packets.
3182   return EnableSoftwareBreakpoint(bp_site);
3183 }
3184 
DisableBreakpointSite(BreakpointSite * bp_site)3185 Status ProcessGDBRemote::DisableBreakpointSite(BreakpointSite *bp_site) {
3186   Status error;
3187   assert(bp_site != nullptr);
3188   addr_t addr = bp_site->GetLoadAddress();
3189   user_id_t site_id = bp_site->GetID();
3190   Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_BREAKPOINTS));
3191   LLDB_LOGF(log,
3192             "ProcessGDBRemote::DisableBreakpointSite (site_id = %" PRIu64
3193             ") addr = 0x%8.8" PRIx64,
3194             site_id, (uint64_t)addr);
3195 
3196   if (bp_site->IsEnabled()) {
3197     const size_t bp_op_size = GetSoftwareBreakpointTrapOpcode(bp_site);
3198 
3199     BreakpointSite::Type bp_type = bp_site->GetType();
3200     switch (bp_type) {
3201     case BreakpointSite::eSoftware:
3202       error = DisableSoftwareBreakpoint(bp_site);
3203       break;
3204 
3205     case BreakpointSite::eHardware:
3206       if (m_gdb_comm.SendGDBStoppointTypePacket(eBreakpointHardware, false,
3207                                                 addr, bp_op_size))
3208         error.SetErrorToGenericError();
3209       break;
3210 
3211     case BreakpointSite::eExternal: {
3212       if (m_gdb_comm.SendGDBStoppointTypePacket(eBreakpointSoftware, false,
3213                                                 addr, bp_op_size))
3214         error.SetErrorToGenericError();
3215     } break;
3216     }
3217     if (error.Success())
3218       bp_site->SetEnabled(false);
3219   } else {
3220     LLDB_LOGF(log,
3221               "ProcessGDBRemote::DisableBreakpointSite (site_id = %" PRIu64
3222               ") addr = 0x%8.8" PRIx64 " -- SUCCESS (already disabled)",
3223               site_id, (uint64_t)addr);
3224     return error;
3225   }
3226 
3227   if (error.Success())
3228     error.SetErrorToGenericError();
3229   return error;
3230 }
3231 
3232 // Pre-requisite: wp != NULL.
GetGDBStoppointType(Watchpoint * wp)3233 static GDBStoppointType GetGDBStoppointType(Watchpoint *wp) {
3234   assert(wp);
3235   bool watch_read = wp->WatchpointRead();
3236   bool watch_write = wp->WatchpointWrite();
3237 
3238   // watch_read and watch_write cannot both be false.
3239   assert(watch_read || watch_write);
3240   if (watch_read && watch_write)
3241     return eWatchpointReadWrite;
3242   else if (watch_read)
3243     return eWatchpointRead;
3244   else // Must be watch_write, then.
3245     return eWatchpointWrite;
3246 }
3247 
EnableWatchpoint(Watchpoint * wp,bool notify)3248 Status ProcessGDBRemote::EnableWatchpoint(Watchpoint *wp, bool notify) {
3249   Status error;
3250   if (wp) {
3251     user_id_t watchID = wp->GetID();
3252     addr_t addr = wp->GetLoadAddress();
3253     Log *log(
3254         ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_WATCHPOINTS));
3255     LLDB_LOGF(log, "ProcessGDBRemote::EnableWatchpoint(watchID = %" PRIu64 ")",
3256               watchID);
3257     if (wp->IsEnabled()) {
3258       LLDB_LOGF(log,
3259                 "ProcessGDBRemote::EnableWatchpoint(watchID = %" PRIu64
3260                 ") addr = 0x%8.8" PRIx64 ": watchpoint already enabled.",
3261                 watchID, (uint64_t)addr);
3262       return error;
3263     }
3264 
3265     GDBStoppointType type = GetGDBStoppointType(wp);
3266     // Pass down an appropriate z/Z packet...
3267     if (m_gdb_comm.SupportsGDBStoppointPacket(type)) {
3268       if (m_gdb_comm.SendGDBStoppointTypePacket(type, true, addr,
3269                                                 wp->GetByteSize()) == 0) {
3270         wp->SetEnabled(true, notify);
3271         return error;
3272       } else
3273         error.SetErrorString("sending gdb watchpoint packet failed");
3274     } else
3275       error.SetErrorString("watchpoints not supported");
3276   } else {
3277     error.SetErrorString("Watchpoint argument was NULL.");
3278   }
3279   if (error.Success())
3280     error.SetErrorToGenericError();
3281   return error;
3282 }
3283 
DisableWatchpoint(Watchpoint * wp,bool notify)3284 Status ProcessGDBRemote::DisableWatchpoint(Watchpoint *wp, bool notify) {
3285   Status error;
3286   if (wp) {
3287     user_id_t watchID = wp->GetID();
3288 
3289     Log *log(
3290         ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_WATCHPOINTS));
3291 
3292     addr_t addr = wp->GetLoadAddress();
3293 
3294     LLDB_LOGF(log,
3295               "ProcessGDBRemote::DisableWatchpoint (watchID = %" PRIu64
3296               ") addr = 0x%8.8" PRIx64,
3297               watchID, (uint64_t)addr);
3298 
3299     if (!wp->IsEnabled()) {
3300       LLDB_LOGF(log,
3301                 "ProcessGDBRemote::DisableWatchpoint (watchID = %" PRIu64
3302                 ") addr = 0x%8.8" PRIx64 " -- SUCCESS (already disabled)",
3303                 watchID, (uint64_t)addr);
3304       // See also 'class WatchpointSentry' within StopInfo.cpp. This disabling
3305       // attempt might come from the user-supplied actions, we'll route it in
3306       // order for the watchpoint object to intelligently process this action.
3307       wp->SetEnabled(false, notify);
3308       return error;
3309     }
3310 
3311     if (wp->IsHardware()) {
3312       GDBStoppointType type = GetGDBStoppointType(wp);
3313       // Pass down an appropriate z/Z packet...
3314       if (m_gdb_comm.SendGDBStoppointTypePacket(type, false, addr,
3315                                                 wp->GetByteSize()) == 0) {
3316         wp->SetEnabled(false, notify);
3317         return error;
3318       } else
3319         error.SetErrorString("sending gdb watchpoint packet failed");
3320     }
3321     // TODO: clear software watchpoints if we implement them
3322   } else {
3323     error.SetErrorString("Watchpoint argument was NULL.");
3324   }
3325   if (error.Success())
3326     error.SetErrorToGenericError();
3327   return error;
3328 }
3329 
Clear()3330 void ProcessGDBRemote::Clear() {
3331   m_thread_list_real.Clear();
3332   m_thread_list.Clear();
3333 }
3334 
DoSignal(int signo)3335 Status ProcessGDBRemote::DoSignal(int signo) {
3336   Status error;
3337   Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
3338   LLDB_LOGF(log, "ProcessGDBRemote::DoSignal (signal = %d)", signo);
3339 
3340   if (!m_gdb_comm.SendAsyncSignal(signo))
3341     error.SetErrorStringWithFormat("failed to send signal %i", signo);
3342   return error;
3343 }
3344 
ConnectToReplayServer()3345 Status ProcessGDBRemote::ConnectToReplayServer() {
3346   Status status = m_gdb_replay_server.Connect(m_gdb_comm);
3347   if (status.Fail())
3348     return status;
3349 
3350   // Enable replay mode.
3351   m_replay_mode = true;
3352 
3353   // Start server thread.
3354   m_gdb_replay_server.StartAsyncThread();
3355 
3356   // Start client thread.
3357   StartAsyncThread();
3358 
3359   // Do the usual setup.
3360   return ConnectToDebugserver("");
3361 }
3362 
3363 Status
EstablishConnectionIfNeeded(const ProcessInfo & process_info)3364 ProcessGDBRemote::EstablishConnectionIfNeeded(const ProcessInfo &process_info) {
3365   // Make sure we aren't already connected?
3366   if (m_gdb_comm.IsConnected())
3367     return Status();
3368 
3369   PlatformSP platform_sp(GetTarget().GetPlatform());
3370   if (platform_sp && !platform_sp->IsHost())
3371     return Status("Lost debug server connection");
3372 
3373   if (repro::Reproducer::Instance().IsReplaying())
3374     return ConnectToReplayServer();
3375 
3376   auto error = LaunchAndConnectToDebugserver(process_info);
3377   if (error.Fail()) {
3378     const char *error_string = error.AsCString();
3379     if (error_string == nullptr)
3380       error_string = "unable to launch " DEBUGSERVER_BASENAME;
3381   }
3382   return error;
3383 }
3384 #if !defined(_WIN32)
3385 #define USE_SOCKETPAIR_FOR_LOCAL_CONNECTION 1
3386 #endif
3387 
3388 #ifdef USE_SOCKETPAIR_FOR_LOCAL_CONNECTION
SetCloexecFlag(int fd)3389 static bool SetCloexecFlag(int fd) {
3390 #if defined(FD_CLOEXEC)
3391   int flags = ::fcntl(fd, F_GETFD);
3392   if (flags == -1)
3393     return false;
3394   return (::fcntl(fd, F_SETFD, flags | FD_CLOEXEC) == 0);
3395 #else
3396   return false;
3397 #endif
3398 }
3399 #endif
3400 
LaunchAndConnectToDebugserver(const ProcessInfo & process_info)3401 Status ProcessGDBRemote::LaunchAndConnectToDebugserver(
3402     const ProcessInfo &process_info) {
3403   using namespace std::placeholders; // For _1, _2, etc.
3404 
3405   Status error;
3406   if (m_debugserver_pid == LLDB_INVALID_PROCESS_ID) {
3407     // If we locate debugserver, keep that located version around
3408     static FileSpec g_debugserver_file_spec;
3409 
3410     ProcessLaunchInfo debugserver_launch_info;
3411     // Make debugserver run in its own session so signals generated by special
3412     // terminal key sequences (^C) don't affect debugserver.
3413     debugserver_launch_info.SetLaunchInSeparateProcessGroup(true);
3414 
3415     const std::weak_ptr<ProcessGDBRemote> this_wp =
3416         std::static_pointer_cast<ProcessGDBRemote>(shared_from_this());
3417     debugserver_launch_info.SetMonitorProcessCallback(
3418         std::bind(MonitorDebugserverProcess, this_wp, _1, _2, _3, _4), false);
3419     debugserver_launch_info.SetUserID(process_info.GetUserID());
3420 
3421 #if defined(__APPLE__)
3422     // On macOS 11, we need to support x86_64 applications translated to
3423     // arm64. We check whether a binary is translated and spawn the correct
3424     // debugserver accordingly.
3425     int mib[] = { CTL_KERN, KERN_PROC, KERN_PROC_PID,
3426                   static_cast<int>(process_info.GetProcessID()) };
3427     struct kinfo_proc processInfo;
3428     size_t bufsize = sizeof(processInfo);
3429     if (sysctl(mib, (unsigned)(sizeof(mib)/sizeof(int)), &processInfo,
3430                &bufsize, NULL, 0) == 0 && bufsize > 0) {
3431       if (processInfo.kp_proc.p_flag & P_TRANSLATED) {
3432         FileSpec rosetta_debugserver("/Library/Apple/usr/libexec/oah/debugserver");
3433         debugserver_launch_info.SetExecutableFile(rosetta_debugserver, false);
3434       }
3435     }
3436 #endif
3437 
3438     int communication_fd = -1;
3439 #ifdef USE_SOCKETPAIR_FOR_LOCAL_CONNECTION
3440     // Use a socketpair on non-Windows systems for security and performance
3441     // reasons.
3442     int sockets[2]; /* the pair of socket descriptors */
3443     if (socketpair(AF_UNIX, SOCK_STREAM, 0, sockets) == -1) {
3444       error.SetErrorToErrno();
3445       return error;
3446     }
3447 
3448     int our_socket = sockets[0];
3449     int gdb_socket = sockets[1];
3450     auto cleanup_our = llvm::make_scope_exit([&]() { close(our_socket); });
3451     auto cleanup_gdb = llvm::make_scope_exit([&]() { close(gdb_socket); });
3452 
3453     // Don't let any child processes inherit our communication socket
3454     SetCloexecFlag(our_socket);
3455     communication_fd = gdb_socket;
3456 #endif
3457 
3458     error = m_gdb_comm.StartDebugserverProcess(
3459         nullptr, GetTarget().GetPlatform().get(), debugserver_launch_info,
3460         nullptr, nullptr, communication_fd);
3461 
3462     if (error.Success())
3463       m_debugserver_pid = debugserver_launch_info.GetProcessID();
3464     else
3465       m_debugserver_pid = LLDB_INVALID_PROCESS_ID;
3466 
3467     if (m_debugserver_pid != LLDB_INVALID_PROCESS_ID) {
3468 #ifdef USE_SOCKETPAIR_FOR_LOCAL_CONNECTION
3469       // Our process spawned correctly, we can now set our connection to use
3470       // our end of the socket pair
3471       cleanup_our.release();
3472       m_gdb_comm.SetConnection(
3473           std::make_unique<ConnectionFileDescriptor>(our_socket, true));
3474 #endif
3475       StartAsyncThread();
3476     }
3477 
3478     if (error.Fail()) {
3479       Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
3480 
3481       LLDB_LOGF(log, "failed to start debugserver process: %s",
3482                 error.AsCString());
3483       return error;
3484     }
3485 
3486     if (m_gdb_comm.IsConnected()) {
3487       // Finish the connection process by doing the handshake without
3488       // connecting (send NULL URL)
3489       error = ConnectToDebugserver("");
3490     } else {
3491       error.SetErrorString("connection failed");
3492     }
3493   }
3494   return error;
3495 }
3496 
MonitorDebugserverProcess(std::weak_ptr<ProcessGDBRemote> process_wp,lldb::pid_t debugserver_pid,bool exited,int signo,int exit_status)3497 bool ProcessGDBRemote::MonitorDebugserverProcess(
3498     std::weak_ptr<ProcessGDBRemote> process_wp, lldb::pid_t debugserver_pid,
3499     bool exited,    // True if the process did exit
3500     int signo,      // Zero for no signal
3501     int exit_status // Exit value of process if signal is zero
3502 ) {
3503   // "debugserver_pid" argument passed in is the process ID for debugserver
3504   // that we are tracking...
3505   Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
3506   const bool handled = true;
3507 
3508   LLDB_LOGF(log,
3509             "ProcessGDBRemote::%s(process_wp, pid=%" PRIu64
3510             ", signo=%i (0x%x), exit_status=%i)",
3511             __FUNCTION__, debugserver_pid, signo, signo, exit_status);
3512 
3513   std::shared_ptr<ProcessGDBRemote> process_sp = process_wp.lock();
3514   LLDB_LOGF(log, "ProcessGDBRemote::%s(process = %p)", __FUNCTION__,
3515             static_cast<void *>(process_sp.get()));
3516   if (!process_sp || process_sp->m_debugserver_pid != debugserver_pid)
3517     return handled;
3518 
3519   // Sleep for a half a second to make sure our inferior process has time to
3520   // set its exit status before we set it incorrectly when both the debugserver
3521   // and the inferior process shut down.
3522   std::this_thread::sleep_for(std::chrono::milliseconds(500));
3523 
3524   // If our process hasn't yet exited, debugserver might have died. If the
3525   // process did exit, then we are reaping it.
3526   const StateType state = process_sp->GetState();
3527 
3528   if (state != eStateInvalid && state != eStateUnloaded &&
3529       state != eStateExited && state != eStateDetached) {
3530     char error_str[1024];
3531     if (signo) {
3532       const char *signal_cstr =
3533           process_sp->GetUnixSignals()->GetSignalAsCString(signo);
3534       if (signal_cstr)
3535         ::snprintf(error_str, sizeof(error_str),
3536                    DEBUGSERVER_BASENAME " died with signal %s", signal_cstr);
3537       else
3538         ::snprintf(error_str, sizeof(error_str),
3539                    DEBUGSERVER_BASENAME " died with signal %i", signo);
3540     } else {
3541       ::snprintf(error_str, sizeof(error_str),
3542                  DEBUGSERVER_BASENAME " died with an exit status of 0x%8.8x",
3543                  exit_status);
3544     }
3545 
3546     process_sp->SetExitStatus(-1, error_str);
3547   }
3548   // Debugserver has exited we need to let our ProcessGDBRemote know that it no
3549   // longer has a debugserver instance
3550   process_sp->m_debugserver_pid = LLDB_INVALID_PROCESS_ID;
3551   return handled;
3552 }
3553 
KillDebugserverProcess()3554 void ProcessGDBRemote::KillDebugserverProcess() {
3555   m_gdb_comm.Disconnect();
3556   if (m_debugserver_pid != LLDB_INVALID_PROCESS_ID) {
3557     Host::Kill(m_debugserver_pid, SIGINT);
3558     m_debugserver_pid = LLDB_INVALID_PROCESS_ID;
3559   }
3560 }
3561 
Initialize()3562 void ProcessGDBRemote::Initialize() {
3563   static llvm::once_flag g_once_flag;
3564 
3565   llvm::call_once(g_once_flag, []() {
3566     PluginManager::RegisterPlugin(GetPluginNameStatic(),
3567                                   GetPluginDescriptionStatic(), CreateInstance,
3568                                   DebuggerInitialize);
3569   });
3570 }
3571 
DebuggerInitialize(Debugger & debugger)3572 void ProcessGDBRemote::DebuggerInitialize(Debugger &debugger) {
3573   if (!PluginManager::GetSettingForProcessPlugin(
3574           debugger, PluginProperties::GetSettingName())) {
3575     const bool is_global_setting = true;
3576     PluginManager::CreateSettingForProcessPlugin(
3577         debugger, GetGlobalPluginProperties()->GetValueProperties(),
3578         ConstString("Properties for the gdb-remote process plug-in."),
3579         is_global_setting);
3580   }
3581 }
3582 
StartAsyncThread()3583 bool ProcessGDBRemote::StartAsyncThread() {
3584   Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
3585 
3586   LLDB_LOGF(log, "ProcessGDBRemote::%s ()", __FUNCTION__);
3587 
3588   std::lock_guard<std::recursive_mutex> guard(m_async_thread_state_mutex);
3589   if (!m_async_thread.IsJoinable()) {
3590     // Create a thread that watches our internal state and controls which
3591     // events make it to clients (into the DCProcess event queue).
3592 
3593     llvm::Expected<HostThread> async_thread = ThreadLauncher::LaunchThread(
3594         "<lldb.process.gdb-remote.async>", ProcessGDBRemote::AsyncThread, this);
3595     if (!async_thread) {
3596       LLDB_LOG_ERROR(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_HOST),
3597                      async_thread.takeError(),
3598                      "failed to launch host thread: {}");
3599       return false;
3600     }
3601     m_async_thread = *async_thread;
3602   } else
3603     LLDB_LOGF(log,
3604               "ProcessGDBRemote::%s () - Called when Async thread was "
3605               "already running.",
3606               __FUNCTION__);
3607 
3608   return m_async_thread.IsJoinable();
3609 }
3610 
StopAsyncThread()3611 void ProcessGDBRemote::StopAsyncThread() {
3612   Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
3613 
3614   LLDB_LOGF(log, "ProcessGDBRemote::%s ()", __FUNCTION__);
3615 
3616   std::lock_guard<std::recursive_mutex> guard(m_async_thread_state_mutex);
3617   if (m_async_thread.IsJoinable()) {
3618     m_async_broadcaster.BroadcastEvent(eBroadcastBitAsyncThreadShouldExit);
3619 
3620     //  This will shut down the async thread.
3621     m_gdb_comm.Disconnect(); // Disconnect from the debug server.
3622 
3623     // Stop the stdio thread
3624     m_async_thread.Join(nullptr);
3625     m_async_thread.Reset();
3626   } else
3627     LLDB_LOGF(
3628         log,
3629         "ProcessGDBRemote::%s () - Called when Async thread was not running.",
3630         __FUNCTION__);
3631 }
3632 
HandleNotifyPacket(StringExtractorGDBRemote & packet)3633 bool ProcessGDBRemote::HandleNotifyPacket(StringExtractorGDBRemote &packet) {
3634   // get the packet at a string
3635   const std::string &pkt = std::string(packet.GetStringRef());
3636   // skip %stop:
3637   StringExtractorGDBRemote stop_info(pkt.c_str() + 5);
3638 
3639   // pass as a thread stop info packet
3640   SetLastStopPacket(stop_info);
3641 
3642   // check for more stop reasons
3643   HandleStopReplySequence();
3644 
3645   // if the process is stopped then we need to fake a resume so that we can
3646   // stop properly with the new break. This is possible due to
3647   // SetPrivateState() broadcasting the state change as a side effect.
3648   if (GetPrivateState() == lldb::StateType::eStateStopped) {
3649     SetPrivateState(lldb::StateType::eStateRunning);
3650   }
3651 
3652   // since we have some stopped packets we can halt the process
3653   SetPrivateState(lldb::StateType::eStateStopped);
3654 
3655   return true;
3656 }
3657 
AsyncThread(void * arg)3658 thread_result_t ProcessGDBRemote::AsyncThread(void *arg) {
3659   ProcessGDBRemote *process = (ProcessGDBRemote *)arg;
3660 
3661   Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
3662   LLDB_LOGF(log,
3663             "ProcessGDBRemote::%s (arg = %p, pid = %" PRIu64
3664             ") thread starting...",
3665             __FUNCTION__, arg, process->GetID());
3666 
3667   EventSP event_sp;
3668   bool done = false;
3669   while (!done) {
3670     LLDB_LOGF(log,
3671               "ProcessGDBRemote::%s (arg = %p, pid = %" PRIu64
3672               ") listener.WaitForEvent (NULL, event_sp)...",
3673               __FUNCTION__, arg, process->GetID());
3674     if (process->m_async_listener_sp->GetEvent(event_sp, llvm::None)) {
3675       const uint32_t event_type = event_sp->GetType();
3676       if (event_sp->BroadcasterIs(&process->m_async_broadcaster)) {
3677         LLDB_LOGF(log,
3678                   "ProcessGDBRemote::%s (arg = %p, pid = %" PRIu64
3679                   ") Got an event of type: %d...",
3680                   __FUNCTION__, arg, process->GetID(), event_type);
3681 
3682         switch (event_type) {
3683         case eBroadcastBitAsyncContinue: {
3684           const EventDataBytes *continue_packet =
3685               EventDataBytes::GetEventDataFromEvent(event_sp.get());
3686 
3687           if (continue_packet) {
3688             const char *continue_cstr =
3689                 (const char *)continue_packet->GetBytes();
3690             const size_t continue_cstr_len = continue_packet->GetByteSize();
3691             LLDB_LOGF(log,
3692                       "ProcessGDBRemote::%s (arg = %p, pid = %" PRIu64
3693                       ") got eBroadcastBitAsyncContinue: %s",
3694                       __FUNCTION__, arg, process->GetID(), continue_cstr);
3695 
3696             if (::strstr(continue_cstr, "vAttach") == nullptr)
3697               process->SetPrivateState(eStateRunning);
3698             StringExtractorGDBRemote response;
3699 
3700             // If in Non-Stop-Mode
3701             if (process->GetTarget().GetNonStopModeEnabled()) {
3702               // send the vCont packet
3703               if (!process->GetGDBRemote().SendvContPacket(
3704                       llvm::StringRef(continue_cstr, continue_cstr_len),
3705                       response)) {
3706                 // Something went wrong
3707                 done = true;
3708                 break;
3709               }
3710             }
3711             // If in All-Stop-Mode
3712             else {
3713               StateType stop_state =
3714                   process->GetGDBRemote().SendContinuePacketAndWaitForResponse(
3715                       *process, *process->GetUnixSignals(),
3716                       llvm::StringRef(continue_cstr, continue_cstr_len),
3717                       response);
3718 
3719               // We need to immediately clear the thread ID list so we are sure
3720               // to get a valid list of threads. The thread ID list might be
3721               // contained within the "response", or the stop reply packet that
3722               // caused the stop. So clear it now before we give the stop reply
3723               // packet to the process using the
3724               // process->SetLastStopPacket()...
3725               process->ClearThreadIDList();
3726 
3727               switch (stop_state) {
3728               case eStateStopped:
3729               case eStateCrashed:
3730               case eStateSuspended:
3731                 process->SetLastStopPacket(response);
3732                 process->SetPrivateState(stop_state);
3733                 break;
3734 
3735               case eStateExited: {
3736                 process->SetLastStopPacket(response);
3737                 process->ClearThreadIDList();
3738                 response.SetFilePos(1);
3739 
3740                 int exit_status = response.GetHexU8();
3741                 std::string desc_string;
3742                 if (response.GetBytesLeft() > 0 &&
3743                     response.GetChar('-') == ';') {
3744                   llvm::StringRef desc_str;
3745                   llvm::StringRef desc_token;
3746                   while (response.GetNameColonValue(desc_token, desc_str)) {
3747                     if (desc_token != "description")
3748                       continue;
3749                     StringExtractor extractor(desc_str);
3750                     extractor.GetHexByteString(desc_string);
3751                   }
3752                 }
3753                 process->SetExitStatus(exit_status, desc_string.c_str());
3754                 done = true;
3755                 break;
3756               }
3757               case eStateInvalid: {
3758                 // Check to see if we were trying to attach and if we got back
3759                 // the "E87" error code from debugserver -- this indicates that
3760                 // the process is not debuggable.  Return a slightly more
3761                 // helpful error message about why the attach failed.
3762                 if (::strstr(continue_cstr, "vAttach") != nullptr &&
3763                     response.GetError() == 0x87) {
3764                   process->SetExitStatus(-1, "cannot attach to process due to "
3765                                              "System Integrity Protection");
3766                 } else if (::strstr(continue_cstr, "vAttach") != nullptr &&
3767                            response.GetStatus().Fail()) {
3768                   process->SetExitStatus(-1, response.GetStatus().AsCString());
3769                 } else {
3770                   process->SetExitStatus(-1, "lost connection");
3771                 }
3772                 break;
3773               }
3774 
3775               default:
3776                 process->SetPrivateState(stop_state);
3777                 break;
3778               } // switch(stop_state)
3779             }   // else // if in All-stop-mode
3780           }     // if (continue_packet)
3781         }       // case eBroadcastBitAsyncContinue
3782         break;
3783 
3784         case eBroadcastBitAsyncThreadShouldExit:
3785           LLDB_LOGF(log,
3786                     "ProcessGDBRemote::%s (arg = %p, pid = %" PRIu64
3787                     ") got eBroadcastBitAsyncThreadShouldExit...",
3788                     __FUNCTION__, arg, process->GetID());
3789           done = true;
3790           break;
3791 
3792         default:
3793           LLDB_LOGF(log,
3794                     "ProcessGDBRemote::%s (arg = %p, pid = %" PRIu64
3795                     ") got unknown event 0x%8.8x",
3796                     __FUNCTION__, arg, process->GetID(), event_type);
3797           done = true;
3798           break;
3799         }
3800       } else if (event_sp->BroadcasterIs(&process->m_gdb_comm)) {
3801         switch (event_type) {
3802         case Communication::eBroadcastBitReadThreadDidExit:
3803           process->SetExitStatus(-1, "lost connection");
3804           done = true;
3805           break;
3806 
3807         case GDBRemoteCommunication::eBroadcastBitGdbReadThreadGotNotify: {
3808           lldb_private::Event *event = event_sp.get();
3809           const EventDataBytes *continue_packet =
3810               EventDataBytes::GetEventDataFromEvent(event);
3811           StringExtractorGDBRemote notify(
3812               (const char *)continue_packet->GetBytes());
3813           // Hand this over to the process to handle
3814           process->HandleNotifyPacket(notify);
3815           break;
3816         }
3817 
3818         default:
3819           LLDB_LOGF(log,
3820                     "ProcessGDBRemote::%s (arg = %p, pid = %" PRIu64
3821                     ") got unknown event 0x%8.8x",
3822                     __FUNCTION__, arg, process->GetID(), event_type);
3823           done = true;
3824           break;
3825         }
3826       }
3827     } else {
3828       LLDB_LOGF(log,
3829                 "ProcessGDBRemote::%s (arg = %p, pid = %" PRIu64
3830                 ") listener.WaitForEvent (NULL, event_sp) => false",
3831                 __FUNCTION__, arg, process->GetID());
3832       done = true;
3833     }
3834   }
3835 
3836   LLDB_LOGF(log,
3837             "ProcessGDBRemote::%s (arg = %p, pid = %" PRIu64
3838             ") thread exiting...",
3839             __FUNCTION__, arg, process->GetID());
3840 
3841   return {};
3842 }
3843 
3844 // uint32_t
3845 // ProcessGDBRemote::ListProcessesMatchingName (const char *name, StringList
3846 // &matches, std::vector<lldb::pid_t> &pids)
3847 //{
3848 //    // If we are planning to launch the debugserver remotely, then we need to
3849 //    fire up a debugserver
3850 //    // process and ask it for the list of processes. But if we are local, we
3851 //    can let the Host do it.
3852 //    if (m_local_debugserver)
3853 //    {
3854 //        return Host::ListProcessesMatchingName (name, matches, pids);
3855 //    }
3856 //    else
3857 //    {
3858 //        // FIXME: Implement talking to the remote debugserver.
3859 //        return 0;
3860 //    }
3861 //
3862 //}
3863 //
NewThreadNotifyBreakpointHit(void * baton,StoppointCallbackContext * context,lldb::user_id_t break_id,lldb::user_id_t break_loc_id)3864 bool ProcessGDBRemote::NewThreadNotifyBreakpointHit(
3865     void *baton, StoppointCallbackContext *context, lldb::user_id_t break_id,
3866     lldb::user_id_t break_loc_id) {
3867   // I don't think I have to do anything here, just make sure I notice the new
3868   // thread when it starts to
3869   // run so I can stop it if that's what I want to do.
3870   Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_STEP));
3871   LLDB_LOGF(log, "Hit New Thread Notification breakpoint.");
3872   return false;
3873 }
3874 
UpdateAutomaticSignalFiltering()3875 Status ProcessGDBRemote::UpdateAutomaticSignalFiltering() {
3876   Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
3877   LLDB_LOG(log, "Check if need to update ignored signals");
3878 
3879   // QPassSignals package is not supported by the server, there is no way we
3880   // can ignore any signals on server side.
3881   if (!m_gdb_comm.GetQPassSignalsSupported())
3882     return Status();
3883 
3884   // No signals, nothing to send.
3885   if (m_unix_signals_sp == nullptr)
3886     return Status();
3887 
3888   // Signals' version hasn't changed, no need to send anything.
3889   uint64_t new_signals_version = m_unix_signals_sp->GetVersion();
3890   if (new_signals_version == m_last_signals_version) {
3891     LLDB_LOG(log, "Signals' version hasn't changed. version={0}",
3892              m_last_signals_version);
3893     return Status();
3894   }
3895 
3896   auto signals_to_ignore =
3897       m_unix_signals_sp->GetFilteredSignals(false, false, false);
3898   Status error = m_gdb_comm.SendSignalsToIgnore(signals_to_ignore);
3899 
3900   LLDB_LOG(log,
3901            "Signals' version changed. old version={0}, new version={1}, "
3902            "signals ignored={2}, update result={3}",
3903            m_last_signals_version, new_signals_version,
3904            signals_to_ignore.size(), error);
3905 
3906   if (error.Success())
3907     m_last_signals_version = new_signals_version;
3908 
3909   return error;
3910 }
3911 
StartNoticingNewThreads()3912 bool ProcessGDBRemote::StartNoticingNewThreads() {
3913   Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_STEP));
3914   if (m_thread_create_bp_sp) {
3915     if (log && log->GetVerbose())
3916       LLDB_LOGF(log, "Enabled noticing new thread breakpoint.");
3917     m_thread_create_bp_sp->SetEnabled(true);
3918   } else {
3919     PlatformSP platform_sp(GetTarget().GetPlatform());
3920     if (platform_sp) {
3921       m_thread_create_bp_sp =
3922           platform_sp->SetThreadCreationBreakpoint(GetTarget());
3923       if (m_thread_create_bp_sp) {
3924         if (log && log->GetVerbose())
3925           LLDB_LOGF(
3926               log, "Successfully created new thread notification breakpoint %i",
3927               m_thread_create_bp_sp->GetID());
3928         m_thread_create_bp_sp->SetCallback(
3929             ProcessGDBRemote::NewThreadNotifyBreakpointHit, this, true);
3930       } else {
3931         LLDB_LOGF(log, "Failed to create new thread notification breakpoint.");
3932       }
3933     }
3934   }
3935   return m_thread_create_bp_sp.get() != nullptr;
3936 }
3937 
StopNoticingNewThreads()3938 bool ProcessGDBRemote::StopNoticingNewThreads() {
3939   Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_STEP));
3940   if (log && log->GetVerbose())
3941     LLDB_LOGF(log, "Disabling new thread notification breakpoint.");
3942 
3943   if (m_thread_create_bp_sp)
3944     m_thread_create_bp_sp->SetEnabled(false);
3945 
3946   return true;
3947 }
3948 
GetDynamicLoader()3949 DynamicLoader *ProcessGDBRemote::GetDynamicLoader() {
3950   if (m_dyld_up.get() == nullptr)
3951     m_dyld_up.reset(DynamicLoader::FindPlugin(this, nullptr));
3952   return m_dyld_up.get();
3953 }
3954 
SendEventData(const char * data)3955 Status ProcessGDBRemote::SendEventData(const char *data) {
3956   int return_value;
3957   bool was_supported;
3958 
3959   Status error;
3960 
3961   return_value = m_gdb_comm.SendLaunchEventDataPacket(data, &was_supported);
3962   if (return_value != 0) {
3963     if (!was_supported)
3964       error.SetErrorString("Sending events is not supported for this process.");
3965     else
3966       error.SetErrorStringWithFormat("Error sending event data: %d.",
3967                                      return_value);
3968   }
3969   return error;
3970 }
3971 
GetAuxvData()3972 DataExtractor ProcessGDBRemote::GetAuxvData() {
3973   DataBufferSP buf;
3974   if (m_gdb_comm.GetQXferAuxvReadSupported()) {
3975     std::string response_string;
3976     if (m_gdb_comm.SendPacketsAndConcatenateResponses("qXfer:auxv:read::",
3977                                                       response_string) ==
3978         GDBRemoteCommunication::PacketResult::Success)
3979       buf = std::make_shared<DataBufferHeap>(response_string.c_str(),
3980                                              response_string.length());
3981   }
3982   return DataExtractor(buf, GetByteOrder(), GetAddressByteSize());
3983 }
3984 
3985 StructuredData::ObjectSP
GetExtendedInfoForThread(lldb::tid_t tid)3986 ProcessGDBRemote::GetExtendedInfoForThread(lldb::tid_t tid) {
3987   StructuredData::ObjectSP object_sp;
3988 
3989   if (m_gdb_comm.GetThreadExtendedInfoSupported()) {
3990     StructuredData::ObjectSP args_dict(new StructuredData::Dictionary());
3991     SystemRuntime *runtime = GetSystemRuntime();
3992     if (runtime) {
3993       runtime->AddThreadExtendedInfoPacketHints(args_dict);
3994     }
3995     args_dict->GetAsDictionary()->AddIntegerItem("thread", tid);
3996 
3997     StreamString packet;
3998     packet << "jThreadExtendedInfo:";
3999     args_dict->Dump(packet, false);
4000 
4001     // FIXME the final character of a JSON dictionary, '}', is the escape
4002     // character in gdb-remote binary mode.  lldb currently doesn't escape
4003     // these characters in its packet output -- so we add the quoted version of
4004     // the } character here manually in case we talk to a debugserver which un-
4005     // escapes the characters at packet read time.
4006     packet << (char)(0x7d ^ 0x20);
4007 
4008     StringExtractorGDBRemote response;
4009     response.SetResponseValidatorToJSON();
4010     if (m_gdb_comm.SendPacketAndWaitForResponse(packet.GetString(), response,
4011                                                 false) ==
4012         GDBRemoteCommunication::PacketResult::Success) {
4013       StringExtractorGDBRemote::ResponseType response_type =
4014           response.GetResponseType();
4015       if (response_type == StringExtractorGDBRemote::eResponse) {
4016         if (!response.Empty()) {
4017           object_sp =
4018               StructuredData::ParseJSON(std::string(response.GetStringRef()));
4019         }
4020       }
4021     }
4022   }
4023   return object_sp;
4024 }
4025 
GetLoadedDynamicLibrariesInfos(lldb::addr_t image_list_address,lldb::addr_t image_count)4026 StructuredData::ObjectSP ProcessGDBRemote::GetLoadedDynamicLibrariesInfos(
4027     lldb::addr_t image_list_address, lldb::addr_t image_count) {
4028 
4029   StructuredData::ObjectSP args_dict(new StructuredData::Dictionary());
4030   args_dict->GetAsDictionary()->AddIntegerItem("image_list_address",
4031                                                image_list_address);
4032   args_dict->GetAsDictionary()->AddIntegerItem("image_count", image_count);
4033 
4034   return GetLoadedDynamicLibrariesInfos_sender(args_dict);
4035 }
4036 
GetLoadedDynamicLibrariesInfos()4037 StructuredData::ObjectSP ProcessGDBRemote::GetLoadedDynamicLibrariesInfos() {
4038   StructuredData::ObjectSP args_dict(new StructuredData::Dictionary());
4039 
4040   args_dict->GetAsDictionary()->AddBooleanItem("fetch_all_solibs", true);
4041 
4042   return GetLoadedDynamicLibrariesInfos_sender(args_dict);
4043 }
4044 
GetLoadedDynamicLibrariesInfos(const std::vector<lldb::addr_t> & load_addresses)4045 StructuredData::ObjectSP ProcessGDBRemote::GetLoadedDynamicLibrariesInfos(
4046     const std::vector<lldb::addr_t> &load_addresses) {
4047   StructuredData::ObjectSP args_dict(new StructuredData::Dictionary());
4048   StructuredData::ArraySP addresses(new StructuredData::Array);
4049 
4050   for (auto addr : load_addresses) {
4051     StructuredData::ObjectSP addr_sp(new StructuredData::Integer(addr));
4052     addresses->AddItem(addr_sp);
4053   }
4054 
4055   args_dict->GetAsDictionary()->AddItem("solib_addresses", addresses);
4056 
4057   return GetLoadedDynamicLibrariesInfos_sender(args_dict);
4058 }
4059 
4060 StructuredData::ObjectSP
GetLoadedDynamicLibrariesInfos_sender(StructuredData::ObjectSP args_dict)4061 ProcessGDBRemote::GetLoadedDynamicLibrariesInfos_sender(
4062     StructuredData::ObjectSP args_dict) {
4063   StructuredData::ObjectSP object_sp;
4064 
4065   if (m_gdb_comm.GetLoadedDynamicLibrariesInfosSupported()) {
4066     // Scope for the scoped timeout object
4067     GDBRemoteCommunication::ScopedTimeout timeout(m_gdb_comm,
4068                                                   std::chrono::seconds(10));
4069 
4070     StreamString packet;
4071     packet << "jGetLoadedDynamicLibrariesInfos:";
4072     args_dict->Dump(packet, false);
4073 
4074     // FIXME the final character of a JSON dictionary, '}', is the escape
4075     // character in gdb-remote binary mode.  lldb currently doesn't escape
4076     // these characters in its packet output -- so we add the quoted version of
4077     // the } character here manually in case we talk to a debugserver which un-
4078     // escapes the characters at packet read time.
4079     packet << (char)(0x7d ^ 0x20);
4080 
4081     StringExtractorGDBRemote response;
4082     response.SetResponseValidatorToJSON();
4083     if (m_gdb_comm.SendPacketAndWaitForResponse(packet.GetString(), response,
4084                                                 false) ==
4085         GDBRemoteCommunication::PacketResult::Success) {
4086       StringExtractorGDBRemote::ResponseType response_type =
4087           response.GetResponseType();
4088       if (response_type == StringExtractorGDBRemote::eResponse) {
4089         if (!response.Empty()) {
4090           object_sp =
4091               StructuredData::ParseJSON(std::string(response.GetStringRef()));
4092         }
4093       }
4094     }
4095   }
4096   return object_sp;
4097 }
4098 
GetSharedCacheInfo()4099 StructuredData::ObjectSP ProcessGDBRemote::GetSharedCacheInfo() {
4100   StructuredData::ObjectSP object_sp;
4101   StructuredData::ObjectSP args_dict(new StructuredData::Dictionary());
4102 
4103   if (m_gdb_comm.GetSharedCacheInfoSupported()) {
4104     StreamString packet;
4105     packet << "jGetSharedCacheInfo:";
4106     args_dict->Dump(packet, false);
4107 
4108     // FIXME the final character of a JSON dictionary, '}', is the escape
4109     // character in gdb-remote binary mode.  lldb currently doesn't escape
4110     // these characters in its packet output -- so we add the quoted version of
4111     // the } character here manually in case we talk to a debugserver which un-
4112     // escapes the characters at packet read time.
4113     packet << (char)(0x7d ^ 0x20);
4114 
4115     StringExtractorGDBRemote response;
4116     response.SetResponseValidatorToJSON();
4117     if (m_gdb_comm.SendPacketAndWaitForResponse(packet.GetString(), response,
4118                                                 false) ==
4119         GDBRemoteCommunication::PacketResult::Success) {
4120       StringExtractorGDBRemote::ResponseType response_type =
4121           response.GetResponseType();
4122       if (response_type == StringExtractorGDBRemote::eResponse) {
4123         if (!response.Empty()) {
4124           object_sp =
4125               StructuredData::ParseJSON(std::string(response.GetStringRef()));
4126         }
4127       }
4128     }
4129   }
4130   return object_sp;
4131 }
4132 
ConfigureStructuredData(ConstString type_name,const StructuredData::ObjectSP & config_sp)4133 Status ProcessGDBRemote::ConfigureStructuredData(
4134     ConstString type_name, const StructuredData::ObjectSP &config_sp) {
4135   return m_gdb_comm.ConfigureRemoteStructuredData(type_name, config_sp);
4136 }
4137 
4138 // Establish the largest memory read/write payloads we should use. If the
4139 // remote stub has a max packet size, stay under that size.
4140 //
4141 // If the remote stub's max packet size is crazy large, use a reasonable
4142 // largeish default.
4143 //
4144 // If the remote stub doesn't advertise a max packet size, use a conservative
4145 // default.
4146 
GetMaxMemorySize()4147 void ProcessGDBRemote::GetMaxMemorySize() {
4148   const uint64_t reasonable_largeish_default = 128 * 1024;
4149   const uint64_t conservative_default = 512;
4150 
4151   if (m_max_memory_size == 0) {
4152     uint64_t stub_max_size = m_gdb_comm.GetRemoteMaxPacketSize();
4153     if (stub_max_size != UINT64_MAX && stub_max_size != 0) {
4154       // Save the stub's claimed maximum packet size
4155       m_remote_stub_max_memory_size = stub_max_size;
4156 
4157       // Even if the stub says it can support ginormous packets, don't exceed
4158       // our reasonable largeish default packet size.
4159       if (stub_max_size > reasonable_largeish_default) {
4160         stub_max_size = reasonable_largeish_default;
4161       }
4162 
4163       // Memory packet have other overheads too like Maddr,size:#NN Instead of
4164       // calculating the bytes taken by size and addr every time, we take a
4165       // maximum guess here.
4166       if (stub_max_size > 70)
4167         stub_max_size -= 32 + 32 + 6;
4168       else {
4169         // In unlikely scenario that max packet size is less then 70, we will
4170         // hope that data being written is small enough to fit.
4171         Log *log(ProcessGDBRemoteLog::GetLogIfAnyCategoryIsSet(
4172             GDBR_LOG_COMM | GDBR_LOG_MEMORY));
4173         if (log)
4174           log->Warning("Packet size is too small. "
4175                        "LLDB may face problems while writing memory");
4176       }
4177 
4178       m_max_memory_size = stub_max_size;
4179     } else {
4180       m_max_memory_size = conservative_default;
4181     }
4182   }
4183 }
4184 
SetUserSpecifiedMaxMemoryTransferSize(uint64_t user_specified_max)4185 void ProcessGDBRemote::SetUserSpecifiedMaxMemoryTransferSize(
4186     uint64_t user_specified_max) {
4187   if (user_specified_max != 0) {
4188     GetMaxMemorySize();
4189 
4190     if (m_remote_stub_max_memory_size != 0) {
4191       if (m_remote_stub_max_memory_size < user_specified_max) {
4192         m_max_memory_size = m_remote_stub_max_memory_size; // user specified a
4193                                                            // packet size too
4194                                                            // big, go as big
4195         // as the remote stub says we can go.
4196       } else {
4197         m_max_memory_size = user_specified_max; // user's packet size is good
4198       }
4199     } else {
4200       m_max_memory_size =
4201           user_specified_max; // user's packet size is probably fine
4202     }
4203   }
4204 }
4205 
GetModuleSpec(const FileSpec & module_file_spec,const ArchSpec & arch,ModuleSpec & module_spec)4206 bool ProcessGDBRemote::GetModuleSpec(const FileSpec &module_file_spec,
4207                                      const ArchSpec &arch,
4208                                      ModuleSpec &module_spec) {
4209   Log *log = GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PLATFORM);
4210 
4211   const ModuleCacheKey key(module_file_spec.GetPath(),
4212                            arch.GetTriple().getTriple());
4213   auto cached = m_cached_module_specs.find(key);
4214   if (cached != m_cached_module_specs.end()) {
4215     module_spec = cached->second;
4216     return bool(module_spec);
4217   }
4218 
4219   if (!m_gdb_comm.GetModuleInfo(module_file_spec, arch, module_spec)) {
4220     LLDB_LOGF(log, "ProcessGDBRemote::%s - failed to get module info for %s:%s",
4221               __FUNCTION__, module_file_spec.GetPath().c_str(),
4222               arch.GetTriple().getTriple().c_str());
4223     return false;
4224   }
4225 
4226   if (log) {
4227     StreamString stream;
4228     module_spec.Dump(stream);
4229     LLDB_LOGF(log, "ProcessGDBRemote::%s - got module info for (%s:%s) : %s",
4230               __FUNCTION__, module_file_spec.GetPath().c_str(),
4231               arch.GetTriple().getTriple().c_str(), stream.GetData());
4232   }
4233 
4234   m_cached_module_specs[key] = module_spec;
4235   return true;
4236 }
4237 
PrefetchModuleSpecs(llvm::ArrayRef<FileSpec> module_file_specs,const llvm::Triple & triple)4238 void ProcessGDBRemote::PrefetchModuleSpecs(
4239     llvm::ArrayRef<FileSpec> module_file_specs, const llvm::Triple &triple) {
4240   auto module_specs = m_gdb_comm.GetModulesInfo(module_file_specs, triple);
4241   if (module_specs) {
4242     for (const FileSpec &spec : module_file_specs)
4243       m_cached_module_specs[ModuleCacheKey(spec.GetPath(),
4244                                            triple.getTriple())] = ModuleSpec();
4245     for (const ModuleSpec &spec : *module_specs)
4246       m_cached_module_specs[ModuleCacheKey(spec.GetFileSpec().GetPath(),
4247                                            triple.getTriple())] = spec;
4248   }
4249 }
4250 
GetHostOSVersion()4251 llvm::VersionTuple ProcessGDBRemote::GetHostOSVersion() {
4252   return m_gdb_comm.GetOSVersion();
4253 }
4254 
GetHostMacCatalystVersion()4255 llvm::VersionTuple ProcessGDBRemote::GetHostMacCatalystVersion() {
4256   return m_gdb_comm.GetMacCatalystVersion();
4257 }
4258 
4259 namespace {
4260 
4261 typedef std::vector<std::string> stringVec;
4262 
4263 typedef std::vector<struct GdbServerRegisterInfo> GDBServerRegisterVec;
4264 struct RegisterSetInfo {
4265   ConstString name;
4266 };
4267 
4268 typedef std::map<uint32_t, RegisterSetInfo> RegisterSetMap;
4269 
4270 struct GdbServerTargetInfo {
4271   std::string arch;
4272   std::string osabi;
4273   stringVec includes;
4274   RegisterSetMap reg_set_map;
4275 };
4276 
ParseRegisters(XMLNode feature_node,GdbServerTargetInfo & target_info,GDBRemoteDynamicRegisterInfo & dyn_reg_info,ABISP abi_sp,uint32_t & reg_num_remote,uint32_t & reg_num_local)4277 bool ParseRegisters(XMLNode feature_node, GdbServerTargetInfo &target_info,
4278                     GDBRemoteDynamicRegisterInfo &dyn_reg_info, ABISP abi_sp,
4279                     uint32_t &reg_num_remote, uint32_t &reg_num_local) {
4280   if (!feature_node)
4281     return false;
4282 
4283   uint32_t reg_offset = LLDB_INVALID_INDEX32;
4284   feature_node.ForEachChildElementWithName(
4285       "reg", [&target_info, &dyn_reg_info, &reg_num_remote, &reg_num_local,
4286               &reg_offset, &abi_sp](const XMLNode &reg_node) -> bool {
4287         std::string gdb_group;
4288         std::string gdb_type;
4289         ConstString reg_name;
4290         ConstString alt_name;
4291         ConstString set_name;
4292         std::vector<uint32_t> value_regs;
4293         std::vector<uint32_t> invalidate_regs;
4294         std::vector<uint8_t> dwarf_opcode_bytes;
4295         bool encoding_set = false;
4296         bool format_set = false;
4297         RegisterInfo reg_info = {
4298             nullptr,       // Name
4299             nullptr,       // Alt name
4300             0,             // byte size
4301             reg_offset,    // offset
4302             eEncodingUint, // encoding
4303             eFormatHex,    // format
4304             {
4305                 LLDB_INVALID_REGNUM, // eh_frame reg num
4306                 LLDB_INVALID_REGNUM, // DWARF reg num
4307                 LLDB_INVALID_REGNUM, // generic reg num
4308                 reg_num_remote,      // process plugin reg num
4309                 reg_num_local        // native register number
4310             },
4311             nullptr,
4312             nullptr,
4313             nullptr, // Dwarf Expression opcode bytes pointer
4314             0        // Dwarf Expression opcode bytes length
4315         };
4316 
4317         reg_node.ForEachAttribute([&target_info, &gdb_group, &gdb_type,
4318                                    &reg_name, &alt_name, &set_name, &value_regs,
4319                                    &invalidate_regs, &encoding_set, &format_set,
4320                                    &reg_info, &reg_offset, &dwarf_opcode_bytes](
4321                                       const llvm::StringRef &name,
4322                                       const llvm::StringRef &value) -> bool {
4323           if (name == "name") {
4324             reg_name.SetString(value);
4325           } else if (name == "bitsize") {
4326             reg_info.byte_size =
4327                 StringConvert::ToUInt32(value.data(), 0, 0) / CHAR_BIT;
4328           } else if (name == "type") {
4329             gdb_type = value.str();
4330           } else if (name == "group") {
4331             gdb_group = value.str();
4332           } else if (name == "regnum") {
4333             const uint32_t regnum =
4334                 StringConvert::ToUInt32(value.data(), LLDB_INVALID_REGNUM, 0);
4335             if (regnum != LLDB_INVALID_REGNUM) {
4336               reg_info.kinds[eRegisterKindProcessPlugin] = regnum;
4337             }
4338           } else if (name == "offset") {
4339             reg_offset = StringConvert::ToUInt32(value.data(), UINT32_MAX, 0);
4340           } else if (name == "altname") {
4341             alt_name.SetString(value);
4342           } else if (name == "encoding") {
4343             encoding_set = true;
4344             reg_info.encoding = Args::StringToEncoding(value, eEncodingUint);
4345           } else if (name == "format") {
4346             format_set = true;
4347             Format format = eFormatInvalid;
4348             if (OptionArgParser::ToFormat(value.data(), format, nullptr)
4349                     .Success())
4350               reg_info.format = format;
4351             else if (value == "vector-sint8")
4352               reg_info.format = eFormatVectorOfSInt8;
4353             else if (value == "vector-uint8")
4354               reg_info.format = eFormatVectorOfUInt8;
4355             else if (value == "vector-sint16")
4356               reg_info.format = eFormatVectorOfSInt16;
4357             else if (value == "vector-uint16")
4358               reg_info.format = eFormatVectorOfUInt16;
4359             else if (value == "vector-sint32")
4360               reg_info.format = eFormatVectorOfSInt32;
4361             else if (value == "vector-uint32")
4362               reg_info.format = eFormatVectorOfUInt32;
4363             else if (value == "vector-float32")
4364               reg_info.format = eFormatVectorOfFloat32;
4365             else if (value == "vector-uint64")
4366               reg_info.format = eFormatVectorOfUInt64;
4367             else if (value == "vector-uint128")
4368               reg_info.format = eFormatVectorOfUInt128;
4369           } else if (name == "group_id") {
4370             const uint32_t set_id =
4371                 StringConvert::ToUInt32(value.data(), UINT32_MAX, 0);
4372             RegisterSetMap::const_iterator pos =
4373                 target_info.reg_set_map.find(set_id);
4374             if (pos != target_info.reg_set_map.end())
4375               set_name = pos->second.name;
4376           } else if (name == "gcc_regnum" || name == "ehframe_regnum") {
4377             reg_info.kinds[eRegisterKindEHFrame] =
4378                 StringConvert::ToUInt32(value.data(), LLDB_INVALID_REGNUM, 0);
4379           } else if (name == "dwarf_regnum") {
4380             reg_info.kinds[eRegisterKindDWARF] =
4381                 StringConvert::ToUInt32(value.data(), LLDB_INVALID_REGNUM, 0);
4382           } else if (name == "generic") {
4383             reg_info.kinds[eRegisterKindGeneric] =
4384                 Args::StringToGenericRegister(value);
4385           } else if (name == "value_regnums") {
4386             SplitCommaSeparatedRegisterNumberString(value, value_regs, 0);
4387           } else if (name == "invalidate_regnums") {
4388             SplitCommaSeparatedRegisterNumberString(value, invalidate_regs, 0);
4389           } else if (name == "dynamic_size_dwarf_expr_bytes") {
4390             std::string opcode_string = value.str();
4391             size_t dwarf_opcode_len = opcode_string.length() / 2;
4392             assert(dwarf_opcode_len > 0);
4393 
4394             dwarf_opcode_bytes.resize(dwarf_opcode_len);
4395             reg_info.dynamic_size_dwarf_len = dwarf_opcode_len;
4396             StringExtractor opcode_extractor(opcode_string);
4397             uint32_t ret_val =
4398                 opcode_extractor.GetHexBytesAvail(dwarf_opcode_bytes);
4399             assert(dwarf_opcode_len == ret_val);
4400             UNUSED_IF_ASSERT_DISABLED(ret_val);
4401             reg_info.dynamic_size_dwarf_expr_bytes = dwarf_opcode_bytes.data();
4402           } else {
4403             printf("unhandled attribute %s = %s\n", name.data(), value.data());
4404           }
4405           return true; // Keep iterating through all attributes
4406         });
4407 
4408         if (!gdb_type.empty() && !(encoding_set || format_set)) {
4409           if (llvm::StringRef(gdb_type).startswith("int")) {
4410             reg_info.format = eFormatHex;
4411             reg_info.encoding = eEncodingUint;
4412           } else if (gdb_type == "data_ptr" || gdb_type == "code_ptr") {
4413             reg_info.format = eFormatAddressInfo;
4414             reg_info.encoding = eEncodingUint;
4415           } else if (gdb_type == "i387_ext" || gdb_type == "float") {
4416             reg_info.format = eFormatFloat;
4417             reg_info.encoding = eEncodingIEEE754;
4418           }
4419         }
4420 
4421         // Only update the register set name if we didn't get a "reg_set"
4422         // attribute. "set_name" will be empty if we didn't have a "reg_set"
4423         // attribute.
4424         if (!set_name) {
4425           if (!gdb_group.empty()) {
4426             set_name.SetCString(gdb_group.c_str());
4427           } else {
4428             // If no register group name provided anywhere,
4429             // we'll create a 'general' register set
4430             set_name.SetCString("general");
4431           }
4432         }
4433 
4434         reg_info.byte_offset = reg_offset;
4435         assert(reg_info.byte_size != 0);
4436         reg_offset = LLDB_INVALID_INDEX32;
4437         if (!value_regs.empty()) {
4438           value_regs.push_back(LLDB_INVALID_REGNUM);
4439           reg_info.value_regs = value_regs.data();
4440         }
4441         if (!invalidate_regs.empty()) {
4442           invalidate_regs.push_back(LLDB_INVALID_REGNUM);
4443           reg_info.invalidate_regs = invalidate_regs.data();
4444         }
4445 
4446         reg_num_remote = reg_info.kinds[eRegisterKindProcessPlugin] + 1;
4447         ++reg_num_local;
4448         reg_info.name = reg_name.AsCString();
4449         if (abi_sp)
4450           abi_sp->AugmentRegisterInfo(reg_info);
4451         dyn_reg_info.AddRegister(reg_info, reg_name, alt_name, set_name);
4452 
4453         return true; // Keep iterating through all "reg" elements
4454       });
4455   return true;
4456 }
4457 
4458 } // namespace
4459 
4460 // This method fetches a register description feature xml file from
4461 // the remote stub and adds registers/register groupsets/architecture
4462 // information to the current process.  It will call itself recursively
4463 // for nested register definition files.  It returns true if it was able
4464 // to fetch and parse an xml file.
GetGDBServerRegisterInfoXMLAndProcess(ArchSpec & arch_to_use,std::string xml_filename,uint32_t & reg_num_remote,uint32_t & reg_num_local)4465 bool ProcessGDBRemote::GetGDBServerRegisterInfoXMLAndProcess(
4466     ArchSpec &arch_to_use, std::string xml_filename, uint32_t &reg_num_remote,
4467     uint32_t &reg_num_local) {
4468   // request the target xml file
4469   std::string raw;
4470   lldb_private::Status lldberr;
4471   if (!m_gdb_comm.ReadExtFeature(ConstString("features"),
4472                                  ConstString(xml_filename.c_str()), raw,
4473                                  lldberr)) {
4474     return false;
4475   }
4476 
4477   XMLDocument xml_document;
4478 
4479   if (xml_document.ParseMemory(raw.c_str(), raw.size(), xml_filename.c_str())) {
4480     GdbServerTargetInfo target_info;
4481     std::vector<XMLNode> feature_nodes;
4482 
4483     // The top level feature XML file will start with a <target> tag.
4484     XMLNode target_node = xml_document.GetRootElement("target");
4485     if (target_node) {
4486       target_node.ForEachChildElement([&target_info, &feature_nodes](
4487                                           const XMLNode &node) -> bool {
4488         llvm::StringRef name = node.GetName();
4489         if (name == "architecture") {
4490           node.GetElementText(target_info.arch);
4491         } else if (name == "osabi") {
4492           node.GetElementText(target_info.osabi);
4493         } else if (name == "xi:include" || name == "include") {
4494           llvm::StringRef href = node.GetAttributeValue("href");
4495           if (!href.empty())
4496             target_info.includes.push_back(href.str());
4497         } else if (name == "feature") {
4498           feature_nodes.push_back(node);
4499         } else if (name == "groups") {
4500           node.ForEachChildElementWithName(
4501               "group", [&target_info](const XMLNode &node) -> bool {
4502                 uint32_t set_id = UINT32_MAX;
4503                 RegisterSetInfo set_info;
4504 
4505                 node.ForEachAttribute(
4506                     [&set_id, &set_info](const llvm::StringRef &name,
4507                                          const llvm::StringRef &value) -> bool {
4508                       if (name == "id")
4509                         set_id = StringConvert::ToUInt32(value.data(),
4510                                                          UINT32_MAX, 0);
4511                       if (name == "name")
4512                         set_info.name = ConstString(value);
4513                       return true; // Keep iterating through all attributes
4514                     });
4515 
4516                 if (set_id != UINT32_MAX)
4517                   target_info.reg_set_map[set_id] = set_info;
4518                 return true; // Keep iterating through all "group" elements
4519               });
4520         }
4521         return true; // Keep iterating through all children of the target_node
4522       });
4523     } else {
4524       // In an included XML feature file, we're already "inside" the <target>
4525       // tag of the initial XML file; this included file will likely only have
4526       // a <feature> tag.  Need to check for any more included files in this
4527       // <feature> element.
4528       XMLNode feature_node = xml_document.GetRootElement("feature");
4529       if (feature_node) {
4530         feature_nodes.push_back(feature_node);
4531         feature_node.ForEachChildElement([&target_info](
4532                                         const XMLNode &node) -> bool {
4533           llvm::StringRef name = node.GetName();
4534           if (name == "xi:include" || name == "include") {
4535             llvm::StringRef href = node.GetAttributeValue("href");
4536             if (!href.empty())
4537               target_info.includes.push_back(href.str());
4538             }
4539             return true;
4540           });
4541       }
4542     }
4543 
4544     // If the target.xml includes an architecture entry like
4545     //   <architecture>i386:x86-64</architecture> (seen from VMWare ESXi)
4546     //   <architecture>arm</architecture> (seen from Segger JLink on unspecified arm board)
4547     // use that if we don't have anything better.
4548     if (!arch_to_use.IsValid() && !target_info.arch.empty()) {
4549       if (target_info.arch == "i386:x86-64") {
4550         // We don't have any information about vendor or OS.
4551         arch_to_use.SetTriple("x86_64--");
4552         GetTarget().MergeArchitecture(arch_to_use);
4553       }
4554 
4555       // SEGGER J-Link jtag boards send this very-generic arch name,
4556       // we'll need to use this if we have absolutely nothing better
4557       // to work with or the register definitions won't be accepted.
4558       if (target_info.arch == "arm") {
4559         arch_to_use.SetTriple("arm--");
4560         GetTarget().MergeArchitecture(arch_to_use);
4561       }
4562     }
4563 
4564     if (arch_to_use.IsValid()) {
4565       // Don't use Process::GetABI, this code gets called from DidAttach, and
4566       // in that context we haven't set the Target's architecture yet, so the
4567       // ABI is also potentially incorrect.
4568       ABISP abi_to_use_sp = ABI::FindPlugin(shared_from_this(), arch_to_use);
4569       for (auto &feature_node : feature_nodes) {
4570         ParseRegisters(feature_node, target_info, this->m_register_info,
4571                        abi_to_use_sp, reg_num_remote, reg_num_local);
4572       }
4573 
4574       for (const auto &include : target_info.includes) {
4575         GetGDBServerRegisterInfoXMLAndProcess(arch_to_use, include,
4576                                               reg_num_remote, reg_num_local);
4577       }
4578     }
4579   } else {
4580     return false;
4581   }
4582   return true;
4583 }
4584 
4585 // query the target of gdb-remote for extended target information returns
4586 // true on success (got register definitions), false on failure (did not).
GetGDBServerRegisterInfo(ArchSpec & arch_to_use)4587 bool ProcessGDBRemote::GetGDBServerRegisterInfo(ArchSpec &arch_to_use) {
4588   // Make sure LLDB has an XML parser it can use first
4589   if (!XMLDocument::XMLEnabled())
4590     return false;
4591 
4592   // check that we have extended feature read support
4593   if (!m_gdb_comm.GetQXferFeaturesReadSupported())
4594     return false;
4595 
4596   uint32_t reg_num_remote = 0;
4597   uint32_t reg_num_local = 0;
4598   if (GetGDBServerRegisterInfoXMLAndProcess(arch_to_use, "target.xml",
4599                                             reg_num_remote, reg_num_local))
4600     this->m_register_info.Finalize(arch_to_use);
4601 
4602   return m_register_info.GetNumRegisters() > 0;
4603 }
4604 
GetLoadedModuleList()4605 llvm::Expected<LoadedModuleInfoList> ProcessGDBRemote::GetLoadedModuleList() {
4606   // Make sure LLDB has an XML parser it can use first
4607   if (!XMLDocument::XMLEnabled())
4608     return llvm::createStringError(llvm::inconvertibleErrorCode(),
4609                                    "XML parsing not available");
4610 
4611   Log *log = GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS);
4612   LLDB_LOGF(log, "ProcessGDBRemote::%s", __FUNCTION__);
4613 
4614   LoadedModuleInfoList list;
4615   GDBRemoteCommunicationClient &comm = m_gdb_comm;
4616   bool can_use_svr4 = GetGlobalPluginProperties()->GetUseSVR4();
4617 
4618   // check that we have extended feature read support
4619   if (can_use_svr4 && comm.GetQXferLibrariesSVR4ReadSupported()) {
4620     // request the loaded library list
4621     std::string raw;
4622     lldb_private::Status lldberr;
4623 
4624     if (!comm.ReadExtFeature(ConstString("libraries-svr4"), ConstString(""),
4625                              raw, lldberr))
4626       return llvm::createStringError(llvm::inconvertibleErrorCode(),
4627                                      "Error in libraries-svr4 packet");
4628 
4629     // parse the xml file in memory
4630     LLDB_LOGF(log, "parsing: %s", raw.c_str());
4631     XMLDocument doc;
4632 
4633     if (!doc.ParseMemory(raw.c_str(), raw.size(), "noname.xml"))
4634       return llvm::createStringError(llvm::inconvertibleErrorCode(),
4635                                      "Error reading noname.xml");
4636 
4637     XMLNode root_element = doc.GetRootElement("library-list-svr4");
4638     if (!root_element)
4639       return llvm::createStringError(
4640           llvm::inconvertibleErrorCode(),
4641           "Error finding library-list-svr4 xml element");
4642 
4643     // main link map structure
4644     llvm::StringRef main_lm = root_element.GetAttributeValue("main-lm");
4645     if (!main_lm.empty()) {
4646       list.m_link_map =
4647           StringConvert::ToUInt64(main_lm.data(), LLDB_INVALID_ADDRESS, 0);
4648     }
4649 
4650     root_element.ForEachChildElementWithName(
4651         "library", [log, &list](const XMLNode &library) -> bool {
4652 
4653           LoadedModuleInfoList::LoadedModuleInfo module;
4654 
4655           library.ForEachAttribute(
4656               [&module](const llvm::StringRef &name,
4657                         const llvm::StringRef &value) -> bool {
4658 
4659                 if (name == "name")
4660                   module.set_name(value.str());
4661                 else if (name == "lm") {
4662                   // the address of the link_map struct.
4663                   module.set_link_map(StringConvert::ToUInt64(
4664                       value.data(), LLDB_INVALID_ADDRESS, 0));
4665                 } else if (name == "l_addr") {
4666                   // the displacement as read from the field 'l_addr' of the
4667                   // link_map struct.
4668                   module.set_base(StringConvert::ToUInt64(
4669                       value.data(), LLDB_INVALID_ADDRESS, 0));
4670                   // base address is always a displacement, not an absolute
4671                   // value.
4672                   module.set_base_is_offset(true);
4673                 } else if (name == "l_ld") {
4674                   // the memory address of the libraries PT_DYNAMIC section.
4675                   module.set_dynamic(StringConvert::ToUInt64(
4676                       value.data(), LLDB_INVALID_ADDRESS, 0));
4677                 }
4678 
4679                 return true; // Keep iterating over all properties of "library"
4680               });
4681 
4682           if (log) {
4683             std::string name;
4684             lldb::addr_t lm = 0, base = 0, ld = 0;
4685             bool base_is_offset;
4686 
4687             module.get_name(name);
4688             module.get_link_map(lm);
4689             module.get_base(base);
4690             module.get_base_is_offset(base_is_offset);
4691             module.get_dynamic(ld);
4692 
4693             LLDB_LOGF(log,
4694                       "found (link_map:0x%08" PRIx64 ", base:0x%08" PRIx64
4695                       "[%s], ld:0x%08" PRIx64 ", name:'%s')",
4696                       lm, base, (base_is_offset ? "offset" : "absolute"), ld,
4697                       name.c_str());
4698           }
4699 
4700           list.add(module);
4701           return true; // Keep iterating over all "library" elements in the root
4702                        // node
4703         });
4704 
4705     if (log)
4706       LLDB_LOGF(log, "found %" PRId32 " modules in total",
4707                 (int)list.m_list.size());
4708     return list;
4709   } else if (comm.GetQXferLibrariesReadSupported()) {
4710     // request the loaded library list
4711     std::string raw;
4712     lldb_private::Status lldberr;
4713 
4714     if (!comm.ReadExtFeature(ConstString("libraries"), ConstString(""), raw,
4715                              lldberr))
4716       return llvm::createStringError(llvm::inconvertibleErrorCode(),
4717                                      "Error in libraries packet");
4718 
4719     LLDB_LOGF(log, "parsing: %s", raw.c_str());
4720     XMLDocument doc;
4721 
4722     if (!doc.ParseMemory(raw.c_str(), raw.size(), "noname.xml"))
4723       return llvm::createStringError(llvm::inconvertibleErrorCode(),
4724                                      "Error reading noname.xml");
4725 
4726     XMLNode root_element = doc.GetRootElement("library-list");
4727     if (!root_element)
4728       return llvm::createStringError(llvm::inconvertibleErrorCode(),
4729                                      "Error finding library-list xml element");
4730 
4731     root_element.ForEachChildElementWithName(
4732         "library", [log, &list](const XMLNode &library) -> bool {
4733           LoadedModuleInfoList::LoadedModuleInfo module;
4734 
4735           llvm::StringRef name = library.GetAttributeValue("name");
4736           module.set_name(name.str());
4737 
4738           // The base address of a given library will be the address of its
4739           // first section. Most remotes send only one section for Windows
4740           // targets for example.
4741           const XMLNode &section =
4742               library.FindFirstChildElementWithName("section");
4743           llvm::StringRef address = section.GetAttributeValue("address");
4744           module.set_base(
4745               StringConvert::ToUInt64(address.data(), LLDB_INVALID_ADDRESS, 0));
4746           // These addresses are absolute values.
4747           module.set_base_is_offset(false);
4748 
4749           if (log) {
4750             std::string name;
4751             lldb::addr_t base = 0;
4752             bool base_is_offset;
4753             module.get_name(name);
4754             module.get_base(base);
4755             module.get_base_is_offset(base_is_offset);
4756 
4757             LLDB_LOGF(log, "found (base:0x%08" PRIx64 "[%s], name:'%s')", base,
4758                       (base_is_offset ? "offset" : "absolute"), name.c_str());
4759           }
4760 
4761           list.add(module);
4762           return true; // Keep iterating over all "library" elements in the root
4763                        // node
4764         });
4765 
4766     if (log)
4767       LLDB_LOGF(log, "found %" PRId32 " modules in total",
4768                 (int)list.m_list.size());
4769     return list;
4770   } else {
4771     return llvm::createStringError(llvm::inconvertibleErrorCode(),
4772                                    "Remote libraries not supported");
4773   }
4774 }
4775 
LoadModuleAtAddress(const FileSpec & file,lldb::addr_t link_map,lldb::addr_t base_addr,bool value_is_offset)4776 lldb::ModuleSP ProcessGDBRemote::LoadModuleAtAddress(const FileSpec &file,
4777                                                      lldb::addr_t link_map,
4778                                                      lldb::addr_t base_addr,
4779                                                      bool value_is_offset) {
4780   DynamicLoader *loader = GetDynamicLoader();
4781   if (!loader)
4782     return nullptr;
4783 
4784   return loader->LoadModuleAtAddress(file, link_map, base_addr,
4785                                      value_is_offset);
4786 }
4787 
LoadModules()4788 llvm::Error ProcessGDBRemote::LoadModules() {
4789   using lldb_private::process_gdb_remote::ProcessGDBRemote;
4790 
4791   // request a list of loaded libraries from GDBServer
4792   llvm::Expected<LoadedModuleInfoList> module_list = GetLoadedModuleList();
4793   if (!module_list)
4794     return module_list.takeError();
4795 
4796   // get a list of all the modules
4797   ModuleList new_modules;
4798 
4799   for (LoadedModuleInfoList::LoadedModuleInfo &modInfo : module_list->m_list) {
4800     std::string mod_name;
4801     lldb::addr_t mod_base;
4802     lldb::addr_t link_map;
4803     bool mod_base_is_offset;
4804 
4805     bool valid = true;
4806     valid &= modInfo.get_name(mod_name);
4807     valid &= modInfo.get_base(mod_base);
4808     valid &= modInfo.get_base_is_offset(mod_base_is_offset);
4809     if (!valid)
4810       continue;
4811 
4812     if (!modInfo.get_link_map(link_map))
4813       link_map = LLDB_INVALID_ADDRESS;
4814 
4815     FileSpec file(mod_name);
4816     FileSystem::Instance().Resolve(file);
4817     lldb::ModuleSP module_sp =
4818         LoadModuleAtAddress(file, link_map, mod_base, mod_base_is_offset);
4819 
4820     if (module_sp.get())
4821       new_modules.Append(module_sp);
4822   }
4823 
4824   if (new_modules.GetSize() > 0) {
4825     ModuleList removed_modules;
4826     Target &target = GetTarget();
4827     ModuleList &loaded_modules = m_process->GetTarget().GetImages();
4828 
4829     for (size_t i = 0; i < loaded_modules.GetSize(); ++i) {
4830       const lldb::ModuleSP loaded_module = loaded_modules.GetModuleAtIndex(i);
4831 
4832       bool found = false;
4833       for (size_t j = 0; j < new_modules.GetSize(); ++j) {
4834         if (new_modules.GetModuleAtIndex(j).get() == loaded_module.get())
4835           found = true;
4836       }
4837 
4838       // The main executable will never be included in libraries-svr4, don't
4839       // remove it
4840       if (!found &&
4841           loaded_module.get() != target.GetExecutableModulePointer()) {
4842         removed_modules.Append(loaded_module);
4843       }
4844     }
4845 
4846     loaded_modules.Remove(removed_modules);
4847     m_process->GetTarget().ModulesDidUnload(removed_modules, false);
4848 
4849     new_modules.ForEach([&target](const lldb::ModuleSP module_sp) -> bool {
4850       lldb_private::ObjectFile *obj = module_sp->GetObjectFile();
4851       if (!obj)
4852         return true;
4853 
4854       if (obj->GetType() != ObjectFile::Type::eTypeExecutable)
4855         return true;
4856 
4857       lldb::ModuleSP module_copy_sp = module_sp;
4858       target.SetExecutableModule(module_copy_sp, eLoadDependentsNo);
4859       return false;
4860     });
4861 
4862     loaded_modules.AppendIfNeeded(new_modules);
4863     m_process->GetTarget().ModulesDidLoad(new_modules);
4864   }
4865 
4866   return llvm::ErrorSuccess();
4867 }
4868 
GetFileLoadAddress(const FileSpec & file,bool & is_loaded,lldb::addr_t & load_addr)4869 Status ProcessGDBRemote::GetFileLoadAddress(const FileSpec &file,
4870                                             bool &is_loaded,
4871                                             lldb::addr_t &load_addr) {
4872   is_loaded = false;
4873   load_addr = LLDB_INVALID_ADDRESS;
4874 
4875   std::string file_path = file.GetPath(false);
4876   if (file_path.empty())
4877     return Status("Empty file name specified");
4878 
4879   StreamString packet;
4880   packet.PutCString("qFileLoadAddress:");
4881   packet.PutStringAsRawHex8(file_path);
4882 
4883   StringExtractorGDBRemote response;
4884   if (m_gdb_comm.SendPacketAndWaitForResponse(packet.GetString(), response,
4885                                               false) !=
4886       GDBRemoteCommunication::PacketResult::Success)
4887     return Status("Sending qFileLoadAddress packet failed");
4888 
4889   if (response.IsErrorResponse()) {
4890     if (response.GetError() == 1) {
4891       // The file is not loaded into the inferior
4892       is_loaded = false;
4893       load_addr = LLDB_INVALID_ADDRESS;
4894       return Status();
4895     }
4896 
4897     return Status(
4898         "Fetching file load address from remote server returned an error");
4899   }
4900 
4901   if (response.IsNormalResponse()) {
4902     is_loaded = true;
4903     load_addr = response.GetHexMaxU64(false, LLDB_INVALID_ADDRESS);
4904     return Status();
4905   }
4906 
4907   return Status(
4908       "Unknown error happened during sending the load address packet");
4909 }
4910 
ModulesDidLoad(ModuleList & module_list)4911 void ProcessGDBRemote::ModulesDidLoad(ModuleList &module_list) {
4912   // We must call the lldb_private::Process::ModulesDidLoad () first before we
4913   // do anything
4914   Process::ModulesDidLoad(module_list);
4915 
4916   // After loading shared libraries, we can ask our remote GDB server if it
4917   // needs any symbols.
4918   m_gdb_comm.ServeSymbolLookups(this);
4919 }
4920 
HandleAsyncStdout(llvm::StringRef out)4921 void ProcessGDBRemote::HandleAsyncStdout(llvm::StringRef out) {
4922   AppendSTDOUT(out.data(), out.size());
4923 }
4924 
4925 static const char *end_delimiter = "--end--;";
4926 static const int end_delimiter_len = 8;
4927 
HandleAsyncMisc(llvm::StringRef data)4928 void ProcessGDBRemote::HandleAsyncMisc(llvm::StringRef data) {
4929   std::string input = data.str(); // '1' to move beyond 'A'
4930   if (m_partial_profile_data.length() > 0) {
4931     m_partial_profile_data.append(input);
4932     input = m_partial_profile_data;
4933     m_partial_profile_data.clear();
4934   }
4935 
4936   size_t found, pos = 0, len = input.length();
4937   while ((found = input.find(end_delimiter, pos)) != std::string::npos) {
4938     StringExtractorGDBRemote profileDataExtractor(
4939         input.substr(pos, found).c_str());
4940     std::string profile_data =
4941         HarmonizeThreadIdsForProfileData(profileDataExtractor);
4942     BroadcastAsyncProfileData(profile_data);
4943 
4944     pos = found + end_delimiter_len;
4945   }
4946 
4947   if (pos < len) {
4948     // Last incomplete chunk.
4949     m_partial_profile_data = input.substr(pos);
4950   }
4951 }
4952 
HarmonizeThreadIdsForProfileData(StringExtractorGDBRemote & profileDataExtractor)4953 std::string ProcessGDBRemote::HarmonizeThreadIdsForProfileData(
4954     StringExtractorGDBRemote &profileDataExtractor) {
4955   std::map<uint64_t, uint32_t> new_thread_id_to_used_usec_map;
4956   std::string output;
4957   llvm::raw_string_ostream output_stream(output);
4958   llvm::StringRef name, value;
4959 
4960   // Going to assuming thread_used_usec comes first, else bail out.
4961   while (profileDataExtractor.GetNameColonValue(name, value)) {
4962     if (name.compare("thread_used_id") == 0) {
4963       StringExtractor threadIDHexExtractor(value);
4964       uint64_t thread_id = threadIDHexExtractor.GetHexMaxU64(false, 0);
4965 
4966       bool has_used_usec = false;
4967       uint32_t curr_used_usec = 0;
4968       llvm::StringRef usec_name, usec_value;
4969       uint32_t input_file_pos = profileDataExtractor.GetFilePos();
4970       if (profileDataExtractor.GetNameColonValue(usec_name, usec_value)) {
4971         if (usec_name.equals("thread_used_usec")) {
4972           has_used_usec = true;
4973           usec_value.getAsInteger(0, curr_used_usec);
4974         } else {
4975           // We didn't find what we want, it is probably an older version. Bail
4976           // out.
4977           profileDataExtractor.SetFilePos(input_file_pos);
4978         }
4979       }
4980 
4981       if (has_used_usec) {
4982         uint32_t prev_used_usec = 0;
4983         std::map<uint64_t, uint32_t>::iterator iterator =
4984             m_thread_id_to_used_usec_map.find(thread_id);
4985         if (iterator != m_thread_id_to_used_usec_map.end()) {
4986           prev_used_usec = m_thread_id_to_used_usec_map[thread_id];
4987         }
4988 
4989         uint32_t real_used_usec = curr_used_usec - prev_used_usec;
4990         // A good first time record is one that runs for at least 0.25 sec
4991         bool good_first_time =
4992             (prev_used_usec == 0) && (real_used_usec > 250000);
4993         bool good_subsequent_time =
4994             (prev_used_usec > 0) &&
4995             ((real_used_usec > 0) || (HasAssignedIndexIDToThread(thread_id)));
4996 
4997         if (good_first_time || good_subsequent_time) {
4998           // We try to avoid doing too many index id reservation, resulting in
4999           // fast increase of index ids.
5000 
5001           output_stream << name << ":";
5002           int32_t index_id = AssignIndexIDToThread(thread_id);
5003           output_stream << index_id << ";";
5004 
5005           output_stream << usec_name << ":" << usec_value << ";";
5006         } else {
5007           // Skip past 'thread_used_name'.
5008           llvm::StringRef local_name, local_value;
5009           profileDataExtractor.GetNameColonValue(local_name, local_value);
5010         }
5011 
5012         // Store current time as previous time so that they can be compared
5013         // later.
5014         new_thread_id_to_used_usec_map[thread_id] = curr_used_usec;
5015       } else {
5016         // Bail out and use old string.
5017         output_stream << name << ":" << value << ";";
5018       }
5019     } else {
5020       output_stream << name << ":" << value << ";";
5021     }
5022   }
5023   output_stream << end_delimiter;
5024   m_thread_id_to_used_usec_map = new_thread_id_to_used_usec_map;
5025 
5026   return output_stream.str();
5027 }
5028 
HandleStopReply()5029 void ProcessGDBRemote::HandleStopReply() {
5030   if (GetStopID() != 0)
5031     return;
5032 
5033   if (GetID() == LLDB_INVALID_PROCESS_ID) {
5034     lldb::pid_t pid = m_gdb_comm.GetCurrentProcessID();
5035     if (pid != LLDB_INVALID_PROCESS_ID)
5036       SetID(pid);
5037   }
5038   BuildDynamicRegisterInfo(true);
5039 }
5040 
5041 static const char *const s_async_json_packet_prefix = "JSON-async:";
5042 
5043 static StructuredData::ObjectSP
ParseStructuredDataPacket(llvm::StringRef packet)5044 ParseStructuredDataPacket(llvm::StringRef packet) {
5045   Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
5046 
5047   if (!packet.consume_front(s_async_json_packet_prefix)) {
5048     if (log) {
5049       LLDB_LOGF(
5050           log,
5051           "GDBRemoteCommunicationClientBase::%s() received $J packet "
5052           "but was not a StructuredData packet: packet starts with "
5053           "%s",
5054           __FUNCTION__,
5055           packet.slice(0, strlen(s_async_json_packet_prefix)).str().c_str());
5056     }
5057     return StructuredData::ObjectSP();
5058   }
5059 
5060   // This is an asynchronous JSON packet, destined for a StructuredDataPlugin.
5061   StructuredData::ObjectSP json_sp =
5062       StructuredData::ParseJSON(std::string(packet));
5063   if (log) {
5064     if (json_sp) {
5065       StreamString json_str;
5066       json_sp->Dump(json_str, true);
5067       json_str.Flush();
5068       LLDB_LOGF(log,
5069                 "ProcessGDBRemote::%s() "
5070                 "received Async StructuredData packet: %s",
5071                 __FUNCTION__, json_str.GetData());
5072     } else {
5073       LLDB_LOGF(log,
5074                 "ProcessGDBRemote::%s"
5075                 "() received StructuredData packet:"
5076                 " parse failure",
5077                 __FUNCTION__);
5078     }
5079   }
5080   return json_sp;
5081 }
5082 
HandleAsyncStructuredDataPacket(llvm::StringRef data)5083 void ProcessGDBRemote::HandleAsyncStructuredDataPacket(llvm::StringRef data) {
5084   auto structured_data_sp = ParseStructuredDataPacket(data);
5085   if (structured_data_sp)
5086     RouteAsyncStructuredData(structured_data_sp);
5087 }
5088 
5089 class CommandObjectProcessGDBRemoteSpeedTest : public CommandObjectParsed {
5090 public:
CommandObjectProcessGDBRemoteSpeedTest(CommandInterpreter & interpreter)5091   CommandObjectProcessGDBRemoteSpeedTest(CommandInterpreter &interpreter)
5092       : CommandObjectParsed(interpreter, "process plugin packet speed-test",
5093                             "Tests packet speeds of various sizes to determine "
5094                             "the performance characteristics of the GDB remote "
5095                             "connection. ",
5096                             nullptr),
5097         m_option_group(),
5098         m_num_packets(LLDB_OPT_SET_1, false, "count", 'c', 0, eArgTypeCount,
5099                       "The number of packets to send of each varying size "
5100                       "(default is 1000).",
5101                       1000),
5102         m_max_send(LLDB_OPT_SET_1, false, "max-send", 's', 0, eArgTypeCount,
5103                    "The maximum number of bytes to send in a packet. Sizes "
5104                    "increase in powers of 2 while the size is less than or "
5105                    "equal to this option value. (default 1024).",
5106                    1024),
5107         m_max_recv(LLDB_OPT_SET_1, false, "max-receive", 'r', 0, eArgTypeCount,
5108                    "The maximum number of bytes to receive in a packet. Sizes "
5109                    "increase in powers of 2 while the size is less than or "
5110                    "equal to this option value. (default 1024).",
5111                    1024),
5112         m_json(LLDB_OPT_SET_1, false, "json", 'j',
5113                "Print the output as JSON data for easy parsing.", false, true) {
5114     m_option_group.Append(&m_num_packets, LLDB_OPT_SET_ALL, LLDB_OPT_SET_1);
5115     m_option_group.Append(&m_max_send, LLDB_OPT_SET_ALL, LLDB_OPT_SET_1);
5116     m_option_group.Append(&m_max_recv, LLDB_OPT_SET_ALL, LLDB_OPT_SET_1);
5117     m_option_group.Append(&m_json, LLDB_OPT_SET_ALL, LLDB_OPT_SET_1);
5118     m_option_group.Finalize();
5119   }
5120 
~CommandObjectProcessGDBRemoteSpeedTest()5121   ~CommandObjectProcessGDBRemoteSpeedTest() override {}
5122 
GetOptions()5123   Options *GetOptions() override { return &m_option_group; }
5124 
DoExecute(Args & command,CommandReturnObject & result)5125   bool DoExecute(Args &command, CommandReturnObject &result) override {
5126     const size_t argc = command.GetArgumentCount();
5127     if (argc == 0) {
5128       ProcessGDBRemote *process =
5129           (ProcessGDBRemote *)m_interpreter.GetExecutionContext()
5130               .GetProcessPtr();
5131       if (process) {
5132         StreamSP output_stream_sp(
5133             m_interpreter.GetDebugger().GetAsyncOutputStream());
5134         result.SetImmediateOutputStream(output_stream_sp);
5135 
5136         const uint32_t num_packets =
5137             (uint32_t)m_num_packets.GetOptionValue().GetCurrentValue();
5138         const uint64_t max_send = m_max_send.GetOptionValue().GetCurrentValue();
5139         const uint64_t max_recv = m_max_recv.GetOptionValue().GetCurrentValue();
5140         const bool json = m_json.GetOptionValue().GetCurrentValue();
5141         const uint64_t k_recv_amount =
5142             4 * 1024 * 1024; // Receive amount in bytes
5143         process->GetGDBRemote().TestPacketSpeed(
5144             num_packets, max_send, max_recv, k_recv_amount, json,
5145             output_stream_sp ? *output_stream_sp : result.GetOutputStream());
5146         result.SetStatus(eReturnStatusSuccessFinishResult);
5147         return true;
5148       }
5149     } else {
5150       result.AppendErrorWithFormat("'%s' takes no arguments",
5151                                    m_cmd_name.c_str());
5152     }
5153     result.SetStatus(eReturnStatusFailed);
5154     return false;
5155   }
5156 
5157 protected:
5158   OptionGroupOptions m_option_group;
5159   OptionGroupUInt64 m_num_packets;
5160   OptionGroupUInt64 m_max_send;
5161   OptionGroupUInt64 m_max_recv;
5162   OptionGroupBoolean m_json;
5163 };
5164 
5165 class CommandObjectProcessGDBRemotePacketHistory : public CommandObjectParsed {
5166 private:
5167 public:
CommandObjectProcessGDBRemotePacketHistory(CommandInterpreter & interpreter)5168   CommandObjectProcessGDBRemotePacketHistory(CommandInterpreter &interpreter)
5169       : CommandObjectParsed(interpreter, "process plugin packet history",
5170                             "Dumps the packet history buffer. ", nullptr) {}
5171 
~CommandObjectProcessGDBRemotePacketHistory()5172   ~CommandObjectProcessGDBRemotePacketHistory() override {}
5173 
DoExecute(Args & command,CommandReturnObject & result)5174   bool DoExecute(Args &command, CommandReturnObject &result) override {
5175     const size_t argc = command.GetArgumentCount();
5176     if (argc == 0) {
5177       ProcessGDBRemote *process =
5178           (ProcessGDBRemote *)m_interpreter.GetExecutionContext()
5179               .GetProcessPtr();
5180       if (process) {
5181         process->GetGDBRemote().DumpHistory(result.GetOutputStream());
5182         result.SetStatus(eReturnStatusSuccessFinishResult);
5183         return true;
5184       }
5185     } else {
5186       result.AppendErrorWithFormat("'%s' takes no arguments",
5187                                    m_cmd_name.c_str());
5188     }
5189     result.SetStatus(eReturnStatusFailed);
5190     return false;
5191   }
5192 };
5193 
5194 class CommandObjectProcessGDBRemotePacketXferSize : public CommandObjectParsed {
5195 private:
5196 public:
CommandObjectProcessGDBRemotePacketXferSize(CommandInterpreter & interpreter)5197   CommandObjectProcessGDBRemotePacketXferSize(CommandInterpreter &interpreter)
5198       : CommandObjectParsed(
5199             interpreter, "process plugin packet xfer-size",
5200             "Maximum size that lldb will try to read/write one one chunk.",
5201             nullptr) {}
5202 
~CommandObjectProcessGDBRemotePacketXferSize()5203   ~CommandObjectProcessGDBRemotePacketXferSize() override {}
5204 
DoExecute(Args & command,CommandReturnObject & result)5205   bool DoExecute(Args &command, CommandReturnObject &result) override {
5206     const size_t argc = command.GetArgumentCount();
5207     if (argc == 0) {
5208       result.AppendErrorWithFormat("'%s' takes an argument to specify the max "
5209                                    "amount to be transferred when "
5210                                    "reading/writing",
5211                                    m_cmd_name.c_str());
5212       result.SetStatus(eReturnStatusFailed);
5213       return false;
5214     }
5215 
5216     ProcessGDBRemote *process =
5217         (ProcessGDBRemote *)m_interpreter.GetExecutionContext().GetProcessPtr();
5218     if (process) {
5219       const char *packet_size = command.GetArgumentAtIndex(0);
5220       errno = 0;
5221       uint64_t user_specified_max = strtoul(packet_size, nullptr, 10);
5222       if (errno == 0 && user_specified_max != 0) {
5223         process->SetUserSpecifiedMaxMemoryTransferSize(user_specified_max);
5224         result.SetStatus(eReturnStatusSuccessFinishResult);
5225         return true;
5226       }
5227     }
5228     result.SetStatus(eReturnStatusFailed);
5229     return false;
5230   }
5231 };
5232 
5233 class CommandObjectProcessGDBRemotePacketSend : public CommandObjectParsed {
5234 private:
5235 public:
CommandObjectProcessGDBRemotePacketSend(CommandInterpreter & interpreter)5236   CommandObjectProcessGDBRemotePacketSend(CommandInterpreter &interpreter)
5237       : CommandObjectParsed(interpreter, "process plugin packet send",
5238                             "Send a custom packet through the GDB remote "
5239                             "protocol and print the answer. "
5240                             "The packet header and footer will automatically "
5241                             "be added to the packet prior to sending and "
5242                             "stripped from the result.",
5243                             nullptr) {}
5244 
~CommandObjectProcessGDBRemotePacketSend()5245   ~CommandObjectProcessGDBRemotePacketSend() override {}
5246 
DoExecute(Args & command,CommandReturnObject & result)5247   bool DoExecute(Args &command, CommandReturnObject &result) override {
5248     const size_t argc = command.GetArgumentCount();
5249     if (argc == 0) {
5250       result.AppendErrorWithFormat(
5251           "'%s' takes a one or more packet content arguments",
5252           m_cmd_name.c_str());
5253       result.SetStatus(eReturnStatusFailed);
5254       return false;
5255     }
5256 
5257     ProcessGDBRemote *process =
5258         (ProcessGDBRemote *)m_interpreter.GetExecutionContext().GetProcessPtr();
5259     if (process) {
5260       for (size_t i = 0; i < argc; ++i) {
5261         const char *packet_cstr = command.GetArgumentAtIndex(0);
5262         bool send_async = true;
5263         StringExtractorGDBRemote response;
5264         process->GetGDBRemote().SendPacketAndWaitForResponse(
5265             packet_cstr, response, send_async);
5266         result.SetStatus(eReturnStatusSuccessFinishResult);
5267         Stream &output_strm = result.GetOutputStream();
5268         output_strm.Printf("  packet: %s\n", packet_cstr);
5269         std::string response_str = std::string(response.GetStringRef());
5270 
5271         if (strstr(packet_cstr, "qGetProfileData") != nullptr) {
5272           response_str = process->HarmonizeThreadIdsForProfileData(response);
5273         }
5274 
5275         if (response_str.empty())
5276           output_strm.PutCString("response: \nerror: UNIMPLEMENTED\n");
5277         else
5278           output_strm.Printf("response: %s\n", response.GetStringRef().data());
5279       }
5280     }
5281     return true;
5282   }
5283 };
5284 
5285 class CommandObjectProcessGDBRemotePacketMonitor : public CommandObjectRaw {
5286 private:
5287 public:
CommandObjectProcessGDBRemotePacketMonitor(CommandInterpreter & interpreter)5288   CommandObjectProcessGDBRemotePacketMonitor(CommandInterpreter &interpreter)
5289       : CommandObjectRaw(interpreter, "process plugin packet monitor",
5290                          "Send a qRcmd packet through the GDB remote protocol "
5291                          "and print the response."
5292                          "The argument passed to this command will be hex "
5293                          "encoded into a valid 'qRcmd' packet, sent and the "
5294                          "response will be printed.") {}
5295 
~CommandObjectProcessGDBRemotePacketMonitor()5296   ~CommandObjectProcessGDBRemotePacketMonitor() override {}
5297 
DoExecute(llvm::StringRef command,CommandReturnObject & result)5298   bool DoExecute(llvm::StringRef command,
5299                  CommandReturnObject &result) override {
5300     if (command.empty()) {
5301       result.AppendErrorWithFormat("'%s' takes a command string argument",
5302                                    m_cmd_name.c_str());
5303       result.SetStatus(eReturnStatusFailed);
5304       return false;
5305     }
5306 
5307     ProcessGDBRemote *process =
5308         (ProcessGDBRemote *)m_interpreter.GetExecutionContext().GetProcessPtr();
5309     if (process) {
5310       StreamString packet;
5311       packet.PutCString("qRcmd,");
5312       packet.PutBytesAsRawHex8(command.data(), command.size());
5313 
5314       bool send_async = true;
5315       StringExtractorGDBRemote response;
5316       Stream &output_strm = result.GetOutputStream();
5317       process->GetGDBRemote().SendPacketAndReceiveResponseWithOutputSupport(
5318           packet.GetString(), response, send_async,
5319           [&output_strm](llvm::StringRef output) { output_strm << output; });
5320       result.SetStatus(eReturnStatusSuccessFinishResult);
5321       output_strm.Printf("  packet: %s\n", packet.GetData());
5322       const std::string &response_str = std::string(response.GetStringRef());
5323 
5324       if (response_str.empty())
5325         output_strm.PutCString("response: \nerror: UNIMPLEMENTED\n");
5326       else
5327         output_strm.Printf("response: %s\n", response.GetStringRef().data());
5328     }
5329     return true;
5330   }
5331 };
5332 
5333 class CommandObjectProcessGDBRemotePacket : public CommandObjectMultiword {
5334 private:
5335 public:
CommandObjectProcessGDBRemotePacket(CommandInterpreter & interpreter)5336   CommandObjectProcessGDBRemotePacket(CommandInterpreter &interpreter)
5337       : CommandObjectMultiword(interpreter, "process plugin packet",
5338                                "Commands that deal with GDB remote packets.",
5339                                nullptr) {
5340     LoadSubCommand(
5341         "history",
5342         CommandObjectSP(
5343             new CommandObjectProcessGDBRemotePacketHistory(interpreter)));
5344     LoadSubCommand(
5345         "send", CommandObjectSP(
5346                     new CommandObjectProcessGDBRemotePacketSend(interpreter)));
5347     LoadSubCommand(
5348         "monitor",
5349         CommandObjectSP(
5350             new CommandObjectProcessGDBRemotePacketMonitor(interpreter)));
5351     LoadSubCommand(
5352         "xfer-size",
5353         CommandObjectSP(
5354             new CommandObjectProcessGDBRemotePacketXferSize(interpreter)));
5355     LoadSubCommand("speed-test",
5356                    CommandObjectSP(new CommandObjectProcessGDBRemoteSpeedTest(
5357                        interpreter)));
5358   }
5359 
~CommandObjectProcessGDBRemotePacket()5360   ~CommandObjectProcessGDBRemotePacket() override {}
5361 };
5362 
5363 class CommandObjectMultiwordProcessGDBRemote : public CommandObjectMultiword {
5364 public:
CommandObjectMultiwordProcessGDBRemote(CommandInterpreter & interpreter)5365   CommandObjectMultiwordProcessGDBRemote(CommandInterpreter &interpreter)
5366       : CommandObjectMultiword(
5367             interpreter, "process plugin",
5368             "Commands for operating on a ProcessGDBRemote process.",
5369             "process plugin <subcommand> [<subcommand-options>]") {
5370     LoadSubCommand(
5371         "packet",
5372         CommandObjectSP(new CommandObjectProcessGDBRemotePacket(interpreter)));
5373   }
5374 
~CommandObjectMultiwordProcessGDBRemote()5375   ~CommandObjectMultiwordProcessGDBRemote() override {}
5376 };
5377 
GetPluginCommandObject()5378 CommandObject *ProcessGDBRemote::GetPluginCommandObject() {
5379   if (!m_command_sp)
5380     m_command_sp = std::make_shared<CommandObjectMultiwordProcessGDBRemote>(
5381         GetTarget().GetDebugger().GetCommandInterpreter());
5382   return m_command_sp.get();
5383 }
5384