xref: /llvm-project/lldb/source/Plugins/Process/gdb-remote/ProcessGDBRemote.cpp (revision ec3e290502db5ab7dbaa067e674c5ee6cb34ac10)
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/State.h"
64 #include "lldb/Utility/StreamString.h"
65 #include "lldb/Utility/Timer.h"
66 #include <algorithm>
67 #include <csignal>
68 #include <map>
69 #include <memory>
70 #include <mutex>
71 #include <sstream>
72 #include <thread>
73 
74 #include "GDBRemoteRegisterContext.h"
75 #include "GDBRemoteRegisterFallback.h"
76 #include "Plugins/Process/Utility/GDBRemoteSignals.h"
77 #include "Plugins/Process/Utility/InferiorCallPOSIX.h"
78 #include "Plugins/Process/Utility/StopInfoMachException.h"
79 #include "ProcessGDBRemote.h"
80 #include "ProcessGDBRemoteLog.h"
81 #include "ThreadGDBRemote.h"
82 #include "lldb/Host/Host.h"
83 #include "lldb/Utility/StringExtractorGDBRemote.h"
84 
85 #include "llvm/ADT/ScopeExit.h"
86 #include "llvm/ADT/StringSwitch.h"
87 #include "llvm/Support/Threading.h"
88 #include "llvm/Support/raw_ostream.h"
89 
90 #define DEBUGSERVER_BASENAME "debugserver"
91 using namespace lldb;
92 using namespace lldb_private;
93 using namespace lldb_private::process_gdb_remote;
94 
95 LLDB_PLUGIN_DEFINE(ProcessGDBRemote)
96 
97 namespace lldb {
98 // Provide a function that can easily dump the packet history if we know a
99 // ProcessGDBRemote * value (which we can get from logs or from debugging). We
100 // need the function in the lldb namespace so it makes it into the final
101 // executable since the LLDB shared library only exports stuff in the lldb
102 // namespace. This allows you to attach with a debugger and call this function
103 // and get the packet history dumped to a file.
104 void DumpProcessGDBRemotePacketHistory(void *p, const char *path) {
105   auto file = FileSystem::Instance().Open(
106       FileSpec(path), File::eOpenOptionWriteOnly | File::eOpenOptionCanCreate);
107   if (!file) {
108     llvm::consumeError(file.takeError());
109     return;
110   }
111   StreamFile stream(std::move(file.get()));
112   ((ProcessGDBRemote *)p)->GetGDBRemote().DumpHistory(stream);
113 }
114 } // namespace lldb
115 
116 namespace {
117 
118 #define LLDB_PROPERTIES_processgdbremote
119 #include "ProcessGDBRemoteProperties.inc"
120 
121 enum {
122 #define LLDB_PROPERTIES_processgdbremote
123 #include "ProcessGDBRemotePropertiesEnum.inc"
124 };
125 
126 class PluginProperties : public Properties {
127 public:
128   static ConstString GetSettingName() {
129     return ConstString(ProcessGDBRemote::GetPluginNameStatic());
130   }
131 
132   PluginProperties() : Properties() {
133     m_collection_sp = std::make_shared<OptionValueProperties>(GetSettingName());
134     m_collection_sp->Initialize(g_processgdbremote_properties);
135   }
136 
137   ~PluginProperties() override = default;
138 
139   uint64_t GetPacketTimeout() {
140     const uint32_t idx = ePropertyPacketTimeout;
141     return m_collection_sp->GetPropertyAtIndexAsUInt64(
142         nullptr, idx, g_processgdbremote_properties[idx].default_uint_value);
143   }
144 
145   bool SetPacketTimeout(uint64_t timeout) {
146     const uint32_t idx = ePropertyPacketTimeout;
147     return m_collection_sp->SetPropertyAtIndexAsUInt64(nullptr, idx, timeout);
148   }
149 
150   FileSpec GetTargetDefinitionFile() const {
151     const uint32_t idx = ePropertyTargetDefinitionFile;
152     return m_collection_sp->GetPropertyAtIndexAsFileSpec(nullptr, idx);
153   }
154 
155   bool GetUseSVR4() const {
156     const uint32_t idx = ePropertyUseSVR4;
157     return m_collection_sp->GetPropertyAtIndexAsBoolean(
158         nullptr, idx,
159         g_processgdbremote_properties[idx].default_uint_value != 0);
160   }
161 
162   bool GetUseGPacketForReading() const {
163     const uint32_t idx = ePropertyUseGPacketForReading;
164     return m_collection_sp->GetPropertyAtIndexAsBoolean(nullptr, idx, true);
165   }
166 };
167 
168 static PluginProperties &GetGlobalPluginProperties() {
169   static PluginProperties g_settings;
170   return g_settings;
171 }
172 
173 } // namespace
174 
175 // TODO Randomly assigning a port is unsafe.  We should get an unused
176 // ephemeral port from the kernel and make sure we reserve it before passing it
177 // to debugserver.
178 
179 #if defined(__APPLE__)
180 #define LOW_PORT (IPPORT_RESERVED)
181 #define HIGH_PORT (IPPORT_HIFIRSTAUTO)
182 #else
183 #define LOW_PORT (1024u)
184 #define HIGH_PORT (49151u)
185 #endif
186 
187 llvm::StringRef ProcessGDBRemote::GetPluginDescriptionStatic() {
188   return "GDB Remote protocol based debugging plug-in.";
189 }
190 
191 void ProcessGDBRemote::Terminate() {
192   PluginManager::UnregisterPlugin(ProcessGDBRemote::CreateInstance);
193 }
194 
195 lldb::ProcessSP ProcessGDBRemote::CreateInstance(
196     lldb::TargetSP target_sp, ListenerSP listener_sp,
197     const FileSpec *crash_file_path, bool can_connect) {
198   lldb::ProcessSP process_sp;
199   if (crash_file_path == nullptr)
200     process_sp = std::shared_ptr<ProcessGDBRemote>(
201         new ProcessGDBRemote(target_sp, listener_sp));
202   return process_sp;
203 }
204 
205 std::chrono::seconds ProcessGDBRemote::GetPacketTimeout() {
206   return std::chrono::seconds(GetGlobalPluginProperties().GetPacketTimeout());
207 }
208 
209 ArchSpec ProcessGDBRemote::GetSystemArchitecture() {
210   return m_gdb_comm.GetHostArchitecture();
211 }
212 
213 bool ProcessGDBRemote::CanDebug(lldb::TargetSP target_sp,
214                                 bool plugin_specified_by_name) {
215   if (plugin_specified_by_name)
216     return true;
217 
218   // For now we are just making sure the file exists for a given module
219   Module *exe_module = target_sp->GetExecutableModulePointer();
220   if (exe_module) {
221     ObjectFile *exe_objfile = exe_module->GetObjectFile();
222     // We can't debug core files...
223     switch (exe_objfile->GetType()) {
224     case ObjectFile::eTypeInvalid:
225     case ObjectFile::eTypeCoreFile:
226     case ObjectFile::eTypeDebugInfo:
227     case ObjectFile::eTypeObjectFile:
228     case ObjectFile::eTypeSharedLibrary:
229     case ObjectFile::eTypeStubLibrary:
230     case ObjectFile::eTypeJIT:
231       return false;
232     case ObjectFile::eTypeExecutable:
233     case ObjectFile::eTypeDynamicLinker:
234     case ObjectFile::eTypeUnknown:
235       break;
236     }
237     return FileSystem::Instance().Exists(exe_module->GetFileSpec());
238   }
239   // However, if there is no executable module, we return true since we might
240   // be preparing to attach.
241   return true;
242 }
243 
244 // ProcessGDBRemote constructor
245 ProcessGDBRemote::ProcessGDBRemote(lldb::TargetSP target_sp,
246                                    ListenerSP listener_sp)
247     : Process(target_sp, listener_sp),
248       m_debugserver_pid(LLDB_INVALID_PROCESS_ID), m_register_info_sp(nullptr),
249       m_async_broadcaster(nullptr, "lldb.process.gdb-remote.async-broadcaster"),
250       m_async_listener_sp(
251           Listener::MakeListener("lldb.process.gdb-remote.async-listener")),
252       m_async_thread_state_mutex(), m_thread_ids(), m_thread_pcs(),
253       m_jstopinfo_sp(), m_jthreadsinfo_sp(), m_continue_c_tids(),
254       m_continue_C_tids(), m_continue_s_tids(), m_continue_S_tids(),
255       m_max_memory_size(0), m_remote_stub_max_memory_size(0),
256       m_addr_to_mmap_size(), m_thread_create_bp_sp(),
257       m_waiting_for_attach(false),
258       m_command_sp(), m_breakpoint_pc_offset(0),
259       m_initial_tid(LLDB_INVALID_THREAD_ID), m_allow_flash_writes(false),
260       m_erased_flash_ranges(), m_vfork_in_progress(false) {
261   m_async_broadcaster.SetEventName(eBroadcastBitAsyncThreadShouldExit,
262                                    "async thread should exit");
263   m_async_broadcaster.SetEventName(eBroadcastBitAsyncContinue,
264                                    "async thread continue");
265   m_async_broadcaster.SetEventName(eBroadcastBitAsyncThreadDidExit,
266                                    "async thread did exit");
267 
268   Log *log = GetLog(GDBRLog::Async);
269 
270   const uint32_t async_event_mask =
271       eBroadcastBitAsyncContinue | eBroadcastBitAsyncThreadShouldExit;
272 
273   if (m_async_listener_sp->StartListeningForEvents(
274           &m_async_broadcaster, async_event_mask) != async_event_mask) {
275     LLDB_LOGF(log,
276               "ProcessGDBRemote::%s failed to listen for "
277               "m_async_broadcaster events",
278               __FUNCTION__);
279   }
280 
281   const uint64_t timeout_seconds =
282       GetGlobalPluginProperties().GetPacketTimeout();
283   if (timeout_seconds > 0)
284     m_gdb_comm.SetPacketTimeout(std::chrono::seconds(timeout_seconds));
285 
286   m_use_g_packet_for_reading =
287       GetGlobalPluginProperties().GetUseGPacketForReading();
288 }
289 
290 // Destructor
291 ProcessGDBRemote::~ProcessGDBRemote() {
292   //  m_mach_process.UnregisterNotificationCallbacks (this);
293   Clear();
294   // We need to call finalize on the process before destroying ourselves to
295   // make sure all of the broadcaster cleanup goes as planned. If we destruct
296   // this class, then Process::~Process() might have problems trying to fully
297   // destroy the broadcaster.
298   Finalize();
299 
300   // The general Finalize is going to try to destroy the process and that
301   // SHOULD shut down the async thread.  However, if we don't kill it it will
302   // get stranded and its connection will go away so when it wakes up it will
303   // crash.  So kill it for sure here.
304   StopAsyncThread();
305   KillDebugserverProcess();
306 }
307 
308 bool ProcessGDBRemote::ParsePythonTargetDefinition(
309     const FileSpec &target_definition_fspec) {
310   ScriptInterpreter *interpreter =
311       GetTarget().GetDebugger().GetScriptInterpreter();
312   Status error;
313   StructuredData::ObjectSP module_object_sp(
314       interpreter->LoadPluginModule(target_definition_fspec, error));
315   if (module_object_sp) {
316     StructuredData::DictionarySP target_definition_sp(
317         interpreter->GetDynamicSettings(module_object_sp, &GetTarget(),
318                                         "gdb-server-target-definition", error));
319 
320     if (target_definition_sp) {
321       StructuredData::ObjectSP target_object(
322           target_definition_sp->GetValueForKey("host-info"));
323       if (target_object) {
324         if (auto host_info_dict = target_object->GetAsDictionary()) {
325           StructuredData::ObjectSP triple_value =
326               host_info_dict->GetValueForKey("triple");
327           if (auto triple_string_value = triple_value->GetAsString()) {
328             std::string triple_string =
329                 std::string(triple_string_value->GetValue());
330             ArchSpec host_arch(triple_string.c_str());
331             if (!host_arch.IsCompatibleMatch(GetTarget().GetArchitecture())) {
332               GetTarget().SetArchitecture(host_arch);
333             }
334           }
335         }
336       }
337       m_breakpoint_pc_offset = 0;
338       StructuredData::ObjectSP breakpoint_pc_offset_value =
339           target_definition_sp->GetValueForKey("breakpoint-pc-offset");
340       if (breakpoint_pc_offset_value) {
341         if (auto breakpoint_pc_int_value =
342                 breakpoint_pc_offset_value->GetAsInteger())
343           m_breakpoint_pc_offset = breakpoint_pc_int_value->GetValue();
344       }
345 
346       if (m_register_info_sp->SetRegisterInfo(
347               *target_definition_sp, GetTarget().GetArchitecture()) > 0) {
348         return true;
349       }
350     }
351   }
352   return false;
353 }
354 
355 static size_t SplitCommaSeparatedRegisterNumberString(
356     const llvm::StringRef &comma_separated_register_numbers,
357     std::vector<uint32_t> &regnums, int base) {
358   regnums.clear();
359   for (llvm::StringRef x : llvm::split(comma_separated_register_numbers, ',')) {
360     uint32_t reg;
361     if (llvm::to_integer(x, reg, base))
362       regnums.push_back(reg);
363   }
364   return regnums.size();
365 }
366 
367 void ProcessGDBRemote::BuildDynamicRegisterInfo(bool force) {
368   if (!force && m_register_info_sp)
369     return;
370 
371   m_register_info_sp = std::make_shared<GDBRemoteDynamicRegisterInfo>();
372 
373   // Check if qHostInfo specified a specific packet timeout for this
374   // connection. If so then lets update our setting so the user knows what the
375   // timeout is and can see it.
376   const auto host_packet_timeout = m_gdb_comm.GetHostDefaultPacketTimeout();
377   if (host_packet_timeout > std::chrono::seconds(0)) {
378     GetGlobalPluginProperties().SetPacketTimeout(host_packet_timeout.count());
379   }
380 
381   // Register info search order:
382   //     1 - Use the target definition python file if one is specified.
383   //     2 - If the target definition doesn't have any of the info from the
384   //     target.xml (registers) then proceed to read the target.xml.
385   //     3 - Fall back on the qRegisterInfo packets.
386   //     4 - Use hardcoded defaults if available.
387 
388   FileSpec target_definition_fspec =
389       GetGlobalPluginProperties().GetTargetDefinitionFile();
390   if (!FileSystem::Instance().Exists(target_definition_fspec)) {
391     // If the filename doesn't exist, it may be a ~ not having been expanded -
392     // try to resolve it.
393     FileSystem::Instance().Resolve(target_definition_fspec);
394   }
395   if (target_definition_fspec) {
396     // See if we can get register definitions from a python file
397     if (ParsePythonTargetDefinition(target_definition_fspec))
398       return;
399 
400     Debugger::ReportError("target description file " +
401                               target_definition_fspec.GetPath() +
402                               " failed to parse",
403                           GetTarget().GetDebugger().GetID());
404   }
405 
406   const ArchSpec &target_arch = GetTarget().GetArchitecture();
407   const ArchSpec &remote_host_arch = m_gdb_comm.GetHostArchitecture();
408   const ArchSpec &remote_process_arch = m_gdb_comm.GetProcessArchitecture();
409 
410   // Use the process' architecture instead of the host arch, if available
411   ArchSpec arch_to_use;
412   if (remote_process_arch.IsValid())
413     arch_to_use = remote_process_arch;
414   else
415     arch_to_use = remote_host_arch;
416 
417   if (!arch_to_use.IsValid())
418     arch_to_use = target_arch;
419 
420   if (GetGDBServerRegisterInfo(arch_to_use))
421     return;
422 
423   char packet[128];
424   std::vector<DynamicRegisterInfo::Register> registers;
425   uint32_t reg_num = 0;
426   for (StringExtractorGDBRemote::ResponseType response_type =
427            StringExtractorGDBRemote::eResponse;
428        response_type == StringExtractorGDBRemote::eResponse; ++reg_num) {
429     const int packet_len =
430         ::snprintf(packet, sizeof(packet), "qRegisterInfo%x", reg_num);
431     assert(packet_len < (int)sizeof(packet));
432     UNUSED_IF_ASSERT_DISABLED(packet_len);
433     StringExtractorGDBRemote response;
434     if (m_gdb_comm.SendPacketAndWaitForResponse(packet, response) ==
435         GDBRemoteCommunication::PacketResult::Success) {
436       response_type = response.GetResponseType();
437       if (response_type == StringExtractorGDBRemote::eResponse) {
438         llvm::StringRef name;
439         llvm::StringRef value;
440         DynamicRegisterInfo::Register reg_info;
441 
442         while (response.GetNameColonValue(name, value)) {
443           if (name.equals("name")) {
444             reg_info.name.SetString(value);
445           } else if (name.equals("alt-name")) {
446             reg_info.alt_name.SetString(value);
447           } else if (name.equals("bitsize")) {
448             if (!value.getAsInteger(0, reg_info.byte_size))
449               reg_info.byte_size /= CHAR_BIT;
450           } else if (name.equals("offset")) {
451             value.getAsInteger(0, reg_info.byte_offset);
452           } else if (name.equals("encoding")) {
453             const Encoding encoding = Args::StringToEncoding(value);
454             if (encoding != eEncodingInvalid)
455               reg_info.encoding = encoding;
456           } else if (name.equals("format")) {
457             if (!OptionArgParser::ToFormat(value.str().c_str(), reg_info.format, nullptr)
458                     .Success())
459               reg_info.format =
460                   llvm::StringSwitch<Format>(value)
461                       .Case("binary", eFormatBinary)
462                       .Case("decimal", eFormatDecimal)
463                       .Case("hex", eFormatHex)
464                       .Case("float", eFormatFloat)
465                       .Case("vector-sint8", eFormatVectorOfSInt8)
466                       .Case("vector-uint8", eFormatVectorOfUInt8)
467                       .Case("vector-sint16", eFormatVectorOfSInt16)
468                       .Case("vector-uint16", eFormatVectorOfUInt16)
469                       .Case("vector-sint32", eFormatVectorOfSInt32)
470                       .Case("vector-uint32", eFormatVectorOfUInt32)
471                       .Case("vector-float32", eFormatVectorOfFloat32)
472                       .Case("vector-uint64", eFormatVectorOfUInt64)
473                       .Case("vector-uint128", eFormatVectorOfUInt128)
474                       .Default(eFormatInvalid);
475           } else if (name.equals("set")) {
476             reg_info.set_name.SetString(value);
477           } else if (name.equals("gcc") || name.equals("ehframe")) {
478             value.getAsInteger(0, reg_info.regnum_ehframe);
479           } else if (name.equals("dwarf")) {
480             value.getAsInteger(0, reg_info.regnum_dwarf);
481           } else if (name.equals("generic")) {
482             reg_info.regnum_generic = Args::StringToGenericRegister(value);
483           } else if (name.equals("container-regs")) {
484             SplitCommaSeparatedRegisterNumberString(value, reg_info.value_regs, 16);
485           } else if (name.equals("invalidate-regs")) {
486             SplitCommaSeparatedRegisterNumberString(value, reg_info.invalidate_regs, 16);
487           }
488         }
489 
490         assert(reg_info.byte_size != 0);
491         registers.push_back(reg_info);
492       } else {
493         break; // ensure exit before reg_num is incremented
494       }
495     } else {
496       break;
497     }
498   }
499 
500   if (registers.empty())
501     registers = GetFallbackRegisters(arch_to_use);
502 
503   AddRemoteRegisters(registers, arch_to_use);
504 }
505 
506 Status ProcessGDBRemote::DoWillLaunch(lldb_private::Module *module) {
507   return WillLaunchOrAttach();
508 }
509 
510 Status ProcessGDBRemote::DoWillAttachToProcessWithID(lldb::pid_t pid) {
511   return WillLaunchOrAttach();
512 }
513 
514 Status ProcessGDBRemote::DoWillAttachToProcessWithName(const char *process_name,
515                                                        bool wait_for_launch) {
516   return WillLaunchOrAttach();
517 }
518 
519 Status ProcessGDBRemote::DoConnectRemote(llvm::StringRef remote_url) {
520   Log *log = GetLog(GDBRLog::Process);
521 
522   Status error(WillLaunchOrAttach());
523   if (error.Fail())
524     return error;
525 
526   error = ConnectToDebugserver(remote_url);
527   if (error.Fail())
528     return error;
529 
530   StartAsyncThread();
531 
532   lldb::pid_t pid = m_gdb_comm.GetCurrentProcessID();
533   if (pid == LLDB_INVALID_PROCESS_ID) {
534     // We don't have a valid process ID, so note that we are connected and
535     // could now request to launch or attach, or get remote process listings...
536     SetPrivateState(eStateConnected);
537   } else {
538     // We have a valid process
539     SetID(pid);
540     GetThreadList();
541     StringExtractorGDBRemote response;
542     if (m_gdb_comm.GetStopReply(response)) {
543       SetLastStopPacket(response);
544 
545       Target &target = GetTarget();
546       if (!target.GetArchitecture().IsValid()) {
547         if (m_gdb_comm.GetProcessArchitecture().IsValid()) {
548           target.SetArchitecture(m_gdb_comm.GetProcessArchitecture());
549         } else {
550           if (m_gdb_comm.GetHostArchitecture().IsValid()) {
551             target.SetArchitecture(m_gdb_comm.GetHostArchitecture());
552           }
553         }
554       }
555 
556       // The remote stub may know about the "main binary" in
557       // the context of a firmware debug session, and can
558       // give us a UUID and an address/slide of where the
559       // binary is loaded in memory.
560       UUID standalone_uuid;
561       addr_t standalone_value;
562       bool standalone_value_is_offset;
563       if (m_gdb_comm.GetProcessStandaloneBinary(
564               standalone_uuid, standalone_value, standalone_value_is_offset)) {
565         ModuleSP module_sp;
566 
567         if (standalone_uuid.IsValid()) {
568           const bool force_symbol_search = true;
569           const bool notify = true;
570           DynamicLoader::LoadBinaryWithUUIDAndAddress(
571               this, llvm::StringRef(), standalone_uuid, standalone_value,
572               standalone_value_is_offset, force_symbol_search, notify);
573         }
574       }
575 
576       // The remote stub may know about a list of binaries to
577       // force load into the process -- a firmware type situation
578       // where multiple binaries are present in virtual memory,
579       // and we are only given the addresses of the binaries.
580       // Not intended for use with userland debugging when we
581       // a DynamicLoader plugin that knows how to find the loaded
582       // binaries and will track updates as binaries are added.
583 
584       std::vector<addr_t> bin_addrs = m_gdb_comm.GetProcessStandaloneBinaries();
585       if (bin_addrs.size()) {
586         UUID uuid;
587         const bool value_is_slide = false;
588         for (addr_t addr : bin_addrs) {
589           const bool notify = true;
590           // First see if this is a special platform
591           // binary that may determine the DynamicLoader and
592           // Platform to be used in this Process/Target in the
593           // process of loading it.
594           if (GetTarget()
595                   .GetDebugger()
596                   .GetPlatformList()
597                   .LoadPlatformBinaryAndSetup(this, addr, notify))
598             continue;
599 
600           const bool force_symbol_search = true;
601           // Second manually load this binary into the Target.
602           DynamicLoader::LoadBinaryWithUUIDAndAddress(
603               this, llvm::StringRef(), uuid, addr, value_is_slide,
604               force_symbol_search, notify);
605         }
606       }
607 
608       const StateType state = SetThreadStopInfo(response);
609       if (state != eStateInvalid) {
610         SetPrivateState(state);
611       } else
612         error.SetErrorStringWithFormat(
613             "Process %" PRIu64 " was reported after connecting to "
614             "'%s', but state was not stopped: %s",
615             pid, remote_url.str().c_str(), StateAsCString(state));
616     } else
617       error.SetErrorStringWithFormat("Process %" PRIu64
618                                      " was reported after connecting to '%s', "
619                                      "but no stop reply packet was received",
620                                      pid, remote_url.str().c_str());
621   }
622 
623   LLDB_LOGF(log,
624             "ProcessGDBRemote::%s pid %" PRIu64
625             ": normalizing target architecture initial triple: %s "
626             "(GetTarget().GetArchitecture().IsValid() %s, "
627             "m_gdb_comm.GetHostArchitecture().IsValid(): %s)",
628             __FUNCTION__, GetID(),
629             GetTarget().GetArchitecture().GetTriple().getTriple().c_str(),
630             GetTarget().GetArchitecture().IsValid() ? "true" : "false",
631             m_gdb_comm.GetHostArchitecture().IsValid() ? "true" : "false");
632 
633   if (error.Success() && !GetTarget().GetArchitecture().IsValid() &&
634       m_gdb_comm.GetHostArchitecture().IsValid()) {
635     // Prefer the *process'* architecture over that of the *host*, if
636     // available.
637     if (m_gdb_comm.GetProcessArchitecture().IsValid())
638       GetTarget().SetArchitecture(m_gdb_comm.GetProcessArchitecture());
639     else
640       GetTarget().SetArchitecture(m_gdb_comm.GetHostArchitecture());
641   }
642 
643   LLDB_LOGF(log,
644             "ProcessGDBRemote::%s pid %" PRIu64
645             ": normalized target architecture triple: %s",
646             __FUNCTION__, GetID(),
647             GetTarget().GetArchitecture().GetTriple().getTriple().c_str());
648 
649   return error;
650 }
651 
652 Status ProcessGDBRemote::WillLaunchOrAttach() {
653   Status error;
654   m_stdio_communication.Clear();
655   return error;
656 }
657 
658 // Process Control
659 Status ProcessGDBRemote::DoLaunch(lldb_private::Module *exe_module,
660                                   ProcessLaunchInfo &launch_info) {
661   Log *log = GetLog(GDBRLog::Process);
662   Status error;
663 
664   LLDB_LOGF(log, "ProcessGDBRemote::%s() entered", __FUNCTION__);
665 
666   uint32_t launch_flags = launch_info.GetFlags().Get();
667   FileSpec stdin_file_spec{};
668   FileSpec stdout_file_spec{};
669   FileSpec stderr_file_spec{};
670   FileSpec working_dir = launch_info.GetWorkingDirectory();
671 
672   const FileAction *file_action;
673   file_action = launch_info.GetFileActionForFD(STDIN_FILENO);
674   if (file_action) {
675     if (file_action->GetAction() == FileAction::eFileActionOpen)
676       stdin_file_spec = file_action->GetFileSpec();
677   }
678   file_action = launch_info.GetFileActionForFD(STDOUT_FILENO);
679   if (file_action) {
680     if (file_action->GetAction() == FileAction::eFileActionOpen)
681       stdout_file_spec = file_action->GetFileSpec();
682   }
683   file_action = launch_info.GetFileActionForFD(STDERR_FILENO);
684   if (file_action) {
685     if (file_action->GetAction() == FileAction::eFileActionOpen)
686       stderr_file_spec = file_action->GetFileSpec();
687   }
688 
689   if (log) {
690     if (stdin_file_spec || stdout_file_spec || stderr_file_spec)
691       LLDB_LOGF(log,
692                 "ProcessGDBRemote::%s provided with STDIO paths via "
693                 "launch_info: stdin=%s, stdout=%s, stderr=%s",
694                 __FUNCTION__,
695                 stdin_file_spec ? stdin_file_spec.GetPath().c_str() : "<null>",
696                 stdout_file_spec ? stdout_file_spec.GetPath().c_str() : "<null>",
697                 stderr_file_spec ? stderr_file_spec.GetPath().c_str() : "<null>");
698     else
699       LLDB_LOGF(log,
700                 "ProcessGDBRemote::%s no STDIO paths given via launch_info",
701                 __FUNCTION__);
702   }
703 
704   const bool disable_stdio = (launch_flags & eLaunchFlagDisableSTDIO) != 0;
705   if (stdin_file_spec || disable_stdio) {
706     // the inferior will be reading stdin from the specified file or stdio is
707     // completely disabled
708     m_stdin_forward = false;
709   } else {
710     m_stdin_forward = true;
711   }
712 
713   //  ::LogSetBitMask (GDBR_LOG_DEFAULT);
714   //  ::LogSetOptions (LLDB_LOG_OPTION_THREADSAFE |
715   //  LLDB_LOG_OPTION_PREPEND_TIMESTAMP |
716   //  LLDB_LOG_OPTION_PREPEND_PROC_AND_THREAD);
717   //  ::LogSetLogFile ("/dev/stdout");
718 
719   error = EstablishConnectionIfNeeded(launch_info);
720   if (error.Success()) {
721     PseudoTerminal pty;
722     const bool disable_stdio = (launch_flags & eLaunchFlagDisableSTDIO) != 0;
723 
724     PlatformSP platform_sp(GetTarget().GetPlatform());
725     if (disable_stdio) {
726       // set to /dev/null unless redirected to a file above
727       if (!stdin_file_spec)
728         stdin_file_spec.SetFile(FileSystem::DEV_NULL,
729                                 FileSpec::Style::native);
730       if (!stdout_file_spec)
731         stdout_file_spec.SetFile(FileSystem::DEV_NULL,
732                                  FileSpec::Style::native);
733       if (!stderr_file_spec)
734         stderr_file_spec.SetFile(FileSystem::DEV_NULL,
735                                  FileSpec::Style::native);
736     } else if (platform_sp && platform_sp->IsHost()) {
737       // If the debugserver is local and we aren't disabling STDIO, lets use
738       // a pseudo terminal to instead of relying on the 'O' packets for stdio
739       // since 'O' packets can really slow down debugging if the inferior
740       // does a lot of output.
741       if ((!stdin_file_spec || !stdout_file_spec || !stderr_file_spec) &&
742           !errorToBool(pty.OpenFirstAvailablePrimary(O_RDWR | O_NOCTTY))) {
743         FileSpec secondary_name(pty.GetSecondaryName());
744 
745         if (!stdin_file_spec)
746           stdin_file_spec = secondary_name;
747 
748         if (!stdout_file_spec)
749           stdout_file_spec = secondary_name;
750 
751         if (!stderr_file_spec)
752           stderr_file_spec = secondary_name;
753       }
754       LLDB_LOGF(
755           log,
756           "ProcessGDBRemote::%s adjusted STDIO paths for local platform "
757           "(IsHost() is true) using secondary: stdin=%s, stdout=%s, "
758           "stderr=%s",
759           __FUNCTION__,
760           stdin_file_spec ? stdin_file_spec.GetPath().c_str() : "<null>",
761           stdout_file_spec ? stdout_file_spec.GetPath().c_str() : "<null>",
762           stderr_file_spec ? stderr_file_spec.GetPath().c_str() : "<null>");
763     }
764 
765     LLDB_LOGF(log,
766               "ProcessGDBRemote::%s final STDIO paths after all "
767               "adjustments: stdin=%s, stdout=%s, stderr=%s",
768               __FUNCTION__,
769               stdin_file_spec ? stdin_file_spec.GetPath().c_str() : "<null>",
770               stdout_file_spec ? stdout_file_spec.GetPath().c_str() : "<null>",
771               stderr_file_spec ? stderr_file_spec.GetPath().c_str() : "<null>");
772 
773     if (stdin_file_spec)
774       m_gdb_comm.SetSTDIN(stdin_file_spec);
775     if (stdout_file_spec)
776       m_gdb_comm.SetSTDOUT(stdout_file_spec);
777     if (stderr_file_spec)
778       m_gdb_comm.SetSTDERR(stderr_file_spec);
779 
780     m_gdb_comm.SetDisableASLR(launch_flags & eLaunchFlagDisableASLR);
781     m_gdb_comm.SetDetachOnError(launch_flags & eLaunchFlagDetachOnError);
782 
783     m_gdb_comm.SendLaunchArchPacket(
784         GetTarget().GetArchitecture().GetArchitectureName());
785 
786     const char *launch_event_data = launch_info.GetLaunchEventData();
787     if (launch_event_data != nullptr && *launch_event_data != '\0')
788       m_gdb_comm.SendLaunchEventDataPacket(launch_event_data);
789 
790     if (working_dir) {
791       m_gdb_comm.SetWorkingDir(working_dir);
792     }
793 
794     // Send the environment and the program + arguments after we connect
795     m_gdb_comm.SendEnvironment(launch_info.GetEnvironment());
796 
797     {
798       // Scope for the scoped timeout object
799       GDBRemoteCommunication::ScopedTimeout timeout(m_gdb_comm,
800                                                     std::chrono::seconds(10));
801 
802       int arg_packet_err = m_gdb_comm.SendArgumentsPacket(launch_info);
803       if (arg_packet_err == 0) {
804         std::string error_str;
805         if (m_gdb_comm.GetLaunchSuccess(error_str)) {
806           SetID(m_gdb_comm.GetCurrentProcessID());
807         } else {
808           error.SetErrorString(error_str.c_str());
809         }
810       } else {
811         error.SetErrorStringWithFormat("'A' packet returned an error: %i",
812                                        arg_packet_err);
813       }
814     }
815 
816     if (GetID() == LLDB_INVALID_PROCESS_ID) {
817       LLDB_LOGF(log, "failed to connect to debugserver: %s",
818                 error.AsCString());
819       KillDebugserverProcess();
820       return error;
821     }
822 
823     StringExtractorGDBRemote response;
824     if (m_gdb_comm.GetStopReply(response)) {
825       SetLastStopPacket(response);
826 
827       const ArchSpec &process_arch = m_gdb_comm.GetProcessArchitecture();
828 
829       if (process_arch.IsValid()) {
830         GetTarget().MergeArchitecture(process_arch);
831       } else {
832         const ArchSpec &host_arch = m_gdb_comm.GetHostArchitecture();
833         if (host_arch.IsValid())
834           GetTarget().MergeArchitecture(host_arch);
835       }
836 
837       SetPrivateState(SetThreadStopInfo(response));
838 
839       if (!disable_stdio) {
840         if (pty.GetPrimaryFileDescriptor() != PseudoTerminal::invalid_fd)
841           SetSTDIOFileDescriptor(pty.ReleasePrimaryFileDescriptor());
842       }
843     }
844   } else {
845     LLDB_LOGF(log, "failed to connect to debugserver: %s", error.AsCString());
846   }
847   return error;
848 }
849 
850 Status ProcessGDBRemote::ConnectToDebugserver(llvm::StringRef connect_url) {
851   Status error;
852   // Only connect if we have a valid connect URL
853   Log *log = GetLog(GDBRLog::Process);
854 
855   if (!connect_url.empty()) {
856     LLDB_LOGF(log, "ProcessGDBRemote::%s Connecting to %s", __FUNCTION__,
857               connect_url.str().c_str());
858     std::unique_ptr<ConnectionFileDescriptor> conn_up(
859         new ConnectionFileDescriptor());
860     if (conn_up) {
861       const uint32_t max_retry_count = 50;
862       uint32_t retry_count = 0;
863       while (!m_gdb_comm.IsConnected()) {
864         if (conn_up->Connect(connect_url, &error) == eConnectionStatusSuccess) {
865           m_gdb_comm.SetConnection(std::move(conn_up));
866           break;
867         }
868 
869         retry_count++;
870 
871         if (retry_count >= max_retry_count)
872           break;
873 
874         std::this_thread::sleep_for(std::chrono::milliseconds(100));
875       }
876     }
877   }
878 
879   if (!m_gdb_comm.IsConnected()) {
880     if (error.Success())
881       error.SetErrorString("not connected to remote gdb server");
882     return error;
883   }
884 
885   // We always seem to be able to open a connection to a local port so we need
886   // to make sure we can then send data to it. If we can't then we aren't
887   // actually connected to anything, so try and do the handshake with the
888   // remote GDB server and make sure that goes alright.
889   if (!m_gdb_comm.HandshakeWithServer(&error)) {
890     m_gdb_comm.Disconnect();
891     if (error.Success())
892       error.SetErrorString("not connected to remote gdb server");
893     return error;
894   }
895 
896   m_gdb_comm.GetEchoSupported();
897   m_gdb_comm.GetThreadSuffixSupported();
898   m_gdb_comm.GetListThreadsInStopReplySupported();
899   m_gdb_comm.GetHostInfo();
900   m_gdb_comm.GetVContSupported('c');
901   m_gdb_comm.GetVAttachOrWaitSupported();
902   m_gdb_comm.EnableErrorStringInPacket();
903 
904   // First dispatch any commands from the platform:
905   auto handle_cmds = [&] (const Args &args) ->  void {
906     for (const Args::ArgEntry &entry : args) {
907       StringExtractorGDBRemote response;
908       m_gdb_comm.SendPacketAndWaitForResponse(
909           entry.c_str(), response);
910     }
911   };
912 
913   PlatformSP platform_sp = GetTarget().GetPlatform();
914   if (platform_sp) {
915     handle_cmds(platform_sp->GetExtraStartupCommands());
916   }
917 
918   // Then dispatch any process commands:
919   handle_cmds(GetExtraStartupCommands());
920 
921   return error;
922 }
923 
924 void ProcessGDBRemote::DidLaunchOrAttach(ArchSpec &process_arch) {
925   Log *log = GetLog(GDBRLog::Process);
926   BuildDynamicRegisterInfo(false);
927 
928   // See if the GDB server supports qHostInfo or qProcessInfo packets. Prefer
929   // qProcessInfo as it will be more specific to our process.
930 
931   const ArchSpec &remote_process_arch = m_gdb_comm.GetProcessArchitecture();
932   if (remote_process_arch.IsValid()) {
933     process_arch = remote_process_arch;
934     LLDB_LOG(log, "gdb-remote had process architecture, using {0} {1}",
935              process_arch.GetArchitectureName(),
936              process_arch.GetTriple().getTriple());
937   } else {
938     process_arch = m_gdb_comm.GetHostArchitecture();
939     LLDB_LOG(log,
940              "gdb-remote did not have process architecture, using gdb-remote "
941              "host architecture {0} {1}",
942              process_arch.GetArchitectureName(),
943              process_arch.GetTriple().getTriple());
944   }
945 
946   if (int addressable_bits = m_gdb_comm.GetAddressingBits()) {
947     lldb::addr_t address_mask = ~((1ULL << addressable_bits) - 1);
948     SetCodeAddressMask(address_mask);
949     SetDataAddressMask(address_mask);
950   }
951 
952   if (process_arch.IsValid()) {
953     const ArchSpec &target_arch = GetTarget().GetArchitecture();
954     if (target_arch.IsValid()) {
955       LLDB_LOG(log, "analyzing target arch, currently {0} {1}",
956                target_arch.GetArchitectureName(),
957                target_arch.GetTriple().getTriple());
958 
959       // If the remote host is ARM and we have apple as the vendor, then
960       // ARM executables and shared libraries can have mixed ARM
961       // architectures.
962       // You can have an armv6 executable, and if the host is armv7, then the
963       // system will load the best possible architecture for all shared
964       // libraries it has, so we really need to take the remote host
965       // architecture as our defacto architecture in this case.
966 
967       if ((process_arch.GetMachine() == llvm::Triple::arm ||
968            process_arch.GetMachine() == llvm::Triple::thumb) &&
969           process_arch.GetTriple().getVendor() == llvm::Triple::Apple) {
970         GetTarget().SetArchitecture(process_arch);
971         LLDB_LOG(log,
972                  "remote process is ARM/Apple, "
973                  "setting target arch to {0} {1}",
974                  process_arch.GetArchitectureName(),
975                  process_arch.GetTriple().getTriple());
976       } else {
977         // Fill in what is missing in the triple
978         const llvm::Triple &remote_triple = process_arch.GetTriple();
979         llvm::Triple new_target_triple = target_arch.GetTriple();
980         if (new_target_triple.getVendorName().size() == 0) {
981           new_target_triple.setVendor(remote_triple.getVendor());
982 
983           if (new_target_triple.getOSName().size() == 0) {
984             new_target_triple.setOS(remote_triple.getOS());
985 
986             if (new_target_triple.getEnvironmentName().size() == 0)
987               new_target_triple.setEnvironment(remote_triple.getEnvironment());
988           }
989 
990           ArchSpec new_target_arch = target_arch;
991           new_target_arch.SetTriple(new_target_triple);
992           GetTarget().SetArchitecture(new_target_arch);
993         }
994       }
995 
996       LLDB_LOG(log,
997                "final target arch after adjustments for remote architecture: "
998                "{0} {1}",
999                target_arch.GetArchitectureName(),
1000                target_arch.GetTriple().getTriple());
1001     } else {
1002       // The target doesn't have a valid architecture yet, set it from the
1003       // architecture we got from the remote GDB server
1004       GetTarget().SetArchitecture(process_arch);
1005     }
1006   }
1007 
1008   MaybeLoadExecutableModule();
1009 
1010   // Find out which StructuredDataPlugins are supported by the debug monitor.
1011   // These plugins transmit data over async $J packets.
1012   if (StructuredData::Array *supported_packets =
1013           m_gdb_comm.GetSupportedStructuredDataPlugins())
1014     MapSupportedStructuredDataPlugins(*supported_packets);
1015 
1016   // If connected to LLDB ("native-signals+"), use signal defs for
1017   // the remote platform.  If connected to GDB, just use the standard set.
1018   if (!m_gdb_comm.UsesNativeSignals()) {
1019     SetUnixSignals(std::make_shared<GDBRemoteSignals>());
1020   } else {
1021     PlatformSP platform_sp = GetTarget().GetPlatform();
1022     if (platform_sp && platform_sp->IsConnected())
1023       SetUnixSignals(platform_sp->GetUnixSignals());
1024     else
1025       SetUnixSignals(UnixSignals::Create(GetTarget().GetArchitecture()));
1026   }
1027 }
1028 
1029 void ProcessGDBRemote::MaybeLoadExecutableModule() {
1030   ModuleSP module_sp = GetTarget().GetExecutableModule();
1031   if (!module_sp)
1032     return;
1033 
1034   llvm::Optional<QOffsets> offsets = m_gdb_comm.GetQOffsets();
1035   if (!offsets)
1036     return;
1037 
1038   bool is_uniform =
1039       size_t(llvm::count(offsets->offsets, offsets->offsets[0])) ==
1040       offsets->offsets.size();
1041   if (!is_uniform)
1042     return; // TODO: Handle non-uniform responses.
1043 
1044   bool changed = false;
1045   module_sp->SetLoadAddress(GetTarget(), offsets->offsets[0],
1046                             /*value_is_offset=*/true, changed);
1047   if (changed) {
1048     ModuleList list;
1049     list.Append(module_sp);
1050     m_process->GetTarget().ModulesDidLoad(list);
1051   }
1052 }
1053 
1054 void ProcessGDBRemote::DidLaunch() {
1055   ArchSpec process_arch;
1056   DidLaunchOrAttach(process_arch);
1057 }
1058 
1059 Status ProcessGDBRemote::DoAttachToProcessWithID(
1060     lldb::pid_t attach_pid, const ProcessAttachInfo &attach_info) {
1061   Log *log = GetLog(GDBRLog::Process);
1062   Status error;
1063 
1064   LLDB_LOGF(log, "ProcessGDBRemote::%s()", __FUNCTION__);
1065 
1066   // Clear out and clean up from any current state
1067   Clear();
1068   if (attach_pid != LLDB_INVALID_PROCESS_ID) {
1069     error = EstablishConnectionIfNeeded(attach_info);
1070     if (error.Success()) {
1071       m_gdb_comm.SetDetachOnError(attach_info.GetDetachOnError());
1072 
1073       char packet[64];
1074       const int packet_len =
1075           ::snprintf(packet, sizeof(packet), "vAttach;%" PRIx64, attach_pid);
1076       SetID(attach_pid);
1077       m_async_broadcaster.BroadcastEvent(
1078           eBroadcastBitAsyncContinue, new EventDataBytes(packet, packet_len));
1079     } else
1080       SetExitStatus(-1, error.AsCString());
1081   }
1082 
1083   return error;
1084 }
1085 
1086 Status ProcessGDBRemote::DoAttachToProcessWithName(
1087     const char *process_name, const ProcessAttachInfo &attach_info) {
1088   Status error;
1089   // Clear out and clean up from any current state
1090   Clear();
1091 
1092   if (process_name && process_name[0]) {
1093     error = EstablishConnectionIfNeeded(attach_info);
1094     if (error.Success()) {
1095       StreamString packet;
1096 
1097       m_gdb_comm.SetDetachOnError(attach_info.GetDetachOnError());
1098 
1099       if (attach_info.GetWaitForLaunch()) {
1100         if (!m_gdb_comm.GetVAttachOrWaitSupported()) {
1101           packet.PutCString("vAttachWait");
1102         } else {
1103           if (attach_info.GetIgnoreExisting())
1104             packet.PutCString("vAttachWait");
1105           else
1106             packet.PutCString("vAttachOrWait");
1107         }
1108       } else
1109         packet.PutCString("vAttachName");
1110       packet.PutChar(';');
1111       packet.PutBytesAsRawHex8(process_name, strlen(process_name),
1112                                endian::InlHostByteOrder(),
1113                                endian::InlHostByteOrder());
1114 
1115       m_async_broadcaster.BroadcastEvent(
1116           eBroadcastBitAsyncContinue,
1117           new EventDataBytes(packet.GetString().data(), packet.GetSize()));
1118 
1119     } else
1120       SetExitStatus(-1, error.AsCString());
1121   }
1122   return error;
1123 }
1124 
1125 llvm::Expected<TraceSupportedResponse> ProcessGDBRemote::TraceSupported() {
1126   return m_gdb_comm.SendTraceSupported(GetInterruptTimeout());
1127 }
1128 
1129 llvm::Error ProcessGDBRemote::TraceStop(const TraceStopRequest &request) {
1130   return m_gdb_comm.SendTraceStop(request, GetInterruptTimeout());
1131 }
1132 
1133 llvm::Error ProcessGDBRemote::TraceStart(const llvm::json::Value &request) {
1134   return m_gdb_comm.SendTraceStart(request, GetInterruptTimeout());
1135 }
1136 
1137 llvm::Expected<std::string>
1138 ProcessGDBRemote::TraceGetState(llvm::StringRef type) {
1139   return m_gdb_comm.SendTraceGetState(type, GetInterruptTimeout());
1140 }
1141 
1142 llvm::Expected<std::vector<uint8_t>>
1143 ProcessGDBRemote::TraceGetBinaryData(const TraceGetBinaryDataRequest &request) {
1144   return m_gdb_comm.SendTraceGetBinaryData(request, GetInterruptTimeout());
1145 }
1146 
1147 void ProcessGDBRemote::DidExit() {
1148   // When we exit, disconnect from the GDB server communications
1149   m_gdb_comm.Disconnect();
1150 }
1151 
1152 void ProcessGDBRemote::DidAttach(ArchSpec &process_arch) {
1153   // If you can figure out what the architecture is, fill it in here.
1154   process_arch.Clear();
1155   DidLaunchOrAttach(process_arch);
1156 }
1157 
1158 Status ProcessGDBRemote::WillResume() {
1159   m_continue_c_tids.clear();
1160   m_continue_C_tids.clear();
1161   m_continue_s_tids.clear();
1162   m_continue_S_tids.clear();
1163   m_jstopinfo_sp.reset();
1164   m_jthreadsinfo_sp.reset();
1165   return Status();
1166 }
1167 
1168 Status ProcessGDBRemote::DoResume() {
1169   Status error;
1170   Log *log = GetLog(GDBRLog::Process);
1171   LLDB_LOGF(log, "ProcessGDBRemote::Resume()");
1172 
1173   ListenerSP listener_sp(
1174       Listener::MakeListener("gdb-remote.resume-packet-sent"));
1175   if (listener_sp->StartListeningForEvents(
1176           &m_gdb_comm, GDBRemoteClientBase::eBroadcastBitRunPacketSent)) {
1177     listener_sp->StartListeningForEvents(
1178         &m_async_broadcaster,
1179         ProcessGDBRemote::eBroadcastBitAsyncThreadDidExit);
1180 
1181     const size_t num_threads = GetThreadList().GetSize();
1182 
1183     StreamString continue_packet;
1184     bool continue_packet_error = false;
1185     if (m_gdb_comm.HasAnyVContSupport()) {
1186       std::string pid_prefix;
1187       if (m_gdb_comm.GetMultiprocessSupported())
1188         pid_prefix = llvm::formatv("p{0:x-}.", GetID());
1189 
1190       if (m_continue_c_tids.size() == num_threads ||
1191           (m_continue_c_tids.empty() && m_continue_C_tids.empty() &&
1192            m_continue_s_tids.empty() && m_continue_S_tids.empty())) {
1193         // All threads are continuing
1194         if (m_gdb_comm.GetMultiprocessSupported())
1195           continue_packet.Format("vCont;c:{0}-1", pid_prefix);
1196         else
1197           continue_packet.PutCString("c");
1198       } else {
1199         continue_packet.PutCString("vCont");
1200 
1201         if (!m_continue_c_tids.empty()) {
1202           if (m_gdb_comm.GetVContSupported('c')) {
1203             for (tid_collection::const_iterator
1204                      t_pos = m_continue_c_tids.begin(),
1205                      t_end = m_continue_c_tids.end();
1206                  t_pos != t_end; ++t_pos)
1207               continue_packet.Format(";c:{0}{1:x-}", pid_prefix, *t_pos);
1208           } else
1209             continue_packet_error = true;
1210         }
1211 
1212         if (!continue_packet_error && !m_continue_C_tids.empty()) {
1213           if (m_gdb_comm.GetVContSupported('C')) {
1214             for (tid_sig_collection::const_iterator
1215                      s_pos = m_continue_C_tids.begin(),
1216                      s_end = m_continue_C_tids.end();
1217                  s_pos != s_end; ++s_pos)
1218               continue_packet.Format(";C{0:x-2}:{1}{2:x-}", s_pos->second,
1219                                      pid_prefix, s_pos->first);
1220           } else
1221             continue_packet_error = true;
1222         }
1223 
1224         if (!continue_packet_error && !m_continue_s_tids.empty()) {
1225           if (m_gdb_comm.GetVContSupported('s')) {
1226             for (tid_collection::const_iterator
1227                      t_pos = m_continue_s_tids.begin(),
1228                      t_end = m_continue_s_tids.end();
1229                  t_pos != t_end; ++t_pos)
1230               continue_packet.Format(";s:{0}{1:x-}", pid_prefix, *t_pos);
1231           } else
1232             continue_packet_error = true;
1233         }
1234 
1235         if (!continue_packet_error && !m_continue_S_tids.empty()) {
1236           if (m_gdb_comm.GetVContSupported('S')) {
1237             for (tid_sig_collection::const_iterator
1238                      s_pos = m_continue_S_tids.begin(),
1239                      s_end = m_continue_S_tids.end();
1240                  s_pos != s_end; ++s_pos)
1241               continue_packet.Format(";S{0:x-2}:{1}{2:x-}", s_pos->second,
1242                                      pid_prefix, s_pos->first);
1243           } else
1244             continue_packet_error = true;
1245         }
1246 
1247         if (continue_packet_error)
1248           continue_packet.Clear();
1249       }
1250     } else
1251       continue_packet_error = true;
1252 
1253     if (continue_packet_error) {
1254       // Either no vCont support, or we tried to use part of the vCont packet
1255       // that wasn't supported by the remote GDB server. We need to try and
1256       // make a simple packet that can do our continue
1257       const size_t num_continue_c_tids = m_continue_c_tids.size();
1258       const size_t num_continue_C_tids = m_continue_C_tids.size();
1259       const size_t num_continue_s_tids = m_continue_s_tids.size();
1260       const size_t num_continue_S_tids = m_continue_S_tids.size();
1261       if (num_continue_c_tids > 0) {
1262         if (num_continue_c_tids == num_threads) {
1263           // All threads are resuming...
1264           m_gdb_comm.SetCurrentThreadForRun(-1);
1265           continue_packet.PutChar('c');
1266           continue_packet_error = false;
1267         } else if (num_continue_c_tids == 1 && num_continue_C_tids == 0 &&
1268                    num_continue_s_tids == 0 && num_continue_S_tids == 0) {
1269           // Only one thread is continuing
1270           m_gdb_comm.SetCurrentThreadForRun(m_continue_c_tids.front());
1271           continue_packet.PutChar('c');
1272           continue_packet_error = false;
1273         }
1274       }
1275 
1276       if (continue_packet_error && num_continue_C_tids > 0) {
1277         if ((num_continue_C_tids + num_continue_c_tids) == num_threads &&
1278             num_continue_C_tids > 0 && num_continue_s_tids == 0 &&
1279             num_continue_S_tids == 0) {
1280           const int continue_signo = m_continue_C_tids.front().second;
1281           // Only one thread is continuing
1282           if (num_continue_C_tids > 1) {
1283             // More that one thread with a signal, yet we don't have vCont
1284             // support and we are being asked to resume each thread with a
1285             // signal, we need to make sure they are all the same signal, or we
1286             // can't issue the continue accurately with the current support...
1287             if (num_continue_C_tids > 1) {
1288               continue_packet_error = false;
1289               for (size_t i = 1; i < m_continue_C_tids.size(); ++i) {
1290                 if (m_continue_C_tids[i].second != continue_signo)
1291                   continue_packet_error = true;
1292               }
1293             }
1294             if (!continue_packet_error)
1295               m_gdb_comm.SetCurrentThreadForRun(-1);
1296           } else {
1297             // Set the continue thread ID
1298             continue_packet_error = false;
1299             m_gdb_comm.SetCurrentThreadForRun(m_continue_C_tids.front().first);
1300           }
1301           if (!continue_packet_error) {
1302             // Add threads continuing with the same signo...
1303             continue_packet.Printf("C%2.2x", continue_signo);
1304           }
1305         }
1306       }
1307 
1308       if (continue_packet_error && num_continue_s_tids > 0) {
1309         if (num_continue_s_tids == num_threads) {
1310           // All threads are resuming...
1311           m_gdb_comm.SetCurrentThreadForRun(-1);
1312 
1313           continue_packet.PutChar('s');
1314 
1315           continue_packet_error = false;
1316         } else if (num_continue_c_tids == 0 && num_continue_C_tids == 0 &&
1317                    num_continue_s_tids == 1 && num_continue_S_tids == 0) {
1318           // Only one thread is stepping
1319           m_gdb_comm.SetCurrentThreadForRun(m_continue_s_tids.front());
1320           continue_packet.PutChar('s');
1321           continue_packet_error = false;
1322         }
1323       }
1324 
1325       if (!continue_packet_error && num_continue_S_tids > 0) {
1326         if (num_continue_S_tids == num_threads) {
1327           const int step_signo = m_continue_S_tids.front().second;
1328           // Are all threads trying to step with the same signal?
1329           continue_packet_error = false;
1330           if (num_continue_S_tids > 1) {
1331             for (size_t i = 1; i < num_threads; ++i) {
1332               if (m_continue_S_tids[i].second != step_signo)
1333                 continue_packet_error = true;
1334             }
1335           }
1336           if (!continue_packet_error) {
1337             // Add threads stepping with the same signo...
1338             m_gdb_comm.SetCurrentThreadForRun(-1);
1339             continue_packet.Printf("S%2.2x", step_signo);
1340           }
1341         } else if (num_continue_c_tids == 0 && num_continue_C_tids == 0 &&
1342                    num_continue_s_tids == 0 && num_continue_S_tids == 1) {
1343           // Only one thread is stepping with signal
1344           m_gdb_comm.SetCurrentThreadForRun(m_continue_S_tids.front().first);
1345           continue_packet.Printf("S%2.2x", m_continue_S_tids.front().second);
1346           continue_packet_error = false;
1347         }
1348       }
1349     }
1350 
1351     if (continue_packet_error) {
1352       error.SetErrorString("can't make continue packet for this resume");
1353     } else {
1354       EventSP event_sp;
1355       if (!m_async_thread.IsJoinable()) {
1356         error.SetErrorString("Trying to resume but the async thread is dead.");
1357         LLDB_LOGF(log, "ProcessGDBRemote::DoResume: Trying to resume but the "
1358                        "async thread is dead.");
1359         return error;
1360       }
1361 
1362       m_async_broadcaster.BroadcastEvent(
1363           eBroadcastBitAsyncContinue,
1364           new EventDataBytes(continue_packet.GetString().data(),
1365                              continue_packet.GetSize()));
1366 
1367       if (!listener_sp->GetEvent(event_sp, std::chrono::seconds(5))) {
1368         error.SetErrorString("Resume timed out.");
1369         LLDB_LOGF(log, "ProcessGDBRemote::DoResume: Resume timed out.");
1370       } else if (event_sp->BroadcasterIs(&m_async_broadcaster)) {
1371         error.SetErrorString("Broadcast continue, but the async thread was "
1372                              "killed before we got an ack back.");
1373         LLDB_LOGF(log,
1374                   "ProcessGDBRemote::DoResume: Broadcast continue, but the "
1375                   "async thread was killed before we got an ack back.");
1376         return error;
1377       }
1378     }
1379   }
1380 
1381   return error;
1382 }
1383 
1384 void ProcessGDBRemote::ClearThreadIDList() {
1385   std::lock_guard<std::recursive_mutex> guard(m_thread_list_real.GetMutex());
1386   m_thread_ids.clear();
1387   m_thread_pcs.clear();
1388 }
1389 
1390 size_t ProcessGDBRemote::UpdateThreadIDsFromStopReplyThreadsValue(
1391     llvm::StringRef value) {
1392   m_thread_ids.clear();
1393   lldb::pid_t pid = m_gdb_comm.GetCurrentProcessID();
1394   StringExtractorGDBRemote thread_ids{value};
1395 
1396   do {
1397     auto pid_tid = thread_ids.GetPidTid(pid);
1398     if (pid_tid && pid_tid->first == pid) {
1399       lldb::tid_t tid = pid_tid->second;
1400       if (tid != LLDB_INVALID_THREAD_ID &&
1401           tid != StringExtractorGDBRemote::AllProcesses)
1402         m_thread_ids.push_back(tid);
1403     }
1404   } while (thread_ids.GetChar() == ',');
1405 
1406   return m_thread_ids.size();
1407 }
1408 
1409 size_t ProcessGDBRemote::UpdateThreadPCsFromStopReplyThreadsValue(
1410     llvm::StringRef value) {
1411   m_thread_pcs.clear();
1412   for (llvm::StringRef x : llvm::split(value, ',')) {
1413     lldb::addr_t pc;
1414     if (llvm::to_integer(x, pc, 16))
1415       m_thread_pcs.push_back(pc);
1416   }
1417   return m_thread_pcs.size();
1418 }
1419 
1420 bool ProcessGDBRemote::UpdateThreadIDList() {
1421   std::lock_guard<std::recursive_mutex> guard(m_thread_list_real.GetMutex());
1422 
1423   if (m_jthreadsinfo_sp) {
1424     // If we have the JSON threads info, we can get the thread list from that
1425     StructuredData::Array *thread_infos = m_jthreadsinfo_sp->GetAsArray();
1426     if (thread_infos && thread_infos->GetSize() > 0) {
1427       m_thread_ids.clear();
1428       m_thread_pcs.clear();
1429       thread_infos->ForEach([this](StructuredData::Object *object) -> bool {
1430         StructuredData::Dictionary *thread_dict = object->GetAsDictionary();
1431         if (thread_dict) {
1432           // Set the thread stop info from the JSON dictionary
1433           SetThreadStopInfo(thread_dict);
1434           lldb::tid_t tid = LLDB_INVALID_THREAD_ID;
1435           if (thread_dict->GetValueForKeyAsInteger<lldb::tid_t>("tid", tid))
1436             m_thread_ids.push_back(tid);
1437         }
1438         return true; // Keep iterating through all thread_info objects
1439       });
1440     }
1441     if (!m_thread_ids.empty())
1442       return true;
1443   } else {
1444     // See if we can get the thread IDs from the current stop reply packets
1445     // that might contain a "threads" key/value pair
1446 
1447     if (m_last_stop_packet) {
1448       // Get the thread stop info
1449       StringExtractorGDBRemote &stop_info = *m_last_stop_packet;
1450       const std::string &stop_info_str = std::string(stop_info.GetStringRef());
1451 
1452       m_thread_pcs.clear();
1453       const size_t thread_pcs_pos = stop_info_str.find(";thread-pcs:");
1454       if (thread_pcs_pos != std::string::npos) {
1455         const size_t start = thread_pcs_pos + strlen(";thread-pcs:");
1456         const size_t end = stop_info_str.find(';', start);
1457         if (end != std::string::npos) {
1458           std::string value = stop_info_str.substr(start, end - start);
1459           UpdateThreadPCsFromStopReplyThreadsValue(value);
1460         }
1461       }
1462 
1463       const size_t threads_pos = stop_info_str.find(";threads:");
1464       if (threads_pos != std::string::npos) {
1465         const size_t start = threads_pos + strlen(";threads:");
1466         const size_t end = stop_info_str.find(';', start);
1467         if (end != std::string::npos) {
1468           std::string value = stop_info_str.substr(start, end - start);
1469           if (UpdateThreadIDsFromStopReplyThreadsValue(value))
1470             return true;
1471         }
1472       }
1473     }
1474   }
1475 
1476   bool sequence_mutex_unavailable = false;
1477   m_gdb_comm.GetCurrentThreadIDs(m_thread_ids, sequence_mutex_unavailable);
1478   if (sequence_mutex_unavailable) {
1479     return false; // We just didn't get the list
1480   }
1481   return true;
1482 }
1483 
1484 bool ProcessGDBRemote::DoUpdateThreadList(ThreadList &old_thread_list,
1485                                           ThreadList &new_thread_list) {
1486   // locker will keep a mutex locked until it goes out of scope
1487   Log *log = GetLog(GDBRLog::Thread);
1488   LLDB_LOGV(log, "pid = {0}", GetID());
1489 
1490   size_t num_thread_ids = m_thread_ids.size();
1491   // The "m_thread_ids" thread ID list should always be updated after each stop
1492   // reply packet, but in case it isn't, update it here.
1493   if (num_thread_ids == 0) {
1494     if (!UpdateThreadIDList())
1495       return false;
1496     num_thread_ids = m_thread_ids.size();
1497   }
1498 
1499   ThreadList old_thread_list_copy(old_thread_list);
1500   if (num_thread_ids > 0) {
1501     for (size_t i = 0; i < num_thread_ids; ++i) {
1502       tid_t tid = m_thread_ids[i];
1503       ThreadSP thread_sp(
1504           old_thread_list_copy.RemoveThreadByProtocolID(tid, false));
1505       if (!thread_sp) {
1506         thread_sp = std::make_shared<ThreadGDBRemote>(*this, tid);
1507         LLDB_LOGV(log, "Making new thread: {0} for thread ID: {1:x}.",
1508                   thread_sp.get(), thread_sp->GetID());
1509       } else {
1510         LLDB_LOGV(log, "Found old thread: {0} for thread ID: {1:x}.",
1511                   thread_sp.get(), thread_sp->GetID());
1512       }
1513 
1514       SetThreadPc(thread_sp, i);
1515       new_thread_list.AddThreadSortedByIndexID(thread_sp);
1516     }
1517   }
1518 
1519   // Whatever that is left in old_thread_list_copy are not present in
1520   // new_thread_list. Remove non-existent threads from internal id table.
1521   size_t old_num_thread_ids = old_thread_list_copy.GetSize(false);
1522   for (size_t i = 0; i < old_num_thread_ids; i++) {
1523     ThreadSP old_thread_sp(old_thread_list_copy.GetThreadAtIndex(i, false));
1524     if (old_thread_sp) {
1525       lldb::tid_t old_thread_id = old_thread_sp->GetProtocolID();
1526       m_thread_id_to_index_id_map.erase(old_thread_id);
1527     }
1528   }
1529 
1530   return true;
1531 }
1532 
1533 void ProcessGDBRemote::SetThreadPc(const ThreadSP &thread_sp, uint64_t index) {
1534   if (m_thread_ids.size() == m_thread_pcs.size() && thread_sp.get() &&
1535       GetByteOrder() != eByteOrderInvalid) {
1536     ThreadGDBRemote *gdb_thread =
1537         static_cast<ThreadGDBRemote *>(thread_sp.get());
1538     RegisterContextSP reg_ctx_sp(thread_sp->GetRegisterContext());
1539     if (reg_ctx_sp) {
1540       uint32_t pc_regnum = reg_ctx_sp->ConvertRegisterKindToRegisterNumber(
1541           eRegisterKindGeneric, LLDB_REGNUM_GENERIC_PC);
1542       if (pc_regnum != LLDB_INVALID_REGNUM) {
1543         gdb_thread->PrivateSetRegisterValue(pc_regnum, m_thread_pcs[index]);
1544       }
1545     }
1546   }
1547 }
1548 
1549 bool ProcessGDBRemote::GetThreadStopInfoFromJSON(
1550     ThreadGDBRemote *thread, const StructuredData::ObjectSP &thread_infos_sp) {
1551   // See if we got thread stop infos for all threads via the "jThreadsInfo"
1552   // packet
1553   if (thread_infos_sp) {
1554     StructuredData::Array *thread_infos = thread_infos_sp->GetAsArray();
1555     if (thread_infos) {
1556       lldb::tid_t tid;
1557       const size_t n = thread_infos->GetSize();
1558       for (size_t i = 0; i < n; ++i) {
1559         StructuredData::Dictionary *thread_dict =
1560             thread_infos->GetItemAtIndex(i)->GetAsDictionary();
1561         if (thread_dict) {
1562           if (thread_dict->GetValueForKeyAsInteger<lldb::tid_t>(
1563                   "tid", tid, LLDB_INVALID_THREAD_ID)) {
1564             if (tid == thread->GetID())
1565               return (bool)SetThreadStopInfo(thread_dict);
1566           }
1567         }
1568       }
1569     }
1570   }
1571   return false;
1572 }
1573 
1574 bool ProcessGDBRemote::CalculateThreadStopInfo(ThreadGDBRemote *thread) {
1575   // See if we got thread stop infos for all threads via the "jThreadsInfo"
1576   // packet
1577   if (GetThreadStopInfoFromJSON(thread, m_jthreadsinfo_sp))
1578     return true;
1579 
1580   // See if we got thread stop info for any threads valid stop info reasons
1581   // threads via the "jstopinfo" packet stop reply packet key/value pair?
1582   if (m_jstopinfo_sp) {
1583     // If we have "jstopinfo" then we have stop descriptions for all threads
1584     // that have stop reasons, and if there is no entry for a thread, then it
1585     // has no stop reason.
1586     thread->GetRegisterContext()->InvalidateIfNeeded(true);
1587     if (!GetThreadStopInfoFromJSON(thread, m_jstopinfo_sp)) {
1588       thread->SetStopInfo(StopInfoSP());
1589     }
1590     return true;
1591   }
1592 
1593   // Fall back to using the qThreadStopInfo packet
1594   StringExtractorGDBRemote stop_packet;
1595   if (GetGDBRemote().GetThreadStopInfo(thread->GetProtocolID(), stop_packet))
1596     return SetThreadStopInfo(stop_packet) == eStateStopped;
1597   return false;
1598 }
1599 
1600 ThreadSP ProcessGDBRemote::SetThreadStopInfo(
1601     lldb::tid_t tid, ExpeditedRegisterMap &expedited_register_map,
1602     uint8_t signo, const std::string &thread_name, const std::string &reason,
1603     const std::string &description, uint32_t exc_type,
1604     const std::vector<addr_t> &exc_data, addr_t thread_dispatch_qaddr,
1605     bool queue_vars_valid, // Set to true if queue_name, queue_kind and
1606                            // queue_serial are valid
1607     LazyBool associated_with_dispatch_queue, addr_t dispatch_queue_t,
1608     std::string &queue_name, QueueKind queue_kind, uint64_t queue_serial) {
1609   ThreadSP thread_sp;
1610   if (tid != LLDB_INVALID_THREAD_ID) {
1611     // Scope for "locker" below
1612     {
1613       // m_thread_list_real does have its own mutex, but we need to hold onto
1614       // the mutex between the call to m_thread_list_real.FindThreadByID(...)
1615       // and the m_thread_list_real.AddThread(...) so it doesn't change on us
1616       std::lock_guard<std::recursive_mutex> guard(
1617           m_thread_list_real.GetMutex());
1618       thread_sp = m_thread_list_real.FindThreadByProtocolID(tid, false);
1619 
1620       if (!thread_sp) {
1621         // Create the thread if we need to
1622         thread_sp = std::make_shared<ThreadGDBRemote>(*this, tid);
1623         m_thread_list_real.AddThread(thread_sp);
1624       }
1625     }
1626 
1627     if (thread_sp) {
1628       ThreadGDBRemote *gdb_thread =
1629           static_cast<ThreadGDBRemote *>(thread_sp.get());
1630       RegisterContextSP gdb_reg_ctx_sp(gdb_thread->GetRegisterContext());
1631 
1632       gdb_reg_ctx_sp->InvalidateIfNeeded(true);
1633 
1634       auto iter = std::find(m_thread_ids.begin(), m_thread_ids.end(), tid);
1635       if (iter != m_thread_ids.end()) {
1636         SetThreadPc(thread_sp, iter - m_thread_ids.begin());
1637       }
1638 
1639       for (const auto &pair : expedited_register_map) {
1640         StringExtractor reg_value_extractor(pair.second);
1641         WritableDataBufferSP buffer_sp(new DataBufferHeap(
1642             reg_value_extractor.GetStringRef().size() / 2, 0));
1643         reg_value_extractor.GetHexBytes(buffer_sp->GetData(), '\xcc');
1644         uint32_t lldb_regnum =
1645             gdb_reg_ctx_sp->ConvertRegisterKindToRegisterNumber(
1646                 eRegisterKindProcessPlugin, pair.first);
1647         gdb_thread->PrivateSetRegisterValue(lldb_regnum, buffer_sp->GetData());
1648       }
1649 
1650       // AArch64 SVE specific code below calls AArch64SVEReconfigure to update
1651       // SVE register sizes and offsets if value of VG register has changed
1652       // since last stop.
1653       const ArchSpec &arch = GetTarget().GetArchitecture();
1654       if (arch.IsValid() && arch.GetTriple().isAArch64()) {
1655         GDBRemoteRegisterContext *reg_ctx_sp =
1656             static_cast<GDBRemoteRegisterContext *>(
1657                 gdb_thread->GetRegisterContext().get());
1658 
1659         if (reg_ctx_sp)
1660           reg_ctx_sp->AArch64SVEReconfigure();
1661       }
1662 
1663       thread_sp->SetName(thread_name.empty() ? nullptr : thread_name.c_str());
1664 
1665       gdb_thread->SetThreadDispatchQAddr(thread_dispatch_qaddr);
1666       // Check if the GDB server was able to provide the queue name, kind and
1667       // serial number
1668       if (queue_vars_valid)
1669         gdb_thread->SetQueueInfo(std::move(queue_name), queue_kind,
1670                                  queue_serial, dispatch_queue_t,
1671                                  associated_with_dispatch_queue);
1672       else
1673         gdb_thread->ClearQueueInfo();
1674 
1675       gdb_thread->SetAssociatedWithLibdispatchQueue(
1676           associated_with_dispatch_queue);
1677 
1678       if (dispatch_queue_t != LLDB_INVALID_ADDRESS)
1679         gdb_thread->SetQueueLibdispatchQueueAddress(dispatch_queue_t);
1680 
1681       // Make sure we update our thread stop reason just once, but don't
1682       // overwrite the stop info for threads that haven't moved:
1683       StopInfoSP current_stop_info_sp = thread_sp->GetPrivateStopInfo(false);
1684       if (thread_sp->GetTemporaryResumeState() == eStateSuspended &&
1685           current_stop_info_sp) {
1686           thread_sp->SetStopInfo(current_stop_info_sp);
1687           return thread_sp;
1688       }
1689 
1690       if (!thread_sp->StopInfoIsUpToDate()) {
1691         thread_sp->SetStopInfo(StopInfoSP());
1692         // If there's a memory thread backed by this thread, we need to use it
1693         // to calculate StopInfo.
1694         if (ThreadSP memory_thread_sp =
1695                 m_thread_list.GetBackingThread(thread_sp))
1696           thread_sp = memory_thread_sp;
1697 
1698         if (exc_type != 0) {
1699           const size_t exc_data_size = exc_data.size();
1700 
1701           thread_sp->SetStopInfo(
1702               StopInfoMachException::CreateStopReasonWithMachException(
1703                   *thread_sp, exc_type, exc_data_size,
1704                   exc_data_size >= 1 ? exc_data[0] : 0,
1705                   exc_data_size >= 2 ? exc_data[1] : 0,
1706                   exc_data_size >= 3 ? exc_data[2] : 0));
1707         } else {
1708           bool handled = false;
1709           bool did_exec = false;
1710           if (!reason.empty()) {
1711             if (reason == "trace") {
1712               addr_t pc = thread_sp->GetRegisterContext()->GetPC();
1713               lldb::BreakpointSiteSP bp_site_sp = thread_sp->GetProcess()
1714                                                       ->GetBreakpointSiteList()
1715                                                       .FindByAddress(pc);
1716 
1717               // If the current pc is a breakpoint site then the StopInfo
1718               // should be set to Breakpoint Otherwise, it will be set to
1719               // Trace.
1720               if (bp_site_sp && bp_site_sp->ValidForThisThread(*thread_sp)) {
1721                 thread_sp->SetStopInfo(
1722                     StopInfo::CreateStopReasonWithBreakpointSiteID(
1723                         *thread_sp, bp_site_sp->GetID()));
1724               } else
1725                 thread_sp->SetStopInfo(
1726                     StopInfo::CreateStopReasonToTrace(*thread_sp));
1727               handled = true;
1728             } else if (reason == "breakpoint") {
1729               addr_t pc = thread_sp->GetRegisterContext()->GetPC();
1730               lldb::BreakpointSiteSP bp_site_sp = thread_sp->GetProcess()
1731                                                       ->GetBreakpointSiteList()
1732                                                       .FindByAddress(pc);
1733               if (bp_site_sp) {
1734                 // If the breakpoint is for this thread, then we'll report the
1735                 // hit, but if it is for another thread, we can just report no
1736                 // reason.  We don't need to worry about stepping over the
1737                 // breakpoint here, that will be taken care of when the thread
1738                 // resumes and notices that there's a breakpoint under the pc.
1739                 handled = true;
1740                 if (bp_site_sp->ValidForThisThread(*thread_sp)) {
1741                   thread_sp->SetStopInfo(
1742                       StopInfo::CreateStopReasonWithBreakpointSiteID(
1743                           *thread_sp, bp_site_sp->GetID()));
1744                 } else {
1745                   StopInfoSP invalid_stop_info_sp;
1746                   thread_sp->SetStopInfo(invalid_stop_info_sp);
1747                 }
1748               }
1749             } else if (reason == "trap") {
1750               // Let the trap just use the standard signal stop reason below...
1751             } else if (reason == "watchpoint") {
1752               StringExtractor desc_extractor(description.c_str());
1753               addr_t wp_addr = desc_extractor.GetU64(LLDB_INVALID_ADDRESS);
1754               uint32_t wp_index = desc_extractor.GetU32(LLDB_INVALID_INDEX32);
1755               addr_t wp_hit_addr = desc_extractor.GetU64(LLDB_INVALID_ADDRESS);
1756               watch_id_t watch_id = LLDB_INVALID_WATCH_ID;
1757               if (wp_addr != LLDB_INVALID_ADDRESS) {
1758                 WatchpointSP wp_sp;
1759                 ArchSpec::Core core = GetTarget().GetArchitecture().GetCore();
1760                 if ((core >= ArchSpec::kCore_mips_first &&
1761                      core <= ArchSpec::kCore_mips_last) ||
1762                     (core >= ArchSpec::eCore_arm_generic &&
1763                      core <= ArchSpec::eCore_arm_aarch64))
1764                   wp_sp = GetTarget().GetWatchpointList().FindByAddress(
1765                       wp_hit_addr);
1766                 if (!wp_sp)
1767                   wp_sp =
1768                       GetTarget().GetWatchpointList().FindByAddress(wp_addr);
1769                 if (wp_sp) {
1770                   wp_sp->SetHardwareIndex(wp_index);
1771                   watch_id = wp_sp->GetID();
1772                 }
1773               }
1774               if (watch_id == LLDB_INVALID_WATCH_ID) {
1775                 Log *log(GetLog(GDBRLog::Watchpoints));
1776                 LLDB_LOGF(log, "failed to find watchpoint");
1777               }
1778               thread_sp->SetStopInfo(StopInfo::CreateStopReasonWithWatchpointID(
1779                   *thread_sp, watch_id, wp_hit_addr));
1780               handled = true;
1781             } else if (reason == "exception") {
1782               thread_sp->SetStopInfo(StopInfo::CreateStopReasonWithException(
1783                   *thread_sp, description.c_str()));
1784               handled = true;
1785             } else if (reason == "exec") {
1786               did_exec = true;
1787               thread_sp->SetStopInfo(
1788                   StopInfo::CreateStopReasonWithExec(*thread_sp));
1789               handled = true;
1790             } else if (reason == "processor trace") {
1791               thread_sp->SetStopInfo(StopInfo::CreateStopReasonProcessorTrace(
1792                   *thread_sp, description.c_str()));
1793             } else if (reason == "fork") {
1794               StringExtractor desc_extractor(description.c_str());
1795               lldb::pid_t child_pid = desc_extractor.GetU64(
1796                   LLDB_INVALID_PROCESS_ID);
1797               lldb::tid_t child_tid = desc_extractor.GetU64(
1798                   LLDB_INVALID_THREAD_ID);
1799               thread_sp->SetStopInfo(StopInfo::CreateStopReasonFork(
1800                   *thread_sp, child_pid, child_tid));
1801               handled = true;
1802             } else if (reason == "vfork") {
1803               StringExtractor desc_extractor(description.c_str());
1804               lldb::pid_t child_pid = desc_extractor.GetU64(
1805                   LLDB_INVALID_PROCESS_ID);
1806               lldb::tid_t child_tid = desc_extractor.GetU64(
1807                   LLDB_INVALID_THREAD_ID);
1808               thread_sp->SetStopInfo(StopInfo::CreateStopReasonVFork(
1809                   *thread_sp, child_pid, child_tid));
1810               handled = true;
1811             } else if (reason == "vforkdone") {
1812               thread_sp->SetStopInfo(
1813                   StopInfo::CreateStopReasonVForkDone(*thread_sp));
1814               handled = true;
1815             }
1816           } else if (!signo) {
1817             addr_t pc = thread_sp->GetRegisterContext()->GetPC();
1818             lldb::BreakpointSiteSP bp_site_sp =
1819                 thread_sp->GetProcess()->GetBreakpointSiteList().FindByAddress(
1820                     pc);
1821 
1822             // If the current pc is a breakpoint site then the StopInfo should
1823             // be set to Breakpoint even though the remote stub did not set it
1824             // as such. This can happen when the thread is involuntarily
1825             // interrupted (e.g. due to stops on other threads) just as it is
1826             // about to execute the breakpoint instruction.
1827             if (bp_site_sp && bp_site_sp->ValidForThisThread(*thread_sp)) {
1828               thread_sp->SetStopInfo(
1829                   StopInfo::CreateStopReasonWithBreakpointSiteID(
1830                       *thread_sp, bp_site_sp->GetID()));
1831               handled = true;
1832             }
1833           }
1834 
1835           if (!handled && signo && !did_exec) {
1836             if (signo == SIGTRAP) {
1837               // Currently we are going to assume SIGTRAP means we are either
1838               // hitting a breakpoint or hardware single stepping.
1839               handled = true;
1840               addr_t pc = thread_sp->GetRegisterContext()->GetPC() +
1841                           m_breakpoint_pc_offset;
1842               lldb::BreakpointSiteSP bp_site_sp = thread_sp->GetProcess()
1843                                                       ->GetBreakpointSiteList()
1844                                                       .FindByAddress(pc);
1845 
1846               if (bp_site_sp) {
1847                 // If the breakpoint is for this thread, then we'll report the
1848                 // hit, but if it is for another thread, we can just report no
1849                 // reason.  We don't need to worry about stepping over the
1850                 // breakpoint here, that will be taken care of when the thread
1851                 // resumes and notices that there's a breakpoint under the pc.
1852                 if (bp_site_sp->ValidForThisThread(*thread_sp)) {
1853                   if (m_breakpoint_pc_offset != 0)
1854                     thread_sp->GetRegisterContext()->SetPC(pc);
1855                   thread_sp->SetStopInfo(
1856                       StopInfo::CreateStopReasonWithBreakpointSiteID(
1857                           *thread_sp, bp_site_sp->GetID()));
1858                 } else {
1859                   StopInfoSP invalid_stop_info_sp;
1860                   thread_sp->SetStopInfo(invalid_stop_info_sp);
1861                 }
1862               } else {
1863                 // If we were stepping then assume the stop was the result of
1864                 // the trace.  If we were not stepping then report the SIGTRAP.
1865                 // FIXME: We are still missing the case where we single step
1866                 // over a trap instruction.
1867                 if (thread_sp->GetTemporaryResumeState() == eStateStepping)
1868                   thread_sp->SetStopInfo(
1869                       StopInfo::CreateStopReasonToTrace(*thread_sp));
1870                 else
1871                   thread_sp->SetStopInfo(StopInfo::CreateStopReasonWithSignal(
1872                       *thread_sp, signo, description.c_str()));
1873               }
1874             }
1875             if (!handled)
1876               thread_sp->SetStopInfo(StopInfo::CreateStopReasonWithSignal(
1877                   *thread_sp, signo, description.c_str()));
1878           }
1879 
1880           if (!description.empty()) {
1881             lldb::StopInfoSP stop_info_sp(thread_sp->GetStopInfo());
1882             if (stop_info_sp) {
1883               const char *stop_info_desc = stop_info_sp->GetDescription();
1884               if (!stop_info_desc || !stop_info_desc[0])
1885                 stop_info_sp->SetDescription(description.c_str());
1886             } else {
1887               thread_sp->SetStopInfo(StopInfo::CreateStopReasonWithException(
1888                   *thread_sp, description.c_str()));
1889             }
1890           }
1891         }
1892       }
1893     }
1894   }
1895   return thread_sp;
1896 }
1897 
1898 lldb::ThreadSP
1899 ProcessGDBRemote::SetThreadStopInfo(StructuredData::Dictionary *thread_dict) {
1900   static ConstString g_key_tid("tid");
1901   static ConstString g_key_name("name");
1902   static ConstString g_key_reason("reason");
1903   static ConstString g_key_metype("metype");
1904   static ConstString g_key_medata("medata");
1905   static ConstString g_key_qaddr("qaddr");
1906   static ConstString g_key_dispatch_queue_t("dispatch_queue_t");
1907   static ConstString g_key_associated_with_dispatch_queue(
1908       "associated_with_dispatch_queue");
1909   static ConstString g_key_queue_name("qname");
1910   static ConstString g_key_queue_kind("qkind");
1911   static ConstString g_key_queue_serial_number("qserialnum");
1912   static ConstString g_key_registers("registers");
1913   static ConstString g_key_memory("memory");
1914   static ConstString g_key_address("address");
1915   static ConstString g_key_bytes("bytes");
1916   static ConstString g_key_description("description");
1917   static ConstString g_key_signal("signal");
1918 
1919   // Stop with signal and thread info
1920   lldb::tid_t tid = LLDB_INVALID_THREAD_ID;
1921   uint8_t signo = 0;
1922   std::string value;
1923   std::string thread_name;
1924   std::string reason;
1925   std::string description;
1926   uint32_t exc_type = 0;
1927   std::vector<addr_t> exc_data;
1928   addr_t thread_dispatch_qaddr = LLDB_INVALID_ADDRESS;
1929   ExpeditedRegisterMap expedited_register_map;
1930   bool queue_vars_valid = false;
1931   addr_t dispatch_queue_t = LLDB_INVALID_ADDRESS;
1932   LazyBool associated_with_dispatch_queue = eLazyBoolCalculate;
1933   std::string queue_name;
1934   QueueKind queue_kind = eQueueKindUnknown;
1935   uint64_t queue_serial_number = 0;
1936   // Iterate through all of the thread dictionary key/value pairs from the
1937   // structured data dictionary
1938 
1939   // FIXME: we're silently ignoring invalid data here
1940   thread_dict->ForEach([this, &tid, &expedited_register_map, &thread_name,
1941                         &signo, &reason, &description, &exc_type, &exc_data,
1942                         &thread_dispatch_qaddr, &queue_vars_valid,
1943                         &associated_with_dispatch_queue, &dispatch_queue_t,
1944                         &queue_name, &queue_kind, &queue_serial_number](
1945                            ConstString key,
1946                            StructuredData::Object *object) -> bool {
1947     if (key == g_key_tid) {
1948       // thread in big endian hex
1949       tid = object->GetIntegerValue(LLDB_INVALID_THREAD_ID);
1950     } else if (key == g_key_metype) {
1951       // exception type in big endian hex
1952       exc_type = object->GetIntegerValue(0);
1953     } else if (key == g_key_medata) {
1954       // exception data in big endian hex
1955       StructuredData::Array *array = object->GetAsArray();
1956       if (array) {
1957         array->ForEach([&exc_data](StructuredData::Object *object) -> bool {
1958           exc_data.push_back(object->GetIntegerValue());
1959           return true; // Keep iterating through all array items
1960         });
1961       }
1962     } else if (key == g_key_name) {
1963       thread_name = std::string(object->GetStringValue());
1964     } else if (key == g_key_qaddr) {
1965       thread_dispatch_qaddr = object->GetIntegerValue(LLDB_INVALID_ADDRESS);
1966     } else if (key == g_key_queue_name) {
1967       queue_vars_valid = true;
1968       queue_name = std::string(object->GetStringValue());
1969     } else if (key == g_key_queue_kind) {
1970       std::string queue_kind_str = std::string(object->GetStringValue());
1971       if (queue_kind_str == "serial") {
1972         queue_vars_valid = true;
1973         queue_kind = eQueueKindSerial;
1974       } else if (queue_kind_str == "concurrent") {
1975         queue_vars_valid = true;
1976         queue_kind = eQueueKindConcurrent;
1977       }
1978     } else if (key == g_key_queue_serial_number) {
1979       queue_serial_number = object->GetIntegerValue(0);
1980       if (queue_serial_number != 0)
1981         queue_vars_valid = true;
1982     } else if (key == g_key_dispatch_queue_t) {
1983       dispatch_queue_t = object->GetIntegerValue(0);
1984       if (dispatch_queue_t != 0 && dispatch_queue_t != LLDB_INVALID_ADDRESS)
1985         queue_vars_valid = true;
1986     } else if (key == g_key_associated_with_dispatch_queue) {
1987       queue_vars_valid = true;
1988       bool associated = object->GetBooleanValue();
1989       if (associated)
1990         associated_with_dispatch_queue = eLazyBoolYes;
1991       else
1992         associated_with_dispatch_queue = eLazyBoolNo;
1993     } else if (key == g_key_reason) {
1994       reason = std::string(object->GetStringValue());
1995     } else if (key == g_key_description) {
1996       description = std::string(object->GetStringValue());
1997     } else if (key == g_key_registers) {
1998       StructuredData::Dictionary *registers_dict = object->GetAsDictionary();
1999 
2000       if (registers_dict) {
2001         registers_dict->ForEach(
2002             [&expedited_register_map](ConstString key,
2003                                       StructuredData::Object *object) -> bool {
2004               uint32_t reg;
2005               if (llvm::to_integer(key.AsCString(), reg))
2006                 expedited_register_map[reg] =
2007                     std::string(object->GetStringValue());
2008               return true; // Keep iterating through all array items
2009             });
2010       }
2011     } else if (key == g_key_memory) {
2012       StructuredData::Array *array = object->GetAsArray();
2013       if (array) {
2014         array->ForEach([this](StructuredData::Object *object) -> bool {
2015           StructuredData::Dictionary *mem_cache_dict =
2016               object->GetAsDictionary();
2017           if (mem_cache_dict) {
2018             lldb::addr_t mem_cache_addr = LLDB_INVALID_ADDRESS;
2019             if (mem_cache_dict->GetValueForKeyAsInteger<lldb::addr_t>(
2020                     "address", mem_cache_addr)) {
2021               if (mem_cache_addr != LLDB_INVALID_ADDRESS) {
2022                 llvm::StringRef str;
2023                 if (mem_cache_dict->GetValueForKeyAsString("bytes", str)) {
2024                   StringExtractor bytes(str);
2025                   bytes.SetFilePos(0);
2026 
2027                   const size_t byte_size = bytes.GetStringRef().size() / 2;
2028                   WritableDataBufferSP data_buffer_sp(
2029                       new DataBufferHeap(byte_size, 0));
2030                   const size_t bytes_copied =
2031                       bytes.GetHexBytes(data_buffer_sp->GetData(), 0);
2032                   if (bytes_copied == byte_size)
2033                     m_memory_cache.AddL1CacheData(mem_cache_addr,
2034                                                   data_buffer_sp);
2035                 }
2036               }
2037             }
2038           }
2039           return true; // Keep iterating through all array items
2040         });
2041       }
2042 
2043     } else if (key == g_key_signal)
2044       signo = object->GetIntegerValue(LLDB_INVALID_SIGNAL_NUMBER);
2045     return true; // Keep iterating through all dictionary key/value pairs
2046   });
2047 
2048   return SetThreadStopInfo(tid, expedited_register_map, signo, thread_name,
2049                            reason, description, exc_type, exc_data,
2050                            thread_dispatch_qaddr, queue_vars_valid,
2051                            associated_with_dispatch_queue, dispatch_queue_t,
2052                            queue_name, queue_kind, queue_serial_number);
2053 }
2054 
2055 StateType ProcessGDBRemote::SetThreadStopInfo(StringExtractor &stop_packet) {
2056   lldb::pid_t pid = m_gdb_comm.GetCurrentProcessID();
2057   stop_packet.SetFilePos(0);
2058   const char stop_type = stop_packet.GetChar();
2059   switch (stop_type) {
2060   case 'T':
2061   case 'S': {
2062     // This is a bit of a hack, but is is required. If we did exec, we need to
2063     // clear our thread lists and also know to rebuild our dynamic register
2064     // info before we lookup and threads and populate the expedited register
2065     // values so we need to know this right away so we can cleanup and update
2066     // our registers.
2067     const uint32_t stop_id = GetStopID();
2068     if (stop_id == 0) {
2069       // Our first stop, make sure we have a process ID, and also make sure we
2070       // know about our registers
2071       if (GetID() == LLDB_INVALID_PROCESS_ID && pid != LLDB_INVALID_PROCESS_ID)
2072         SetID(pid);
2073       BuildDynamicRegisterInfo(true);
2074     }
2075     // Stop with signal and thread info
2076     lldb::pid_t stop_pid = LLDB_INVALID_PROCESS_ID;
2077     lldb::tid_t tid = LLDB_INVALID_THREAD_ID;
2078     const uint8_t signo = stop_packet.GetHexU8();
2079     llvm::StringRef key;
2080     llvm::StringRef value;
2081     std::string thread_name;
2082     std::string reason;
2083     std::string description;
2084     uint32_t exc_type = 0;
2085     std::vector<addr_t> exc_data;
2086     addr_t thread_dispatch_qaddr = LLDB_INVALID_ADDRESS;
2087     bool queue_vars_valid =
2088         false; // says if locals below that start with "queue_" are valid
2089     addr_t dispatch_queue_t = LLDB_INVALID_ADDRESS;
2090     LazyBool associated_with_dispatch_queue = eLazyBoolCalculate;
2091     std::string queue_name;
2092     QueueKind queue_kind = eQueueKindUnknown;
2093     uint64_t queue_serial_number = 0;
2094     ExpeditedRegisterMap expedited_register_map;
2095     while (stop_packet.GetNameColonValue(key, value)) {
2096       if (key.compare("metype") == 0) {
2097         // exception type in big endian hex
2098         value.getAsInteger(16, exc_type);
2099       } else if (key.compare("medata") == 0) {
2100         // exception data in big endian hex
2101         uint64_t x;
2102         value.getAsInteger(16, x);
2103         exc_data.push_back(x);
2104       } else if (key.compare("thread") == 0) {
2105         // thread-id
2106         StringExtractorGDBRemote thread_id{value};
2107         auto pid_tid = thread_id.GetPidTid(pid);
2108         if (pid_tid) {
2109           stop_pid = pid_tid->first;
2110           tid = pid_tid->second;
2111         } else
2112           tid = LLDB_INVALID_THREAD_ID;
2113       } else if (key.compare("threads") == 0) {
2114         std::lock_guard<std::recursive_mutex> guard(
2115             m_thread_list_real.GetMutex());
2116         UpdateThreadIDsFromStopReplyThreadsValue(value);
2117       } else if (key.compare("thread-pcs") == 0) {
2118         m_thread_pcs.clear();
2119         // A comma separated list of all threads in the current
2120         // process that includes the thread for this stop reply packet
2121         lldb::addr_t pc;
2122         while (!value.empty()) {
2123           llvm::StringRef pc_str;
2124           std::tie(pc_str, value) = value.split(',');
2125           if (pc_str.getAsInteger(16, pc))
2126             pc = LLDB_INVALID_ADDRESS;
2127           m_thread_pcs.push_back(pc);
2128         }
2129       } else if (key.compare("jstopinfo") == 0) {
2130         StringExtractor json_extractor(value);
2131         std::string json;
2132         // Now convert the HEX bytes into a string value
2133         json_extractor.GetHexByteString(json);
2134 
2135         // This JSON contains thread IDs and thread stop info for all threads.
2136         // It doesn't contain expedited registers, memory or queue info.
2137         m_jstopinfo_sp = StructuredData::ParseJSON(json);
2138       } else if (key.compare("hexname") == 0) {
2139         StringExtractor name_extractor(value);
2140         std::string name;
2141         // Now convert the HEX bytes into a string value
2142         name_extractor.GetHexByteString(thread_name);
2143       } else if (key.compare("name") == 0) {
2144         thread_name = std::string(value);
2145       } else if (key.compare("qaddr") == 0) {
2146         value.getAsInteger(16, thread_dispatch_qaddr);
2147       } else if (key.compare("dispatch_queue_t") == 0) {
2148         queue_vars_valid = true;
2149         value.getAsInteger(16, dispatch_queue_t);
2150       } else if (key.compare("qname") == 0) {
2151         queue_vars_valid = true;
2152         StringExtractor name_extractor(value);
2153         // Now convert the HEX bytes into a string value
2154         name_extractor.GetHexByteString(queue_name);
2155       } else if (key.compare("qkind") == 0) {
2156         queue_kind = llvm::StringSwitch<QueueKind>(value)
2157                          .Case("serial", eQueueKindSerial)
2158                          .Case("concurrent", eQueueKindConcurrent)
2159                          .Default(eQueueKindUnknown);
2160         queue_vars_valid = queue_kind != eQueueKindUnknown;
2161       } else if (key.compare("qserialnum") == 0) {
2162         if (!value.getAsInteger(0, queue_serial_number))
2163           queue_vars_valid = true;
2164       } else if (key.compare("reason") == 0) {
2165         reason = std::string(value);
2166       } else if (key.compare("description") == 0) {
2167         StringExtractor desc_extractor(value);
2168         // Now convert the HEX bytes into a string value
2169         desc_extractor.GetHexByteString(description);
2170       } else if (key.compare("memory") == 0) {
2171         // Expedited memory. GDB servers can choose to send back expedited
2172         // memory that can populate the L1 memory cache in the process so that
2173         // things like the frame pointer backchain can be expedited. This will
2174         // help stack backtracing be more efficient by not having to send as
2175         // many memory read requests down the remote GDB server.
2176 
2177         // Key/value pair format: memory:<addr>=<bytes>;
2178         // <addr> is a number whose base will be interpreted by the prefix:
2179         //      "0x[0-9a-fA-F]+" for hex
2180         //      "0[0-7]+" for octal
2181         //      "[1-9]+" for decimal
2182         // <bytes> is native endian ASCII hex bytes just like the register
2183         // values
2184         llvm::StringRef addr_str, bytes_str;
2185         std::tie(addr_str, bytes_str) = value.split('=');
2186         if (!addr_str.empty() && !bytes_str.empty()) {
2187           lldb::addr_t mem_cache_addr = LLDB_INVALID_ADDRESS;
2188           if (!addr_str.getAsInteger(0, mem_cache_addr)) {
2189             StringExtractor bytes(bytes_str);
2190             const size_t byte_size = bytes.GetBytesLeft() / 2;
2191             WritableDataBufferSP data_buffer_sp(
2192                 new DataBufferHeap(byte_size, 0));
2193             const size_t bytes_copied =
2194                 bytes.GetHexBytes(data_buffer_sp->GetData(), 0);
2195             if (bytes_copied == byte_size)
2196               m_memory_cache.AddL1CacheData(mem_cache_addr, data_buffer_sp);
2197           }
2198         }
2199       } else if (key.compare("watch") == 0 || key.compare("rwatch") == 0 ||
2200                  key.compare("awatch") == 0) {
2201         // Support standard GDB remote stop reply packet 'TAAwatch:addr'
2202         lldb::addr_t wp_addr = LLDB_INVALID_ADDRESS;
2203         value.getAsInteger(16, wp_addr);
2204 
2205         WatchpointSP wp_sp =
2206             GetTarget().GetWatchpointList().FindByAddress(wp_addr);
2207         uint32_t wp_index = LLDB_INVALID_INDEX32;
2208 
2209         if (wp_sp)
2210           wp_index = wp_sp->GetHardwareIndex();
2211 
2212         reason = "watchpoint";
2213         StreamString ostr;
2214         ostr.Printf("%" PRIu64 " %" PRIu32, wp_addr, wp_index);
2215         description = std::string(ostr.GetString());
2216       } else if (key.compare("library") == 0) {
2217         auto error = LoadModules();
2218         if (error) {
2219           Log *log(GetLog(GDBRLog::Process));
2220           LLDB_LOG_ERROR(log, std::move(error), "Failed to load modules: {0}");
2221         }
2222       } else if (key.compare("fork") == 0 || key.compare("vfork") == 0) {
2223         // fork includes child pid/tid in thread-id format
2224         StringExtractorGDBRemote thread_id{value};
2225         auto pid_tid = thread_id.GetPidTid(LLDB_INVALID_PROCESS_ID);
2226         if (!pid_tid) {
2227           Log *log(GetLog(GDBRLog::Process));
2228           LLDB_LOG(log, "Invalid PID/TID to fork: {0}", value);
2229           pid_tid = {{LLDB_INVALID_PROCESS_ID, LLDB_INVALID_THREAD_ID}};
2230         }
2231 
2232         reason = key.str();
2233         StreamString ostr;
2234         ostr.Printf("%" PRIu64 " %" PRIu64, pid_tid->first, pid_tid->second);
2235         description = std::string(ostr.GetString());
2236       } else if (key.size() == 2 && ::isxdigit(key[0]) && ::isxdigit(key[1])) {
2237         uint32_t reg = UINT32_MAX;
2238         if (!key.getAsInteger(16, reg))
2239           expedited_register_map[reg] = std::string(std::move(value));
2240       }
2241     }
2242 
2243     if (stop_pid != LLDB_INVALID_PROCESS_ID && stop_pid != pid) {
2244       Log *log = GetLog(GDBRLog::Process);
2245       LLDB_LOG(log,
2246                "Received stop for incorrect PID = {0} (inferior PID = {1})",
2247                stop_pid, pid);
2248       return eStateInvalid;
2249     }
2250 
2251     if (tid == LLDB_INVALID_THREAD_ID) {
2252       // A thread id may be invalid if the response is old style 'S' packet
2253       // which does not provide the
2254       // thread information. So update the thread list and choose the first
2255       // one.
2256       UpdateThreadIDList();
2257 
2258       if (!m_thread_ids.empty()) {
2259         tid = m_thread_ids.front();
2260       }
2261     }
2262 
2263     ThreadSP thread_sp = SetThreadStopInfo(
2264         tid, expedited_register_map, signo, thread_name, reason, description,
2265         exc_type, exc_data, thread_dispatch_qaddr, queue_vars_valid,
2266         associated_with_dispatch_queue, dispatch_queue_t, queue_name,
2267         queue_kind, queue_serial_number);
2268 
2269     return eStateStopped;
2270   } break;
2271 
2272   case 'W':
2273   case 'X':
2274     // process exited
2275     return eStateExited;
2276 
2277   default:
2278     break;
2279   }
2280   return eStateInvalid;
2281 }
2282 
2283 void ProcessGDBRemote::RefreshStateAfterStop() {
2284   std::lock_guard<std::recursive_mutex> guard(m_thread_list_real.GetMutex());
2285 
2286   m_thread_ids.clear();
2287   m_thread_pcs.clear();
2288 
2289   // Set the thread stop info. It might have a "threads" key whose value is a
2290   // list of all thread IDs in the current process, so m_thread_ids might get
2291   // set.
2292   // Check to see if SetThreadStopInfo() filled in m_thread_ids?
2293   if (m_thread_ids.empty()) {
2294       // No, we need to fetch the thread list manually
2295       UpdateThreadIDList();
2296   }
2297 
2298   // We might set some stop info's so make sure the thread list is up to
2299   // date before we do that or we might overwrite what was computed here.
2300   UpdateThreadListIfNeeded();
2301 
2302   if (m_last_stop_packet)
2303     SetThreadStopInfo(*m_last_stop_packet);
2304   m_last_stop_packet.reset();
2305 
2306   // If we have queried for a default thread id
2307   if (m_initial_tid != LLDB_INVALID_THREAD_ID) {
2308     m_thread_list.SetSelectedThreadByID(m_initial_tid);
2309     m_initial_tid = LLDB_INVALID_THREAD_ID;
2310   }
2311 
2312   // Let all threads recover from stopping and do any clean up based on the
2313   // previous thread state (if any).
2314   m_thread_list_real.RefreshStateAfterStop();
2315 }
2316 
2317 Status ProcessGDBRemote::DoHalt(bool &caused_stop) {
2318   Status error;
2319 
2320   if (m_public_state.GetValue() == eStateAttaching) {
2321     // We are being asked to halt during an attach. We need to just close our
2322     // file handle and debugserver will go away, and we can be done...
2323     m_gdb_comm.Disconnect();
2324   } else
2325     caused_stop = m_gdb_comm.Interrupt(GetInterruptTimeout());
2326   return error;
2327 }
2328 
2329 Status ProcessGDBRemote::DoDetach(bool keep_stopped) {
2330   Status error;
2331   Log *log = GetLog(GDBRLog::Process);
2332   LLDB_LOGF(log, "ProcessGDBRemote::DoDetach(keep_stopped: %i)", keep_stopped);
2333 
2334   error = m_gdb_comm.Detach(keep_stopped);
2335   if (log) {
2336     if (error.Success())
2337       log->PutCString(
2338           "ProcessGDBRemote::DoDetach() detach packet sent successfully");
2339     else
2340       LLDB_LOGF(log,
2341                 "ProcessGDBRemote::DoDetach() detach packet send failed: %s",
2342                 error.AsCString() ? error.AsCString() : "<unknown error>");
2343   }
2344 
2345   if (!error.Success())
2346     return error;
2347 
2348   // Sleep for one second to let the process get all detached...
2349   StopAsyncThread();
2350 
2351   SetPrivateState(eStateDetached);
2352   ResumePrivateStateThread();
2353 
2354   // KillDebugserverProcess ();
2355   return error;
2356 }
2357 
2358 Status ProcessGDBRemote::DoDestroy() {
2359   Log *log = GetLog(GDBRLog::Process);
2360   LLDB_LOGF(log, "ProcessGDBRemote::DoDestroy()");
2361 
2362   // Interrupt if our inferior is running...
2363   int exit_status = SIGABRT;
2364   std::string exit_string;
2365 
2366   if (m_gdb_comm.IsConnected()) {
2367     if (m_public_state.GetValue() != eStateAttaching) {
2368       llvm::Expected<int> kill_res = m_gdb_comm.KillProcess(GetID());
2369 
2370       if (kill_res) {
2371         exit_status = kill_res.get();
2372 #if defined(__APPLE__)
2373         // For Native processes on Mac OS X, we launch through the Host
2374         // Platform, then hand the process off to debugserver, which becomes
2375         // the parent process through "PT_ATTACH".  Then when we go to kill
2376         // the process on Mac OS X we call ptrace(PT_KILL) to kill it, then
2377         // we call waitpid which returns with no error and the correct
2378         // status.  But amusingly enough that doesn't seem to actually reap
2379         // the process, but instead it is left around as a Zombie.  Probably
2380         // the kernel is in the process of switching ownership back to lldb
2381         // which was the original parent, and gets confused in the handoff.
2382         // Anyway, so call waitpid here to finally reap it.
2383         PlatformSP platform_sp(GetTarget().GetPlatform());
2384         if (platform_sp && platform_sp->IsHost()) {
2385           int status;
2386           ::pid_t reap_pid;
2387           reap_pid = waitpid(GetID(), &status, WNOHANG);
2388           LLDB_LOGF(log, "Reaped pid: %d, status: %d.\n", reap_pid, status);
2389         }
2390 #endif
2391         ClearThreadIDList();
2392         exit_string.assign("killed");
2393       } else {
2394         exit_string.assign(llvm::toString(kill_res.takeError()));
2395       }
2396     } else {
2397       exit_string.assign("killed or interrupted while attaching.");
2398     }
2399   } else {
2400     // If we missed setting the exit status on the way out, do it here.
2401     // NB set exit status can be called multiple times, the first one sets the
2402     // status.
2403     exit_string.assign("destroying when not connected to debugserver");
2404   }
2405 
2406   SetExitStatus(exit_status, exit_string.c_str());
2407 
2408   StopAsyncThread();
2409   KillDebugserverProcess();
2410   return Status();
2411 }
2412 
2413 void ProcessGDBRemote::SetLastStopPacket(
2414     const StringExtractorGDBRemote &response) {
2415   const bool did_exec =
2416       response.GetStringRef().find(";reason:exec;") != std::string::npos;
2417   if (did_exec) {
2418     Log *log = GetLog(GDBRLog::Process);
2419     LLDB_LOGF(log, "ProcessGDBRemote::SetLastStopPacket () - detected exec");
2420 
2421     m_thread_list_real.Clear();
2422     m_thread_list.Clear();
2423     BuildDynamicRegisterInfo(true);
2424     m_gdb_comm.ResetDiscoverableSettings(did_exec);
2425   }
2426 
2427   m_last_stop_packet = response;
2428 }
2429 
2430 void ProcessGDBRemote::SetUnixSignals(const UnixSignalsSP &signals_sp) {
2431   Process::SetUnixSignals(std::make_shared<GDBRemoteSignals>(signals_sp));
2432 }
2433 
2434 // Process Queries
2435 
2436 bool ProcessGDBRemote::IsAlive() {
2437   return m_gdb_comm.IsConnected() && Process::IsAlive();
2438 }
2439 
2440 addr_t ProcessGDBRemote::GetImageInfoAddress() {
2441   // request the link map address via the $qShlibInfoAddr packet
2442   lldb::addr_t addr = m_gdb_comm.GetShlibInfoAddr();
2443 
2444   // the loaded module list can also provides a link map address
2445   if (addr == LLDB_INVALID_ADDRESS) {
2446     llvm::Expected<LoadedModuleInfoList> list = GetLoadedModuleList();
2447     if (!list) {
2448       Log *log = GetLog(GDBRLog::Process);
2449       LLDB_LOG_ERROR(log, list.takeError(), "Failed to read module list: {0}.");
2450     } else {
2451       addr = list->m_link_map;
2452     }
2453   }
2454 
2455   return addr;
2456 }
2457 
2458 void ProcessGDBRemote::WillPublicStop() {
2459   // See if the GDB remote client supports the JSON threads info. If so, we
2460   // gather stop info for all threads, expedited registers, expedited memory,
2461   // runtime queue information (iOS and MacOSX only), and more. Expediting
2462   // memory will help stack backtracing be much faster. Expediting registers
2463   // will make sure we don't have to read the thread registers for GPRs.
2464   m_jthreadsinfo_sp = m_gdb_comm.GetThreadsInfo();
2465 
2466   if (m_jthreadsinfo_sp) {
2467     // Now set the stop info for each thread and also expedite any registers
2468     // and memory that was in the jThreadsInfo response.
2469     StructuredData::Array *thread_infos = m_jthreadsinfo_sp->GetAsArray();
2470     if (thread_infos) {
2471       const size_t n = thread_infos->GetSize();
2472       for (size_t i = 0; i < n; ++i) {
2473         StructuredData::Dictionary *thread_dict =
2474             thread_infos->GetItemAtIndex(i)->GetAsDictionary();
2475         if (thread_dict)
2476           SetThreadStopInfo(thread_dict);
2477       }
2478     }
2479   }
2480 }
2481 
2482 // Process Memory
2483 size_t ProcessGDBRemote::DoReadMemory(addr_t addr, void *buf, size_t size,
2484                                       Status &error) {
2485   GetMaxMemorySize();
2486   bool binary_memory_read = m_gdb_comm.GetxPacketSupported();
2487   // M and m packets take 2 bytes for 1 byte of memory
2488   size_t max_memory_size =
2489       binary_memory_read ? m_max_memory_size : m_max_memory_size / 2;
2490   if (size > max_memory_size) {
2491     // Keep memory read sizes down to a sane limit. This function will be
2492     // called multiple times in order to complete the task by
2493     // lldb_private::Process so it is ok to do this.
2494     size = max_memory_size;
2495   }
2496 
2497   char packet[64];
2498   int packet_len;
2499   packet_len = ::snprintf(packet, sizeof(packet), "%c%" PRIx64 ",%" PRIx64,
2500                           binary_memory_read ? 'x' : 'm', (uint64_t)addr,
2501                           (uint64_t)size);
2502   assert(packet_len + 1 < (int)sizeof(packet));
2503   UNUSED_IF_ASSERT_DISABLED(packet_len);
2504   StringExtractorGDBRemote response;
2505   if (m_gdb_comm.SendPacketAndWaitForResponse(packet, response,
2506                                               GetInterruptTimeout()) ==
2507       GDBRemoteCommunication::PacketResult::Success) {
2508     if (response.IsNormalResponse()) {
2509       error.Clear();
2510       if (binary_memory_read) {
2511         // The lower level GDBRemoteCommunication packet receive layer has
2512         // already de-quoted any 0x7d character escaping that was present in
2513         // the packet
2514 
2515         size_t data_received_size = response.GetBytesLeft();
2516         if (data_received_size > size) {
2517           // Don't write past the end of BUF if the remote debug server gave us
2518           // too much data for some reason.
2519           data_received_size = size;
2520         }
2521         memcpy(buf, response.GetStringRef().data(), data_received_size);
2522         return data_received_size;
2523       } else {
2524         return response.GetHexBytes(
2525             llvm::MutableArrayRef<uint8_t>((uint8_t *)buf, size), '\xdd');
2526       }
2527     } else if (response.IsErrorResponse())
2528       error.SetErrorStringWithFormat("memory read failed for 0x%" PRIx64, addr);
2529     else if (response.IsUnsupportedResponse())
2530       error.SetErrorStringWithFormat(
2531           "GDB server does not support reading memory");
2532     else
2533       error.SetErrorStringWithFormat(
2534           "unexpected response to GDB server memory read packet '%s': '%s'",
2535           packet, response.GetStringRef().data());
2536   } else {
2537     error.SetErrorStringWithFormat("failed to send packet: '%s'", packet);
2538   }
2539   return 0;
2540 }
2541 
2542 bool ProcessGDBRemote::SupportsMemoryTagging() {
2543   return m_gdb_comm.GetMemoryTaggingSupported();
2544 }
2545 
2546 llvm::Expected<std::vector<uint8_t>>
2547 ProcessGDBRemote::DoReadMemoryTags(lldb::addr_t addr, size_t len,
2548                                    int32_t type) {
2549   // By this point ReadMemoryTags has validated that tagging is enabled
2550   // for this target/process/address.
2551   DataBufferSP buffer_sp = m_gdb_comm.ReadMemoryTags(addr, len, type);
2552   if (!buffer_sp) {
2553     return llvm::createStringError(llvm::inconvertibleErrorCode(),
2554                                    "Error reading memory tags from remote");
2555   }
2556 
2557   // Return the raw tag data
2558   llvm::ArrayRef<uint8_t> tag_data = buffer_sp->GetData();
2559   std::vector<uint8_t> got;
2560   got.reserve(tag_data.size());
2561   std::copy(tag_data.begin(), tag_data.end(), std::back_inserter(got));
2562   return got;
2563 }
2564 
2565 Status ProcessGDBRemote::DoWriteMemoryTags(lldb::addr_t addr, size_t len,
2566                                            int32_t type,
2567                                            const std::vector<uint8_t> &tags) {
2568   // By now WriteMemoryTags should have validated that tagging is enabled
2569   // for this target/process.
2570   return m_gdb_comm.WriteMemoryTags(addr, len, type, tags);
2571 }
2572 
2573 Status ProcessGDBRemote::WriteObjectFile(
2574     std::vector<ObjectFile::LoadableData> entries) {
2575   Status error;
2576   // Sort the entries by address because some writes, like those to flash
2577   // memory, must happen in order of increasing address.
2578   std::stable_sort(
2579       std::begin(entries), std::end(entries),
2580       [](const ObjectFile::LoadableData a, const ObjectFile::LoadableData b) {
2581         return a.Dest < b.Dest;
2582       });
2583   m_allow_flash_writes = true;
2584   error = Process::WriteObjectFile(entries);
2585   if (error.Success())
2586     error = FlashDone();
2587   else
2588     // Even though some of the writing failed, try to send a flash done if some
2589     // of the writing succeeded so the flash state is reset to normal, but
2590     // don't stomp on the error status that was set in the write failure since
2591     // that's the one we want to report back.
2592     FlashDone();
2593   m_allow_flash_writes = false;
2594   return error;
2595 }
2596 
2597 bool ProcessGDBRemote::HasErased(FlashRange range) {
2598   auto size = m_erased_flash_ranges.GetSize();
2599   for (size_t i = 0; i < size; ++i)
2600     if (m_erased_flash_ranges.GetEntryAtIndex(i)->Contains(range))
2601       return true;
2602   return false;
2603 }
2604 
2605 Status ProcessGDBRemote::FlashErase(lldb::addr_t addr, size_t size) {
2606   Status status;
2607 
2608   MemoryRegionInfo region;
2609   status = GetMemoryRegionInfo(addr, region);
2610   if (!status.Success())
2611     return status;
2612 
2613   // The gdb spec doesn't say if erasures are allowed across multiple regions,
2614   // but we'll disallow it to be safe and to keep the logic simple by worring
2615   // about only one region's block size.  DoMemoryWrite is this function's
2616   // primary user, and it can easily keep writes within a single memory region
2617   if (addr + size > region.GetRange().GetRangeEnd()) {
2618     status.SetErrorString("Unable to erase flash in multiple regions");
2619     return status;
2620   }
2621 
2622   uint64_t blocksize = region.GetBlocksize();
2623   if (blocksize == 0) {
2624     status.SetErrorString("Unable to erase flash because blocksize is 0");
2625     return status;
2626   }
2627 
2628   // Erasures can only be done on block boundary adresses, so round down addr
2629   // and round up size
2630   lldb::addr_t block_start_addr = addr - (addr % blocksize);
2631   size += (addr - block_start_addr);
2632   if ((size % blocksize) != 0)
2633     size += (blocksize - size % blocksize);
2634 
2635   FlashRange range(block_start_addr, size);
2636 
2637   if (HasErased(range))
2638     return status;
2639 
2640   // We haven't erased the entire range, but we may have erased part of it.
2641   // (e.g., block A is already erased and range starts in A and ends in B). So,
2642   // adjust range if necessary to exclude already erased blocks.
2643   if (!m_erased_flash_ranges.IsEmpty()) {
2644     // Assuming that writes and erasures are done in increasing addr order,
2645     // because that is a requirement of the vFlashWrite command.  Therefore, we
2646     // only need to look at the last range in the list for overlap.
2647     const auto &last_range = *m_erased_flash_ranges.Back();
2648     if (range.GetRangeBase() < last_range.GetRangeEnd()) {
2649       auto overlap = last_range.GetRangeEnd() - range.GetRangeBase();
2650       // overlap will be less than range.GetByteSize() or else HasErased()
2651       // would have been true
2652       range.SetByteSize(range.GetByteSize() - overlap);
2653       range.SetRangeBase(range.GetRangeBase() + overlap);
2654     }
2655   }
2656 
2657   StreamString packet;
2658   packet.Printf("vFlashErase:%" PRIx64 ",%" PRIx64, range.GetRangeBase(),
2659                 (uint64_t)range.GetByteSize());
2660 
2661   StringExtractorGDBRemote response;
2662   if (m_gdb_comm.SendPacketAndWaitForResponse(packet.GetString(), response,
2663                                               GetInterruptTimeout()) ==
2664       GDBRemoteCommunication::PacketResult::Success) {
2665     if (response.IsOKResponse()) {
2666       m_erased_flash_ranges.Insert(range, true);
2667     } else {
2668       if (response.IsErrorResponse())
2669         status.SetErrorStringWithFormat("flash erase failed for 0x%" PRIx64,
2670                                         addr);
2671       else if (response.IsUnsupportedResponse())
2672         status.SetErrorStringWithFormat("GDB server does not support flashing");
2673       else
2674         status.SetErrorStringWithFormat(
2675             "unexpected response to GDB server flash erase packet '%s': '%s'",
2676             packet.GetData(), response.GetStringRef().data());
2677     }
2678   } else {
2679     status.SetErrorStringWithFormat("failed to send packet: '%s'",
2680                                     packet.GetData());
2681   }
2682   return status;
2683 }
2684 
2685 Status ProcessGDBRemote::FlashDone() {
2686   Status status;
2687   // If we haven't erased any blocks, then we must not have written anything
2688   // either, so there is no need to actually send a vFlashDone command
2689   if (m_erased_flash_ranges.IsEmpty())
2690     return status;
2691   StringExtractorGDBRemote response;
2692   if (m_gdb_comm.SendPacketAndWaitForResponse("vFlashDone", response,
2693                                               GetInterruptTimeout()) ==
2694       GDBRemoteCommunication::PacketResult::Success) {
2695     if (response.IsOKResponse()) {
2696       m_erased_flash_ranges.Clear();
2697     } else {
2698       if (response.IsErrorResponse())
2699         status.SetErrorStringWithFormat("flash done failed");
2700       else if (response.IsUnsupportedResponse())
2701         status.SetErrorStringWithFormat("GDB server does not support flashing");
2702       else
2703         status.SetErrorStringWithFormat(
2704             "unexpected response to GDB server flash done packet: '%s'",
2705             response.GetStringRef().data());
2706     }
2707   } else {
2708     status.SetErrorStringWithFormat("failed to send flash done packet");
2709   }
2710   return status;
2711 }
2712 
2713 size_t ProcessGDBRemote::DoWriteMemory(addr_t addr, const void *buf,
2714                                        size_t size, Status &error) {
2715   GetMaxMemorySize();
2716   // M and m packets take 2 bytes for 1 byte of memory
2717   size_t max_memory_size = m_max_memory_size / 2;
2718   if (size > max_memory_size) {
2719     // Keep memory read sizes down to a sane limit. This function will be
2720     // called multiple times in order to complete the task by
2721     // lldb_private::Process so it is ok to do this.
2722     size = max_memory_size;
2723   }
2724 
2725   StreamGDBRemote packet;
2726 
2727   MemoryRegionInfo region;
2728   Status region_status = GetMemoryRegionInfo(addr, region);
2729 
2730   bool is_flash =
2731       region_status.Success() && region.GetFlash() == MemoryRegionInfo::eYes;
2732 
2733   if (is_flash) {
2734     if (!m_allow_flash_writes) {
2735       error.SetErrorString("Writing to flash memory is not allowed");
2736       return 0;
2737     }
2738     // Keep the write within a flash memory region
2739     if (addr + size > region.GetRange().GetRangeEnd())
2740       size = region.GetRange().GetRangeEnd() - addr;
2741     // Flash memory must be erased before it can be written
2742     error = FlashErase(addr, size);
2743     if (!error.Success())
2744       return 0;
2745     packet.Printf("vFlashWrite:%" PRIx64 ":", addr);
2746     packet.PutEscapedBytes(buf, size);
2747   } else {
2748     packet.Printf("M%" PRIx64 ",%" PRIx64 ":", addr, (uint64_t)size);
2749     packet.PutBytesAsRawHex8(buf, size, endian::InlHostByteOrder(),
2750                              endian::InlHostByteOrder());
2751   }
2752   StringExtractorGDBRemote response;
2753   if (m_gdb_comm.SendPacketAndWaitForResponse(packet.GetString(), response,
2754                                               GetInterruptTimeout()) ==
2755       GDBRemoteCommunication::PacketResult::Success) {
2756     if (response.IsOKResponse()) {
2757       error.Clear();
2758       return size;
2759     } else if (response.IsErrorResponse())
2760       error.SetErrorStringWithFormat("memory write failed for 0x%" PRIx64,
2761                                      addr);
2762     else if (response.IsUnsupportedResponse())
2763       error.SetErrorStringWithFormat(
2764           "GDB server does not support writing memory");
2765     else
2766       error.SetErrorStringWithFormat(
2767           "unexpected response to GDB server memory write packet '%s': '%s'",
2768           packet.GetData(), response.GetStringRef().data());
2769   } else {
2770     error.SetErrorStringWithFormat("failed to send packet: '%s'",
2771                                    packet.GetData());
2772   }
2773   return 0;
2774 }
2775 
2776 lldb::addr_t ProcessGDBRemote::DoAllocateMemory(size_t size,
2777                                                 uint32_t permissions,
2778                                                 Status &error) {
2779   Log *log = GetLog(LLDBLog::Process | LLDBLog::Expressions);
2780   addr_t allocated_addr = LLDB_INVALID_ADDRESS;
2781 
2782   if (m_gdb_comm.SupportsAllocDeallocMemory() != eLazyBoolNo) {
2783     allocated_addr = m_gdb_comm.AllocateMemory(size, permissions);
2784     if (allocated_addr != LLDB_INVALID_ADDRESS ||
2785         m_gdb_comm.SupportsAllocDeallocMemory() == eLazyBoolYes)
2786       return allocated_addr;
2787   }
2788 
2789   if (m_gdb_comm.SupportsAllocDeallocMemory() == eLazyBoolNo) {
2790     // Call mmap() to create memory in the inferior..
2791     unsigned prot = 0;
2792     if (permissions & lldb::ePermissionsReadable)
2793       prot |= eMmapProtRead;
2794     if (permissions & lldb::ePermissionsWritable)
2795       prot |= eMmapProtWrite;
2796     if (permissions & lldb::ePermissionsExecutable)
2797       prot |= eMmapProtExec;
2798 
2799     if (InferiorCallMmap(this, allocated_addr, 0, size, prot,
2800                          eMmapFlagsAnon | eMmapFlagsPrivate, -1, 0))
2801       m_addr_to_mmap_size[allocated_addr] = size;
2802     else {
2803       allocated_addr = LLDB_INVALID_ADDRESS;
2804       LLDB_LOGF(log,
2805                 "ProcessGDBRemote::%s no direct stub support for memory "
2806                 "allocation, and InferiorCallMmap also failed - is stub "
2807                 "missing register context save/restore capability?",
2808                 __FUNCTION__);
2809     }
2810   }
2811 
2812   if (allocated_addr == LLDB_INVALID_ADDRESS)
2813     error.SetErrorStringWithFormat(
2814         "unable to allocate %" PRIu64 " bytes of memory with permissions %s",
2815         (uint64_t)size, GetPermissionsAsCString(permissions));
2816   else
2817     error.Clear();
2818   return allocated_addr;
2819 }
2820 
2821 Status ProcessGDBRemote::DoGetMemoryRegionInfo(addr_t load_addr,
2822                                                MemoryRegionInfo &region_info) {
2823 
2824   Status error(m_gdb_comm.GetMemoryRegionInfo(load_addr, region_info));
2825   return error;
2826 }
2827 
2828 Status ProcessGDBRemote::GetWatchpointSupportInfo(uint32_t &num) {
2829 
2830   Status error(m_gdb_comm.GetWatchpointSupportInfo(num));
2831   return error;
2832 }
2833 
2834 Status ProcessGDBRemote::GetWatchpointSupportInfo(uint32_t &num, bool &after) {
2835   Status error(m_gdb_comm.GetWatchpointSupportInfo(
2836       num, after, GetTarget().GetArchitecture()));
2837   return error;
2838 }
2839 
2840 Status ProcessGDBRemote::DoDeallocateMemory(lldb::addr_t addr) {
2841   Status error;
2842   LazyBool supported = m_gdb_comm.SupportsAllocDeallocMemory();
2843 
2844   switch (supported) {
2845   case eLazyBoolCalculate:
2846     // We should never be deallocating memory without allocating memory first
2847     // so we should never get eLazyBoolCalculate
2848     error.SetErrorString(
2849         "tried to deallocate memory without ever allocating memory");
2850     break;
2851 
2852   case eLazyBoolYes:
2853     if (!m_gdb_comm.DeallocateMemory(addr))
2854       error.SetErrorStringWithFormat(
2855           "unable to deallocate memory at 0x%" PRIx64, addr);
2856     break;
2857 
2858   case eLazyBoolNo:
2859     // Call munmap() to deallocate memory in the inferior..
2860     {
2861       MMapMap::iterator pos = m_addr_to_mmap_size.find(addr);
2862       if (pos != m_addr_to_mmap_size.end() &&
2863           InferiorCallMunmap(this, addr, pos->second))
2864         m_addr_to_mmap_size.erase(pos);
2865       else
2866         error.SetErrorStringWithFormat(
2867             "unable to deallocate memory at 0x%" PRIx64, addr);
2868     }
2869     break;
2870   }
2871 
2872   return error;
2873 }
2874 
2875 // Process STDIO
2876 size_t ProcessGDBRemote::PutSTDIN(const char *src, size_t src_len,
2877                                   Status &error) {
2878   if (m_stdio_communication.IsConnected()) {
2879     ConnectionStatus status;
2880     m_stdio_communication.WriteAll(src, src_len, status, nullptr);
2881   } else if (m_stdin_forward) {
2882     m_gdb_comm.SendStdinNotification(src, src_len);
2883   }
2884   return 0;
2885 }
2886 
2887 Status ProcessGDBRemote::EnableBreakpointSite(BreakpointSite *bp_site) {
2888   Status error;
2889   assert(bp_site != nullptr);
2890 
2891   // Get logging info
2892   Log *log = GetLog(GDBRLog::Breakpoints);
2893   user_id_t site_id = bp_site->GetID();
2894 
2895   // Get the breakpoint address
2896   const addr_t addr = bp_site->GetLoadAddress();
2897 
2898   // Log that a breakpoint was requested
2899   LLDB_LOGF(log,
2900             "ProcessGDBRemote::EnableBreakpointSite (size_id = %" PRIu64
2901             ") address = 0x%" PRIx64,
2902             site_id, (uint64_t)addr);
2903 
2904   // Breakpoint already exists and is enabled
2905   if (bp_site->IsEnabled()) {
2906     LLDB_LOGF(log,
2907               "ProcessGDBRemote::EnableBreakpointSite (size_id = %" PRIu64
2908               ") address = 0x%" PRIx64 " -- SUCCESS (already enabled)",
2909               site_id, (uint64_t)addr);
2910     return error;
2911   }
2912 
2913   // Get the software breakpoint trap opcode size
2914   const size_t bp_op_size = GetSoftwareBreakpointTrapOpcode(bp_site);
2915 
2916   // SupportsGDBStoppointPacket() simply checks a boolean, indicating if this
2917   // breakpoint type is supported by the remote stub. These are set to true by
2918   // default, and later set to false only after we receive an unimplemented
2919   // response when sending a breakpoint packet. This means initially that
2920   // unless we were specifically instructed to use a hardware breakpoint, LLDB
2921   // will attempt to set a software breakpoint. HardwareRequired() also queries
2922   // a boolean variable which indicates if the user specifically asked for
2923   // hardware breakpoints.  If true then we will skip over software
2924   // breakpoints.
2925   if (m_gdb_comm.SupportsGDBStoppointPacket(eBreakpointSoftware) &&
2926       (!bp_site->HardwareRequired())) {
2927     // Try to send off a software breakpoint packet ($Z0)
2928     uint8_t error_no = m_gdb_comm.SendGDBStoppointTypePacket(
2929         eBreakpointSoftware, true, addr, bp_op_size, GetInterruptTimeout());
2930     if (error_no == 0) {
2931       // The breakpoint was placed successfully
2932       bp_site->SetEnabled(true);
2933       bp_site->SetType(BreakpointSite::eExternal);
2934       return error;
2935     }
2936 
2937     // SendGDBStoppointTypePacket() will return an error if it was unable to
2938     // set this breakpoint. We need to differentiate between a error specific
2939     // to placing this breakpoint or if we have learned that this breakpoint
2940     // type is unsupported. To do this, we must test the support boolean for
2941     // this breakpoint type to see if it now indicates that this breakpoint
2942     // type is unsupported.  If they are still supported then we should return
2943     // with the error code.  If they are now unsupported, then we would like to
2944     // fall through and try another form of breakpoint.
2945     if (m_gdb_comm.SupportsGDBStoppointPacket(eBreakpointSoftware)) {
2946       if (error_no != UINT8_MAX)
2947         error.SetErrorStringWithFormat(
2948             "error: %d sending the breakpoint request", error_no);
2949       else
2950         error.SetErrorString("error sending the breakpoint request");
2951       return error;
2952     }
2953 
2954     // We reach here when software breakpoints have been found to be
2955     // unsupported. For future calls to set a breakpoint, we will not attempt
2956     // to set a breakpoint with a type that is known not to be supported.
2957     LLDB_LOGF(log, "Software breakpoints are unsupported");
2958 
2959     // So we will fall through and try a hardware breakpoint
2960   }
2961 
2962   // The process of setting a hardware breakpoint is much the same as above.
2963   // We check the supported boolean for this breakpoint type, and if it is
2964   // thought to be supported then we will try to set this breakpoint with a
2965   // hardware breakpoint.
2966   if (m_gdb_comm.SupportsGDBStoppointPacket(eBreakpointHardware)) {
2967     // Try to send off a hardware breakpoint packet ($Z1)
2968     uint8_t error_no = m_gdb_comm.SendGDBStoppointTypePacket(
2969         eBreakpointHardware, true, addr, bp_op_size, GetInterruptTimeout());
2970     if (error_no == 0) {
2971       // The breakpoint was placed successfully
2972       bp_site->SetEnabled(true);
2973       bp_site->SetType(BreakpointSite::eHardware);
2974       return error;
2975     }
2976 
2977     // Check if the error was something other then an unsupported breakpoint
2978     // type
2979     if (m_gdb_comm.SupportsGDBStoppointPacket(eBreakpointHardware)) {
2980       // Unable to set this hardware breakpoint
2981       if (error_no != UINT8_MAX)
2982         error.SetErrorStringWithFormat(
2983             "error: %d sending the hardware breakpoint request "
2984             "(hardware breakpoint resources might be exhausted or unavailable)",
2985             error_no);
2986       else
2987         error.SetErrorString("error sending the hardware breakpoint request "
2988                              "(hardware breakpoint resources "
2989                              "might be exhausted or unavailable)");
2990       return error;
2991     }
2992 
2993     // We will reach here when the stub gives an unsupported response to a
2994     // hardware breakpoint
2995     LLDB_LOGF(log, "Hardware breakpoints are unsupported");
2996 
2997     // Finally we will falling through to a #trap style breakpoint
2998   }
2999 
3000   // Don't fall through when hardware breakpoints were specifically requested
3001   if (bp_site->HardwareRequired()) {
3002     error.SetErrorString("hardware breakpoints are not supported");
3003     return error;
3004   }
3005 
3006   // As a last resort we want to place a manual breakpoint. An instruction is
3007   // placed into the process memory using memory write packets.
3008   return EnableSoftwareBreakpoint(bp_site);
3009 }
3010 
3011 Status ProcessGDBRemote::DisableBreakpointSite(BreakpointSite *bp_site) {
3012   Status error;
3013   assert(bp_site != nullptr);
3014   addr_t addr = bp_site->GetLoadAddress();
3015   user_id_t site_id = bp_site->GetID();
3016   Log *log = GetLog(GDBRLog::Breakpoints);
3017   LLDB_LOGF(log,
3018             "ProcessGDBRemote::DisableBreakpointSite (site_id = %" PRIu64
3019             ") addr = 0x%8.8" PRIx64,
3020             site_id, (uint64_t)addr);
3021 
3022   if (bp_site->IsEnabled()) {
3023     const size_t bp_op_size = GetSoftwareBreakpointTrapOpcode(bp_site);
3024 
3025     BreakpointSite::Type bp_type = bp_site->GetType();
3026     switch (bp_type) {
3027     case BreakpointSite::eSoftware:
3028       error = DisableSoftwareBreakpoint(bp_site);
3029       break;
3030 
3031     case BreakpointSite::eHardware:
3032       if (m_gdb_comm.SendGDBStoppointTypePacket(eBreakpointHardware, false,
3033                                                 addr, bp_op_size,
3034                                                 GetInterruptTimeout()))
3035         error.SetErrorToGenericError();
3036       break;
3037 
3038     case BreakpointSite::eExternal: {
3039       if (m_gdb_comm.SendGDBStoppointTypePacket(eBreakpointSoftware, false,
3040                                                 addr, bp_op_size,
3041                                                 GetInterruptTimeout()))
3042         error.SetErrorToGenericError();
3043     } break;
3044     }
3045     if (error.Success())
3046       bp_site->SetEnabled(false);
3047   } else {
3048     LLDB_LOGF(log,
3049               "ProcessGDBRemote::DisableBreakpointSite (site_id = %" PRIu64
3050               ") addr = 0x%8.8" PRIx64 " -- SUCCESS (already disabled)",
3051               site_id, (uint64_t)addr);
3052     return error;
3053   }
3054 
3055   if (error.Success())
3056     error.SetErrorToGenericError();
3057   return error;
3058 }
3059 
3060 // Pre-requisite: wp != NULL.
3061 static GDBStoppointType GetGDBStoppointType(Watchpoint *wp) {
3062   assert(wp);
3063   bool watch_read = wp->WatchpointRead();
3064   bool watch_write = wp->WatchpointWrite();
3065 
3066   // watch_read and watch_write cannot both be false.
3067   assert(watch_read || watch_write);
3068   if (watch_read && watch_write)
3069     return eWatchpointReadWrite;
3070   else if (watch_read)
3071     return eWatchpointRead;
3072   else // Must be watch_write, then.
3073     return eWatchpointWrite;
3074 }
3075 
3076 Status ProcessGDBRemote::EnableWatchpoint(Watchpoint *wp, bool notify) {
3077   Status error;
3078   if (wp) {
3079     user_id_t watchID = wp->GetID();
3080     addr_t addr = wp->GetLoadAddress();
3081     Log *log(GetLog(GDBRLog::Watchpoints));
3082     LLDB_LOGF(log, "ProcessGDBRemote::EnableWatchpoint(watchID = %" PRIu64 ")",
3083               watchID);
3084     if (wp->IsEnabled()) {
3085       LLDB_LOGF(log,
3086                 "ProcessGDBRemote::EnableWatchpoint(watchID = %" PRIu64
3087                 ") addr = 0x%8.8" PRIx64 ": watchpoint already enabled.",
3088                 watchID, (uint64_t)addr);
3089       return error;
3090     }
3091 
3092     GDBStoppointType type = GetGDBStoppointType(wp);
3093     // Pass down an appropriate z/Z packet...
3094     if (m_gdb_comm.SupportsGDBStoppointPacket(type)) {
3095       if (m_gdb_comm.SendGDBStoppointTypePacket(type, true, addr,
3096                                                 wp->GetByteSize(),
3097                                                 GetInterruptTimeout()) == 0) {
3098         wp->SetEnabled(true, notify);
3099         return error;
3100       } else
3101         error.SetErrorString("sending gdb watchpoint packet failed");
3102     } else
3103       error.SetErrorString("watchpoints not supported");
3104   } else {
3105     error.SetErrorString("Watchpoint argument was NULL.");
3106   }
3107   if (error.Success())
3108     error.SetErrorToGenericError();
3109   return error;
3110 }
3111 
3112 Status ProcessGDBRemote::DisableWatchpoint(Watchpoint *wp, bool notify) {
3113   Status error;
3114   if (wp) {
3115     user_id_t watchID = wp->GetID();
3116 
3117     Log *log(GetLog(GDBRLog::Watchpoints));
3118 
3119     addr_t addr = wp->GetLoadAddress();
3120 
3121     LLDB_LOGF(log,
3122               "ProcessGDBRemote::DisableWatchpoint (watchID = %" PRIu64
3123               ") addr = 0x%8.8" PRIx64,
3124               watchID, (uint64_t)addr);
3125 
3126     if (!wp->IsEnabled()) {
3127       LLDB_LOGF(log,
3128                 "ProcessGDBRemote::DisableWatchpoint (watchID = %" PRIu64
3129                 ") addr = 0x%8.8" PRIx64 " -- SUCCESS (already disabled)",
3130                 watchID, (uint64_t)addr);
3131       // See also 'class WatchpointSentry' within StopInfo.cpp. This disabling
3132       // attempt might come from the user-supplied actions, we'll route it in
3133       // order for the watchpoint object to intelligently process this action.
3134       wp->SetEnabled(false, notify);
3135       return error;
3136     }
3137 
3138     if (wp->IsHardware()) {
3139       GDBStoppointType type = GetGDBStoppointType(wp);
3140       // Pass down an appropriate z/Z packet...
3141       if (m_gdb_comm.SendGDBStoppointTypePacket(type, false, addr,
3142                                                 wp->GetByteSize(),
3143                                                 GetInterruptTimeout()) == 0) {
3144         wp->SetEnabled(false, notify);
3145         return error;
3146       } else
3147         error.SetErrorString("sending gdb watchpoint packet failed");
3148     }
3149     // TODO: clear software watchpoints if we implement them
3150   } else {
3151     error.SetErrorString("Watchpoint argument was NULL.");
3152   }
3153   if (error.Success())
3154     error.SetErrorToGenericError();
3155   return error;
3156 }
3157 
3158 void ProcessGDBRemote::Clear() {
3159   m_thread_list_real.Clear();
3160   m_thread_list.Clear();
3161 }
3162 
3163 Status ProcessGDBRemote::DoSignal(int signo) {
3164   Status error;
3165   Log *log = GetLog(GDBRLog::Process);
3166   LLDB_LOGF(log, "ProcessGDBRemote::DoSignal (signal = %d)", signo);
3167 
3168   if (!m_gdb_comm.SendAsyncSignal(signo, GetInterruptTimeout()))
3169     error.SetErrorStringWithFormat("failed to send signal %i", signo);
3170   return error;
3171 }
3172 
3173 Status
3174 ProcessGDBRemote::EstablishConnectionIfNeeded(const ProcessInfo &process_info) {
3175   // Make sure we aren't already connected?
3176   if (m_gdb_comm.IsConnected())
3177     return Status();
3178 
3179   PlatformSP platform_sp(GetTarget().GetPlatform());
3180   if (platform_sp && !platform_sp->IsHost())
3181     return Status("Lost debug server connection");
3182 
3183   auto error = LaunchAndConnectToDebugserver(process_info);
3184   if (error.Fail()) {
3185     const char *error_string = error.AsCString();
3186     if (error_string == nullptr)
3187       error_string = "unable to launch " DEBUGSERVER_BASENAME;
3188   }
3189   return error;
3190 }
3191 #if !defined(_WIN32)
3192 #define USE_SOCKETPAIR_FOR_LOCAL_CONNECTION 1
3193 #endif
3194 
3195 #ifdef USE_SOCKETPAIR_FOR_LOCAL_CONNECTION
3196 static bool SetCloexecFlag(int fd) {
3197 #if defined(FD_CLOEXEC)
3198   int flags = ::fcntl(fd, F_GETFD);
3199   if (flags == -1)
3200     return false;
3201   return (::fcntl(fd, F_SETFD, flags | FD_CLOEXEC) == 0);
3202 #else
3203   return false;
3204 #endif
3205 }
3206 #endif
3207 
3208 Status ProcessGDBRemote::LaunchAndConnectToDebugserver(
3209     const ProcessInfo &process_info) {
3210   using namespace std::placeholders; // For _1, _2, etc.
3211 
3212   Status error;
3213   if (m_debugserver_pid == LLDB_INVALID_PROCESS_ID) {
3214     // If we locate debugserver, keep that located version around
3215     static FileSpec g_debugserver_file_spec;
3216 
3217     ProcessLaunchInfo debugserver_launch_info;
3218     // Make debugserver run in its own session so signals generated by special
3219     // terminal key sequences (^C) don't affect debugserver.
3220     debugserver_launch_info.SetLaunchInSeparateProcessGroup(true);
3221 
3222     const std::weak_ptr<ProcessGDBRemote> this_wp =
3223         std::static_pointer_cast<ProcessGDBRemote>(shared_from_this());
3224     debugserver_launch_info.SetMonitorProcessCallback(
3225         std::bind(MonitorDebugserverProcess, this_wp, _1, _2, _3));
3226     debugserver_launch_info.SetUserID(process_info.GetUserID());
3227 
3228 #if defined(__APPLE__)
3229     // On macOS 11, we need to support x86_64 applications translated to
3230     // arm64. We check whether a binary is translated and spawn the correct
3231     // debugserver accordingly.
3232     int mib[] = { CTL_KERN, KERN_PROC, KERN_PROC_PID,
3233                   static_cast<int>(process_info.GetProcessID()) };
3234     struct kinfo_proc processInfo;
3235     size_t bufsize = sizeof(processInfo);
3236     if (sysctl(mib, (unsigned)(sizeof(mib)/sizeof(int)), &processInfo,
3237                &bufsize, NULL, 0) == 0 && bufsize > 0) {
3238       if (processInfo.kp_proc.p_flag & P_TRANSLATED) {
3239         FileSpec rosetta_debugserver("/Library/Apple/usr/libexec/oah/debugserver");
3240         debugserver_launch_info.SetExecutableFile(rosetta_debugserver, false);
3241       }
3242     }
3243 #endif
3244 
3245     int communication_fd = -1;
3246 #ifdef USE_SOCKETPAIR_FOR_LOCAL_CONNECTION
3247     // Use a socketpair on non-Windows systems for security and performance
3248     // reasons.
3249     int sockets[2]; /* the pair of socket descriptors */
3250     if (socketpair(AF_UNIX, SOCK_STREAM, 0, sockets) == -1) {
3251       error.SetErrorToErrno();
3252       return error;
3253     }
3254 
3255     int our_socket = sockets[0];
3256     int gdb_socket = sockets[1];
3257     auto cleanup_our = llvm::make_scope_exit([&]() { close(our_socket); });
3258     auto cleanup_gdb = llvm::make_scope_exit([&]() { close(gdb_socket); });
3259 
3260     // Don't let any child processes inherit our communication socket
3261     SetCloexecFlag(our_socket);
3262     communication_fd = gdb_socket;
3263 #endif
3264 
3265     error = m_gdb_comm.StartDebugserverProcess(
3266         nullptr, GetTarget().GetPlatform().get(), debugserver_launch_info,
3267         nullptr, nullptr, communication_fd);
3268 
3269     if (error.Success())
3270       m_debugserver_pid = debugserver_launch_info.GetProcessID();
3271     else
3272       m_debugserver_pid = LLDB_INVALID_PROCESS_ID;
3273 
3274     if (m_debugserver_pid != LLDB_INVALID_PROCESS_ID) {
3275 #ifdef USE_SOCKETPAIR_FOR_LOCAL_CONNECTION
3276       // Our process spawned correctly, we can now set our connection to use
3277       // our end of the socket pair
3278       cleanup_our.release();
3279       m_gdb_comm.SetConnection(
3280           std::make_unique<ConnectionFileDescriptor>(our_socket, true));
3281 #endif
3282       StartAsyncThread();
3283     }
3284 
3285     if (error.Fail()) {
3286       Log *log = GetLog(GDBRLog::Process);
3287 
3288       LLDB_LOGF(log, "failed to start debugserver process: %s",
3289                 error.AsCString());
3290       return error;
3291     }
3292 
3293     if (m_gdb_comm.IsConnected()) {
3294       // Finish the connection process by doing the handshake without
3295       // connecting (send NULL URL)
3296       error = ConnectToDebugserver("");
3297     } else {
3298       error.SetErrorString("connection failed");
3299     }
3300   }
3301   return error;
3302 }
3303 
3304 void ProcessGDBRemote::MonitorDebugserverProcess(
3305     std::weak_ptr<ProcessGDBRemote> process_wp, lldb::pid_t debugserver_pid,
3306     int signo,      // Zero for no signal
3307     int exit_status // Exit value of process if signal is zero
3308 ) {
3309   // "debugserver_pid" argument passed in is the process ID for debugserver
3310   // that we are tracking...
3311   Log *log = GetLog(GDBRLog::Process);
3312 
3313   LLDB_LOGF(log,
3314             "ProcessGDBRemote::%s(process_wp, pid=%" PRIu64
3315             ", signo=%i (0x%x), exit_status=%i)",
3316             __FUNCTION__, debugserver_pid, signo, signo, exit_status);
3317 
3318   std::shared_ptr<ProcessGDBRemote> process_sp = process_wp.lock();
3319   LLDB_LOGF(log, "ProcessGDBRemote::%s(process = %p)", __FUNCTION__,
3320             static_cast<void *>(process_sp.get()));
3321   if (!process_sp || process_sp->m_debugserver_pid != debugserver_pid)
3322     return;
3323 
3324   // Sleep for a half a second to make sure our inferior process has time to
3325   // set its exit status before we set it incorrectly when both the debugserver
3326   // and the inferior process shut down.
3327   std::this_thread::sleep_for(std::chrono::milliseconds(500));
3328 
3329   // If our process hasn't yet exited, debugserver might have died. If the
3330   // process did exit, then we are reaping it.
3331   const StateType state = process_sp->GetState();
3332 
3333   if (state != eStateInvalid && state != eStateUnloaded &&
3334       state != eStateExited && state != eStateDetached) {
3335     char error_str[1024];
3336     if (signo) {
3337       const char *signal_cstr =
3338           process_sp->GetUnixSignals()->GetSignalAsCString(signo);
3339       if (signal_cstr)
3340         ::snprintf(error_str, sizeof(error_str),
3341                    DEBUGSERVER_BASENAME " died with signal %s", signal_cstr);
3342       else
3343         ::snprintf(error_str, sizeof(error_str),
3344                    DEBUGSERVER_BASENAME " died with signal %i", signo);
3345     } else {
3346       ::snprintf(error_str, sizeof(error_str),
3347                  DEBUGSERVER_BASENAME " died with an exit status of 0x%8.8x",
3348                  exit_status);
3349     }
3350 
3351     process_sp->SetExitStatus(-1, error_str);
3352   }
3353   // Debugserver has exited we need to let our ProcessGDBRemote know that it no
3354   // longer has a debugserver instance
3355   process_sp->m_debugserver_pid = LLDB_INVALID_PROCESS_ID;
3356 }
3357 
3358 void ProcessGDBRemote::KillDebugserverProcess() {
3359   m_gdb_comm.Disconnect();
3360   if (m_debugserver_pid != LLDB_INVALID_PROCESS_ID) {
3361     Host::Kill(m_debugserver_pid, SIGINT);
3362     m_debugserver_pid = LLDB_INVALID_PROCESS_ID;
3363   }
3364 }
3365 
3366 void ProcessGDBRemote::Initialize() {
3367   static llvm::once_flag g_once_flag;
3368 
3369   llvm::call_once(g_once_flag, []() {
3370     PluginManager::RegisterPlugin(GetPluginNameStatic(),
3371                                   GetPluginDescriptionStatic(), CreateInstance,
3372                                   DebuggerInitialize);
3373   });
3374 }
3375 
3376 void ProcessGDBRemote::DebuggerInitialize(Debugger &debugger) {
3377   if (!PluginManager::GetSettingForProcessPlugin(
3378           debugger, PluginProperties::GetSettingName())) {
3379     const bool is_global_setting = true;
3380     PluginManager::CreateSettingForProcessPlugin(
3381         debugger, GetGlobalPluginProperties().GetValueProperties(),
3382         ConstString("Properties for the gdb-remote process plug-in."),
3383         is_global_setting);
3384   }
3385 }
3386 
3387 bool ProcessGDBRemote::StartAsyncThread() {
3388   Log *log = GetLog(GDBRLog::Process);
3389 
3390   LLDB_LOGF(log, "ProcessGDBRemote::%s ()", __FUNCTION__);
3391 
3392   std::lock_guard<std::recursive_mutex> guard(m_async_thread_state_mutex);
3393   if (!m_async_thread.IsJoinable()) {
3394     // Create a thread that watches our internal state and controls which
3395     // events make it to clients (into the DCProcess event queue).
3396 
3397     llvm::Expected<HostThread> async_thread =
3398         ThreadLauncher::LaunchThread("<lldb.process.gdb-remote.async>", [this] {
3399           return ProcessGDBRemote::AsyncThread();
3400         });
3401     if (!async_thread) {
3402       LLDB_LOG_ERROR(GetLog(LLDBLog::Host), async_thread.takeError(),
3403                      "failed to launch host thread: {}");
3404       return false;
3405     }
3406     m_async_thread = *async_thread;
3407   } else
3408     LLDB_LOGF(log,
3409               "ProcessGDBRemote::%s () - Called when Async thread was "
3410               "already running.",
3411               __FUNCTION__);
3412 
3413   return m_async_thread.IsJoinable();
3414 }
3415 
3416 void ProcessGDBRemote::StopAsyncThread() {
3417   Log *log = GetLog(GDBRLog::Process);
3418 
3419   LLDB_LOGF(log, "ProcessGDBRemote::%s ()", __FUNCTION__);
3420 
3421   std::lock_guard<std::recursive_mutex> guard(m_async_thread_state_mutex);
3422   if (m_async_thread.IsJoinable()) {
3423     m_async_broadcaster.BroadcastEvent(eBroadcastBitAsyncThreadShouldExit);
3424 
3425     //  This will shut down the async thread.
3426     m_gdb_comm.Disconnect(); // Disconnect from the debug server.
3427 
3428     // Stop the stdio thread
3429     m_async_thread.Join(nullptr);
3430     m_async_thread.Reset();
3431   } else
3432     LLDB_LOGF(
3433         log,
3434         "ProcessGDBRemote::%s () - Called when Async thread was not running.",
3435         __FUNCTION__);
3436 }
3437 
3438 thread_result_t ProcessGDBRemote::AsyncThread() {
3439   Log *log = GetLog(GDBRLog::Process);
3440   LLDB_LOGF(log, "ProcessGDBRemote::%s(pid = %" PRIu64 ") thread starting...",
3441             __FUNCTION__, GetID());
3442 
3443   EventSP event_sp;
3444 
3445   // We need to ignore any packets that come in after we have
3446   // have decided the process has exited.  There are some
3447   // situations, for instance when we try to interrupt a running
3448   // process and the interrupt fails, where another packet might
3449   // get delivered after we've decided to give up on the process.
3450   // But once we've decided we are done with the process we will
3451   // not be in a state to do anything useful with new packets.
3452   // So it is safer to simply ignore any remaining packets by
3453   // explicitly checking for eStateExited before reentering the
3454   // fetch loop.
3455 
3456   bool done = false;
3457   while (!done && GetPrivateState() != eStateExited) {
3458     LLDB_LOGF(log,
3459               "ProcessGDBRemote::%s(pid = %" PRIu64
3460               ") listener.WaitForEvent (NULL, event_sp)...",
3461               __FUNCTION__, GetID());
3462 
3463     if (m_async_listener_sp->GetEvent(event_sp, llvm::None)) {
3464       const uint32_t event_type = event_sp->GetType();
3465       if (event_sp->BroadcasterIs(&m_async_broadcaster)) {
3466         LLDB_LOGF(log,
3467                   "ProcessGDBRemote::%s(pid = %" PRIu64
3468                   ") Got an event of type: %d...",
3469                   __FUNCTION__, GetID(), event_type);
3470 
3471         switch (event_type) {
3472         case eBroadcastBitAsyncContinue: {
3473           const EventDataBytes *continue_packet =
3474               EventDataBytes::GetEventDataFromEvent(event_sp.get());
3475 
3476           if (continue_packet) {
3477             const char *continue_cstr =
3478                 (const char *)continue_packet->GetBytes();
3479             const size_t continue_cstr_len = continue_packet->GetByteSize();
3480             LLDB_LOGF(log,
3481                       "ProcessGDBRemote::%s(pid = %" PRIu64
3482                       ") got eBroadcastBitAsyncContinue: %s",
3483                       __FUNCTION__, GetID(), continue_cstr);
3484 
3485             if (::strstr(continue_cstr, "vAttach") == nullptr)
3486               SetPrivateState(eStateRunning);
3487             StringExtractorGDBRemote response;
3488 
3489             StateType stop_state =
3490                 GetGDBRemote().SendContinuePacketAndWaitForResponse(
3491                     *this, *GetUnixSignals(),
3492                     llvm::StringRef(continue_cstr, continue_cstr_len),
3493                     GetInterruptTimeout(), response);
3494 
3495             // We need to immediately clear the thread ID list so we are sure
3496             // to get a valid list of threads. The thread ID list might be
3497             // contained within the "response", or the stop reply packet that
3498             // caused the stop. So clear it now before we give the stop reply
3499             // packet to the process using the
3500             // SetLastStopPacket()...
3501             ClearThreadIDList();
3502 
3503             switch (stop_state) {
3504             case eStateStopped:
3505             case eStateCrashed:
3506             case eStateSuspended:
3507               SetLastStopPacket(response);
3508               SetPrivateState(stop_state);
3509               break;
3510 
3511             case eStateExited: {
3512               SetLastStopPacket(response);
3513               ClearThreadIDList();
3514               response.SetFilePos(1);
3515 
3516               int exit_status = response.GetHexU8();
3517               std::string desc_string;
3518               if (response.GetBytesLeft() > 0 && response.GetChar('-') == ';') {
3519                 llvm::StringRef desc_str;
3520                 llvm::StringRef desc_token;
3521                 while (response.GetNameColonValue(desc_token, desc_str)) {
3522                   if (desc_token != "description")
3523                     continue;
3524                   StringExtractor extractor(desc_str);
3525                   extractor.GetHexByteString(desc_string);
3526                 }
3527               }
3528               SetExitStatus(exit_status, desc_string.c_str());
3529               done = true;
3530               break;
3531             }
3532             case eStateInvalid: {
3533               // Check to see if we were trying to attach and if we got back
3534               // the "E87" error code from debugserver -- this indicates that
3535               // the process is not debuggable.  Return a slightly more
3536               // helpful error message about why the attach failed.
3537               if (::strstr(continue_cstr, "vAttach") != nullptr &&
3538                   response.GetError() == 0x87) {
3539                 SetExitStatus(-1, "cannot attach to process due to "
3540                                   "System Integrity Protection");
3541               } else if (::strstr(continue_cstr, "vAttach") != nullptr &&
3542                          response.GetStatus().Fail()) {
3543                 SetExitStatus(-1, response.GetStatus().AsCString());
3544               } else {
3545                 SetExitStatus(-1, "lost connection");
3546               }
3547               done = true;
3548               break;
3549             }
3550 
3551             default:
3552               SetPrivateState(stop_state);
3553               break;
3554             }   // switch(stop_state)
3555           }     // if (continue_packet)
3556         }       // case eBroadcastBitAsyncContinue
3557         break;
3558 
3559         case eBroadcastBitAsyncThreadShouldExit:
3560           LLDB_LOGF(log,
3561                     "ProcessGDBRemote::%s(pid = %" PRIu64
3562                     ") got eBroadcastBitAsyncThreadShouldExit...",
3563                     __FUNCTION__, GetID());
3564           done = true;
3565           break;
3566 
3567         default:
3568           LLDB_LOGF(log,
3569                     "ProcessGDBRemote::%s(pid = %" PRIu64
3570                     ") got unknown event 0x%8.8x",
3571                     __FUNCTION__, GetID(), event_type);
3572           done = true;
3573           break;
3574         }
3575       }
3576     } else {
3577       LLDB_LOGF(log,
3578                 "ProcessGDBRemote::%s(pid = %" PRIu64
3579                 ") listener.WaitForEvent (NULL, event_sp) => false",
3580                 __FUNCTION__, GetID());
3581       done = true;
3582     }
3583   }
3584 
3585   LLDB_LOGF(log, "ProcessGDBRemote::%s(pid = %" PRIu64 ") thread exiting...",
3586             __FUNCTION__, GetID());
3587 
3588   return {};
3589 }
3590 
3591 // uint32_t
3592 // ProcessGDBRemote::ListProcessesMatchingName (const char *name, StringList
3593 // &matches, std::vector<lldb::pid_t> &pids)
3594 //{
3595 //    // If we are planning to launch the debugserver remotely, then we need to
3596 //    fire up a debugserver
3597 //    // process and ask it for the list of processes. But if we are local, we
3598 //    can let the Host do it.
3599 //    if (m_local_debugserver)
3600 //    {
3601 //        return Host::ListProcessesMatchingName (name, matches, pids);
3602 //    }
3603 //    else
3604 //    {
3605 //        // FIXME: Implement talking to the remote debugserver.
3606 //        return 0;
3607 //    }
3608 //
3609 //}
3610 //
3611 bool ProcessGDBRemote::NewThreadNotifyBreakpointHit(
3612     void *baton, StoppointCallbackContext *context, lldb::user_id_t break_id,
3613     lldb::user_id_t break_loc_id) {
3614   // I don't think I have to do anything here, just make sure I notice the new
3615   // thread when it starts to
3616   // run so I can stop it if that's what I want to do.
3617   Log *log = GetLog(LLDBLog::Step);
3618   LLDB_LOGF(log, "Hit New Thread Notification breakpoint.");
3619   return false;
3620 }
3621 
3622 Status ProcessGDBRemote::UpdateAutomaticSignalFiltering() {
3623   Log *log = GetLog(GDBRLog::Process);
3624   LLDB_LOG(log, "Check if need to update ignored signals");
3625 
3626   // QPassSignals package is not supported by the server, there is no way we
3627   // can ignore any signals on server side.
3628   if (!m_gdb_comm.GetQPassSignalsSupported())
3629     return Status();
3630 
3631   // No signals, nothing to send.
3632   if (m_unix_signals_sp == nullptr)
3633     return Status();
3634 
3635   // Signals' version hasn't changed, no need to send anything.
3636   uint64_t new_signals_version = m_unix_signals_sp->GetVersion();
3637   if (new_signals_version == m_last_signals_version) {
3638     LLDB_LOG(log, "Signals' version hasn't changed. version={0}",
3639              m_last_signals_version);
3640     return Status();
3641   }
3642 
3643   auto signals_to_ignore =
3644       m_unix_signals_sp->GetFilteredSignals(false, false, false);
3645   Status error = m_gdb_comm.SendSignalsToIgnore(signals_to_ignore);
3646 
3647   LLDB_LOG(log,
3648            "Signals' version changed. old version={0}, new version={1}, "
3649            "signals ignored={2}, update result={3}",
3650            m_last_signals_version, new_signals_version,
3651            signals_to_ignore.size(), error);
3652 
3653   if (error.Success())
3654     m_last_signals_version = new_signals_version;
3655 
3656   return error;
3657 }
3658 
3659 bool ProcessGDBRemote::StartNoticingNewThreads() {
3660   Log *log = GetLog(LLDBLog::Step);
3661   if (m_thread_create_bp_sp) {
3662     if (log && log->GetVerbose())
3663       LLDB_LOGF(log, "Enabled noticing new thread breakpoint.");
3664     m_thread_create_bp_sp->SetEnabled(true);
3665   } else {
3666     PlatformSP platform_sp(GetTarget().GetPlatform());
3667     if (platform_sp) {
3668       m_thread_create_bp_sp =
3669           platform_sp->SetThreadCreationBreakpoint(GetTarget());
3670       if (m_thread_create_bp_sp) {
3671         if (log && log->GetVerbose())
3672           LLDB_LOGF(
3673               log, "Successfully created new thread notification breakpoint %i",
3674               m_thread_create_bp_sp->GetID());
3675         m_thread_create_bp_sp->SetCallback(
3676             ProcessGDBRemote::NewThreadNotifyBreakpointHit, this, true);
3677       } else {
3678         LLDB_LOGF(log, "Failed to create new thread notification breakpoint.");
3679       }
3680     }
3681   }
3682   return m_thread_create_bp_sp.get() != nullptr;
3683 }
3684 
3685 bool ProcessGDBRemote::StopNoticingNewThreads() {
3686   Log *log = GetLog(LLDBLog::Step);
3687   if (log && log->GetVerbose())
3688     LLDB_LOGF(log, "Disabling new thread notification breakpoint.");
3689 
3690   if (m_thread_create_bp_sp)
3691     m_thread_create_bp_sp->SetEnabled(false);
3692 
3693   return true;
3694 }
3695 
3696 DynamicLoader *ProcessGDBRemote::GetDynamicLoader() {
3697   if (m_dyld_up.get() == nullptr)
3698     m_dyld_up.reset(DynamicLoader::FindPlugin(this, ""));
3699   return m_dyld_up.get();
3700 }
3701 
3702 Status ProcessGDBRemote::SendEventData(const char *data) {
3703   int return_value;
3704   bool was_supported;
3705 
3706   Status error;
3707 
3708   return_value = m_gdb_comm.SendLaunchEventDataPacket(data, &was_supported);
3709   if (return_value != 0) {
3710     if (!was_supported)
3711       error.SetErrorString("Sending events is not supported for this process.");
3712     else
3713       error.SetErrorStringWithFormat("Error sending event data: %d.",
3714                                      return_value);
3715   }
3716   return error;
3717 }
3718 
3719 DataExtractor ProcessGDBRemote::GetAuxvData() {
3720   DataBufferSP buf;
3721   if (m_gdb_comm.GetQXferAuxvReadSupported()) {
3722     llvm::Expected<std::string> response = m_gdb_comm.ReadExtFeature("auxv", "");
3723     if (response)
3724       buf = std::make_shared<DataBufferHeap>(response->c_str(),
3725                                              response->length());
3726     else
3727       LLDB_LOG_ERROR(GetLog(GDBRLog::Process), response.takeError(), "{0}");
3728   }
3729   return DataExtractor(buf, GetByteOrder(), GetAddressByteSize());
3730 }
3731 
3732 StructuredData::ObjectSP
3733 ProcessGDBRemote::GetExtendedInfoForThread(lldb::tid_t tid) {
3734   StructuredData::ObjectSP object_sp;
3735 
3736   if (m_gdb_comm.GetThreadExtendedInfoSupported()) {
3737     StructuredData::ObjectSP args_dict(new StructuredData::Dictionary());
3738     SystemRuntime *runtime = GetSystemRuntime();
3739     if (runtime) {
3740       runtime->AddThreadExtendedInfoPacketHints(args_dict);
3741     }
3742     args_dict->GetAsDictionary()->AddIntegerItem("thread", tid);
3743 
3744     StreamString packet;
3745     packet << "jThreadExtendedInfo:";
3746     args_dict->Dump(packet, false);
3747 
3748     // FIXME the final character of a JSON dictionary, '}', is the escape
3749     // character in gdb-remote binary mode.  lldb currently doesn't escape
3750     // these characters in its packet output -- so we add the quoted version of
3751     // the } character here manually in case we talk to a debugserver which un-
3752     // escapes the characters at packet read time.
3753     packet << (char)(0x7d ^ 0x20);
3754 
3755     StringExtractorGDBRemote response;
3756     response.SetResponseValidatorToJSON();
3757     if (m_gdb_comm.SendPacketAndWaitForResponse(packet.GetString(), response) ==
3758         GDBRemoteCommunication::PacketResult::Success) {
3759       StringExtractorGDBRemote::ResponseType response_type =
3760           response.GetResponseType();
3761       if (response_type == StringExtractorGDBRemote::eResponse) {
3762         if (!response.Empty()) {
3763           object_sp =
3764               StructuredData::ParseJSON(std::string(response.GetStringRef()));
3765         }
3766       }
3767     }
3768   }
3769   return object_sp;
3770 }
3771 
3772 StructuredData::ObjectSP ProcessGDBRemote::GetLoadedDynamicLibrariesInfos(
3773     lldb::addr_t image_list_address, lldb::addr_t image_count) {
3774 
3775   StructuredData::ObjectSP args_dict(new StructuredData::Dictionary());
3776   args_dict->GetAsDictionary()->AddIntegerItem("image_list_address",
3777                                                image_list_address);
3778   args_dict->GetAsDictionary()->AddIntegerItem("image_count", image_count);
3779 
3780   return GetLoadedDynamicLibrariesInfos_sender(args_dict);
3781 }
3782 
3783 StructuredData::ObjectSP ProcessGDBRemote::GetLoadedDynamicLibrariesInfos() {
3784   StructuredData::ObjectSP args_dict(new StructuredData::Dictionary());
3785 
3786   args_dict->GetAsDictionary()->AddBooleanItem("fetch_all_solibs", true);
3787 
3788   return GetLoadedDynamicLibrariesInfos_sender(args_dict);
3789 }
3790 
3791 StructuredData::ObjectSP ProcessGDBRemote::GetLoadedDynamicLibrariesInfos(
3792     const std::vector<lldb::addr_t> &load_addresses) {
3793   StructuredData::ObjectSP args_dict(new StructuredData::Dictionary());
3794   StructuredData::ArraySP addresses(new StructuredData::Array);
3795 
3796   for (auto addr : load_addresses) {
3797     StructuredData::ObjectSP addr_sp(new StructuredData::Integer(addr));
3798     addresses->AddItem(addr_sp);
3799   }
3800 
3801   args_dict->GetAsDictionary()->AddItem("solib_addresses", addresses);
3802 
3803   return GetLoadedDynamicLibrariesInfos_sender(args_dict);
3804 }
3805 
3806 StructuredData::ObjectSP
3807 ProcessGDBRemote::GetLoadedDynamicLibrariesInfos_sender(
3808     StructuredData::ObjectSP args_dict) {
3809   StructuredData::ObjectSP object_sp;
3810 
3811   if (m_gdb_comm.GetLoadedDynamicLibrariesInfosSupported()) {
3812     // Scope for the scoped timeout object
3813     GDBRemoteCommunication::ScopedTimeout timeout(m_gdb_comm,
3814                                                   std::chrono::seconds(10));
3815 
3816     StreamString packet;
3817     packet << "jGetLoadedDynamicLibrariesInfos:";
3818     args_dict->Dump(packet, false);
3819 
3820     // FIXME the final character of a JSON dictionary, '}', is the escape
3821     // character in gdb-remote binary mode.  lldb currently doesn't escape
3822     // these characters in its packet output -- so we add the quoted version of
3823     // the } character here manually in case we talk to a debugserver which un-
3824     // escapes the characters at packet read time.
3825     packet << (char)(0x7d ^ 0x20);
3826 
3827     StringExtractorGDBRemote response;
3828     response.SetResponseValidatorToJSON();
3829     if (m_gdb_comm.SendPacketAndWaitForResponse(packet.GetString(), response) ==
3830         GDBRemoteCommunication::PacketResult::Success) {
3831       StringExtractorGDBRemote::ResponseType response_type =
3832           response.GetResponseType();
3833       if (response_type == StringExtractorGDBRemote::eResponse) {
3834         if (!response.Empty()) {
3835           object_sp =
3836               StructuredData::ParseJSON(std::string(response.GetStringRef()));
3837         }
3838       }
3839     }
3840   }
3841   return object_sp;
3842 }
3843 
3844 StructuredData::ObjectSP ProcessGDBRemote::GetSharedCacheInfo() {
3845   StructuredData::ObjectSP object_sp;
3846   StructuredData::ObjectSP args_dict(new StructuredData::Dictionary());
3847 
3848   if (m_gdb_comm.GetSharedCacheInfoSupported()) {
3849     StreamString packet;
3850     packet << "jGetSharedCacheInfo:";
3851     args_dict->Dump(packet, false);
3852 
3853     // FIXME the final character of a JSON dictionary, '}', is the escape
3854     // character in gdb-remote binary mode.  lldb currently doesn't escape
3855     // these characters in its packet output -- so we add the quoted version of
3856     // the } character here manually in case we talk to a debugserver which un-
3857     // escapes the characters at packet read time.
3858     packet << (char)(0x7d ^ 0x20);
3859 
3860     StringExtractorGDBRemote response;
3861     response.SetResponseValidatorToJSON();
3862     if (m_gdb_comm.SendPacketAndWaitForResponse(packet.GetString(), response) ==
3863         GDBRemoteCommunication::PacketResult::Success) {
3864       StringExtractorGDBRemote::ResponseType response_type =
3865           response.GetResponseType();
3866       if (response_type == StringExtractorGDBRemote::eResponse) {
3867         if (!response.Empty()) {
3868           object_sp =
3869               StructuredData::ParseJSON(std::string(response.GetStringRef()));
3870         }
3871       }
3872     }
3873   }
3874   return object_sp;
3875 }
3876 
3877 Status ProcessGDBRemote::ConfigureStructuredData(
3878     ConstString type_name, const StructuredData::ObjectSP &config_sp) {
3879   return m_gdb_comm.ConfigureRemoteStructuredData(type_name, config_sp);
3880 }
3881 
3882 // Establish the largest memory read/write payloads we should use. If the
3883 // remote stub has a max packet size, stay under that size.
3884 //
3885 // If the remote stub's max packet size is crazy large, use a reasonable
3886 // largeish default.
3887 //
3888 // If the remote stub doesn't advertise a max packet size, use a conservative
3889 // default.
3890 
3891 void ProcessGDBRemote::GetMaxMemorySize() {
3892   const uint64_t reasonable_largeish_default = 128 * 1024;
3893   const uint64_t conservative_default = 512;
3894 
3895   if (m_max_memory_size == 0) {
3896     uint64_t stub_max_size = m_gdb_comm.GetRemoteMaxPacketSize();
3897     if (stub_max_size != UINT64_MAX && stub_max_size != 0) {
3898       // Save the stub's claimed maximum packet size
3899       m_remote_stub_max_memory_size = stub_max_size;
3900 
3901       // Even if the stub says it can support ginormous packets, don't exceed
3902       // our reasonable largeish default packet size.
3903       if (stub_max_size > reasonable_largeish_default) {
3904         stub_max_size = reasonable_largeish_default;
3905       }
3906 
3907       // Memory packet have other overheads too like Maddr,size:#NN Instead of
3908       // calculating the bytes taken by size and addr every time, we take a
3909       // maximum guess here.
3910       if (stub_max_size > 70)
3911         stub_max_size -= 32 + 32 + 6;
3912       else {
3913         // In unlikely scenario that max packet size is less then 70, we will
3914         // hope that data being written is small enough to fit.
3915         Log *log(GetLog(GDBRLog::Comm | GDBRLog::Memory));
3916         if (log)
3917           log->Warning("Packet size is too small. "
3918                        "LLDB may face problems while writing memory");
3919       }
3920 
3921       m_max_memory_size = stub_max_size;
3922     } else {
3923       m_max_memory_size = conservative_default;
3924     }
3925   }
3926 }
3927 
3928 void ProcessGDBRemote::SetUserSpecifiedMaxMemoryTransferSize(
3929     uint64_t user_specified_max) {
3930   if (user_specified_max != 0) {
3931     GetMaxMemorySize();
3932 
3933     if (m_remote_stub_max_memory_size != 0) {
3934       if (m_remote_stub_max_memory_size < user_specified_max) {
3935         m_max_memory_size = m_remote_stub_max_memory_size; // user specified a
3936                                                            // packet size too
3937                                                            // big, go as big
3938         // as the remote stub says we can go.
3939       } else {
3940         m_max_memory_size = user_specified_max; // user's packet size is good
3941       }
3942     } else {
3943       m_max_memory_size =
3944           user_specified_max; // user's packet size is probably fine
3945     }
3946   }
3947 }
3948 
3949 bool ProcessGDBRemote::GetModuleSpec(const FileSpec &module_file_spec,
3950                                      const ArchSpec &arch,
3951                                      ModuleSpec &module_spec) {
3952   Log *log = GetLog(LLDBLog::Platform);
3953 
3954   const ModuleCacheKey key(module_file_spec.GetPath(),
3955                            arch.GetTriple().getTriple());
3956   auto cached = m_cached_module_specs.find(key);
3957   if (cached != m_cached_module_specs.end()) {
3958     module_spec = cached->second;
3959     return bool(module_spec);
3960   }
3961 
3962   if (!m_gdb_comm.GetModuleInfo(module_file_spec, arch, module_spec)) {
3963     LLDB_LOGF(log, "ProcessGDBRemote::%s - failed to get module info for %s:%s",
3964               __FUNCTION__, module_file_spec.GetPath().c_str(),
3965               arch.GetTriple().getTriple().c_str());
3966     return false;
3967   }
3968 
3969   if (log) {
3970     StreamString stream;
3971     module_spec.Dump(stream);
3972     LLDB_LOGF(log, "ProcessGDBRemote::%s - got module info for (%s:%s) : %s",
3973               __FUNCTION__, module_file_spec.GetPath().c_str(),
3974               arch.GetTriple().getTriple().c_str(), stream.GetData());
3975   }
3976 
3977   m_cached_module_specs[key] = module_spec;
3978   return true;
3979 }
3980 
3981 void ProcessGDBRemote::PrefetchModuleSpecs(
3982     llvm::ArrayRef<FileSpec> module_file_specs, const llvm::Triple &triple) {
3983   auto module_specs = m_gdb_comm.GetModulesInfo(module_file_specs, triple);
3984   if (module_specs) {
3985     for (const FileSpec &spec : module_file_specs)
3986       m_cached_module_specs[ModuleCacheKey(spec.GetPath(),
3987                                            triple.getTriple())] = ModuleSpec();
3988     for (const ModuleSpec &spec : *module_specs)
3989       m_cached_module_specs[ModuleCacheKey(spec.GetFileSpec().GetPath(),
3990                                            triple.getTriple())] = spec;
3991   }
3992 }
3993 
3994 llvm::VersionTuple ProcessGDBRemote::GetHostOSVersion() {
3995   return m_gdb_comm.GetOSVersion();
3996 }
3997 
3998 llvm::VersionTuple ProcessGDBRemote::GetHostMacCatalystVersion() {
3999   return m_gdb_comm.GetMacCatalystVersion();
4000 }
4001 
4002 namespace {
4003 
4004 typedef std::vector<std::string> stringVec;
4005 
4006 typedef std::vector<struct GdbServerRegisterInfo> GDBServerRegisterVec;
4007 struct RegisterSetInfo {
4008   ConstString name;
4009 };
4010 
4011 typedef std::map<uint32_t, RegisterSetInfo> RegisterSetMap;
4012 
4013 struct GdbServerTargetInfo {
4014   std::string arch;
4015   std::string osabi;
4016   stringVec includes;
4017   RegisterSetMap reg_set_map;
4018 };
4019 
4020 bool ParseRegisters(XMLNode feature_node, GdbServerTargetInfo &target_info,
4021                     std::vector<DynamicRegisterInfo::Register> &registers) {
4022   if (!feature_node)
4023     return false;
4024 
4025   Log *log(GetLog(GDBRLog::Process));
4026 
4027   feature_node.ForEachChildElementWithName(
4028       "reg", [&target_info, &registers, log](const XMLNode &reg_node) -> bool {
4029         std::string gdb_group;
4030         std::string gdb_type;
4031         DynamicRegisterInfo::Register reg_info;
4032         bool encoding_set = false;
4033         bool format_set = false;
4034 
4035         // FIXME: we're silently ignoring invalid data here
4036         reg_node.ForEachAttribute([&target_info, &gdb_group, &gdb_type,
4037                                    &encoding_set, &format_set, &reg_info,
4038                                    log](const llvm::StringRef &name,
4039                                         const llvm::StringRef &value) -> bool {
4040           if (name == "name") {
4041             reg_info.name.SetString(value);
4042           } else if (name == "bitsize") {
4043             if (llvm::to_integer(value, reg_info.byte_size))
4044               reg_info.byte_size =
4045                   llvm::divideCeil(reg_info.byte_size, CHAR_BIT);
4046           } else if (name == "type") {
4047             gdb_type = value.str();
4048           } else if (name == "group") {
4049             gdb_group = value.str();
4050           } else if (name == "regnum") {
4051             llvm::to_integer(value, reg_info.regnum_remote);
4052           } else if (name == "offset") {
4053             llvm::to_integer(value, reg_info.byte_offset);
4054           } else if (name == "altname") {
4055             reg_info.alt_name.SetString(value);
4056           } else if (name == "encoding") {
4057             encoding_set = true;
4058             reg_info.encoding = Args::StringToEncoding(value, eEncodingUint);
4059           } else if (name == "format") {
4060             format_set = true;
4061             if (!OptionArgParser::ToFormat(value.data(), reg_info.format,
4062                                            nullptr)
4063                      .Success())
4064               reg_info.format =
4065                   llvm::StringSwitch<lldb::Format>(value)
4066                       .Case("vector-sint8", eFormatVectorOfSInt8)
4067                       .Case("vector-uint8", eFormatVectorOfUInt8)
4068                       .Case("vector-sint16", eFormatVectorOfSInt16)
4069                       .Case("vector-uint16", eFormatVectorOfUInt16)
4070                       .Case("vector-sint32", eFormatVectorOfSInt32)
4071                       .Case("vector-uint32", eFormatVectorOfUInt32)
4072                       .Case("vector-float32", eFormatVectorOfFloat32)
4073                       .Case("vector-uint64", eFormatVectorOfUInt64)
4074                       .Case("vector-uint128", eFormatVectorOfUInt128)
4075                       .Default(eFormatInvalid);
4076           } else if (name == "group_id") {
4077             uint32_t set_id = UINT32_MAX;
4078             llvm::to_integer(value, set_id);
4079             RegisterSetMap::const_iterator pos =
4080                 target_info.reg_set_map.find(set_id);
4081             if (pos != target_info.reg_set_map.end())
4082               reg_info.set_name = pos->second.name;
4083           } else if (name == "gcc_regnum" || name == "ehframe_regnum") {
4084             llvm::to_integer(value, reg_info.regnum_ehframe);
4085           } else if (name == "dwarf_regnum") {
4086             llvm::to_integer(value, reg_info.regnum_dwarf);
4087           } else if (name == "generic") {
4088             reg_info.regnum_generic = Args::StringToGenericRegister(value);
4089           } else if (name == "value_regnums") {
4090             SplitCommaSeparatedRegisterNumberString(value, reg_info.value_regs,
4091                                                     0);
4092           } else if (name == "invalidate_regnums") {
4093             SplitCommaSeparatedRegisterNumberString(
4094                 value, reg_info.invalidate_regs, 0);
4095           } else {
4096             LLDB_LOGF(log,
4097                       "ProcessGDBRemote::ParseRegisters unhandled reg "
4098                       "attribute %s = %s",
4099                       name.data(), value.data());
4100           }
4101           return true; // Keep iterating through all attributes
4102         });
4103 
4104         if (!gdb_type.empty() && !(encoding_set || format_set)) {
4105           if (llvm::StringRef(gdb_type).startswith("int")) {
4106             reg_info.format = eFormatHex;
4107             reg_info.encoding = eEncodingUint;
4108           } else if (gdb_type == "data_ptr" || gdb_type == "code_ptr") {
4109             reg_info.format = eFormatAddressInfo;
4110             reg_info.encoding = eEncodingUint;
4111           } else if (gdb_type == "float") {
4112             reg_info.format = eFormatFloat;
4113             reg_info.encoding = eEncodingIEEE754;
4114           } else if (gdb_type == "aarch64v" ||
4115                      llvm::StringRef(gdb_type).startswith("vec") ||
4116                      gdb_type == "i387_ext" || gdb_type == "uint128") {
4117             // lldb doesn't handle 128-bit uints correctly (for ymm*h), so treat
4118             // them as vector (similarly to xmm/ymm)
4119             reg_info.format = eFormatVectorOfUInt8;
4120             reg_info.encoding = eEncodingVector;
4121           } else {
4122             LLDB_LOGF(
4123                 log,
4124                 "ProcessGDBRemote::ParseRegisters Could not determine lldb"
4125                 "format and encoding for gdb type %s",
4126                 gdb_type.c_str());
4127           }
4128         }
4129 
4130         // Only update the register set name if we didn't get a "reg_set"
4131         // attribute. "set_name" will be empty if we didn't have a "reg_set"
4132         // attribute.
4133         if (!reg_info.set_name) {
4134           if (!gdb_group.empty()) {
4135             reg_info.set_name.SetCString(gdb_group.c_str());
4136           } else {
4137             // If no register group name provided anywhere,
4138             // we'll create a 'general' register set
4139             reg_info.set_name.SetCString("general");
4140           }
4141         }
4142 
4143         if (reg_info.byte_size == 0) {
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