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