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