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