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