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