xref: /llvm-project/lldb/source/Plugins/Process/gdb-remote/ProcessGDBRemote.cpp (revision 1370a1cb5b97ecfc4fd2cb550159db9c9ebd3a68)
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->GetAsSignedInteger())
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->GetUnsignedIntegerValue(LLDB_INVALID_THREAD_ID);
1971     } else if (key == g_key_metype) {
1972       // exception type in big endian hex
1973       exc_type = object->GetUnsignedIntegerValue(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->GetUnsignedIntegerValue());
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 =
1987           object->GetUnsignedIntegerValue(LLDB_INVALID_ADDRESS);
1988     } else if (key == g_key_queue_name) {
1989       queue_vars_valid = true;
1990       queue_name = std::string(object->GetStringValue());
1991     } else if (key == g_key_queue_kind) {
1992       std::string queue_kind_str = std::string(object->GetStringValue());
1993       if (queue_kind_str == "serial") {
1994         queue_vars_valid = true;
1995         queue_kind = eQueueKindSerial;
1996       } else if (queue_kind_str == "concurrent") {
1997         queue_vars_valid = true;
1998         queue_kind = eQueueKindConcurrent;
1999       }
2000     } else if (key == g_key_queue_serial_number) {
2001       queue_serial_number = object->GetUnsignedIntegerValue(0);
2002       if (queue_serial_number != 0)
2003         queue_vars_valid = true;
2004     } else if (key == g_key_dispatch_queue_t) {
2005       dispatch_queue_t = object->GetUnsignedIntegerValue(0);
2006       if (dispatch_queue_t != 0 && dispatch_queue_t != LLDB_INVALID_ADDRESS)
2007         queue_vars_valid = true;
2008     } else if (key == g_key_associated_with_dispatch_queue) {
2009       queue_vars_valid = true;
2010       bool associated = object->GetBooleanValue();
2011       if (associated)
2012         associated_with_dispatch_queue = eLazyBoolYes;
2013       else
2014         associated_with_dispatch_queue = eLazyBoolNo;
2015     } else if (key == g_key_reason) {
2016       reason = std::string(object->GetStringValue());
2017     } else if (key == g_key_description) {
2018       description = std::string(object->GetStringValue());
2019     } else if (key == g_key_registers) {
2020       StructuredData::Dictionary *registers_dict = object->GetAsDictionary();
2021 
2022       if (registers_dict) {
2023         registers_dict->ForEach(
2024             [&expedited_register_map](ConstString key,
2025                                       StructuredData::Object *object) -> bool {
2026               uint32_t reg;
2027               if (llvm::to_integer(key.AsCString(), reg))
2028                 expedited_register_map[reg] =
2029                     std::string(object->GetStringValue());
2030               return true; // Keep iterating through all array items
2031             });
2032       }
2033     } else if (key == g_key_memory) {
2034       StructuredData::Array *array = object->GetAsArray();
2035       if (array) {
2036         array->ForEach([this](StructuredData::Object *object) -> bool {
2037           StructuredData::Dictionary *mem_cache_dict =
2038               object->GetAsDictionary();
2039           if (mem_cache_dict) {
2040             lldb::addr_t mem_cache_addr = LLDB_INVALID_ADDRESS;
2041             if (mem_cache_dict->GetValueForKeyAsInteger<lldb::addr_t>(
2042                     "address", mem_cache_addr)) {
2043               if (mem_cache_addr != LLDB_INVALID_ADDRESS) {
2044                 llvm::StringRef str;
2045                 if (mem_cache_dict->GetValueForKeyAsString("bytes", str)) {
2046                   StringExtractor bytes(str);
2047                   bytes.SetFilePos(0);
2048 
2049                   const size_t byte_size = bytes.GetStringRef().size() / 2;
2050                   WritableDataBufferSP data_buffer_sp(
2051                       new DataBufferHeap(byte_size, 0));
2052                   const size_t bytes_copied =
2053                       bytes.GetHexBytes(data_buffer_sp->GetData(), 0);
2054                   if (bytes_copied == byte_size)
2055                     m_memory_cache.AddL1CacheData(mem_cache_addr,
2056                                                   data_buffer_sp);
2057                 }
2058               }
2059             }
2060           }
2061           return true; // Keep iterating through all array items
2062         });
2063       }
2064 
2065     } else if (key == g_key_signal)
2066       signo = object->GetUnsignedIntegerValue(LLDB_INVALID_SIGNAL_NUMBER);
2067     return true; // Keep iterating through all dictionary key/value pairs
2068   });
2069 
2070   return SetThreadStopInfo(tid, expedited_register_map, signo, thread_name,
2071                            reason, description, exc_type, exc_data,
2072                            thread_dispatch_qaddr, queue_vars_valid,
2073                            associated_with_dispatch_queue, dispatch_queue_t,
2074                            queue_name, queue_kind, queue_serial_number);
2075 }
2076 
2077 StateType ProcessGDBRemote::SetThreadStopInfo(StringExtractor &stop_packet) {
2078   lldb::pid_t pid = m_gdb_comm.GetCurrentProcessID();
2079   stop_packet.SetFilePos(0);
2080   const char stop_type = stop_packet.GetChar();
2081   switch (stop_type) {
2082   case 'T':
2083   case 'S': {
2084     // This is a bit of a hack, but is is required. If we did exec, we need to
2085     // clear our thread lists and also know to rebuild our dynamic register
2086     // info before we lookup and threads and populate the expedited register
2087     // values so we need to know this right away so we can cleanup and update
2088     // our registers.
2089     const uint32_t stop_id = GetStopID();
2090     if (stop_id == 0) {
2091       // Our first stop, make sure we have a process ID, and also make sure we
2092       // know about our registers
2093       if (GetID() == LLDB_INVALID_PROCESS_ID && pid != LLDB_INVALID_PROCESS_ID)
2094         SetID(pid);
2095       BuildDynamicRegisterInfo(true);
2096     }
2097     // Stop with signal and thread info
2098     lldb::pid_t stop_pid = LLDB_INVALID_PROCESS_ID;
2099     lldb::tid_t tid = LLDB_INVALID_THREAD_ID;
2100     const uint8_t signo = stop_packet.GetHexU8();
2101     llvm::StringRef key;
2102     llvm::StringRef value;
2103     std::string thread_name;
2104     std::string reason;
2105     std::string description;
2106     uint32_t exc_type = 0;
2107     std::vector<addr_t> exc_data;
2108     addr_t thread_dispatch_qaddr = LLDB_INVALID_ADDRESS;
2109     bool queue_vars_valid =
2110         false; // says if locals below that start with "queue_" are valid
2111     addr_t dispatch_queue_t = LLDB_INVALID_ADDRESS;
2112     LazyBool associated_with_dispatch_queue = eLazyBoolCalculate;
2113     std::string queue_name;
2114     QueueKind queue_kind = eQueueKindUnknown;
2115     uint64_t queue_serial_number = 0;
2116     ExpeditedRegisterMap expedited_register_map;
2117     while (stop_packet.GetNameColonValue(key, value)) {
2118       if (key.compare("metype") == 0) {
2119         // exception type in big endian hex
2120         value.getAsInteger(16, exc_type);
2121       } else if (key.compare("medata") == 0) {
2122         // exception data in big endian hex
2123         uint64_t x;
2124         value.getAsInteger(16, x);
2125         exc_data.push_back(x);
2126       } else if (key.compare("thread") == 0) {
2127         // thread-id
2128         StringExtractorGDBRemote thread_id{value};
2129         auto pid_tid = thread_id.GetPidTid(pid);
2130         if (pid_tid) {
2131           stop_pid = pid_tid->first;
2132           tid = pid_tid->second;
2133         } else
2134           tid = LLDB_INVALID_THREAD_ID;
2135       } else if (key.compare("threads") == 0) {
2136         std::lock_guard<std::recursive_mutex> guard(
2137             m_thread_list_real.GetMutex());
2138         UpdateThreadIDsFromStopReplyThreadsValue(value);
2139       } else if (key.compare("thread-pcs") == 0) {
2140         m_thread_pcs.clear();
2141         // A comma separated list of all threads in the current
2142         // process that includes the thread for this stop reply packet
2143         lldb::addr_t pc;
2144         while (!value.empty()) {
2145           llvm::StringRef pc_str;
2146           std::tie(pc_str, value) = value.split(',');
2147           if (pc_str.getAsInteger(16, pc))
2148             pc = LLDB_INVALID_ADDRESS;
2149           m_thread_pcs.push_back(pc);
2150         }
2151       } else if (key.compare("jstopinfo") == 0) {
2152         StringExtractor json_extractor(value);
2153         std::string json;
2154         // Now convert the HEX bytes into a string value
2155         json_extractor.GetHexByteString(json);
2156 
2157         // This JSON contains thread IDs and thread stop info for all threads.
2158         // It doesn't contain expedited registers, memory or queue info.
2159         m_jstopinfo_sp = StructuredData::ParseJSON(json);
2160       } else if (key.compare("hexname") == 0) {
2161         StringExtractor name_extractor(value);
2162         std::string name;
2163         // Now convert the HEX bytes into a string value
2164         name_extractor.GetHexByteString(thread_name);
2165       } else if (key.compare("name") == 0) {
2166         thread_name = std::string(value);
2167       } else if (key.compare("qaddr") == 0) {
2168         value.getAsInteger(16, thread_dispatch_qaddr);
2169       } else if (key.compare("dispatch_queue_t") == 0) {
2170         queue_vars_valid = true;
2171         value.getAsInteger(16, dispatch_queue_t);
2172       } else if (key.compare("qname") == 0) {
2173         queue_vars_valid = true;
2174         StringExtractor name_extractor(value);
2175         // Now convert the HEX bytes into a string value
2176         name_extractor.GetHexByteString(queue_name);
2177       } else if (key.compare("qkind") == 0) {
2178         queue_kind = llvm::StringSwitch<QueueKind>(value)
2179                          .Case("serial", eQueueKindSerial)
2180                          .Case("concurrent", eQueueKindConcurrent)
2181                          .Default(eQueueKindUnknown);
2182         queue_vars_valid = queue_kind != eQueueKindUnknown;
2183       } else if (key.compare("qserialnum") == 0) {
2184         if (!value.getAsInteger(0, queue_serial_number))
2185           queue_vars_valid = true;
2186       } else if (key.compare("reason") == 0) {
2187         reason = std::string(value);
2188       } else if (key.compare("description") == 0) {
2189         StringExtractor desc_extractor(value);
2190         // Now convert the HEX bytes into a string value
2191         desc_extractor.GetHexByteString(description);
2192       } else if (key.compare("memory") == 0) {
2193         // Expedited memory. GDB servers can choose to send back expedited
2194         // memory that can populate the L1 memory cache in the process so that
2195         // things like the frame pointer backchain can be expedited. This will
2196         // help stack backtracing be more efficient by not having to send as
2197         // many memory read requests down the remote GDB server.
2198 
2199         // Key/value pair format: memory:<addr>=<bytes>;
2200         // <addr> is a number whose base will be interpreted by the prefix:
2201         //      "0x[0-9a-fA-F]+" for hex
2202         //      "0[0-7]+" for octal
2203         //      "[1-9]+" for decimal
2204         // <bytes> is native endian ASCII hex bytes just like the register
2205         // values
2206         llvm::StringRef addr_str, bytes_str;
2207         std::tie(addr_str, bytes_str) = value.split('=');
2208         if (!addr_str.empty() && !bytes_str.empty()) {
2209           lldb::addr_t mem_cache_addr = LLDB_INVALID_ADDRESS;
2210           if (!addr_str.getAsInteger(0, mem_cache_addr)) {
2211             StringExtractor bytes(bytes_str);
2212             const size_t byte_size = bytes.GetBytesLeft() / 2;
2213             WritableDataBufferSP data_buffer_sp(
2214                 new DataBufferHeap(byte_size, 0));
2215             const size_t bytes_copied =
2216                 bytes.GetHexBytes(data_buffer_sp->GetData(), 0);
2217             if (bytes_copied == byte_size)
2218               m_memory_cache.AddL1CacheData(mem_cache_addr, data_buffer_sp);
2219           }
2220         }
2221       } else if (key.compare("watch") == 0 || key.compare("rwatch") == 0 ||
2222                  key.compare("awatch") == 0) {
2223         // Support standard GDB remote stop reply packet 'TAAwatch:addr'
2224         lldb::addr_t wp_addr = LLDB_INVALID_ADDRESS;
2225         value.getAsInteger(16, wp_addr);
2226 
2227         WatchpointSP wp_sp =
2228             GetTarget().GetWatchpointList().FindByAddress(wp_addr);
2229         uint32_t wp_index = LLDB_INVALID_INDEX32;
2230 
2231         if (wp_sp)
2232           wp_index = wp_sp->GetHardwareIndex();
2233 
2234         // Rewrite gdb standard watch/rwatch/awatch to
2235         // "reason:watchpoint" + "description:ADDR",
2236         // which is parsed in SetThreadStopInfo.
2237         reason = "watchpoint";
2238         StreamString ostr;
2239         ostr.Printf("%" PRIu64 " %" PRIu32, wp_addr, wp_index);
2240         description = std::string(ostr.GetString());
2241       } else if (key.compare("library") == 0) {
2242         auto error = LoadModules();
2243         if (error) {
2244           Log *log(GetLog(GDBRLog::Process));
2245           LLDB_LOG_ERROR(log, std::move(error), "Failed to load modules: {0}");
2246         }
2247       } else if (key.compare("fork") == 0 || key.compare("vfork") == 0) {
2248         // fork includes child pid/tid in thread-id format
2249         StringExtractorGDBRemote thread_id{value};
2250         auto pid_tid = thread_id.GetPidTid(LLDB_INVALID_PROCESS_ID);
2251         if (!pid_tid) {
2252           Log *log(GetLog(GDBRLog::Process));
2253           LLDB_LOG(log, "Invalid PID/TID to fork: {0}", value);
2254           pid_tid = {{LLDB_INVALID_PROCESS_ID, LLDB_INVALID_THREAD_ID}};
2255         }
2256 
2257         reason = key.str();
2258         StreamString ostr;
2259         ostr.Printf("%" PRIu64 " %" PRIu64, pid_tid->first, pid_tid->second);
2260         description = std::string(ostr.GetString());
2261       } else if (key.compare("addressing_bits") == 0) {
2262         uint64_t addressing_bits;
2263         if (!value.getAsInteger(0, addressing_bits)) {
2264           addr_t address_mask = ~((1ULL << addressing_bits) - 1);
2265           SetCodeAddressMask(address_mask);
2266           SetDataAddressMask(address_mask);
2267         }
2268       } else if (key.size() == 2 && ::isxdigit(key[0]) && ::isxdigit(key[1])) {
2269         uint32_t reg = UINT32_MAX;
2270         if (!key.getAsInteger(16, reg))
2271           expedited_register_map[reg] = std::string(std::move(value));
2272       }
2273     }
2274 
2275     if (stop_pid != LLDB_INVALID_PROCESS_ID && stop_pid != pid) {
2276       Log *log = GetLog(GDBRLog::Process);
2277       LLDB_LOG(log,
2278                "Received stop for incorrect PID = {0} (inferior PID = {1})",
2279                stop_pid, pid);
2280       return eStateInvalid;
2281     }
2282 
2283     if (tid == LLDB_INVALID_THREAD_ID) {
2284       // A thread id may be invalid if the response is old style 'S' packet
2285       // which does not provide the
2286       // thread information. So update the thread list and choose the first
2287       // one.
2288       UpdateThreadIDList();
2289 
2290       if (!m_thread_ids.empty()) {
2291         tid = m_thread_ids.front();
2292       }
2293     }
2294 
2295     ThreadSP thread_sp = SetThreadStopInfo(
2296         tid, expedited_register_map, signo, thread_name, reason, description,
2297         exc_type, exc_data, thread_dispatch_qaddr, queue_vars_valid,
2298         associated_with_dispatch_queue, dispatch_queue_t, queue_name,
2299         queue_kind, queue_serial_number);
2300 
2301     return eStateStopped;
2302   } break;
2303 
2304   case 'W':
2305   case 'X':
2306     // process exited
2307     return eStateExited;
2308 
2309   default:
2310     break;
2311   }
2312   return eStateInvalid;
2313 }
2314 
2315 void ProcessGDBRemote::RefreshStateAfterStop() {
2316   std::lock_guard<std::recursive_mutex> guard(m_thread_list_real.GetMutex());
2317 
2318   m_thread_ids.clear();
2319   m_thread_pcs.clear();
2320 
2321   // Set the thread stop info. It might have a "threads" key whose value is a
2322   // list of all thread IDs in the current process, so m_thread_ids might get
2323   // set.
2324   // Check to see if SetThreadStopInfo() filled in m_thread_ids?
2325   if (m_thread_ids.empty()) {
2326       // No, we need to fetch the thread list manually
2327       UpdateThreadIDList();
2328   }
2329 
2330   // We might set some stop info's so make sure the thread list is up to
2331   // date before we do that or we might overwrite what was computed here.
2332   UpdateThreadListIfNeeded();
2333 
2334   if (m_last_stop_packet)
2335     SetThreadStopInfo(*m_last_stop_packet);
2336   m_last_stop_packet.reset();
2337 
2338   // If we have queried for a default thread id
2339   if (m_initial_tid != LLDB_INVALID_THREAD_ID) {
2340     m_thread_list.SetSelectedThreadByID(m_initial_tid);
2341     m_initial_tid = LLDB_INVALID_THREAD_ID;
2342   }
2343 
2344   // Let all threads recover from stopping and do any clean up based on the
2345   // previous thread state (if any).
2346   m_thread_list_real.RefreshStateAfterStop();
2347 }
2348 
2349 Status ProcessGDBRemote::DoHalt(bool &caused_stop) {
2350   Status error;
2351 
2352   if (m_public_state.GetValue() == eStateAttaching) {
2353     // We are being asked to halt during an attach. We need to just close our
2354     // file handle and debugserver will go away, and we can be done...
2355     m_gdb_comm.Disconnect();
2356   } else
2357     caused_stop = m_gdb_comm.Interrupt(GetInterruptTimeout());
2358   return error;
2359 }
2360 
2361 Status ProcessGDBRemote::DoDetach(bool keep_stopped) {
2362   Status error;
2363   Log *log = GetLog(GDBRLog::Process);
2364   LLDB_LOGF(log, "ProcessGDBRemote::DoDetach(keep_stopped: %i)", keep_stopped);
2365 
2366   error = m_gdb_comm.Detach(keep_stopped);
2367   if (log) {
2368     if (error.Success())
2369       log->PutCString(
2370           "ProcessGDBRemote::DoDetach() detach packet sent successfully");
2371     else
2372       LLDB_LOGF(log,
2373                 "ProcessGDBRemote::DoDetach() detach packet send failed: %s",
2374                 error.AsCString() ? error.AsCString() : "<unknown error>");
2375   }
2376 
2377   if (!error.Success())
2378     return error;
2379 
2380   // Sleep for one second to let the process get all detached...
2381   StopAsyncThread();
2382 
2383   SetPrivateState(eStateDetached);
2384   ResumePrivateStateThread();
2385 
2386   // KillDebugserverProcess ();
2387   return error;
2388 }
2389 
2390 Status ProcessGDBRemote::DoDestroy() {
2391   Log *log = GetLog(GDBRLog::Process);
2392   LLDB_LOGF(log, "ProcessGDBRemote::DoDestroy()");
2393 
2394   // Interrupt if our inferior is running...
2395   int exit_status = SIGABRT;
2396   std::string exit_string;
2397 
2398   if (m_gdb_comm.IsConnected()) {
2399     if (m_public_state.GetValue() != eStateAttaching) {
2400       llvm::Expected<int> kill_res = m_gdb_comm.KillProcess(GetID());
2401 
2402       if (kill_res) {
2403         exit_status = kill_res.get();
2404 #if defined(__APPLE__)
2405         // For Native processes on Mac OS X, we launch through the Host
2406         // Platform, then hand the process off to debugserver, which becomes
2407         // the parent process through "PT_ATTACH".  Then when we go to kill
2408         // the process on Mac OS X we call ptrace(PT_KILL) to kill it, then
2409         // we call waitpid which returns with no error and the correct
2410         // status.  But amusingly enough that doesn't seem to actually reap
2411         // the process, but instead it is left around as a Zombie.  Probably
2412         // the kernel is in the process of switching ownership back to lldb
2413         // which was the original parent, and gets confused in the handoff.
2414         // Anyway, so call waitpid here to finally reap it.
2415         PlatformSP platform_sp(GetTarget().GetPlatform());
2416         if (platform_sp && platform_sp->IsHost()) {
2417           int status;
2418           ::pid_t reap_pid;
2419           reap_pid = waitpid(GetID(), &status, WNOHANG);
2420           LLDB_LOGF(log, "Reaped pid: %d, status: %d.\n", reap_pid, status);
2421         }
2422 #endif
2423         ClearThreadIDList();
2424         exit_string.assign("killed");
2425       } else {
2426         exit_string.assign(llvm::toString(kill_res.takeError()));
2427       }
2428     } else {
2429       exit_string.assign("killed or interrupted while attaching.");
2430     }
2431   } else {
2432     // If we missed setting the exit status on the way out, do it here.
2433     // NB set exit status can be called multiple times, the first one sets the
2434     // status.
2435     exit_string.assign("destroying when not connected to debugserver");
2436   }
2437 
2438   SetExitStatus(exit_status, exit_string.c_str());
2439 
2440   StopAsyncThread();
2441   KillDebugserverProcess();
2442   return Status();
2443 }
2444 
2445 void ProcessGDBRemote::SetLastStopPacket(
2446     const StringExtractorGDBRemote &response) {
2447   const bool did_exec =
2448       response.GetStringRef().find(";reason:exec;") != std::string::npos;
2449   if (did_exec) {
2450     Log *log = GetLog(GDBRLog::Process);
2451     LLDB_LOGF(log, "ProcessGDBRemote::SetLastStopPacket () - detected exec");
2452 
2453     m_thread_list_real.Clear();
2454     m_thread_list.Clear();
2455     BuildDynamicRegisterInfo(true);
2456     m_gdb_comm.ResetDiscoverableSettings(did_exec);
2457   }
2458 
2459   m_last_stop_packet = response;
2460 }
2461 
2462 void ProcessGDBRemote::SetUnixSignals(const UnixSignalsSP &signals_sp) {
2463   Process::SetUnixSignals(std::make_shared<GDBRemoteSignals>(signals_sp));
2464 }
2465 
2466 // Process Queries
2467 
2468 bool ProcessGDBRemote::IsAlive() {
2469   return m_gdb_comm.IsConnected() && Process::IsAlive();
2470 }
2471 
2472 addr_t ProcessGDBRemote::GetImageInfoAddress() {
2473   // request the link map address via the $qShlibInfoAddr packet
2474   lldb::addr_t addr = m_gdb_comm.GetShlibInfoAddr();
2475 
2476   // the loaded module list can also provides a link map address
2477   if (addr == LLDB_INVALID_ADDRESS) {
2478     llvm::Expected<LoadedModuleInfoList> list = GetLoadedModuleList();
2479     if (!list) {
2480       Log *log = GetLog(GDBRLog::Process);
2481       LLDB_LOG_ERROR(log, list.takeError(), "Failed to read module list: {0}.");
2482     } else {
2483       addr = list->m_link_map;
2484     }
2485   }
2486 
2487   return addr;
2488 }
2489 
2490 void ProcessGDBRemote::WillPublicStop() {
2491   // See if the GDB remote client supports the JSON threads info. If so, we
2492   // gather stop info for all threads, expedited registers, expedited memory,
2493   // runtime queue information (iOS and MacOSX only), and more. Expediting
2494   // memory will help stack backtracing be much faster. Expediting registers
2495   // will make sure we don't have to read the thread registers for GPRs.
2496   m_jthreadsinfo_sp = m_gdb_comm.GetThreadsInfo();
2497 
2498   if (m_jthreadsinfo_sp) {
2499     // Now set the stop info for each thread and also expedite any registers
2500     // and memory that was in the jThreadsInfo response.
2501     StructuredData::Array *thread_infos = m_jthreadsinfo_sp->GetAsArray();
2502     if (thread_infos) {
2503       const size_t n = thread_infos->GetSize();
2504       for (size_t i = 0; i < n; ++i) {
2505         StructuredData::Dictionary *thread_dict =
2506             thread_infos->GetItemAtIndex(i)->GetAsDictionary();
2507         if (thread_dict)
2508           SetThreadStopInfo(thread_dict);
2509       }
2510     }
2511   }
2512 }
2513 
2514 // Process Memory
2515 size_t ProcessGDBRemote::DoReadMemory(addr_t addr, void *buf, size_t size,
2516                                       Status &error) {
2517   GetMaxMemorySize();
2518   bool binary_memory_read = m_gdb_comm.GetxPacketSupported();
2519   // M and m packets take 2 bytes for 1 byte of memory
2520   size_t max_memory_size =
2521       binary_memory_read ? m_max_memory_size : m_max_memory_size / 2;
2522   if (size > max_memory_size) {
2523     // Keep memory read sizes down to a sane limit. This function will be
2524     // called multiple times in order to complete the task by
2525     // lldb_private::Process so it is ok to do this.
2526     size = max_memory_size;
2527   }
2528 
2529   char packet[64];
2530   int packet_len;
2531   packet_len = ::snprintf(packet, sizeof(packet), "%c%" PRIx64 ",%" PRIx64,
2532                           binary_memory_read ? 'x' : 'm', (uint64_t)addr,
2533                           (uint64_t)size);
2534   assert(packet_len + 1 < (int)sizeof(packet));
2535   UNUSED_IF_ASSERT_DISABLED(packet_len);
2536   StringExtractorGDBRemote response;
2537   if (m_gdb_comm.SendPacketAndWaitForResponse(packet, response,
2538                                               GetInterruptTimeout()) ==
2539       GDBRemoteCommunication::PacketResult::Success) {
2540     if (response.IsNormalResponse()) {
2541       error.Clear();
2542       if (binary_memory_read) {
2543         // The lower level GDBRemoteCommunication packet receive layer has
2544         // already de-quoted any 0x7d character escaping that was present in
2545         // the packet
2546 
2547         size_t data_received_size = response.GetBytesLeft();
2548         if (data_received_size > size) {
2549           // Don't write past the end of BUF if the remote debug server gave us
2550           // too much data for some reason.
2551           data_received_size = size;
2552         }
2553         memcpy(buf, response.GetStringRef().data(), data_received_size);
2554         return data_received_size;
2555       } else {
2556         return response.GetHexBytes(
2557             llvm::MutableArrayRef<uint8_t>((uint8_t *)buf, size), '\xdd');
2558       }
2559     } else if (response.IsErrorResponse())
2560       error.SetErrorStringWithFormat("memory read failed for 0x%" PRIx64, addr);
2561     else if (response.IsUnsupportedResponse())
2562       error.SetErrorStringWithFormat(
2563           "GDB server does not support reading memory");
2564     else
2565       error.SetErrorStringWithFormat(
2566           "unexpected response to GDB server memory read packet '%s': '%s'",
2567           packet, response.GetStringRef().data());
2568   } else {
2569     error.SetErrorStringWithFormat("failed to send packet: '%s'", packet);
2570   }
2571   return 0;
2572 }
2573 
2574 bool ProcessGDBRemote::SupportsMemoryTagging() {
2575   return m_gdb_comm.GetMemoryTaggingSupported();
2576 }
2577 
2578 llvm::Expected<std::vector<uint8_t>>
2579 ProcessGDBRemote::DoReadMemoryTags(lldb::addr_t addr, size_t len,
2580                                    int32_t type) {
2581   // By this point ReadMemoryTags has validated that tagging is enabled
2582   // for this target/process/address.
2583   DataBufferSP buffer_sp = m_gdb_comm.ReadMemoryTags(addr, len, type);
2584   if (!buffer_sp) {
2585     return llvm::createStringError(llvm::inconvertibleErrorCode(),
2586                                    "Error reading memory tags from remote");
2587   }
2588 
2589   // Return the raw tag data
2590   llvm::ArrayRef<uint8_t> tag_data = buffer_sp->GetData();
2591   std::vector<uint8_t> got;
2592   got.reserve(tag_data.size());
2593   std::copy(tag_data.begin(), tag_data.end(), std::back_inserter(got));
2594   return got;
2595 }
2596 
2597 Status ProcessGDBRemote::DoWriteMemoryTags(lldb::addr_t addr, size_t len,
2598                                            int32_t type,
2599                                            const std::vector<uint8_t> &tags) {
2600   // By now WriteMemoryTags should have validated that tagging is enabled
2601   // for this target/process.
2602   return m_gdb_comm.WriteMemoryTags(addr, len, type, tags);
2603 }
2604 
2605 Status ProcessGDBRemote::WriteObjectFile(
2606     std::vector<ObjectFile::LoadableData> entries) {
2607   Status error;
2608   // Sort the entries by address because some writes, like those to flash
2609   // memory, must happen in order of increasing address.
2610   std::stable_sort(
2611       std::begin(entries), std::end(entries),
2612       [](const ObjectFile::LoadableData a, const ObjectFile::LoadableData b) {
2613         return a.Dest < b.Dest;
2614       });
2615   m_allow_flash_writes = true;
2616   error = Process::WriteObjectFile(entries);
2617   if (error.Success())
2618     error = FlashDone();
2619   else
2620     // Even though some of the writing failed, try to send a flash done if some
2621     // of the writing succeeded so the flash state is reset to normal, but
2622     // don't stomp on the error status that was set in the write failure since
2623     // that's the one we want to report back.
2624     FlashDone();
2625   m_allow_flash_writes = false;
2626   return error;
2627 }
2628 
2629 bool ProcessGDBRemote::HasErased(FlashRange range) {
2630   auto size = m_erased_flash_ranges.GetSize();
2631   for (size_t i = 0; i < size; ++i)
2632     if (m_erased_flash_ranges.GetEntryAtIndex(i)->Contains(range))
2633       return true;
2634   return false;
2635 }
2636 
2637 Status ProcessGDBRemote::FlashErase(lldb::addr_t addr, size_t size) {
2638   Status status;
2639 
2640   MemoryRegionInfo region;
2641   status = GetMemoryRegionInfo(addr, region);
2642   if (!status.Success())
2643     return status;
2644 
2645   // The gdb spec doesn't say if erasures are allowed across multiple regions,
2646   // but we'll disallow it to be safe and to keep the logic simple by worring
2647   // about only one region's block size.  DoMemoryWrite is this function's
2648   // primary user, and it can easily keep writes within a single memory region
2649   if (addr + size > region.GetRange().GetRangeEnd()) {
2650     status.SetErrorString("Unable to erase flash in multiple regions");
2651     return status;
2652   }
2653 
2654   uint64_t blocksize = region.GetBlocksize();
2655   if (blocksize == 0) {
2656     status.SetErrorString("Unable to erase flash because blocksize is 0");
2657     return status;
2658   }
2659 
2660   // Erasures can only be done on block boundary adresses, so round down addr
2661   // and round up size
2662   lldb::addr_t block_start_addr = addr - (addr % blocksize);
2663   size += (addr - block_start_addr);
2664   if ((size % blocksize) != 0)
2665     size += (blocksize - size % blocksize);
2666 
2667   FlashRange range(block_start_addr, size);
2668 
2669   if (HasErased(range))
2670     return status;
2671 
2672   // We haven't erased the entire range, but we may have erased part of it.
2673   // (e.g., block A is already erased and range starts in A and ends in B). So,
2674   // adjust range if necessary to exclude already erased blocks.
2675   if (!m_erased_flash_ranges.IsEmpty()) {
2676     // Assuming that writes and erasures are done in increasing addr order,
2677     // because that is a requirement of the vFlashWrite command.  Therefore, we
2678     // only need to look at the last range in the list for overlap.
2679     const auto &last_range = *m_erased_flash_ranges.Back();
2680     if (range.GetRangeBase() < last_range.GetRangeEnd()) {
2681       auto overlap = last_range.GetRangeEnd() - range.GetRangeBase();
2682       // overlap will be less than range.GetByteSize() or else HasErased()
2683       // would have been true
2684       range.SetByteSize(range.GetByteSize() - overlap);
2685       range.SetRangeBase(range.GetRangeBase() + overlap);
2686     }
2687   }
2688 
2689   StreamString packet;
2690   packet.Printf("vFlashErase:%" PRIx64 ",%" PRIx64, range.GetRangeBase(),
2691                 (uint64_t)range.GetByteSize());
2692 
2693   StringExtractorGDBRemote response;
2694   if (m_gdb_comm.SendPacketAndWaitForResponse(packet.GetString(), response,
2695                                               GetInterruptTimeout()) ==
2696       GDBRemoteCommunication::PacketResult::Success) {
2697     if (response.IsOKResponse()) {
2698       m_erased_flash_ranges.Insert(range, true);
2699     } else {
2700       if (response.IsErrorResponse())
2701         status.SetErrorStringWithFormat("flash erase failed for 0x%" PRIx64,
2702                                         addr);
2703       else if (response.IsUnsupportedResponse())
2704         status.SetErrorStringWithFormat("GDB server does not support flashing");
2705       else
2706         status.SetErrorStringWithFormat(
2707             "unexpected response to GDB server flash erase packet '%s': '%s'",
2708             packet.GetData(), response.GetStringRef().data());
2709     }
2710   } else {
2711     status.SetErrorStringWithFormat("failed to send packet: '%s'",
2712                                     packet.GetData());
2713   }
2714   return status;
2715 }
2716 
2717 Status ProcessGDBRemote::FlashDone() {
2718   Status status;
2719   // If we haven't erased any blocks, then we must not have written anything
2720   // either, so there is no need to actually send a vFlashDone command
2721   if (m_erased_flash_ranges.IsEmpty())
2722     return status;
2723   StringExtractorGDBRemote response;
2724   if (m_gdb_comm.SendPacketAndWaitForResponse("vFlashDone", response,
2725                                               GetInterruptTimeout()) ==
2726       GDBRemoteCommunication::PacketResult::Success) {
2727     if (response.IsOKResponse()) {
2728       m_erased_flash_ranges.Clear();
2729     } else {
2730       if (response.IsErrorResponse())
2731         status.SetErrorStringWithFormat("flash done failed");
2732       else if (response.IsUnsupportedResponse())
2733         status.SetErrorStringWithFormat("GDB server does not support flashing");
2734       else
2735         status.SetErrorStringWithFormat(
2736             "unexpected response to GDB server flash done packet: '%s'",
2737             response.GetStringRef().data());
2738     }
2739   } else {
2740     status.SetErrorStringWithFormat("failed to send flash done packet");
2741   }
2742   return status;
2743 }
2744 
2745 size_t ProcessGDBRemote::DoWriteMemory(addr_t addr, const void *buf,
2746                                        size_t size, Status &error) {
2747   GetMaxMemorySize();
2748   // M and m packets take 2 bytes for 1 byte of memory
2749   size_t max_memory_size = m_max_memory_size / 2;
2750   if (size > max_memory_size) {
2751     // Keep memory read sizes down to a sane limit. This function will be
2752     // called multiple times in order to complete the task by
2753     // lldb_private::Process so it is ok to do this.
2754     size = max_memory_size;
2755   }
2756 
2757   StreamGDBRemote packet;
2758 
2759   MemoryRegionInfo region;
2760   Status region_status = GetMemoryRegionInfo(addr, region);
2761 
2762   bool is_flash =
2763       region_status.Success() && region.GetFlash() == MemoryRegionInfo::eYes;
2764 
2765   if (is_flash) {
2766     if (!m_allow_flash_writes) {
2767       error.SetErrorString("Writing to flash memory is not allowed");
2768       return 0;
2769     }
2770     // Keep the write within a flash memory region
2771     if (addr + size > region.GetRange().GetRangeEnd())
2772       size = region.GetRange().GetRangeEnd() - addr;
2773     // Flash memory must be erased before it can be written
2774     error = FlashErase(addr, size);
2775     if (!error.Success())
2776       return 0;
2777     packet.Printf("vFlashWrite:%" PRIx64 ":", addr);
2778     packet.PutEscapedBytes(buf, size);
2779   } else {
2780     packet.Printf("M%" PRIx64 ",%" PRIx64 ":", addr, (uint64_t)size);
2781     packet.PutBytesAsRawHex8(buf, size, endian::InlHostByteOrder(),
2782                              endian::InlHostByteOrder());
2783   }
2784   StringExtractorGDBRemote response;
2785   if (m_gdb_comm.SendPacketAndWaitForResponse(packet.GetString(), response,
2786                                               GetInterruptTimeout()) ==
2787       GDBRemoteCommunication::PacketResult::Success) {
2788     if (response.IsOKResponse()) {
2789       error.Clear();
2790       return size;
2791     } else if (response.IsErrorResponse())
2792       error.SetErrorStringWithFormat("memory write failed for 0x%" PRIx64,
2793                                      addr);
2794     else if (response.IsUnsupportedResponse())
2795       error.SetErrorStringWithFormat(
2796           "GDB server does not support writing memory");
2797     else
2798       error.SetErrorStringWithFormat(
2799           "unexpected response to GDB server memory write packet '%s': '%s'",
2800           packet.GetData(), response.GetStringRef().data());
2801   } else {
2802     error.SetErrorStringWithFormat("failed to send packet: '%s'",
2803                                    packet.GetData());
2804   }
2805   return 0;
2806 }
2807 
2808 lldb::addr_t ProcessGDBRemote::DoAllocateMemory(size_t size,
2809                                                 uint32_t permissions,
2810                                                 Status &error) {
2811   Log *log = GetLog(LLDBLog::Process | LLDBLog::Expressions);
2812   addr_t allocated_addr = LLDB_INVALID_ADDRESS;
2813 
2814   if (m_gdb_comm.SupportsAllocDeallocMemory() != eLazyBoolNo) {
2815     allocated_addr = m_gdb_comm.AllocateMemory(size, permissions);
2816     if (allocated_addr != LLDB_INVALID_ADDRESS ||
2817         m_gdb_comm.SupportsAllocDeallocMemory() == eLazyBoolYes)
2818       return allocated_addr;
2819   }
2820 
2821   if (m_gdb_comm.SupportsAllocDeallocMemory() == eLazyBoolNo) {
2822     // Call mmap() to create memory in the inferior..
2823     unsigned prot = 0;
2824     if (permissions & lldb::ePermissionsReadable)
2825       prot |= eMmapProtRead;
2826     if (permissions & lldb::ePermissionsWritable)
2827       prot |= eMmapProtWrite;
2828     if (permissions & lldb::ePermissionsExecutable)
2829       prot |= eMmapProtExec;
2830 
2831     if (InferiorCallMmap(this, allocated_addr, 0, size, prot,
2832                          eMmapFlagsAnon | eMmapFlagsPrivate, -1, 0))
2833       m_addr_to_mmap_size[allocated_addr] = size;
2834     else {
2835       allocated_addr = LLDB_INVALID_ADDRESS;
2836       LLDB_LOGF(log,
2837                 "ProcessGDBRemote::%s no direct stub support for memory "
2838                 "allocation, and InferiorCallMmap also failed - is stub "
2839                 "missing register context save/restore capability?",
2840                 __FUNCTION__);
2841     }
2842   }
2843 
2844   if (allocated_addr == LLDB_INVALID_ADDRESS)
2845     error.SetErrorStringWithFormat(
2846         "unable to allocate %" PRIu64 " bytes of memory with permissions %s",
2847         (uint64_t)size, GetPermissionsAsCString(permissions));
2848   else
2849     error.Clear();
2850   return allocated_addr;
2851 }
2852 
2853 Status ProcessGDBRemote::DoGetMemoryRegionInfo(addr_t load_addr,
2854                                                MemoryRegionInfo &region_info) {
2855 
2856   Status error(m_gdb_comm.GetMemoryRegionInfo(load_addr, region_info));
2857   return error;
2858 }
2859 
2860 std::optional<uint32_t> ProcessGDBRemote::GetWatchpointSlotCount() {
2861   return m_gdb_comm.GetWatchpointSlotCount();
2862 }
2863 
2864 std::optional<bool> ProcessGDBRemote::DoGetWatchpointReportedAfter() {
2865   return m_gdb_comm.GetWatchpointReportedAfter();
2866 }
2867 
2868 Status ProcessGDBRemote::DoDeallocateMemory(lldb::addr_t addr) {
2869   Status error;
2870   LazyBool supported = m_gdb_comm.SupportsAllocDeallocMemory();
2871 
2872   switch (supported) {
2873   case eLazyBoolCalculate:
2874     // We should never be deallocating memory without allocating memory first
2875     // so we should never get eLazyBoolCalculate
2876     error.SetErrorString(
2877         "tried to deallocate memory without ever allocating memory");
2878     break;
2879 
2880   case eLazyBoolYes:
2881     if (!m_gdb_comm.DeallocateMemory(addr))
2882       error.SetErrorStringWithFormat(
2883           "unable to deallocate memory at 0x%" PRIx64, addr);
2884     break;
2885 
2886   case eLazyBoolNo:
2887     // Call munmap() to deallocate memory in the inferior..
2888     {
2889       MMapMap::iterator pos = m_addr_to_mmap_size.find(addr);
2890       if (pos != m_addr_to_mmap_size.end() &&
2891           InferiorCallMunmap(this, addr, pos->second))
2892         m_addr_to_mmap_size.erase(pos);
2893       else
2894         error.SetErrorStringWithFormat(
2895             "unable to deallocate memory at 0x%" PRIx64, addr);
2896     }
2897     break;
2898   }
2899 
2900   return error;
2901 }
2902 
2903 // Process STDIO
2904 size_t ProcessGDBRemote::PutSTDIN(const char *src, size_t src_len,
2905                                   Status &error) {
2906   if (m_stdio_communication.IsConnected()) {
2907     ConnectionStatus status;
2908     m_stdio_communication.WriteAll(src, src_len, status, nullptr);
2909   } else if (m_stdin_forward) {
2910     m_gdb_comm.SendStdinNotification(src, src_len);
2911   }
2912   return 0;
2913 }
2914 
2915 Status ProcessGDBRemote::EnableBreakpointSite(BreakpointSite *bp_site) {
2916   Status error;
2917   assert(bp_site != nullptr);
2918 
2919   // Get logging info
2920   Log *log = GetLog(GDBRLog::Breakpoints);
2921   user_id_t site_id = bp_site->GetID();
2922 
2923   // Get the breakpoint address
2924   const addr_t addr = bp_site->GetLoadAddress();
2925 
2926   // Log that a breakpoint was requested
2927   LLDB_LOGF(log,
2928             "ProcessGDBRemote::EnableBreakpointSite (size_id = %" PRIu64
2929             ") address = 0x%" PRIx64,
2930             site_id, (uint64_t)addr);
2931 
2932   // Breakpoint already exists and is enabled
2933   if (bp_site->IsEnabled()) {
2934     LLDB_LOGF(log,
2935               "ProcessGDBRemote::EnableBreakpointSite (size_id = %" PRIu64
2936               ") address = 0x%" PRIx64 " -- SUCCESS (already enabled)",
2937               site_id, (uint64_t)addr);
2938     return error;
2939   }
2940 
2941   // Get the software breakpoint trap opcode size
2942   const size_t bp_op_size = GetSoftwareBreakpointTrapOpcode(bp_site);
2943 
2944   // SupportsGDBStoppointPacket() simply checks a boolean, indicating if this
2945   // breakpoint type is supported by the remote stub. These are set to true by
2946   // default, and later set to false only after we receive an unimplemented
2947   // response when sending a breakpoint packet. This means initially that
2948   // unless we were specifically instructed to use a hardware breakpoint, LLDB
2949   // will attempt to set a software breakpoint. HardwareRequired() also queries
2950   // a boolean variable which indicates if the user specifically asked for
2951   // hardware breakpoints.  If true then we will skip over software
2952   // breakpoints.
2953   if (m_gdb_comm.SupportsGDBStoppointPacket(eBreakpointSoftware) &&
2954       (!bp_site->HardwareRequired())) {
2955     // Try to send off a software breakpoint packet ($Z0)
2956     uint8_t error_no = m_gdb_comm.SendGDBStoppointTypePacket(
2957         eBreakpointSoftware, true, addr, bp_op_size, GetInterruptTimeout());
2958     if (error_no == 0) {
2959       // The breakpoint was placed successfully
2960       bp_site->SetEnabled(true);
2961       bp_site->SetType(BreakpointSite::eExternal);
2962       return error;
2963     }
2964 
2965     // SendGDBStoppointTypePacket() will return an error if it was unable to
2966     // set this breakpoint. We need to differentiate between a error specific
2967     // to placing this breakpoint or if we have learned that this breakpoint
2968     // type is unsupported. To do this, we must test the support boolean for
2969     // this breakpoint type to see if it now indicates that this breakpoint
2970     // type is unsupported.  If they are still supported then we should return
2971     // with the error code.  If they are now unsupported, then we would like to
2972     // fall through and try another form of breakpoint.
2973     if (m_gdb_comm.SupportsGDBStoppointPacket(eBreakpointSoftware)) {
2974       if (error_no != UINT8_MAX)
2975         error.SetErrorStringWithFormat(
2976             "error: %d sending the breakpoint request", error_no);
2977       else
2978         error.SetErrorString("error sending the breakpoint request");
2979       return error;
2980     }
2981 
2982     // We reach here when software breakpoints have been found to be
2983     // unsupported. For future calls to set a breakpoint, we will not attempt
2984     // to set a breakpoint with a type that is known not to be supported.
2985     LLDB_LOGF(log, "Software breakpoints are unsupported");
2986 
2987     // So we will fall through and try a hardware breakpoint
2988   }
2989 
2990   // The process of setting a hardware breakpoint is much the same as above.
2991   // We check the supported boolean for this breakpoint type, and if it is
2992   // thought to be supported then we will try to set this breakpoint with a
2993   // hardware breakpoint.
2994   if (m_gdb_comm.SupportsGDBStoppointPacket(eBreakpointHardware)) {
2995     // Try to send off a hardware breakpoint packet ($Z1)
2996     uint8_t error_no = m_gdb_comm.SendGDBStoppointTypePacket(
2997         eBreakpointHardware, true, addr, bp_op_size, GetInterruptTimeout());
2998     if (error_no == 0) {
2999       // The breakpoint was placed successfully
3000       bp_site->SetEnabled(true);
3001       bp_site->SetType(BreakpointSite::eHardware);
3002       return error;
3003     }
3004 
3005     // Check if the error was something other then an unsupported breakpoint
3006     // type
3007     if (m_gdb_comm.SupportsGDBStoppointPacket(eBreakpointHardware)) {
3008       // Unable to set this hardware breakpoint
3009       if (error_no != UINT8_MAX)
3010         error.SetErrorStringWithFormat(
3011             "error: %d sending the hardware breakpoint request "
3012             "(hardware breakpoint resources might be exhausted or unavailable)",
3013             error_no);
3014       else
3015         error.SetErrorString("error sending the hardware breakpoint request "
3016                              "(hardware breakpoint resources "
3017                              "might be exhausted or unavailable)");
3018       return error;
3019     }
3020 
3021     // We will reach here when the stub gives an unsupported response to a
3022     // hardware breakpoint
3023     LLDB_LOGF(log, "Hardware breakpoints are unsupported");
3024 
3025     // Finally we will falling through to a #trap style breakpoint
3026   }
3027 
3028   // Don't fall through when hardware breakpoints were specifically requested
3029   if (bp_site->HardwareRequired()) {
3030     error.SetErrorString("hardware breakpoints are not supported");
3031     return error;
3032   }
3033 
3034   // As a last resort we want to place a manual breakpoint. An instruction is
3035   // placed into the process memory using memory write packets.
3036   return EnableSoftwareBreakpoint(bp_site);
3037 }
3038 
3039 Status ProcessGDBRemote::DisableBreakpointSite(BreakpointSite *bp_site) {
3040   Status error;
3041   assert(bp_site != nullptr);
3042   addr_t addr = bp_site->GetLoadAddress();
3043   user_id_t site_id = bp_site->GetID();
3044   Log *log = GetLog(GDBRLog::Breakpoints);
3045   LLDB_LOGF(log,
3046             "ProcessGDBRemote::DisableBreakpointSite (site_id = %" PRIu64
3047             ") addr = 0x%8.8" PRIx64,
3048             site_id, (uint64_t)addr);
3049 
3050   if (bp_site->IsEnabled()) {
3051     const size_t bp_op_size = GetSoftwareBreakpointTrapOpcode(bp_site);
3052 
3053     BreakpointSite::Type bp_type = bp_site->GetType();
3054     switch (bp_type) {
3055     case BreakpointSite::eSoftware:
3056       error = DisableSoftwareBreakpoint(bp_site);
3057       break;
3058 
3059     case BreakpointSite::eHardware:
3060       if (m_gdb_comm.SendGDBStoppointTypePacket(eBreakpointHardware, false,
3061                                                 addr, bp_op_size,
3062                                                 GetInterruptTimeout()))
3063         error.SetErrorToGenericError();
3064       break;
3065 
3066     case BreakpointSite::eExternal: {
3067       if (m_gdb_comm.SendGDBStoppointTypePacket(eBreakpointSoftware, false,
3068                                                 addr, bp_op_size,
3069                                                 GetInterruptTimeout()))
3070         error.SetErrorToGenericError();
3071     } break;
3072     }
3073     if (error.Success())
3074       bp_site->SetEnabled(false);
3075   } else {
3076     LLDB_LOGF(log,
3077               "ProcessGDBRemote::DisableBreakpointSite (site_id = %" PRIu64
3078               ") addr = 0x%8.8" PRIx64 " -- SUCCESS (already disabled)",
3079               site_id, (uint64_t)addr);
3080     return error;
3081   }
3082 
3083   if (error.Success())
3084     error.SetErrorToGenericError();
3085   return error;
3086 }
3087 
3088 // Pre-requisite: wp != NULL.
3089 static GDBStoppointType GetGDBStoppointType(Watchpoint *wp) {
3090   assert(wp);
3091   bool watch_read = wp->WatchpointRead();
3092   bool watch_write = wp->WatchpointWrite();
3093 
3094   // watch_read and watch_write cannot both be false.
3095   assert(watch_read || watch_write);
3096   if (watch_read && watch_write)
3097     return eWatchpointReadWrite;
3098   else if (watch_read)
3099     return eWatchpointRead;
3100   else // Must be watch_write, then.
3101     return eWatchpointWrite;
3102 }
3103 
3104 Status ProcessGDBRemote::EnableWatchpoint(Watchpoint *wp, bool notify) {
3105   Status error;
3106   if (wp) {
3107     user_id_t watchID = wp->GetID();
3108     addr_t addr = wp->GetLoadAddress();
3109     Log *log(GetLog(GDBRLog::Watchpoints));
3110     LLDB_LOGF(log, "ProcessGDBRemote::EnableWatchpoint(watchID = %" PRIu64 ")",
3111               watchID);
3112     if (wp->IsEnabled()) {
3113       LLDB_LOGF(log,
3114                 "ProcessGDBRemote::EnableWatchpoint(watchID = %" PRIu64
3115                 ") addr = 0x%8.8" PRIx64 ": watchpoint already enabled.",
3116                 watchID, (uint64_t)addr);
3117       return error;
3118     }
3119 
3120     GDBStoppointType type = GetGDBStoppointType(wp);
3121     // Pass down an appropriate z/Z packet...
3122     if (m_gdb_comm.SupportsGDBStoppointPacket(type)) {
3123       if (m_gdb_comm.SendGDBStoppointTypePacket(type, true, addr,
3124                                                 wp->GetByteSize(),
3125                                                 GetInterruptTimeout()) == 0) {
3126         wp->SetEnabled(true, notify);
3127         return error;
3128       } else
3129         error.SetErrorString("sending gdb watchpoint packet failed");
3130     } else
3131       error.SetErrorString("watchpoints not supported");
3132   } else {
3133     error.SetErrorString("Watchpoint argument was NULL.");
3134   }
3135   if (error.Success())
3136     error.SetErrorToGenericError();
3137   return error;
3138 }
3139 
3140 Status ProcessGDBRemote::DisableWatchpoint(Watchpoint *wp, bool notify) {
3141   Status error;
3142   if (wp) {
3143     user_id_t watchID = wp->GetID();
3144 
3145     Log *log(GetLog(GDBRLog::Watchpoints));
3146 
3147     addr_t addr = wp->GetLoadAddress();
3148 
3149     LLDB_LOGF(log,
3150               "ProcessGDBRemote::DisableWatchpoint (watchID = %" PRIu64
3151               ") addr = 0x%8.8" PRIx64,
3152               watchID, (uint64_t)addr);
3153 
3154     if (!wp->IsEnabled()) {
3155       LLDB_LOGF(log,
3156                 "ProcessGDBRemote::DisableWatchpoint (watchID = %" PRIu64
3157                 ") addr = 0x%8.8" PRIx64 " -- SUCCESS (already disabled)",
3158                 watchID, (uint64_t)addr);
3159       // See also 'class WatchpointSentry' within StopInfo.cpp. This disabling
3160       // attempt might come from the user-supplied actions, we'll route it in
3161       // order for the watchpoint object to intelligently process this action.
3162       wp->SetEnabled(false, notify);
3163       return error;
3164     }
3165 
3166     if (wp->IsHardware()) {
3167       GDBStoppointType type = GetGDBStoppointType(wp);
3168       // Pass down an appropriate z/Z packet...
3169       if (m_gdb_comm.SendGDBStoppointTypePacket(type, false, addr,
3170                                                 wp->GetByteSize(),
3171                                                 GetInterruptTimeout()) == 0) {
3172         wp->SetEnabled(false, notify);
3173         return error;
3174       } else
3175         error.SetErrorString("sending gdb watchpoint packet failed");
3176     }
3177     // TODO: clear software watchpoints if we implement them
3178   } else {
3179     error.SetErrorString("Watchpoint argument was NULL.");
3180   }
3181   if (error.Success())
3182     error.SetErrorToGenericError();
3183   return error;
3184 }
3185 
3186 void ProcessGDBRemote::Clear() {
3187   m_thread_list_real.Clear();
3188   m_thread_list.Clear();
3189 }
3190 
3191 Status ProcessGDBRemote::DoSignal(int signo) {
3192   Status error;
3193   Log *log = GetLog(GDBRLog::Process);
3194   LLDB_LOGF(log, "ProcessGDBRemote::DoSignal (signal = %d)", signo);
3195 
3196   if (!m_gdb_comm.SendAsyncSignal(signo, GetInterruptTimeout()))
3197     error.SetErrorStringWithFormat("failed to send signal %i", signo);
3198   return error;
3199 }
3200 
3201 Status
3202 ProcessGDBRemote::EstablishConnectionIfNeeded(const ProcessInfo &process_info) {
3203   // Make sure we aren't already connected?
3204   if (m_gdb_comm.IsConnected())
3205     return Status();
3206 
3207   PlatformSP platform_sp(GetTarget().GetPlatform());
3208   if (platform_sp && !platform_sp->IsHost())
3209     return Status("Lost debug server connection");
3210 
3211   auto error = LaunchAndConnectToDebugserver(process_info);
3212   if (error.Fail()) {
3213     const char *error_string = error.AsCString();
3214     if (error_string == nullptr)
3215       error_string = "unable to launch " DEBUGSERVER_BASENAME;
3216   }
3217   return error;
3218 }
3219 #if !defined(_WIN32)
3220 #define USE_SOCKETPAIR_FOR_LOCAL_CONNECTION 1
3221 #endif
3222 
3223 #ifdef USE_SOCKETPAIR_FOR_LOCAL_CONNECTION
3224 static bool SetCloexecFlag(int fd) {
3225 #if defined(FD_CLOEXEC)
3226   int flags = ::fcntl(fd, F_GETFD);
3227   if (flags == -1)
3228     return false;
3229   return (::fcntl(fd, F_SETFD, flags | FD_CLOEXEC) == 0);
3230 #else
3231   return false;
3232 #endif
3233 }
3234 #endif
3235 
3236 Status ProcessGDBRemote::LaunchAndConnectToDebugserver(
3237     const ProcessInfo &process_info) {
3238   using namespace std::placeholders; // For _1, _2, etc.
3239 
3240   Status error;
3241   if (m_debugserver_pid == LLDB_INVALID_PROCESS_ID) {
3242     // If we locate debugserver, keep that located version around
3243     static FileSpec g_debugserver_file_spec;
3244 
3245     ProcessLaunchInfo debugserver_launch_info;
3246     // Make debugserver run in its own session so signals generated by special
3247     // terminal key sequences (^C) don't affect debugserver.
3248     debugserver_launch_info.SetLaunchInSeparateProcessGroup(true);
3249 
3250     const std::weak_ptr<ProcessGDBRemote> this_wp =
3251         std::static_pointer_cast<ProcessGDBRemote>(shared_from_this());
3252     debugserver_launch_info.SetMonitorProcessCallback(
3253         std::bind(MonitorDebugserverProcess, this_wp, _1, _2, _3));
3254     debugserver_launch_info.SetUserID(process_info.GetUserID());
3255 
3256 #if defined(__APPLE__)
3257     // On macOS 11, we need to support x86_64 applications translated to
3258     // arm64. We check whether a binary is translated and spawn the correct
3259     // debugserver accordingly.
3260     int mib[] = { CTL_KERN, KERN_PROC, KERN_PROC_PID,
3261                   static_cast<int>(process_info.GetProcessID()) };
3262     struct kinfo_proc processInfo;
3263     size_t bufsize = sizeof(processInfo);
3264     if (sysctl(mib, (unsigned)(sizeof(mib)/sizeof(int)), &processInfo,
3265                &bufsize, NULL, 0) == 0 && bufsize > 0) {
3266       if (processInfo.kp_proc.p_flag & P_TRANSLATED) {
3267         FileSpec rosetta_debugserver("/Library/Apple/usr/libexec/oah/debugserver");
3268         debugserver_launch_info.SetExecutableFile(rosetta_debugserver, false);
3269       }
3270     }
3271 #endif
3272 
3273     int communication_fd = -1;
3274 #ifdef USE_SOCKETPAIR_FOR_LOCAL_CONNECTION
3275     // Use a socketpair on non-Windows systems for security and performance
3276     // reasons.
3277     int sockets[2]; /* the pair of socket descriptors */
3278     if (socketpair(AF_UNIX, SOCK_STREAM, 0, sockets) == -1) {
3279       error.SetErrorToErrno();
3280       return error;
3281     }
3282 
3283     int our_socket = sockets[0];
3284     int gdb_socket = sockets[1];
3285     auto cleanup_our = llvm::make_scope_exit([&]() { close(our_socket); });
3286     auto cleanup_gdb = llvm::make_scope_exit([&]() { close(gdb_socket); });
3287 
3288     // Don't let any child processes inherit our communication socket
3289     SetCloexecFlag(our_socket);
3290     communication_fd = gdb_socket;
3291 #endif
3292 
3293     error = m_gdb_comm.StartDebugserverProcess(
3294         nullptr, GetTarget().GetPlatform().get(), debugserver_launch_info,
3295         nullptr, nullptr, communication_fd);
3296 
3297     if (error.Success())
3298       m_debugserver_pid = debugserver_launch_info.GetProcessID();
3299     else
3300       m_debugserver_pid = LLDB_INVALID_PROCESS_ID;
3301 
3302     if (m_debugserver_pid != LLDB_INVALID_PROCESS_ID) {
3303 #ifdef USE_SOCKETPAIR_FOR_LOCAL_CONNECTION
3304       // Our process spawned correctly, we can now set our connection to use
3305       // our end of the socket pair
3306       cleanup_our.release();
3307       m_gdb_comm.SetConnection(
3308           std::make_unique<ConnectionFileDescriptor>(our_socket, true));
3309 #endif
3310       StartAsyncThread();
3311     }
3312 
3313     if (error.Fail()) {
3314       Log *log = GetLog(GDBRLog::Process);
3315 
3316       LLDB_LOGF(log, "failed to start debugserver process: %s",
3317                 error.AsCString());
3318       return error;
3319     }
3320 
3321     if (m_gdb_comm.IsConnected()) {
3322       // Finish the connection process by doing the handshake without
3323       // connecting (send NULL URL)
3324       error = ConnectToDebugserver("");
3325     } else {
3326       error.SetErrorString("connection failed");
3327     }
3328   }
3329   return error;
3330 }
3331 
3332 void ProcessGDBRemote::MonitorDebugserverProcess(
3333     std::weak_ptr<ProcessGDBRemote> process_wp, lldb::pid_t debugserver_pid,
3334     int signo,      // Zero for no signal
3335     int exit_status // Exit value of process if signal is zero
3336 ) {
3337   // "debugserver_pid" argument passed in is the process ID for debugserver
3338   // that we are tracking...
3339   Log *log = GetLog(GDBRLog::Process);
3340 
3341   LLDB_LOGF(log,
3342             "ProcessGDBRemote::%s(process_wp, pid=%" PRIu64
3343             ", signo=%i (0x%x), exit_status=%i)",
3344             __FUNCTION__, debugserver_pid, signo, signo, exit_status);
3345 
3346   std::shared_ptr<ProcessGDBRemote> process_sp = process_wp.lock();
3347   LLDB_LOGF(log, "ProcessGDBRemote::%s(process = %p)", __FUNCTION__,
3348             static_cast<void *>(process_sp.get()));
3349   if (!process_sp || process_sp->m_debugserver_pid != debugserver_pid)
3350     return;
3351 
3352   // Sleep for a half a second to make sure our inferior process has time to
3353   // set its exit status before we set it incorrectly when both the debugserver
3354   // and the inferior process shut down.
3355   std::this_thread::sleep_for(std::chrono::milliseconds(500));
3356 
3357   // If our process hasn't yet exited, debugserver might have died. If the
3358   // process did exit, then we are reaping it.
3359   const StateType state = process_sp->GetState();
3360 
3361   if (state != eStateInvalid && state != eStateUnloaded &&
3362       state != eStateExited && state != eStateDetached) {
3363     char error_str[1024];
3364     if (signo) {
3365       const char *signal_cstr =
3366           process_sp->GetUnixSignals()->GetSignalAsCString(signo);
3367       if (signal_cstr)
3368         ::snprintf(error_str, sizeof(error_str),
3369                    DEBUGSERVER_BASENAME " died with signal %s", signal_cstr);
3370       else
3371         ::snprintf(error_str, sizeof(error_str),
3372                    DEBUGSERVER_BASENAME " died with signal %i", signo);
3373     } else {
3374       ::snprintf(error_str, sizeof(error_str),
3375                  DEBUGSERVER_BASENAME " died with an exit status of 0x%8.8x",
3376                  exit_status);
3377     }
3378 
3379     process_sp->SetExitStatus(-1, error_str);
3380   }
3381   // Debugserver has exited we need to let our ProcessGDBRemote know that it no
3382   // longer has a debugserver instance
3383   process_sp->m_debugserver_pid = LLDB_INVALID_PROCESS_ID;
3384 }
3385 
3386 void ProcessGDBRemote::KillDebugserverProcess() {
3387   m_gdb_comm.Disconnect();
3388   if (m_debugserver_pid != LLDB_INVALID_PROCESS_ID) {
3389     Host::Kill(m_debugserver_pid, SIGINT);
3390     m_debugserver_pid = LLDB_INVALID_PROCESS_ID;
3391   }
3392 }
3393 
3394 void ProcessGDBRemote::Initialize() {
3395   static llvm::once_flag g_once_flag;
3396 
3397   llvm::call_once(g_once_flag, []() {
3398     PluginManager::RegisterPlugin(GetPluginNameStatic(),
3399                                   GetPluginDescriptionStatic(), CreateInstance,
3400                                   DebuggerInitialize);
3401   });
3402 }
3403 
3404 void ProcessGDBRemote::DebuggerInitialize(Debugger &debugger) {
3405   if (!PluginManager::GetSettingForProcessPlugin(
3406           debugger, PluginProperties::GetSettingName())) {
3407     const bool is_global_setting = true;
3408     PluginManager::CreateSettingForProcessPlugin(
3409         debugger, GetGlobalPluginProperties().GetValueProperties(),
3410         "Properties for the gdb-remote process plug-in.", is_global_setting);
3411   }
3412 }
3413 
3414 bool ProcessGDBRemote::StartAsyncThread() {
3415   Log *log = GetLog(GDBRLog::Process);
3416 
3417   LLDB_LOGF(log, "ProcessGDBRemote::%s ()", __FUNCTION__);
3418 
3419   std::lock_guard<std::recursive_mutex> guard(m_async_thread_state_mutex);
3420   if (!m_async_thread.IsJoinable()) {
3421     // Create a thread that watches our internal state and controls which
3422     // events make it to clients (into the DCProcess event queue).
3423 
3424     llvm::Expected<HostThread> async_thread =
3425         ThreadLauncher::LaunchThread("<lldb.process.gdb-remote.async>", [this] {
3426           return ProcessGDBRemote::AsyncThread();
3427         });
3428     if (!async_thread) {
3429       LLDB_LOG_ERROR(GetLog(LLDBLog::Host), async_thread.takeError(),
3430                      "failed to launch host thread: {}");
3431       return false;
3432     }
3433     m_async_thread = *async_thread;
3434   } else
3435     LLDB_LOGF(log,
3436               "ProcessGDBRemote::%s () - Called when Async thread was "
3437               "already running.",
3438               __FUNCTION__);
3439 
3440   return m_async_thread.IsJoinable();
3441 }
3442 
3443 void ProcessGDBRemote::StopAsyncThread() {
3444   Log *log = GetLog(GDBRLog::Process);
3445 
3446   LLDB_LOGF(log, "ProcessGDBRemote::%s ()", __FUNCTION__);
3447 
3448   std::lock_guard<std::recursive_mutex> guard(m_async_thread_state_mutex);
3449   if (m_async_thread.IsJoinable()) {
3450     m_async_broadcaster.BroadcastEvent(eBroadcastBitAsyncThreadShouldExit);
3451 
3452     //  This will shut down the async thread.
3453     m_gdb_comm.Disconnect(); // Disconnect from the debug server.
3454 
3455     // Stop the stdio thread
3456     m_async_thread.Join(nullptr);
3457     m_async_thread.Reset();
3458   } else
3459     LLDB_LOGF(
3460         log,
3461         "ProcessGDBRemote::%s () - Called when Async thread was not running.",
3462         __FUNCTION__);
3463 }
3464 
3465 thread_result_t ProcessGDBRemote::AsyncThread() {
3466   Log *log = GetLog(GDBRLog::Process);
3467   LLDB_LOGF(log, "ProcessGDBRemote::%s(pid = %" PRIu64 ") thread starting...",
3468             __FUNCTION__, GetID());
3469 
3470   EventSP event_sp;
3471 
3472   // We need to ignore any packets that come in after we have
3473   // have decided the process has exited.  There are some
3474   // situations, for instance when we try to interrupt a running
3475   // process and the interrupt fails, where another packet might
3476   // get delivered after we've decided to give up on the process.
3477   // But once we've decided we are done with the process we will
3478   // not be in a state to do anything useful with new packets.
3479   // So it is safer to simply ignore any remaining packets by
3480   // explicitly checking for eStateExited before reentering the
3481   // fetch loop.
3482 
3483   bool done = false;
3484   while (!done && GetPrivateState() != eStateExited) {
3485     LLDB_LOGF(log,
3486               "ProcessGDBRemote::%s(pid = %" PRIu64
3487               ") listener.WaitForEvent (NULL, event_sp)...",
3488               __FUNCTION__, GetID());
3489 
3490     if (m_async_listener_sp->GetEvent(event_sp, std::nullopt)) {
3491       const uint32_t event_type = event_sp->GetType();
3492       if (event_sp->BroadcasterIs(&m_async_broadcaster)) {
3493         LLDB_LOGF(log,
3494                   "ProcessGDBRemote::%s(pid = %" PRIu64
3495                   ") Got an event of type: %d...",
3496                   __FUNCTION__, GetID(), event_type);
3497 
3498         switch (event_type) {
3499         case eBroadcastBitAsyncContinue: {
3500           const EventDataBytes *continue_packet =
3501               EventDataBytes::GetEventDataFromEvent(event_sp.get());
3502 
3503           if (continue_packet) {
3504             const char *continue_cstr =
3505                 (const char *)continue_packet->GetBytes();
3506             const size_t continue_cstr_len = continue_packet->GetByteSize();
3507             LLDB_LOGF(log,
3508                       "ProcessGDBRemote::%s(pid = %" PRIu64
3509                       ") got eBroadcastBitAsyncContinue: %s",
3510                       __FUNCTION__, GetID(), continue_cstr);
3511 
3512             if (::strstr(continue_cstr, "vAttach") == nullptr)
3513               SetPrivateState(eStateRunning);
3514             StringExtractorGDBRemote response;
3515 
3516             StateType stop_state =
3517                 GetGDBRemote().SendContinuePacketAndWaitForResponse(
3518                     *this, *GetUnixSignals(),
3519                     llvm::StringRef(continue_cstr, continue_cstr_len),
3520                     GetInterruptTimeout(), response);
3521 
3522             // We need to immediately clear the thread ID list so we are sure
3523             // to get a valid list of threads. The thread ID list might be
3524             // contained within the "response", or the stop reply packet that
3525             // caused the stop. So clear it now before we give the stop reply
3526             // packet to the process using the
3527             // SetLastStopPacket()...
3528             ClearThreadIDList();
3529 
3530             switch (stop_state) {
3531             case eStateStopped:
3532             case eStateCrashed:
3533             case eStateSuspended:
3534               SetLastStopPacket(response);
3535               SetPrivateState(stop_state);
3536               break;
3537 
3538             case eStateExited: {
3539               SetLastStopPacket(response);
3540               ClearThreadIDList();
3541               response.SetFilePos(1);
3542 
3543               int exit_status = response.GetHexU8();
3544               std::string desc_string;
3545               if (response.GetBytesLeft() > 0 && response.GetChar('-') == ';') {
3546                 llvm::StringRef desc_str;
3547                 llvm::StringRef desc_token;
3548                 while (response.GetNameColonValue(desc_token, desc_str)) {
3549                   if (desc_token != "description")
3550                     continue;
3551                   StringExtractor extractor(desc_str);
3552                   extractor.GetHexByteString(desc_string);
3553                 }
3554               }
3555               SetExitStatus(exit_status, desc_string.c_str());
3556               done = true;
3557               break;
3558             }
3559             case eStateInvalid: {
3560               // Check to see if we were trying to attach and if we got back
3561               // the "E87" error code from debugserver -- this indicates that
3562               // the process is not debuggable.  Return a slightly more
3563               // helpful error message about why the attach failed.
3564               if (::strstr(continue_cstr, "vAttach") != nullptr &&
3565                   response.GetError() == 0x87) {
3566                 SetExitStatus(-1, "cannot attach to process due to "
3567                                   "System Integrity Protection");
3568               } else if (::strstr(continue_cstr, "vAttach") != nullptr &&
3569                          response.GetStatus().Fail()) {
3570                 SetExitStatus(-1, response.GetStatus().AsCString());
3571               } else {
3572                 SetExitStatus(-1, "lost connection");
3573               }
3574               done = true;
3575               break;
3576             }
3577 
3578             default:
3579               SetPrivateState(stop_state);
3580               break;
3581             }   // switch(stop_state)
3582           }     // if (continue_packet)
3583         }       // case eBroadcastBitAsyncContinue
3584         break;
3585 
3586         case eBroadcastBitAsyncThreadShouldExit:
3587           LLDB_LOGF(log,
3588                     "ProcessGDBRemote::%s(pid = %" PRIu64
3589                     ") got eBroadcastBitAsyncThreadShouldExit...",
3590                     __FUNCTION__, GetID());
3591           done = true;
3592           break;
3593 
3594         default:
3595           LLDB_LOGF(log,
3596                     "ProcessGDBRemote::%s(pid = %" PRIu64
3597                     ") got unknown event 0x%8.8x",
3598                     __FUNCTION__, GetID(), event_type);
3599           done = true;
3600           break;
3601         }
3602       }
3603     } else {
3604       LLDB_LOGF(log,
3605                 "ProcessGDBRemote::%s(pid = %" PRIu64
3606                 ") listener.WaitForEvent (NULL, event_sp) => false",
3607                 __FUNCTION__, GetID());
3608       done = true;
3609     }
3610   }
3611 
3612   LLDB_LOGF(log, "ProcessGDBRemote::%s(pid = %" PRIu64 ") thread exiting...",
3613             __FUNCTION__, GetID());
3614 
3615   return {};
3616 }
3617 
3618 // uint32_t
3619 // ProcessGDBRemote::ListProcessesMatchingName (const char *name, StringList
3620 // &matches, std::vector<lldb::pid_t> &pids)
3621 //{
3622 //    // If we are planning to launch the debugserver remotely, then we need to
3623 //    fire up a debugserver
3624 //    // process and ask it for the list of processes. But if we are local, we
3625 //    can let the Host do it.
3626 //    if (m_local_debugserver)
3627 //    {
3628 //        return Host::ListProcessesMatchingName (name, matches, pids);
3629 //    }
3630 //    else
3631 //    {
3632 //        // FIXME: Implement talking to the remote debugserver.
3633 //        return 0;
3634 //    }
3635 //
3636 //}
3637 //
3638 bool ProcessGDBRemote::NewThreadNotifyBreakpointHit(
3639     void *baton, StoppointCallbackContext *context, lldb::user_id_t break_id,
3640     lldb::user_id_t break_loc_id) {
3641   // I don't think I have to do anything here, just make sure I notice the new
3642   // thread when it starts to
3643   // run so I can stop it if that's what I want to do.
3644   Log *log = GetLog(LLDBLog::Step);
3645   LLDB_LOGF(log, "Hit New Thread Notification breakpoint.");
3646   return false;
3647 }
3648 
3649 Status ProcessGDBRemote::UpdateAutomaticSignalFiltering() {
3650   Log *log = GetLog(GDBRLog::Process);
3651   LLDB_LOG(log, "Check if need to update ignored signals");
3652 
3653   // QPassSignals package is not supported by the server, there is no way we
3654   // can ignore any signals on server side.
3655   if (!m_gdb_comm.GetQPassSignalsSupported())
3656     return Status();
3657 
3658   // No signals, nothing to send.
3659   if (m_unix_signals_sp == nullptr)
3660     return Status();
3661 
3662   // Signals' version hasn't changed, no need to send anything.
3663   uint64_t new_signals_version = m_unix_signals_sp->GetVersion();
3664   if (new_signals_version == m_last_signals_version) {
3665     LLDB_LOG(log, "Signals' version hasn't changed. version={0}",
3666              m_last_signals_version);
3667     return Status();
3668   }
3669 
3670   auto signals_to_ignore =
3671       m_unix_signals_sp->GetFilteredSignals(false, false, false);
3672   Status error = m_gdb_comm.SendSignalsToIgnore(signals_to_ignore);
3673 
3674   LLDB_LOG(log,
3675            "Signals' version changed. old version={0}, new version={1}, "
3676            "signals ignored={2}, update result={3}",
3677            m_last_signals_version, new_signals_version,
3678            signals_to_ignore.size(), error);
3679 
3680   if (error.Success())
3681     m_last_signals_version = new_signals_version;
3682 
3683   return error;
3684 }
3685 
3686 bool ProcessGDBRemote::StartNoticingNewThreads() {
3687   Log *log = GetLog(LLDBLog::Step);
3688   if (m_thread_create_bp_sp) {
3689     if (log && log->GetVerbose())
3690       LLDB_LOGF(log, "Enabled noticing new thread breakpoint.");
3691     m_thread_create_bp_sp->SetEnabled(true);
3692   } else {
3693     PlatformSP platform_sp(GetTarget().GetPlatform());
3694     if (platform_sp) {
3695       m_thread_create_bp_sp =
3696           platform_sp->SetThreadCreationBreakpoint(GetTarget());
3697       if (m_thread_create_bp_sp) {
3698         if (log && log->GetVerbose())
3699           LLDB_LOGF(
3700               log, "Successfully created new thread notification breakpoint %i",
3701               m_thread_create_bp_sp->GetID());
3702         m_thread_create_bp_sp->SetCallback(
3703             ProcessGDBRemote::NewThreadNotifyBreakpointHit, this, true);
3704       } else {
3705         LLDB_LOGF(log, "Failed to create new thread notification breakpoint.");
3706       }
3707     }
3708   }
3709   return m_thread_create_bp_sp.get() != nullptr;
3710 }
3711 
3712 bool ProcessGDBRemote::StopNoticingNewThreads() {
3713   Log *log = GetLog(LLDBLog::Step);
3714   if (log && log->GetVerbose())
3715     LLDB_LOGF(log, "Disabling new thread notification breakpoint.");
3716 
3717   if (m_thread_create_bp_sp)
3718     m_thread_create_bp_sp->SetEnabled(false);
3719 
3720   return true;
3721 }
3722 
3723 DynamicLoader *ProcessGDBRemote::GetDynamicLoader() {
3724   if (m_dyld_up.get() == nullptr)
3725     m_dyld_up.reset(DynamicLoader::FindPlugin(this, ""));
3726   return m_dyld_up.get();
3727 }
3728 
3729 Status ProcessGDBRemote::SendEventData(const char *data) {
3730   int return_value;
3731   bool was_supported;
3732 
3733   Status error;
3734 
3735   return_value = m_gdb_comm.SendLaunchEventDataPacket(data, &was_supported);
3736   if (return_value != 0) {
3737     if (!was_supported)
3738       error.SetErrorString("Sending events is not supported for this process.");
3739     else
3740       error.SetErrorStringWithFormat("Error sending event data: %d.",
3741                                      return_value);
3742   }
3743   return error;
3744 }
3745 
3746 DataExtractor ProcessGDBRemote::GetAuxvData() {
3747   DataBufferSP buf;
3748   if (m_gdb_comm.GetQXferAuxvReadSupported()) {
3749     llvm::Expected<std::string> response = m_gdb_comm.ReadExtFeature("auxv", "");
3750     if (response)
3751       buf = std::make_shared<DataBufferHeap>(response->c_str(),
3752                                              response->length());
3753     else
3754       LLDB_LOG_ERROR(GetLog(GDBRLog::Process), response.takeError(), "{0}");
3755   }
3756   return DataExtractor(buf, GetByteOrder(), GetAddressByteSize());
3757 }
3758 
3759 StructuredData::ObjectSP
3760 ProcessGDBRemote::GetExtendedInfoForThread(lldb::tid_t tid) {
3761   StructuredData::ObjectSP object_sp;
3762 
3763   if (m_gdb_comm.GetThreadExtendedInfoSupported()) {
3764     StructuredData::ObjectSP args_dict(new StructuredData::Dictionary());
3765     SystemRuntime *runtime = GetSystemRuntime();
3766     if (runtime) {
3767       runtime->AddThreadExtendedInfoPacketHints(args_dict);
3768     }
3769     args_dict->GetAsDictionary()->AddIntegerItem("thread", tid);
3770 
3771     StreamString packet;
3772     packet << "jThreadExtendedInfo:";
3773     args_dict->Dump(packet, false);
3774 
3775     // FIXME the final character of a JSON dictionary, '}', is the escape
3776     // character in gdb-remote binary mode.  lldb currently doesn't escape
3777     // these characters in its packet output -- so we add the quoted version of
3778     // the } character here manually in case we talk to a debugserver which un-
3779     // escapes the characters at packet read time.
3780     packet << (char)(0x7d ^ 0x20);
3781 
3782     StringExtractorGDBRemote response;
3783     response.SetResponseValidatorToJSON();
3784     if (m_gdb_comm.SendPacketAndWaitForResponse(packet.GetString(), response) ==
3785         GDBRemoteCommunication::PacketResult::Success) {
3786       StringExtractorGDBRemote::ResponseType response_type =
3787           response.GetResponseType();
3788       if (response_type == StringExtractorGDBRemote::eResponse) {
3789         if (!response.Empty()) {
3790           object_sp = StructuredData::ParseJSON(response.GetStringRef());
3791         }
3792       }
3793     }
3794   }
3795   return object_sp;
3796 }
3797 
3798 StructuredData::ObjectSP ProcessGDBRemote::GetLoadedDynamicLibrariesInfos(
3799     lldb::addr_t image_list_address, lldb::addr_t image_count) {
3800 
3801   StructuredData::ObjectSP args_dict(new StructuredData::Dictionary());
3802   args_dict->GetAsDictionary()->AddIntegerItem("image_list_address",
3803                                                image_list_address);
3804   args_dict->GetAsDictionary()->AddIntegerItem("image_count", image_count);
3805 
3806   return GetLoadedDynamicLibrariesInfos_sender(args_dict);
3807 }
3808 
3809 StructuredData::ObjectSP ProcessGDBRemote::GetLoadedDynamicLibrariesInfos() {
3810   StructuredData::ObjectSP args_dict(new StructuredData::Dictionary());
3811 
3812   args_dict->GetAsDictionary()->AddBooleanItem("fetch_all_solibs", true);
3813 
3814   return GetLoadedDynamicLibrariesInfos_sender(args_dict);
3815 }
3816 
3817 StructuredData::ObjectSP ProcessGDBRemote::GetLoadedDynamicLibrariesInfos(
3818     const std::vector<lldb::addr_t> &load_addresses) {
3819   StructuredData::ObjectSP args_dict(new StructuredData::Dictionary());
3820   StructuredData::ArraySP addresses(new StructuredData::Array);
3821 
3822   for (auto addr : load_addresses)
3823     addresses->AddIntegerItem(addr);
3824 
3825   args_dict->GetAsDictionary()->AddItem("solib_addresses", addresses);
3826 
3827   return GetLoadedDynamicLibrariesInfos_sender(args_dict);
3828 }
3829 
3830 StructuredData::ObjectSP
3831 ProcessGDBRemote::GetLoadedDynamicLibrariesInfos_sender(
3832     StructuredData::ObjectSP args_dict) {
3833   StructuredData::ObjectSP object_sp;
3834 
3835   if (m_gdb_comm.GetLoadedDynamicLibrariesInfosSupported()) {
3836     // Scope for the scoped timeout object
3837     GDBRemoteCommunication::ScopedTimeout timeout(m_gdb_comm,
3838                                                   std::chrono::seconds(10));
3839 
3840     StreamString packet;
3841     packet << "jGetLoadedDynamicLibrariesInfos:";
3842     args_dict->Dump(packet, false);
3843 
3844     // FIXME the final character of a JSON dictionary, '}', is the escape
3845     // character in gdb-remote binary mode.  lldb currently doesn't escape
3846     // these characters in its packet output -- so we add the quoted version of
3847     // the } character here manually in case we talk to a debugserver which un-
3848     // escapes the characters at packet read time.
3849     packet << (char)(0x7d ^ 0x20);
3850 
3851     StringExtractorGDBRemote response;
3852     response.SetResponseValidatorToJSON();
3853     if (m_gdb_comm.SendPacketAndWaitForResponse(packet.GetString(), response) ==
3854         GDBRemoteCommunication::PacketResult::Success) {
3855       StringExtractorGDBRemote::ResponseType response_type =
3856           response.GetResponseType();
3857       if (response_type == StringExtractorGDBRemote::eResponse) {
3858         if (!response.Empty()) {
3859           object_sp = StructuredData::ParseJSON(response.GetStringRef());
3860         }
3861       }
3862     }
3863   }
3864   return object_sp;
3865 }
3866 
3867 StructuredData::ObjectSP ProcessGDBRemote::GetDynamicLoaderProcessState() {
3868   StructuredData::ObjectSP object_sp;
3869   StructuredData::ObjectSP args_dict(new StructuredData::Dictionary());
3870 
3871   if (m_gdb_comm.GetDynamicLoaderProcessStateSupported()) {
3872     StringExtractorGDBRemote response;
3873     response.SetResponseValidatorToJSON();
3874     if (m_gdb_comm.SendPacketAndWaitForResponse("jGetDyldProcessState",
3875                                                 response) ==
3876         GDBRemoteCommunication::PacketResult::Success) {
3877       StringExtractorGDBRemote::ResponseType response_type =
3878           response.GetResponseType();
3879       if (response_type == StringExtractorGDBRemote::eResponse) {
3880         if (!response.Empty()) {
3881           object_sp = StructuredData::ParseJSON(response.GetStringRef());
3882         }
3883       }
3884     }
3885   }
3886   return object_sp;
3887 }
3888 
3889 StructuredData::ObjectSP ProcessGDBRemote::GetSharedCacheInfo() {
3890   StructuredData::ObjectSP object_sp;
3891   StructuredData::ObjectSP args_dict(new StructuredData::Dictionary());
3892 
3893   if (m_gdb_comm.GetSharedCacheInfoSupported()) {
3894     StreamString packet;
3895     packet << "jGetSharedCacheInfo:";
3896     args_dict->Dump(packet, false);
3897 
3898     // FIXME the final character of a JSON dictionary, '}', is the escape
3899     // character in gdb-remote binary mode.  lldb currently doesn't escape
3900     // these characters in its packet output -- so we add the quoted version of
3901     // the } character here manually in case we talk to a debugserver which un-
3902     // escapes the characters at packet read time.
3903     packet << (char)(0x7d ^ 0x20);
3904 
3905     StringExtractorGDBRemote response;
3906     response.SetResponseValidatorToJSON();
3907     if (m_gdb_comm.SendPacketAndWaitForResponse(packet.GetString(), response) ==
3908         GDBRemoteCommunication::PacketResult::Success) {
3909       StringExtractorGDBRemote::ResponseType response_type =
3910           response.GetResponseType();
3911       if (response_type == StringExtractorGDBRemote::eResponse) {
3912         if (!response.Empty()) {
3913           object_sp = StructuredData::ParseJSON(response.GetStringRef());
3914         }
3915       }
3916     }
3917   }
3918   return object_sp;
3919 }
3920 
3921 Status ProcessGDBRemote::ConfigureStructuredData(
3922     ConstString type_name, const StructuredData::ObjectSP &config_sp) {
3923   return m_gdb_comm.ConfigureRemoteStructuredData(type_name, config_sp);
3924 }
3925 
3926 // Establish the largest memory read/write payloads we should use. If the
3927 // remote stub has a max packet size, stay under that size.
3928 //
3929 // If the remote stub's max packet size is crazy large, use a reasonable
3930 // largeish default.
3931 //
3932 // If the remote stub doesn't advertise a max packet size, use a conservative
3933 // default.
3934 
3935 void ProcessGDBRemote::GetMaxMemorySize() {
3936   const uint64_t reasonable_largeish_default = 128 * 1024;
3937   const uint64_t conservative_default = 512;
3938 
3939   if (m_max_memory_size == 0) {
3940     uint64_t stub_max_size = m_gdb_comm.GetRemoteMaxPacketSize();
3941     if (stub_max_size != UINT64_MAX && stub_max_size != 0) {
3942       // Save the stub's claimed maximum packet size
3943       m_remote_stub_max_memory_size = stub_max_size;
3944 
3945       // Even if the stub says it can support ginormous packets, don't exceed
3946       // our reasonable largeish default packet size.
3947       if (stub_max_size > reasonable_largeish_default) {
3948         stub_max_size = reasonable_largeish_default;
3949       }
3950 
3951       // Memory packet have other overheads too like Maddr,size:#NN Instead of
3952       // calculating the bytes taken by size and addr every time, we take a
3953       // maximum guess here.
3954       if (stub_max_size > 70)
3955         stub_max_size -= 32 + 32 + 6;
3956       else {
3957         // In unlikely scenario that max packet size is less then 70, we will
3958         // hope that data being written is small enough to fit.
3959         Log *log(GetLog(GDBRLog::Comm | GDBRLog::Memory));
3960         if (log)
3961           log->Warning("Packet size is too small. "
3962                        "LLDB may face problems while writing memory");
3963       }
3964 
3965       m_max_memory_size = stub_max_size;
3966     } else {
3967       m_max_memory_size = conservative_default;
3968     }
3969   }
3970 }
3971 
3972 void ProcessGDBRemote::SetUserSpecifiedMaxMemoryTransferSize(
3973     uint64_t user_specified_max) {
3974   if (user_specified_max != 0) {
3975     GetMaxMemorySize();
3976 
3977     if (m_remote_stub_max_memory_size != 0) {
3978       if (m_remote_stub_max_memory_size < user_specified_max) {
3979         m_max_memory_size = m_remote_stub_max_memory_size; // user specified a
3980                                                            // packet size too
3981                                                            // big, go as big
3982         // as the remote stub says we can go.
3983       } else {
3984         m_max_memory_size = user_specified_max; // user's packet size is good
3985       }
3986     } else {
3987       m_max_memory_size =
3988           user_specified_max; // user's packet size is probably fine
3989     }
3990   }
3991 }
3992 
3993 bool ProcessGDBRemote::GetModuleSpec(const FileSpec &module_file_spec,
3994                                      const ArchSpec &arch,
3995                                      ModuleSpec &module_spec) {
3996   Log *log = GetLog(LLDBLog::Platform);
3997 
3998   const ModuleCacheKey key(module_file_spec.GetPath(),
3999                            arch.GetTriple().getTriple());
4000   auto cached = m_cached_module_specs.find(key);
4001   if (cached != m_cached_module_specs.end()) {
4002     module_spec = cached->second;
4003     return bool(module_spec);
4004   }
4005 
4006   if (!m_gdb_comm.GetModuleInfo(module_file_spec, arch, module_spec)) {
4007     LLDB_LOGF(log, "ProcessGDBRemote::%s - failed to get module info for %s:%s",
4008               __FUNCTION__, module_file_spec.GetPath().c_str(),
4009               arch.GetTriple().getTriple().c_str());
4010     return false;
4011   }
4012 
4013   if (log) {
4014     StreamString stream;
4015     module_spec.Dump(stream);
4016     LLDB_LOGF(log, "ProcessGDBRemote::%s - got module info for (%s:%s) : %s",
4017               __FUNCTION__, module_file_spec.GetPath().c_str(),
4018               arch.GetTriple().getTriple().c_str(), stream.GetData());
4019   }
4020 
4021   m_cached_module_specs[key] = module_spec;
4022   return true;
4023 }
4024 
4025 void ProcessGDBRemote::PrefetchModuleSpecs(
4026     llvm::ArrayRef<FileSpec> module_file_specs, const llvm::Triple &triple) {
4027   auto module_specs = m_gdb_comm.GetModulesInfo(module_file_specs, triple);
4028   if (module_specs) {
4029     for (const FileSpec &spec : module_file_specs)
4030       m_cached_module_specs[ModuleCacheKey(spec.GetPath(),
4031                                            triple.getTriple())] = ModuleSpec();
4032     for (const ModuleSpec &spec : *module_specs)
4033       m_cached_module_specs[ModuleCacheKey(spec.GetFileSpec().GetPath(),
4034                                            triple.getTriple())] = spec;
4035   }
4036 }
4037 
4038 llvm::VersionTuple ProcessGDBRemote::GetHostOSVersion() {
4039   return m_gdb_comm.GetOSVersion();
4040 }
4041 
4042 llvm::VersionTuple ProcessGDBRemote::GetHostMacCatalystVersion() {
4043   return m_gdb_comm.GetMacCatalystVersion();
4044 }
4045 
4046 namespace {
4047 
4048 typedef std::vector<std::string> stringVec;
4049 
4050 typedef std::vector<struct GdbServerRegisterInfo> GDBServerRegisterVec;
4051 struct RegisterSetInfo {
4052   ConstString name;
4053 };
4054 
4055 typedef std::map<uint32_t, RegisterSetInfo> RegisterSetMap;
4056 
4057 struct GdbServerTargetInfo {
4058   std::string arch;
4059   std::string osabi;
4060   stringVec includes;
4061   RegisterSetMap reg_set_map;
4062 };
4063 
4064 static std::vector<RegisterFlags::Field> ParseFlagsFields(XMLNode flags_node,
4065                                                           unsigned size) {
4066   Log *log(GetLog(GDBRLog::Process));
4067   const unsigned max_start_bit = size * 8 - 1;
4068 
4069   // Process the fields of this set of flags.
4070   std::vector<RegisterFlags::Field> fields;
4071   flags_node.ForEachChildElementWithName("field", [&fields, max_start_bit,
4072                                                    &log](const XMLNode
4073                                                              &field_node) {
4074     std::optional<llvm::StringRef> name;
4075     std::optional<unsigned> start;
4076     std::optional<unsigned> end;
4077 
4078     field_node.ForEachAttribute([&name, &start, &end, max_start_bit,
4079                                  &log](const llvm::StringRef &attr_name,
4080                                        const llvm::StringRef &attr_value) {
4081       // Note that XML in general requires that each of these attributes only
4082       // appears once, so we don't have to handle that here.
4083       if (attr_name == "name") {
4084         LLDB_LOG(log,
4085                  "ProcessGDBRemote::ParseFlags Found field node name \"{0}\"",
4086                  attr_value.data());
4087         name = attr_value;
4088       } else if (attr_name == "start") {
4089         unsigned parsed_start = 0;
4090         if (llvm::to_integer(attr_value, parsed_start)) {
4091           if (parsed_start > max_start_bit) {
4092             LLDB_LOG(
4093                 log,
4094                 "ProcessGDBRemote::ParseFlags Invalid start {0} in field node, "
4095                 "cannot be > {1}",
4096                 parsed_start, max_start_bit);
4097           } else
4098             start = parsed_start;
4099         } else {
4100           LLDB_LOG(log,
4101                    "ProcessGDBRemote::ParseFlags Invalid start \"{0}\" in "
4102                    "field node",
4103                    attr_value.data());
4104         }
4105       } else if (attr_name == "end") {
4106         unsigned parsed_end = 0;
4107         if (llvm::to_integer(attr_value, parsed_end))
4108           if (parsed_end > max_start_bit) {
4109             LLDB_LOG(
4110                 log,
4111                 "ProcessGDBRemote::ParseFlags Invalid end {0} in field node, "
4112                 "cannot be > {1}",
4113                 parsed_end, max_start_bit);
4114           } else
4115             end = parsed_end;
4116         else {
4117           LLDB_LOG(
4118               log,
4119               "ProcessGDBRemote::ParseFlags Invalid end \"{0}\" in field node",
4120               attr_value.data());
4121         }
4122       } else if (attr_name == "type") {
4123         // Type is a known attribute but we do not currently use it and it is
4124         // not required.
4125       } else {
4126         LLDB_LOG(log,
4127                  "ProcessGDBRemote::ParseFlags Ignoring unknown attribute "
4128                  "\"{0}\" in field node",
4129                  attr_name.data());
4130       }
4131 
4132       return true; // Walk all attributes of the field.
4133     });
4134 
4135     if (name && start && end) {
4136       if (*start > *end) {
4137         LLDB_LOG(log,
4138                  "ProcessGDBRemote::ParseFlags Start {0} > end {1} in field "
4139                  "\"{2}\", ignoring",
4140                  *start, *end, name->data());
4141       } else {
4142         fields.push_back(RegisterFlags::Field(name->str(), *start, *end));
4143       }
4144     }
4145 
4146     return true; // Iterate all "field" nodes.
4147   });
4148   return fields;
4149 }
4150 
4151 void ParseFlags(
4152     XMLNode feature_node,
4153     llvm::StringMap<std::unique_ptr<RegisterFlags>> &registers_flags_types) {
4154   Log *log(GetLog(GDBRLog::Process));
4155 
4156   feature_node.ForEachChildElementWithName(
4157       "flags",
4158       [&log, &registers_flags_types](const XMLNode &flags_node) -> bool {
4159         LLDB_LOG(log, "ProcessGDBRemote::ParseFlags Found flags node \"{0}\"",
4160                  flags_node.GetAttributeValue("id").c_str());
4161 
4162         std::optional<llvm::StringRef> id;
4163         std::optional<unsigned> size;
4164         flags_node.ForEachAttribute(
4165             [&id, &size, &log](const llvm::StringRef &name,
4166                                const llvm::StringRef &value) {
4167               if (name == "id") {
4168                 id = value;
4169               } else if (name == "size") {
4170                 unsigned parsed_size = 0;
4171                 if (llvm::to_integer(value, parsed_size))
4172                   size = parsed_size;
4173                 else {
4174                   LLDB_LOG(log,
4175                            "ProcessGDBRemote::ParseFlags Invalid size \"{0}\" "
4176                            "in flags node",
4177                            value.data());
4178                 }
4179               } else {
4180                 LLDB_LOG(log,
4181                          "ProcessGDBRemote::ParseFlags Ignoring unknown "
4182                          "attribute \"{0}\" in flags node",
4183                          name.data());
4184               }
4185               return true; // Walk all attributes.
4186             });
4187 
4188         if (id && size) {
4189           // Process the fields of this set of flags.
4190           std::vector<RegisterFlags::Field> fields =
4191               ParseFlagsFields(flags_node, *size);
4192           if (fields.size()) {
4193             // Sort so that the fields with the MSBs are first.
4194             std::sort(fields.rbegin(), fields.rend());
4195             std::vector<RegisterFlags::Field>::const_iterator overlap =
4196                 std::adjacent_find(fields.begin(), fields.end(),
4197                                    [](const RegisterFlags::Field &lhs,
4198                                       const RegisterFlags::Field &rhs) {
4199                                      return lhs.Overlaps(rhs);
4200                                    });
4201 
4202             // If no fields overlap, use them.
4203             if (overlap == fields.end()) {
4204               if (registers_flags_types.contains(*id)) {
4205                 // In theory you could define some flag set, use it with a
4206                 // register then redefine it. We do not know if anyone does
4207                 // that, or what they would expect to happen in that case.
4208                 //
4209                 // LLDB chooses to take the first definition and ignore the rest
4210                 // as waiting until everything has been processed is more
4211                 // expensive and difficult. This means that pointers to flag
4212                 // sets in the register info remain valid if later the flag set
4213                 // is redefined. If we allowed redefinitions, LLDB would crash
4214                 // when you tried to print a register that used the original
4215                 // definition.
4216                 LLDB_LOG(
4217                     log,
4218                     "ProcessGDBRemote::ParseFlags Definition of flags "
4219                     "\"{0}\" shadows "
4220                     "previous definition, using original definition instead.",
4221                     id->data());
4222               } else {
4223                 registers_flags_types.insert_or_assign(
4224                     *id, std::make_unique<RegisterFlags>(id->str(), *size,
4225                                                          std::move(fields)));
4226               }
4227             } else {
4228               // If any fields overlap, ignore the whole set of flags.
4229               std::vector<RegisterFlags::Field>::const_iterator next =
4230                   std::next(overlap);
4231               LLDB_LOG(
4232                   log,
4233                   "ProcessGDBRemote::ParseFlags Ignoring flags because fields "
4234                   "{0} (start: {1} end: {2}) and {3} (start: {4} end: {5}) "
4235                   "overlap.",
4236                   overlap->GetName().c_str(), overlap->GetStart(),
4237                   overlap->GetEnd(), next->GetName().c_str(), next->GetStart(),
4238                   next->GetEnd());
4239             }
4240           } else {
4241             LLDB_LOG(
4242                 log,
4243                 "ProcessGDBRemote::ParseFlags Ignoring definition of flags "
4244                 "\"{0}\" because it contains no fields.",
4245                 id->data());
4246           }
4247         }
4248 
4249         return true; // Keep iterating through all "flags" elements.
4250       });
4251 }
4252 
4253 bool ParseRegisters(
4254     XMLNode feature_node, GdbServerTargetInfo &target_info,
4255     std::vector<DynamicRegisterInfo::Register> &registers,
4256     llvm::StringMap<std::unique_ptr<RegisterFlags>> &registers_flags_types) {
4257   if (!feature_node)
4258     return false;
4259 
4260   Log *log(GetLog(GDBRLog::Process));
4261 
4262   ParseFlags(feature_node, registers_flags_types);
4263   for (const auto &flags : registers_flags_types)
4264     flags.second->log(log);
4265 
4266   feature_node.ForEachChildElementWithName(
4267       "reg",
4268       [&target_info, &registers, &registers_flags_types,
4269        log](const XMLNode &reg_node) -> bool {
4270         std::string gdb_group;
4271         std::string gdb_type;
4272         DynamicRegisterInfo::Register reg_info;
4273         bool encoding_set = false;
4274         bool format_set = false;
4275 
4276         // FIXME: we're silently ignoring invalid data here
4277         reg_node.ForEachAttribute([&target_info, &gdb_group, &gdb_type,
4278                                    &encoding_set, &format_set, &reg_info,
4279                                    log](const llvm::StringRef &name,
4280                                         const llvm::StringRef &value) -> bool {
4281           if (name == "name") {
4282             reg_info.name.SetString(value);
4283           } else if (name == "bitsize") {
4284             if (llvm::to_integer(value, reg_info.byte_size))
4285               reg_info.byte_size =
4286                   llvm::divideCeil(reg_info.byte_size, CHAR_BIT);
4287           } else if (name == "type") {
4288             gdb_type = value.str();
4289           } else if (name == "group") {
4290             gdb_group = value.str();
4291           } else if (name == "regnum") {
4292             llvm::to_integer(value, reg_info.regnum_remote);
4293           } else if (name == "offset") {
4294             llvm::to_integer(value, reg_info.byte_offset);
4295           } else if (name == "altname") {
4296             reg_info.alt_name.SetString(value);
4297           } else if (name == "encoding") {
4298             encoding_set = true;
4299             reg_info.encoding = Args::StringToEncoding(value, eEncodingUint);
4300           } else if (name == "format") {
4301             format_set = true;
4302             if (!OptionArgParser::ToFormat(value.data(), reg_info.format,
4303                                            nullptr)
4304                      .Success())
4305               reg_info.format =
4306                   llvm::StringSwitch<lldb::Format>(value)
4307                       .Case("vector-sint8", eFormatVectorOfSInt8)
4308                       .Case("vector-uint8", eFormatVectorOfUInt8)
4309                       .Case("vector-sint16", eFormatVectorOfSInt16)
4310                       .Case("vector-uint16", eFormatVectorOfUInt16)
4311                       .Case("vector-sint32", eFormatVectorOfSInt32)
4312                       .Case("vector-uint32", eFormatVectorOfUInt32)
4313                       .Case("vector-float32", eFormatVectorOfFloat32)
4314                       .Case("vector-uint64", eFormatVectorOfUInt64)
4315                       .Case("vector-uint128", eFormatVectorOfUInt128)
4316                       .Default(eFormatInvalid);
4317           } else if (name == "group_id") {
4318             uint32_t set_id = UINT32_MAX;
4319             llvm::to_integer(value, set_id);
4320             RegisterSetMap::const_iterator pos =
4321                 target_info.reg_set_map.find(set_id);
4322             if (pos != target_info.reg_set_map.end())
4323               reg_info.set_name = pos->second.name;
4324           } else if (name == "gcc_regnum" || name == "ehframe_regnum") {
4325             llvm::to_integer(value, reg_info.regnum_ehframe);
4326           } else if (name == "dwarf_regnum") {
4327             llvm::to_integer(value, reg_info.regnum_dwarf);
4328           } else if (name == "generic") {
4329             reg_info.regnum_generic = Args::StringToGenericRegister(value);
4330           } else if (name == "value_regnums") {
4331             SplitCommaSeparatedRegisterNumberString(value, reg_info.value_regs,
4332                                                     0);
4333           } else if (name == "invalidate_regnums") {
4334             SplitCommaSeparatedRegisterNumberString(
4335                 value, reg_info.invalidate_regs, 0);
4336           } else {
4337             LLDB_LOGF(log,
4338                       "ProcessGDBRemote::ParseRegisters unhandled reg "
4339                       "attribute %s = %s",
4340                       name.data(), value.data());
4341           }
4342           return true; // Keep iterating through all attributes
4343         });
4344 
4345         if (!gdb_type.empty()) {
4346           // gdb_type could reference some flags type defined in XML.
4347           llvm::StringMap<std::unique_ptr<RegisterFlags>>::iterator it =
4348               registers_flags_types.find(gdb_type);
4349           if (it != registers_flags_types.end()) {
4350             auto flags_type = it->second.get();
4351             if (reg_info.byte_size == flags_type->GetSize())
4352               reg_info.flags_type = flags_type;
4353             else
4354               LLDB_LOGF(log,
4355                         "ProcessGDBRemote::ParseRegisters Size of register "
4356                         "flags %s (%d bytes) for "
4357                         "register %s does not match the register size (%d "
4358                         "bytes). Ignoring this set of flags.",
4359                         flags_type->GetID().c_str(), flags_type->GetSize(),
4360                         reg_info.name.AsCString(), reg_info.byte_size);
4361           }
4362 
4363           // There's a slim chance that the gdb_type name is both a flags type
4364           // and a simple type. Just in case, look for that too (setting both
4365           // does no harm).
4366           if (!gdb_type.empty() && !(encoding_set || format_set)) {
4367             if (llvm::StringRef(gdb_type).startswith("int")) {
4368               reg_info.format = eFormatHex;
4369               reg_info.encoding = eEncodingUint;
4370             } else if (gdb_type == "data_ptr" || gdb_type == "code_ptr") {
4371               reg_info.format = eFormatAddressInfo;
4372               reg_info.encoding = eEncodingUint;
4373             } else if (gdb_type == "float") {
4374               reg_info.format = eFormatFloat;
4375               reg_info.encoding = eEncodingIEEE754;
4376             } else if (gdb_type == "aarch64v" ||
4377                        llvm::StringRef(gdb_type).startswith("vec") ||
4378                        gdb_type == "i387_ext" || gdb_type == "uint128") {
4379               // lldb doesn't handle 128-bit uints correctly (for ymm*h), so
4380               // treat them as vector (similarly to xmm/ymm)
4381               reg_info.format = eFormatVectorOfUInt8;
4382               reg_info.encoding = eEncodingVector;
4383             } else {
4384               LLDB_LOGF(
4385                   log,
4386                   "ProcessGDBRemote::ParseRegisters Could not determine lldb"
4387                   "format and encoding for gdb type %s",
4388                   gdb_type.c_str());
4389             }
4390           }
4391         }
4392 
4393         // Only update the register set name if we didn't get a "reg_set"
4394         // attribute. "set_name" will be empty if we didn't have a "reg_set"
4395         // attribute.
4396         if (!reg_info.set_name) {
4397           if (!gdb_group.empty()) {
4398             reg_info.set_name.SetCString(gdb_group.c_str());
4399           } else {
4400             // If no register group name provided anywhere,
4401             // we'll create a 'general' register set
4402             reg_info.set_name.SetCString("general");
4403           }
4404         }
4405 
4406         if (reg_info.byte_size == 0) {
4407           LLDB_LOGF(log,
4408                     "ProcessGDBRemote::%s Skipping zero bitsize register %s",
4409                     __FUNCTION__, reg_info.name.AsCString());
4410         } else
4411           registers.push_back(reg_info);
4412 
4413         return true; // Keep iterating through all "reg" elements
4414       });
4415   return true;
4416 }
4417 
4418 } // namespace
4419 
4420 // This method fetches a register description feature xml file from
4421 // the remote stub and adds registers/register groupsets/architecture
4422 // information to the current process.  It will call itself recursively
4423 // for nested register definition files.  It returns true if it was able
4424 // to fetch and parse an xml file.
4425 bool ProcessGDBRemote::GetGDBServerRegisterInfoXMLAndProcess(
4426     ArchSpec &arch_to_use, std::string xml_filename,
4427     std::vector<DynamicRegisterInfo::Register> &registers) {
4428   // request the target xml file
4429   llvm::Expected<std::string> raw = m_gdb_comm.ReadExtFeature("features", xml_filename);
4430   if (errorToBool(raw.takeError()))
4431     return false;
4432 
4433   XMLDocument xml_document;
4434 
4435   if (xml_document.ParseMemory(raw->c_str(), raw->size(),
4436                                xml_filename.c_str())) {
4437     GdbServerTargetInfo target_info;
4438     std::vector<XMLNode> feature_nodes;
4439 
4440     // The top level feature XML file will start with a <target> tag.
4441     XMLNode target_node = xml_document.GetRootElement("target");
4442     if (target_node) {
4443       target_node.ForEachChildElement([&target_info, &feature_nodes](
4444                                           const XMLNode &node) -> bool {
4445         llvm::StringRef name = node.GetName();
4446         if (name == "architecture") {
4447           node.GetElementText(target_info.arch);
4448         } else if (name == "osabi") {
4449           node.GetElementText(target_info.osabi);
4450         } else if (name == "xi:include" || name == "include") {
4451           std::string href = node.GetAttributeValue("href");
4452           if (!href.empty())
4453             target_info.includes.push_back(href);
4454         } else if (name == "feature") {
4455           feature_nodes.push_back(node);
4456         } else if (name == "groups") {
4457           node.ForEachChildElementWithName(
4458               "group", [&target_info](const XMLNode &node) -> bool {
4459                 uint32_t set_id = UINT32_MAX;
4460                 RegisterSetInfo set_info;
4461 
4462                 node.ForEachAttribute(
4463                     [&set_id, &set_info](const llvm::StringRef &name,
4464                                          const llvm::StringRef &value) -> bool {
4465                       // FIXME: we're silently ignoring invalid data here
4466                       if (name == "id")
4467                         llvm::to_integer(value, set_id);
4468                       if (name == "name")
4469                         set_info.name = ConstString(value);
4470                       return true; // Keep iterating through all attributes
4471                     });
4472 
4473                 if (set_id != UINT32_MAX)
4474                   target_info.reg_set_map[set_id] = set_info;
4475                 return true; // Keep iterating through all "group" elements
4476               });
4477         }
4478         return true; // Keep iterating through all children of the target_node
4479       });
4480     } else {
4481       // In an included XML feature file, we're already "inside" the <target>
4482       // tag of the initial XML file; this included file will likely only have
4483       // a <feature> tag.  Need to check for any more included files in this
4484       // <feature> element.
4485       XMLNode feature_node = xml_document.GetRootElement("feature");
4486       if (feature_node) {
4487         feature_nodes.push_back(feature_node);
4488         feature_node.ForEachChildElement([&target_info](
4489                                         const XMLNode &node) -> bool {
4490           llvm::StringRef name = node.GetName();
4491           if (name == "xi:include" || name == "include") {
4492             std::string href = node.GetAttributeValue("href");
4493             if (!href.empty())
4494               target_info.includes.push_back(href);
4495             }
4496             return true;
4497           });
4498       }
4499     }
4500 
4501     // gdbserver does not implement the LLDB packets used to determine host
4502     // or process architecture.  If that is the case, attempt to use
4503     // the <architecture/> field from target.xml, e.g.:
4504     //
4505     //   <architecture>i386:x86-64</architecture> (seen from VMWare ESXi)
4506     //   <architecture>arm</architecture> (seen from Segger JLink on unspecified
4507     //   arm board)
4508     if (!arch_to_use.IsValid() && !target_info.arch.empty()) {
4509       // We don't have any information about vendor or OS.
4510       arch_to_use.SetTriple(llvm::StringSwitch<std::string>(target_info.arch)
4511                                 .Case("i386:x86-64", "x86_64")
4512                                 .Default(target_info.arch) +
4513                             "--");
4514 
4515       if (arch_to_use.IsValid())
4516         GetTarget().MergeArchitecture(arch_to_use);
4517     }
4518 
4519     if (arch_to_use.IsValid()) {
4520       for (auto &feature_node : feature_nodes) {
4521         ParseRegisters(feature_node, target_info, registers,
4522                        m_registers_flags_types);
4523       }
4524 
4525       for (const auto &include : target_info.includes) {
4526         GetGDBServerRegisterInfoXMLAndProcess(arch_to_use, include,
4527                                               registers);
4528       }
4529     }
4530   } else {
4531     return false;
4532   }
4533   return true;
4534 }
4535 
4536 void ProcessGDBRemote::AddRemoteRegisters(
4537     std::vector<DynamicRegisterInfo::Register> &registers,
4538     const ArchSpec &arch_to_use) {
4539   std::map<uint32_t, uint32_t> remote_to_local_map;
4540   uint32_t remote_regnum = 0;
4541   for (auto it : llvm::enumerate(registers)) {
4542     DynamicRegisterInfo::Register &remote_reg_info = it.value();
4543 
4544     // Assign successive remote regnums if missing.
4545     if (remote_reg_info.regnum_remote == LLDB_INVALID_REGNUM)
4546       remote_reg_info.regnum_remote = remote_regnum;
4547 
4548     // Create a mapping from remote to local regnos.
4549     remote_to_local_map[remote_reg_info.regnum_remote] = it.index();
4550 
4551     remote_regnum = remote_reg_info.regnum_remote + 1;
4552   }
4553 
4554   for (DynamicRegisterInfo::Register &remote_reg_info : registers) {
4555     auto proc_to_lldb = [&remote_to_local_map](uint32_t process_regnum) {
4556       auto lldb_regit = remote_to_local_map.find(process_regnum);
4557       return lldb_regit != remote_to_local_map.end() ? lldb_regit->second
4558                                                      : LLDB_INVALID_REGNUM;
4559     };
4560 
4561     llvm::transform(remote_reg_info.value_regs,
4562                     remote_reg_info.value_regs.begin(), proc_to_lldb);
4563     llvm::transform(remote_reg_info.invalidate_regs,
4564                     remote_reg_info.invalidate_regs.begin(), proc_to_lldb);
4565   }
4566 
4567   // Don't use Process::GetABI, this code gets called from DidAttach, and
4568   // in that context we haven't set the Target's architecture yet, so the
4569   // ABI is also potentially incorrect.
4570   if (ABISP abi_sp = ABI::FindPlugin(shared_from_this(), arch_to_use))
4571     abi_sp->AugmentRegisterInfo(registers);
4572 
4573   m_register_info_sp->SetRegisterInfo(std::move(registers), arch_to_use);
4574 }
4575 
4576 // query the target of gdb-remote for extended target information returns
4577 // true on success (got register definitions), false on failure (did not).
4578 bool ProcessGDBRemote::GetGDBServerRegisterInfo(ArchSpec &arch_to_use) {
4579   // Make sure LLDB has an XML parser it can use first
4580   if (!XMLDocument::XMLEnabled())
4581     return false;
4582 
4583   // check that we have extended feature read support
4584   if (!m_gdb_comm.GetQXferFeaturesReadSupported())
4585     return false;
4586 
4587   // This holds register flags information for the whole of target.xml.
4588   // target.xml may include further documents that
4589   // GetGDBServerRegisterInfoXMLAndProcess will recurse to fetch and process.
4590   // That's why we clear the cache here, and not in
4591   // GetGDBServerRegisterInfoXMLAndProcess. To prevent it being cleared on every
4592   // include read.
4593   m_registers_flags_types.clear();
4594   std::vector<DynamicRegisterInfo::Register> registers;
4595   if (GetGDBServerRegisterInfoXMLAndProcess(arch_to_use, "target.xml",
4596                                             registers))
4597     AddRemoteRegisters(registers, arch_to_use);
4598 
4599   return m_register_info_sp->GetNumRegisters() > 0;
4600 }
4601 
4602 llvm::Expected<LoadedModuleInfoList> ProcessGDBRemote::GetLoadedModuleList() {
4603   // Make sure LLDB has an XML parser it can use first
4604   if (!XMLDocument::XMLEnabled())
4605     return llvm::createStringError(llvm::inconvertibleErrorCode(),
4606                                    "XML parsing not available");
4607 
4608   Log *log = GetLog(LLDBLog::Process);
4609   LLDB_LOGF(log, "ProcessGDBRemote::%s", __FUNCTION__);
4610 
4611   LoadedModuleInfoList list;
4612   GDBRemoteCommunicationClient &comm = m_gdb_comm;
4613   bool can_use_svr4 = GetGlobalPluginProperties().GetUseSVR4();
4614 
4615   // check that we have extended feature read support
4616   if (can_use_svr4 && comm.GetQXferLibrariesSVR4ReadSupported()) {
4617     // request the loaded library list
4618     llvm::Expected<std::string> raw = comm.ReadExtFeature("libraries-svr4", "");
4619     if (!raw)
4620       return raw.takeError();
4621 
4622     // parse the xml file in memory
4623     LLDB_LOGF(log, "parsing: %s", raw->c_str());
4624     XMLDocument doc;
4625 
4626     if (!doc.ParseMemory(raw->c_str(), raw->size(), "noname.xml"))
4627       return llvm::createStringError(llvm::inconvertibleErrorCode(),
4628                                      "Error reading noname.xml");
4629 
4630     XMLNode root_element = doc.GetRootElement("library-list-svr4");
4631     if (!root_element)
4632       return llvm::createStringError(
4633           llvm::inconvertibleErrorCode(),
4634           "Error finding library-list-svr4 xml element");
4635 
4636     // main link map structure
4637     std::string main_lm = root_element.GetAttributeValue("main-lm");
4638     // FIXME: we're silently ignoring invalid data here
4639     if (!main_lm.empty())
4640       llvm::to_integer(main_lm, list.m_link_map);
4641 
4642     root_element.ForEachChildElementWithName(
4643         "library", [log, &list](const XMLNode &library) -> bool {
4644           LoadedModuleInfoList::LoadedModuleInfo module;
4645 
4646           // FIXME: we're silently ignoring invalid data here
4647           library.ForEachAttribute(
4648               [&module](const llvm::StringRef &name,
4649                         const llvm::StringRef &value) -> bool {
4650                 uint64_t uint_value = LLDB_INVALID_ADDRESS;
4651                 if (name == "name")
4652                   module.set_name(value.str());
4653                 else if (name == "lm") {
4654                   // the address of the link_map struct.
4655                   llvm::to_integer(value, uint_value);
4656                   module.set_link_map(uint_value);
4657                 } else if (name == "l_addr") {
4658                   // the displacement as read from the field 'l_addr' of the
4659                   // link_map struct.
4660                   llvm::to_integer(value, uint_value);
4661                   module.set_base(uint_value);
4662                   // base address is always a displacement, not an absolute
4663                   // value.
4664                   module.set_base_is_offset(true);
4665                 } else if (name == "l_ld") {
4666                   // the memory address of the libraries PT_DYNAMIC section.
4667                   llvm::to_integer(value, uint_value);
4668                   module.set_dynamic(uint_value);
4669                 }
4670 
4671                 return true; // Keep iterating over all properties of "library"
4672               });
4673 
4674           if (log) {
4675             std::string name;
4676             lldb::addr_t lm = 0, base = 0, ld = 0;
4677             bool base_is_offset;
4678 
4679             module.get_name(name);
4680             module.get_link_map(lm);
4681             module.get_base(base);
4682             module.get_base_is_offset(base_is_offset);
4683             module.get_dynamic(ld);
4684 
4685             LLDB_LOGF(log,
4686                       "found (link_map:0x%08" PRIx64 ", base:0x%08" PRIx64
4687                       "[%s], ld:0x%08" PRIx64 ", name:'%s')",
4688                       lm, base, (base_is_offset ? "offset" : "absolute"), ld,
4689                       name.c_str());
4690           }
4691 
4692           list.add(module);
4693           return true; // Keep iterating over all "library" elements in the root
4694                        // node
4695         });
4696 
4697     if (log)
4698       LLDB_LOGF(log, "found %" PRId32 " modules in total",
4699                 (int)list.m_list.size());
4700     return list;
4701   } else if (comm.GetQXferLibrariesReadSupported()) {
4702     // request the loaded library list
4703     llvm::Expected<std::string> raw = comm.ReadExtFeature("libraries", "");
4704 
4705     if (!raw)
4706       return raw.takeError();
4707 
4708     LLDB_LOGF(log, "parsing: %s", raw->c_str());
4709     XMLDocument doc;
4710 
4711     if (!doc.ParseMemory(raw->c_str(), raw->size(), "noname.xml"))
4712       return llvm::createStringError(llvm::inconvertibleErrorCode(),
4713                                      "Error reading noname.xml");
4714 
4715     XMLNode root_element = doc.GetRootElement("library-list");
4716     if (!root_element)
4717       return llvm::createStringError(llvm::inconvertibleErrorCode(),
4718                                      "Error finding library-list xml element");
4719 
4720     // FIXME: we're silently ignoring invalid data here
4721     root_element.ForEachChildElementWithName(
4722         "library", [log, &list](const XMLNode &library) -> bool {
4723           LoadedModuleInfoList::LoadedModuleInfo module;
4724 
4725           std::string name = library.GetAttributeValue("name");
4726           module.set_name(name);
4727 
4728           // The base address of a given library will be the address of its
4729           // first section. Most remotes send only one section for Windows
4730           // targets for example.
4731           const XMLNode &section =
4732               library.FindFirstChildElementWithName("section");
4733           std::string address = section.GetAttributeValue("address");
4734           uint64_t address_value = LLDB_INVALID_ADDRESS;
4735           llvm::to_integer(address, address_value);
4736           module.set_base(address_value);
4737           // These addresses are absolute values.
4738           module.set_base_is_offset(false);
4739 
4740           if (log) {
4741             std::string name;
4742             lldb::addr_t base = 0;
4743             bool base_is_offset;
4744             module.get_name(name);
4745             module.get_base(base);
4746             module.get_base_is_offset(base_is_offset);
4747 
4748             LLDB_LOGF(log, "found (base:0x%08" PRIx64 "[%s], name:'%s')", base,
4749                       (base_is_offset ? "offset" : "absolute"), name.c_str());
4750           }
4751 
4752           list.add(module);
4753           return true; // Keep iterating over all "library" elements in the root
4754                        // node
4755         });
4756 
4757     if (log)
4758       LLDB_LOGF(log, "found %" PRId32 " modules in total",
4759                 (int)list.m_list.size());
4760     return list;
4761   } else {
4762     return llvm::createStringError(llvm::inconvertibleErrorCode(),
4763                                    "Remote libraries not supported");
4764   }
4765 }
4766 
4767 lldb::ModuleSP ProcessGDBRemote::LoadModuleAtAddress(const FileSpec &file,
4768                                                      lldb::addr_t link_map,
4769                                                      lldb::addr_t base_addr,
4770                                                      bool value_is_offset) {
4771   DynamicLoader *loader = GetDynamicLoader();
4772   if (!loader)
4773     return nullptr;
4774 
4775   return loader->LoadModuleAtAddress(file, link_map, base_addr,
4776                                      value_is_offset);
4777 }
4778 
4779 llvm::Error ProcessGDBRemote::LoadModules() {
4780   using lldb_private::process_gdb_remote::ProcessGDBRemote;
4781 
4782   // request a list of loaded libraries from GDBServer
4783   llvm::Expected<LoadedModuleInfoList> module_list = GetLoadedModuleList();
4784   if (!module_list)
4785     return module_list.takeError();
4786 
4787   // get a list of all the modules
4788   ModuleList new_modules;
4789 
4790   for (LoadedModuleInfoList::LoadedModuleInfo &modInfo : module_list->m_list) {
4791     std::string mod_name;
4792     lldb::addr_t mod_base;
4793     lldb::addr_t link_map;
4794     bool mod_base_is_offset;
4795 
4796     bool valid = true;
4797     valid &= modInfo.get_name(mod_name);
4798     valid &= modInfo.get_base(mod_base);
4799     valid &= modInfo.get_base_is_offset(mod_base_is_offset);
4800     if (!valid)
4801       continue;
4802 
4803     if (!modInfo.get_link_map(link_map))
4804       link_map = LLDB_INVALID_ADDRESS;
4805 
4806     FileSpec file(mod_name);
4807     FileSystem::Instance().Resolve(file);
4808     lldb::ModuleSP module_sp =
4809         LoadModuleAtAddress(file, link_map, mod_base, mod_base_is_offset);
4810 
4811     if (module_sp.get())
4812       new_modules.Append(module_sp);
4813   }
4814 
4815   if (new_modules.GetSize() > 0) {
4816     ModuleList removed_modules;
4817     Target &target = GetTarget();
4818     ModuleList &loaded_modules = m_process->GetTarget().GetImages();
4819 
4820     for (size_t i = 0; i < loaded_modules.GetSize(); ++i) {
4821       const lldb::ModuleSP loaded_module = loaded_modules.GetModuleAtIndex(i);
4822 
4823       bool found = false;
4824       for (size_t j = 0; j < new_modules.GetSize(); ++j) {
4825         if (new_modules.GetModuleAtIndex(j).get() == loaded_module.get())
4826           found = true;
4827       }
4828 
4829       // The main executable will never be included in libraries-svr4, don't
4830       // remove it
4831       if (!found &&
4832           loaded_module.get() != target.GetExecutableModulePointer()) {
4833         removed_modules.Append(loaded_module);
4834       }
4835     }
4836 
4837     loaded_modules.Remove(removed_modules);
4838     m_process->GetTarget().ModulesDidUnload(removed_modules, false);
4839 
4840     new_modules.ForEach([&target](const lldb::ModuleSP module_sp) -> bool {
4841       lldb_private::ObjectFile *obj = module_sp->GetObjectFile();
4842       if (!obj)
4843         return true;
4844 
4845       if (obj->GetType() != ObjectFile::Type::eTypeExecutable)
4846         return true;
4847 
4848       lldb::ModuleSP module_copy_sp = module_sp;
4849       target.SetExecutableModule(module_copy_sp, eLoadDependentsNo);
4850       return false;
4851     });
4852 
4853     loaded_modules.AppendIfNeeded(new_modules);
4854     m_process->GetTarget().ModulesDidLoad(new_modules);
4855   }
4856 
4857   return llvm::ErrorSuccess();
4858 }
4859 
4860 Status ProcessGDBRemote::GetFileLoadAddress(const FileSpec &file,
4861                                             bool &is_loaded,
4862                                             lldb::addr_t &load_addr) {
4863   is_loaded = false;
4864   load_addr = LLDB_INVALID_ADDRESS;
4865 
4866   std::string file_path = file.GetPath(false);
4867   if (file_path.empty())
4868     return Status("Empty file name specified");
4869 
4870   StreamString packet;
4871   packet.PutCString("qFileLoadAddress:");
4872   packet.PutStringAsRawHex8(file_path);
4873 
4874   StringExtractorGDBRemote response;
4875   if (m_gdb_comm.SendPacketAndWaitForResponse(packet.GetString(), response) !=
4876       GDBRemoteCommunication::PacketResult::Success)
4877     return Status("Sending qFileLoadAddress packet failed");
4878 
4879   if (response.IsErrorResponse()) {
4880     if (response.GetError() == 1) {
4881       // The file is not loaded into the inferior
4882       is_loaded = false;
4883       load_addr = LLDB_INVALID_ADDRESS;
4884       return Status();
4885     }
4886 
4887     return Status(
4888         "Fetching file load address from remote server returned an error");
4889   }
4890 
4891   if (response.IsNormalResponse()) {
4892     is_loaded = true;
4893     load_addr = response.GetHexMaxU64(false, LLDB_INVALID_ADDRESS);
4894     return Status();
4895   }
4896 
4897   return Status(
4898       "Unknown error happened during sending the load address packet");
4899 }
4900 
4901 void ProcessGDBRemote::ModulesDidLoad(ModuleList &module_list) {
4902   // We must call the lldb_private::Process::ModulesDidLoad () first before we
4903   // do anything
4904   Process::ModulesDidLoad(module_list);
4905 
4906   // After loading shared libraries, we can ask our remote GDB server if it
4907   // needs any symbols.
4908   m_gdb_comm.ServeSymbolLookups(this);
4909 }
4910 
4911 void ProcessGDBRemote::HandleAsyncStdout(llvm::StringRef out) {
4912   AppendSTDOUT(out.data(), out.size());
4913 }
4914 
4915 static const char *end_delimiter = "--end--;";
4916 static const int end_delimiter_len = 8;
4917 
4918 void ProcessGDBRemote::HandleAsyncMisc(llvm::StringRef data) {
4919   std::string input = data.str(); // '1' to move beyond 'A'
4920   if (m_partial_profile_data.length() > 0) {
4921     m_partial_profile_data.append(input);
4922     input = m_partial_profile_data;
4923     m_partial_profile_data.clear();
4924   }
4925 
4926   size_t found, pos = 0, len = input.length();
4927   while ((found = input.find(end_delimiter, pos)) != std::string::npos) {
4928     StringExtractorGDBRemote profileDataExtractor(
4929         input.substr(pos, found).c_str());
4930     std::string profile_data =
4931         HarmonizeThreadIdsForProfileData(profileDataExtractor);
4932     BroadcastAsyncProfileData(profile_data);
4933 
4934     pos = found + end_delimiter_len;
4935   }
4936 
4937   if (pos < len) {
4938     // Last incomplete chunk.
4939     m_partial_profile_data = input.substr(pos);
4940   }
4941 }
4942 
4943 std::string ProcessGDBRemote::HarmonizeThreadIdsForProfileData(
4944     StringExtractorGDBRemote &profileDataExtractor) {
4945   std::map<uint64_t, uint32_t> new_thread_id_to_used_usec_map;
4946   std::string output;
4947   llvm::raw_string_ostream output_stream(output);
4948   llvm::StringRef name, value;
4949 
4950   // Going to assuming thread_used_usec comes first, else bail out.
4951   while (profileDataExtractor.GetNameColonValue(name, value)) {
4952     if (name.compare("thread_used_id") == 0) {
4953       StringExtractor threadIDHexExtractor(value);
4954       uint64_t thread_id = threadIDHexExtractor.GetHexMaxU64(false, 0);
4955 
4956       bool has_used_usec = false;
4957       uint32_t curr_used_usec = 0;
4958       llvm::StringRef usec_name, usec_value;
4959       uint32_t input_file_pos = profileDataExtractor.GetFilePos();
4960       if (profileDataExtractor.GetNameColonValue(usec_name, usec_value)) {
4961         if (usec_name.equals("thread_used_usec")) {
4962           has_used_usec = true;
4963           usec_value.getAsInteger(0, curr_used_usec);
4964         } else {
4965           // We didn't find what we want, it is probably an older version. Bail
4966           // out.
4967           profileDataExtractor.SetFilePos(input_file_pos);
4968         }
4969       }
4970 
4971       if (has_used_usec) {
4972         uint32_t prev_used_usec = 0;
4973         std::map<uint64_t, uint32_t>::iterator iterator =
4974             m_thread_id_to_used_usec_map.find(thread_id);
4975         if (iterator != m_thread_id_to_used_usec_map.end()) {
4976           prev_used_usec = m_thread_id_to_used_usec_map[thread_id];
4977         }
4978 
4979         uint32_t real_used_usec = curr_used_usec - prev_used_usec;
4980         // A good first time record is one that runs for at least 0.25 sec
4981         bool good_first_time =
4982             (prev_used_usec == 0) && (real_used_usec > 250000);
4983         bool good_subsequent_time =
4984             (prev_used_usec > 0) &&
4985             ((real_used_usec > 0) || (HasAssignedIndexIDToThread(thread_id)));
4986 
4987         if (good_first_time || good_subsequent_time) {
4988           // We try to avoid doing too many index id reservation, resulting in
4989           // fast increase of index ids.
4990 
4991           output_stream << name << ":";
4992           int32_t index_id = AssignIndexIDToThread(thread_id);
4993           output_stream << index_id << ";";
4994 
4995           output_stream << usec_name << ":" << usec_value << ";";
4996         } else {
4997           // Skip past 'thread_used_name'.
4998           llvm::StringRef local_name, local_value;
4999           profileDataExtractor.GetNameColonValue(local_name, local_value);
5000         }
5001 
5002         // Store current time as previous time so that they can be compared
5003         // later.
5004         new_thread_id_to_used_usec_map[thread_id] = curr_used_usec;
5005       } else {
5006         // Bail out and use old string.
5007         output_stream << name << ":" << value << ";";
5008       }
5009     } else {
5010       output_stream << name << ":" << value << ";";
5011     }
5012   }
5013   output_stream << end_delimiter;
5014   m_thread_id_to_used_usec_map = new_thread_id_to_used_usec_map;
5015 
5016   return output_stream.str();
5017 }
5018 
5019 void ProcessGDBRemote::HandleStopReply() {
5020   if (GetStopID() != 0)
5021     return;
5022 
5023   if (GetID() == LLDB_INVALID_PROCESS_ID) {
5024     lldb::pid_t pid = m_gdb_comm.GetCurrentProcessID();
5025     if (pid != LLDB_INVALID_PROCESS_ID)
5026       SetID(pid);
5027   }
5028   BuildDynamicRegisterInfo(true);
5029 }
5030 
5031 llvm::Expected<bool> ProcessGDBRemote::SaveCore(llvm::StringRef outfile) {
5032   if (!m_gdb_comm.GetSaveCoreSupported())
5033     return false;
5034 
5035   StreamString packet;
5036   packet.PutCString("qSaveCore;path-hint:");
5037   packet.PutStringAsRawHex8(outfile);
5038 
5039   StringExtractorGDBRemote response;
5040   if (m_gdb_comm.SendPacketAndWaitForResponse(packet.GetString(), response) ==
5041       GDBRemoteCommunication::PacketResult::Success) {
5042     // TODO: grab error message from the packet?  StringExtractor seems to
5043     // be missing a method for that
5044     if (response.IsErrorResponse())
5045       return llvm::createStringError(
5046           llvm::inconvertibleErrorCode(),
5047           llvm::formatv("qSaveCore returned an error"));
5048 
5049     std::string path;
5050 
5051     // process the response
5052     for (auto x : llvm::split(response.GetStringRef(), ';')) {
5053       if (x.consume_front("core-path:"))
5054         StringExtractor(x).GetHexByteString(path);
5055     }
5056 
5057     // verify that we've gotten what we need
5058     if (path.empty())
5059       return llvm::createStringError(llvm::inconvertibleErrorCode(),
5060                                      "qSaveCore returned no core path");
5061 
5062     // now transfer the core file
5063     FileSpec remote_core{llvm::StringRef(path)};
5064     Platform &platform = *GetTarget().GetPlatform();
5065     Status error = platform.GetFile(remote_core, FileSpec(outfile));
5066 
5067     if (platform.IsRemote()) {
5068       // NB: we unlink the file on error too
5069       platform.Unlink(remote_core);
5070       if (error.Fail())
5071         return error.ToError();
5072     }
5073 
5074     return true;
5075   }
5076 
5077   return llvm::createStringError(llvm::inconvertibleErrorCode(),
5078                                  "Unable to send qSaveCore");
5079 }
5080 
5081 static const char *const s_async_json_packet_prefix = "JSON-async:";
5082 
5083 static StructuredData::ObjectSP
5084 ParseStructuredDataPacket(llvm::StringRef packet) {
5085   Log *log = GetLog(GDBRLog::Process);
5086 
5087   if (!packet.consume_front(s_async_json_packet_prefix)) {
5088     if (log) {
5089       LLDB_LOGF(
5090           log,
5091           "GDBRemoteCommunicationClientBase::%s() received $J packet "
5092           "but was not a StructuredData packet: packet starts with "
5093           "%s",
5094           __FUNCTION__,
5095           packet.slice(0, strlen(s_async_json_packet_prefix)).str().c_str());
5096     }
5097     return StructuredData::ObjectSP();
5098   }
5099 
5100   // This is an asynchronous JSON packet, destined for a StructuredDataPlugin.
5101   StructuredData::ObjectSP json_sp = StructuredData::ParseJSON(packet);
5102   if (log) {
5103     if (json_sp) {
5104       StreamString json_str;
5105       json_sp->Dump(json_str, true);
5106       json_str.Flush();
5107       LLDB_LOGF(log,
5108                 "ProcessGDBRemote::%s() "
5109                 "received Async StructuredData packet: %s",
5110                 __FUNCTION__, json_str.GetData());
5111     } else {
5112       LLDB_LOGF(log,
5113                 "ProcessGDBRemote::%s"
5114                 "() received StructuredData packet:"
5115                 " parse failure",
5116                 __FUNCTION__);
5117     }
5118   }
5119   return json_sp;
5120 }
5121 
5122 void ProcessGDBRemote::HandleAsyncStructuredDataPacket(llvm::StringRef data) {
5123   auto structured_data_sp = ParseStructuredDataPacket(data);
5124   if (structured_data_sp)
5125     RouteAsyncStructuredData(structured_data_sp);
5126 }
5127 
5128 class CommandObjectProcessGDBRemoteSpeedTest : public CommandObjectParsed {
5129 public:
5130   CommandObjectProcessGDBRemoteSpeedTest(CommandInterpreter &interpreter)
5131       : CommandObjectParsed(interpreter, "process plugin packet speed-test",
5132                             "Tests packet speeds of various sizes to determine "
5133                             "the performance characteristics of the GDB remote "
5134                             "connection. ",
5135                             nullptr),
5136         m_option_group(),
5137         m_num_packets(LLDB_OPT_SET_1, false, "count", 'c', 0, eArgTypeCount,
5138                       "The number of packets to send of each varying size "
5139                       "(default is 1000).",
5140                       1000),
5141         m_max_send(LLDB_OPT_SET_1, false, "max-send", 's', 0, eArgTypeCount,
5142                    "The maximum number of bytes to send in a packet. Sizes "
5143                    "increase in powers of 2 while the size is less than or "
5144                    "equal to this option value. (default 1024).",
5145                    1024),
5146         m_max_recv(LLDB_OPT_SET_1, false, "max-receive", 'r', 0, eArgTypeCount,
5147                    "The maximum number of bytes to receive in a packet. Sizes "
5148                    "increase in powers of 2 while the size is less than or "
5149                    "equal to this option value. (default 1024).",
5150                    1024),
5151         m_json(LLDB_OPT_SET_1, false, "json", 'j',
5152                "Print the output as JSON data for easy parsing.", false, true) {
5153     m_option_group.Append(&m_num_packets, LLDB_OPT_SET_ALL, LLDB_OPT_SET_1);
5154     m_option_group.Append(&m_max_send, LLDB_OPT_SET_ALL, LLDB_OPT_SET_1);
5155     m_option_group.Append(&m_max_recv, LLDB_OPT_SET_ALL, LLDB_OPT_SET_1);
5156     m_option_group.Append(&m_json, LLDB_OPT_SET_ALL, LLDB_OPT_SET_1);
5157     m_option_group.Finalize();
5158   }
5159 
5160   ~CommandObjectProcessGDBRemoteSpeedTest() override = default;
5161 
5162   Options *GetOptions() override { return &m_option_group; }
5163 
5164   bool DoExecute(Args &command, CommandReturnObject &result) override {
5165     const size_t argc = command.GetArgumentCount();
5166     if (argc == 0) {
5167       ProcessGDBRemote *process =
5168           (ProcessGDBRemote *)m_interpreter.GetExecutionContext()
5169               .GetProcessPtr();
5170       if (process) {
5171         StreamSP output_stream_sp(
5172             m_interpreter.GetDebugger().GetAsyncOutputStream());
5173         result.SetImmediateOutputStream(output_stream_sp);
5174 
5175         const uint32_t num_packets =
5176             (uint32_t)m_num_packets.GetOptionValue().GetCurrentValue();
5177         const uint64_t max_send = m_max_send.GetOptionValue().GetCurrentValue();
5178         const uint64_t max_recv = m_max_recv.GetOptionValue().GetCurrentValue();
5179         const bool json = m_json.GetOptionValue().GetCurrentValue();
5180         const uint64_t k_recv_amount =
5181             4 * 1024 * 1024; // Receive amount in bytes
5182         process->GetGDBRemote().TestPacketSpeed(
5183             num_packets, max_send, max_recv, k_recv_amount, json,
5184             output_stream_sp ? *output_stream_sp : result.GetOutputStream());
5185         result.SetStatus(eReturnStatusSuccessFinishResult);
5186         return true;
5187       }
5188     } else {
5189       result.AppendErrorWithFormat("'%s' takes no arguments",
5190                                    m_cmd_name.c_str());
5191     }
5192     result.SetStatus(eReturnStatusFailed);
5193     return false;
5194   }
5195 
5196 protected:
5197   OptionGroupOptions m_option_group;
5198   OptionGroupUInt64 m_num_packets;
5199   OptionGroupUInt64 m_max_send;
5200   OptionGroupUInt64 m_max_recv;
5201   OptionGroupBoolean m_json;
5202 };
5203 
5204 class CommandObjectProcessGDBRemotePacketHistory : public CommandObjectParsed {
5205 private:
5206 public:
5207   CommandObjectProcessGDBRemotePacketHistory(CommandInterpreter &interpreter)
5208       : CommandObjectParsed(interpreter, "process plugin packet history",
5209                             "Dumps the packet history buffer. ", nullptr) {}
5210 
5211   ~CommandObjectProcessGDBRemotePacketHistory() override = default;
5212 
5213   bool DoExecute(Args &command, CommandReturnObject &result) override {
5214     ProcessGDBRemote *process =
5215         (ProcessGDBRemote *)m_interpreter.GetExecutionContext().GetProcessPtr();
5216     if (process) {
5217       process->GetGDBRemote().DumpHistory(result.GetOutputStream());
5218       result.SetStatus(eReturnStatusSuccessFinishResult);
5219       return true;
5220     }
5221     result.SetStatus(eReturnStatusFailed);
5222     return false;
5223   }
5224 };
5225 
5226 class CommandObjectProcessGDBRemotePacketXferSize : public CommandObjectParsed {
5227 private:
5228 public:
5229   CommandObjectProcessGDBRemotePacketXferSize(CommandInterpreter &interpreter)
5230       : CommandObjectParsed(
5231             interpreter, "process plugin packet xfer-size",
5232             "Maximum size that lldb will try to read/write one one chunk.",
5233             nullptr) {
5234     CommandArgumentData max_arg{eArgTypeUnsignedInteger, eArgRepeatPlain};
5235     m_arguments.push_back({max_arg});
5236   }
5237 
5238   ~CommandObjectProcessGDBRemotePacketXferSize() override = default;
5239 
5240   bool DoExecute(Args &command, CommandReturnObject &result) override {
5241     const size_t argc = command.GetArgumentCount();
5242     if (argc == 0) {
5243       result.AppendErrorWithFormat("'%s' takes an argument to specify the max "
5244                                    "amount to be transferred when "
5245                                    "reading/writing",
5246                                    m_cmd_name.c_str());
5247       return false;
5248     }
5249 
5250     ProcessGDBRemote *process =
5251         (ProcessGDBRemote *)m_interpreter.GetExecutionContext().GetProcessPtr();
5252     if (process) {
5253       const char *packet_size = command.GetArgumentAtIndex(0);
5254       errno = 0;
5255       uint64_t user_specified_max = strtoul(packet_size, nullptr, 10);
5256       if (errno == 0 && user_specified_max != 0) {
5257         process->SetUserSpecifiedMaxMemoryTransferSize(user_specified_max);
5258         result.SetStatus(eReturnStatusSuccessFinishResult);
5259         return true;
5260       }
5261     }
5262     result.SetStatus(eReturnStatusFailed);
5263     return false;
5264   }
5265 };
5266 
5267 class CommandObjectProcessGDBRemotePacketSend : public CommandObjectParsed {
5268 private:
5269 public:
5270   CommandObjectProcessGDBRemotePacketSend(CommandInterpreter &interpreter)
5271       : CommandObjectParsed(interpreter, "process plugin packet send",
5272                             "Send a custom packet through the GDB remote "
5273                             "protocol and print the answer. "
5274                             "The packet header and footer will automatically "
5275                             "be added to the packet prior to sending and "
5276                             "stripped from the result.",
5277                             nullptr) {
5278     CommandArgumentData packet_arg{eArgTypeNone, eArgRepeatStar};
5279     m_arguments.push_back({packet_arg});
5280   }
5281 
5282   ~CommandObjectProcessGDBRemotePacketSend() override = default;
5283 
5284   bool DoExecute(Args &command, CommandReturnObject &result) override {
5285     const size_t argc = command.GetArgumentCount();
5286     if (argc == 0) {
5287       result.AppendErrorWithFormat(
5288           "'%s' takes a one or more packet content arguments",
5289           m_cmd_name.c_str());
5290       return false;
5291     }
5292 
5293     ProcessGDBRemote *process =
5294         (ProcessGDBRemote *)m_interpreter.GetExecutionContext().GetProcessPtr();
5295     if (process) {
5296       for (size_t i = 0; i < argc; ++i) {
5297         const char *packet_cstr = command.GetArgumentAtIndex(0);
5298         StringExtractorGDBRemote response;
5299         process->GetGDBRemote().SendPacketAndWaitForResponse(
5300             packet_cstr, response, process->GetInterruptTimeout());
5301         result.SetStatus(eReturnStatusSuccessFinishResult);
5302         Stream &output_strm = result.GetOutputStream();
5303         output_strm.Printf("  packet: %s\n", packet_cstr);
5304         std::string response_str = std::string(response.GetStringRef());
5305 
5306         if (strstr(packet_cstr, "qGetProfileData") != nullptr) {
5307           response_str = process->HarmonizeThreadIdsForProfileData(response);
5308         }
5309 
5310         if (response_str.empty())
5311           output_strm.PutCString("response: \nerror: UNIMPLEMENTED\n");
5312         else
5313           output_strm.Printf("response: %s\n", response.GetStringRef().data());
5314       }
5315     }
5316     return true;
5317   }
5318 };
5319 
5320 class CommandObjectProcessGDBRemotePacketMonitor : public CommandObjectRaw {
5321 private:
5322 public:
5323   CommandObjectProcessGDBRemotePacketMonitor(CommandInterpreter &interpreter)
5324       : CommandObjectRaw(interpreter, "process plugin packet monitor",
5325                          "Send a qRcmd packet through the GDB remote protocol "
5326                          "and print the response."
5327                          "The argument passed to this command will be hex "
5328                          "encoded into a valid 'qRcmd' packet, sent and the "
5329                          "response will be printed.") {}
5330 
5331   ~CommandObjectProcessGDBRemotePacketMonitor() override = default;
5332 
5333   bool DoExecute(llvm::StringRef command,
5334                  CommandReturnObject &result) override {
5335     if (command.empty()) {
5336       result.AppendErrorWithFormat("'%s' takes a command string argument",
5337                                    m_cmd_name.c_str());
5338       return false;
5339     }
5340 
5341     ProcessGDBRemote *process =
5342         (ProcessGDBRemote *)m_interpreter.GetExecutionContext().GetProcessPtr();
5343     if (process) {
5344       StreamString packet;
5345       packet.PutCString("qRcmd,");
5346       packet.PutBytesAsRawHex8(command.data(), command.size());
5347 
5348       StringExtractorGDBRemote response;
5349       Stream &output_strm = result.GetOutputStream();
5350       process->GetGDBRemote().SendPacketAndReceiveResponseWithOutputSupport(
5351           packet.GetString(), response, process->GetInterruptTimeout(),
5352           [&output_strm](llvm::StringRef output) { output_strm << output; });
5353       result.SetStatus(eReturnStatusSuccessFinishResult);
5354       output_strm.Printf("  packet: %s\n", packet.GetData());
5355       const std::string &response_str = std::string(response.GetStringRef());
5356 
5357       if (response_str.empty())
5358         output_strm.PutCString("response: \nerror: UNIMPLEMENTED\n");
5359       else
5360         output_strm.Printf("response: %s\n", response.GetStringRef().data());
5361     }
5362     return true;
5363   }
5364 };
5365 
5366 class CommandObjectProcessGDBRemotePacket : public CommandObjectMultiword {
5367 private:
5368 public:
5369   CommandObjectProcessGDBRemotePacket(CommandInterpreter &interpreter)
5370       : CommandObjectMultiword(interpreter, "process plugin packet",
5371                                "Commands that deal with GDB remote packets.",
5372                                nullptr) {
5373     LoadSubCommand(
5374         "history",
5375         CommandObjectSP(
5376             new CommandObjectProcessGDBRemotePacketHistory(interpreter)));
5377     LoadSubCommand(
5378         "send", CommandObjectSP(
5379                     new CommandObjectProcessGDBRemotePacketSend(interpreter)));
5380     LoadSubCommand(
5381         "monitor",
5382         CommandObjectSP(
5383             new CommandObjectProcessGDBRemotePacketMonitor(interpreter)));
5384     LoadSubCommand(
5385         "xfer-size",
5386         CommandObjectSP(
5387             new CommandObjectProcessGDBRemotePacketXferSize(interpreter)));
5388     LoadSubCommand("speed-test",
5389                    CommandObjectSP(new CommandObjectProcessGDBRemoteSpeedTest(
5390                        interpreter)));
5391   }
5392 
5393   ~CommandObjectProcessGDBRemotePacket() override = default;
5394 };
5395 
5396 class CommandObjectMultiwordProcessGDBRemote : public CommandObjectMultiword {
5397 public:
5398   CommandObjectMultiwordProcessGDBRemote(CommandInterpreter &interpreter)
5399       : CommandObjectMultiword(
5400             interpreter, "process plugin",
5401             "Commands for operating on a ProcessGDBRemote process.",
5402             "process plugin <subcommand> [<subcommand-options>]") {
5403     LoadSubCommand(
5404         "packet",
5405         CommandObjectSP(new CommandObjectProcessGDBRemotePacket(interpreter)));
5406   }
5407 
5408   ~CommandObjectMultiwordProcessGDBRemote() override = default;
5409 };
5410 
5411 CommandObject *ProcessGDBRemote::GetPluginCommandObject() {
5412   if (!m_command_sp)
5413     m_command_sp = std::make_shared<CommandObjectMultiwordProcessGDBRemote>(
5414         GetTarget().GetDebugger().GetCommandInterpreter());
5415   return m_command_sp.get();
5416 }
5417 
5418 void ProcessGDBRemote::DidForkSwitchSoftwareBreakpoints(bool enable) {
5419   GetBreakpointSiteList().ForEach([this, enable](BreakpointSite *bp_site) {
5420     if (bp_site->IsEnabled() &&
5421         (bp_site->GetType() == BreakpointSite::eSoftware ||
5422          bp_site->GetType() == BreakpointSite::eExternal)) {
5423       m_gdb_comm.SendGDBStoppointTypePacket(
5424           eBreakpointSoftware, enable, bp_site->GetLoadAddress(),
5425           GetSoftwareBreakpointTrapOpcode(bp_site), GetInterruptTimeout());
5426     }
5427   });
5428 }
5429 
5430 void ProcessGDBRemote::DidForkSwitchHardwareTraps(bool enable) {
5431   if (m_gdb_comm.SupportsGDBStoppointPacket(eBreakpointHardware)) {
5432     GetBreakpointSiteList().ForEach([this, enable](BreakpointSite *bp_site) {
5433       if (bp_site->IsEnabled() &&
5434           bp_site->GetType() == BreakpointSite::eHardware) {
5435         m_gdb_comm.SendGDBStoppointTypePacket(
5436             eBreakpointHardware, enable, bp_site->GetLoadAddress(),
5437             GetSoftwareBreakpointTrapOpcode(bp_site), GetInterruptTimeout());
5438       }
5439     });
5440   }
5441 
5442   WatchpointList &wps = GetTarget().GetWatchpointList();
5443   size_t wp_count = wps.GetSize();
5444   for (size_t i = 0; i < wp_count; ++i) {
5445     WatchpointSP wp = wps.GetByIndex(i);
5446     if (wp->IsEnabled()) {
5447       GDBStoppointType type = GetGDBStoppointType(wp.get());
5448       m_gdb_comm.SendGDBStoppointTypePacket(type, enable, wp->GetLoadAddress(),
5449                                             wp->GetByteSize(),
5450                                             GetInterruptTimeout());
5451     }
5452   }
5453 }
5454 
5455 void ProcessGDBRemote::DidFork(lldb::pid_t child_pid, lldb::tid_t child_tid) {
5456   Log *log = GetLog(GDBRLog::Process);
5457 
5458   lldb::pid_t parent_pid = m_gdb_comm.GetCurrentProcessID();
5459   // Any valid TID will suffice, thread-relevant actions will set a proper TID
5460   // anyway.
5461   lldb::tid_t parent_tid = m_thread_ids.front();
5462 
5463   lldb::pid_t follow_pid, detach_pid;
5464   lldb::tid_t follow_tid, detach_tid;
5465 
5466   switch (GetFollowForkMode()) {
5467   case eFollowParent:
5468     follow_pid = parent_pid;
5469     follow_tid = parent_tid;
5470     detach_pid = child_pid;
5471     detach_tid = child_tid;
5472     break;
5473   case eFollowChild:
5474     follow_pid = child_pid;
5475     follow_tid = child_tid;
5476     detach_pid = parent_pid;
5477     detach_tid = parent_tid;
5478     break;
5479   }
5480 
5481   // Switch to the process that is going to be detached.
5482   if (!m_gdb_comm.SetCurrentThread(detach_tid, detach_pid)) {
5483     LLDB_LOG(log, "ProcessGDBRemote::DidFork() unable to set pid/tid");
5484     return;
5485   }
5486 
5487   // Disable all software breakpoints in the forked process.
5488   if (m_gdb_comm.SupportsGDBStoppointPacket(eBreakpointSoftware))
5489     DidForkSwitchSoftwareBreakpoints(false);
5490 
5491   // Remove hardware breakpoints / watchpoints from parent process if we're
5492   // following child.
5493   if (GetFollowForkMode() == eFollowChild)
5494     DidForkSwitchHardwareTraps(false);
5495 
5496   // Switch to the process that is going to be followed
5497   if (!m_gdb_comm.SetCurrentThread(follow_tid, follow_pid) ||
5498       !m_gdb_comm.SetCurrentThreadForRun(follow_tid, follow_pid)) {
5499     LLDB_LOG(log, "ProcessGDBRemote::DidFork() unable to reset pid/tid");
5500     return;
5501   }
5502 
5503   LLDB_LOG(log, "Detaching process {0}", detach_pid);
5504   Status error = m_gdb_comm.Detach(false, detach_pid);
5505   if (error.Fail()) {
5506     LLDB_LOG(log, "ProcessGDBRemote::DidFork() detach packet send failed: {0}",
5507              error.AsCString() ? error.AsCString() : "<unknown error>");
5508     return;
5509   }
5510 
5511   // Hardware breakpoints/watchpoints are not inherited implicitly,
5512   // so we need to readd them if we're following child.
5513   if (GetFollowForkMode() == eFollowChild) {
5514     DidForkSwitchHardwareTraps(true);
5515     // Update our PID
5516     SetID(child_pid);
5517   }
5518 }
5519 
5520 void ProcessGDBRemote::DidVFork(lldb::pid_t child_pid, lldb::tid_t child_tid) {
5521   Log *log = GetLog(GDBRLog::Process);
5522 
5523   assert(!m_vfork_in_progress);
5524   m_vfork_in_progress = true;
5525 
5526   // Disable all software breakpoints for the duration of vfork.
5527   if (m_gdb_comm.SupportsGDBStoppointPacket(eBreakpointSoftware))
5528     DidForkSwitchSoftwareBreakpoints(false);
5529 
5530   lldb::pid_t detach_pid;
5531   lldb::tid_t detach_tid;
5532 
5533   switch (GetFollowForkMode()) {
5534   case eFollowParent:
5535     detach_pid = child_pid;
5536     detach_tid = child_tid;
5537     break;
5538   case eFollowChild:
5539     detach_pid = m_gdb_comm.GetCurrentProcessID();
5540     // Any valid TID will suffice, thread-relevant actions will set a proper TID
5541     // anyway.
5542     detach_tid = m_thread_ids.front();
5543 
5544     // Switch to the parent process before detaching it.
5545     if (!m_gdb_comm.SetCurrentThread(detach_tid, detach_pid)) {
5546       LLDB_LOG(log, "ProcessGDBRemote::DidFork() unable to set pid/tid");
5547       return;
5548     }
5549 
5550     // Remove hardware breakpoints / watchpoints from the parent process.
5551     DidForkSwitchHardwareTraps(false);
5552 
5553     // Switch to the child process.
5554     if (!m_gdb_comm.SetCurrentThread(child_tid, child_pid) ||
5555         !m_gdb_comm.SetCurrentThreadForRun(child_tid, child_pid)) {
5556       LLDB_LOG(log, "ProcessGDBRemote::DidFork() unable to reset pid/tid");
5557       return;
5558     }
5559     break;
5560   }
5561 
5562   LLDB_LOG(log, "Detaching process {0}", detach_pid);
5563   Status error = m_gdb_comm.Detach(false, detach_pid);
5564   if (error.Fail()) {
5565       LLDB_LOG(log,
5566                "ProcessGDBRemote::DidFork() detach packet send failed: {0}",
5567                 error.AsCString() ? error.AsCString() : "<unknown error>");
5568       return;
5569   }
5570 
5571   if (GetFollowForkMode() == eFollowChild) {
5572     // Update our PID
5573     SetID(child_pid);
5574   }
5575 }
5576 
5577 void ProcessGDBRemote::DidVForkDone() {
5578   assert(m_vfork_in_progress);
5579   m_vfork_in_progress = false;
5580 
5581   // Reenable all software breakpoints that were enabled before vfork.
5582   if (m_gdb_comm.SupportsGDBStoppointPacket(eBreakpointSoftware))
5583     DidForkSwitchSoftwareBreakpoints(true);
5584 }
5585 
5586 void ProcessGDBRemote::DidExec() {
5587   // If we are following children, vfork is finished by exec (rather than
5588   // vforkdone that is submitted for parent).
5589   if (GetFollowForkMode() == eFollowChild)
5590     m_vfork_in_progress = false;
5591   Process::DidExec();
5592 }
5593