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