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