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