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