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