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