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