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             UNUSED_IF_ASSERT_DISABLED(ret_val);
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->GetEvent(event_sp, std::chrono::seconds(5)) == false) {
1463         error.SetErrorString("Resume timed out.");
1464         if (log)
1465           log->Printf("ProcessGDBRemote::DoResume: Resume timed out.");
1466       } else if (event_sp->BroadcasterIs(&m_async_broadcaster)) {
1467         error.SetErrorString("Broadcast continue, but the async thread was "
1468                              "killed before we got an ack back.");
1469         if (log)
1470           log->Printf("ProcessGDBRemote::DoResume: Broadcast continue, but the "
1471                       "async thread was killed before we got an ack back.");
1472         return error;
1473       }
1474     }
1475   }
1476 
1477   return error;
1478 }
1479 
1480 void ProcessGDBRemote::HandleStopReplySequence() {
1481   while (true) {
1482     // Send vStopped
1483     StringExtractorGDBRemote response;
1484     m_gdb_comm.SendPacketAndWaitForResponse("vStopped", response, false);
1485 
1486     // OK represents end of signal list
1487     if (response.IsOKResponse())
1488       break;
1489 
1490     // If not OK or a normal packet we have a problem
1491     if (!response.IsNormalResponse())
1492       break;
1493 
1494     SetLastStopPacket(response);
1495   }
1496 }
1497 
1498 void ProcessGDBRemote::ClearThreadIDList() {
1499   std::lock_guard<std::recursive_mutex> guard(m_thread_list_real.GetMutex());
1500   m_thread_ids.clear();
1501   m_thread_pcs.clear();
1502 }
1503 
1504 size_t
1505 ProcessGDBRemote::UpdateThreadIDsFromStopReplyThreadsValue(std::string &value) {
1506   m_thread_ids.clear();
1507   m_thread_pcs.clear();
1508   size_t comma_pos;
1509   lldb::tid_t tid;
1510   while ((comma_pos = value.find(',')) != std::string::npos) {
1511     value[comma_pos] = '\0';
1512     // thread in big endian hex
1513     tid = StringConvert::ToUInt64(value.c_str(), LLDB_INVALID_THREAD_ID, 16);
1514     if (tid != LLDB_INVALID_THREAD_ID)
1515       m_thread_ids.push_back(tid);
1516     value.erase(0, comma_pos + 1);
1517   }
1518   tid = StringConvert::ToUInt64(value.c_str(), LLDB_INVALID_THREAD_ID, 16);
1519   if (tid != LLDB_INVALID_THREAD_ID)
1520     m_thread_ids.push_back(tid);
1521   return m_thread_ids.size();
1522 }
1523 
1524 size_t
1525 ProcessGDBRemote::UpdateThreadPCsFromStopReplyThreadsValue(std::string &value) {
1526   m_thread_pcs.clear();
1527   size_t comma_pos;
1528   lldb::addr_t pc;
1529   while ((comma_pos = value.find(',')) != std::string::npos) {
1530     value[comma_pos] = '\0';
1531     pc = StringConvert::ToUInt64(value.c_str(), LLDB_INVALID_ADDRESS, 16);
1532     if (pc != LLDB_INVALID_ADDRESS)
1533       m_thread_pcs.push_back(pc);
1534     value.erase(0, comma_pos + 1);
1535   }
1536   pc = StringConvert::ToUInt64(value.c_str(), LLDB_INVALID_ADDRESS, 16);
1537   if (pc != LLDB_INVALID_THREAD_ID)
1538     m_thread_pcs.push_back(pc);
1539   return m_thread_pcs.size();
1540 }
1541 
1542 bool ProcessGDBRemote::UpdateThreadIDList() {
1543   std::lock_guard<std::recursive_mutex> guard(m_thread_list_real.GetMutex());
1544 
1545   if (m_jthreadsinfo_sp) {
1546     // If we have the JSON threads info, we can get the thread list from that
1547     StructuredData::Array *thread_infos = m_jthreadsinfo_sp->GetAsArray();
1548     if (thread_infos && thread_infos->GetSize() > 0) {
1549       m_thread_ids.clear();
1550       m_thread_pcs.clear();
1551       thread_infos->ForEach([this](StructuredData::Object *object) -> bool {
1552         StructuredData::Dictionary *thread_dict = object->GetAsDictionary();
1553         if (thread_dict) {
1554           // Set the thread stop info from the JSON dictionary
1555           SetThreadStopInfo(thread_dict);
1556           lldb::tid_t tid = LLDB_INVALID_THREAD_ID;
1557           if (thread_dict->GetValueForKeyAsInteger<lldb::tid_t>("tid", tid))
1558             m_thread_ids.push_back(tid);
1559         }
1560         return true; // Keep iterating through all thread_info objects
1561       });
1562     }
1563     if (!m_thread_ids.empty())
1564       return true;
1565   } else {
1566     // See if we can get the thread IDs from the current stop reply packets
1567     // that might contain a "threads" key/value pair
1568 
1569     // Lock the thread stack while we access it
1570     // Mutex::Locker stop_stack_lock(m_last_stop_packet_mutex);
1571     std::unique_lock<std::recursive_mutex> stop_stack_lock(
1572         m_last_stop_packet_mutex, std::defer_lock);
1573     if (stop_stack_lock.try_lock()) {
1574       // Get the number of stop packets on the stack
1575       int nItems = m_stop_packet_stack.size();
1576       // Iterate over them
1577       for (int i = 0; i < nItems; i++) {
1578         // Get the thread stop info
1579         StringExtractorGDBRemote &stop_info = m_stop_packet_stack[i];
1580         const std::string &stop_info_str = stop_info.GetStringRef();
1581 
1582         m_thread_pcs.clear();
1583         const size_t thread_pcs_pos = stop_info_str.find(";thread-pcs:");
1584         if (thread_pcs_pos != std::string::npos) {
1585           const size_t start = thread_pcs_pos + strlen(";thread-pcs:");
1586           const size_t end = stop_info_str.find(';', start);
1587           if (end != std::string::npos) {
1588             std::string value = stop_info_str.substr(start, end - start);
1589             UpdateThreadPCsFromStopReplyThreadsValue(value);
1590           }
1591         }
1592 
1593         const size_t threads_pos = stop_info_str.find(";threads:");
1594         if (threads_pos != std::string::npos) {
1595           const size_t start = threads_pos + strlen(";threads:");
1596           const size_t end = stop_info_str.find(';', start);
1597           if (end != std::string::npos) {
1598             std::string value = stop_info_str.substr(start, end - start);
1599             if (UpdateThreadIDsFromStopReplyThreadsValue(value))
1600               return true;
1601           }
1602         }
1603       }
1604     }
1605   }
1606 
1607   bool sequence_mutex_unavailable = false;
1608   m_gdb_comm.GetCurrentThreadIDs(m_thread_ids, sequence_mutex_unavailable);
1609   if (sequence_mutex_unavailable) {
1610     return false; // We just didn't get the list
1611   }
1612   return true;
1613 }
1614 
1615 bool ProcessGDBRemote::UpdateThreadList(ThreadList &old_thread_list,
1616                                         ThreadList &new_thread_list) {
1617   // locker will keep a mutex locked until it goes out of scope
1618   Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_THREAD));
1619   if (log && log->GetMask().Test(GDBR_LOG_VERBOSE))
1620     log->Printf("ProcessGDBRemote::%s (pid = %" PRIu64 ")", __FUNCTION__,
1621                 GetID());
1622 
1623   size_t num_thread_ids = m_thread_ids.size();
1624   // The "m_thread_ids" thread ID list should always be updated after each stop
1625   // reply packet, but in case it isn't, update it here.
1626   if (num_thread_ids == 0) {
1627     if (!UpdateThreadIDList())
1628       return false;
1629     num_thread_ids = m_thread_ids.size();
1630   }
1631 
1632   ThreadList old_thread_list_copy(old_thread_list);
1633   if (num_thread_ids > 0) {
1634     for (size_t i = 0; i < num_thread_ids; ++i) {
1635       tid_t tid = m_thread_ids[i];
1636       ThreadSP thread_sp(
1637           old_thread_list_copy.RemoveThreadByProtocolID(tid, false));
1638       if (!thread_sp) {
1639         thread_sp.reset(new ThreadGDBRemote(*this, tid));
1640         if (log && log->GetMask().Test(GDBR_LOG_VERBOSE))
1641           log->Printf("ProcessGDBRemote::%s Making new thread: %p for thread "
1642                       "ID: 0x%" PRIx64 ".\n",
1643                       __FUNCTION__, static_cast<void *>(thread_sp.get()),
1644                       thread_sp->GetID());
1645       } else {
1646         if (log && log->GetMask().Test(GDBR_LOG_VERBOSE))
1647           log->Printf("ProcessGDBRemote::%s Found old thread: %p for thread "
1648                       "ID: 0x%" PRIx64 ".\n",
1649                       __FUNCTION__, static_cast<void *>(thread_sp.get()),
1650                       thread_sp->GetID());
1651       }
1652 
1653       SetThreadPc(thread_sp, i);
1654       new_thread_list.AddThreadSortedByIndexID(thread_sp);
1655     }
1656   }
1657 
1658   // Whatever that is left in old_thread_list_copy are not
1659   // present in new_thread_list. Remove non-existent threads from internal id
1660   // table.
1661   size_t old_num_thread_ids = old_thread_list_copy.GetSize(false);
1662   for (size_t i = 0; i < old_num_thread_ids; i++) {
1663     ThreadSP old_thread_sp(old_thread_list_copy.GetThreadAtIndex(i, false));
1664     if (old_thread_sp) {
1665       lldb::tid_t old_thread_id = old_thread_sp->GetProtocolID();
1666       m_thread_id_to_index_id_map.erase(old_thread_id);
1667     }
1668   }
1669 
1670   return true;
1671 }
1672 
1673 void ProcessGDBRemote::SetThreadPc(const ThreadSP &thread_sp, uint64_t index) {
1674   if (m_thread_ids.size() == m_thread_pcs.size() && thread_sp.get() &&
1675       GetByteOrder() != eByteOrderInvalid) {
1676     ThreadGDBRemote *gdb_thread =
1677         static_cast<ThreadGDBRemote *>(thread_sp.get());
1678     RegisterContextSP reg_ctx_sp(thread_sp->GetRegisterContext());
1679     if (reg_ctx_sp) {
1680       uint32_t pc_regnum = reg_ctx_sp->ConvertRegisterKindToRegisterNumber(
1681           eRegisterKindGeneric, LLDB_REGNUM_GENERIC_PC);
1682       if (pc_regnum != LLDB_INVALID_REGNUM) {
1683         gdb_thread->PrivateSetRegisterValue(pc_regnum, m_thread_pcs[index]);
1684       }
1685     }
1686   }
1687 }
1688 
1689 bool ProcessGDBRemote::GetThreadStopInfoFromJSON(
1690     ThreadGDBRemote *thread, const StructuredData::ObjectSP &thread_infos_sp) {
1691   // See if we got thread stop infos for all threads via the "jThreadsInfo"
1692   // packet
1693   if (thread_infos_sp) {
1694     StructuredData::Array *thread_infos = thread_infos_sp->GetAsArray();
1695     if (thread_infos) {
1696       lldb::tid_t tid;
1697       const size_t n = thread_infos->GetSize();
1698       for (size_t i = 0; i < n; ++i) {
1699         StructuredData::Dictionary *thread_dict =
1700             thread_infos->GetItemAtIndex(i)->GetAsDictionary();
1701         if (thread_dict) {
1702           if (thread_dict->GetValueForKeyAsInteger<lldb::tid_t>(
1703                   "tid", tid, LLDB_INVALID_THREAD_ID)) {
1704             if (tid == thread->GetID())
1705               return (bool)SetThreadStopInfo(thread_dict);
1706           }
1707         }
1708       }
1709     }
1710   }
1711   return false;
1712 }
1713 
1714 bool ProcessGDBRemote::CalculateThreadStopInfo(ThreadGDBRemote *thread) {
1715   // See if we got thread stop infos for all threads via the "jThreadsInfo"
1716   // packet
1717   if (GetThreadStopInfoFromJSON(thread, m_jthreadsinfo_sp))
1718     return true;
1719 
1720   // See if we got thread stop info for any threads valid stop info reasons
1721   // threads
1722   // via the "jstopinfo" packet stop reply packet key/value pair?
1723   if (m_jstopinfo_sp) {
1724     // If we have "jstopinfo" then we have stop descriptions for all threads
1725     // that have stop reasons, and if there is no entry for a thread, then
1726     // it has no stop reason.
1727     thread->GetRegisterContext()->InvalidateIfNeeded(true);
1728     if (!GetThreadStopInfoFromJSON(thread, m_jstopinfo_sp)) {
1729       thread->SetStopInfo(StopInfoSP());
1730     }
1731     return true;
1732   }
1733 
1734   // Fall back to using the qThreadStopInfo packet
1735   StringExtractorGDBRemote stop_packet;
1736   if (GetGDBRemote().GetThreadStopInfo(thread->GetProtocolID(), stop_packet))
1737     return SetThreadStopInfo(stop_packet) == eStateStopped;
1738   return false;
1739 }
1740 
1741 ThreadSP ProcessGDBRemote::SetThreadStopInfo(
1742     lldb::tid_t tid, ExpeditedRegisterMap &expedited_register_map,
1743     uint8_t signo, const std::string &thread_name, const std::string &reason,
1744     const std::string &description, uint32_t exc_type,
1745     const std::vector<addr_t> &exc_data, addr_t thread_dispatch_qaddr,
1746     bool queue_vars_valid, // Set to true if queue_name, queue_kind and
1747                            // queue_serial are valid
1748     LazyBool associated_with_dispatch_queue, addr_t dispatch_queue_t,
1749     std::string &queue_name, QueueKind queue_kind, uint64_t queue_serial) {
1750   ThreadSP thread_sp;
1751   if (tid != LLDB_INVALID_THREAD_ID) {
1752     // Scope for "locker" below
1753     {
1754       // m_thread_list_real does have its own mutex, but we need to
1755       // hold onto the mutex between the call to
1756       // m_thread_list_real.FindThreadByID(...)
1757       // and the m_thread_list_real.AddThread(...) so it doesn't change on us
1758       std::lock_guard<std::recursive_mutex> guard(
1759           m_thread_list_real.GetMutex());
1760       thread_sp = m_thread_list_real.FindThreadByProtocolID(tid, false);
1761 
1762       if (!thread_sp) {
1763         // Create the thread if we need to
1764         thread_sp.reset(new ThreadGDBRemote(*this, tid));
1765         m_thread_list_real.AddThread(thread_sp);
1766       }
1767     }
1768 
1769     if (thread_sp) {
1770       ThreadGDBRemote *gdb_thread =
1771           static_cast<ThreadGDBRemote *>(thread_sp.get());
1772       gdb_thread->GetRegisterContext()->InvalidateIfNeeded(true);
1773 
1774       auto iter = std::find(m_thread_ids.begin(), m_thread_ids.end(), tid);
1775       if (iter != m_thread_ids.end()) {
1776         SetThreadPc(thread_sp, iter - m_thread_ids.begin());
1777       }
1778 
1779       for (const auto &pair : expedited_register_map) {
1780         StringExtractor reg_value_extractor;
1781         reg_value_extractor.GetStringRef() = pair.second;
1782         DataBufferSP buffer_sp(new DataBufferHeap(
1783             reg_value_extractor.GetStringRef().size() / 2, 0));
1784         reg_value_extractor.GetHexBytes(buffer_sp->GetData(), '\xcc');
1785         gdb_thread->PrivateSetRegisterValue(pair.first, buffer_sp->GetData());
1786       }
1787 
1788       thread_sp->SetName(thread_name.empty() ? NULL : thread_name.c_str());
1789 
1790       gdb_thread->SetThreadDispatchQAddr(thread_dispatch_qaddr);
1791       // Check if the GDB server was able to provide the queue name, kind and
1792       // serial number
1793       if (queue_vars_valid)
1794         gdb_thread->SetQueueInfo(std::move(queue_name), queue_kind,
1795                                  queue_serial, dispatch_queue_t,
1796                                  associated_with_dispatch_queue);
1797       else
1798         gdb_thread->ClearQueueInfo();
1799 
1800       gdb_thread->SetAssociatedWithLibdispatchQueue(
1801           associated_with_dispatch_queue);
1802 
1803       if (dispatch_queue_t != LLDB_INVALID_ADDRESS)
1804         gdb_thread->SetQueueLibdispatchQueueAddress(dispatch_queue_t);
1805 
1806       // Make sure we update our thread stop reason just once
1807       if (!thread_sp->StopInfoIsUpToDate()) {
1808         thread_sp->SetStopInfo(StopInfoSP());
1809         // If there's a memory thread backed by this thread, we need to use it
1810         // to calcualte StopInfo.
1811         ThreadSP memory_thread_sp =
1812             m_thread_list.FindThreadByProtocolID(thread_sp->GetProtocolID());
1813         if (memory_thread_sp)
1814           thread_sp = memory_thread_sp;
1815 
1816         if (exc_type != 0) {
1817           const size_t exc_data_size = exc_data.size();
1818 
1819           thread_sp->SetStopInfo(
1820               StopInfoMachException::CreateStopReasonWithMachException(
1821                   *thread_sp, exc_type, exc_data_size,
1822                   exc_data_size >= 1 ? exc_data[0] : 0,
1823                   exc_data_size >= 2 ? exc_data[1] : 0,
1824                   exc_data_size >= 3 ? exc_data[2] : 0));
1825         } else {
1826           bool handled = false;
1827           bool did_exec = false;
1828           if (!reason.empty()) {
1829             if (reason.compare("trace") == 0) {
1830               addr_t pc = thread_sp->GetRegisterContext()->GetPC();
1831               lldb::BreakpointSiteSP bp_site_sp = thread_sp->GetProcess()
1832                                                       ->GetBreakpointSiteList()
1833                                                       .FindByAddress(pc);
1834 
1835               // If the current pc is a breakpoint site then the StopInfo should
1836               // be set to Breakpoint
1837               // Otherwise, it will be set to Trace.
1838               if (bp_site_sp &&
1839                   bp_site_sp->ValidForThisThread(thread_sp.get())) {
1840                 thread_sp->SetStopInfo(
1841                     StopInfo::CreateStopReasonWithBreakpointSiteID(
1842                         *thread_sp, bp_site_sp->GetID()));
1843               } else
1844                 thread_sp->SetStopInfo(
1845                     StopInfo::CreateStopReasonToTrace(*thread_sp));
1846               handled = true;
1847             } else if (reason.compare("breakpoint") == 0) {
1848               addr_t pc = thread_sp->GetRegisterContext()->GetPC();
1849               lldb::BreakpointSiteSP bp_site_sp = thread_sp->GetProcess()
1850                                                       ->GetBreakpointSiteList()
1851                                                       .FindByAddress(pc);
1852               if (bp_site_sp) {
1853                 // If the breakpoint is for this thread, then we'll report the
1854                 // hit, but if it is for another thread,
1855                 // we can just report no reason.  We don't need to worry about
1856                 // stepping over the breakpoint here, that
1857                 // will be taken care of when the thread resumes and notices
1858                 // that there's a breakpoint under the pc.
1859                 handled = true;
1860                 if (bp_site_sp->ValidForThisThread(thread_sp.get())) {
1861                   thread_sp->SetStopInfo(
1862                       StopInfo::CreateStopReasonWithBreakpointSiteID(
1863                           *thread_sp, bp_site_sp->GetID()));
1864                 } else {
1865                   StopInfoSP invalid_stop_info_sp;
1866                   thread_sp->SetStopInfo(invalid_stop_info_sp);
1867                 }
1868               }
1869             } else if (reason.compare("trap") == 0) {
1870               // Let the trap just use the standard signal stop reason below...
1871             } else if (reason.compare("watchpoint") == 0) {
1872               StringExtractor desc_extractor(description.c_str());
1873               addr_t wp_addr = desc_extractor.GetU64(LLDB_INVALID_ADDRESS);
1874               uint32_t wp_index = desc_extractor.GetU32(LLDB_INVALID_INDEX32);
1875               addr_t wp_hit_addr = desc_extractor.GetU64(LLDB_INVALID_ADDRESS);
1876               watch_id_t watch_id = LLDB_INVALID_WATCH_ID;
1877               if (wp_addr != LLDB_INVALID_ADDRESS) {
1878                 WatchpointSP wp_sp;
1879                 ArchSpec::Core core = GetTarget().GetArchitecture().GetCore();
1880                 if ((core >= ArchSpec::kCore_mips_first &&
1881                      core <= ArchSpec::kCore_mips_last) ||
1882                     (core >= ArchSpec::eCore_arm_generic &&
1883                      core <= ArchSpec::eCore_arm_aarch64))
1884                   wp_sp = GetTarget().GetWatchpointList().FindByAddress(
1885                       wp_hit_addr);
1886                 if (!wp_sp)
1887                   wp_sp =
1888                       GetTarget().GetWatchpointList().FindByAddress(wp_addr);
1889                 if (wp_sp) {
1890                   wp_sp->SetHardwareIndex(wp_index);
1891                   watch_id = wp_sp->GetID();
1892                 }
1893               }
1894               if (watch_id == LLDB_INVALID_WATCH_ID) {
1895                 Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(
1896                     GDBR_LOG_WATCHPOINTS));
1897                 if (log)
1898                   log->Printf("failed to find watchpoint");
1899               }
1900               thread_sp->SetStopInfo(StopInfo::CreateStopReasonWithWatchpointID(
1901                   *thread_sp, watch_id, wp_hit_addr));
1902               handled = true;
1903             } else if (reason.compare("exception") == 0) {
1904               thread_sp->SetStopInfo(StopInfo::CreateStopReasonWithException(
1905                   *thread_sp, description.c_str()));
1906               handled = true;
1907             } else if (reason.compare("exec") == 0) {
1908               did_exec = true;
1909               thread_sp->SetStopInfo(
1910                   StopInfo::CreateStopReasonWithExec(*thread_sp));
1911               handled = true;
1912             }
1913           } else if (!signo) {
1914             addr_t pc = thread_sp->GetRegisterContext()->GetPC();
1915             lldb::BreakpointSiteSP bp_site_sp =
1916                 thread_sp->GetProcess()->GetBreakpointSiteList().FindByAddress(
1917                     pc);
1918 
1919             // If the current pc is a breakpoint site then the StopInfo should
1920             // be set to Breakpoint
1921             // even though the remote stub did not set it as such. This can
1922             // happen when
1923             // the thread is involuntarily interrupted (e.g. due to stops on
1924             // other
1925             // threads) just as it is about to execute the breakpoint
1926             // instruction.
1927             if (bp_site_sp && bp_site_sp->ValidForThisThread(thread_sp.get())) {
1928               thread_sp->SetStopInfo(
1929                   StopInfo::CreateStopReasonWithBreakpointSiteID(
1930                       *thread_sp, bp_site_sp->GetID()));
1931               handled = true;
1932             }
1933           }
1934 
1935           if (!handled && signo && did_exec == false) {
1936             if (signo == SIGTRAP) {
1937               // Currently we are going to assume SIGTRAP means we are either
1938               // hitting a breakpoint or hardware single stepping.
1939               handled = true;
1940               addr_t pc = thread_sp->GetRegisterContext()->GetPC() +
1941                           m_breakpoint_pc_offset;
1942               lldb::BreakpointSiteSP bp_site_sp = thread_sp->GetProcess()
1943                                                       ->GetBreakpointSiteList()
1944                                                       .FindByAddress(pc);
1945 
1946               if (bp_site_sp) {
1947                 // If the breakpoint is for this thread, then we'll report the
1948                 // hit, but if it is for another thread,
1949                 // we can just report no reason.  We don't need to worry about
1950                 // stepping over the breakpoint here, that
1951                 // will be taken care of when the thread resumes and notices
1952                 // that there's a breakpoint under the pc.
1953                 if (bp_site_sp->ValidForThisThread(thread_sp.get())) {
1954                   if (m_breakpoint_pc_offset != 0)
1955                     thread_sp->GetRegisterContext()->SetPC(pc);
1956                   thread_sp->SetStopInfo(
1957                       StopInfo::CreateStopReasonWithBreakpointSiteID(
1958                           *thread_sp, bp_site_sp->GetID()));
1959                 } else {
1960                   StopInfoSP invalid_stop_info_sp;
1961                   thread_sp->SetStopInfo(invalid_stop_info_sp);
1962                 }
1963               } else {
1964                 // If we were stepping then assume the stop was the result of
1965                 // the trace.  If we were
1966                 // not stepping then report the SIGTRAP.
1967                 // FIXME: We are still missing the case where we single step
1968                 // over a trap instruction.
1969                 if (thread_sp->GetTemporaryResumeState() == eStateStepping)
1970                   thread_sp->SetStopInfo(
1971                       StopInfo::CreateStopReasonToTrace(*thread_sp));
1972                 else
1973                   thread_sp->SetStopInfo(StopInfo::CreateStopReasonWithSignal(
1974                       *thread_sp, signo, description.c_str()));
1975               }
1976             }
1977             if (!handled)
1978               thread_sp->SetStopInfo(StopInfo::CreateStopReasonWithSignal(
1979                   *thread_sp, signo, description.c_str()));
1980           }
1981 
1982           if (!description.empty()) {
1983             lldb::StopInfoSP stop_info_sp(thread_sp->GetStopInfo());
1984             if (stop_info_sp) {
1985               const char *stop_info_desc = stop_info_sp->GetDescription();
1986               if (!stop_info_desc || !stop_info_desc[0])
1987                 stop_info_sp->SetDescription(description.c_str());
1988             } else {
1989               thread_sp->SetStopInfo(StopInfo::CreateStopReasonWithException(
1990                   *thread_sp, description.c_str()));
1991             }
1992           }
1993         }
1994       }
1995     }
1996   }
1997   return thread_sp;
1998 }
1999 
2000 lldb::ThreadSP
2001 ProcessGDBRemote::SetThreadStopInfo(StructuredData::Dictionary *thread_dict) {
2002   static ConstString g_key_tid("tid");
2003   static ConstString g_key_name("name");
2004   static ConstString g_key_reason("reason");
2005   static ConstString g_key_metype("metype");
2006   static ConstString g_key_medata("medata");
2007   static ConstString g_key_qaddr("qaddr");
2008   static ConstString g_key_dispatch_queue_t("dispatch_queue_t");
2009   static ConstString g_key_associated_with_dispatch_queue(
2010       "associated_with_dispatch_queue");
2011   static ConstString g_key_queue_name("qname");
2012   static ConstString g_key_queue_kind("qkind");
2013   static ConstString g_key_queue_serial_number("qserialnum");
2014   static ConstString g_key_registers("registers");
2015   static ConstString g_key_memory("memory");
2016   static ConstString g_key_address("address");
2017   static ConstString g_key_bytes("bytes");
2018   static ConstString g_key_description("description");
2019   static ConstString g_key_signal("signal");
2020 
2021   // Stop with signal and thread info
2022   lldb::tid_t tid = LLDB_INVALID_THREAD_ID;
2023   uint8_t signo = 0;
2024   std::string value;
2025   std::string thread_name;
2026   std::string reason;
2027   std::string description;
2028   uint32_t exc_type = 0;
2029   std::vector<addr_t> exc_data;
2030   addr_t thread_dispatch_qaddr = LLDB_INVALID_ADDRESS;
2031   ExpeditedRegisterMap expedited_register_map;
2032   bool queue_vars_valid = false;
2033   addr_t dispatch_queue_t = LLDB_INVALID_ADDRESS;
2034   LazyBool associated_with_dispatch_queue = eLazyBoolCalculate;
2035   std::string queue_name;
2036   QueueKind queue_kind = eQueueKindUnknown;
2037   uint64_t queue_serial_number = 0;
2038   // Iterate through all of the thread dictionary key/value pairs from the
2039   // structured data dictionary
2040 
2041   thread_dict->ForEach([this, &tid, &expedited_register_map, &thread_name,
2042                         &signo, &reason, &description, &exc_type, &exc_data,
2043                         &thread_dispatch_qaddr, &queue_vars_valid,
2044                         &associated_with_dispatch_queue, &dispatch_queue_t,
2045                         &queue_name, &queue_kind, &queue_serial_number](
2046                            ConstString key,
2047                            StructuredData::Object *object) -> bool {
2048     if (key == g_key_tid) {
2049       // thread in big endian hex
2050       tid = object->GetIntegerValue(LLDB_INVALID_THREAD_ID);
2051     } else if (key == g_key_metype) {
2052       // exception type in big endian hex
2053       exc_type = object->GetIntegerValue(0);
2054     } else if (key == g_key_medata) {
2055       // exception data in big endian hex
2056       StructuredData::Array *array = object->GetAsArray();
2057       if (array) {
2058         array->ForEach([&exc_data](StructuredData::Object *object) -> bool {
2059           exc_data.push_back(object->GetIntegerValue());
2060           return true; // Keep iterating through all array items
2061         });
2062       }
2063     } else if (key == g_key_name) {
2064       thread_name = object->GetStringValue();
2065     } else if (key == g_key_qaddr) {
2066       thread_dispatch_qaddr = object->GetIntegerValue(LLDB_INVALID_ADDRESS);
2067     } else if (key == g_key_queue_name) {
2068       queue_vars_valid = true;
2069       queue_name = object->GetStringValue();
2070     } else if (key == g_key_queue_kind) {
2071       std::string queue_kind_str = object->GetStringValue();
2072       if (queue_kind_str == "serial") {
2073         queue_vars_valid = true;
2074         queue_kind = eQueueKindSerial;
2075       } else if (queue_kind_str == "concurrent") {
2076         queue_vars_valid = true;
2077         queue_kind = eQueueKindConcurrent;
2078       }
2079     } else if (key == g_key_queue_serial_number) {
2080       queue_serial_number = object->GetIntegerValue(0);
2081       if (queue_serial_number != 0)
2082         queue_vars_valid = true;
2083     } else if (key == g_key_dispatch_queue_t) {
2084       dispatch_queue_t = object->GetIntegerValue(0);
2085       if (dispatch_queue_t != 0 && dispatch_queue_t != LLDB_INVALID_ADDRESS)
2086         queue_vars_valid = true;
2087     } else if (key == g_key_associated_with_dispatch_queue) {
2088       queue_vars_valid = true;
2089       bool associated = object->GetBooleanValue();
2090       if (associated)
2091         associated_with_dispatch_queue = eLazyBoolYes;
2092       else
2093         associated_with_dispatch_queue = eLazyBoolNo;
2094     } else if (key == g_key_reason) {
2095       reason = object->GetStringValue();
2096     } else if (key == g_key_description) {
2097       description = object->GetStringValue();
2098     } else if (key == g_key_registers) {
2099       StructuredData::Dictionary *registers_dict = object->GetAsDictionary();
2100 
2101       if (registers_dict) {
2102         registers_dict->ForEach(
2103             [&expedited_register_map](ConstString key,
2104                                       StructuredData::Object *object) -> bool {
2105               const uint32_t reg =
2106                   StringConvert::ToUInt32(key.GetCString(), UINT32_MAX, 10);
2107               if (reg != UINT32_MAX)
2108                 expedited_register_map[reg] = object->GetStringValue();
2109               return true; // Keep iterating through all array items
2110             });
2111       }
2112     } else if (key == g_key_memory) {
2113       StructuredData::Array *array = object->GetAsArray();
2114       if (array) {
2115         array->ForEach([this](StructuredData::Object *object) -> bool {
2116           StructuredData::Dictionary *mem_cache_dict =
2117               object->GetAsDictionary();
2118           if (mem_cache_dict) {
2119             lldb::addr_t mem_cache_addr = LLDB_INVALID_ADDRESS;
2120             if (mem_cache_dict->GetValueForKeyAsInteger<lldb::addr_t>(
2121                     "address", mem_cache_addr)) {
2122               if (mem_cache_addr != LLDB_INVALID_ADDRESS) {
2123                 StringExtractor bytes;
2124                 if (mem_cache_dict->GetValueForKeyAsString(
2125                         "bytes", bytes.GetStringRef())) {
2126                   bytes.SetFilePos(0);
2127 
2128                   const size_t byte_size = bytes.GetStringRef().size() / 2;
2129                   DataBufferSP data_buffer_sp(new DataBufferHeap(byte_size, 0));
2130                   const size_t bytes_copied =
2131                       bytes.GetHexBytes(data_buffer_sp->GetData(), 0);
2132                   if (bytes_copied == byte_size)
2133                     m_memory_cache.AddL1CacheData(mem_cache_addr,
2134                                                   data_buffer_sp);
2135                 }
2136               }
2137             }
2138           }
2139           return true; // Keep iterating through all array items
2140         });
2141       }
2142 
2143     } else if (key == g_key_signal)
2144       signo = object->GetIntegerValue(LLDB_INVALID_SIGNAL_NUMBER);
2145     return true; // Keep iterating through all dictionary key/value pairs
2146   });
2147 
2148   return SetThreadStopInfo(tid, expedited_register_map, signo, thread_name,
2149                            reason, description, exc_type, exc_data,
2150                            thread_dispatch_qaddr, queue_vars_valid,
2151                            associated_with_dispatch_queue, dispatch_queue_t,
2152                            queue_name, queue_kind, queue_serial_number);
2153 }
2154 
2155 StateType ProcessGDBRemote::SetThreadStopInfo(StringExtractor &stop_packet) {
2156   stop_packet.SetFilePos(0);
2157   const char stop_type = stop_packet.GetChar();
2158   switch (stop_type) {
2159   case 'T':
2160   case 'S': {
2161     // This is a bit of a hack, but is is required. If we did exec, we
2162     // need to clear our thread lists and also know to rebuild our dynamic
2163     // register info before we lookup and threads and populate the expedited
2164     // register values so we need to know this right away so we can cleanup
2165     // and update our registers.
2166     const uint32_t stop_id = GetStopID();
2167     if (stop_id == 0) {
2168       // Our first stop, make sure we have a process ID, and also make
2169       // sure we know about our registers
2170       if (GetID() == LLDB_INVALID_PROCESS_ID) {
2171         lldb::pid_t pid = m_gdb_comm.GetCurrentProcessID();
2172         if (pid != LLDB_INVALID_PROCESS_ID)
2173           SetID(pid);
2174       }
2175       BuildDynamicRegisterInfo(true);
2176     }
2177     // Stop with signal and thread info
2178     lldb::tid_t tid = LLDB_INVALID_THREAD_ID;
2179     const uint8_t signo = stop_packet.GetHexU8();
2180     llvm::StringRef key;
2181     llvm::StringRef value;
2182     std::string thread_name;
2183     std::string reason;
2184     std::string description;
2185     uint32_t exc_type = 0;
2186     std::vector<addr_t> exc_data;
2187     addr_t thread_dispatch_qaddr = LLDB_INVALID_ADDRESS;
2188     bool queue_vars_valid =
2189         false; // says if locals below that start with "queue_" are valid
2190     addr_t dispatch_queue_t = LLDB_INVALID_ADDRESS;
2191     LazyBool associated_with_dispatch_queue = eLazyBoolCalculate;
2192     std::string queue_name;
2193     QueueKind queue_kind = eQueueKindUnknown;
2194     uint64_t queue_serial_number = 0;
2195     ExpeditedRegisterMap expedited_register_map;
2196     while (stop_packet.GetNameColonValue(key, value)) {
2197       if (key.compare("metype") == 0) {
2198         // exception type in big endian hex
2199         value.getAsInteger(16, exc_type);
2200       } else if (key.compare("medata") == 0) {
2201         // exception data in big endian hex
2202         uint64_t x;
2203         value.getAsInteger(16, x);
2204         exc_data.push_back(x);
2205       } else if (key.compare("thread") == 0) {
2206         // thread in big endian hex
2207         if (value.getAsInteger(16, tid))
2208           tid = LLDB_INVALID_THREAD_ID;
2209       } else if (key.compare("threads") == 0) {
2210         std::lock_guard<std::recursive_mutex> guard(
2211             m_thread_list_real.GetMutex());
2212 
2213         m_thread_ids.clear();
2214         // A comma separated list of all threads in the current
2215         // process that includes the thread for this stop reply
2216         // packet
2217         lldb::tid_t tid;
2218         while (!value.empty()) {
2219           llvm::StringRef tid_str;
2220           std::tie(tid_str, value) = value.split(',');
2221           if (tid_str.getAsInteger(16, tid))
2222             tid = LLDB_INVALID_THREAD_ID;
2223           m_thread_ids.push_back(tid);
2224         }
2225       } else if (key.compare("thread-pcs") == 0) {
2226         m_thread_pcs.clear();
2227         // A comma separated list of all threads in the current
2228         // process that includes the thread for this stop reply
2229         // packet
2230         lldb::addr_t pc;
2231         while (!value.empty()) {
2232           llvm::StringRef pc_str;
2233           std::tie(pc_str, value) = value.split(',');
2234           if (pc_str.getAsInteger(16, pc))
2235             pc = LLDB_INVALID_ADDRESS;
2236           m_thread_pcs.push_back(pc);
2237         }
2238       } else if (key.compare("jstopinfo") == 0) {
2239         StringExtractor json_extractor(value);
2240         std::string json;
2241         // Now convert the HEX bytes into a string value
2242         json_extractor.GetHexByteString(json);
2243 
2244         // This JSON contains thread IDs and thread stop info for all threads.
2245         // It doesn't contain expedited registers, memory or queue info.
2246         m_jstopinfo_sp = StructuredData::ParseJSON(json);
2247       } else if (key.compare("hexname") == 0) {
2248         StringExtractor name_extractor(value);
2249         std::string name;
2250         // Now convert the HEX bytes into a string value
2251         name_extractor.GetHexByteString(thread_name);
2252       } else if (key.compare("name") == 0) {
2253         thread_name = value;
2254       } else if (key.compare("qaddr") == 0) {
2255         value.getAsInteger(16, thread_dispatch_qaddr);
2256       } else if (key.compare("dispatch_queue_t") == 0) {
2257         queue_vars_valid = true;
2258         value.getAsInteger(16, dispatch_queue_t);
2259       } else if (key.compare("qname") == 0) {
2260         queue_vars_valid = true;
2261         StringExtractor name_extractor(value);
2262         // Now convert the HEX bytes into a string value
2263         name_extractor.GetHexByteString(queue_name);
2264       } else if (key.compare("qkind") == 0) {
2265         queue_kind = llvm::StringSwitch<QueueKind>(value)
2266                          .Case("serial", eQueueKindSerial)
2267                          .Case("concurrent", eQueueKindConcurrent)
2268                          .Default(eQueueKindUnknown);
2269         queue_vars_valid = queue_kind != eQueueKindUnknown;
2270       } else if (key.compare("qserialnum") == 0) {
2271         if (!value.getAsInteger(0, queue_serial_number))
2272           queue_vars_valid = true;
2273       } else if (key.compare("reason") == 0) {
2274         reason = value;
2275       } else if (key.compare("description") == 0) {
2276         StringExtractor desc_extractor(value);
2277         // Now convert the HEX bytes into a string value
2278         desc_extractor.GetHexByteString(description);
2279       } else if (key.compare("memory") == 0) {
2280         // Expedited memory. GDB servers can choose to send back expedited
2281         // memory
2282         // that can populate the L1 memory cache in the process so that things
2283         // like
2284         // the frame pointer backchain can be expedited. This will help stack
2285         // backtracing be more efficient by not having to send as many memory
2286         // read
2287         // requests down the remote GDB server.
2288 
2289         // Key/value pair format: memory:<addr>=<bytes>;
2290         // <addr> is a number whose base will be interpreted by the prefix:
2291         //      "0x[0-9a-fA-F]+" for hex
2292         //      "0[0-7]+" for octal
2293         //      "[1-9]+" for decimal
2294         // <bytes> is native endian ASCII hex bytes just like the register
2295         // values
2296         llvm::StringRef addr_str, bytes_str;
2297         std::tie(addr_str, bytes_str) = value.split('=');
2298         if (!addr_str.empty() && !bytes_str.empty()) {
2299           lldb::addr_t mem_cache_addr = LLDB_INVALID_ADDRESS;
2300           if (!addr_str.getAsInteger(0, mem_cache_addr)) {
2301             StringExtractor bytes(bytes_str);
2302             const size_t byte_size = bytes.GetBytesLeft() / 2;
2303             DataBufferSP data_buffer_sp(new DataBufferHeap(byte_size, 0));
2304             const size_t bytes_copied =
2305                 bytes.GetHexBytes(data_buffer_sp->GetData(), 0);
2306             if (bytes_copied == byte_size)
2307               m_memory_cache.AddL1CacheData(mem_cache_addr, data_buffer_sp);
2308           }
2309         }
2310       } else if (key.compare("watch") == 0 || key.compare("rwatch") == 0 ||
2311                  key.compare("awatch") == 0) {
2312         // Support standard GDB remote stop reply packet 'TAAwatch:addr'
2313         lldb::addr_t wp_addr = LLDB_INVALID_ADDRESS;
2314         value.getAsInteger(16, wp_addr);
2315 
2316         WatchpointSP wp_sp =
2317             GetTarget().GetWatchpointList().FindByAddress(wp_addr);
2318         uint32_t wp_index = LLDB_INVALID_INDEX32;
2319 
2320         if (wp_sp)
2321           wp_index = wp_sp->GetHardwareIndex();
2322 
2323         reason = "watchpoint";
2324         StreamString ostr;
2325         ostr.Printf("%" PRIu64 " %" PRIu32, wp_addr, wp_index);
2326         description = ostr.GetString();
2327       } else if (key.compare("library") == 0) {
2328         LoadModules();
2329       } else if (key.size() == 2 && ::isxdigit(key[0]) && ::isxdigit(key[1])) {
2330         uint32_t reg = UINT32_MAX;
2331         if (!key.getAsInteger(16, reg))
2332           expedited_register_map[reg] = std::move(value);
2333       }
2334     }
2335 
2336     if (tid == LLDB_INVALID_THREAD_ID) {
2337       // A thread id may be invalid if the response is old style 'S' packet
2338       // which does not provide the
2339       // thread information. So update the thread list and choose the first one.
2340       UpdateThreadIDList();
2341 
2342       if (!m_thread_ids.empty()) {
2343         tid = m_thread_ids.front();
2344       }
2345     }
2346 
2347     ThreadSP thread_sp = SetThreadStopInfo(
2348         tid, expedited_register_map, signo, thread_name, reason, description,
2349         exc_type, exc_data, thread_dispatch_qaddr, queue_vars_valid,
2350         associated_with_dispatch_queue, dispatch_queue_t, queue_name,
2351         queue_kind, queue_serial_number);
2352 
2353     return eStateStopped;
2354   } break;
2355 
2356   case 'W':
2357   case 'X':
2358     // process exited
2359     return eStateExited;
2360 
2361   default:
2362     break;
2363   }
2364   return eStateInvalid;
2365 }
2366 
2367 void ProcessGDBRemote::RefreshStateAfterStop() {
2368   std::lock_guard<std::recursive_mutex> guard(m_thread_list_real.GetMutex());
2369 
2370   m_thread_ids.clear();
2371   m_thread_pcs.clear();
2372   // Set the thread stop info. It might have a "threads" key whose value is
2373   // a list of all thread IDs in the current process, so m_thread_ids might
2374   // get set.
2375 
2376   // Scope for the lock
2377   {
2378     // Lock the thread stack while we access it
2379     std::lock_guard<std::recursive_mutex> guard(m_last_stop_packet_mutex);
2380     // Get the number of stop packets on the stack
2381     int nItems = m_stop_packet_stack.size();
2382     // Iterate over them
2383     for (int i = 0; i < nItems; i++) {
2384       // Get the thread stop info
2385       StringExtractorGDBRemote stop_info = m_stop_packet_stack[i];
2386       // Process thread stop info
2387       SetThreadStopInfo(stop_info);
2388     }
2389     // Clear the thread stop stack
2390     m_stop_packet_stack.clear();
2391   }
2392 
2393   // Check to see if SetThreadStopInfo() filled in m_thread_ids?
2394   if (m_thread_ids.empty()) {
2395     // No, we need to fetch the thread list manually
2396     UpdateThreadIDList();
2397   }
2398 
2399   // If we have queried for a default thread id
2400   if (m_initial_tid != LLDB_INVALID_THREAD_ID) {
2401     m_thread_list.SetSelectedThreadByID(m_initial_tid);
2402     m_initial_tid = LLDB_INVALID_THREAD_ID;
2403   }
2404 
2405   // Let all threads recover from stopping and do any clean up based
2406   // on the previous thread state (if any).
2407   m_thread_list_real.RefreshStateAfterStop();
2408 }
2409 
2410 Error ProcessGDBRemote::DoHalt(bool &caused_stop) {
2411   Error error;
2412 
2413   if (m_public_state.GetValue() == eStateAttaching) {
2414     // We are being asked to halt during an attach. We need to just close
2415     // our file handle and debugserver will go away, and we can be done...
2416     m_gdb_comm.Disconnect();
2417   } else
2418     caused_stop = m_gdb_comm.Interrupt();
2419   return error;
2420 }
2421 
2422 Error ProcessGDBRemote::DoDetach(bool keep_stopped) {
2423   Error error;
2424   Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
2425   if (log)
2426     log->Printf("ProcessGDBRemote::DoDetach(keep_stopped: %i)", keep_stopped);
2427 
2428   error = m_gdb_comm.Detach(keep_stopped);
2429   if (log) {
2430     if (error.Success())
2431       log->PutCString(
2432           "ProcessGDBRemote::DoDetach() detach packet sent successfully");
2433     else
2434       log->Printf("ProcessGDBRemote::DoDetach() detach packet send failed: %s",
2435                   error.AsCString() ? error.AsCString() : "<unknown error>");
2436   }
2437 
2438   if (!error.Success())
2439     return error;
2440 
2441   // Sleep for one second to let the process get all detached...
2442   StopAsyncThread();
2443 
2444   SetPrivateState(eStateDetached);
2445   ResumePrivateStateThread();
2446 
2447   // KillDebugserverProcess ();
2448   return error;
2449 }
2450 
2451 Error ProcessGDBRemote::DoDestroy() {
2452   Error error;
2453   Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
2454   if (log)
2455     log->Printf("ProcessGDBRemote::DoDestroy()");
2456 
2457   // There is a bug in older iOS debugservers where they don't shut down the
2458   // process
2459   // they are debugging properly.  If the process is sitting at a breakpoint or
2460   // an exception,
2461   // this can cause problems with restarting.  So we check to see if any of our
2462   // threads are stopped
2463   // at a breakpoint, and if so we remove all the breakpoints, resume the
2464   // process, and THEN
2465   // destroy it again.
2466   //
2467   // Note, we don't have a good way to test the version of debugserver, but I
2468   // happen to know that
2469   // the set of all the iOS debugservers which don't support
2470   // GetThreadSuffixSupported() and that of
2471   // the debugservers with this bug are equal.  There really should be a better
2472   // way to test this!
2473   //
2474   // We also use m_destroy_tried_resuming to make sure we only do this once, if
2475   // we resume and then halt and
2476   // get called here to destroy again and we're still at a breakpoint or
2477   // exception, then we should
2478   // just do the straight-forward kill.
2479   //
2480   // And of course, if we weren't able to stop the process by the time we get
2481   // here, it isn't
2482   // necessary (or helpful) to do any of this.
2483 
2484   if (!m_gdb_comm.GetThreadSuffixSupported() &&
2485       m_public_state.GetValue() != eStateRunning) {
2486     PlatformSP platform_sp = GetTarget().GetPlatform();
2487 
2488     // FIXME: These should be ConstStrings so we aren't doing strcmp'ing.
2489     if (platform_sp && platform_sp->GetName() &&
2490         platform_sp->GetName() == PlatformRemoteiOS::GetPluginNameStatic()) {
2491       if (m_destroy_tried_resuming) {
2492         if (log)
2493           log->PutCString("ProcessGDBRemote::DoDestroy() - Tried resuming to "
2494                           "destroy once already, not doing it again.");
2495       } else {
2496         // At present, the plans are discarded and the breakpoints disabled
2497         // Process::Destroy,
2498         // but we really need it to happen here and it doesn't matter if we do
2499         // it twice.
2500         m_thread_list.DiscardThreadPlans();
2501         DisableAllBreakpointSites();
2502 
2503         bool stop_looks_like_crash = false;
2504         ThreadList &threads = GetThreadList();
2505 
2506         {
2507           std::lock_guard<std::recursive_mutex> guard(threads.GetMutex());
2508 
2509           size_t num_threads = threads.GetSize();
2510           for (size_t i = 0; i < num_threads; i++) {
2511             ThreadSP thread_sp = threads.GetThreadAtIndex(i);
2512             StopInfoSP stop_info_sp = thread_sp->GetPrivateStopInfo();
2513             StopReason reason = eStopReasonInvalid;
2514             if (stop_info_sp)
2515               reason = stop_info_sp->GetStopReason();
2516             if (reason == eStopReasonBreakpoint ||
2517                 reason == eStopReasonException) {
2518               if (log)
2519                 log->Printf(
2520                     "ProcessGDBRemote::DoDestroy() - thread: 0x%4.4" PRIx64
2521                     " stopped with reason: %s.",
2522                     thread_sp->GetProtocolID(), stop_info_sp->GetDescription());
2523               stop_looks_like_crash = true;
2524               break;
2525             }
2526           }
2527         }
2528 
2529         if (stop_looks_like_crash) {
2530           if (log)
2531             log->PutCString("ProcessGDBRemote::DoDestroy() - Stopped at a "
2532                             "breakpoint, continue and then kill.");
2533           m_destroy_tried_resuming = true;
2534 
2535           // If we are going to run again before killing, it would be good to
2536           // suspend all the threads
2537           // before resuming so they won't get into more trouble.  Sadly, for
2538           // the threads stopped with
2539           // the breakpoint or exception, the exception doesn't get cleared if
2540           // it is suspended, so we do
2541           // have to run the risk of letting those threads proceed a bit.
2542 
2543           {
2544             std::lock_guard<std::recursive_mutex> guard(threads.GetMutex());
2545 
2546             size_t num_threads = threads.GetSize();
2547             for (size_t i = 0; i < num_threads; i++) {
2548               ThreadSP thread_sp = threads.GetThreadAtIndex(i);
2549               StopInfoSP stop_info_sp = thread_sp->GetPrivateStopInfo();
2550               StopReason reason = eStopReasonInvalid;
2551               if (stop_info_sp)
2552                 reason = stop_info_sp->GetStopReason();
2553               if (reason != eStopReasonBreakpoint &&
2554                   reason != eStopReasonException) {
2555                 if (log)
2556                   log->Printf("ProcessGDBRemote::DoDestroy() - Suspending "
2557                               "thread: 0x%4.4" PRIx64 " before running.",
2558                               thread_sp->GetProtocolID());
2559                 thread_sp->SetResumeState(eStateSuspended);
2560               }
2561             }
2562           }
2563           Resume();
2564           return Destroy(false);
2565         }
2566       }
2567     }
2568   }
2569 
2570   // Interrupt if our inferior is running...
2571   int exit_status = SIGABRT;
2572   std::string exit_string;
2573 
2574   if (m_gdb_comm.IsConnected()) {
2575     if (m_public_state.GetValue() != eStateAttaching) {
2576       StringExtractorGDBRemote response;
2577       bool send_async = true;
2578       GDBRemoteCommunication::ScopedTimeout(m_gdb_comm,
2579                                             std::chrono::seconds(3));
2580 
2581       if (m_gdb_comm.SendPacketAndWaitForResponse("k", response, send_async) ==
2582           GDBRemoteCommunication::PacketResult::Success) {
2583         char packet_cmd = response.GetChar(0);
2584 
2585         if (packet_cmd == 'W' || packet_cmd == 'X') {
2586 #if defined(__APPLE__)
2587           // For Native processes on Mac OS X, we launch through the Host
2588           // Platform, then hand the process off
2589           // to debugserver, which becomes the parent process through
2590           // "PT_ATTACH".  Then when we go to kill
2591           // the process on Mac OS X we call ptrace(PT_KILL) to kill it, then we
2592           // call waitpid which returns
2593           // with no error and the correct status.  But amusingly enough that
2594           // doesn't seem to actually reap
2595           // the process, but instead it is left around as a Zombie.  Probably
2596           // the kernel is in the process of
2597           // switching ownership back to lldb which was the original parent, and
2598           // gets confused in the handoff.
2599           // Anyway, so call waitpid here to finally reap it.
2600           PlatformSP platform_sp(GetTarget().GetPlatform());
2601           if (platform_sp && platform_sp->IsHost()) {
2602             int status;
2603             ::pid_t reap_pid;
2604             reap_pid = waitpid(GetID(), &status, WNOHANG);
2605             if (log)
2606               log->Printf("Reaped pid: %d, status: %d.\n", reap_pid, status);
2607           }
2608 #endif
2609           SetLastStopPacket(response);
2610           ClearThreadIDList();
2611           exit_status = response.GetHexU8();
2612         } else {
2613           if (log)
2614             log->Printf("ProcessGDBRemote::DoDestroy - got unexpected response "
2615                         "to k packet: %s",
2616                         response.GetStringRef().c_str());
2617           exit_string.assign("got unexpected response to k packet: ");
2618           exit_string.append(response.GetStringRef());
2619         }
2620       } else {
2621         if (log)
2622           log->Printf("ProcessGDBRemote::DoDestroy - failed to send k packet");
2623         exit_string.assign("failed to send the k packet");
2624       }
2625     } else {
2626       if (log)
2627         log->Printf("ProcessGDBRemote::DoDestroy - killed or interrupted while "
2628                     "attaching");
2629       exit_string.assign("killed or interrupted while attaching.");
2630     }
2631   } else {
2632     // If we missed setting the exit status on the way out, do it here.
2633     // NB set exit status can be called multiple times, the first one sets the
2634     // status.
2635     exit_string.assign("destroying when not connected to debugserver");
2636   }
2637 
2638   SetExitStatus(exit_status, exit_string.c_str());
2639 
2640   StopAsyncThread();
2641   KillDebugserverProcess();
2642   return error;
2643 }
2644 
2645 void ProcessGDBRemote::SetLastStopPacket(
2646     const StringExtractorGDBRemote &response) {
2647   const bool did_exec =
2648       response.GetStringRef().find(";reason:exec;") != std::string::npos;
2649   if (did_exec) {
2650     Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
2651     if (log)
2652       log->Printf("ProcessGDBRemote::SetLastStopPacket () - detected exec");
2653 
2654     m_thread_list_real.Clear();
2655     m_thread_list.Clear();
2656     BuildDynamicRegisterInfo(true);
2657     m_gdb_comm.ResetDiscoverableSettings(did_exec);
2658   }
2659 
2660   // Scope the lock
2661   {
2662     // Lock the thread stack while we access it
2663     std::lock_guard<std::recursive_mutex> guard(m_last_stop_packet_mutex);
2664 
2665     // We are are not using non-stop mode, there can only be one last stop
2666     // reply packet, so clear the list.
2667     if (GetTarget().GetNonStopModeEnabled() == false)
2668       m_stop_packet_stack.clear();
2669 
2670     // Add this stop packet to the stop packet stack
2671     // This stack will get popped and examined when we switch to the
2672     // Stopped state
2673     m_stop_packet_stack.push_back(response);
2674   }
2675 }
2676 
2677 void ProcessGDBRemote::SetUnixSignals(const UnixSignalsSP &signals_sp) {
2678   Process::SetUnixSignals(std::make_shared<GDBRemoteSignals>(signals_sp));
2679 }
2680 
2681 //------------------------------------------------------------------
2682 // Process Queries
2683 //------------------------------------------------------------------
2684 
2685 bool ProcessGDBRemote::IsAlive() {
2686   return m_gdb_comm.IsConnected() && Process::IsAlive();
2687 }
2688 
2689 addr_t ProcessGDBRemote::GetImageInfoAddress() {
2690   // request the link map address via the $qShlibInfoAddr packet
2691   lldb::addr_t addr = m_gdb_comm.GetShlibInfoAddr();
2692 
2693   // the loaded module list can also provides a link map address
2694   if (addr == LLDB_INVALID_ADDRESS) {
2695     LoadedModuleInfoList list;
2696     if (GetLoadedModuleList(list).Success())
2697       addr = list.m_link_map;
2698   }
2699 
2700   return addr;
2701 }
2702 
2703 void ProcessGDBRemote::WillPublicStop() {
2704   // See if the GDB remote client supports the JSON threads info.
2705   // If so, we gather stop info for all threads, expedited registers,
2706   // expedited memory, runtime queue information (iOS and MacOSX only),
2707   // and more. Expediting memory will help stack backtracing be much
2708   // faster. Expediting registers will make sure we don't have to read
2709   // the thread registers for GPRs.
2710   m_jthreadsinfo_sp = m_gdb_comm.GetThreadsInfo();
2711 
2712   if (m_jthreadsinfo_sp) {
2713     // Now set the stop info for each thread and also expedite any registers
2714     // and memory that was in the jThreadsInfo response.
2715     StructuredData::Array *thread_infos = m_jthreadsinfo_sp->GetAsArray();
2716     if (thread_infos) {
2717       const size_t n = thread_infos->GetSize();
2718       for (size_t i = 0; i < n; ++i) {
2719         StructuredData::Dictionary *thread_dict =
2720             thread_infos->GetItemAtIndex(i)->GetAsDictionary();
2721         if (thread_dict)
2722           SetThreadStopInfo(thread_dict);
2723       }
2724     }
2725   }
2726 }
2727 
2728 //------------------------------------------------------------------
2729 // Process Memory
2730 //------------------------------------------------------------------
2731 size_t ProcessGDBRemote::DoReadMemory(addr_t addr, void *buf, size_t size,
2732                                       Error &error) {
2733   GetMaxMemorySize();
2734   bool binary_memory_read = m_gdb_comm.GetxPacketSupported();
2735   // M and m packets take 2 bytes for 1 byte of memory
2736   size_t max_memory_size =
2737       binary_memory_read ? m_max_memory_size : m_max_memory_size / 2;
2738   if (size > max_memory_size) {
2739     // Keep memory read sizes down to a sane limit. This function will be
2740     // called multiple times in order to complete the task by
2741     // lldb_private::Process so it is ok to do this.
2742     size = max_memory_size;
2743   }
2744 
2745   char packet[64];
2746   int packet_len;
2747   packet_len = ::snprintf(packet, sizeof(packet), "%c%" PRIx64 ",%" PRIx64,
2748                           binary_memory_read ? 'x' : 'm', (uint64_t)addr,
2749                           (uint64_t)size);
2750   assert(packet_len + 1 < (int)sizeof(packet));
2751   UNUSED_IF_ASSERT_DISABLED(packet_len);
2752   StringExtractorGDBRemote response;
2753   if (m_gdb_comm.SendPacketAndWaitForResponse(packet, response, true) ==
2754       GDBRemoteCommunication::PacketResult::Success) {
2755     if (response.IsNormalResponse()) {
2756       error.Clear();
2757       if (binary_memory_read) {
2758         // The lower level GDBRemoteCommunication packet receive layer has
2759         // already de-quoted any
2760         // 0x7d character escaping that was present in the packet
2761 
2762         size_t data_received_size = response.GetBytesLeft();
2763         if (data_received_size > size) {
2764           // Don't write past the end of BUF if the remote debug server gave us
2765           // too
2766           // much data for some reason.
2767           data_received_size = size;
2768         }
2769         memcpy(buf, response.GetStringRef().data(), data_received_size);
2770         return data_received_size;
2771       } else {
2772         return response.GetHexBytes(
2773             llvm::MutableArrayRef<uint8_t>((uint8_t *)buf, size), '\xdd');
2774       }
2775     } else if (response.IsErrorResponse())
2776       error.SetErrorStringWithFormat("memory read failed for 0x%" PRIx64, addr);
2777     else if (response.IsUnsupportedResponse())
2778       error.SetErrorStringWithFormat(
2779           "GDB server does not support reading memory");
2780     else
2781       error.SetErrorStringWithFormat(
2782           "unexpected response to GDB server memory read packet '%s': '%s'",
2783           packet, response.GetStringRef().c_str());
2784   } else {
2785     error.SetErrorStringWithFormat("failed to send packet: '%s'", packet);
2786   }
2787   return 0;
2788 }
2789 
2790 size_t ProcessGDBRemote::DoWriteMemory(addr_t addr, const void *buf,
2791                                        size_t size, Error &error) {
2792   GetMaxMemorySize();
2793   // M and m packets take 2 bytes for 1 byte of memory
2794   size_t max_memory_size = m_max_memory_size / 2;
2795   if (size > max_memory_size) {
2796     // Keep memory read sizes down to a sane limit. This function will be
2797     // called multiple times in order to complete the task by
2798     // lldb_private::Process so it is ok to do this.
2799     size = max_memory_size;
2800   }
2801 
2802   StreamString packet;
2803   packet.Printf("M%" PRIx64 ",%" PRIx64 ":", addr, (uint64_t)size);
2804   packet.PutBytesAsRawHex8(buf, size, endian::InlHostByteOrder(),
2805                            endian::InlHostByteOrder());
2806   StringExtractorGDBRemote response;
2807   if (m_gdb_comm.SendPacketAndWaitForResponse(packet.GetString(), response,
2808                                               true) ==
2809       GDBRemoteCommunication::PacketResult::Success) {
2810     if (response.IsOKResponse()) {
2811       error.Clear();
2812       return size;
2813     } else if (response.IsErrorResponse())
2814       error.SetErrorStringWithFormat("memory write failed for 0x%" PRIx64,
2815                                      addr);
2816     else if (response.IsUnsupportedResponse())
2817       error.SetErrorStringWithFormat(
2818           "GDB server does not support writing memory");
2819     else
2820       error.SetErrorStringWithFormat(
2821           "unexpected response to GDB server memory write packet '%s': '%s'",
2822           packet.GetData(), response.GetStringRef().c_str());
2823   } else {
2824     error.SetErrorStringWithFormat("failed to send packet: '%s'",
2825                                    packet.GetData());
2826   }
2827   return 0;
2828 }
2829 
2830 lldb::addr_t ProcessGDBRemote::DoAllocateMemory(size_t size,
2831                                                 uint32_t permissions,
2832                                                 Error &error) {
2833   Log *log(
2834       GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS | LIBLLDB_LOG_EXPRESSIONS));
2835   addr_t allocated_addr = LLDB_INVALID_ADDRESS;
2836 
2837   if (m_gdb_comm.SupportsAllocDeallocMemory() != eLazyBoolNo) {
2838     allocated_addr = m_gdb_comm.AllocateMemory(size, permissions);
2839     if (allocated_addr != LLDB_INVALID_ADDRESS ||
2840         m_gdb_comm.SupportsAllocDeallocMemory() == eLazyBoolYes)
2841       return allocated_addr;
2842   }
2843 
2844   if (m_gdb_comm.SupportsAllocDeallocMemory() == eLazyBoolNo) {
2845     // Call mmap() to create memory in the inferior..
2846     unsigned prot = 0;
2847     if (permissions & lldb::ePermissionsReadable)
2848       prot |= eMmapProtRead;
2849     if (permissions & lldb::ePermissionsWritable)
2850       prot |= eMmapProtWrite;
2851     if (permissions & lldb::ePermissionsExecutable)
2852       prot |= eMmapProtExec;
2853 
2854     if (InferiorCallMmap(this, allocated_addr, 0, size, prot,
2855                          eMmapFlagsAnon | eMmapFlagsPrivate, -1, 0))
2856       m_addr_to_mmap_size[allocated_addr] = size;
2857     else {
2858       allocated_addr = LLDB_INVALID_ADDRESS;
2859       if (log)
2860         log->Printf("ProcessGDBRemote::%s no direct stub support for memory "
2861                     "allocation, and InferiorCallMmap also failed - is stub "
2862                     "missing register context save/restore capability?",
2863                     __FUNCTION__);
2864     }
2865   }
2866 
2867   if (allocated_addr == LLDB_INVALID_ADDRESS)
2868     error.SetErrorStringWithFormat(
2869         "unable to allocate %" PRIu64 " bytes of memory with permissions %s",
2870         (uint64_t)size, GetPermissionsAsCString(permissions));
2871   else
2872     error.Clear();
2873   return allocated_addr;
2874 }
2875 
2876 Error ProcessGDBRemote::GetMemoryRegionInfo(addr_t load_addr,
2877                                             MemoryRegionInfo &region_info) {
2878 
2879   Error error(m_gdb_comm.GetMemoryRegionInfo(load_addr, region_info));
2880   return error;
2881 }
2882 
2883 Error ProcessGDBRemote::GetWatchpointSupportInfo(uint32_t &num) {
2884 
2885   Error error(m_gdb_comm.GetWatchpointSupportInfo(num));
2886   return error;
2887 }
2888 
2889 Error ProcessGDBRemote::GetWatchpointSupportInfo(uint32_t &num, bool &after) {
2890   Error error(m_gdb_comm.GetWatchpointSupportInfo(
2891       num, after, GetTarget().GetArchitecture()));
2892   return error;
2893 }
2894 
2895 Error ProcessGDBRemote::DoDeallocateMemory(lldb::addr_t addr) {
2896   Error error;
2897   LazyBool supported = m_gdb_comm.SupportsAllocDeallocMemory();
2898 
2899   switch (supported) {
2900   case eLazyBoolCalculate:
2901     // We should never be deallocating memory without allocating memory
2902     // first so we should never get eLazyBoolCalculate
2903     error.SetErrorString(
2904         "tried to deallocate memory without ever allocating memory");
2905     break;
2906 
2907   case eLazyBoolYes:
2908     if (!m_gdb_comm.DeallocateMemory(addr))
2909       error.SetErrorStringWithFormat(
2910           "unable to deallocate memory at 0x%" PRIx64, addr);
2911     break;
2912 
2913   case eLazyBoolNo:
2914     // Call munmap() to deallocate memory in the inferior..
2915     {
2916       MMapMap::iterator pos = m_addr_to_mmap_size.find(addr);
2917       if (pos != m_addr_to_mmap_size.end() &&
2918           InferiorCallMunmap(this, addr, pos->second))
2919         m_addr_to_mmap_size.erase(pos);
2920       else
2921         error.SetErrorStringWithFormat(
2922             "unable to deallocate memory at 0x%" PRIx64, addr);
2923     }
2924     break;
2925   }
2926 
2927   return error;
2928 }
2929 
2930 //------------------------------------------------------------------
2931 // Process STDIO
2932 //------------------------------------------------------------------
2933 size_t ProcessGDBRemote::PutSTDIN(const char *src, size_t src_len,
2934                                   Error &error) {
2935   if (m_stdio_communication.IsConnected()) {
2936     ConnectionStatus status;
2937     m_stdio_communication.Write(src, src_len, status, NULL);
2938   } else if (m_stdin_forward) {
2939     m_gdb_comm.SendStdinNotification(src, src_len);
2940   }
2941   return 0;
2942 }
2943 
2944 Error ProcessGDBRemote::EnableBreakpointSite(BreakpointSite *bp_site) {
2945   Error error;
2946   assert(bp_site != NULL);
2947 
2948   // Get logging info
2949   Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_BREAKPOINTS));
2950   user_id_t site_id = bp_site->GetID();
2951 
2952   // Get the breakpoint address
2953   const addr_t addr = bp_site->GetLoadAddress();
2954 
2955   // Log that a breakpoint was requested
2956   if (log)
2957     log->Printf("ProcessGDBRemote::EnableBreakpointSite (size_id = %" PRIu64
2958                 ") address = 0x%" PRIx64,
2959                 site_id, (uint64_t)addr);
2960 
2961   // Breakpoint already exists and is enabled
2962   if (bp_site->IsEnabled()) {
2963     if (log)
2964       log->Printf("ProcessGDBRemote::EnableBreakpointSite (size_id = %" PRIu64
2965                   ") address = 0x%" PRIx64 " -- SUCCESS (already enabled)",
2966                   site_id, (uint64_t)addr);
2967     return error;
2968   }
2969 
2970   // Get the software breakpoint trap opcode size
2971   const size_t bp_op_size = GetSoftwareBreakpointTrapOpcode(bp_site);
2972 
2973   // SupportsGDBStoppointPacket() simply checks a boolean, indicating if this
2974   // breakpoint type
2975   // is supported by the remote stub. These are set to true by default, and
2976   // later set to false
2977   // only after we receive an unimplemented response when sending a breakpoint
2978   // packet. This means
2979   // initially that unless we were specifically instructed to use a hardware
2980   // breakpoint, LLDB will
2981   // attempt to set a software breakpoint. HardwareRequired() also queries a
2982   // boolean variable which
2983   // indicates if the user specifically asked for hardware breakpoints.  If true
2984   // then we will
2985   // skip over software breakpoints.
2986   if (m_gdb_comm.SupportsGDBStoppointPacket(eBreakpointSoftware) &&
2987       (!bp_site->HardwareRequired())) {
2988     // Try to send off a software breakpoint packet ($Z0)
2989     uint8_t error_no = m_gdb_comm.SendGDBStoppointTypePacket(
2990         eBreakpointSoftware, true, addr, bp_op_size);
2991     if (error_no == 0) {
2992       // The breakpoint was placed successfully
2993       bp_site->SetEnabled(true);
2994       bp_site->SetType(BreakpointSite::eExternal);
2995       return error;
2996     }
2997 
2998     // SendGDBStoppointTypePacket() will return an error if it was unable to set
2999     // this
3000     // breakpoint. We need to differentiate between a error specific to placing
3001     // this breakpoint
3002     // or if we have learned that this breakpoint type is unsupported. To do
3003     // this, we
3004     // must test the support boolean for this breakpoint type to see if it now
3005     // indicates that
3006     // this breakpoint type is unsupported.  If they are still supported then we
3007     // should return
3008     // with the error code.  If they are now unsupported, then we would like to
3009     // fall through
3010     // and try another form of breakpoint.
3011     if (m_gdb_comm.SupportsGDBStoppointPacket(eBreakpointSoftware)) {
3012       if (error_no != UINT8_MAX)
3013         error.SetErrorStringWithFormat(
3014             "error: %d sending the breakpoint request", errno);
3015       else
3016         error.SetErrorString("error sending the breakpoint request");
3017       return error;
3018     }
3019 
3020     // We reach here when software breakpoints have been found to be
3021     // unsupported. For future
3022     // calls to set a breakpoint, we will not attempt to set a breakpoint with a
3023     // type that is
3024     // known not to be supported.
3025     if (log)
3026       log->Printf("Software breakpoints are unsupported");
3027 
3028     // So we will fall through and try a hardware breakpoint
3029   }
3030 
3031   // The process of setting a hardware breakpoint is much the same as above.  We
3032   // check the
3033   // supported boolean for this breakpoint type, and if it is thought to be
3034   // supported then we
3035   // will try to set this breakpoint with a hardware breakpoint.
3036   if (m_gdb_comm.SupportsGDBStoppointPacket(eBreakpointHardware)) {
3037     // Try to send off a hardware breakpoint packet ($Z1)
3038     uint8_t error_no = m_gdb_comm.SendGDBStoppointTypePacket(
3039         eBreakpointHardware, true, addr, bp_op_size);
3040     if (error_no == 0) {
3041       // The breakpoint was placed successfully
3042       bp_site->SetEnabled(true);
3043       bp_site->SetType(BreakpointSite::eHardware);
3044       return error;
3045     }
3046 
3047     // Check if the error was something other then an unsupported breakpoint
3048     // type
3049     if (m_gdb_comm.SupportsGDBStoppointPacket(eBreakpointHardware)) {
3050       // Unable to set this hardware breakpoint
3051       if (error_no != UINT8_MAX)
3052         error.SetErrorStringWithFormat(
3053             "error: %d sending the hardware breakpoint request "
3054             "(hardware breakpoint resources might be exhausted or unavailable)",
3055             error_no);
3056       else
3057         error.SetErrorString("error sending the hardware breakpoint request "
3058                              "(hardware breakpoint resources "
3059                              "might be exhausted or unavailable)");
3060       return error;
3061     }
3062 
3063     // We will reach here when the stub gives an unsupported response to a
3064     // hardware breakpoint
3065     if (log)
3066       log->Printf("Hardware breakpoints are unsupported");
3067 
3068     // Finally we will falling through to a #trap style breakpoint
3069   }
3070 
3071   // Don't fall through when hardware breakpoints were specifically requested
3072   if (bp_site->HardwareRequired()) {
3073     error.SetErrorString("hardware breakpoints are not supported");
3074     return error;
3075   }
3076 
3077   // As a last resort we want to place a manual breakpoint. An instruction
3078   // is placed into the process memory using memory write packets.
3079   return EnableSoftwareBreakpoint(bp_site);
3080 }
3081 
3082 Error ProcessGDBRemote::DisableBreakpointSite(BreakpointSite *bp_site) {
3083   Error error;
3084   assert(bp_site != NULL);
3085   addr_t addr = bp_site->GetLoadAddress();
3086   user_id_t site_id = bp_site->GetID();
3087   Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_BREAKPOINTS));
3088   if (log)
3089     log->Printf("ProcessGDBRemote::DisableBreakpointSite (site_id = %" PRIu64
3090                 ") addr = 0x%8.8" PRIx64,
3091                 site_id, (uint64_t)addr);
3092 
3093   if (bp_site->IsEnabled()) {
3094     const size_t bp_op_size = GetSoftwareBreakpointTrapOpcode(bp_site);
3095 
3096     BreakpointSite::Type bp_type = bp_site->GetType();
3097     switch (bp_type) {
3098     case BreakpointSite::eSoftware:
3099       error = DisableSoftwareBreakpoint(bp_site);
3100       break;
3101 
3102     case BreakpointSite::eHardware:
3103       if (m_gdb_comm.SendGDBStoppointTypePacket(eBreakpointHardware, false,
3104                                                 addr, bp_op_size))
3105         error.SetErrorToGenericError();
3106       break;
3107 
3108     case BreakpointSite::eExternal: {
3109       GDBStoppointType stoppoint_type;
3110       if (bp_site->IsHardware())
3111         stoppoint_type = eBreakpointHardware;
3112       else
3113         stoppoint_type = eBreakpointSoftware;
3114 
3115       if (m_gdb_comm.SendGDBStoppointTypePacket(stoppoint_type, false, addr,
3116                                                 bp_op_size))
3117         error.SetErrorToGenericError();
3118     } break;
3119     }
3120     if (error.Success())
3121       bp_site->SetEnabled(false);
3122   } else {
3123     if (log)
3124       log->Printf("ProcessGDBRemote::DisableBreakpointSite (site_id = %" PRIu64
3125                   ") addr = 0x%8.8" PRIx64 " -- SUCCESS (already disabled)",
3126                   site_id, (uint64_t)addr);
3127     return error;
3128   }
3129 
3130   if (error.Success())
3131     error.SetErrorToGenericError();
3132   return error;
3133 }
3134 
3135 // Pre-requisite: wp != NULL.
3136 static GDBStoppointType GetGDBStoppointType(Watchpoint *wp) {
3137   assert(wp);
3138   bool watch_read = wp->WatchpointRead();
3139   bool watch_write = wp->WatchpointWrite();
3140 
3141   // watch_read and watch_write cannot both be false.
3142   assert(watch_read || watch_write);
3143   if (watch_read && watch_write)
3144     return eWatchpointReadWrite;
3145   else if (watch_read)
3146     return eWatchpointRead;
3147   else // Must be watch_write, then.
3148     return eWatchpointWrite;
3149 }
3150 
3151 Error ProcessGDBRemote::EnableWatchpoint(Watchpoint *wp, bool notify) {
3152   Error error;
3153   if (wp) {
3154     user_id_t watchID = wp->GetID();
3155     addr_t addr = wp->GetLoadAddress();
3156     Log *log(
3157         ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_WATCHPOINTS));
3158     if (log)
3159       log->Printf("ProcessGDBRemote::EnableWatchpoint(watchID = %" PRIu64 ")",
3160                   watchID);
3161     if (wp->IsEnabled()) {
3162       if (log)
3163         log->Printf("ProcessGDBRemote::EnableWatchpoint(watchID = %" PRIu64
3164                     ") addr = 0x%8.8" PRIx64 ": watchpoint already enabled.",
3165                     watchID, (uint64_t)addr);
3166       return error;
3167     }
3168 
3169     GDBStoppointType type = GetGDBStoppointType(wp);
3170     // Pass down an appropriate z/Z packet...
3171     if (m_gdb_comm.SupportsGDBStoppointPacket(type)) {
3172       if (m_gdb_comm.SendGDBStoppointTypePacket(type, true, addr,
3173                                                 wp->GetByteSize()) == 0) {
3174         wp->SetEnabled(true, notify);
3175         return error;
3176       } else
3177         error.SetErrorString("sending gdb watchpoint packet failed");
3178     } else
3179       error.SetErrorString("watchpoints not supported");
3180   } else {
3181     error.SetErrorString("Watchpoint argument was NULL.");
3182   }
3183   if (error.Success())
3184     error.SetErrorToGenericError();
3185   return error;
3186 }
3187 
3188 Error ProcessGDBRemote::DisableWatchpoint(Watchpoint *wp, bool notify) {
3189   Error error;
3190   if (wp) {
3191     user_id_t watchID = wp->GetID();
3192 
3193     Log *log(
3194         ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_WATCHPOINTS));
3195 
3196     addr_t addr = wp->GetLoadAddress();
3197 
3198     if (log)
3199       log->Printf("ProcessGDBRemote::DisableWatchpoint (watchID = %" PRIu64
3200                   ") addr = 0x%8.8" PRIx64,
3201                   watchID, (uint64_t)addr);
3202 
3203     if (!wp->IsEnabled()) {
3204       if (log)
3205         log->Printf("ProcessGDBRemote::DisableWatchpoint (watchID = %" PRIu64
3206                     ") addr = 0x%8.8" PRIx64 " -- SUCCESS (already disabled)",
3207                     watchID, (uint64_t)addr);
3208       // See also 'class WatchpointSentry' within StopInfo.cpp.
3209       // This disabling attempt might come from the user-supplied actions, we'll
3210       // route it in order for
3211       // the watchpoint object to intelligently process this action.
3212       wp->SetEnabled(false, notify);
3213       return error;
3214     }
3215 
3216     if (wp->IsHardware()) {
3217       GDBStoppointType type = GetGDBStoppointType(wp);
3218       // Pass down an appropriate z/Z packet...
3219       if (m_gdb_comm.SendGDBStoppointTypePacket(type, false, addr,
3220                                                 wp->GetByteSize()) == 0) {
3221         wp->SetEnabled(false, notify);
3222         return error;
3223       } else
3224         error.SetErrorString("sending gdb watchpoint packet failed");
3225     }
3226     // TODO: clear software watchpoints if we implement them
3227   } else {
3228     error.SetErrorString("Watchpoint argument was NULL.");
3229   }
3230   if (error.Success())
3231     error.SetErrorToGenericError();
3232   return error;
3233 }
3234 
3235 void ProcessGDBRemote::Clear() {
3236   m_flags = 0;
3237   m_thread_list_real.Clear();
3238   m_thread_list.Clear();
3239 }
3240 
3241 Error ProcessGDBRemote::DoSignal(int signo) {
3242   Error error;
3243   Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
3244   if (log)
3245     log->Printf("ProcessGDBRemote::DoSignal (signal = %d)", signo);
3246 
3247   if (!m_gdb_comm.SendAsyncSignal(signo))
3248     error.SetErrorStringWithFormat("failed to send signal %i", signo);
3249   return error;
3250 }
3251 
3252 Error ProcessGDBRemote::EstablishConnectionIfNeeded(
3253     const ProcessInfo &process_info) {
3254   // Make sure we aren't already connected?
3255   if (m_gdb_comm.IsConnected())
3256     return Error();
3257 
3258   PlatformSP platform_sp(GetTarget().GetPlatform());
3259   if (platform_sp && !platform_sp->IsHost())
3260     return Error("Lost debug server connection");
3261 
3262   auto error = LaunchAndConnectToDebugserver(process_info);
3263   if (error.Fail()) {
3264     const char *error_string = error.AsCString();
3265     if (error_string == nullptr)
3266       error_string = "unable to launch " DEBUGSERVER_BASENAME;
3267   }
3268   return error;
3269 }
3270 #if defined(__APPLE__)
3271 #define USE_SOCKETPAIR_FOR_LOCAL_CONNECTION 1
3272 #endif
3273 
3274 #ifdef USE_SOCKETPAIR_FOR_LOCAL_CONNECTION
3275 static bool SetCloexecFlag(int fd) {
3276 #if defined(FD_CLOEXEC)
3277   int flags = ::fcntl(fd, F_GETFD);
3278   if (flags == -1)
3279     return false;
3280   return (::fcntl(fd, F_SETFD, flags | FD_CLOEXEC) == 0);
3281 #else
3282   return false;
3283 #endif
3284 }
3285 #endif
3286 
3287 Error ProcessGDBRemote::LaunchAndConnectToDebugserver(
3288     const ProcessInfo &process_info) {
3289   using namespace std::placeholders; // For _1, _2, etc.
3290 
3291   Error error;
3292   if (m_debugserver_pid == LLDB_INVALID_PROCESS_ID) {
3293     // If we locate debugserver, keep that located version around
3294     static FileSpec g_debugserver_file_spec;
3295 
3296     ProcessLaunchInfo debugserver_launch_info;
3297     // Make debugserver run in its own session so signals generated by
3298     // special terminal key sequences (^C) don't affect debugserver.
3299     debugserver_launch_info.SetLaunchInSeparateProcessGroup(true);
3300 
3301     const std::weak_ptr<ProcessGDBRemote> this_wp =
3302         std::static_pointer_cast<ProcessGDBRemote>(shared_from_this());
3303     debugserver_launch_info.SetMonitorProcessCallback(
3304         std::bind(MonitorDebugserverProcess, this_wp, _1, _2, _3, _4), false);
3305     debugserver_launch_info.SetUserID(process_info.GetUserID());
3306 
3307     int communication_fd = -1;
3308 #ifdef USE_SOCKETPAIR_FOR_LOCAL_CONNECTION
3309     // Auto close the sockets we might open up unless everything goes OK. This
3310     // helps us not leak file descriptors when things go wrong.
3311     lldb_utility::CleanUp<int, int> our_socket(-1, -1, close);
3312     lldb_utility::CleanUp<int, int> gdb_socket(-1, -1, close);
3313 
3314     // Use a socketpair on Apple for now until other platforms can verify it
3315     // works and is fast enough
3316     {
3317       int sockets[2]; /* the pair of socket descriptors */
3318       if (socketpair(AF_UNIX, SOCK_STREAM, 0, sockets) == -1) {
3319         error.SetErrorToErrno();
3320         return error;
3321       }
3322 
3323       our_socket.set(sockets[0]);
3324       gdb_socket.set(sockets[1]);
3325     }
3326 
3327     // Don't let any child processes inherit our communication socket
3328     SetCloexecFlag(our_socket.get());
3329     communication_fd = gdb_socket.get();
3330 #endif
3331 
3332     error = m_gdb_comm.StartDebugserverProcess(
3333         nullptr, GetTarget().GetPlatform().get(), debugserver_launch_info,
3334         nullptr, nullptr, communication_fd);
3335 
3336     if (error.Success())
3337       m_debugserver_pid = debugserver_launch_info.GetProcessID();
3338     else
3339       m_debugserver_pid = LLDB_INVALID_PROCESS_ID;
3340 
3341     if (m_debugserver_pid != LLDB_INVALID_PROCESS_ID) {
3342 #ifdef USE_SOCKETPAIR_FOR_LOCAL_CONNECTION
3343       // Our process spawned correctly, we can now set our connection to use our
3344       // end of the socket pair
3345       m_gdb_comm.SetConnection(
3346           new ConnectionFileDescriptor(our_socket.release(), true));
3347 #endif
3348       StartAsyncThread();
3349     }
3350 
3351     if (error.Fail()) {
3352       Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
3353 
3354       if (log)
3355         log->Printf("failed to start debugserver process: %s",
3356                     error.AsCString());
3357       return error;
3358     }
3359 
3360     if (m_gdb_comm.IsConnected()) {
3361       // Finish the connection process by doing the handshake without connecting
3362       // (send NULL URL)
3363       ConnectToDebugserver("");
3364     } else {
3365       error.SetErrorString("connection failed");
3366     }
3367   }
3368   return error;
3369 }
3370 
3371 bool ProcessGDBRemote::MonitorDebugserverProcess(
3372     std::weak_ptr<ProcessGDBRemote> process_wp, lldb::pid_t debugserver_pid,
3373     bool exited,    // True if the process did exit
3374     int signo,      // Zero for no signal
3375     int exit_status // Exit value of process if signal is zero
3376     ) {
3377   // "debugserver_pid" argument passed in is the process ID for
3378   // debugserver that we are tracking...
3379   Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
3380   const bool handled = true;
3381 
3382   if (log)
3383     log->Printf("ProcessGDBRemote::%s(process_wp, pid=%" PRIu64
3384                 ", signo=%i (0x%x), exit_status=%i)",
3385                 __FUNCTION__, debugserver_pid, signo, signo, exit_status);
3386 
3387   std::shared_ptr<ProcessGDBRemote> process_sp = process_wp.lock();
3388   if (log)
3389     log->Printf("ProcessGDBRemote::%s(process = %p)", __FUNCTION__,
3390                 static_cast<void *>(process_sp.get()));
3391   if (!process_sp || process_sp->m_debugserver_pid != debugserver_pid)
3392     return handled;
3393 
3394   // Sleep for a half a second to make sure our inferior process has
3395   // time to set its exit status before we set it incorrectly when
3396   // both the debugserver and the inferior process shut down.
3397   usleep(500000);
3398   // If our process hasn't yet exited, debugserver might have died.
3399   // If the process did exit, then we are reaping it.
3400   const StateType state = process_sp->GetState();
3401 
3402   if (state != eStateInvalid && state != eStateUnloaded &&
3403       state != eStateExited && state != eStateDetached) {
3404     char error_str[1024];
3405     if (signo) {
3406       const char *signal_cstr =
3407           process_sp->GetUnixSignals()->GetSignalAsCString(signo);
3408       if (signal_cstr)
3409         ::snprintf(error_str, sizeof(error_str),
3410                    DEBUGSERVER_BASENAME " died with signal %s", signal_cstr);
3411       else
3412         ::snprintf(error_str, sizeof(error_str),
3413                    DEBUGSERVER_BASENAME " died with signal %i", signo);
3414     } else {
3415       ::snprintf(error_str, sizeof(error_str),
3416                  DEBUGSERVER_BASENAME " died with an exit status of 0x%8.8x",
3417                  exit_status);
3418     }
3419 
3420     process_sp->SetExitStatus(-1, error_str);
3421   }
3422   // Debugserver has exited we need to let our ProcessGDBRemote
3423   // know that it no longer has a debugserver instance
3424   process_sp->m_debugserver_pid = LLDB_INVALID_PROCESS_ID;
3425   return handled;
3426 }
3427 
3428 void ProcessGDBRemote::KillDebugserverProcess() {
3429   m_gdb_comm.Disconnect();
3430   if (m_debugserver_pid != LLDB_INVALID_PROCESS_ID) {
3431     Host::Kill(m_debugserver_pid, SIGINT);
3432     m_debugserver_pid = LLDB_INVALID_PROCESS_ID;
3433   }
3434 }
3435 
3436 void ProcessGDBRemote::Initialize() {
3437   static std::once_flag g_once_flag;
3438 
3439   std::call_once(g_once_flag, []() {
3440     PluginManager::RegisterPlugin(GetPluginNameStatic(),
3441                                   GetPluginDescriptionStatic(), CreateInstance,
3442                                   DebuggerInitialize);
3443   });
3444 }
3445 
3446 void ProcessGDBRemote::DebuggerInitialize(Debugger &debugger) {
3447   if (!PluginManager::GetSettingForProcessPlugin(
3448           debugger, PluginProperties::GetSettingName())) {
3449     const bool is_global_setting = true;
3450     PluginManager::CreateSettingForProcessPlugin(
3451         debugger, GetGlobalPluginProperties()->GetValueProperties(),
3452         ConstString("Properties for the gdb-remote process plug-in."),
3453         is_global_setting);
3454   }
3455 }
3456 
3457 bool ProcessGDBRemote::StartAsyncThread() {
3458   Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
3459 
3460   if (log)
3461     log->Printf("ProcessGDBRemote::%s ()", __FUNCTION__);
3462 
3463   std::lock_guard<std::recursive_mutex> guard(m_async_thread_state_mutex);
3464   if (!m_async_thread.IsJoinable()) {
3465     // Create a thread that watches our internal state and controls which
3466     // events make it to clients (into the DCProcess event queue).
3467 
3468     m_async_thread =
3469         ThreadLauncher::LaunchThread("<lldb.process.gdb-remote.async>",
3470                                      ProcessGDBRemote::AsyncThread, this, NULL);
3471   } else if (log)
3472     log->Printf("ProcessGDBRemote::%s () - Called when Async thread was "
3473                 "already running.",
3474                 __FUNCTION__);
3475 
3476   return m_async_thread.IsJoinable();
3477 }
3478 
3479 void ProcessGDBRemote::StopAsyncThread() {
3480   Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
3481 
3482   if (log)
3483     log->Printf("ProcessGDBRemote::%s ()", __FUNCTION__);
3484 
3485   std::lock_guard<std::recursive_mutex> guard(m_async_thread_state_mutex);
3486   if (m_async_thread.IsJoinable()) {
3487     m_async_broadcaster.BroadcastEvent(eBroadcastBitAsyncThreadShouldExit);
3488 
3489     //  This will shut down the async thread.
3490     m_gdb_comm.Disconnect(); // Disconnect from the debug server.
3491 
3492     // Stop the stdio thread
3493     m_async_thread.Join(nullptr);
3494     m_async_thread.Reset();
3495   } else if (log)
3496     log->Printf(
3497         "ProcessGDBRemote::%s () - Called when Async thread was not running.",
3498         __FUNCTION__);
3499 }
3500 
3501 bool ProcessGDBRemote::HandleNotifyPacket(StringExtractorGDBRemote &packet) {
3502   // get the packet at a string
3503   const std::string &pkt = packet.GetStringRef();
3504   // skip %stop:
3505   StringExtractorGDBRemote stop_info(pkt.c_str() + 5);
3506 
3507   // pass as a thread stop info packet
3508   SetLastStopPacket(stop_info);
3509 
3510   // check for more stop reasons
3511   HandleStopReplySequence();
3512 
3513   // if the process is stopped then we need to fake a resume
3514   // so that we can stop properly with the new break. This
3515   // is possible due to SetPrivateState() broadcasting the
3516   // state change as a side effect.
3517   if (GetPrivateState() == lldb::StateType::eStateStopped) {
3518     SetPrivateState(lldb::StateType::eStateRunning);
3519   }
3520 
3521   // since we have some stopped packets we can halt the process
3522   SetPrivateState(lldb::StateType::eStateStopped);
3523 
3524   return true;
3525 }
3526 
3527 thread_result_t ProcessGDBRemote::AsyncThread(void *arg) {
3528   ProcessGDBRemote *process = (ProcessGDBRemote *)arg;
3529 
3530   Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
3531   if (log)
3532     log->Printf("ProcessGDBRemote::%s (arg = %p, pid = %" PRIu64
3533                 ") thread starting...",
3534                 __FUNCTION__, arg, process->GetID());
3535 
3536   EventSP event_sp;
3537   bool done = false;
3538   while (!done) {
3539     if (log)
3540       log->Printf("ProcessGDBRemote::%s (arg = %p, pid = %" PRIu64
3541                   ") listener.WaitForEvent (NULL, event_sp)...",
3542                   __FUNCTION__, arg, process->GetID());
3543     if (process->m_async_listener_sp->GetEvent(event_sp, llvm::None)) {
3544       const uint32_t event_type = event_sp->GetType();
3545       if (event_sp->BroadcasterIs(&process->m_async_broadcaster)) {
3546         if (log)
3547           log->Printf("ProcessGDBRemote::%s (arg = %p, pid = %" PRIu64
3548                       ") Got an event of type: %d...",
3549                       __FUNCTION__, arg, process->GetID(), event_type);
3550 
3551         switch (event_type) {
3552         case eBroadcastBitAsyncContinue: {
3553           const EventDataBytes *continue_packet =
3554               EventDataBytes::GetEventDataFromEvent(event_sp.get());
3555 
3556           if (continue_packet) {
3557             const char *continue_cstr =
3558                 (const char *)continue_packet->GetBytes();
3559             const size_t continue_cstr_len = continue_packet->GetByteSize();
3560             if (log)
3561               log->Printf("ProcessGDBRemote::%s (arg = %p, pid = %" PRIu64
3562                           ") got eBroadcastBitAsyncContinue: %s",
3563                           __FUNCTION__, arg, process->GetID(), continue_cstr);
3564 
3565             if (::strstr(continue_cstr, "vAttach") == NULL)
3566               process->SetPrivateState(eStateRunning);
3567             StringExtractorGDBRemote response;
3568 
3569             // If in Non-Stop-Mode
3570             if (process->GetTarget().GetNonStopModeEnabled()) {
3571               // send the vCont packet
3572               if (!process->GetGDBRemote().SendvContPacket(
3573                       llvm::StringRef(continue_cstr, continue_cstr_len),
3574                       response)) {
3575                 // Something went wrong
3576                 done = true;
3577                 break;
3578               }
3579             }
3580             // If in All-Stop-Mode
3581             else {
3582               StateType stop_state =
3583                   process->GetGDBRemote().SendContinuePacketAndWaitForResponse(
3584                       *process, *process->GetUnixSignals(),
3585                       llvm::StringRef(continue_cstr, continue_cstr_len),
3586                       response);
3587 
3588               // We need to immediately clear the thread ID list so we are sure
3589               // to get a valid list of threads.
3590               // The thread ID list might be contained within the "response", or
3591               // the stop reply packet that
3592               // caused the stop. So clear it now before we give the stop reply
3593               // packet to the process
3594               // using the process->SetLastStopPacket()...
3595               process->ClearThreadIDList();
3596 
3597               switch (stop_state) {
3598               case eStateStopped:
3599               case eStateCrashed:
3600               case eStateSuspended:
3601                 process->SetLastStopPacket(response);
3602                 process->SetPrivateState(stop_state);
3603                 break;
3604 
3605               case eStateExited: {
3606                 process->SetLastStopPacket(response);
3607                 process->ClearThreadIDList();
3608                 response.SetFilePos(1);
3609 
3610                 int exit_status = response.GetHexU8();
3611                 std::string desc_string;
3612                 if (response.GetBytesLeft() > 0 &&
3613                     response.GetChar('-') == ';') {
3614                   llvm::StringRef desc_str;
3615                   llvm::StringRef desc_token;
3616                   while (response.GetNameColonValue(desc_token, desc_str)) {
3617                     if (desc_token != "description")
3618                       continue;
3619                     StringExtractor extractor(desc_str);
3620                     extractor.GetHexByteString(desc_string);
3621                   }
3622                 }
3623                 process->SetExitStatus(exit_status, desc_string.c_str());
3624                 done = true;
3625                 break;
3626               }
3627               case eStateInvalid: {
3628                 // Check to see if we were trying to attach and if we got back
3629                 // the "E87" error code from debugserver -- this indicates that
3630                 // the process is not debuggable.  Return a slightly more
3631                 // helpful
3632                 // error message about why the attach failed.
3633                 if (::strstr(continue_cstr, "vAttach") != NULL &&
3634                     response.GetError() == 0x87) {
3635                   process->SetExitStatus(-1, "cannot attach to process due to "
3636                                              "System Integrity Protection");
3637                 }
3638                 // E01 code from vAttach means that the attach failed
3639                 if (::strstr(continue_cstr, "vAttach") != NULL &&
3640                     response.GetError() == 0x1) {
3641                   process->SetExitStatus(-1, "unable to attach");
3642                 } else {
3643                   process->SetExitStatus(-1, "lost connection");
3644                 }
3645                 break;
3646               }
3647 
3648               default:
3649                 process->SetPrivateState(stop_state);
3650                 break;
3651               } // switch(stop_state)
3652             }   // else // if in All-stop-mode
3653           }     // if (continue_packet)
3654         }       // case eBroadcastBitAysncContinue
3655         break;
3656 
3657         case eBroadcastBitAsyncThreadShouldExit:
3658           if (log)
3659             log->Printf("ProcessGDBRemote::%s (arg = %p, pid = %" PRIu64
3660                         ") got eBroadcastBitAsyncThreadShouldExit...",
3661                         __FUNCTION__, arg, process->GetID());
3662           done = true;
3663           break;
3664 
3665         default:
3666           if (log)
3667             log->Printf("ProcessGDBRemote::%s (arg = %p, pid = %" PRIu64
3668                         ") got unknown event 0x%8.8x",
3669                         __FUNCTION__, arg, process->GetID(), event_type);
3670           done = true;
3671           break;
3672         }
3673       } else if (event_sp->BroadcasterIs(&process->m_gdb_comm)) {
3674         switch (event_type) {
3675         case Communication::eBroadcastBitReadThreadDidExit:
3676           process->SetExitStatus(-1, "lost connection");
3677           done = true;
3678           break;
3679 
3680         case GDBRemoteCommunication::eBroadcastBitGdbReadThreadGotNotify: {
3681           lldb_private::Event *event = event_sp.get();
3682           const EventDataBytes *continue_packet =
3683               EventDataBytes::GetEventDataFromEvent(event);
3684           StringExtractorGDBRemote notify(
3685               (const char *)continue_packet->GetBytes());
3686           // Hand this over to the process to handle
3687           process->HandleNotifyPacket(notify);
3688           break;
3689         }
3690 
3691         default:
3692           if (log)
3693             log->Printf("ProcessGDBRemote::%s (arg = %p, pid = %" PRIu64
3694                         ") got unknown event 0x%8.8x",
3695                         __FUNCTION__, arg, process->GetID(), event_type);
3696           done = true;
3697           break;
3698         }
3699       }
3700     } else {
3701       if (log)
3702         log->Printf("ProcessGDBRemote::%s (arg = %p, pid = %" PRIu64
3703                     ") listener.WaitForEvent (NULL, event_sp) => false",
3704                     __FUNCTION__, arg, process->GetID());
3705       done = true;
3706     }
3707   }
3708 
3709   if (log)
3710     log->Printf("ProcessGDBRemote::%s (arg = %p, pid = %" PRIu64
3711                 ") thread exiting...",
3712                 __FUNCTION__, arg, process->GetID());
3713 
3714   return NULL;
3715 }
3716 
3717 // uint32_t
3718 // ProcessGDBRemote::ListProcessesMatchingName (const char *name, StringList
3719 // &matches, std::vector<lldb::pid_t> &pids)
3720 //{
3721 //    // If we are planning to launch the debugserver remotely, then we need to
3722 //    fire up a debugserver
3723 //    // process and ask it for the list of processes. But if we are local, we
3724 //    can let the Host do it.
3725 //    if (m_local_debugserver)
3726 //    {
3727 //        return Host::ListProcessesMatchingName (name, matches, pids);
3728 //    }
3729 //    else
3730 //    {
3731 //        // FIXME: Implement talking to the remote debugserver.
3732 //        return 0;
3733 //    }
3734 //
3735 //}
3736 //
3737 bool ProcessGDBRemote::NewThreadNotifyBreakpointHit(
3738     void *baton, StoppointCallbackContext *context, lldb::user_id_t break_id,
3739     lldb::user_id_t break_loc_id) {
3740   // I don't think I have to do anything here, just make sure I notice the new
3741   // thread when it starts to
3742   // run so I can stop it if that's what I want to do.
3743   Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_STEP));
3744   if (log)
3745     log->Printf("Hit New Thread Notification breakpoint.");
3746   return false;
3747 }
3748 
3749 bool ProcessGDBRemote::StartNoticingNewThreads() {
3750   Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_STEP));
3751   if (m_thread_create_bp_sp) {
3752     if (log && log->GetVerbose())
3753       log->Printf("Enabled noticing new thread breakpoint.");
3754     m_thread_create_bp_sp->SetEnabled(true);
3755   } else {
3756     PlatformSP platform_sp(GetTarget().GetPlatform());
3757     if (platform_sp) {
3758       m_thread_create_bp_sp =
3759           platform_sp->SetThreadCreationBreakpoint(GetTarget());
3760       if (m_thread_create_bp_sp) {
3761         if (log && log->GetVerbose())
3762           log->Printf(
3763               "Successfully created new thread notification breakpoint %i",
3764               m_thread_create_bp_sp->GetID());
3765         m_thread_create_bp_sp->SetCallback(
3766             ProcessGDBRemote::NewThreadNotifyBreakpointHit, this, true);
3767       } else {
3768         if (log)
3769           log->Printf("Failed to create new thread notification breakpoint.");
3770       }
3771     }
3772   }
3773   return m_thread_create_bp_sp.get() != NULL;
3774 }
3775 
3776 bool ProcessGDBRemote::StopNoticingNewThreads() {
3777   Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_STEP));
3778   if (log && log->GetVerbose())
3779     log->Printf("Disabling new thread notification breakpoint.");
3780 
3781   if (m_thread_create_bp_sp)
3782     m_thread_create_bp_sp->SetEnabled(false);
3783 
3784   return true;
3785 }
3786 
3787 DynamicLoader *ProcessGDBRemote::GetDynamicLoader() {
3788   if (m_dyld_ap.get() == NULL)
3789     m_dyld_ap.reset(DynamicLoader::FindPlugin(this, NULL));
3790   return m_dyld_ap.get();
3791 }
3792 
3793 Error ProcessGDBRemote::SendEventData(const char *data) {
3794   int return_value;
3795   bool was_supported;
3796 
3797   Error error;
3798 
3799   return_value = m_gdb_comm.SendLaunchEventDataPacket(data, &was_supported);
3800   if (return_value != 0) {
3801     if (!was_supported)
3802       error.SetErrorString("Sending events is not supported for this process.");
3803     else
3804       error.SetErrorStringWithFormat("Error sending event data: %d.",
3805                                      return_value);
3806   }
3807   return error;
3808 }
3809 
3810 const DataBufferSP ProcessGDBRemote::GetAuxvData() {
3811   DataBufferSP buf;
3812   if (m_gdb_comm.GetQXferAuxvReadSupported()) {
3813     std::string response_string;
3814     if (m_gdb_comm.SendPacketsAndConcatenateResponses("qXfer:auxv:read::",
3815                                                       response_string) ==
3816         GDBRemoteCommunication::PacketResult::Success)
3817       buf.reset(new DataBufferHeap(response_string.c_str(),
3818                                    response_string.length()));
3819   }
3820   return buf;
3821 }
3822 
3823 StructuredData::ObjectSP
3824 ProcessGDBRemote::GetExtendedInfoForThread(lldb::tid_t tid) {
3825   StructuredData::ObjectSP object_sp;
3826 
3827   if (m_gdb_comm.GetThreadExtendedInfoSupported()) {
3828     StructuredData::ObjectSP args_dict(new StructuredData::Dictionary());
3829     SystemRuntime *runtime = GetSystemRuntime();
3830     if (runtime) {
3831       runtime->AddThreadExtendedInfoPacketHints(args_dict);
3832     }
3833     args_dict->GetAsDictionary()->AddIntegerItem("thread", tid);
3834 
3835     StreamString packet;
3836     packet << "jThreadExtendedInfo:";
3837     args_dict->Dump(packet, false);
3838 
3839     // FIXME the final character of a JSON dictionary, '}', is the escape
3840     // character in gdb-remote binary mode.  lldb currently doesn't escape
3841     // these characters in its packet output -- so we add the quoted version
3842     // of the } character here manually in case we talk to a debugserver which
3843     // un-escapes the characters at packet read time.
3844     packet << (char)(0x7d ^ 0x20);
3845 
3846     StringExtractorGDBRemote response;
3847     response.SetResponseValidatorToJSON();
3848     if (m_gdb_comm.SendPacketAndWaitForResponse(packet.GetString(), response,
3849                                                 false) ==
3850         GDBRemoteCommunication::PacketResult::Success) {
3851       StringExtractorGDBRemote::ResponseType response_type =
3852           response.GetResponseType();
3853       if (response_type == StringExtractorGDBRemote::eResponse) {
3854         if (!response.Empty()) {
3855           object_sp = StructuredData::ParseJSON(response.GetStringRef());
3856         }
3857       }
3858     }
3859   }
3860   return object_sp;
3861 }
3862 
3863 StructuredData::ObjectSP ProcessGDBRemote::GetLoadedDynamicLibrariesInfos(
3864     lldb::addr_t image_list_address, lldb::addr_t image_count) {
3865 
3866   StructuredData::ObjectSP args_dict(new StructuredData::Dictionary());
3867   args_dict->GetAsDictionary()->AddIntegerItem("image_list_address",
3868                                                image_list_address);
3869   args_dict->GetAsDictionary()->AddIntegerItem("image_count", image_count);
3870 
3871   return GetLoadedDynamicLibrariesInfos_sender(args_dict);
3872 }
3873 
3874 StructuredData::ObjectSP ProcessGDBRemote::GetLoadedDynamicLibrariesInfos() {
3875   StructuredData::ObjectSP args_dict(new StructuredData::Dictionary());
3876 
3877   args_dict->GetAsDictionary()->AddBooleanItem("fetch_all_solibs", true);
3878 
3879   return GetLoadedDynamicLibrariesInfos_sender(args_dict);
3880 }
3881 
3882 StructuredData::ObjectSP ProcessGDBRemote::GetLoadedDynamicLibrariesInfos(
3883     const std::vector<lldb::addr_t> &load_addresses) {
3884   StructuredData::ObjectSP args_dict(new StructuredData::Dictionary());
3885   StructuredData::ArraySP addresses(new StructuredData::Array);
3886 
3887   for (auto addr : load_addresses) {
3888     StructuredData::ObjectSP addr_sp(new StructuredData::Integer(addr));
3889     addresses->AddItem(addr_sp);
3890   }
3891 
3892   args_dict->GetAsDictionary()->AddItem("solib_addresses", addresses);
3893 
3894   return GetLoadedDynamicLibrariesInfos_sender(args_dict);
3895 }
3896 
3897 StructuredData::ObjectSP
3898 ProcessGDBRemote::GetLoadedDynamicLibrariesInfos_sender(
3899     StructuredData::ObjectSP args_dict) {
3900   StructuredData::ObjectSP object_sp;
3901 
3902   if (m_gdb_comm.GetLoadedDynamicLibrariesInfosSupported()) {
3903     // Scope for the scoped timeout object
3904     GDBRemoteCommunication::ScopedTimeout timeout(m_gdb_comm,
3905                                                   std::chrono::seconds(10));
3906 
3907     StreamString packet;
3908     packet << "jGetLoadedDynamicLibrariesInfos:";
3909     args_dict->Dump(packet, false);
3910 
3911     // FIXME the final character of a JSON dictionary, '}', is the escape
3912     // character in gdb-remote binary mode.  lldb currently doesn't escape
3913     // these characters in its packet output -- so we add the quoted version
3914     // of the } character here manually in case we talk to a debugserver which
3915     // un-escapes the characters at packet read time.
3916     packet << (char)(0x7d ^ 0x20);
3917 
3918     StringExtractorGDBRemote response;
3919     response.SetResponseValidatorToJSON();
3920     if (m_gdb_comm.SendPacketAndWaitForResponse(packet.GetString(), response,
3921                                                 false) ==
3922         GDBRemoteCommunication::PacketResult::Success) {
3923       StringExtractorGDBRemote::ResponseType response_type =
3924           response.GetResponseType();
3925       if (response_type == StringExtractorGDBRemote::eResponse) {
3926         if (!response.Empty()) {
3927           object_sp = StructuredData::ParseJSON(response.GetStringRef());
3928         }
3929       }
3930     }
3931   }
3932   return object_sp;
3933 }
3934 
3935 StructuredData::ObjectSP ProcessGDBRemote::GetSharedCacheInfo() {
3936   StructuredData::ObjectSP object_sp;
3937   StructuredData::ObjectSP args_dict(new StructuredData::Dictionary());
3938 
3939   if (m_gdb_comm.GetSharedCacheInfoSupported()) {
3940     StreamString packet;
3941     packet << "jGetSharedCacheInfo:";
3942     args_dict->Dump(packet, false);
3943 
3944     // FIXME the final character of a JSON dictionary, '}', is the escape
3945     // character in gdb-remote binary mode.  lldb currently doesn't escape
3946     // these characters in its packet output -- so we add the quoted version
3947     // of the } character here manually in case we talk to a debugserver which
3948     // un-escapes the characters at packet read time.
3949     packet << (char)(0x7d ^ 0x20);
3950 
3951     StringExtractorGDBRemote response;
3952     response.SetResponseValidatorToJSON();
3953     if (m_gdb_comm.SendPacketAndWaitForResponse(packet.GetString(), response,
3954                                                 false) ==
3955         GDBRemoteCommunication::PacketResult::Success) {
3956       StringExtractorGDBRemote::ResponseType response_type =
3957           response.GetResponseType();
3958       if (response_type == StringExtractorGDBRemote::eResponse) {
3959         if (!response.Empty()) {
3960           object_sp = StructuredData::ParseJSON(response.GetStringRef());
3961         }
3962       }
3963     }
3964   }
3965   return object_sp;
3966 }
3967 
3968 Error ProcessGDBRemote::ConfigureStructuredData(
3969     const ConstString &type_name, const StructuredData::ObjectSP &config_sp) {
3970   return m_gdb_comm.ConfigureRemoteStructuredData(type_name, config_sp);
3971 }
3972 
3973 // Establish the largest memory read/write payloads we should use.
3974 // If the remote stub has a max packet size, stay under that size.
3975 //
3976 // If the remote stub's max packet size is crazy large, use a
3977 // reasonable largeish default.
3978 //
3979 // If the remote stub doesn't advertise a max packet size, use a
3980 // conservative default.
3981 
3982 void ProcessGDBRemote::GetMaxMemorySize() {
3983   const uint64_t reasonable_largeish_default = 128 * 1024;
3984   const uint64_t conservative_default = 512;
3985 
3986   if (m_max_memory_size == 0) {
3987     uint64_t stub_max_size = m_gdb_comm.GetRemoteMaxPacketSize();
3988     if (stub_max_size != UINT64_MAX && stub_max_size != 0) {
3989       // Save the stub's claimed maximum packet size
3990       m_remote_stub_max_memory_size = stub_max_size;
3991 
3992       // Even if the stub says it can support ginormous packets,
3993       // don't exceed our reasonable largeish default packet size.
3994       if (stub_max_size > reasonable_largeish_default) {
3995         stub_max_size = reasonable_largeish_default;
3996       }
3997 
3998       // Memory packet have other overheads too like Maddr,size:#NN
3999       // Instead of calculating the bytes taken by size and addr every
4000       // time, we take a maximum guess here.
4001       if (stub_max_size > 70)
4002         stub_max_size -= 32 + 32 + 6;
4003       else {
4004         // In unlikely scenario that max packet size is less then 70, we will
4005         // hope that data being written is small enough to fit.
4006         Log *log(ProcessGDBRemoteLog::GetLogIfAnyCategoryIsSet(
4007             GDBR_LOG_COMM | GDBR_LOG_MEMORY));
4008         if (log)
4009           log->Warning("Packet size is too small. "
4010                        "LLDB may face problems while writing memory");
4011       }
4012 
4013       m_max_memory_size = stub_max_size;
4014     } else {
4015       m_max_memory_size = conservative_default;
4016     }
4017   }
4018 }
4019 
4020 void ProcessGDBRemote::SetUserSpecifiedMaxMemoryTransferSize(
4021     uint64_t user_specified_max) {
4022   if (user_specified_max != 0) {
4023     GetMaxMemorySize();
4024 
4025     if (m_remote_stub_max_memory_size != 0) {
4026       if (m_remote_stub_max_memory_size < user_specified_max) {
4027         m_max_memory_size = m_remote_stub_max_memory_size; // user specified a
4028                                                            // packet size too
4029                                                            // big, go as big
4030         // as the remote stub says we can go.
4031       } else {
4032         m_max_memory_size = user_specified_max; // user's packet size is good
4033       }
4034     } else {
4035       m_max_memory_size =
4036           user_specified_max; // user's packet size is probably fine
4037     }
4038   }
4039 }
4040 
4041 bool ProcessGDBRemote::GetModuleSpec(const FileSpec &module_file_spec,
4042                                      const ArchSpec &arch,
4043                                      ModuleSpec &module_spec) {
4044   Log *log = GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PLATFORM);
4045 
4046   const ModuleCacheKey key(module_file_spec.GetPath(),
4047                            arch.GetTriple().getTriple());
4048   auto cached = m_cached_module_specs.find(key);
4049   if (cached != m_cached_module_specs.end()) {
4050     module_spec = cached->second;
4051     return bool(module_spec);
4052   }
4053 
4054   if (!m_gdb_comm.GetModuleInfo(module_file_spec, arch, module_spec)) {
4055     if (log)
4056       log->Printf("ProcessGDBRemote::%s - failed to get module info for %s:%s",
4057                   __FUNCTION__, module_file_spec.GetPath().c_str(),
4058                   arch.GetTriple().getTriple().c_str());
4059     return false;
4060   }
4061 
4062   if (log) {
4063     StreamString stream;
4064     module_spec.Dump(stream);
4065     log->Printf("ProcessGDBRemote::%s - got module info for (%s:%s) : %s",
4066                 __FUNCTION__, module_file_spec.GetPath().c_str(),
4067                 arch.GetTriple().getTriple().c_str(), stream.GetData());
4068   }
4069 
4070   m_cached_module_specs[key] = module_spec;
4071   return true;
4072 }
4073 
4074 void ProcessGDBRemote::PrefetchModuleSpecs(
4075     llvm::ArrayRef<FileSpec> module_file_specs, const llvm::Triple &triple) {
4076   auto module_specs = m_gdb_comm.GetModulesInfo(module_file_specs, triple);
4077   if (module_specs) {
4078     for (const FileSpec &spec : module_file_specs)
4079       m_cached_module_specs[ModuleCacheKey(spec.GetPath(),
4080                                            triple.getTriple())] = ModuleSpec();
4081     for (const ModuleSpec &spec : *module_specs)
4082       m_cached_module_specs[ModuleCacheKey(spec.GetFileSpec().GetPath(),
4083                                            triple.getTriple())] = spec;
4084   }
4085 }
4086 
4087 bool ProcessGDBRemote::GetHostOSVersion(uint32_t &major, uint32_t &minor,
4088                                         uint32_t &update) {
4089   if (m_gdb_comm.GetOSVersion(major, minor, update))
4090     return true;
4091   // We failed to get the host OS version, defer to the base
4092   // implementation to correctly invalidate the arguments.
4093   return Process::GetHostOSVersion(major, minor, update);
4094 }
4095 
4096 namespace {
4097 
4098 typedef std::vector<std::string> stringVec;
4099 
4100 typedef std::vector<struct GdbServerRegisterInfo> GDBServerRegisterVec;
4101 struct RegisterSetInfo {
4102   ConstString name;
4103 };
4104 
4105 typedef std::map<uint32_t, RegisterSetInfo> RegisterSetMap;
4106 
4107 struct GdbServerTargetInfo {
4108   std::string arch;
4109   std::string osabi;
4110   stringVec includes;
4111   RegisterSetMap reg_set_map;
4112   XMLNode feature_node;
4113 };
4114 
4115 bool ParseRegisters(XMLNode feature_node, GdbServerTargetInfo &target_info,
4116                     GDBRemoteDynamicRegisterInfo &dyn_reg_info, ABISP abi_sp,
4117                     uint32_t &cur_reg_num, uint32_t &reg_offset) {
4118   if (!feature_node)
4119     return false;
4120 
4121   feature_node.ForEachChildElementWithName(
4122       "reg", [&target_info, &dyn_reg_info, &cur_reg_num, &reg_offset,
4123               &abi_sp](const XMLNode &reg_node) -> bool {
4124         std::string gdb_group;
4125         std::string gdb_type;
4126         ConstString reg_name;
4127         ConstString alt_name;
4128         ConstString set_name;
4129         std::vector<uint32_t> value_regs;
4130         std::vector<uint32_t> invalidate_regs;
4131         std::vector<uint8_t> dwarf_opcode_bytes;
4132         bool encoding_set = false;
4133         bool format_set = false;
4134         RegisterInfo reg_info = {
4135             NULL,          // Name
4136             NULL,          // Alt name
4137             0,             // byte size
4138             reg_offset,    // offset
4139             eEncodingUint, // encoding
4140             eFormatHex,    // format
4141             {
4142                 LLDB_INVALID_REGNUM, // eh_frame reg num
4143                 LLDB_INVALID_REGNUM, // DWARF reg num
4144                 LLDB_INVALID_REGNUM, // generic reg num
4145                 cur_reg_num,         // process plugin reg num
4146                 cur_reg_num          // native register number
4147             },
4148             NULL,
4149             NULL,
4150             NULL, // Dwarf Expression opcode bytes pointer
4151             0     // Dwarf Expression opcode bytes length
4152         };
4153 
4154         reg_node.ForEachAttribute([&target_info, &gdb_group, &gdb_type,
4155                                    &reg_name, &alt_name, &set_name, &value_regs,
4156                                    &invalidate_regs, &encoding_set, &format_set,
4157                                    &reg_info, &cur_reg_num, &reg_offset,
4158                                    &dwarf_opcode_bytes](
4159                                       const llvm::StringRef &name,
4160                                       const llvm::StringRef &value) -> bool {
4161           if (name == "name") {
4162             reg_name.SetString(value);
4163           } else if (name == "bitsize") {
4164             reg_info.byte_size =
4165                 StringConvert::ToUInt32(value.data(), 0, 0) / CHAR_BIT;
4166           } else if (name == "type") {
4167             gdb_type = value.str();
4168           } else if (name == "group") {
4169             gdb_group = value.str();
4170           } else if (name == "regnum") {
4171             const uint32_t regnum =
4172                 StringConvert::ToUInt32(value.data(), LLDB_INVALID_REGNUM, 0);
4173             if (regnum != LLDB_INVALID_REGNUM) {
4174               reg_info.kinds[eRegisterKindProcessPlugin] = regnum;
4175             }
4176           } else if (name == "offset") {
4177             reg_offset = StringConvert::ToUInt32(value.data(), UINT32_MAX, 0);
4178           } else if (name == "altname") {
4179             alt_name.SetString(value);
4180           } else if (name == "encoding") {
4181             encoding_set = true;
4182             reg_info.encoding = Args::StringToEncoding(value, eEncodingUint);
4183           } else if (name == "format") {
4184             format_set = true;
4185             Format format = eFormatInvalid;
4186             if (Args::StringToFormat(value.data(), format, NULL).Success())
4187               reg_info.format = format;
4188             else if (value == "vector-sint8")
4189               reg_info.format = eFormatVectorOfSInt8;
4190             else if (value == "vector-uint8")
4191               reg_info.format = eFormatVectorOfUInt8;
4192             else if (value == "vector-sint16")
4193               reg_info.format = eFormatVectorOfSInt16;
4194             else if (value == "vector-uint16")
4195               reg_info.format = eFormatVectorOfUInt16;
4196             else if (value == "vector-sint32")
4197               reg_info.format = eFormatVectorOfSInt32;
4198             else if (value == "vector-uint32")
4199               reg_info.format = eFormatVectorOfUInt32;
4200             else if (value == "vector-float32")
4201               reg_info.format = eFormatVectorOfFloat32;
4202             else if (value == "vector-uint64")
4203               reg_info.format = eFormatVectorOfUInt64;
4204             else if (value == "vector-uint128")
4205               reg_info.format = eFormatVectorOfUInt128;
4206           } else if (name == "group_id") {
4207             const uint32_t set_id =
4208                 StringConvert::ToUInt32(value.data(), UINT32_MAX, 0);
4209             RegisterSetMap::const_iterator pos =
4210                 target_info.reg_set_map.find(set_id);
4211             if (pos != target_info.reg_set_map.end())
4212               set_name = pos->second.name;
4213           } else if (name == "gcc_regnum" || name == "ehframe_regnum") {
4214             reg_info.kinds[eRegisterKindEHFrame] =
4215                 StringConvert::ToUInt32(value.data(), LLDB_INVALID_REGNUM, 0);
4216           } else if (name == "dwarf_regnum") {
4217             reg_info.kinds[eRegisterKindDWARF] =
4218                 StringConvert::ToUInt32(value.data(), LLDB_INVALID_REGNUM, 0);
4219           } else if (name == "generic") {
4220             reg_info.kinds[eRegisterKindGeneric] =
4221                 Args::StringToGenericRegister(value);
4222           } else if (name == "value_regnums") {
4223             SplitCommaSeparatedRegisterNumberString(value, value_regs, 0);
4224           } else if (name == "invalidate_regnums") {
4225             SplitCommaSeparatedRegisterNumberString(value, invalidate_regs, 0);
4226           } else if (name == "dynamic_size_dwarf_expr_bytes") {
4227             StringExtractor opcode_extractor;
4228             std::string opcode_string = value.str();
4229             size_t dwarf_opcode_len = opcode_string.length() / 2;
4230             assert(dwarf_opcode_len > 0);
4231 
4232             dwarf_opcode_bytes.resize(dwarf_opcode_len);
4233             reg_info.dynamic_size_dwarf_len = dwarf_opcode_len;
4234             opcode_extractor.GetStringRef().swap(opcode_string);
4235             uint32_t ret_val =
4236                 opcode_extractor.GetHexBytesAvail(dwarf_opcode_bytes);
4237             assert(dwarf_opcode_len == ret_val);
4238             UNUSED_IF_ASSERT_DISABLED(ret_val);
4239             reg_info.dynamic_size_dwarf_expr_bytes = dwarf_opcode_bytes.data();
4240           } else {
4241             printf("unhandled attribute %s = %s\n", name.data(), value.data());
4242           }
4243           return true; // Keep iterating through all attributes
4244         });
4245 
4246         if (!gdb_type.empty() && !(encoding_set || format_set)) {
4247           if (gdb_type.find("int") == 0) {
4248             reg_info.format = eFormatHex;
4249             reg_info.encoding = eEncodingUint;
4250           } else if (gdb_type == "data_ptr" || gdb_type == "code_ptr") {
4251             reg_info.format = eFormatAddressInfo;
4252             reg_info.encoding = eEncodingUint;
4253           } else if (gdb_type == "i387_ext" || gdb_type == "float") {
4254             reg_info.format = eFormatFloat;
4255             reg_info.encoding = eEncodingIEEE754;
4256           }
4257         }
4258 
4259         // Only update the register set name if we didn't get a "reg_set"
4260         // attribute.
4261         // "set_name" will be empty if we didn't have a "reg_set" attribute.
4262         if (!set_name && !gdb_group.empty())
4263           set_name.SetCString(gdb_group.c_str());
4264 
4265         reg_info.byte_offset = reg_offset;
4266         assert(reg_info.byte_size != 0);
4267         reg_offset += reg_info.byte_size;
4268         if (!value_regs.empty()) {
4269           value_regs.push_back(LLDB_INVALID_REGNUM);
4270           reg_info.value_regs = value_regs.data();
4271         }
4272         if (!invalidate_regs.empty()) {
4273           invalidate_regs.push_back(LLDB_INVALID_REGNUM);
4274           reg_info.invalidate_regs = invalidate_regs.data();
4275         }
4276 
4277         ++cur_reg_num;
4278         AugmentRegisterInfoViaABI(reg_info, reg_name, abi_sp);
4279         dyn_reg_info.AddRegister(reg_info, reg_name, alt_name, set_name);
4280 
4281         return true; // Keep iterating through all "reg" elements
4282       });
4283   return true;
4284 }
4285 
4286 } // namespace {}
4287 
4288 // query the target of gdb-remote for extended target information
4289 // return:  'true'  on success
4290 //          'false' on failure
4291 bool ProcessGDBRemote::GetGDBServerRegisterInfo(ArchSpec &arch_to_use) {
4292   // Make sure LLDB has an XML parser it can use first
4293   if (!XMLDocument::XMLEnabled())
4294     return false;
4295 
4296   // redirect libxml2's error handler since the default prints to stdout
4297 
4298   GDBRemoteCommunicationClient &comm = m_gdb_comm;
4299 
4300   // check that we have extended feature read support
4301   if (!comm.GetQXferFeaturesReadSupported())
4302     return false;
4303 
4304   // request the target xml file
4305   std::string raw;
4306   lldb_private::Error lldberr;
4307   if (!comm.ReadExtFeature(ConstString("features"), ConstString("target.xml"),
4308                            raw, lldberr)) {
4309     return false;
4310   }
4311 
4312   XMLDocument xml_document;
4313 
4314   if (xml_document.ParseMemory(raw.c_str(), raw.size(), "target.xml")) {
4315     GdbServerTargetInfo target_info;
4316 
4317     XMLNode target_node = xml_document.GetRootElement("target");
4318     if (target_node) {
4319       XMLNode feature_node;
4320       target_node.ForEachChildElement([&target_info, this, &feature_node](
4321                                           const XMLNode &node) -> bool {
4322         llvm::StringRef name = node.GetName();
4323         if (name == "architecture") {
4324           node.GetElementText(target_info.arch);
4325         } else if (name == "osabi") {
4326           node.GetElementText(target_info.osabi);
4327         } else if (name == "xi:include" || name == "include") {
4328           llvm::StringRef href = node.GetAttributeValue("href");
4329           if (!href.empty())
4330             target_info.includes.push_back(href.str());
4331         } else if (name == "feature") {
4332           feature_node = node;
4333         } else if (name == "groups") {
4334           node.ForEachChildElementWithName(
4335               "group", [&target_info](const XMLNode &node) -> bool {
4336                 uint32_t set_id = UINT32_MAX;
4337                 RegisterSetInfo set_info;
4338 
4339                 node.ForEachAttribute(
4340                     [&set_id, &set_info](const llvm::StringRef &name,
4341                                          const llvm::StringRef &value) -> bool {
4342                       if (name == "id")
4343                         set_id = StringConvert::ToUInt32(value.data(),
4344                                                          UINT32_MAX, 0);
4345                       if (name == "name")
4346                         set_info.name = ConstString(value);
4347                       return true; // Keep iterating through all attributes
4348                     });
4349 
4350                 if (set_id != UINT32_MAX)
4351                   target_info.reg_set_map[set_id] = set_info;
4352                 return true; // Keep iterating through all "group" elements
4353               });
4354         }
4355         return true; // Keep iterating through all children of the target_node
4356       });
4357 
4358       // Initialize these outside of ParseRegisters, since they should not be
4359       // reset inside each include feature
4360       uint32_t cur_reg_num = 0;
4361       uint32_t reg_offset = 0;
4362 
4363       // Don't use Process::GetABI, this code gets called from DidAttach, and in
4364       // that context we haven't
4365       // set the Target's architecture yet, so the ABI is also potentially
4366       // incorrect.
4367       ABISP abi_to_use_sp = ABI::FindPlugin(arch_to_use);
4368       if (feature_node) {
4369         ParseRegisters(feature_node, target_info, this->m_register_info,
4370                        abi_to_use_sp, cur_reg_num, reg_offset);
4371       }
4372 
4373       for (const auto &include : target_info.includes) {
4374         // request register file
4375         std::string xml_data;
4376         if (!comm.ReadExtFeature(ConstString("features"), ConstString(include),
4377                                  xml_data, lldberr))
4378           continue;
4379 
4380         XMLDocument include_xml_document;
4381         include_xml_document.ParseMemory(xml_data.data(), xml_data.size(),
4382                                          include.c_str());
4383         XMLNode include_feature_node =
4384             include_xml_document.GetRootElement("feature");
4385         if (include_feature_node) {
4386           ParseRegisters(include_feature_node, target_info,
4387                          this->m_register_info, abi_to_use_sp, cur_reg_num,
4388                          reg_offset);
4389         }
4390       }
4391       this->m_register_info.Finalize(arch_to_use);
4392     }
4393   }
4394 
4395   return m_register_info.GetNumRegisters() > 0;
4396 }
4397 
4398 Error ProcessGDBRemote::GetLoadedModuleList(LoadedModuleInfoList &list) {
4399   // Make sure LLDB has an XML parser it can use first
4400   if (!XMLDocument::XMLEnabled())
4401     return Error(0, ErrorType::eErrorTypeGeneric);
4402 
4403   Log *log = GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS);
4404   if (log)
4405     log->Printf("ProcessGDBRemote::%s", __FUNCTION__);
4406 
4407   GDBRemoteCommunicationClient &comm = m_gdb_comm;
4408 
4409   // check that we have extended feature read support
4410   if (comm.GetQXferLibrariesSVR4ReadSupported()) {
4411     list.clear();
4412 
4413     // request the loaded library list
4414     std::string raw;
4415     lldb_private::Error lldberr;
4416 
4417     if (!comm.ReadExtFeature(ConstString("libraries-svr4"), ConstString(""),
4418                              raw, lldberr))
4419       return Error(0, ErrorType::eErrorTypeGeneric);
4420 
4421     // parse the xml file in memory
4422     if (log)
4423       log->Printf("parsing: %s", raw.c_str());
4424     XMLDocument doc;
4425 
4426     if (!doc.ParseMemory(raw.c_str(), raw.size(), "noname.xml"))
4427       return Error(0, ErrorType::eErrorTypeGeneric);
4428 
4429     XMLNode root_element = doc.GetRootElement("library-list-svr4");
4430     if (!root_element)
4431       return Error();
4432 
4433     // main link map structure
4434     llvm::StringRef main_lm = root_element.GetAttributeValue("main-lm");
4435     if (!main_lm.empty()) {
4436       list.m_link_map =
4437           StringConvert::ToUInt64(main_lm.data(), LLDB_INVALID_ADDRESS, 0);
4438     }
4439 
4440     root_element.ForEachChildElementWithName(
4441         "library", [log, &list](const XMLNode &library) -> bool {
4442 
4443           LoadedModuleInfoList::LoadedModuleInfo module;
4444 
4445           library.ForEachAttribute(
4446               [log, &module](const llvm::StringRef &name,
4447                              const llvm::StringRef &value) -> bool {
4448 
4449                 if (name == "name")
4450                   module.set_name(value.str());
4451                 else if (name == "lm") {
4452                   // the address of the link_map struct.
4453                   module.set_link_map(StringConvert::ToUInt64(
4454                       value.data(), LLDB_INVALID_ADDRESS, 0));
4455                 } else if (name == "l_addr") {
4456                   // the displacement as read from the field 'l_addr' of the
4457                   // link_map struct.
4458                   module.set_base(StringConvert::ToUInt64(
4459                       value.data(), LLDB_INVALID_ADDRESS, 0));
4460                   // base address is always a displacement, not an absolute
4461                   // value.
4462                   module.set_base_is_offset(true);
4463                 } else if (name == "l_ld") {
4464                   // the memory address of the libraries PT_DYAMIC section.
4465                   module.set_dynamic(StringConvert::ToUInt64(
4466                       value.data(), LLDB_INVALID_ADDRESS, 0));
4467                 }
4468 
4469                 return true; // Keep iterating over all properties of "library"
4470               });
4471 
4472           if (log) {
4473             std::string name;
4474             lldb::addr_t lm = 0, base = 0, ld = 0;
4475             bool base_is_offset;
4476 
4477             module.get_name(name);
4478             module.get_link_map(lm);
4479             module.get_base(base);
4480             module.get_base_is_offset(base_is_offset);
4481             module.get_dynamic(ld);
4482 
4483             log->Printf("found (link_map:0x%08" PRIx64 ", base:0x%08" PRIx64
4484                         "[%s], ld:0x%08" PRIx64 ", name:'%s')",
4485                         lm, base, (base_is_offset ? "offset" : "absolute"), ld,
4486                         name.c_str());
4487           }
4488 
4489           list.add(module);
4490           return true; // Keep iterating over all "library" elements in the root
4491                        // node
4492         });
4493 
4494     if (log)
4495       log->Printf("found %" PRId32 " modules in total",
4496                   (int)list.m_list.size());
4497   } else if (comm.GetQXferLibrariesReadSupported()) {
4498     list.clear();
4499 
4500     // request the loaded library list
4501     std::string raw;
4502     lldb_private::Error lldberr;
4503 
4504     if (!comm.ReadExtFeature(ConstString("libraries"), ConstString(""), raw,
4505                              lldberr))
4506       return Error(0, ErrorType::eErrorTypeGeneric);
4507 
4508     if (log)
4509       log->Printf("parsing: %s", raw.c_str());
4510     XMLDocument doc;
4511 
4512     if (!doc.ParseMemory(raw.c_str(), raw.size(), "noname.xml"))
4513       return Error(0, ErrorType::eErrorTypeGeneric);
4514 
4515     XMLNode root_element = doc.GetRootElement("library-list");
4516     if (!root_element)
4517       return Error();
4518 
4519     root_element.ForEachChildElementWithName(
4520         "library", [log, &list](const XMLNode &library) -> bool {
4521           LoadedModuleInfoList::LoadedModuleInfo module;
4522 
4523           llvm::StringRef name = library.GetAttributeValue("name");
4524           module.set_name(name.str());
4525 
4526           // The base address of a given library will be the address of its
4527           // first section. Most remotes send only one section for Windows
4528           // targets for example.
4529           const XMLNode &section =
4530               library.FindFirstChildElementWithName("section");
4531           llvm::StringRef address = section.GetAttributeValue("address");
4532           module.set_base(
4533               StringConvert::ToUInt64(address.data(), LLDB_INVALID_ADDRESS, 0));
4534           // These addresses are absolute values.
4535           module.set_base_is_offset(false);
4536 
4537           if (log) {
4538             std::string name;
4539             lldb::addr_t base = 0;
4540             bool base_is_offset;
4541             module.get_name(name);
4542             module.get_base(base);
4543             module.get_base_is_offset(base_is_offset);
4544 
4545             log->Printf("found (base:0x%08" PRIx64 "[%s], name:'%s')", base,
4546                         (base_is_offset ? "offset" : "absolute"), name.c_str());
4547           }
4548 
4549           list.add(module);
4550           return true; // Keep iterating over all "library" elements in the root
4551                        // node
4552         });
4553 
4554     if (log)
4555       log->Printf("found %" PRId32 " modules in total",
4556                   (int)list.m_list.size());
4557   } else {
4558     return Error(0, ErrorType::eErrorTypeGeneric);
4559   }
4560 
4561   return Error();
4562 }
4563 
4564 lldb::ModuleSP ProcessGDBRemote::LoadModuleAtAddress(const FileSpec &file,
4565                                                      lldb::addr_t link_map,
4566                                                      lldb::addr_t base_addr,
4567                                                      bool value_is_offset) {
4568   DynamicLoader *loader = GetDynamicLoader();
4569   if (!loader)
4570     return nullptr;
4571 
4572   return loader->LoadModuleAtAddress(file, link_map, base_addr,
4573                                      value_is_offset);
4574 }
4575 
4576 size_t ProcessGDBRemote::LoadModules(LoadedModuleInfoList &module_list) {
4577   using lldb_private::process_gdb_remote::ProcessGDBRemote;
4578 
4579   // request a list of loaded libraries from GDBServer
4580   if (GetLoadedModuleList(module_list).Fail())
4581     return 0;
4582 
4583   // get a list of all the modules
4584   ModuleList new_modules;
4585 
4586   for (LoadedModuleInfoList::LoadedModuleInfo &modInfo : module_list.m_list) {
4587     std::string mod_name;
4588     lldb::addr_t mod_base;
4589     lldb::addr_t link_map;
4590     bool mod_base_is_offset;
4591 
4592     bool valid = true;
4593     valid &= modInfo.get_name(mod_name);
4594     valid &= modInfo.get_base(mod_base);
4595     valid &= modInfo.get_base_is_offset(mod_base_is_offset);
4596     if (!valid)
4597       continue;
4598 
4599     if (!modInfo.get_link_map(link_map))
4600       link_map = LLDB_INVALID_ADDRESS;
4601 
4602     FileSpec file(mod_name, true);
4603     lldb::ModuleSP module_sp =
4604         LoadModuleAtAddress(file, link_map, mod_base, mod_base_is_offset);
4605 
4606     if (module_sp.get())
4607       new_modules.Append(module_sp);
4608   }
4609 
4610   if (new_modules.GetSize() > 0) {
4611     ModuleList removed_modules;
4612     Target &target = GetTarget();
4613     ModuleList &loaded_modules = m_process->GetTarget().GetImages();
4614 
4615     for (size_t i = 0; i < loaded_modules.GetSize(); ++i) {
4616       const lldb::ModuleSP loaded_module = loaded_modules.GetModuleAtIndex(i);
4617 
4618       bool found = false;
4619       for (size_t j = 0; j < new_modules.GetSize(); ++j) {
4620         if (new_modules.GetModuleAtIndex(j).get() == loaded_module.get())
4621           found = true;
4622       }
4623 
4624       // The main executable will never be included in libraries-svr4, don't
4625       // remove it
4626       if (!found &&
4627           loaded_module.get() != target.GetExecutableModulePointer()) {
4628         removed_modules.Append(loaded_module);
4629       }
4630     }
4631 
4632     loaded_modules.Remove(removed_modules);
4633     m_process->GetTarget().ModulesDidUnload(removed_modules, false);
4634 
4635     new_modules.ForEach([&target](const lldb::ModuleSP module_sp) -> bool {
4636       lldb_private::ObjectFile *obj = module_sp->GetObjectFile();
4637       if (!obj)
4638         return true;
4639 
4640       if (obj->GetType() != ObjectFile::Type::eTypeExecutable)
4641         return true;
4642 
4643       lldb::ModuleSP module_copy_sp = module_sp;
4644       target.SetExecutableModule(module_copy_sp, false);
4645       return false;
4646     });
4647 
4648     loaded_modules.AppendIfNeeded(new_modules);
4649     m_process->GetTarget().ModulesDidLoad(new_modules);
4650   }
4651 
4652   return new_modules.GetSize();
4653 }
4654 
4655 size_t ProcessGDBRemote::LoadModules() {
4656   LoadedModuleInfoList module_list;
4657   return LoadModules(module_list);
4658 }
4659 
4660 Error ProcessGDBRemote::GetFileLoadAddress(const FileSpec &file,
4661                                            bool &is_loaded,
4662                                            lldb::addr_t &load_addr) {
4663   is_loaded = false;
4664   load_addr = LLDB_INVALID_ADDRESS;
4665 
4666   std::string file_path = file.GetPath(false);
4667   if (file_path.empty())
4668     return Error("Empty file name specified");
4669 
4670   StreamString packet;
4671   packet.PutCString("qFileLoadAddress:");
4672   packet.PutCStringAsRawHex8(file_path.c_str());
4673 
4674   StringExtractorGDBRemote response;
4675   if (m_gdb_comm.SendPacketAndWaitForResponse(packet.GetString(), response,
4676                                               false) !=
4677       GDBRemoteCommunication::PacketResult::Success)
4678     return Error("Sending qFileLoadAddress packet failed");
4679 
4680   if (response.IsErrorResponse()) {
4681     if (response.GetError() == 1) {
4682       // The file is not loaded into the inferior
4683       is_loaded = false;
4684       load_addr = LLDB_INVALID_ADDRESS;
4685       return Error();
4686     }
4687 
4688     return Error(
4689         "Fetching file load address from remote server returned an error");
4690   }
4691 
4692   if (response.IsNormalResponse()) {
4693     is_loaded = true;
4694     load_addr = response.GetHexMaxU64(false, LLDB_INVALID_ADDRESS);
4695     return Error();
4696   }
4697 
4698   return Error("Unknown error happened during sending the load address packet");
4699 }
4700 
4701 void ProcessGDBRemote::ModulesDidLoad(ModuleList &module_list) {
4702   // We must call the lldb_private::Process::ModulesDidLoad () first before we
4703   // do anything
4704   Process::ModulesDidLoad(module_list);
4705 
4706   // After loading shared libraries, we can ask our remote GDB server if
4707   // it needs any symbols.
4708   m_gdb_comm.ServeSymbolLookups(this);
4709 }
4710 
4711 void ProcessGDBRemote::HandleAsyncStdout(llvm::StringRef out) {
4712   AppendSTDOUT(out.data(), out.size());
4713 }
4714 
4715 static const char *end_delimiter = "--end--;";
4716 static const int end_delimiter_len = 8;
4717 
4718 void ProcessGDBRemote::HandleAsyncMisc(llvm::StringRef data) {
4719   std::string input = data.str(); // '1' to move beyond 'A'
4720   if (m_partial_profile_data.length() > 0) {
4721     m_partial_profile_data.append(input);
4722     input = m_partial_profile_data;
4723     m_partial_profile_data.clear();
4724   }
4725 
4726   size_t found, pos = 0, len = input.length();
4727   while ((found = input.find(end_delimiter, pos)) != std::string::npos) {
4728     StringExtractorGDBRemote profileDataExtractor(
4729         input.substr(pos, found).c_str());
4730     std::string profile_data =
4731         HarmonizeThreadIdsForProfileData(profileDataExtractor);
4732     BroadcastAsyncProfileData(profile_data);
4733 
4734     pos = found + end_delimiter_len;
4735   }
4736 
4737   if (pos < len) {
4738     // Last incomplete chunk.
4739     m_partial_profile_data = input.substr(pos);
4740   }
4741 }
4742 
4743 std::string ProcessGDBRemote::HarmonizeThreadIdsForProfileData(
4744     StringExtractorGDBRemote &profileDataExtractor) {
4745   std::map<uint64_t, uint32_t> new_thread_id_to_used_usec_map;
4746   std::string output;
4747   llvm::raw_string_ostream output_stream(output);
4748   llvm::StringRef name, value;
4749 
4750   // Going to assuming thread_used_usec comes first, else bail out.
4751   while (profileDataExtractor.GetNameColonValue(name, value)) {
4752     if (name.compare("thread_used_id") == 0) {
4753       StringExtractor threadIDHexExtractor(value);
4754       uint64_t thread_id = threadIDHexExtractor.GetHexMaxU64(false, 0);
4755 
4756       bool has_used_usec = false;
4757       uint32_t curr_used_usec = 0;
4758       llvm::StringRef usec_name, usec_value;
4759       uint32_t input_file_pos = profileDataExtractor.GetFilePos();
4760       if (profileDataExtractor.GetNameColonValue(usec_name, usec_value)) {
4761         if (usec_name.equals("thread_used_usec")) {
4762           has_used_usec = true;
4763           usec_value.getAsInteger(0, curr_used_usec);
4764         } else {
4765           // We didn't find what we want, it is probably
4766           // an older version. Bail out.
4767           profileDataExtractor.SetFilePos(input_file_pos);
4768         }
4769       }
4770 
4771       if (has_used_usec) {
4772         uint32_t prev_used_usec = 0;
4773         std::map<uint64_t, uint32_t>::iterator iterator =
4774             m_thread_id_to_used_usec_map.find(thread_id);
4775         if (iterator != m_thread_id_to_used_usec_map.end()) {
4776           prev_used_usec = m_thread_id_to_used_usec_map[thread_id];
4777         }
4778 
4779         uint32_t real_used_usec = curr_used_usec - prev_used_usec;
4780         // A good first time record is one that runs for at least 0.25 sec
4781         bool good_first_time =
4782             (prev_used_usec == 0) && (real_used_usec > 250000);
4783         bool good_subsequent_time =
4784             (prev_used_usec > 0) &&
4785             ((real_used_usec > 0) || (HasAssignedIndexIDToThread(thread_id)));
4786 
4787         if (good_first_time || good_subsequent_time) {
4788           // We try to avoid doing too many index id reservation,
4789           // resulting in fast increase of index ids.
4790 
4791           output_stream << name << ":";
4792           int32_t index_id = AssignIndexIDToThread(thread_id);
4793           output_stream << index_id << ";";
4794 
4795           output_stream << usec_name << ":" << usec_value << ";";
4796         } else {
4797           // Skip past 'thread_used_name'.
4798           llvm::StringRef local_name, local_value;
4799           profileDataExtractor.GetNameColonValue(local_name, local_value);
4800         }
4801 
4802         // Store current time as previous time so that they can be compared
4803         // later.
4804         new_thread_id_to_used_usec_map[thread_id] = curr_used_usec;
4805       } else {
4806         // Bail out and use old string.
4807         output_stream << name << ":" << value << ";";
4808       }
4809     } else {
4810       output_stream << name << ":" << value << ";";
4811     }
4812   }
4813   output_stream << end_delimiter;
4814   m_thread_id_to_used_usec_map = new_thread_id_to_used_usec_map;
4815 
4816   return output_stream.str();
4817 }
4818 
4819 void ProcessGDBRemote::HandleStopReply() {
4820   if (GetStopID() != 0)
4821     return;
4822 
4823   if (GetID() == LLDB_INVALID_PROCESS_ID) {
4824     lldb::pid_t pid = m_gdb_comm.GetCurrentProcessID();
4825     if (pid != LLDB_INVALID_PROCESS_ID)
4826       SetID(pid);
4827   }
4828   BuildDynamicRegisterInfo(true);
4829 }
4830 
4831 static const char *const s_async_json_packet_prefix = "JSON-async:";
4832 
4833 static StructuredData::ObjectSP
4834 ParseStructuredDataPacket(llvm::StringRef packet) {
4835   Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
4836 
4837   if (!packet.consume_front(s_async_json_packet_prefix)) {
4838     if (log) {
4839       log->Printf(
4840           "GDBRemoteCommmunicationClientBase::%s() received $J packet "
4841           "but was not a StructuredData packet: packet starts with "
4842           "%s",
4843           __FUNCTION__,
4844           packet.slice(0, strlen(s_async_json_packet_prefix)).str().c_str());
4845     }
4846     return StructuredData::ObjectSP();
4847   }
4848 
4849   // This is an asynchronous JSON packet, destined for a
4850   // StructuredDataPlugin.
4851   StructuredData::ObjectSP json_sp = StructuredData::ParseJSON(packet);
4852   if (log) {
4853     if (json_sp) {
4854       StreamString json_str;
4855       json_sp->Dump(json_str);
4856       json_str.Flush();
4857       log->Printf("ProcessGDBRemote::%s() "
4858                   "received Async StructuredData packet: %s",
4859                   __FUNCTION__, json_str.GetData());
4860     } else {
4861       log->Printf("ProcessGDBRemote::%s"
4862                   "() received StructuredData packet:"
4863                   " parse failure",
4864                   __FUNCTION__);
4865     }
4866   }
4867   return json_sp;
4868 }
4869 
4870 void ProcessGDBRemote::HandleAsyncStructuredDataPacket(llvm::StringRef data) {
4871   auto structured_data_sp = ParseStructuredDataPacket(data);
4872   if (structured_data_sp)
4873     RouteAsyncStructuredData(structured_data_sp);
4874 }
4875 
4876 class CommandObjectProcessGDBRemoteSpeedTest : public CommandObjectParsed {
4877 public:
4878   CommandObjectProcessGDBRemoteSpeedTest(CommandInterpreter &interpreter)
4879       : CommandObjectParsed(interpreter, "process plugin packet speed-test",
4880                             "Tests packet speeds of various sizes to determine "
4881                             "the performance characteristics of the GDB remote "
4882                             "connection. ",
4883                             NULL),
4884         m_option_group(),
4885         m_num_packets(LLDB_OPT_SET_1, false, "count", 'c', 0, eArgTypeCount,
4886                       "The number of packets to send of each varying size "
4887                       "(default is 1000).",
4888                       1000),
4889         m_max_send(LLDB_OPT_SET_1, false, "max-send", 's', 0, eArgTypeCount,
4890                    "The maximum number of bytes to send in a packet. Sizes "
4891                    "increase in powers of 2 while the size is less than or "
4892                    "equal to this option value. (default 1024).",
4893                    1024),
4894         m_max_recv(LLDB_OPT_SET_1, false, "max-receive", 'r', 0, eArgTypeCount,
4895                    "The maximum number of bytes to receive in a packet. Sizes "
4896                    "increase in powers of 2 while the size is less than or "
4897                    "equal to this option value. (default 1024).",
4898                    1024),
4899         m_json(LLDB_OPT_SET_1, false, "json", 'j',
4900                "Print the output as JSON data for easy parsing.", false, true) {
4901     m_option_group.Append(&m_num_packets, LLDB_OPT_SET_ALL, LLDB_OPT_SET_1);
4902     m_option_group.Append(&m_max_send, LLDB_OPT_SET_ALL, LLDB_OPT_SET_1);
4903     m_option_group.Append(&m_max_recv, LLDB_OPT_SET_ALL, LLDB_OPT_SET_1);
4904     m_option_group.Append(&m_json, LLDB_OPT_SET_ALL, LLDB_OPT_SET_1);
4905     m_option_group.Finalize();
4906   }
4907 
4908   ~CommandObjectProcessGDBRemoteSpeedTest() {}
4909 
4910   Options *GetOptions() override { return &m_option_group; }
4911 
4912   bool DoExecute(Args &command, CommandReturnObject &result) override {
4913     const size_t argc = command.GetArgumentCount();
4914     if (argc == 0) {
4915       ProcessGDBRemote *process =
4916           (ProcessGDBRemote *)m_interpreter.GetExecutionContext()
4917               .GetProcessPtr();
4918       if (process) {
4919         StreamSP output_stream_sp(
4920             m_interpreter.GetDebugger().GetAsyncOutputStream());
4921         result.SetImmediateOutputStream(output_stream_sp);
4922 
4923         const uint32_t num_packets =
4924             (uint32_t)m_num_packets.GetOptionValue().GetCurrentValue();
4925         const uint64_t max_send = m_max_send.GetOptionValue().GetCurrentValue();
4926         const uint64_t max_recv = m_max_recv.GetOptionValue().GetCurrentValue();
4927         const bool json = m_json.GetOptionValue().GetCurrentValue();
4928         const uint64_t k_recv_amount =
4929             4 * 1024 * 1024; // Receive amount in bytes
4930         process->GetGDBRemote().TestPacketSpeed(
4931             num_packets, max_send, max_recv, k_recv_amount, json,
4932             output_stream_sp ? *output_stream_sp : result.GetOutputStream());
4933         result.SetStatus(eReturnStatusSuccessFinishResult);
4934         return true;
4935       }
4936     } else {
4937       result.AppendErrorWithFormat("'%s' takes no arguments",
4938                                    m_cmd_name.c_str());
4939     }
4940     result.SetStatus(eReturnStatusFailed);
4941     return false;
4942   }
4943 
4944 protected:
4945   OptionGroupOptions m_option_group;
4946   OptionGroupUInt64 m_num_packets;
4947   OptionGroupUInt64 m_max_send;
4948   OptionGroupUInt64 m_max_recv;
4949   OptionGroupBoolean m_json;
4950 };
4951 
4952 class CommandObjectProcessGDBRemotePacketHistory : public CommandObjectParsed {
4953 private:
4954 public:
4955   CommandObjectProcessGDBRemotePacketHistory(CommandInterpreter &interpreter)
4956       : CommandObjectParsed(interpreter, "process plugin packet history",
4957                             "Dumps the packet history buffer. ", NULL) {}
4958 
4959   ~CommandObjectProcessGDBRemotePacketHistory() {}
4960 
4961   bool DoExecute(Args &command, CommandReturnObject &result) override {
4962     const size_t argc = command.GetArgumentCount();
4963     if (argc == 0) {
4964       ProcessGDBRemote *process =
4965           (ProcessGDBRemote *)m_interpreter.GetExecutionContext()
4966               .GetProcessPtr();
4967       if (process) {
4968         process->GetGDBRemote().DumpHistory(result.GetOutputStream());
4969         result.SetStatus(eReturnStatusSuccessFinishResult);
4970         return true;
4971       }
4972     } else {
4973       result.AppendErrorWithFormat("'%s' takes no arguments",
4974                                    m_cmd_name.c_str());
4975     }
4976     result.SetStatus(eReturnStatusFailed);
4977     return false;
4978   }
4979 };
4980 
4981 class CommandObjectProcessGDBRemotePacketXferSize : public CommandObjectParsed {
4982 private:
4983 public:
4984   CommandObjectProcessGDBRemotePacketXferSize(CommandInterpreter &interpreter)
4985       : CommandObjectParsed(
4986             interpreter, "process plugin packet xfer-size",
4987             "Maximum size that lldb will try to read/write one one chunk.",
4988             NULL) {}
4989 
4990   ~CommandObjectProcessGDBRemotePacketXferSize() {}
4991 
4992   bool DoExecute(Args &command, CommandReturnObject &result) override {
4993     const size_t argc = command.GetArgumentCount();
4994     if (argc == 0) {
4995       result.AppendErrorWithFormat("'%s' takes an argument to specify the max "
4996                                    "amount to be transferred when "
4997                                    "reading/writing",
4998                                    m_cmd_name.c_str());
4999       result.SetStatus(eReturnStatusFailed);
5000       return false;
5001     }
5002 
5003     ProcessGDBRemote *process =
5004         (ProcessGDBRemote *)m_interpreter.GetExecutionContext().GetProcessPtr();
5005     if (process) {
5006       const char *packet_size = command.GetArgumentAtIndex(0);
5007       errno = 0;
5008       uint64_t user_specified_max = strtoul(packet_size, NULL, 10);
5009       if (errno == 0 && user_specified_max != 0) {
5010         process->SetUserSpecifiedMaxMemoryTransferSize(user_specified_max);
5011         result.SetStatus(eReturnStatusSuccessFinishResult);
5012         return true;
5013       }
5014     }
5015     result.SetStatus(eReturnStatusFailed);
5016     return false;
5017   }
5018 };
5019 
5020 class CommandObjectProcessGDBRemotePacketSend : public CommandObjectParsed {
5021 private:
5022 public:
5023   CommandObjectProcessGDBRemotePacketSend(CommandInterpreter &interpreter)
5024       : CommandObjectParsed(interpreter, "process plugin packet send",
5025                             "Send a custom packet through the GDB remote "
5026                             "protocol and print the answer. "
5027                             "The packet header and footer will automatically "
5028                             "be added to the packet prior to sending and "
5029                             "stripped from the result.",
5030                             NULL) {}
5031 
5032   ~CommandObjectProcessGDBRemotePacketSend() {}
5033 
5034   bool DoExecute(Args &command, CommandReturnObject &result) override {
5035     const size_t argc = command.GetArgumentCount();
5036     if (argc == 0) {
5037       result.AppendErrorWithFormat(
5038           "'%s' takes a one or more packet content arguments",
5039           m_cmd_name.c_str());
5040       result.SetStatus(eReturnStatusFailed);
5041       return false;
5042     }
5043 
5044     ProcessGDBRemote *process =
5045         (ProcessGDBRemote *)m_interpreter.GetExecutionContext().GetProcessPtr();
5046     if (process) {
5047       for (size_t i = 0; i < argc; ++i) {
5048         const char *packet_cstr = command.GetArgumentAtIndex(0);
5049         bool send_async = true;
5050         StringExtractorGDBRemote response;
5051         process->GetGDBRemote().SendPacketAndWaitForResponse(
5052             packet_cstr, response, send_async);
5053         result.SetStatus(eReturnStatusSuccessFinishResult);
5054         Stream &output_strm = result.GetOutputStream();
5055         output_strm.Printf("  packet: %s\n", packet_cstr);
5056         std::string &response_str = response.GetStringRef();
5057 
5058         if (strstr(packet_cstr, "qGetProfileData") != NULL) {
5059           response_str = process->HarmonizeThreadIdsForProfileData(response);
5060         }
5061 
5062         if (response_str.empty())
5063           output_strm.PutCString("response: \nerror: UNIMPLEMENTED\n");
5064         else
5065           output_strm.Printf("response: %s\n", response.GetStringRef().c_str());
5066       }
5067     }
5068     return true;
5069   }
5070 };
5071 
5072 class CommandObjectProcessGDBRemotePacketMonitor : public CommandObjectRaw {
5073 private:
5074 public:
5075   CommandObjectProcessGDBRemotePacketMonitor(CommandInterpreter &interpreter)
5076       : CommandObjectRaw(interpreter, "process plugin packet monitor",
5077                          "Send a qRcmd packet through the GDB remote protocol "
5078                          "and print the response."
5079                          "The argument passed to this command will be hex "
5080                          "encoded into a valid 'qRcmd' packet, sent and the "
5081                          "response will be printed.") {}
5082 
5083   ~CommandObjectProcessGDBRemotePacketMonitor() {}
5084 
5085   bool DoExecute(const char *command, CommandReturnObject &result) override {
5086     if (command == NULL || command[0] == '\0') {
5087       result.AppendErrorWithFormat("'%s' takes a command string argument",
5088                                    m_cmd_name.c_str());
5089       result.SetStatus(eReturnStatusFailed);
5090       return false;
5091     }
5092 
5093     ProcessGDBRemote *process =
5094         (ProcessGDBRemote *)m_interpreter.GetExecutionContext().GetProcessPtr();
5095     if (process) {
5096       StreamString packet;
5097       packet.PutCString("qRcmd,");
5098       packet.PutBytesAsRawHex8(command, strlen(command));
5099 
5100       bool send_async = true;
5101       StringExtractorGDBRemote response;
5102       process->GetGDBRemote().SendPacketAndWaitForResponse(
5103           packet.GetString(), response, send_async);
5104       result.SetStatus(eReturnStatusSuccessFinishResult);
5105       Stream &output_strm = result.GetOutputStream();
5106       output_strm.Printf("  packet: %s\n", packet.GetData());
5107       const std::string &response_str = response.GetStringRef();
5108 
5109       if (response_str.empty())
5110         output_strm.PutCString("response: \nerror: UNIMPLEMENTED\n");
5111       else
5112         output_strm.Printf("response: %s\n", response.GetStringRef().c_str());
5113     }
5114     return true;
5115   }
5116 };
5117 
5118 class CommandObjectProcessGDBRemotePacket : public CommandObjectMultiword {
5119 private:
5120 public:
5121   CommandObjectProcessGDBRemotePacket(CommandInterpreter &interpreter)
5122       : CommandObjectMultiword(interpreter, "process plugin packet",
5123                                "Commands that deal with GDB remote packets.",
5124                                NULL) {
5125     LoadSubCommand(
5126         "history",
5127         CommandObjectSP(
5128             new CommandObjectProcessGDBRemotePacketHistory(interpreter)));
5129     LoadSubCommand(
5130         "send", CommandObjectSP(
5131                     new CommandObjectProcessGDBRemotePacketSend(interpreter)));
5132     LoadSubCommand(
5133         "monitor",
5134         CommandObjectSP(
5135             new CommandObjectProcessGDBRemotePacketMonitor(interpreter)));
5136     LoadSubCommand(
5137         "xfer-size",
5138         CommandObjectSP(
5139             new CommandObjectProcessGDBRemotePacketXferSize(interpreter)));
5140     LoadSubCommand("speed-test",
5141                    CommandObjectSP(new CommandObjectProcessGDBRemoteSpeedTest(
5142                        interpreter)));
5143   }
5144 
5145   ~CommandObjectProcessGDBRemotePacket() {}
5146 };
5147 
5148 class CommandObjectMultiwordProcessGDBRemote : public CommandObjectMultiword {
5149 public:
5150   CommandObjectMultiwordProcessGDBRemote(CommandInterpreter &interpreter)
5151       : CommandObjectMultiword(
5152             interpreter, "process plugin",
5153             "Commands for operating on a ProcessGDBRemote process.",
5154             "process plugin <subcommand> [<subcommand-options>]") {
5155     LoadSubCommand(
5156         "packet",
5157         CommandObjectSP(new CommandObjectProcessGDBRemotePacket(interpreter)));
5158   }
5159 
5160   ~CommandObjectMultiwordProcessGDBRemote() {}
5161 };
5162 
5163 CommandObject *ProcessGDBRemote::GetPluginCommandObject() {
5164   if (!m_command_sp)
5165     m_command_sp.reset(new CommandObjectMultiwordProcessGDBRemote(
5166         GetTarget().GetDebugger().GetCommandInterpreter()));
5167   return m_command_sp.get();
5168 }
5169