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