xref: /llvm-project/lldb/source/Plugins/Process/gdb-remote/ProcessGDBRemote.cpp (revision dbc34e2bed10c18c78100a9e8517d9a0b2f6639d)
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         "Properties for the gdb-remote process plug-in.", is_global_setting);
3404   }
3405 }
3406 
3407 bool ProcessGDBRemote::StartAsyncThread() {
3408   Log *log = GetLog(GDBRLog::Process);
3409 
3410   LLDB_LOGF(log, "ProcessGDBRemote::%s ()", __FUNCTION__);
3411 
3412   std::lock_guard<std::recursive_mutex> guard(m_async_thread_state_mutex);
3413   if (!m_async_thread.IsJoinable()) {
3414     // Create a thread that watches our internal state and controls which
3415     // events make it to clients (into the DCProcess event queue).
3416 
3417     llvm::Expected<HostThread> async_thread =
3418         ThreadLauncher::LaunchThread("<lldb.process.gdb-remote.async>", [this] {
3419           return ProcessGDBRemote::AsyncThread();
3420         });
3421     if (!async_thread) {
3422       LLDB_LOG_ERROR(GetLog(LLDBLog::Host), async_thread.takeError(),
3423                      "failed to launch host thread: {}");
3424       return false;
3425     }
3426     m_async_thread = *async_thread;
3427   } else
3428     LLDB_LOGF(log,
3429               "ProcessGDBRemote::%s () - Called when Async thread was "
3430               "already running.",
3431               __FUNCTION__);
3432 
3433   return m_async_thread.IsJoinable();
3434 }
3435 
3436 void ProcessGDBRemote::StopAsyncThread() {
3437   Log *log = GetLog(GDBRLog::Process);
3438 
3439   LLDB_LOGF(log, "ProcessGDBRemote::%s ()", __FUNCTION__);
3440 
3441   std::lock_guard<std::recursive_mutex> guard(m_async_thread_state_mutex);
3442   if (m_async_thread.IsJoinable()) {
3443     m_async_broadcaster.BroadcastEvent(eBroadcastBitAsyncThreadShouldExit);
3444 
3445     //  This will shut down the async thread.
3446     m_gdb_comm.Disconnect(); // Disconnect from the debug server.
3447 
3448     // Stop the stdio thread
3449     m_async_thread.Join(nullptr);
3450     m_async_thread.Reset();
3451   } else
3452     LLDB_LOGF(
3453         log,
3454         "ProcessGDBRemote::%s () - Called when Async thread was not running.",
3455         __FUNCTION__);
3456 }
3457 
3458 thread_result_t ProcessGDBRemote::AsyncThread() {
3459   Log *log = GetLog(GDBRLog::Process);
3460   LLDB_LOGF(log, "ProcessGDBRemote::%s(pid = %" PRIu64 ") thread starting...",
3461             __FUNCTION__, GetID());
3462 
3463   EventSP event_sp;
3464 
3465   // We need to ignore any packets that come in after we have
3466   // have decided the process has exited.  There are some
3467   // situations, for instance when we try to interrupt a running
3468   // process and the interrupt fails, where another packet might
3469   // get delivered after we've decided to give up on the process.
3470   // But once we've decided we are done with the process we will
3471   // not be in a state to do anything useful with new packets.
3472   // So it is safer to simply ignore any remaining packets by
3473   // explicitly checking for eStateExited before reentering the
3474   // fetch loop.
3475 
3476   bool done = false;
3477   while (!done && GetPrivateState() != eStateExited) {
3478     LLDB_LOGF(log,
3479               "ProcessGDBRemote::%s(pid = %" PRIu64
3480               ") listener.WaitForEvent (NULL, event_sp)...",
3481               __FUNCTION__, GetID());
3482 
3483     if (m_async_listener_sp->GetEvent(event_sp, std::nullopt)) {
3484       const uint32_t event_type = event_sp->GetType();
3485       if (event_sp->BroadcasterIs(&m_async_broadcaster)) {
3486         LLDB_LOGF(log,
3487                   "ProcessGDBRemote::%s(pid = %" PRIu64
3488                   ") Got an event of type: %d...",
3489                   __FUNCTION__, GetID(), event_type);
3490 
3491         switch (event_type) {
3492         case eBroadcastBitAsyncContinue: {
3493           const EventDataBytes *continue_packet =
3494               EventDataBytes::GetEventDataFromEvent(event_sp.get());
3495 
3496           if (continue_packet) {
3497             const char *continue_cstr =
3498                 (const char *)continue_packet->GetBytes();
3499             const size_t continue_cstr_len = continue_packet->GetByteSize();
3500             LLDB_LOGF(log,
3501                       "ProcessGDBRemote::%s(pid = %" PRIu64
3502                       ") got eBroadcastBitAsyncContinue: %s",
3503                       __FUNCTION__, GetID(), continue_cstr);
3504 
3505             if (::strstr(continue_cstr, "vAttach") == nullptr)
3506               SetPrivateState(eStateRunning);
3507             StringExtractorGDBRemote response;
3508 
3509             StateType stop_state =
3510                 GetGDBRemote().SendContinuePacketAndWaitForResponse(
3511                     *this, *GetUnixSignals(),
3512                     llvm::StringRef(continue_cstr, continue_cstr_len),
3513                     GetInterruptTimeout(), response);
3514 
3515             // We need to immediately clear the thread ID list so we are sure
3516             // to get a valid list of threads. The thread ID list might be
3517             // contained within the "response", or the stop reply packet that
3518             // caused the stop. So clear it now before we give the stop reply
3519             // packet to the process using the
3520             // SetLastStopPacket()...
3521             ClearThreadIDList();
3522 
3523             switch (stop_state) {
3524             case eStateStopped:
3525             case eStateCrashed:
3526             case eStateSuspended:
3527               SetLastStopPacket(response);
3528               SetPrivateState(stop_state);
3529               break;
3530 
3531             case eStateExited: {
3532               SetLastStopPacket(response);
3533               ClearThreadIDList();
3534               response.SetFilePos(1);
3535 
3536               int exit_status = response.GetHexU8();
3537               std::string desc_string;
3538               if (response.GetBytesLeft() > 0 && response.GetChar('-') == ';') {
3539                 llvm::StringRef desc_str;
3540                 llvm::StringRef desc_token;
3541                 while (response.GetNameColonValue(desc_token, desc_str)) {
3542                   if (desc_token != "description")
3543                     continue;
3544                   StringExtractor extractor(desc_str);
3545                   extractor.GetHexByteString(desc_string);
3546                 }
3547               }
3548               SetExitStatus(exit_status, desc_string.c_str());
3549               done = true;
3550               break;
3551             }
3552             case eStateInvalid: {
3553               // Check to see if we were trying to attach and if we got back
3554               // the "E87" error code from debugserver -- this indicates that
3555               // the process is not debuggable.  Return a slightly more
3556               // helpful error message about why the attach failed.
3557               if (::strstr(continue_cstr, "vAttach") != nullptr &&
3558                   response.GetError() == 0x87) {
3559                 SetExitStatus(-1, "cannot attach to process due to "
3560                                   "System Integrity Protection");
3561               } else if (::strstr(continue_cstr, "vAttach") != nullptr &&
3562                          response.GetStatus().Fail()) {
3563                 SetExitStatus(-1, response.GetStatus().AsCString());
3564               } else {
3565                 SetExitStatus(-1, "lost connection");
3566               }
3567               done = true;
3568               break;
3569             }
3570 
3571             default:
3572               SetPrivateState(stop_state);
3573               break;
3574             }   // switch(stop_state)
3575           }     // if (continue_packet)
3576         }       // case eBroadcastBitAsyncContinue
3577         break;
3578 
3579         case eBroadcastBitAsyncThreadShouldExit:
3580           LLDB_LOGF(log,
3581                     "ProcessGDBRemote::%s(pid = %" PRIu64
3582                     ") got eBroadcastBitAsyncThreadShouldExit...",
3583                     __FUNCTION__, GetID());
3584           done = true;
3585           break;
3586 
3587         default:
3588           LLDB_LOGF(log,
3589                     "ProcessGDBRemote::%s(pid = %" PRIu64
3590                     ") got unknown event 0x%8.8x",
3591                     __FUNCTION__, GetID(), event_type);
3592           done = true;
3593           break;
3594         }
3595       }
3596     } else {
3597       LLDB_LOGF(log,
3598                 "ProcessGDBRemote::%s(pid = %" PRIu64
3599                 ") listener.WaitForEvent (NULL, event_sp) => false",
3600                 __FUNCTION__, GetID());
3601       done = true;
3602     }
3603   }
3604 
3605   LLDB_LOGF(log, "ProcessGDBRemote::%s(pid = %" PRIu64 ") thread exiting...",
3606             __FUNCTION__, GetID());
3607 
3608   return {};
3609 }
3610 
3611 // uint32_t
3612 // ProcessGDBRemote::ListProcessesMatchingName (const char *name, StringList
3613 // &matches, std::vector<lldb::pid_t> &pids)
3614 //{
3615 //    // If we are planning to launch the debugserver remotely, then we need to
3616 //    fire up a debugserver
3617 //    // process and ask it for the list of processes. But if we are local, we
3618 //    can let the Host do it.
3619 //    if (m_local_debugserver)
3620 //    {
3621 //        return Host::ListProcessesMatchingName (name, matches, pids);
3622 //    }
3623 //    else
3624 //    {
3625 //        // FIXME: Implement talking to the remote debugserver.
3626 //        return 0;
3627 //    }
3628 //
3629 //}
3630 //
3631 bool ProcessGDBRemote::NewThreadNotifyBreakpointHit(
3632     void *baton, StoppointCallbackContext *context, lldb::user_id_t break_id,
3633     lldb::user_id_t break_loc_id) {
3634   // I don't think I have to do anything here, just make sure I notice the new
3635   // thread when it starts to
3636   // run so I can stop it if that's what I want to do.
3637   Log *log = GetLog(LLDBLog::Step);
3638   LLDB_LOGF(log, "Hit New Thread Notification breakpoint.");
3639   return false;
3640 }
3641 
3642 Status ProcessGDBRemote::UpdateAutomaticSignalFiltering() {
3643   Log *log = GetLog(GDBRLog::Process);
3644   LLDB_LOG(log, "Check if need to update ignored signals");
3645 
3646   // QPassSignals package is not supported by the server, there is no way we
3647   // can ignore any signals on server side.
3648   if (!m_gdb_comm.GetQPassSignalsSupported())
3649     return Status();
3650 
3651   // No signals, nothing to send.
3652   if (m_unix_signals_sp == nullptr)
3653     return Status();
3654 
3655   // Signals' version hasn't changed, no need to send anything.
3656   uint64_t new_signals_version = m_unix_signals_sp->GetVersion();
3657   if (new_signals_version == m_last_signals_version) {
3658     LLDB_LOG(log, "Signals' version hasn't changed. version={0}",
3659              m_last_signals_version);
3660     return Status();
3661   }
3662 
3663   auto signals_to_ignore =
3664       m_unix_signals_sp->GetFilteredSignals(false, false, false);
3665   Status error = m_gdb_comm.SendSignalsToIgnore(signals_to_ignore);
3666 
3667   LLDB_LOG(log,
3668            "Signals' version changed. old version={0}, new version={1}, "
3669            "signals ignored={2}, update result={3}",
3670            m_last_signals_version, new_signals_version,
3671            signals_to_ignore.size(), error);
3672 
3673   if (error.Success())
3674     m_last_signals_version = new_signals_version;
3675 
3676   return error;
3677 }
3678 
3679 bool ProcessGDBRemote::StartNoticingNewThreads() {
3680   Log *log = GetLog(LLDBLog::Step);
3681   if (m_thread_create_bp_sp) {
3682     if (log && log->GetVerbose())
3683       LLDB_LOGF(log, "Enabled noticing new thread breakpoint.");
3684     m_thread_create_bp_sp->SetEnabled(true);
3685   } else {
3686     PlatformSP platform_sp(GetTarget().GetPlatform());
3687     if (platform_sp) {
3688       m_thread_create_bp_sp =
3689           platform_sp->SetThreadCreationBreakpoint(GetTarget());
3690       if (m_thread_create_bp_sp) {
3691         if (log && log->GetVerbose())
3692           LLDB_LOGF(
3693               log, "Successfully created new thread notification breakpoint %i",
3694               m_thread_create_bp_sp->GetID());
3695         m_thread_create_bp_sp->SetCallback(
3696             ProcessGDBRemote::NewThreadNotifyBreakpointHit, this, true);
3697       } else {
3698         LLDB_LOGF(log, "Failed to create new thread notification breakpoint.");
3699       }
3700     }
3701   }
3702   return m_thread_create_bp_sp.get() != nullptr;
3703 }
3704 
3705 bool ProcessGDBRemote::StopNoticingNewThreads() {
3706   Log *log = GetLog(LLDBLog::Step);
3707   if (log && log->GetVerbose())
3708     LLDB_LOGF(log, "Disabling new thread notification breakpoint.");
3709 
3710   if (m_thread_create_bp_sp)
3711     m_thread_create_bp_sp->SetEnabled(false);
3712 
3713   return true;
3714 }
3715 
3716 DynamicLoader *ProcessGDBRemote::GetDynamicLoader() {
3717   if (m_dyld_up.get() == nullptr)
3718     m_dyld_up.reset(DynamicLoader::FindPlugin(this, ""));
3719   return m_dyld_up.get();
3720 }
3721 
3722 Status ProcessGDBRemote::SendEventData(const char *data) {
3723   int return_value;
3724   bool was_supported;
3725 
3726   Status error;
3727 
3728   return_value = m_gdb_comm.SendLaunchEventDataPacket(data, &was_supported);
3729   if (return_value != 0) {
3730     if (!was_supported)
3731       error.SetErrorString("Sending events is not supported for this process.");
3732     else
3733       error.SetErrorStringWithFormat("Error sending event data: %d.",
3734                                      return_value);
3735   }
3736   return error;
3737 }
3738 
3739 DataExtractor ProcessGDBRemote::GetAuxvData() {
3740   DataBufferSP buf;
3741   if (m_gdb_comm.GetQXferAuxvReadSupported()) {
3742     llvm::Expected<std::string> response = m_gdb_comm.ReadExtFeature("auxv", "");
3743     if (response)
3744       buf = std::make_shared<DataBufferHeap>(response->c_str(),
3745                                              response->length());
3746     else
3747       LLDB_LOG_ERROR(GetLog(GDBRLog::Process), response.takeError(), "{0}");
3748   }
3749   return DataExtractor(buf, GetByteOrder(), GetAddressByteSize());
3750 }
3751 
3752 StructuredData::ObjectSP
3753 ProcessGDBRemote::GetExtendedInfoForThread(lldb::tid_t tid) {
3754   StructuredData::ObjectSP object_sp;
3755 
3756   if (m_gdb_comm.GetThreadExtendedInfoSupported()) {
3757     StructuredData::ObjectSP args_dict(new StructuredData::Dictionary());
3758     SystemRuntime *runtime = GetSystemRuntime();
3759     if (runtime) {
3760       runtime->AddThreadExtendedInfoPacketHints(args_dict);
3761     }
3762     args_dict->GetAsDictionary()->AddIntegerItem("thread", tid);
3763 
3764     StreamString packet;
3765     packet << "jThreadExtendedInfo:";
3766     args_dict->Dump(packet, false);
3767 
3768     // FIXME the final character of a JSON dictionary, '}', is the escape
3769     // character in gdb-remote binary mode.  lldb currently doesn't escape
3770     // these characters in its packet output -- so we add the quoted version of
3771     // the } character here manually in case we talk to a debugserver which un-
3772     // escapes the characters at packet read time.
3773     packet << (char)(0x7d ^ 0x20);
3774 
3775     StringExtractorGDBRemote response;
3776     response.SetResponseValidatorToJSON();
3777     if (m_gdb_comm.SendPacketAndWaitForResponse(packet.GetString(), response) ==
3778         GDBRemoteCommunication::PacketResult::Success) {
3779       StringExtractorGDBRemote::ResponseType response_type =
3780           response.GetResponseType();
3781       if (response_type == StringExtractorGDBRemote::eResponse) {
3782         if (!response.Empty()) {
3783           object_sp = StructuredData::ParseJSON(response.GetStringRef());
3784         }
3785       }
3786     }
3787   }
3788   return object_sp;
3789 }
3790 
3791 StructuredData::ObjectSP ProcessGDBRemote::GetLoadedDynamicLibrariesInfos(
3792     lldb::addr_t image_list_address, lldb::addr_t image_count) {
3793 
3794   StructuredData::ObjectSP args_dict(new StructuredData::Dictionary());
3795   args_dict->GetAsDictionary()->AddIntegerItem("image_list_address",
3796                                                image_list_address);
3797   args_dict->GetAsDictionary()->AddIntegerItem("image_count", image_count);
3798 
3799   return GetLoadedDynamicLibrariesInfos_sender(args_dict);
3800 }
3801 
3802 StructuredData::ObjectSP ProcessGDBRemote::GetLoadedDynamicLibrariesInfos() {
3803   StructuredData::ObjectSP args_dict(new StructuredData::Dictionary());
3804 
3805   args_dict->GetAsDictionary()->AddBooleanItem("fetch_all_solibs", true);
3806 
3807   return GetLoadedDynamicLibrariesInfos_sender(args_dict);
3808 }
3809 
3810 StructuredData::ObjectSP ProcessGDBRemote::GetLoadedDynamicLibrariesInfos(
3811     const std::vector<lldb::addr_t> &load_addresses) {
3812   StructuredData::ObjectSP args_dict(new StructuredData::Dictionary());
3813   StructuredData::ArraySP addresses(new StructuredData::Array);
3814 
3815   for (auto addr : load_addresses) {
3816     StructuredData::ObjectSP addr_sp(new StructuredData::Integer(addr));
3817     addresses->AddItem(addr_sp);
3818   }
3819 
3820   args_dict->GetAsDictionary()->AddItem("solib_addresses", addresses);
3821 
3822   return GetLoadedDynamicLibrariesInfos_sender(args_dict);
3823 }
3824 
3825 StructuredData::ObjectSP
3826 ProcessGDBRemote::GetLoadedDynamicLibrariesInfos_sender(
3827     StructuredData::ObjectSP args_dict) {
3828   StructuredData::ObjectSP object_sp;
3829 
3830   if (m_gdb_comm.GetLoadedDynamicLibrariesInfosSupported()) {
3831     // Scope for the scoped timeout object
3832     GDBRemoteCommunication::ScopedTimeout timeout(m_gdb_comm,
3833                                                   std::chrono::seconds(10));
3834 
3835     StreamString packet;
3836     packet << "jGetLoadedDynamicLibrariesInfos:";
3837     args_dict->Dump(packet, false);
3838 
3839     // FIXME the final character of a JSON dictionary, '}', is the escape
3840     // character in gdb-remote binary mode.  lldb currently doesn't escape
3841     // these characters in its packet output -- so we add the quoted version of
3842     // the } character here manually in case we talk to a debugserver which un-
3843     // escapes the characters at packet read time.
3844     packet << (char)(0x7d ^ 0x20);
3845 
3846     StringExtractorGDBRemote response;
3847     response.SetResponseValidatorToJSON();
3848     if (m_gdb_comm.SendPacketAndWaitForResponse(packet.GetString(), response) ==
3849         GDBRemoteCommunication::PacketResult::Success) {
3850       StringExtractorGDBRemote::ResponseType response_type =
3851           response.GetResponseType();
3852       if (response_type == StringExtractorGDBRemote::eResponse) {
3853         if (!response.Empty()) {
3854           object_sp = StructuredData::ParseJSON(response.GetStringRef());
3855         }
3856       }
3857     }
3858   }
3859   return object_sp;
3860 }
3861 
3862 StructuredData::ObjectSP ProcessGDBRemote::GetDynamicLoaderProcessState() {
3863   StructuredData::ObjectSP object_sp;
3864   StructuredData::ObjectSP args_dict(new StructuredData::Dictionary());
3865 
3866   if (m_gdb_comm.GetDynamicLoaderProcessStateSupported()) {
3867     StringExtractorGDBRemote response;
3868     response.SetResponseValidatorToJSON();
3869     if (m_gdb_comm.SendPacketAndWaitForResponse("jGetDyldProcessState",
3870                                                 response) ==
3871         GDBRemoteCommunication::PacketResult::Success) {
3872       StringExtractorGDBRemote::ResponseType response_type =
3873           response.GetResponseType();
3874       if (response_type == StringExtractorGDBRemote::eResponse) {
3875         if (!response.Empty()) {
3876           object_sp = StructuredData::ParseJSON(response.GetStringRef());
3877         }
3878       }
3879     }
3880   }
3881   return object_sp;
3882 }
3883 
3884 StructuredData::ObjectSP ProcessGDBRemote::GetSharedCacheInfo() {
3885   StructuredData::ObjectSP object_sp;
3886   StructuredData::ObjectSP args_dict(new StructuredData::Dictionary());
3887 
3888   if (m_gdb_comm.GetSharedCacheInfoSupported()) {
3889     StreamString packet;
3890     packet << "jGetSharedCacheInfo:";
3891     args_dict->Dump(packet, false);
3892 
3893     // FIXME the final character of a JSON dictionary, '}', is the escape
3894     // character in gdb-remote binary mode.  lldb currently doesn't escape
3895     // these characters in its packet output -- so we add the quoted version of
3896     // the } character here manually in case we talk to a debugserver which un-
3897     // escapes the characters at packet read time.
3898     packet << (char)(0x7d ^ 0x20);
3899 
3900     StringExtractorGDBRemote response;
3901     response.SetResponseValidatorToJSON();
3902     if (m_gdb_comm.SendPacketAndWaitForResponse(packet.GetString(), response) ==
3903         GDBRemoteCommunication::PacketResult::Success) {
3904       StringExtractorGDBRemote::ResponseType response_type =
3905           response.GetResponseType();
3906       if (response_type == StringExtractorGDBRemote::eResponse) {
3907         if (!response.Empty()) {
3908           object_sp = StructuredData::ParseJSON(response.GetStringRef());
3909         }
3910       }
3911     }
3912   }
3913   return object_sp;
3914 }
3915 
3916 Status ProcessGDBRemote::ConfigureStructuredData(
3917     ConstString type_name, const StructuredData::ObjectSP &config_sp) {
3918   return m_gdb_comm.ConfigureRemoteStructuredData(type_name, config_sp);
3919 }
3920 
3921 // Establish the largest memory read/write payloads we should use. If the
3922 // remote stub has a max packet size, stay under that size.
3923 //
3924 // If the remote stub's max packet size is crazy large, use a reasonable
3925 // largeish default.
3926 //
3927 // If the remote stub doesn't advertise a max packet size, use a conservative
3928 // default.
3929 
3930 void ProcessGDBRemote::GetMaxMemorySize() {
3931   const uint64_t reasonable_largeish_default = 128 * 1024;
3932   const uint64_t conservative_default = 512;
3933 
3934   if (m_max_memory_size == 0) {
3935     uint64_t stub_max_size = m_gdb_comm.GetRemoteMaxPacketSize();
3936     if (stub_max_size != UINT64_MAX && stub_max_size != 0) {
3937       // Save the stub's claimed maximum packet size
3938       m_remote_stub_max_memory_size = stub_max_size;
3939 
3940       // Even if the stub says it can support ginormous packets, don't exceed
3941       // our reasonable largeish default packet size.
3942       if (stub_max_size > reasonable_largeish_default) {
3943         stub_max_size = reasonable_largeish_default;
3944       }
3945 
3946       // Memory packet have other overheads too like Maddr,size:#NN Instead of
3947       // calculating the bytes taken by size and addr every time, we take a
3948       // maximum guess here.
3949       if (stub_max_size > 70)
3950         stub_max_size -= 32 + 32 + 6;
3951       else {
3952         // In unlikely scenario that max packet size is less then 70, we will
3953         // hope that data being written is small enough to fit.
3954         Log *log(GetLog(GDBRLog::Comm | GDBRLog::Memory));
3955         if (log)
3956           log->Warning("Packet size is too small. "
3957                        "LLDB may face problems while writing memory");
3958       }
3959 
3960       m_max_memory_size = stub_max_size;
3961     } else {
3962       m_max_memory_size = conservative_default;
3963     }
3964   }
3965 }
3966 
3967 void ProcessGDBRemote::SetUserSpecifiedMaxMemoryTransferSize(
3968     uint64_t user_specified_max) {
3969   if (user_specified_max != 0) {
3970     GetMaxMemorySize();
3971 
3972     if (m_remote_stub_max_memory_size != 0) {
3973       if (m_remote_stub_max_memory_size < user_specified_max) {
3974         m_max_memory_size = m_remote_stub_max_memory_size; // user specified a
3975                                                            // packet size too
3976                                                            // big, go as big
3977         // as the remote stub says we can go.
3978       } else {
3979         m_max_memory_size = user_specified_max; // user's packet size is good
3980       }
3981     } else {
3982       m_max_memory_size =
3983           user_specified_max; // user's packet size is probably fine
3984     }
3985   }
3986 }
3987 
3988 bool ProcessGDBRemote::GetModuleSpec(const FileSpec &module_file_spec,
3989                                      const ArchSpec &arch,
3990                                      ModuleSpec &module_spec) {
3991   Log *log = GetLog(LLDBLog::Platform);
3992 
3993   const ModuleCacheKey key(module_file_spec.GetPath(),
3994                            arch.GetTriple().getTriple());
3995   auto cached = m_cached_module_specs.find(key);
3996   if (cached != m_cached_module_specs.end()) {
3997     module_spec = cached->second;
3998     return bool(module_spec);
3999   }
4000 
4001   if (!m_gdb_comm.GetModuleInfo(module_file_spec, arch, module_spec)) {
4002     LLDB_LOGF(log, "ProcessGDBRemote::%s - failed to get module info for %s:%s",
4003               __FUNCTION__, module_file_spec.GetPath().c_str(),
4004               arch.GetTriple().getTriple().c_str());
4005     return false;
4006   }
4007 
4008   if (log) {
4009     StreamString stream;
4010     module_spec.Dump(stream);
4011     LLDB_LOGF(log, "ProcessGDBRemote::%s - got module info for (%s:%s) : %s",
4012               __FUNCTION__, module_file_spec.GetPath().c_str(),
4013               arch.GetTriple().getTriple().c_str(), stream.GetData());
4014   }
4015 
4016   m_cached_module_specs[key] = module_spec;
4017   return true;
4018 }
4019 
4020 void ProcessGDBRemote::PrefetchModuleSpecs(
4021     llvm::ArrayRef<FileSpec> module_file_specs, const llvm::Triple &triple) {
4022   auto module_specs = m_gdb_comm.GetModulesInfo(module_file_specs, triple);
4023   if (module_specs) {
4024     for (const FileSpec &spec : module_file_specs)
4025       m_cached_module_specs[ModuleCacheKey(spec.GetPath(),
4026                                            triple.getTriple())] = ModuleSpec();
4027     for (const ModuleSpec &spec : *module_specs)
4028       m_cached_module_specs[ModuleCacheKey(spec.GetFileSpec().GetPath(),
4029                                            triple.getTriple())] = spec;
4030   }
4031 }
4032 
4033 llvm::VersionTuple ProcessGDBRemote::GetHostOSVersion() {
4034   return m_gdb_comm.GetOSVersion();
4035 }
4036 
4037 llvm::VersionTuple ProcessGDBRemote::GetHostMacCatalystVersion() {
4038   return m_gdb_comm.GetMacCatalystVersion();
4039 }
4040 
4041 namespace {
4042 
4043 typedef std::vector<std::string> stringVec;
4044 
4045 typedef std::vector<struct GdbServerRegisterInfo> GDBServerRegisterVec;
4046 struct RegisterSetInfo {
4047   ConstString name;
4048 };
4049 
4050 typedef std::map<uint32_t, RegisterSetInfo> RegisterSetMap;
4051 
4052 struct GdbServerTargetInfo {
4053   std::string arch;
4054   std::string osabi;
4055   stringVec includes;
4056   RegisterSetMap reg_set_map;
4057 };
4058 
4059 static std::vector<RegisterFlags::Field> ParseFlagsFields(XMLNode flags_node,
4060                                                           unsigned size) {
4061   Log *log(GetLog(GDBRLog::Process));
4062   const unsigned max_start_bit = size * 8 - 1;
4063 
4064   // Process the fields of this set of flags.
4065   std::vector<RegisterFlags::Field> fields;
4066   flags_node.ForEachChildElementWithName("field", [&fields, max_start_bit,
4067                                                    &log](const XMLNode
4068                                                              &field_node) {
4069     std::optional<llvm::StringRef> name;
4070     std::optional<unsigned> start;
4071     std::optional<unsigned> end;
4072 
4073     field_node.ForEachAttribute([&name, &start, &end, max_start_bit,
4074                                  &log](const llvm::StringRef &attr_name,
4075                                        const llvm::StringRef &attr_value) {
4076       // Note that XML in general requires that each of these attributes only
4077       // appears once, so we don't have to handle that here.
4078       if (attr_name == "name") {
4079         LLDB_LOG(log,
4080                  "ProcessGDBRemote::ParseFlags Found field node name \"{0}\"",
4081                  attr_value.data());
4082         name = attr_value;
4083       } else if (attr_name == "start") {
4084         unsigned parsed_start = 0;
4085         if (llvm::to_integer(attr_value, parsed_start)) {
4086           if (parsed_start > max_start_bit) {
4087             LLDB_LOG(
4088                 log,
4089                 "ProcessGDBRemote::ParseFlags Invalid start {0} in field node, "
4090                 "cannot be > {1}",
4091                 parsed_start, max_start_bit);
4092           } else
4093             start = parsed_start;
4094         } else {
4095           LLDB_LOG(log,
4096                    "ProcessGDBRemote::ParseFlags Invalid start \"{0}\" in "
4097                    "field node",
4098                    attr_value.data());
4099         }
4100       } else if (attr_name == "end") {
4101         unsigned parsed_end = 0;
4102         if (llvm::to_integer(attr_value, parsed_end))
4103           if (parsed_end > max_start_bit) {
4104             LLDB_LOG(
4105                 log,
4106                 "ProcessGDBRemote::ParseFlags Invalid end {0} in field node, "
4107                 "cannot be > {1}",
4108                 parsed_end, max_start_bit);
4109           } else
4110             end = parsed_end;
4111         else {
4112           LLDB_LOG(
4113               log,
4114               "ProcessGDBRemote::ParseFlags Invalid end \"{0}\" in field node",
4115               attr_value.data());
4116         }
4117       } else if (attr_name == "type") {
4118         // Type is a known attribute but we do not currently use it and it is
4119         // not required.
4120       } else {
4121         LLDB_LOG(log,
4122                  "ProcessGDBRemote::ParseFlags Ignoring unknown attribute "
4123                  "\"{0}\" in field node",
4124                  attr_name.data());
4125       }
4126 
4127       return true; // Walk all attributes of the field.
4128     });
4129 
4130     if (name && start && end) {
4131       if (*start > *end) {
4132         LLDB_LOG(log,
4133                  "ProcessGDBRemote::ParseFlags Start {0} > end {1} in field "
4134                  "\"{2}\", ignoring",
4135                  *start, *end, name->data());
4136       } else {
4137         fields.push_back(RegisterFlags::Field(name->str(), *start, *end));
4138       }
4139     }
4140 
4141     return true; // Iterate all "field" nodes.
4142   });
4143   return fields;
4144 }
4145 
4146 void ParseFlags(
4147     XMLNode feature_node,
4148     llvm::StringMap<std::unique_ptr<RegisterFlags>> &registers_flags_types) {
4149   Log *log(GetLog(GDBRLog::Process));
4150 
4151   feature_node.ForEachChildElementWithName(
4152       "flags",
4153       [&log, &registers_flags_types](const XMLNode &flags_node) -> bool {
4154         LLDB_LOG(log, "ProcessGDBRemote::ParseFlags Found flags node \"{0}\"",
4155                  flags_node.GetAttributeValue("id").c_str());
4156 
4157         std::optional<llvm::StringRef> id;
4158         std::optional<unsigned> size;
4159         flags_node.ForEachAttribute(
4160             [&id, &size, &log](const llvm::StringRef &name,
4161                                const llvm::StringRef &value) {
4162               if (name == "id") {
4163                 id = value;
4164               } else if (name == "size") {
4165                 unsigned parsed_size = 0;
4166                 if (llvm::to_integer(value, parsed_size))
4167                   size = parsed_size;
4168                 else {
4169                   LLDB_LOG(log,
4170                            "ProcessGDBRemote::ParseFlags Invalid size \"{0}\" "
4171                            "in flags node",
4172                            value.data());
4173                 }
4174               } else {
4175                 LLDB_LOG(log,
4176                          "ProcessGDBRemote::ParseFlags Ignoring unknown "
4177                          "attribute \"{0}\" in flags node",
4178                          name.data());
4179               }
4180               return true; // Walk all attributes.
4181             });
4182 
4183         if (id && size) {
4184           // Process the fields of this set of flags.
4185           std::vector<RegisterFlags::Field> fields =
4186               ParseFlagsFields(flags_node, *size);
4187           if (fields.size()) {
4188             // Sort so that the fields with the MSBs are first.
4189             std::sort(fields.rbegin(), fields.rend());
4190             std::vector<RegisterFlags::Field>::const_iterator overlap =
4191                 std::adjacent_find(fields.begin(), fields.end(),
4192                                    [](const RegisterFlags::Field &lhs,
4193                                       const RegisterFlags::Field &rhs) {
4194                                      return lhs.Overlaps(rhs);
4195                                    });
4196 
4197             // If no fields overlap, use them.
4198             if (overlap == fields.end()) {
4199               if (registers_flags_types.contains(*id)) {
4200                 // In theory you could define some flag set, use it with a
4201                 // register then redefine it. We do not know if anyone does
4202                 // that, or what they would expect to happen in that case.
4203                 //
4204                 // LLDB chooses to take the first definition and ignore the rest
4205                 // as waiting until everything has been processed is more
4206                 // expensive and difficult. This means that pointers to flag
4207                 // sets in the register info remain valid if later the flag set
4208                 // is redefined. If we allowed redefinitions, LLDB would crash
4209                 // when you tried to print a register that used the original
4210                 // definition.
4211                 LLDB_LOG(
4212                     log,
4213                     "ProcessGDBRemote::ParseFlags Definition of flags "
4214                     "\"{0}\" shadows "
4215                     "previous definition, using original definition instead.",
4216                     id->data());
4217               } else {
4218                 registers_flags_types.insert_or_assign(
4219                     *id, std::make_unique<RegisterFlags>(id->str(), *size,
4220                                                          std::move(fields)));
4221               }
4222             } else {
4223               // If any fields overlap, ignore the whole set of flags.
4224               std::vector<RegisterFlags::Field>::const_iterator next =
4225                   std::next(overlap);
4226               LLDB_LOG(
4227                   log,
4228                   "ProcessGDBRemote::ParseFlags Ignoring flags because fields "
4229                   "{0} (start: {1} end: {2}) and {3} (start: {4} end: {5}) "
4230                   "overlap.",
4231                   overlap->GetName().c_str(), overlap->GetStart(),
4232                   overlap->GetEnd(), next->GetName().c_str(), next->GetStart(),
4233                   next->GetEnd());
4234             }
4235           } else {
4236             LLDB_LOG(
4237                 log,
4238                 "ProcessGDBRemote::ParseFlags Ignoring definition of flags "
4239                 "\"{0}\" because it contains no fields.",
4240                 id->data());
4241           }
4242         }
4243 
4244         return true; // Keep iterating through all "flags" elements.
4245       });
4246 }
4247 
4248 bool ParseRegisters(
4249     XMLNode feature_node, GdbServerTargetInfo &target_info,
4250     std::vector<DynamicRegisterInfo::Register> &registers,
4251     llvm::StringMap<std::unique_ptr<RegisterFlags>> &registers_flags_types) {
4252   if (!feature_node)
4253     return false;
4254 
4255   Log *log(GetLog(GDBRLog::Process));
4256 
4257   ParseFlags(feature_node, registers_flags_types);
4258   for (const auto &flags : registers_flags_types)
4259     flags.second->log(log);
4260 
4261   feature_node.ForEachChildElementWithName(
4262       "reg",
4263       [&target_info, &registers, &registers_flags_types,
4264        log](const XMLNode &reg_node) -> bool {
4265         std::string gdb_group;
4266         std::string gdb_type;
4267         DynamicRegisterInfo::Register reg_info;
4268         bool encoding_set = false;
4269         bool format_set = false;
4270 
4271         // FIXME: we're silently ignoring invalid data here
4272         reg_node.ForEachAttribute([&target_info, &gdb_group, &gdb_type,
4273                                    &encoding_set, &format_set, &reg_info,
4274                                    log](const llvm::StringRef &name,
4275                                         const llvm::StringRef &value) -> bool {
4276           if (name == "name") {
4277             reg_info.name.SetString(value);
4278           } else if (name == "bitsize") {
4279             if (llvm::to_integer(value, reg_info.byte_size))
4280               reg_info.byte_size =
4281                   llvm::divideCeil(reg_info.byte_size, CHAR_BIT);
4282           } else if (name == "type") {
4283             gdb_type = value.str();
4284           } else if (name == "group") {
4285             gdb_group = value.str();
4286           } else if (name == "regnum") {
4287             llvm::to_integer(value, reg_info.regnum_remote);
4288           } else if (name == "offset") {
4289             llvm::to_integer(value, reg_info.byte_offset);
4290           } else if (name == "altname") {
4291             reg_info.alt_name.SetString(value);
4292           } else if (name == "encoding") {
4293             encoding_set = true;
4294             reg_info.encoding = Args::StringToEncoding(value, eEncodingUint);
4295           } else if (name == "format") {
4296             format_set = true;
4297             if (!OptionArgParser::ToFormat(value.data(), reg_info.format,
4298                                            nullptr)
4299                      .Success())
4300               reg_info.format =
4301                   llvm::StringSwitch<lldb::Format>(value)
4302                       .Case("vector-sint8", eFormatVectorOfSInt8)
4303                       .Case("vector-uint8", eFormatVectorOfUInt8)
4304                       .Case("vector-sint16", eFormatVectorOfSInt16)
4305                       .Case("vector-uint16", eFormatVectorOfUInt16)
4306                       .Case("vector-sint32", eFormatVectorOfSInt32)
4307                       .Case("vector-uint32", eFormatVectorOfUInt32)
4308                       .Case("vector-float32", eFormatVectorOfFloat32)
4309                       .Case("vector-uint64", eFormatVectorOfUInt64)
4310                       .Case("vector-uint128", eFormatVectorOfUInt128)
4311                       .Default(eFormatInvalid);
4312           } else if (name == "group_id") {
4313             uint32_t set_id = UINT32_MAX;
4314             llvm::to_integer(value, set_id);
4315             RegisterSetMap::const_iterator pos =
4316                 target_info.reg_set_map.find(set_id);
4317             if (pos != target_info.reg_set_map.end())
4318               reg_info.set_name = pos->second.name;
4319           } else if (name == "gcc_regnum" || name == "ehframe_regnum") {
4320             llvm::to_integer(value, reg_info.regnum_ehframe);
4321           } else if (name == "dwarf_regnum") {
4322             llvm::to_integer(value, reg_info.regnum_dwarf);
4323           } else if (name == "generic") {
4324             reg_info.regnum_generic = Args::StringToGenericRegister(value);
4325           } else if (name == "value_regnums") {
4326             SplitCommaSeparatedRegisterNumberString(value, reg_info.value_regs,
4327                                                     0);
4328           } else if (name == "invalidate_regnums") {
4329             SplitCommaSeparatedRegisterNumberString(
4330                 value, reg_info.invalidate_regs, 0);
4331           } else {
4332             LLDB_LOGF(log,
4333                       "ProcessGDBRemote::ParseRegisters unhandled reg "
4334                       "attribute %s = %s",
4335                       name.data(), value.data());
4336           }
4337           return true; // Keep iterating through all attributes
4338         });
4339 
4340         if (!gdb_type.empty()) {
4341           // gdb_type could reference some flags type defined in XML.
4342           llvm::StringMap<std::unique_ptr<RegisterFlags>>::iterator it =
4343               registers_flags_types.find(gdb_type);
4344           if (it != registers_flags_types.end()) {
4345             auto flags_type = it->second.get();
4346             if (reg_info.byte_size == flags_type->GetSize())
4347               reg_info.flags_type = flags_type;
4348             else
4349               LLDB_LOGF(log,
4350                         "ProcessGDBRemote::ParseRegisters Size of register "
4351                         "flags %s (%d bytes) for "
4352                         "register %s does not match the register size (%d "
4353                         "bytes). Ignoring this set of flags.",
4354                         flags_type->GetID().c_str(), flags_type->GetSize(),
4355                         reg_info.name.AsCString(), reg_info.byte_size);
4356           }
4357 
4358           // There's a slim chance that the gdb_type name is both a flags type
4359           // and a simple type. Just in case, look for that too (setting both
4360           // does no harm).
4361           if (!gdb_type.empty() && !(encoding_set || format_set)) {
4362             if (llvm::StringRef(gdb_type).startswith("int")) {
4363               reg_info.format = eFormatHex;
4364               reg_info.encoding = eEncodingUint;
4365             } else if (gdb_type == "data_ptr" || gdb_type == "code_ptr") {
4366               reg_info.format = eFormatAddressInfo;
4367               reg_info.encoding = eEncodingUint;
4368             } else if (gdb_type == "float") {
4369               reg_info.format = eFormatFloat;
4370               reg_info.encoding = eEncodingIEEE754;
4371             } else if (gdb_type == "aarch64v" ||
4372                        llvm::StringRef(gdb_type).startswith("vec") ||
4373                        gdb_type == "i387_ext" || gdb_type == "uint128") {
4374               // lldb doesn't handle 128-bit uints correctly (for ymm*h), so
4375               // treat them as vector (similarly to xmm/ymm)
4376               reg_info.format = eFormatVectorOfUInt8;
4377               reg_info.encoding = eEncodingVector;
4378             } else {
4379               LLDB_LOGF(
4380                   log,
4381                   "ProcessGDBRemote::ParseRegisters Could not determine lldb"
4382                   "format and encoding for gdb type %s",
4383                   gdb_type.c_str());
4384             }
4385           }
4386         }
4387 
4388         // Only update the register set name if we didn't get a "reg_set"
4389         // attribute. "set_name" will be empty if we didn't have a "reg_set"
4390         // attribute.
4391         if (!reg_info.set_name) {
4392           if (!gdb_group.empty()) {
4393             reg_info.set_name.SetCString(gdb_group.c_str());
4394           } else {
4395             // If no register group name provided anywhere,
4396             // we'll create a 'general' register set
4397             reg_info.set_name.SetCString("general");
4398           }
4399         }
4400 
4401         if (reg_info.byte_size == 0) {
4402           LLDB_LOGF(log,
4403                     "ProcessGDBRemote::%s Skipping zero bitsize register %s",
4404                     __FUNCTION__, reg_info.name.AsCString());
4405         } else
4406           registers.push_back(reg_info);
4407 
4408         return true; // Keep iterating through all "reg" elements
4409       });
4410   return true;
4411 }
4412 
4413 } // namespace
4414 
4415 // This method fetches a register description feature xml file from
4416 // the remote stub and adds registers/register groupsets/architecture
4417 // information to the current process.  It will call itself recursively
4418 // for nested register definition files.  It returns true if it was able
4419 // to fetch and parse an xml file.
4420 bool ProcessGDBRemote::GetGDBServerRegisterInfoXMLAndProcess(
4421     ArchSpec &arch_to_use, std::string xml_filename,
4422     std::vector<DynamicRegisterInfo::Register> &registers) {
4423   // request the target xml file
4424   llvm::Expected<std::string> raw = m_gdb_comm.ReadExtFeature("features", xml_filename);
4425   if (errorToBool(raw.takeError()))
4426     return false;
4427 
4428   XMLDocument xml_document;
4429 
4430   if (xml_document.ParseMemory(raw->c_str(), raw->size(),
4431                                xml_filename.c_str())) {
4432     GdbServerTargetInfo target_info;
4433     std::vector<XMLNode> feature_nodes;
4434 
4435     // The top level feature XML file will start with a <target> tag.
4436     XMLNode target_node = xml_document.GetRootElement("target");
4437     if (target_node) {
4438       target_node.ForEachChildElement([&target_info, &feature_nodes](
4439                                           const XMLNode &node) -> bool {
4440         llvm::StringRef name = node.GetName();
4441         if (name == "architecture") {
4442           node.GetElementText(target_info.arch);
4443         } else if (name == "osabi") {
4444           node.GetElementText(target_info.osabi);
4445         } else if (name == "xi:include" || name == "include") {
4446           std::string href = node.GetAttributeValue("href");
4447           if (!href.empty())
4448             target_info.includes.push_back(href);
4449         } else if (name == "feature") {
4450           feature_nodes.push_back(node);
4451         } else if (name == "groups") {
4452           node.ForEachChildElementWithName(
4453               "group", [&target_info](const XMLNode &node) -> bool {
4454                 uint32_t set_id = UINT32_MAX;
4455                 RegisterSetInfo set_info;
4456 
4457                 node.ForEachAttribute(
4458                     [&set_id, &set_info](const llvm::StringRef &name,
4459                                          const llvm::StringRef &value) -> bool {
4460                       // FIXME: we're silently ignoring invalid data here
4461                       if (name == "id")
4462                         llvm::to_integer(value, set_id);
4463                       if (name == "name")
4464                         set_info.name = ConstString(value);
4465                       return true; // Keep iterating through all attributes
4466                     });
4467 
4468                 if (set_id != UINT32_MAX)
4469                   target_info.reg_set_map[set_id] = set_info;
4470                 return true; // Keep iterating through all "group" elements
4471               });
4472         }
4473         return true; // Keep iterating through all children of the target_node
4474       });
4475     } else {
4476       // In an included XML feature file, we're already "inside" the <target>
4477       // tag of the initial XML file; this included file will likely only have
4478       // a <feature> tag.  Need to check for any more included files in this
4479       // <feature> element.
4480       XMLNode feature_node = xml_document.GetRootElement("feature");
4481       if (feature_node) {
4482         feature_nodes.push_back(feature_node);
4483         feature_node.ForEachChildElement([&target_info](
4484                                         const XMLNode &node) -> bool {
4485           llvm::StringRef name = node.GetName();
4486           if (name == "xi:include" || name == "include") {
4487             std::string href = node.GetAttributeValue("href");
4488             if (!href.empty())
4489               target_info.includes.push_back(href);
4490             }
4491             return true;
4492           });
4493       }
4494     }
4495 
4496     // gdbserver does not implement the LLDB packets used to determine host
4497     // or process architecture.  If that is the case, attempt to use
4498     // the <architecture/> field from target.xml, e.g.:
4499     //
4500     //   <architecture>i386:x86-64</architecture> (seen from VMWare ESXi)
4501     //   <architecture>arm</architecture> (seen from Segger JLink on unspecified
4502     //   arm board)
4503     if (!arch_to_use.IsValid() && !target_info.arch.empty()) {
4504       // We don't have any information about vendor or OS.
4505       arch_to_use.SetTriple(llvm::StringSwitch<std::string>(target_info.arch)
4506                                 .Case("i386:x86-64", "x86_64")
4507                                 .Default(target_info.arch) +
4508                             "--");
4509 
4510       if (arch_to_use.IsValid())
4511         GetTarget().MergeArchitecture(arch_to_use);
4512     }
4513 
4514     if (arch_to_use.IsValid()) {
4515       for (auto &feature_node : feature_nodes) {
4516         ParseRegisters(feature_node, target_info, registers,
4517                        m_registers_flags_types);
4518       }
4519 
4520       for (const auto &include : target_info.includes) {
4521         GetGDBServerRegisterInfoXMLAndProcess(arch_to_use, include,
4522                                               registers);
4523       }
4524     }
4525   } else {
4526     return false;
4527   }
4528   return true;
4529 }
4530 
4531 void ProcessGDBRemote::AddRemoteRegisters(
4532     std::vector<DynamicRegisterInfo::Register> &registers,
4533     const ArchSpec &arch_to_use) {
4534   std::map<uint32_t, uint32_t> remote_to_local_map;
4535   uint32_t remote_regnum = 0;
4536   for (auto it : llvm::enumerate(registers)) {
4537     DynamicRegisterInfo::Register &remote_reg_info = it.value();
4538 
4539     // Assign successive remote regnums if missing.
4540     if (remote_reg_info.regnum_remote == LLDB_INVALID_REGNUM)
4541       remote_reg_info.regnum_remote = remote_regnum;
4542 
4543     // Create a mapping from remote to local regnos.
4544     remote_to_local_map[remote_reg_info.regnum_remote] = it.index();
4545 
4546     remote_regnum = remote_reg_info.regnum_remote + 1;
4547   }
4548 
4549   for (DynamicRegisterInfo::Register &remote_reg_info : registers) {
4550     auto proc_to_lldb = [&remote_to_local_map](uint32_t process_regnum) {
4551       auto lldb_regit = remote_to_local_map.find(process_regnum);
4552       return lldb_regit != remote_to_local_map.end() ? lldb_regit->second
4553                                                      : LLDB_INVALID_REGNUM;
4554     };
4555 
4556     llvm::transform(remote_reg_info.value_regs,
4557                     remote_reg_info.value_regs.begin(), proc_to_lldb);
4558     llvm::transform(remote_reg_info.invalidate_regs,
4559                     remote_reg_info.invalidate_regs.begin(), proc_to_lldb);
4560   }
4561 
4562   // Don't use Process::GetABI, this code gets called from DidAttach, and
4563   // in that context we haven't set the Target's architecture yet, so the
4564   // ABI is also potentially incorrect.
4565   if (ABISP abi_sp = ABI::FindPlugin(shared_from_this(), arch_to_use))
4566     abi_sp->AugmentRegisterInfo(registers);
4567 
4568   m_register_info_sp->SetRegisterInfo(std::move(registers), arch_to_use);
4569 }
4570 
4571 // query the target of gdb-remote for extended target information returns
4572 // true on success (got register definitions), false on failure (did not).
4573 bool ProcessGDBRemote::GetGDBServerRegisterInfo(ArchSpec &arch_to_use) {
4574   // Make sure LLDB has an XML parser it can use first
4575   if (!XMLDocument::XMLEnabled())
4576     return false;
4577 
4578   // check that we have extended feature read support
4579   if (!m_gdb_comm.GetQXferFeaturesReadSupported())
4580     return false;
4581 
4582   // This holds register flags information for the whole of target.xml.
4583   // target.xml may include further documents that
4584   // GetGDBServerRegisterInfoXMLAndProcess will recurse to fetch and process.
4585   // That's why we clear the cache here, and not in
4586   // GetGDBServerRegisterInfoXMLAndProcess. To prevent it being cleared on every
4587   // include read.
4588   m_registers_flags_types.clear();
4589   std::vector<DynamicRegisterInfo::Register> registers;
4590   if (GetGDBServerRegisterInfoXMLAndProcess(arch_to_use, "target.xml",
4591                                             registers))
4592     AddRemoteRegisters(registers, arch_to_use);
4593 
4594   return m_register_info_sp->GetNumRegisters() > 0;
4595 }
4596 
4597 llvm::Expected<LoadedModuleInfoList> ProcessGDBRemote::GetLoadedModuleList() {
4598   // Make sure LLDB has an XML parser it can use first
4599   if (!XMLDocument::XMLEnabled())
4600     return llvm::createStringError(llvm::inconvertibleErrorCode(),
4601                                    "XML parsing not available");
4602 
4603   Log *log = GetLog(LLDBLog::Process);
4604   LLDB_LOGF(log, "ProcessGDBRemote::%s", __FUNCTION__);
4605 
4606   LoadedModuleInfoList list;
4607   GDBRemoteCommunicationClient &comm = m_gdb_comm;
4608   bool can_use_svr4 = GetGlobalPluginProperties().GetUseSVR4();
4609 
4610   // check that we have extended feature read support
4611   if (can_use_svr4 && comm.GetQXferLibrariesSVR4ReadSupported()) {
4612     // request the loaded library list
4613     llvm::Expected<std::string> raw = comm.ReadExtFeature("libraries-svr4", "");
4614     if (!raw)
4615       return raw.takeError();
4616 
4617     // parse the xml file in memory
4618     LLDB_LOGF(log, "parsing: %s", raw->c_str());
4619     XMLDocument doc;
4620 
4621     if (!doc.ParseMemory(raw->c_str(), raw->size(), "noname.xml"))
4622       return llvm::createStringError(llvm::inconvertibleErrorCode(),
4623                                      "Error reading noname.xml");
4624 
4625     XMLNode root_element = doc.GetRootElement("library-list-svr4");
4626     if (!root_element)
4627       return llvm::createStringError(
4628           llvm::inconvertibleErrorCode(),
4629           "Error finding library-list-svr4 xml element");
4630 
4631     // main link map structure
4632     std::string main_lm = root_element.GetAttributeValue("main-lm");
4633     // FIXME: we're silently ignoring invalid data here
4634     if (!main_lm.empty())
4635       llvm::to_integer(main_lm, list.m_link_map);
4636 
4637     root_element.ForEachChildElementWithName(
4638         "library", [log, &list](const XMLNode &library) -> bool {
4639           LoadedModuleInfoList::LoadedModuleInfo module;
4640 
4641           // FIXME: we're silently ignoring invalid data here
4642           library.ForEachAttribute(
4643               [&module](const llvm::StringRef &name,
4644                         const llvm::StringRef &value) -> bool {
4645                 uint64_t uint_value = LLDB_INVALID_ADDRESS;
4646                 if (name == "name")
4647                   module.set_name(value.str());
4648                 else if (name == "lm") {
4649                   // the address of the link_map struct.
4650                   llvm::to_integer(value, uint_value);
4651                   module.set_link_map(uint_value);
4652                 } else if (name == "l_addr") {
4653                   // the displacement as read from the field 'l_addr' of the
4654                   // link_map struct.
4655                   llvm::to_integer(value, uint_value);
4656                   module.set_base(uint_value);
4657                   // base address is always a displacement, not an absolute
4658                   // value.
4659                   module.set_base_is_offset(true);
4660                 } else if (name == "l_ld") {
4661                   // the memory address of the libraries PT_DYNAMIC section.
4662                   llvm::to_integer(value, uint_value);
4663                   module.set_dynamic(uint_value);
4664                 }
4665 
4666                 return true; // Keep iterating over all properties of "library"
4667               });
4668 
4669           if (log) {
4670             std::string name;
4671             lldb::addr_t lm = 0, base = 0, ld = 0;
4672             bool base_is_offset;
4673 
4674             module.get_name(name);
4675             module.get_link_map(lm);
4676             module.get_base(base);
4677             module.get_base_is_offset(base_is_offset);
4678             module.get_dynamic(ld);
4679 
4680             LLDB_LOGF(log,
4681                       "found (link_map:0x%08" PRIx64 ", base:0x%08" PRIx64
4682                       "[%s], ld:0x%08" PRIx64 ", name:'%s')",
4683                       lm, base, (base_is_offset ? "offset" : "absolute"), ld,
4684                       name.c_str());
4685           }
4686 
4687           list.add(module);
4688           return true; // Keep iterating over all "library" elements in the root
4689                        // node
4690         });
4691 
4692     if (log)
4693       LLDB_LOGF(log, "found %" PRId32 " modules in total",
4694                 (int)list.m_list.size());
4695     return list;
4696   } else if (comm.GetQXferLibrariesReadSupported()) {
4697     // request the loaded library list
4698     llvm::Expected<std::string> raw = comm.ReadExtFeature("libraries", "");
4699 
4700     if (!raw)
4701       return raw.takeError();
4702 
4703     LLDB_LOGF(log, "parsing: %s", raw->c_str());
4704     XMLDocument doc;
4705 
4706     if (!doc.ParseMemory(raw->c_str(), raw->size(), "noname.xml"))
4707       return llvm::createStringError(llvm::inconvertibleErrorCode(),
4708                                      "Error reading noname.xml");
4709 
4710     XMLNode root_element = doc.GetRootElement("library-list");
4711     if (!root_element)
4712       return llvm::createStringError(llvm::inconvertibleErrorCode(),
4713                                      "Error finding library-list xml element");
4714 
4715     // FIXME: we're silently ignoring invalid data here
4716     root_element.ForEachChildElementWithName(
4717         "library", [log, &list](const XMLNode &library) -> bool {
4718           LoadedModuleInfoList::LoadedModuleInfo module;
4719 
4720           std::string name = library.GetAttributeValue("name");
4721           module.set_name(name);
4722 
4723           // The base address of a given library will be the address of its
4724           // first section. Most remotes send only one section for Windows
4725           // targets for example.
4726           const XMLNode &section =
4727               library.FindFirstChildElementWithName("section");
4728           std::string address = section.GetAttributeValue("address");
4729           uint64_t address_value = LLDB_INVALID_ADDRESS;
4730           llvm::to_integer(address, address_value);
4731           module.set_base(address_value);
4732           // These addresses are absolute values.
4733           module.set_base_is_offset(false);
4734 
4735           if (log) {
4736             std::string name;
4737             lldb::addr_t base = 0;
4738             bool base_is_offset;
4739             module.get_name(name);
4740             module.get_base(base);
4741             module.get_base_is_offset(base_is_offset);
4742 
4743             LLDB_LOGF(log, "found (base:0x%08" PRIx64 "[%s], name:'%s')", base,
4744                       (base_is_offset ? "offset" : "absolute"), name.c_str());
4745           }
4746 
4747           list.add(module);
4748           return true; // Keep iterating over all "library" elements in the root
4749                        // node
4750         });
4751 
4752     if (log)
4753       LLDB_LOGF(log, "found %" PRId32 " modules in total",
4754                 (int)list.m_list.size());
4755     return list;
4756   } else {
4757     return llvm::createStringError(llvm::inconvertibleErrorCode(),
4758                                    "Remote libraries not supported");
4759   }
4760 }
4761 
4762 lldb::ModuleSP ProcessGDBRemote::LoadModuleAtAddress(const FileSpec &file,
4763                                                      lldb::addr_t link_map,
4764                                                      lldb::addr_t base_addr,
4765                                                      bool value_is_offset) {
4766   DynamicLoader *loader = GetDynamicLoader();
4767   if (!loader)
4768     return nullptr;
4769 
4770   return loader->LoadModuleAtAddress(file, link_map, base_addr,
4771                                      value_is_offset);
4772 }
4773 
4774 llvm::Error ProcessGDBRemote::LoadModules() {
4775   using lldb_private::process_gdb_remote::ProcessGDBRemote;
4776 
4777   // request a list of loaded libraries from GDBServer
4778   llvm::Expected<LoadedModuleInfoList> module_list = GetLoadedModuleList();
4779   if (!module_list)
4780     return module_list.takeError();
4781 
4782   // get a list of all the modules
4783   ModuleList new_modules;
4784 
4785   for (LoadedModuleInfoList::LoadedModuleInfo &modInfo : module_list->m_list) {
4786     std::string mod_name;
4787     lldb::addr_t mod_base;
4788     lldb::addr_t link_map;
4789     bool mod_base_is_offset;
4790 
4791     bool valid = true;
4792     valid &= modInfo.get_name(mod_name);
4793     valid &= modInfo.get_base(mod_base);
4794     valid &= modInfo.get_base_is_offset(mod_base_is_offset);
4795     if (!valid)
4796       continue;
4797 
4798     if (!modInfo.get_link_map(link_map))
4799       link_map = LLDB_INVALID_ADDRESS;
4800 
4801     FileSpec file(mod_name);
4802     FileSystem::Instance().Resolve(file);
4803     lldb::ModuleSP module_sp =
4804         LoadModuleAtAddress(file, link_map, mod_base, mod_base_is_offset);
4805 
4806     if (module_sp.get())
4807       new_modules.Append(module_sp);
4808   }
4809 
4810   if (new_modules.GetSize() > 0) {
4811     ModuleList removed_modules;
4812     Target &target = GetTarget();
4813     ModuleList &loaded_modules = m_process->GetTarget().GetImages();
4814 
4815     for (size_t i = 0; i < loaded_modules.GetSize(); ++i) {
4816       const lldb::ModuleSP loaded_module = loaded_modules.GetModuleAtIndex(i);
4817 
4818       bool found = false;
4819       for (size_t j = 0; j < new_modules.GetSize(); ++j) {
4820         if (new_modules.GetModuleAtIndex(j).get() == loaded_module.get())
4821           found = true;
4822       }
4823 
4824       // The main executable will never be included in libraries-svr4, don't
4825       // remove it
4826       if (!found &&
4827           loaded_module.get() != target.GetExecutableModulePointer()) {
4828         removed_modules.Append(loaded_module);
4829       }
4830     }
4831 
4832     loaded_modules.Remove(removed_modules);
4833     m_process->GetTarget().ModulesDidUnload(removed_modules, false);
4834 
4835     new_modules.ForEach([&target](const lldb::ModuleSP module_sp) -> bool {
4836       lldb_private::ObjectFile *obj = module_sp->GetObjectFile();
4837       if (!obj)
4838         return true;
4839 
4840       if (obj->GetType() != ObjectFile::Type::eTypeExecutable)
4841         return true;
4842 
4843       lldb::ModuleSP module_copy_sp = module_sp;
4844       target.SetExecutableModule(module_copy_sp, eLoadDependentsNo);
4845       return false;
4846     });
4847 
4848     loaded_modules.AppendIfNeeded(new_modules);
4849     m_process->GetTarget().ModulesDidLoad(new_modules);
4850   }
4851 
4852   return llvm::ErrorSuccess();
4853 }
4854 
4855 Status ProcessGDBRemote::GetFileLoadAddress(const FileSpec &file,
4856                                             bool &is_loaded,
4857                                             lldb::addr_t &load_addr) {
4858   is_loaded = false;
4859   load_addr = LLDB_INVALID_ADDRESS;
4860 
4861   std::string file_path = file.GetPath(false);
4862   if (file_path.empty())
4863     return Status("Empty file name specified");
4864 
4865   StreamString packet;
4866   packet.PutCString("qFileLoadAddress:");
4867   packet.PutStringAsRawHex8(file_path);
4868 
4869   StringExtractorGDBRemote response;
4870   if (m_gdb_comm.SendPacketAndWaitForResponse(packet.GetString(), response) !=
4871       GDBRemoteCommunication::PacketResult::Success)
4872     return Status("Sending qFileLoadAddress packet failed");
4873 
4874   if (response.IsErrorResponse()) {
4875     if (response.GetError() == 1) {
4876       // The file is not loaded into the inferior
4877       is_loaded = false;
4878       load_addr = LLDB_INVALID_ADDRESS;
4879       return Status();
4880     }
4881 
4882     return Status(
4883         "Fetching file load address from remote server returned an error");
4884   }
4885 
4886   if (response.IsNormalResponse()) {
4887     is_loaded = true;
4888     load_addr = response.GetHexMaxU64(false, LLDB_INVALID_ADDRESS);
4889     return Status();
4890   }
4891 
4892   return Status(
4893       "Unknown error happened during sending the load address packet");
4894 }
4895 
4896 void ProcessGDBRemote::ModulesDidLoad(ModuleList &module_list) {
4897   // We must call the lldb_private::Process::ModulesDidLoad () first before we
4898   // do anything
4899   Process::ModulesDidLoad(module_list);
4900 
4901   // After loading shared libraries, we can ask our remote GDB server if it
4902   // needs any symbols.
4903   m_gdb_comm.ServeSymbolLookups(this);
4904 }
4905 
4906 void ProcessGDBRemote::HandleAsyncStdout(llvm::StringRef out) {
4907   AppendSTDOUT(out.data(), out.size());
4908 }
4909 
4910 static const char *end_delimiter = "--end--;";
4911 static const int end_delimiter_len = 8;
4912 
4913 void ProcessGDBRemote::HandleAsyncMisc(llvm::StringRef data) {
4914   std::string input = data.str(); // '1' to move beyond 'A'
4915   if (m_partial_profile_data.length() > 0) {
4916     m_partial_profile_data.append(input);
4917     input = m_partial_profile_data;
4918     m_partial_profile_data.clear();
4919   }
4920 
4921   size_t found, pos = 0, len = input.length();
4922   while ((found = input.find(end_delimiter, pos)) != std::string::npos) {
4923     StringExtractorGDBRemote profileDataExtractor(
4924         input.substr(pos, found).c_str());
4925     std::string profile_data =
4926         HarmonizeThreadIdsForProfileData(profileDataExtractor);
4927     BroadcastAsyncProfileData(profile_data);
4928 
4929     pos = found + end_delimiter_len;
4930   }
4931 
4932   if (pos < len) {
4933     // Last incomplete chunk.
4934     m_partial_profile_data = input.substr(pos);
4935   }
4936 }
4937 
4938 std::string ProcessGDBRemote::HarmonizeThreadIdsForProfileData(
4939     StringExtractorGDBRemote &profileDataExtractor) {
4940   std::map<uint64_t, uint32_t> new_thread_id_to_used_usec_map;
4941   std::string output;
4942   llvm::raw_string_ostream output_stream(output);
4943   llvm::StringRef name, value;
4944 
4945   // Going to assuming thread_used_usec comes first, else bail out.
4946   while (profileDataExtractor.GetNameColonValue(name, value)) {
4947     if (name.compare("thread_used_id") == 0) {
4948       StringExtractor threadIDHexExtractor(value);
4949       uint64_t thread_id = threadIDHexExtractor.GetHexMaxU64(false, 0);
4950 
4951       bool has_used_usec = false;
4952       uint32_t curr_used_usec = 0;
4953       llvm::StringRef usec_name, usec_value;
4954       uint32_t input_file_pos = profileDataExtractor.GetFilePos();
4955       if (profileDataExtractor.GetNameColonValue(usec_name, usec_value)) {
4956         if (usec_name.equals("thread_used_usec")) {
4957           has_used_usec = true;
4958           usec_value.getAsInteger(0, curr_used_usec);
4959         } else {
4960           // We didn't find what we want, it is probably an older version. Bail
4961           // out.
4962           profileDataExtractor.SetFilePos(input_file_pos);
4963         }
4964       }
4965 
4966       if (has_used_usec) {
4967         uint32_t prev_used_usec = 0;
4968         std::map<uint64_t, uint32_t>::iterator iterator =
4969             m_thread_id_to_used_usec_map.find(thread_id);
4970         if (iterator != m_thread_id_to_used_usec_map.end()) {
4971           prev_used_usec = m_thread_id_to_used_usec_map[thread_id];
4972         }
4973 
4974         uint32_t real_used_usec = curr_used_usec - prev_used_usec;
4975         // A good first time record is one that runs for at least 0.25 sec
4976         bool good_first_time =
4977             (prev_used_usec == 0) && (real_used_usec > 250000);
4978         bool good_subsequent_time =
4979             (prev_used_usec > 0) &&
4980             ((real_used_usec > 0) || (HasAssignedIndexIDToThread(thread_id)));
4981 
4982         if (good_first_time || good_subsequent_time) {
4983           // We try to avoid doing too many index id reservation, resulting in
4984           // fast increase of index ids.
4985 
4986           output_stream << name << ":";
4987           int32_t index_id = AssignIndexIDToThread(thread_id);
4988           output_stream << index_id << ";";
4989 
4990           output_stream << usec_name << ":" << usec_value << ";";
4991         } else {
4992           // Skip past 'thread_used_name'.
4993           llvm::StringRef local_name, local_value;
4994           profileDataExtractor.GetNameColonValue(local_name, local_value);
4995         }
4996 
4997         // Store current time as previous time so that they can be compared
4998         // later.
4999         new_thread_id_to_used_usec_map[thread_id] = curr_used_usec;
5000       } else {
5001         // Bail out and use old string.
5002         output_stream << name << ":" << value << ";";
5003       }
5004     } else {
5005       output_stream << name << ":" << value << ";";
5006     }
5007   }
5008   output_stream << end_delimiter;
5009   m_thread_id_to_used_usec_map = new_thread_id_to_used_usec_map;
5010 
5011   return output_stream.str();
5012 }
5013 
5014 void ProcessGDBRemote::HandleStopReply() {
5015   if (GetStopID() != 0)
5016     return;
5017 
5018   if (GetID() == LLDB_INVALID_PROCESS_ID) {
5019     lldb::pid_t pid = m_gdb_comm.GetCurrentProcessID();
5020     if (pid != LLDB_INVALID_PROCESS_ID)
5021       SetID(pid);
5022   }
5023   BuildDynamicRegisterInfo(true);
5024 }
5025 
5026 llvm::Expected<bool> ProcessGDBRemote::SaveCore(llvm::StringRef outfile) {
5027   if (!m_gdb_comm.GetSaveCoreSupported())
5028     return false;
5029 
5030   StreamString packet;
5031   packet.PutCString("qSaveCore;path-hint:");
5032   packet.PutStringAsRawHex8(outfile);
5033 
5034   StringExtractorGDBRemote response;
5035   if (m_gdb_comm.SendPacketAndWaitForResponse(packet.GetString(), response) ==
5036       GDBRemoteCommunication::PacketResult::Success) {
5037     // TODO: grab error message from the packet?  StringExtractor seems to
5038     // be missing a method for that
5039     if (response.IsErrorResponse())
5040       return llvm::createStringError(
5041           llvm::inconvertibleErrorCode(),
5042           llvm::formatv("qSaveCore returned an error"));
5043 
5044     std::string path;
5045 
5046     // process the response
5047     for (auto x : llvm::split(response.GetStringRef(), ';')) {
5048       if (x.consume_front("core-path:"))
5049         StringExtractor(x).GetHexByteString(path);
5050     }
5051 
5052     // verify that we've gotten what we need
5053     if (path.empty())
5054       return llvm::createStringError(llvm::inconvertibleErrorCode(),
5055                                      "qSaveCore returned no core path");
5056 
5057     // now transfer the core file
5058     FileSpec remote_core{llvm::StringRef(path)};
5059     Platform &platform = *GetTarget().GetPlatform();
5060     Status error = platform.GetFile(remote_core, FileSpec(outfile));
5061 
5062     if (platform.IsRemote()) {
5063       // NB: we unlink the file on error too
5064       platform.Unlink(remote_core);
5065       if (error.Fail())
5066         return error.ToError();
5067     }
5068 
5069     return true;
5070   }
5071 
5072   return llvm::createStringError(llvm::inconvertibleErrorCode(),
5073                                  "Unable to send qSaveCore");
5074 }
5075 
5076 static const char *const s_async_json_packet_prefix = "JSON-async:";
5077 
5078 static StructuredData::ObjectSP
5079 ParseStructuredDataPacket(llvm::StringRef packet) {
5080   Log *log = GetLog(GDBRLog::Process);
5081 
5082   if (!packet.consume_front(s_async_json_packet_prefix)) {
5083     if (log) {
5084       LLDB_LOGF(
5085           log,
5086           "GDBRemoteCommunicationClientBase::%s() received $J packet "
5087           "but was not a StructuredData packet: packet starts with "
5088           "%s",
5089           __FUNCTION__,
5090           packet.slice(0, strlen(s_async_json_packet_prefix)).str().c_str());
5091     }
5092     return StructuredData::ObjectSP();
5093   }
5094 
5095   // This is an asynchronous JSON packet, destined for a StructuredDataPlugin.
5096   StructuredData::ObjectSP json_sp = StructuredData::ParseJSON(packet);
5097   if (log) {
5098     if (json_sp) {
5099       StreamString json_str;
5100       json_sp->Dump(json_str, true);
5101       json_str.Flush();
5102       LLDB_LOGF(log,
5103                 "ProcessGDBRemote::%s() "
5104                 "received Async StructuredData packet: %s",
5105                 __FUNCTION__, json_str.GetData());
5106     } else {
5107       LLDB_LOGF(log,
5108                 "ProcessGDBRemote::%s"
5109                 "() received StructuredData packet:"
5110                 " parse failure",
5111                 __FUNCTION__);
5112     }
5113   }
5114   return json_sp;
5115 }
5116 
5117 void ProcessGDBRemote::HandleAsyncStructuredDataPacket(llvm::StringRef data) {
5118   auto structured_data_sp = ParseStructuredDataPacket(data);
5119   if (structured_data_sp)
5120     RouteAsyncStructuredData(structured_data_sp);
5121 }
5122 
5123 class CommandObjectProcessGDBRemoteSpeedTest : public CommandObjectParsed {
5124 public:
5125   CommandObjectProcessGDBRemoteSpeedTest(CommandInterpreter &interpreter)
5126       : CommandObjectParsed(interpreter, "process plugin packet speed-test",
5127                             "Tests packet speeds of various sizes to determine "
5128                             "the performance characteristics of the GDB remote "
5129                             "connection. ",
5130                             nullptr),
5131         m_option_group(),
5132         m_num_packets(LLDB_OPT_SET_1, false, "count", 'c', 0, eArgTypeCount,
5133                       "The number of packets to send of each varying size "
5134                       "(default is 1000).",
5135                       1000),
5136         m_max_send(LLDB_OPT_SET_1, false, "max-send", 's', 0, eArgTypeCount,
5137                    "The maximum number of bytes to send in a packet. Sizes "
5138                    "increase in powers of 2 while the size is less than or "
5139                    "equal to this option value. (default 1024).",
5140                    1024),
5141         m_max_recv(LLDB_OPT_SET_1, false, "max-receive", 'r', 0, eArgTypeCount,
5142                    "The maximum number of bytes to receive in a packet. Sizes "
5143                    "increase in powers of 2 while the size is less than or "
5144                    "equal to this option value. (default 1024).",
5145                    1024),
5146         m_json(LLDB_OPT_SET_1, false, "json", 'j',
5147                "Print the output as JSON data for easy parsing.", false, true) {
5148     m_option_group.Append(&m_num_packets, LLDB_OPT_SET_ALL, LLDB_OPT_SET_1);
5149     m_option_group.Append(&m_max_send, LLDB_OPT_SET_ALL, LLDB_OPT_SET_1);
5150     m_option_group.Append(&m_max_recv, LLDB_OPT_SET_ALL, LLDB_OPT_SET_1);
5151     m_option_group.Append(&m_json, LLDB_OPT_SET_ALL, LLDB_OPT_SET_1);
5152     m_option_group.Finalize();
5153   }
5154 
5155   ~CommandObjectProcessGDBRemoteSpeedTest() override = default;
5156 
5157   Options *GetOptions() override { return &m_option_group; }
5158 
5159   bool DoExecute(Args &command, CommandReturnObject &result) override {
5160     const size_t argc = command.GetArgumentCount();
5161     if (argc == 0) {
5162       ProcessGDBRemote *process =
5163           (ProcessGDBRemote *)m_interpreter.GetExecutionContext()
5164               .GetProcessPtr();
5165       if (process) {
5166         StreamSP output_stream_sp(
5167             m_interpreter.GetDebugger().GetAsyncOutputStream());
5168         result.SetImmediateOutputStream(output_stream_sp);
5169 
5170         const uint32_t num_packets =
5171             (uint32_t)m_num_packets.GetOptionValue().GetCurrentValue();
5172         const uint64_t max_send = m_max_send.GetOptionValue().GetCurrentValue();
5173         const uint64_t max_recv = m_max_recv.GetOptionValue().GetCurrentValue();
5174         const bool json = m_json.GetOptionValue().GetCurrentValue();
5175         const uint64_t k_recv_amount =
5176             4 * 1024 * 1024; // Receive amount in bytes
5177         process->GetGDBRemote().TestPacketSpeed(
5178             num_packets, max_send, max_recv, k_recv_amount, json,
5179             output_stream_sp ? *output_stream_sp : result.GetOutputStream());
5180         result.SetStatus(eReturnStatusSuccessFinishResult);
5181         return true;
5182       }
5183     } else {
5184       result.AppendErrorWithFormat("'%s' takes no arguments",
5185                                    m_cmd_name.c_str());
5186     }
5187     result.SetStatus(eReturnStatusFailed);
5188     return false;
5189   }
5190 
5191 protected:
5192   OptionGroupOptions m_option_group;
5193   OptionGroupUInt64 m_num_packets;
5194   OptionGroupUInt64 m_max_send;
5195   OptionGroupUInt64 m_max_recv;
5196   OptionGroupBoolean m_json;
5197 };
5198 
5199 class CommandObjectProcessGDBRemotePacketHistory : public CommandObjectParsed {
5200 private:
5201 public:
5202   CommandObjectProcessGDBRemotePacketHistory(CommandInterpreter &interpreter)
5203       : CommandObjectParsed(interpreter, "process plugin packet history",
5204                             "Dumps the packet history buffer. ", nullptr) {}
5205 
5206   ~CommandObjectProcessGDBRemotePacketHistory() override = default;
5207 
5208   bool DoExecute(Args &command, CommandReturnObject &result) override {
5209     ProcessGDBRemote *process =
5210         (ProcessGDBRemote *)m_interpreter.GetExecutionContext().GetProcessPtr();
5211     if (process) {
5212       process->GetGDBRemote().DumpHistory(result.GetOutputStream());
5213       result.SetStatus(eReturnStatusSuccessFinishResult);
5214       return true;
5215     }
5216     result.SetStatus(eReturnStatusFailed);
5217     return false;
5218   }
5219 };
5220 
5221 class CommandObjectProcessGDBRemotePacketXferSize : public CommandObjectParsed {
5222 private:
5223 public:
5224   CommandObjectProcessGDBRemotePacketXferSize(CommandInterpreter &interpreter)
5225       : CommandObjectParsed(
5226             interpreter, "process plugin packet xfer-size",
5227             "Maximum size that lldb will try to read/write one one chunk.",
5228             nullptr) {
5229     CommandArgumentData max_arg{eArgTypeUnsignedInteger, eArgRepeatPlain};
5230     m_arguments.push_back({max_arg});
5231   }
5232 
5233   ~CommandObjectProcessGDBRemotePacketXferSize() override = default;
5234 
5235   bool DoExecute(Args &command, CommandReturnObject &result) override {
5236     const size_t argc = command.GetArgumentCount();
5237     if (argc == 0) {
5238       result.AppendErrorWithFormat("'%s' takes an argument to specify the max "
5239                                    "amount to be transferred when "
5240                                    "reading/writing",
5241                                    m_cmd_name.c_str());
5242       return false;
5243     }
5244 
5245     ProcessGDBRemote *process =
5246         (ProcessGDBRemote *)m_interpreter.GetExecutionContext().GetProcessPtr();
5247     if (process) {
5248       const char *packet_size = command.GetArgumentAtIndex(0);
5249       errno = 0;
5250       uint64_t user_specified_max = strtoul(packet_size, nullptr, 10);
5251       if (errno == 0 && user_specified_max != 0) {
5252         process->SetUserSpecifiedMaxMemoryTransferSize(user_specified_max);
5253         result.SetStatus(eReturnStatusSuccessFinishResult);
5254         return true;
5255       }
5256     }
5257     result.SetStatus(eReturnStatusFailed);
5258     return false;
5259   }
5260 };
5261 
5262 class CommandObjectProcessGDBRemotePacketSend : public CommandObjectParsed {
5263 private:
5264 public:
5265   CommandObjectProcessGDBRemotePacketSend(CommandInterpreter &interpreter)
5266       : CommandObjectParsed(interpreter, "process plugin packet send",
5267                             "Send a custom packet through the GDB remote "
5268                             "protocol and print the answer. "
5269                             "The packet header and footer will automatically "
5270                             "be added to the packet prior to sending and "
5271                             "stripped from the result.",
5272                             nullptr) {
5273     CommandArgumentData packet_arg{eArgTypeNone, eArgRepeatStar};
5274     m_arguments.push_back({packet_arg});
5275   }
5276 
5277   ~CommandObjectProcessGDBRemotePacketSend() override = default;
5278 
5279   bool DoExecute(Args &command, CommandReturnObject &result) override {
5280     const size_t argc = command.GetArgumentCount();
5281     if (argc == 0) {
5282       result.AppendErrorWithFormat(
5283           "'%s' takes a one or more packet content arguments",
5284           m_cmd_name.c_str());
5285       return false;
5286     }
5287 
5288     ProcessGDBRemote *process =
5289         (ProcessGDBRemote *)m_interpreter.GetExecutionContext().GetProcessPtr();
5290     if (process) {
5291       for (size_t i = 0; i < argc; ++i) {
5292         const char *packet_cstr = command.GetArgumentAtIndex(0);
5293         StringExtractorGDBRemote response;
5294         process->GetGDBRemote().SendPacketAndWaitForResponse(
5295             packet_cstr, response, process->GetInterruptTimeout());
5296         result.SetStatus(eReturnStatusSuccessFinishResult);
5297         Stream &output_strm = result.GetOutputStream();
5298         output_strm.Printf("  packet: %s\n", packet_cstr);
5299         std::string response_str = std::string(response.GetStringRef());
5300 
5301         if (strstr(packet_cstr, "qGetProfileData") != nullptr) {
5302           response_str = process->HarmonizeThreadIdsForProfileData(response);
5303         }
5304 
5305         if (response_str.empty())
5306           output_strm.PutCString("response: \nerror: UNIMPLEMENTED\n");
5307         else
5308           output_strm.Printf("response: %s\n", response.GetStringRef().data());
5309       }
5310     }
5311     return true;
5312   }
5313 };
5314 
5315 class CommandObjectProcessGDBRemotePacketMonitor : public CommandObjectRaw {
5316 private:
5317 public:
5318   CommandObjectProcessGDBRemotePacketMonitor(CommandInterpreter &interpreter)
5319       : CommandObjectRaw(interpreter, "process plugin packet monitor",
5320                          "Send a qRcmd packet through the GDB remote protocol "
5321                          "and print the response."
5322                          "The argument passed to this command will be hex "
5323                          "encoded into a valid 'qRcmd' packet, sent and the "
5324                          "response will be printed.") {}
5325 
5326   ~CommandObjectProcessGDBRemotePacketMonitor() override = default;
5327 
5328   bool DoExecute(llvm::StringRef command,
5329                  CommandReturnObject &result) override {
5330     if (command.empty()) {
5331       result.AppendErrorWithFormat("'%s' takes a command string argument",
5332                                    m_cmd_name.c_str());
5333       return false;
5334     }
5335 
5336     ProcessGDBRemote *process =
5337         (ProcessGDBRemote *)m_interpreter.GetExecutionContext().GetProcessPtr();
5338     if (process) {
5339       StreamString packet;
5340       packet.PutCString("qRcmd,");
5341       packet.PutBytesAsRawHex8(command.data(), command.size());
5342 
5343       StringExtractorGDBRemote response;
5344       Stream &output_strm = result.GetOutputStream();
5345       process->GetGDBRemote().SendPacketAndReceiveResponseWithOutputSupport(
5346           packet.GetString(), response, process->GetInterruptTimeout(),
5347           [&output_strm](llvm::StringRef output) { output_strm << output; });
5348       result.SetStatus(eReturnStatusSuccessFinishResult);
5349       output_strm.Printf("  packet: %s\n", packet.GetData());
5350       const std::string &response_str = std::string(response.GetStringRef());
5351 
5352       if (response_str.empty())
5353         output_strm.PutCString("response: \nerror: UNIMPLEMENTED\n");
5354       else
5355         output_strm.Printf("response: %s\n", response.GetStringRef().data());
5356     }
5357     return true;
5358   }
5359 };
5360 
5361 class CommandObjectProcessGDBRemotePacket : public CommandObjectMultiword {
5362 private:
5363 public:
5364   CommandObjectProcessGDBRemotePacket(CommandInterpreter &interpreter)
5365       : CommandObjectMultiword(interpreter, "process plugin packet",
5366                                "Commands that deal with GDB remote packets.",
5367                                nullptr) {
5368     LoadSubCommand(
5369         "history",
5370         CommandObjectSP(
5371             new CommandObjectProcessGDBRemotePacketHistory(interpreter)));
5372     LoadSubCommand(
5373         "send", CommandObjectSP(
5374                     new CommandObjectProcessGDBRemotePacketSend(interpreter)));
5375     LoadSubCommand(
5376         "monitor",
5377         CommandObjectSP(
5378             new CommandObjectProcessGDBRemotePacketMonitor(interpreter)));
5379     LoadSubCommand(
5380         "xfer-size",
5381         CommandObjectSP(
5382             new CommandObjectProcessGDBRemotePacketXferSize(interpreter)));
5383     LoadSubCommand("speed-test",
5384                    CommandObjectSP(new CommandObjectProcessGDBRemoteSpeedTest(
5385                        interpreter)));
5386   }
5387 
5388   ~CommandObjectProcessGDBRemotePacket() override = default;
5389 };
5390 
5391 class CommandObjectMultiwordProcessGDBRemote : public CommandObjectMultiword {
5392 public:
5393   CommandObjectMultiwordProcessGDBRemote(CommandInterpreter &interpreter)
5394       : CommandObjectMultiword(
5395             interpreter, "process plugin",
5396             "Commands for operating on a ProcessGDBRemote process.",
5397             "process plugin <subcommand> [<subcommand-options>]") {
5398     LoadSubCommand(
5399         "packet",
5400         CommandObjectSP(new CommandObjectProcessGDBRemotePacket(interpreter)));
5401   }
5402 
5403   ~CommandObjectMultiwordProcessGDBRemote() override = default;
5404 };
5405 
5406 CommandObject *ProcessGDBRemote::GetPluginCommandObject() {
5407   if (!m_command_sp)
5408     m_command_sp = std::make_shared<CommandObjectMultiwordProcessGDBRemote>(
5409         GetTarget().GetDebugger().GetCommandInterpreter());
5410   return m_command_sp.get();
5411 }
5412 
5413 void ProcessGDBRemote::DidForkSwitchSoftwareBreakpoints(bool enable) {
5414   GetBreakpointSiteList().ForEach([this, enable](BreakpointSite *bp_site) {
5415     if (bp_site->IsEnabled() &&
5416         (bp_site->GetType() == BreakpointSite::eSoftware ||
5417          bp_site->GetType() == BreakpointSite::eExternal)) {
5418       m_gdb_comm.SendGDBStoppointTypePacket(
5419           eBreakpointSoftware, enable, bp_site->GetLoadAddress(),
5420           GetSoftwareBreakpointTrapOpcode(bp_site), GetInterruptTimeout());
5421     }
5422   });
5423 }
5424 
5425 void ProcessGDBRemote::DidForkSwitchHardwareTraps(bool enable) {
5426   if (m_gdb_comm.SupportsGDBStoppointPacket(eBreakpointHardware)) {
5427     GetBreakpointSiteList().ForEach([this, enable](BreakpointSite *bp_site) {
5428       if (bp_site->IsEnabled() &&
5429           bp_site->GetType() == BreakpointSite::eHardware) {
5430         m_gdb_comm.SendGDBStoppointTypePacket(
5431             eBreakpointHardware, enable, bp_site->GetLoadAddress(),
5432             GetSoftwareBreakpointTrapOpcode(bp_site), GetInterruptTimeout());
5433       }
5434     });
5435   }
5436 
5437   WatchpointList &wps = GetTarget().GetWatchpointList();
5438   size_t wp_count = wps.GetSize();
5439   for (size_t i = 0; i < wp_count; ++i) {
5440     WatchpointSP wp = wps.GetByIndex(i);
5441     if (wp->IsEnabled()) {
5442       GDBStoppointType type = GetGDBStoppointType(wp.get());
5443       m_gdb_comm.SendGDBStoppointTypePacket(type, enable, wp->GetLoadAddress(),
5444                                             wp->GetByteSize(),
5445                                             GetInterruptTimeout());
5446     }
5447   }
5448 }
5449 
5450 void ProcessGDBRemote::DidFork(lldb::pid_t child_pid, lldb::tid_t child_tid) {
5451   Log *log = GetLog(GDBRLog::Process);
5452 
5453   lldb::pid_t parent_pid = m_gdb_comm.GetCurrentProcessID();
5454   // Any valid TID will suffice, thread-relevant actions will set a proper TID
5455   // anyway.
5456   lldb::tid_t parent_tid = m_thread_ids.front();
5457 
5458   lldb::pid_t follow_pid, detach_pid;
5459   lldb::tid_t follow_tid, detach_tid;
5460 
5461   switch (GetFollowForkMode()) {
5462   case eFollowParent:
5463     follow_pid = parent_pid;
5464     follow_tid = parent_tid;
5465     detach_pid = child_pid;
5466     detach_tid = child_tid;
5467     break;
5468   case eFollowChild:
5469     follow_pid = child_pid;
5470     follow_tid = child_tid;
5471     detach_pid = parent_pid;
5472     detach_tid = parent_tid;
5473     break;
5474   }
5475 
5476   // Switch to the process that is going to be detached.
5477   if (!m_gdb_comm.SetCurrentThread(detach_tid, detach_pid)) {
5478     LLDB_LOG(log, "ProcessGDBRemote::DidFork() unable to set pid/tid");
5479     return;
5480   }
5481 
5482   // Disable all software breakpoints in the forked process.
5483   if (m_gdb_comm.SupportsGDBStoppointPacket(eBreakpointSoftware))
5484     DidForkSwitchSoftwareBreakpoints(false);
5485 
5486   // Remove hardware breakpoints / watchpoints from parent process if we're
5487   // following child.
5488   if (GetFollowForkMode() == eFollowChild)
5489     DidForkSwitchHardwareTraps(false);
5490 
5491   // Switch to the process that is going to be followed
5492   if (!m_gdb_comm.SetCurrentThread(follow_tid, follow_pid) ||
5493       !m_gdb_comm.SetCurrentThreadForRun(follow_tid, follow_pid)) {
5494     LLDB_LOG(log, "ProcessGDBRemote::DidFork() unable to reset pid/tid");
5495     return;
5496   }
5497 
5498   LLDB_LOG(log, "Detaching process {0}", detach_pid);
5499   Status error = m_gdb_comm.Detach(false, detach_pid);
5500   if (error.Fail()) {
5501     LLDB_LOG(log, "ProcessGDBRemote::DidFork() detach packet send failed: {0}",
5502              error.AsCString() ? error.AsCString() : "<unknown error>");
5503     return;
5504   }
5505 
5506   // Hardware breakpoints/watchpoints are not inherited implicitly,
5507   // so we need to readd them if we're following child.
5508   if (GetFollowForkMode() == eFollowChild) {
5509     DidForkSwitchHardwareTraps(true);
5510     // Update our PID
5511     SetID(child_pid);
5512   }
5513 }
5514 
5515 void ProcessGDBRemote::DidVFork(lldb::pid_t child_pid, lldb::tid_t child_tid) {
5516   Log *log = GetLog(GDBRLog::Process);
5517 
5518   assert(!m_vfork_in_progress);
5519   m_vfork_in_progress = true;
5520 
5521   // Disable all software breakpoints for the duration of vfork.
5522   if (m_gdb_comm.SupportsGDBStoppointPacket(eBreakpointSoftware))
5523     DidForkSwitchSoftwareBreakpoints(false);
5524 
5525   lldb::pid_t detach_pid;
5526   lldb::tid_t detach_tid;
5527 
5528   switch (GetFollowForkMode()) {
5529   case eFollowParent:
5530     detach_pid = child_pid;
5531     detach_tid = child_tid;
5532     break;
5533   case eFollowChild:
5534     detach_pid = m_gdb_comm.GetCurrentProcessID();
5535     // Any valid TID will suffice, thread-relevant actions will set a proper TID
5536     // anyway.
5537     detach_tid = m_thread_ids.front();
5538 
5539     // Switch to the parent process before detaching it.
5540     if (!m_gdb_comm.SetCurrentThread(detach_tid, detach_pid)) {
5541       LLDB_LOG(log, "ProcessGDBRemote::DidFork() unable to set pid/tid");
5542       return;
5543     }
5544 
5545     // Remove hardware breakpoints / watchpoints from the parent process.
5546     DidForkSwitchHardwareTraps(false);
5547 
5548     // Switch to the child process.
5549     if (!m_gdb_comm.SetCurrentThread(child_tid, child_pid) ||
5550         !m_gdb_comm.SetCurrentThreadForRun(child_tid, child_pid)) {
5551       LLDB_LOG(log, "ProcessGDBRemote::DidFork() unable to reset pid/tid");
5552       return;
5553     }
5554     break;
5555   }
5556 
5557   LLDB_LOG(log, "Detaching process {0}", detach_pid);
5558   Status error = m_gdb_comm.Detach(false, detach_pid);
5559   if (error.Fail()) {
5560       LLDB_LOG(log,
5561                "ProcessGDBRemote::DidFork() detach packet send failed: {0}",
5562                 error.AsCString() ? error.AsCString() : "<unknown error>");
5563       return;
5564   }
5565 
5566   if (GetFollowForkMode() == eFollowChild) {
5567     // Update our PID
5568     SetID(child_pid);
5569   }
5570 }
5571 
5572 void ProcessGDBRemote::DidVForkDone() {
5573   assert(m_vfork_in_progress);
5574   m_vfork_in_progress = false;
5575 
5576   // Reenable all software breakpoints that were enabled before vfork.
5577   if (m_gdb_comm.SupportsGDBStoppointPacket(eBreakpointSoftware))
5578     DidForkSwitchSoftwareBreakpoints(true);
5579 }
5580 
5581 void ProcessGDBRemote::DidExec() {
5582   // If we are following children, vfork is finished by exec (rather than
5583   // vforkdone that is submitted for parent).
5584   if (GetFollowForkMode() == eFollowChild)
5585     m_vfork_in_progress = false;
5586   Process::DidExec();
5587 }
5588