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