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