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