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