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