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