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