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