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