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