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