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