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