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