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