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