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