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