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