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