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