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