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