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