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