xref: /llvm-project/lldb/source/Plugins/Process/gdb-remote/ProcessGDBRemote.cpp (revision 8561ad9296b70b5a2af1574a1576090520d62a7c)
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::DoUpdateThreadList(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       RegisterContextSP gdb_reg_ctx_sp(gdb_thread->GetRegisterContext());
1752 
1753       gdb_reg_ctx_sp->InvalidateIfNeeded(true);
1754 
1755       auto iter = std::find(m_thread_ids.begin(), m_thread_ids.end(), tid);
1756       if (iter != m_thread_ids.end()) {
1757         SetThreadPc(thread_sp, iter - m_thread_ids.begin());
1758       }
1759 
1760       for (const auto &pair : expedited_register_map) {
1761         StringExtractor reg_value_extractor(pair.second);
1762         DataBufferSP buffer_sp(new DataBufferHeap(
1763             reg_value_extractor.GetStringRef().size() / 2, 0));
1764         reg_value_extractor.GetHexBytes(buffer_sp->GetData(), '\xcc');
1765         uint32_t lldb_regnum =
1766             gdb_reg_ctx_sp->ConvertRegisterKindToRegisterNumber(
1767                 eRegisterKindProcessPlugin, pair.first);
1768         gdb_thread->PrivateSetRegisterValue(lldb_regnum, buffer_sp->GetData());
1769       }
1770 
1771       // AArch64 SVE specific code below calls AArch64SVEReconfigure to update
1772       // SVE register sizes and offsets if value of VG register has changed
1773       // since last stop.
1774       const ArchSpec &arch = GetTarget().GetArchitecture();
1775       if (arch.IsValid() && arch.GetTriple().isAArch64()) {
1776         GDBRemoteRegisterContext *reg_ctx_sp =
1777             static_cast<GDBRemoteRegisterContext *>(
1778                 gdb_thread->GetRegisterContext().get());
1779 
1780         if (reg_ctx_sp)
1781           reg_ctx_sp->AArch64SVEReconfigure();
1782       }
1783 
1784       thread_sp->SetName(thread_name.empty() ? nullptr : thread_name.c_str());
1785 
1786       gdb_thread->SetThreadDispatchQAddr(thread_dispatch_qaddr);
1787       // Check if the GDB server was able to provide the queue name, kind and
1788       // serial number
1789       if (queue_vars_valid)
1790         gdb_thread->SetQueueInfo(std::move(queue_name), queue_kind,
1791                                  queue_serial, dispatch_queue_t,
1792                                  associated_with_dispatch_queue);
1793       else
1794         gdb_thread->ClearQueueInfo();
1795 
1796       gdb_thread->SetAssociatedWithLibdispatchQueue(
1797           associated_with_dispatch_queue);
1798 
1799       if (dispatch_queue_t != LLDB_INVALID_ADDRESS)
1800         gdb_thread->SetQueueLibdispatchQueueAddress(dispatch_queue_t);
1801 
1802       // Make sure we update our thread stop reason just once
1803       if (!thread_sp->StopInfoIsUpToDate()) {
1804         thread_sp->SetStopInfo(StopInfoSP());
1805         // If there's a memory thread backed by this thread, we need to use it
1806         // to calculate StopInfo.
1807         if (ThreadSP memory_thread_sp =
1808                 m_thread_list.GetBackingThread(thread_sp))
1809           thread_sp = memory_thread_sp;
1810 
1811         if (exc_type != 0) {
1812           const size_t exc_data_size = exc_data.size();
1813 
1814           thread_sp->SetStopInfo(
1815               StopInfoMachException::CreateStopReasonWithMachException(
1816                   *thread_sp, exc_type, exc_data_size,
1817                   exc_data_size >= 1 ? exc_data[0] : 0,
1818                   exc_data_size >= 2 ? exc_data[1] : 0,
1819                   exc_data_size >= 3 ? exc_data[2] : 0));
1820         } else {
1821           bool handled = false;
1822           bool did_exec = false;
1823           if (!reason.empty()) {
1824             if (reason == "trace") {
1825               addr_t pc = thread_sp->GetRegisterContext()->GetPC();
1826               lldb::BreakpointSiteSP bp_site_sp = thread_sp->GetProcess()
1827                                                       ->GetBreakpointSiteList()
1828                                                       .FindByAddress(pc);
1829 
1830               // If the current pc is a breakpoint site then the StopInfo
1831               // should be set to Breakpoint Otherwise, it will be set to
1832               // Trace.
1833               if (bp_site_sp &&
1834                   bp_site_sp->ValidForThisThread(thread_sp.get())) {
1835                 thread_sp->SetStopInfo(
1836                     StopInfo::CreateStopReasonWithBreakpointSiteID(
1837                         *thread_sp, bp_site_sp->GetID()));
1838               } else
1839                 thread_sp->SetStopInfo(
1840                     StopInfo::CreateStopReasonToTrace(*thread_sp));
1841               handled = true;
1842             } else if (reason == "breakpoint") {
1843               addr_t pc = thread_sp->GetRegisterContext()->GetPC();
1844               lldb::BreakpointSiteSP bp_site_sp = thread_sp->GetProcess()
1845                                                       ->GetBreakpointSiteList()
1846                                                       .FindByAddress(pc);
1847               if (bp_site_sp) {
1848                 // If the breakpoint is for this thread, then we'll report the
1849                 // hit, but if it is for another thread, we can just report no
1850                 // reason.  We don't need to worry about stepping over the
1851                 // breakpoint here, that will be taken care of when the thread
1852                 // resumes and notices that there's a breakpoint under the pc.
1853                 handled = true;
1854                 if (bp_site_sp->ValidForThisThread(thread_sp.get())) {
1855                   thread_sp->SetStopInfo(
1856                       StopInfo::CreateStopReasonWithBreakpointSiteID(
1857                           *thread_sp, bp_site_sp->GetID()));
1858                 } else {
1859                   StopInfoSP invalid_stop_info_sp;
1860                   thread_sp->SetStopInfo(invalid_stop_info_sp);
1861                 }
1862               }
1863             } else if (reason == "trap") {
1864               // Let the trap just use the standard signal stop reason below...
1865             } else if (reason == "watchpoint") {
1866               StringExtractor desc_extractor(description.c_str());
1867               addr_t wp_addr = desc_extractor.GetU64(LLDB_INVALID_ADDRESS);
1868               uint32_t wp_index = desc_extractor.GetU32(LLDB_INVALID_INDEX32);
1869               addr_t wp_hit_addr = desc_extractor.GetU64(LLDB_INVALID_ADDRESS);
1870               watch_id_t watch_id = LLDB_INVALID_WATCH_ID;
1871               if (wp_addr != LLDB_INVALID_ADDRESS) {
1872                 WatchpointSP wp_sp;
1873                 ArchSpec::Core core = GetTarget().GetArchitecture().GetCore();
1874                 if ((core >= ArchSpec::kCore_mips_first &&
1875                      core <= ArchSpec::kCore_mips_last) ||
1876                     (core >= ArchSpec::eCore_arm_generic &&
1877                      core <= ArchSpec::eCore_arm_aarch64))
1878                   wp_sp = GetTarget().GetWatchpointList().FindByAddress(
1879                       wp_hit_addr);
1880                 if (!wp_sp)
1881                   wp_sp =
1882                       GetTarget().GetWatchpointList().FindByAddress(wp_addr);
1883                 if (wp_sp) {
1884                   wp_sp->SetHardwareIndex(wp_index);
1885                   watch_id = wp_sp->GetID();
1886                 }
1887               }
1888               if (watch_id == LLDB_INVALID_WATCH_ID) {
1889                 Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(
1890                     GDBR_LOG_WATCHPOINTS));
1891                 LLDB_LOGF(log, "failed to find watchpoint");
1892               }
1893               thread_sp->SetStopInfo(StopInfo::CreateStopReasonWithWatchpointID(
1894                   *thread_sp, watch_id, wp_hit_addr));
1895               handled = true;
1896             } else if (reason == "exception") {
1897               thread_sp->SetStopInfo(StopInfo::CreateStopReasonWithException(
1898                   *thread_sp, description.c_str()));
1899               handled = true;
1900             } else if (reason == "exec") {
1901               did_exec = true;
1902               thread_sp->SetStopInfo(
1903                   StopInfo::CreateStopReasonWithExec(*thread_sp));
1904               handled = true;
1905             }
1906           } else if (!signo) {
1907             addr_t pc = thread_sp->GetRegisterContext()->GetPC();
1908             lldb::BreakpointSiteSP bp_site_sp =
1909                 thread_sp->GetProcess()->GetBreakpointSiteList().FindByAddress(
1910                     pc);
1911 
1912             // If the current pc is a breakpoint site then the StopInfo should
1913             // be set to Breakpoint even though the remote stub did not set it
1914             // as such. This can happen when the thread is involuntarily
1915             // interrupted (e.g. due to stops on other threads) just as it is
1916             // about to execute the breakpoint instruction.
1917             if (bp_site_sp && bp_site_sp->ValidForThisThread(thread_sp.get())) {
1918               thread_sp->SetStopInfo(
1919                   StopInfo::CreateStopReasonWithBreakpointSiteID(
1920                       *thread_sp, bp_site_sp->GetID()));
1921               handled = true;
1922             }
1923           }
1924 
1925           if (!handled && signo && !did_exec) {
1926             if (signo == SIGTRAP) {
1927               // Currently we are going to assume SIGTRAP means we are either
1928               // hitting a breakpoint or hardware single stepping.
1929               handled = true;
1930               addr_t pc = thread_sp->GetRegisterContext()->GetPC() +
1931                           m_breakpoint_pc_offset;
1932               lldb::BreakpointSiteSP bp_site_sp = thread_sp->GetProcess()
1933                                                       ->GetBreakpointSiteList()
1934                                                       .FindByAddress(pc);
1935 
1936               if (bp_site_sp) {
1937                 // If the breakpoint is for this thread, then we'll report the
1938                 // hit, but if it is for another thread, we can just report no
1939                 // reason.  We don't need to worry about stepping over the
1940                 // breakpoint here, that will be taken care of when the thread
1941                 // resumes and notices that there's a breakpoint under the pc.
1942                 if (bp_site_sp->ValidForThisThread(thread_sp.get())) {
1943                   if (m_breakpoint_pc_offset != 0)
1944                     thread_sp->GetRegisterContext()->SetPC(pc);
1945                   thread_sp->SetStopInfo(
1946                       StopInfo::CreateStopReasonWithBreakpointSiteID(
1947                           *thread_sp, bp_site_sp->GetID()));
1948                 } else {
1949                   StopInfoSP invalid_stop_info_sp;
1950                   thread_sp->SetStopInfo(invalid_stop_info_sp);
1951                 }
1952               } else {
1953                 // If we were stepping then assume the stop was the result of
1954                 // the trace.  If we were not stepping then report the SIGTRAP.
1955                 // FIXME: We are still missing the case where we single step
1956                 // over a trap instruction.
1957                 if (thread_sp->GetTemporaryResumeState() == eStateStepping)
1958                   thread_sp->SetStopInfo(
1959                       StopInfo::CreateStopReasonToTrace(*thread_sp));
1960                 else
1961                   thread_sp->SetStopInfo(StopInfo::CreateStopReasonWithSignal(
1962                       *thread_sp, signo, description.c_str()));
1963               }
1964             }
1965             if (!handled)
1966               thread_sp->SetStopInfo(StopInfo::CreateStopReasonWithSignal(
1967                   *thread_sp, signo, description.c_str()));
1968           }
1969 
1970           if (!description.empty()) {
1971             lldb::StopInfoSP stop_info_sp(thread_sp->GetStopInfo());
1972             if (stop_info_sp) {
1973               const char *stop_info_desc = stop_info_sp->GetDescription();
1974               if (!stop_info_desc || !stop_info_desc[0])
1975                 stop_info_sp->SetDescription(description.c_str());
1976             } else {
1977               thread_sp->SetStopInfo(StopInfo::CreateStopReasonWithException(
1978                   *thread_sp, description.c_str()));
1979             }
1980           }
1981         }
1982       }
1983     }
1984   }
1985   return thread_sp;
1986 }
1987 
1988 lldb::ThreadSP
1989 ProcessGDBRemote::SetThreadStopInfo(StructuredData::Dictionary *thread_dict) {
1990   static ConstString g_key_tid("tid");
1991   static ConstString g_key_name("name");
1992   static ConstString g_key_reason("reason");
1993   static ConstString g_key_metype("metype");
1994   static ConstString g_key_medata("medata");
1995   static ConstString g_key_qaddr("qaddr");
1996   static ConstString g_key_dispatch_queue_t("dispatch_queue_t");
1997   static ConstString g_key_associated_with_dispatch_queue(
1998       "associated_with_dispatch_queue");
1999   static ConstString g_key_queue_name("qname");
2000   static ConstString g_key_queue_kind("qkind");
2001   static ConstString g_key_queue_serial_number("qserialnum");
2002   static ConstString g_key_registers("registers");
2003   static ConstString g_key_memory("memory");
2004   static ConstString g_key_address("address");
2005   static ConstString g_key_bytes("bytes");
2006   static ConstString g_key_description("description");
2007   static ConstString g_key_signal("signal");
2008 
2009   // Stop with signal and thread info
2010   lldb::tid_t tid = LLDB_INVALID_THREAD_ID;
2011   uint8_t signo = 0;
2012   std::string value;
2013   std::string thread_name;
2014   std::string reason;
2015   std::string description;
2016   uint32_t exc_type = 0;
2017   std::vector<addr_t> exc_data;
2018   addr_t thread_dispatch_qaddr = LLDB_INVALID_ADDRESS;
2019   ExpeditedRegisterMap expedited_register_map;
2020   bool queue_vars_valid = false;
2021   addr_t dispatch_queue_t = LLDB_INVALID_ADDRESS;
2022   LazyBool associated_with_dispatch_queue = eLazyBoolCalculate;
2023   std::string queue_name;
2024   QueueKind queue_kind = eQueueKindUnknown;
2025   uint64_t queue_serial_number = 0;
2026   // Iterate through all of the thread dictionary key/value pairs from the
2027   // structured data dictionary
2028 
2029   thread_dict->ForEach([this, &tid, &expedited_register_map, &thread_name,
2030                         &signo, &reason, &description, &exc_type, &exc_data,
2031                         &thread_dispatch_qaddr, &queue_vars_valid,
2032                         &associated_with_dispatch_queue, &dispatch_queue_t,
2033                         &queue_name, &queue_kind, &queue_serial_number](
2034                            ConstString key,
2035                            StructuredData::Object *object) -> bool {
2036     if (key == g_key_tid) {
2037       // thread in big endian hex
2038       tid = object->GetIntegerValue(LLDB_INVALID_THREAD_ID);
2039     } else if (key == g_key_metype) {
2040       // exception type in big endian hex
2041       exc_type = object->GetIntegerValue(0);
2042     } else if (key == g_key_medata) {
2043       // exception data in big endian hex
2044       StructuredData::Array *array = object->GetAsArray();
2045       if (array) {
2046         array->ForEach([&exc_data](StructuredData::Object *object) -> bool {
2047           exc_data.push_back(object->GetIntegerValue());
2048           return true; // Keep iterating through all array items
2049         });
2050       }
2051     } else if (key == g_key_name) {
2052       thread_name = std::string(object->GetStringValue());
2053     } else if (key == g_key_qaddr) {
2054       thread_dispatch_qaddr = object->GetIntegerValue(LLDB_INVALID_ADDRESS);
2055     } else if (key == g_key_queue_name) {
2056       queue_vars_valid = true;
2057       queue_name = std::string(object->GetStringValue());
2058     } else if (key == g_key_queue_kind) {
2059       std::string queue_kind_str = std::string(object->GetStringValue());
2060       if (queue_kind_str == "serial") {
2061         queue_vars_valid = true;
2062         queue_kind = eQueueKindSerial;
2063       } else if (queue_kind_str == "concurrent") {
2064         queue_vars_valid = true;
2065         queue_kind = eQueueKindConcurrent;
2066       }
2067     } else if (key == g_key_queue_serial_number) {
2068       queue_serial_number = object->GetIntegerValue(0);
2069       if (queue_serial_number != 0)
2070         queue_vars_valid = true;
2071     } else if (key == g_key_dispatch_queue_t) {
2072       dispatch_queue_t = object->GetIntegerValue(0);
2073       if (dispatch_queue_t != 0 && dispatch_queue_t != LLDB_INVALID_ADDRESS)
2074         queue_vars_valid = true;
2075     } else if (key == g_key_associated_with_dispatch_queue) {
2076       queue_vars_valid = true;
2077       bool associated = object->GetBooleanValue();
2078       if (associated)
2079         associated_with_dispatch_queue = eLazyBoolYes;
2080       else
2081         associated_with_dispatch_queue = eLazyBoolNo;
2082     } else if (key == g_key_reason) {
2083       reason = std::string(object->GetStringValue());
2084     } else if (key == g_key_description) {
2085       description = std::string(object->GetStringValue());
2086     } else if (key == g_key_registers) {
2087       StructuredData::Dictionary *registers_dict = object->GetAsDictionary();
2088 
2089       if (registers_dict) {
2090         registers_dict->ForEach(
2091             [&expedited_register_map](ConstString key,
2092                                       StructuredData::Object *object) -> bool {
2093               const uint32_t reg =
2094                   StringConvert::ToUInt32(key.GetCString(), UINT32_MAX, 10);
2095               if (reg != UINT32_MAX)
2096                 expedited_register_map[reg] =
2097                     std::string(object->GetStringValue());
2098               return true; // Keep iterating through all array items
2099             });
2100       }
2101     } else if (key == g_key_memory) {
2102       StructuredData::Array *array = object->GetAsArray();
2103       if (array) {
2104         array->ForEach([this](StructuredData::Object *object) -> bool {
2105           StructuredData::Dictionary *mem_cache_dict =
2106               object->GetAsDictionary();
2107           if (mem_cache_dict) {
2108             lldb::addr_t mem_cache_addr = LLDB_INVALID_ADDRESS;
2109             if (mem_cache_dict->GetValueForKeyAsInteger<lldb::addr_t>(
2110                     "address", mem_cache_addr)) {
2111               if (mem_cache_addr != LLDB_INVALID_ADDRESS) {
2112                 llvm::StringRef str;
2113                 if (mem_cache_dict->GetValueForKeyAsString("bytes", str)) {
2114                   StringExtractor bytes(str);
2115                   bytes.SetFilePos(0);
2116 
2117                   const size_t byte_size = bytes.GetStringRef().size() / 2;
2118                   DataBufferSP data_buffer_sp(new DataBufferHeap(byte_size, 0));
2119                   const size_t bytes_copied =
2120                       bytes.GetHexBytes(data_buffer_sp->GetData(), 0);
2121                   if (bytes_copied == byte_size)
2122                     m_memory_cache.AddL1CacheData(mem_cache_addr,
2123                                                   data_buffer_sp);
2124                 }
2125               }
2126             }
2127           }
2128           return true; // Keep iterating through all array items
2129         });
2130       }
2131 
2132     } else if (key == g_key_signal)
2133       signo = object->GetIntegerValue(LLDB_INVALID_SIGNAL_NUMBER);
2134     return true; // Keep iterating through all dictionary key/value pairs
2135   });
2136 
2137   return SetThreadStopInfo(tid, expedited_register_map, signo, thread_name,
2138                            reason, description, exc_type, exc_data,
2139                            thread_dispatch_qaddr, queue_vars_valid,
2140                            associated_with_dispatch_queue, dispatch_queue_t,
2141                            queue_name, queue_kind, queue_serial_number);
2142 }
2143 
2144 StateType ProcessGDBRemote::SetThreadStopInfo(StringExtractor &stop_packet) {
2145   stop_packet.SetFilePos(0);
2146   const char stop_type = stop_packet.GetChar();
2147   switch (stop_type) {
2148   case 'T':
2149   case 'S': {
2150     // This is a bit of a hack, but is is required. If we did exec, we need to
2151     // clear our thread lists and also know to rebuild our dynamic register
2152     // info before we lookup and threads and populate the expedited register
2153     // values so we need to know this right away so we can cleanup and update
2154     // our registers.
2155     const uint32_t stop_id = GetStopID();
2156     if (stop_id == 0) {
2157       // Our first stop, make sure we have a process ID, and also make sure we
2158       // know about our registers
2159       if (GetID() == LLDB_INVALID_PROCESS_ID) {
2160         lldb::pid_t pid = m_gdb_comm.GetCurrentProcessID();
2161         if (pid != LLDB_INVALID_PROCESS_ID)
2162           SetID(pid);
2163       }
2164       BuildDynamicRegisterInfo(true);
2165     }
2166     // Stop with signal and thread info
2167     lldb::tid_t tid = LLDB_INVALID_THREAD_ID;
2168     const uint8_t signo = stop_packet.GetHexU8();
2169     llvm::StringRef key;
2170     llvm::StringRef value;
2171     std::string thread_name;
2172     std::string reason;
2173     std::string description;
2174     uint32_t exc_type = 0;
2175     std::vector<addr_t> exc_data;
2176     addr_t thread_dispatch_qaddr = LLDB_INVALID_ADDRESS;
2177     bool queue_vars_valid =
2178         false; // says if locals below that start with "queue_" are valid
2179     addr_t dispatch_queue_t = LLDB_INVALID_ADDRESS;
2180     LazyBool associated_with_dispatch_queue = eLazyBoolCalculate;
2181     std::string queue_name;
2182     QueueKind queue_kind = eQueueKindUnknown;
2183     uint64_t queue_serial_number = 0;
2184     ExpeditedRegisterMap expedited_register_map;
2185     while (stop_packet.GetNameColonValue(key, value)) {
2186       if (key.compare("metype") == 0) {
2187         // exception type in big endian hex
2188         value.getAsInteger(16, exc_type);
2189       } else if (key.compare("medata") == 0) {
2190         // exception data in big endian hex
2191         uint64_t x;
2192         value.getAsInteger(16, x);
2193         exc_data.push_back(x);
2194       } else if (key.compare("thread") == 0) {
2195         // thread in big endian hex
2196         if (value.getAsInteger(16, tid))
2197           tid = LLDB_INVALID_THREAD_ID;
2198       } else if (key.compare("threads") == 0) {
2199         std::lock_guard<std::recursive_mutex> guard(
2200             m_thread_list_real.GetMutex());
2201 
2202         m_thread_ids.clear();
2203         // A comma separated list of all threads in the current
2204         // process that includes the thread for this stop reply packet
2205         lldb::tid_t tid;
2206         while (!value.empty()) {
2207           llvm::StringRef tid_str;
2208           std::tie(tid_str, value) = value.split(',');
2209           if (tid_str.getAsInteger(16, tid))
2210             tid = LLDB_INVALID_THREAD_ID;
2211           m_thread_ids.push_back(tid);
2212         }
2213       } else if (key.compare("thread-pcs") == 0) {
2214         m_thread_pcs.clear();
2215         // A comma separated list of all threads in the current
2216         // process that includes the thread for this stop reply packet
2217         lldb::addr_t pc;
2218         while (!value.empty()) {
2219           llvm::StringRef pc_str;
2220           std::tie(pc_str, value) = value.split(',');
2221           if (pc_str.getAsInteger(16, pc))
2222             pc = LLDB_INVALID_ADDRESS;
2223           m_thread_pcs.push_back(pc);
2224         }
2225       } else if (key.compare("jstopinfo") == 0) {
2226         StringExtractor json_extractor(value);
2227         std::string json;
2228         // Now convert the HEX bytes into a string value
2229         json_extractor.GetHexByteString(json);
2230 
2231         // This JSON contains thread IDs and thread stop info for all threads.
2232         // It doesn't contain expedited registers, memory or queue info.
2233         m_jstopinfo_sp = StructuredData::ParseJSON(json);
2234       } else if (key.compare("hexname") == 0) {
2235         StringExtractor name_extractor(value);
2236         std::string name;
2237         // Now convert the HEX bytes into a string value
2238         name_extractor.GetHexByteString(thread_name);
2239       } else if (key.compare("name") == 0) {
2240         thread_name = std::string(value);
2241       } else if (key.compare("qaddr") == 0) {
2242         value.getAsInteger(16, thread_dispatch_qaddr);
2243       } else if (key.compare("dispatch_queue_t") == 0) {
2244         queue_vars_valid = true;
2245         value.getAsInteger(16, dispatch_queue_t);
2246       } else if (key.compare("qname") == 0) {
2247         queue_vars_valid = true;
2248         StringExtractor name_extractor(value);
2249         // Now convert the HEX bytes into a string value
2250         name_extractor.GetHexByteString(queue_name);
2251       } else if (key.compare("qkind") == 0) {
2252         queue_kind = llvm::StringSwitch<QueueKind>(value)
2253                          .Case("serial", eQueueKindSerial)
2254                          .Case("concurrent", eQueueKindConcurrent)
2255                          .Default(eQueueKindUnknown);
2256         queue_vars_valid = queue_kind != eQueueKindUnknown;
2257       } else if (key.compare("qserialnum") == 0) {
2258         if (!value.getAsInteger(0, queue_serial_number))
2259           queue_vars_valid = true;
2260       } else if (key.compare("reason") == 0) {
2261         reason = std::string(value);
2262       } else if (key.compare("description") == 0) {
2263         StringExtractor desc_extractor(value);
2264         // Now convert the HEX bytes into a string value
2265         desc_extractor.GetHexByteString(description);
2266       } else if (key.compare("memory") == 0) {
2267         // Expedited memory. GDB servers can choose to send back expedited
2268         // memory that can populate the L1 memory cache in the process so that
2269         // things like the frame pointer backchain can be expedited. This will
2270         // help stack backtracing be more efficient by not having to send as
2271         // many memory read requests down the remote GDB server.
2272 
2273         // Key/value pair format: memory:<addr>=<bytes>;
2274         // <addr> is a number whose base will be interpreted by the prefix:
2275         //      "0x[0-9a-fA-F]+" for hex
2276         //      "0[0-7]+" for octal
2277         //      "[1-9]+" for decimal
2278         // <bytes> is native endian ASCII hex bytes just like the register
2279         // values
2280         llvm::StringRef addr_str, bytes_str;
2281         std::tie(addr_str, bytes_str) = value.split('=');
2282         if (!addr_str.empty() && !bytes_str.empty()) {
2283           lldb::addr_t mem_cache_addr = LLDB_INVALID_ADDRESS;
2284           if (!addr_str.getAsInteger(0, mem_cache_addr)) {
2285             StringExtractor bytes(bytes_str);
2286             const size_t byte_size = bytes.GetBytesLeft() / 2;
2287             DataBufferSP data_buffer_sp(new DataBufferHeap(byte_size, 0));
2288             const size_t bytes_copied =
2289                 bytes.GetHexBytes(data_buffer_sp->GetData(), 0);
2290             if (bytes_copied == byte_size)
2291               m_memory_cache.AddL1CacheData(mem_cache_addr, data_buffer_sp);
2292           }
2293         }
2294       } else if (key.compare("watch") == 0 || key.compare("rwatch") == 0 ||
2295                  key.compare("awatch") == 0) {
2296         // Support standard GDB remote stop reply packet 'TAAwatch:addr'
2297         lldb::addr_t wp_addr = LLDB_INVALID_ADDRESS;
2298         value.getAsInteger(16, wp_addr);
2299 
2300         WatchpointSP wp_sp =
2301             GetTarget().GetWatchpointList().FindByAddress(wp_addr);
2302         uint32_t wp_index = LLDB_INVALID_INDEX32;
2303 
2304         if (wp_sp)
2305           wp_index = wp_sp->GetHardwareIndex();
2306 
2307         reason = "watchpoint";
2308         StreamString ostr;
2309         ostr.Printf("%" PRIu64 " %" PRIu32, wp_addr, wp_index);
2310         description = std::string(ostr.GetString());
2311       } else if (key.compare("library") == 0) {
2312         auto error = LoadModules();
2313         if (error) {
2314           Log *log(
2315               ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
2316           LLDB_LOG_ERROR(log, std::move(error), "Failed to load modules: {0}");
2317         }
2318       } else if (key.size() == 2 && ::isxdigit(key[0]) && ::isxdigit(key[1])) {
2319         uint32_t reg = UINT32_MAX;
2320         if (!key.getAsInteger(16, reg))
2321           expedited_register_map[reg] = std::string(std::move(value));
2322       }
2323     }
2324 
2325     if (tid == LLDB_INVALID_THREAD_ID) {
2326       // A thread id may be invalid if the response is old style 'S' packet
2327       // which does not provide the
2328       // thread information. So update the thread list and choose the first
2329       // one.
2330       UpdateThreadIDList();
2331 
2332       if (!m_thread_ids.empty()) {
2333         tid = m_thread_ids.front();
2334       }
2335     }
2336 
2337     ThreadSP thread_sp = SetThreadStopInfo(
2338         tid, expedited_register_map, signo, thread_name, reason, description,
2339         exc_type, exc_data, thread_dispatch_qaddr, queue_vars_valid,
2340         associated_with_dispatch_queue, dispatch_queue_t, queue_name,
2341         queue_kind, queue_serial_number);
2342 
2343     return eStateStopped;
2344   } break;
2345 
2346   case 'W':
2347   case 'X':
2348     // process exited
2349     return eStateExited;
2350 
2351   default:
2352     break;
2353   }
2354   return eStateInvalid;
2355 }
2356 
2357 void ProcessGDBRemote::RefreshStateAfterStop() {
2358   std::lock_guard<std::recursive_mutex> guard(m_thread_list_real.GetMutex());
2359 
2360   m_thread_ids.clear();
2361   m_thread_pcs.clear();
2362 
2363   // Set the thread stop info. It might have a "threads" key whose value is a
2364   // list of all thread IDs in the current process, so m_thread_ids might get
2365   // set.
2366   // Check to see if SetThreadStopInfo() filled in m_thread_ids?
2367   if (m_thread_ids.empty()) {
2368       // No, we need to fetch the thread list manually
2369       UpdateThreadIDList();
2370   }
2371 
2372   // We might set some stop info's so make sure the thread list is up to
2373   // date before we do that or we might overwrite what was computed here.
2374   UpdateThreadListIfNeeded();
2375 
2376   // Scope for the lock
2377   {
2378     // Lock the thread stack while we access it
2379     std::lock_guard<std::recursive_mutex> guard(m_last_stop_packet_mutex);
2380     // Get the number of stop packets on the stack
2381     int nItems = m_stop_packet_stack.size();
2382     // Iterate over them
2383     for (int i = 0; i < nItems; i++) {
2384       // Get the thread stop info
2385       StringExtractorGDBRemote stop_info = m_stop_packet_stack[i];
2386       // Process thread stop info
2387       SetThreadStopInfo(stop_info);
2388     }
2389     // Clear the thread stop stack
2390     m_stop_packet_stack.clear();
2391   }
2392 
2393   // If we have queried for a default thread id
2394   if (m_initial_tid != LLDB_INVALID_THREAD_ID) {
2395     m_thread_list.SetSelectedThreadByID(m_initial_tid);
2396     m_initial_tid = LLDB_INVALID_THREAD_ID;
2397   }
2398 
2399   // Let all threads recover from stopping and do any clean up based on the
2400   // previous thread state (if any).
2401   m_thread_list_real.RefreshStateAfterStop();
2402 }
2403 
2404 Status ProcessGDBRemote::DoHalt(bool &caused_stop) {
2405   Status error;
2406 
2407   if (m_public_state.GetValue() == eStateAttaching) {
2408     // We are being asked to halt during an attach. We need to just close our
2409     // file handle and debugserver will go away, and we can be done...
2410     m_gdb_comm.Disconnect();
2411   } else
2412     caused_stop = m_gdb_comm.Interrupt();
2413   return error;
2414 }
2415 
2416 Status ProcessGDBRemote::DoDetach(bool keep_stopped) {
2417   Status error;
2418   Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
2419   LLDB_LOGF(log, "ProcessGDBRemote::DoDetach(keep_stopped: %i)", keep_stopped);
2420 
2421   error = m_gdb_comm.Detach(keep_stopped);
2422   if (log) {
2423     if (error.Success())
2424       log->PutCString(
2425           "ProcessGDBRemote::DoDetach() detach packet sent successfully");
2426     else
2427       LLDB_LOGF(log,
2428                 "ProcessGDBRemote::DoDetach() detach packet send failed: %s",
2429                 error.AsCString() ? error.AsCString() : "<unknown error>");
2430   }
2431 
2432   if (!error.Success())
2433     return error;
2434 
2435   // Sleep for one second to let the process get all detached...
2436   StopAsyncThread();
2437 
2438   SetPrivateState(eStateDetached);
2439   ResumePrivateStateThread();
2440 
2441   // KillDebugserverProcess ();
2442   return error;
2443 }
2444 
2445 Status ProcessGDBRemote::DoDestroy() {
2446   Status error;
2447   Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
2448   LLDB_LOGF(log, "ProcessGDBRemote::DoDestroy()");
2449 
2450   // There is a bug in older iOS debugservers where they don't shut down the
2451   // process they are debugging properly.  If the process is sitting at a
2452   // breakpoint or an exception, this can cause problems with restarting.  So
2453   // we check to see if any of our threads are stopped at a breakpoint, and if
2454   // so we remove all the breakpoints, resume the process, and THEN destroy it
2455   // again.
2456   //
2457   // Note, we don't have a good way to test the version of debugserver, but I
2458   // happen to know that the set of all the iOS debugservers which don't
2459   // support GetThreadSuffixSupported() and that of the debugservers with this
2460   // bug are equal.  There really should be a better way to test this!
2461   //
2462   // We also use m_destroy_tried_resuming to make sure we only do this once, if
2463   // we resume and then halt and get called here to destroy again and we're
2464   // still at a breakpoint or exception, then we should just do the straight-
2465   // forward kill.
2466   //
2467   // And of course, if we weren't able to stop the process by the time we get
2468   // here, it isn't necessary (or helpful) to do any of this.
2469 
2470   if (!m_gdb_comm.GetThreadSuffixSupported() &&
2471       m_public_state.GetValue() != eStateRunning) {
2472     PlatformSP platform_sp = GetTarget().GetPlatform();
2473 
2474     // FIXME: These should be ConstStrings so we aren't doing strcmp'ing.
2475     if (platform_sp && platform_sp->GetName() &&
2476         platform_sp->GetName() == PlatformRemoteiOS::GetPluginNameStatic()) {
2477       if (m_destroy_tried_resuming) {
2478         if (log)
2479           log->PutCString("ProcessGDBRemote::DoDestroy() - Tried resuming to "
2480                           "destroy once already, not doing it again.");
2481       } else {
2482         // At present, the plans are discarded and the breakpoints disabled
2483         // Process::Destroy, but we really need it to happen here and it
2484         // doesn't matter if we do it twice.
2485         m_thread_list.DiscardThreadPlans();
2486         DisableAllBreakpointSites();
2487 
2488         bool stop_looks_like_crash = false;
2489         ThreadList &threads = GetThreadList();
2490 
2491         {
2492           std::lock_guard<std::recursive_mutex> guard(threads.GetMutex());
2493 
2494           size_t num_threads = threads.GetSize();
2495           for (size_t i = 0; i < num_threads; i++) {
2496             ThreadSP thread_sp = threads.GetThreadAtIndex(i);
2497             StopInfoSP stop_info_sp = thread_sp->GetPrivateStopInfo();
2498             StopReason reason = eStopReasonInvalid;
2499             if (stop_info_sp)
2500               reason = stop_info_sp->GetStopReason();
2501             if (reason == eStopReasonBreakpoint ||
2502                 reason == eStopReasonException) {
2503               LLDB_LOGF(log,
2504                         "ProcessGDBRemote::DoDestroy() - thread: 0x%4.4" PRIx64
2505                         " stopped with reason: %s.",
2506                         thread_sp->GetProtocolID(),
2507                         stop_info_sp->GetDescription());
2508               stop_looks_like_crash = true;
2509               break;
2510             }
2511           }
2512         }
2513 
2514         if (stop_looks_like_crash) {
2515           if (log)
2516             log->PutCString("ProcessGDBRemote::DoDestroy() - Stopped at a "
2517                             "breakpoint, continue and then kill.");
2518           m_destroy_tried_resuming = true;
2519 
2520           // If we are going to run again before killing, it would be good to
2521           // suspend all the threads before resuming so they won't get into
2522           // more trouble.  Sadly, for the threads stopped with the breakpoint
2523           // or exception, the exception doesn't get cleared if it is
2524           // suspended, so we do have to run the risk of letting those threads
2525           // proceed a bit.
2526 
2527           {
2528             std::lock_guard<std::recursive_mutex> guard(threads.GetMutex());
2529 
2530             size_t num_threads = threads.GetSize();
2531             for (size_t i = 0; i < num_threads; i++) {
2532               ThreadSP thread_sp = threads.GetThreadAtIndex(i);
2533               StopInfoSP stop_info_sp = thread_sp->GetPrivateStopInfo();
2534               StopReason reason = eStopReasonInvalid;
2535               if (stop_info_sp)
2536                 reason = stop_info_sp->GetStopReason();
2537               if (reason != eStopReasonBreakpoint &&
2538                   reason != eStopReasonException) {
2539                 LLDB_LOGF(log,
2540                           "ProcessGDBRemote::DoDestroy() - Suspending "
2541                           "thread: 0x%4.4" PRIx64 " before running.",
2542                           thread_sp->GetProtocolID());
2543                 thread_sp->SetResumeState(eStateSuspended);
2544               }
2545             }
2546           }
2547           Resume();
2548           return Destroy(false);
2549         }
2550       }
2551     }
2552   }
2553 
2554   // Interrupt if our inferior is running...
2555   int exit_status = SIGABRT;
2556   std::string exit_string;
2557 
2558   if (m_gdb_comm.IsConnected()) {
2559     if (m_public_state.GetValue() != eStateAttaching) {
2560       StringExtractorGDBRemote response;
2561       bool send_async = true;
2562       GDBRemoteCommunication::ScopedTimeout(m_gdb_comm,
2563                                             std::chrono::seconds(3));
2564 
2565       if (m_gdb_comm.SendPacketAndWaitForResponse("k", response, send_async) ==
2566           GDBRemoteCommunication::PacketResult::Success) {
2567         char packet_cmd = response.GetChar(0);
2568 
2569         if (packet_cmd == 'W' || packet_cmd == 'X') {
2570 #if defined(__APPLE__)
2571           // For Native processes on Mac OS X, we launch through the Host
2572           // Platform, then hand the process off to debugserver, which becomes
2573           // the parent process through "PT_ATTACH".  Then when we go to kill
2574           // the process on Mac OS X we call ptrace(PT_KILL) to kill it, then
2575           // we call waitpid which returns with no error and the correct
2576           // status.  But amusingly enough that doesn't seem to actually reap
2577           // the process, but instead it is left around as a Zombie.  Probably
2578           // the kernel is in the process of switching ownership back to lldb
2579           // which was the original parent, and gets confused in the handoff.
2580           // Anyway, so call waitpid here to finally reap it.
2581           PlatformSP platform_sp(GetTarget().GetPlatform());
2582           if (platform_sp && platform_sp->IsHost()) {
2583             int status;
2584             ::pid_t reap_pid;
2585             reap_pid = waitpid(GetID(), &status, WNOHANG);
2586             LLDB_LOGF(log, "Reaped pid: %d, status: %d.\n", reap_pid, status);
2587           }
2588 #endif
2589           SetLastStopPacket(response);
2590           ClearThreadIDList();
2591           exit_status = response.GetHexU8();
2592         } else {
2593           LLDB_LOGF(log,
2594                     "ProcessGDBRemote::DoDestroy - got unexpected response "
2595                     "to k packet: %s",
2596                     response.GetStringRef().data());
2597           exit_string.assign("got unexpected response to k packet: ");
2598           exit_string.append(std::string(response.GetStringRef()));
2599         }
2600       } else {
2601         LLDB_LOGF(log, "ProcessGDBRemote::DoDestroy - failed to send k packet");
2602         exit_string.assign("failed to send the k packet");
2603       }
2604     } else {
2605       LLDB_LOGF(log,
2606                 "ProcessGDBRemote::DoDestroy - killed or interrupted while "
2607                 "attaching");
2608       exit_string.assign("killed or interrupted while attaching.");
2609     }
2610   } else {
2611     // If we missed setting the exit status on the way out, do it here.
2612     // NB set exit status can be called multiple times, the first one sets the
2613     // status.
2614     exit_string.assign("destroying when not connected to debugserver");
2615   }
2616 
2617   SetExitStatus(exit_status, exit_string.c_str());
2618 
2619   StopAsyncThread();
2620   KillDebugserverProcess();
2621   return error;
2622 }
2623 
2624 void ProcessGDBRemote::SetLastStopPacket(
2625     const StringExtractorGDBRemote &response) {
2626   const bool did_exec =
2627       response.GetStringRef().find(";reason:exec;") != std::string::npos;
2628   if (did_exec) {
2629     Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
2630     LLDB_LOGF(log, "ProcessGDBRemote::SetLastStopPacket () - detected exec");
2631 
2632     m_thread_list_real.Clear();
2633     m_thread_list.Clear();
2634     BuildDynamicRegisterInfo(true);
2635     m_gdb_comm.ResetDiscoverableSettings(did_exec);
2636   }
2637 
2638   // Scope the lock
2639   {
2640     // Lock the thread stack while we access it
2641     std::lock_guard<std::recursive_mutex> guard(m_last_stop_packet_mutex);
2642 
2643     // We are are not using non-stop mode, there can only be one last stop
2644     // reply packet, so clear the list.
2645     if (!GetTarget().GetNonStopModeEnabled())
2646       m_stop_packet_stack.clear();
2647 
2648     // Add this stop packet to the stop packet stack This stack will get popped
2649     // and examined when we switch to the Stopped state
2650     m_stop_packet_stack.push_back(response);
2651   }
2652 }
2653 
2654 void ProcessGDBRemote::SetUnixSignals(const UnixSignalsSP &signals_sp) {
2655   Process::SetUnixSignals(std::make_shared<GDBRemoteSignals>(signals_sp));
2656 }
2657 
2658 // Process Queries
2659 
2660 bool ProcessGDBRemote::IsAlive() {
2661   return m_gdb_comm.IsConnected() && Process::IsAlive();
2662 }
2663 
2664 addr_t ProcessGDBRemote::GetImageInfoAddress() {
2665   // request the link map address via the $qShlibInfoAddr packet
2666   lldb::addr_t addr = m_gdb_comm.GetShlibInfoAddr();
2667 
2668   // the loaded module list can also provides a link map address
2669   if (addr == LLDB_INVALID_ADDRESS) {
2670     llvm::Expected<LoadedModuleInfoList> list = GetLoadedModuleList();
2671     if (!list) {
2672       Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
2673       LLDB_LOG_ERROR(log, list.takeError(), "Failed to read module list: {0}.");
2674     } else {
2675       addr = list->m_link_map;
2676     }
2677   }
2678 
2679   return addr;
2680 }
2681 
2682 void ProcessGDBRemote::WillPublicStop() {
2683   // See if the GDB remote client supports the JSON threads info. If so, we
2684   // gather stop info for all threads, expedited registers, expedited memory,
2685   // runtime queue information (iOS and MacOSX only), and more. Expediting
2686   // memory will help stack backtracing be much faster. Expediting registers
2687   // will make sure we don't have to read the thread registers for GPRs.
2688   m_jthreadsinfo_sp = m_gdb_comm.GetThreadsInfo();
2689 
2690   if (m_jthreadsinfo_sp) {
2691     // Now set the stop info for each thread and also expedite any registers
2692     // and memory that was in the jThreadsInfo response.
2693     StructuredData::Array *thread_infos = m_jthreadsinfo_sp->GetAsArray();
2694     if (thread_infos) {
2695       const size_t n = thread_infos->GetSize();
2696       for (size_t i = 0; i < n; ++i) {
2697         StructuredData::Dictionary *thread_dict =
2698             thread_infos->GetItemAtIndex(i)->GetAsDictionary();
2699         if (thread_dict)
2700           SetThreadStopInfo(thread_dict);
2701       }
2702     }
2703   }
2704 }
2705 
2706 // Process Memory
2707 size_t ProcessGDBRemote::DoReadMemory(addr_t addr, void *buf, size_t size,
2708                                       Status &error) {
2709   GetMaxMemorySize();
2710   bool binary_memory_read = m_gdb_comm.GetxPacketSupported();
2711   // M and m packets take 2 bytes for 1 byte of memory
2712   size_t max_memory_size =
2713       binary_memory_read ? m_max_memory_size : m_max_memory_size / 2;
2714   if (size > max_memory_size) {
2715     // Keep memory read sizes down to a sane limit. This function will be
2716     // called multiple times in order to complete the task by
2717     // lldb_private::Process so it is ok to do this.
2718     size = max_memory_size;
2719   }
2720 
2721   char packet[64];
2722   int packet_len;
2723   packet_len = ::snprintf(packet, sizeof(packet), "%c%" PRIx64 ",%" PRIx64,
2724                           binary_memory_read ? 'x' : 'm', (uint64_t)addr,
2725                           (uint64_t)size);
2726   assert(packet_len + 1 < (int)sizeof(packet));
2727   UNUSED_IF_ASSERT_DISABLED(packet_len);
2728   StringExtractorGDBRemote response;
2729   if (m_gdb_comm.SendPacketAndWaitForResponse(packet, response, true) ==
2730       GDBRemoteCommunication::PacketResult::Success) {
2731     if (response.IsNormalResponse()) {
2732       error.Clear();
2733       if (binary_memory_read) {
2734         // The lower level GDBRemoteCommunication packet receive layer has
2735         // already de-quoted any 0x7d character escaping that was present in
2736         // the packet
2737 
2738         size_t data_received_size = response.GetBytesLeft();
2739         if (data_received_size > size) {
2740           // Don't write past the end of BUF if the remote debug server gave us
2741           // too much data for some reason.
2742           data_received_size = size;
2743         }
2744         memcpy(buf, response.GetStringRef().data(), data_received_size);
2745         return data_received_size;
2746       } else {
2747         return response.GetHexBytes(
2748             llvm::MutableArrayRef<uint8_t>((uint8_t *)buf, size), '\xdd');
2749       }
2750     } else if (response.IsErrorResponse())
2751       error.SetErrorStringWithFormat("memory read failed for 0x%" PRIx64, addr);
2752     else if (response.IsUnsupportedResponse())
2753       error.SetErrorStringWithFormat(
2754           "GDB server does not support reading memory");
2755     else
2756       error.SetErrorStringWithFormat(
2757           "unexpected response to GDB server memory read packet '%s': '%s'",
2758           packet, response.GetStringRef().data());
2759   } else {
2760     error.SetErrorStringWithFormat("failed to send packet: '%s'", packet);
2761   }
2762   return 0;
2763 }
2764 
2765 Status ProcessGDBRemote::WriteObjectFile(
2766     std::vector<ObjectFile::LoadableData> entries) {
2767   Status error;
2768   // Sort the entries by address because some writes, like those to flash
2769   // memory, must happen in order of increasing address.
2770   std::stable_sort(
2771       std::begin(entries), std::end(entries),
2772       [](const ObjectFile::LoadableData a, const ObjectFile::LoadableData b) {
2773         return a.Dest < b.Dest;
2774       });
2775   m_allow_flash_writes = true;
2776   error = Process::WriteObjectFile(entries);
2777   if (error.Success())
2778     error = FlashDone();
2779   else
2780     // Even though some of the writing failed, try to send a flash done if some
2781     // of the writing succeeded so the flash state is reset to normal, but
2782     // don't stomp on the error status that was set in the write failure since
2783     // that's the one we want to report back.
2784     FlashDone();
2785   m_allow_flash_writes = false;
2786   return error;
2787 }
2788 
2789 bool ProcessGDBRemote::HasErased(FlashRange range) {
2790   auto size = m_erased_flash_ranges.GetSize();
2791   for (size_t i = 0; i < size; ++i)
2792     if (m_erased_flash_ranges.GetEntryAtIndex(i)->Contains(range))
2793       return true;
2794   return false;
2795 }
2796 
2797 Status ProcessGDBRemote::FlashErase(lldb::addr_t addr, size_t size) {
2798   Status status;
2799 
2800   MemoryRegionInfo region;
2801   status = GetMemoryRegionInfo(addr, region);
2802   if (!status.Success())
2803     return status;
2804 
2805   // The gdb spec doesn't say if erasures are allowed across multiple regions,
2806   // but we'll disallow it to be safe and to keep the logic simple by worring
2807   // about only one region's block size.  DoMemoryWrite is this function's
2808   // primary user, and it can easily keep writes within a single memory region
2809   if (addr + size > region.GetRange().GetRangeEnd()) {
2810     status.SetErrorString("Unable to erase flash in multiple regions");
2811     return status;
2812   }
2813 
2814   uint64_t blocksize = region.GetBlocksize();
2815   if (blocksize == 0) {
2816     status.SetErrorString("Unable to erase flash because blocksize is 0");
2817     return status;
2818   }
2819 
2820   // Erasures can only be done on block boundary adresses, so round down addr
2821   // and round up size
2822   lldb::addr_t block_start_addr = addr - (addr % blocksize);
2823   size += (addr - block_start_addr);
2824   if ((size % blocksize) != 0)
2825     size += (blocksize - size % blocksize);
2826 
2827   FlashRange range(block_start_addr, size);
2828 
2829   if (HasErased(range))
2830     return status;
2831 
2832   // We haven't erased the entire range, but we may have erased part of it.
2833   // (e.g., block A is already erased and range starts in A and ends in B). So,
2834   // adjust range if necessary to exclude already erased blocks.
2835   if (!m_erased_flash_ranges.IsEmpty()) {
2836     // Assuming that writes and erasures are done in increasing addr order,
2837     // because that is a requirement of the vFlashWrite command.  Therefore, we
2838     // only need to look at the last range in the list for overlap.
2839     const auto &last_range = *m_erased_flash_ranges.Back();
2840     if (range.GetRangeBase() < last_range.GetRangeEnd()) {
2841       auto overlap = last_range.GetRangeEnd() - range.GetRangeBase();
2842       // overlap will be less than range.GetByteSize() or else HasErased()
2843       // would have been true
2844       range.SetByteSize(range.GetByteSize() - overlap);
2845       range.SetRangeBase(range.GetRangeBase() + overlap);
2846     }
2847   }
2848 
2849   StreamString packet;
2850   packet.Printf("vFlashErase:%" PRIx64 ",%" PRIx64, range.GetRangeBase(),
2851                 (uint64_t)range.GetByteSize());
2852 
2853   StringExtractorGDBRemote response;
2854   if (m_gdb_comm.SendPacketAndWaitForResponse(packet.GetString(), response,
2855                                               true) ==
2856       GDBRemoteCommunication::PacketResult::Success) {
2857     if (response.IsOKResponse()) {
2858       m_erased_flash_ranges.Insert(range, true);
2859     } else {
2860       if (response.IsErrorResponse())
2861         status.SetErrorStringWithFormat("flash erase failed for 0x%" PRIx64,
2862                                         addr);
2863       else if (response.IsUnsupportedResponse())
2864         status.SetErrorStringWithFormat("GDB server does not support flashing");
2865       else
2866         status.SetErrorStringWithFormat(
2867             "unexpected response to GDB server flash erase packet '%s': '%s'",
2868             packet.GetData(), response.GetStringRef().data());
2869     }
2870   } else {
2871     status.SetErrorStringWithFormat("failed to send packet: '%s'",
2872                                     packet.GetData());
2873   }
2874   return status;
2875 }
2876 
2877 Status ProcessGDBRemote::FlashDone() {
2878   Status status;
2879   // If we haven't erased any blocks, then we must not have written anything
2880   // either, so there is no need to actually send a vFlashDone command
2881   if (m_erased_flash_ranges.IsEmpty())
2882     return status;
2883   StringExtractorGDBRemote response;
2884   if (m_gdb_comm.SendPacketAndWaitForResponse("vFlashDone", response, true) ==
2885       GDBRemoteCommunication::PacketResult::Success) {
2886     if (response.IsOKResponse()) {
2887       m_erased_flash_ranges.Clear();
2888     } else {
2889       if (response.IsErrorResponse())
2890         status.SetErrorStringWithFormat("flash done failed");
2891       else if (response.IsUnsupportedResponse())
2892         status.SetErrorStringWithFormat("GDB server does not support flashing");
2893       else
2894         status.SetErrorStringWithFormat(
2895             "unexpected response to GDB server flash done packet: '%s'",
2896             response.GetStringRef().data());
2897     }
2898   } else {
2899     status.SetErrorStringWithFormat("failed to send flash done packet");
2900   }
2901   return status;
2902 }
2903 
2904 size_t ProcessGDBRemote::DoWriteMemory(addr_t addr, const void *buf,
2905                                        size_t size, Status &error) {
2906   GetMaxMemorySize();
2907   // M and m packets take 2 bytes for 1 byte of memory
2908   size_t max_memory_size = m_max_memory_size / 2;
2909   if (size > max_memory_size) {
2910     // Keep memory read sizes down to a sane limit. This function will be
2911     // called multiple times in order to complete the task by
2912     // lldb_private::Process so it is ok to do this.
2913     size = max_memory_size;
2914   }
2915 
2916   StreamGDBRemote packet;
2917 
2918   MemoryRegionInfo region;
2919   Status region_status = GetMemoryRegionInfo(addr, region);
2920 
2921   bool is_flash =
2922       region_status.Success() && region.GetFlash() == MemoryRegionInfo::eYes;
2923 
2924   if (is_flash) {
2925     if (!m_allow_flash_writes) {
2926       error.SetErrorString("Writing to flash memory is not allowed");
2927       return 0;
2928     }
2929     // Keep the write within a flash memory region
2930     if (addr + size > region.GetRange().GetRangeEnd())
2931       size = region.GetRange().GetRangeEnd() - addr;
2932     // Flash memory must be erased before it can be written
2933     error = FlashErase(addr, size);
2934     if (!error.Success())
2935       return 0;
2936     packet.Printf("vFlashWrite:%" PRIx64 ":", addr);
2937     packet.PutEscapedBytes(buf, size);
2938   } else {
2939     packet.Printf("M%" PRIx64 ",%" PRIx64 ":", addr, (uint64_t)size);
2940     packet.PutBytesAsRawHex8(buf, size, endian::InlHostByteOrder(),
2941                              endian::InlHostByteOrder());
2942   }
2943   StringExtractorGDBRemote response;
2944   if (m_gdb_comm.SendPacketAndWaitForResponse(packet.GetString(), response,
2945                                               true) ==
2946       GDBRemoteCommunication::PacketResult::Success) {
2947     if (response.IsOKResponse()) {
2948       error.Clear();
2949       return size;
2950     } else if (response.IsErrorResponse())
2951       error.SetErrorStringWithFormat("memory write failed for 0x%" PRIx64,
2952                                      addr);
2953     else if (response.IsUnsupportedResponse())
2954       error.SetErrorStringWithFormat(
2955           "GDB server does not support writing memory");
2956     else
2957       error.SetErrorStringWithFormat(
2958           "unexpected response to GDB server memory write packet '%s': '%s'",
2959           packet.GetData(), response.GetStringRef().data());
2960   } else {
2961     error.SetErrorStringWithFormat("failed to send packet: '%s'",
2962                                    packet.GetData());
2963   }
2964   return 0;
2965 }
2966 
2967 lldb::addr_t ProcessGDBRemote::DoAllocateMemory(size_t size,
2968                                                 uint32_t permissions,
2969                                                 Status &error) {
2970   Log *log(
2971       GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS | LIBLLDB_LOG_EXPRESSIONS));
2972   addr_t allocated_addr = LLDB_INVALID_ADDRESS;
2973 
2974   if (m_gdb_comm.SupportsAllocDeallocMemory() != eLazyBoolNo) {
2975     allocated_addr = m_gdb_comm.AllocateMemory(size, permissions);
2976     if (allocated_addr != LLDB_INVALID_ADDRESS ||
2977         m_gdb_comm.SupportsAllocDeallocMemory() == eLazyBoolYes)
2978       return allocated_addr;
2979   }
2980 
2981   if (m_gdb_comm.SupportsAllocDeallocMemory() == eLazyBoolNo) {
2982     // Call mmap() to create memory in the inferior..
2983     unsigned prot = 0;
2984     if (permissions & lldb::ePermissionsReadable)
2985       prot |= eMmapProtRead;
2986     if (permissions & lldb::ePermissionsWritable)
2987       prot |= eMmapProtWrite;
2988     if (permissions & lldb::ePermissionsExecutable)
2989       prot |= eMmapProtExec;
2990 
2991     if (InferiorCallMmap(this, allocated_addr, 0, size, prot,
2992                          eMmapFlagsAnon | eMmapFlagsPrivate, -1, 0))
2993       m_addr_to_mmap_size[allocated_addr] = size;
2994     else {
2995       allocated_addr = LLDB_INVALID_ADDRESS;
2996       LLDB_LOGF(log,
2997                 "ProcessGDBRemote::%s no direct stub support for memory "
2998                 "allocation, and InferiorCallMmap also failed - is stub "
2999                 "missing register context save/restore capability?",
3000                 __FUNCTION__);
3001     }
3002   }
3003 
3004   if (allocated_addr == LLDB_INVALID_ADDRESS)
3005     error.SetErrorStringWithFormat(
3006         "unable to allocate %" PRIu64 " bytes of memory with permissions %s",
3007         (uint64_t)size, GetPermissionsAsCString(permissions));
3008   else
3009     error.Clear();
3010   return allocated_addr;
3011 }
3012 
3013 Status ProcessGDBRemote::GetMemoryRegionInfo(addr_t load_addr,
3014                                              MemoryRegionInfo &region_info) {
3015 
3016   Status error(m_gdb_comm.GetMemoryRegionInfo(load_addr, region_info));
3017   return error;
3018 }
3019 
3020 Status ProcessGDBRemote::GetWatchpointSupportInfo(uint32_t &num) {
3021 
3022   Status error(m_gdb_comm.GetWatchpointSupportInfo(num));
3023   return error;
3024 }
3025 
3026 Status ProcessGDBRemote::GetWatchpointSupportInfo(uint32_t &num, bool &after) {
3027   Status error(m_gdb_comm.GetWatchpointSupportInfo(
3028       num, after, GetTarget().GetArchitecture()));
3029   return error;
3030 }
3031 
3032 Status ProcessGDBRemote::DoDeallocateMemory(lldb::addr_t addr) {
3033   Status error;
3034   LazyBool supported = m_gdb_comm.SupportsAllocDeallocMemory();
3035 
3036   switch (supported) {
3037   case eLazyBoolCalculate:
3038     // We should never be deallocating memory without allocating memory first
3039     // so we should never get eLazyBoolCalculate
3040     error.SetErrorString(
3041         "tried to deallocate memory without ever allocating memory");
3042     break;
3043 
3044   case eLazyBoolYes:
3045     if (!m_gdb_comm.DeallocateMemory(addr))
3046       error.SetErrorStringWithFormat(
3047           "unable to deallocate memory at 0x%" PRIx64, addr);
3048     break;
3049 
3050   case eLazyBoolNo:
3051     // Call munmap() to deallocate memory in the inferior..
3052     {
3053       MMapMap::iterator pos = m_addr_to_mmap_size.find(addr);
3054       if (pos != m_addr_to_mmap_size.end() &&
3055           InferiorCallMunmap(this, addr, pos->second))
3056         m_addr_to_mmap_size.erase(pos);
3057       else
3058         error.SetErrorStringWithFormat(
3059             "unable to deallocate memory at 0x%" PRIx64, addr);
3060     }
3061     break;
3062   }
3063 
3064   return error;
3065 }
3066 
3067 // Process STDIO
3068 size_t ProcessGDBRemote::PutSTDIN(const char *src, size_t src_len,
3069                                   Status &error) {
3070   if (m_stdio_communication.IsConnected()) {
3071     ConnectionStatus status;
3072     m_stdio_communication.Write(src, src_len, status, nullptr);
3073   } else if (m_stdin_forward) {
3074     m_gdb_comm.SendStdinNotification(src, src_len);
3075   }
3076   return 0;
3077 }
3078 
3079 Status ProcessGDBRemote::EnableBreakpointSite(BreakpointSite *bp_site) {
3080   Status error;
3081   assert(bp_site != nullptr);
3082 
3083   // Get logging info
3084   Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_BREAKPOINTS));
3085   user_id_t site_id = bp_site->GetID();
3086 
3087   // Get the breakpoint address
3088   const addr_t addr = bp_site->GetLoadAddress();
3089 
3090   // Log that a breakpoint was requested
3091   LLDB_LOGF(log,
3092             "ProcessGDBRemote::EnableBreakpointSite (size_id = %" PRIu64
3093             ") address = 0x%" PRIx64,
3094             site_id, (uint64_t)addr);
3095 
3096   // Breakpoint already exists and is enabled
3097   if (bp_site->IsEnabled()) {
3098     LLDB_LOGF(log,
3099               "ProcessGDBRemote::EnableBreakpointSite (size_id = %" PRIu64
3100               ") address = 0x%" PRIx64 " -- SUCCESS (already enabled)",
3101               site_id, (uint64_t)addr);
3102     return error;
3103   }
3104 
3105   // Get the software breakpoint trap opcode size
3106   const size_t bp_op_size = GetSoftwareBreakpointTrapOpcode(bp_site);
3107 
3108   // SupportsGDBStoppointPacket() simply checks a boolean, indicating if this
3109   // breakpoint type is supported by the remote stub. These are set to true by
3110   // default, and later set to false only after we receive an unimplemented
3111   // response when sending a breakpoint packet. This means initially that
3112   // unless we were specifically instructed to use a hardware breakpoint, LLDB
3113   // will attempt to set a software breakpoint. HardwareRequired() also queries
3114   // a boolean variable which indicates if the user specifically asked for
3115   // hardware breakpoints.  If true then we will skip over software
3116   // breakpoints.
3117   if (m_gdb_comm.SupportsGDBStoppointPacket(eBreakpointSoftware) &&
3118       (!bp_site->HardwareRequired())) {
3119     // Try to send off a software breakpoint packet ($Z0)
3120     uint8_t error_no = m_gdb_comm.SendGDBStoppointTypePacket(
3121         eBreakpointSoftware, true, addr, bp_op_size);
3122     if (error_no == 0) {
3123       // The breakpoint was placed successfully
3124       bp_site->SetEnabled(true);
3125       bp_site->SetType(BreakpointSite::eExternal);
3126       return error;
3127     }
3128 
3129     // SendGDBStoppointTypePacket() will return an error if it was unable to
3130     // set this breakpoint. We need to differentiate between a error specific
3131     // to placing this breakpoint or if we have learned that this breakpoint
3132     // type is unsupported. To do this, we must test the support boolean for
3133     // this breakpoint type to see if it now indicates that this breakpoint
3134     // type is unsupported.  If they are still supported then we should return
3135     // with the error code.  If they are now unsupported, then we would like to
3136     // fall through and try another form of breakpoint.
3137     if (m_gdb_comm.SupportsGDBStoppointPacket(eBreakpointSoftware)) {
3138       if (error_no != UINT8_MAX)
3139         error.SetErrorStringWithFormat(
3140             "error: %d sending the breakpoint request", error_no);
3141       else
3142         error.SetErrorString("error sending the breakpoint request");
3143       return error;
3144     }
3145 
3146     // We reach here when software breakpoints have been found to be
3147     // unsupported. For future calls to set a breakpoint, we will not attempt
3148     // to set a breakpoint with a type that is known not to be supported.
3149     LLDB_LOGF(log, "Software breakpoints are unsupported");
3150 
3151     // So we will fall through and try a hardware breakpoint
3152   }
3153 
3154   // The process of setting a hardware breakpoint is much the same as above.
3155   // We check the supported boolean for this breakpoint type, and if it is
3156   // thought to be supported then we will try to set this breakpoint with a
3157   // hardware breakpoint.
3158   if (m_gdb_comm.SupportsGDBStoppointPacket(eBreakpointHardware)) {
3159     // Try to send off a hardware breakpoint packet ($Z1)
3160     uint8_t error_no = m_gdb_comm.SendGDBStoppointTypePacket(
3161         eBreakpointHardware, true, addr, bp_op_size);
3162     if (error_no == 0) {
3163       // The breakpoint was placed successfully
3164       bp_site->SetEnabled(true);
3165       bp_site->SetType(BreakpointSite::eHardware);
3166       return error;
3167     }
3168 
3169     // Check if the error was something other then an unsupported breakpoint
3170     // type
3171     if (m_gdb_comm.SupportsGDBStoppointPacket(eBreakpointHardware)) {
3172       // Unable to set this hardware breakpoint
3173       if (error_no != UINT8_MAX)
3174         error.SetErrorStringWithFormat(
3175             "error: %d sending the hardware breakpoint request "
3176             "(hardware breakpoint resources might be exhausted or unavailable)",
3177             error_no);
3178       else
3179         error.SetErrorString("error sending the hardware breakpoint request "
3180                              "(hardware breakpoint resources "
3181                              "might be exhausted or unavailable)");
3182       return error;
3183     }
3184 
3185     // We will reach here when the stub gives an unsupported response to a
3186     // hardware breakpoint
3187     LLDB_LOGF(log, "Hardware breakpoints are unsupported");
3188 
3189     // Finally we will falling through to a #trap style breakpoint
3190   }
3191 
3192   // Don't fall through when hardware breakpoints were specifically requested
3193   if (bp_site->HardwareRequired()) {
3194     error.SetErrorString("hardware breakpoints are not supported");
3195     return error;
3196   }
3197 
3198   // As a last resort we want to place a manual breakpoint. An instruction is
3199   // placed into the process memory using memory write packets.
3200   return EnableSoftwareBreakpoint(bp_site);
3201 }
3202 
3203 Status ProcessGDBRemote::DisableBreakpointSite(BreakpointSite *bp_site) {
3204   Status error;
3205   assert(bp_site != nullptr);
3206   addr_t addr = bp_site->GetLoadAddress();
3207   user_id_t site_id = bp_site->GetID();
3208   Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_BREAKPOINTS));
3209   LLDB_LOGF(log,
3210             "ProcessGDBRemote::DisableBreakpointSite (site_id = %" PRIu64
3211             ") addr = 0x%8.8" PRIx64,
3212             site_id, (uint64_t)addr);
3213 
3214   if (bp_site->IsEnabled()) {
3215     const size_t bp_op_size = GetSoftwareBreakpointTrapOpcode(bp_site);
3216 
3217     BreakpointSite::Type bp_type = bp_site->GetType();
3218     switch (bp_type) {
3219     case BreakpointSite::eSoftware:
3220       error = DisableSoftwareBreakpoint(bp_site);
3221       break;
3222 
3223     case BreakpointSite::eHardware:
3224       if (m_gdb_comm.SendGDBStoppointTypePacket(eBreakpointHardware, false,
3225                                                 addr, bp_op_size))
3226         error.SetErrorToGenericError();
3227       break;
3228 
3229     case BreakpointSite::eExternal: {
3230       if (m_gdb_comm.SendGDBStoppointTypePacket(eBreakpointSoftware, false,
3231                                                 addr, bp_op_size))
3232         error.SetErrorToGenericError();
3233     } break;
3234     }
3235     if (error.Success())
3236       bp_site->SetEnabled(false);
3237   } else {
3238     LLDB_LOGF(log,
3239               "ProcessGDBRemote::DisableBreakpointSite (site_id = %" PRIu64
3240               ") addr = 0x%8.8" PRIx64 " -- SUCCESS (already disabled)",
3241               site_id, (uint64_t)addr);
3242     return error;
3243   }
3244 
3245   if (error.Success())
3246     error.SetErrorToGenericError();
3247   return error;
3248 }
3249 
3250 // Pre-requisite: wp != NULL.
3251 static GDBStoppointType GetGDBStoppointType(Watchpoint *wp) {
3252   assert(wp);
3253   bool watch_read = wp->WatchpointRead();
3254   bool watch_write = wp->WatchpointWrite();
3255 
3256   // watch_read and watch_write cannot both be false.
3257   assert(watch_read || watch_write);
3258   if (watch_read && watch_write)
3259     return eWatchpointReadWrite;
3260   else if (watch_read)
3261     return eWatchpointRead;
3262   else // Must be watch_write, then.
3263     return eWatchpointWrite;
3264 }
3265 
3266 Status ProcessGDBRemote::EnableWatchpoint(Watchpoint *wp, bool notify) {
3267   Status error;
3268   if (wp) {
3269     user_id_t watchID = wp->GetID();
3270     addr_t addr = wp->GetLoadAddress();
3271     Log *log(
3272         ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_WATCHPOINTS));
3273     LLDB_LOGF(log, "ProcessGDBRemote::EnableWatchpoint(watchID = %" PRIu64 ")",
3274               watchID);
3275     if (wp->IsEnabled()) {
3276       LLDB_LOGF(log,
3277                 "ProcessGDBRemote::EnableWatchpoint(watchID = %" PRIu64
3278                 ") addr = 0x%8.8" PRIx64 ": watchpoint already enabled.",
3279                 watchID, (uint64_t)addr);
3280       return error;
3281     }
3282 
3283     GDBStoppointType type = GetGDBStoppointType(wp);
3284     // Pass down an appropriate z/Z packet...
3285     if (m_gdb_comm.SupportsGDBStoppointPacket(type)) {
3286       if (m_gdb_comm.SendGDBStoppointTypePacket(type, true, addr,
3287                                                 wp->GetByteSize()) == 0) {
3288         wp->SetEnabled(true, notify);
3289         return error;
3290       } else
3291         error.SetErrorString("sending gdb watchpoint packet failed");
3292     } else
3293       error.SetErrorString("watchpoints not supported");
3294   } else {
3295     error.SetErrorString("Watchpoint argument was NULL.");
3296   }
3297   if (error.Success())
3298     error.SetErrorToGenericError();
3299   return error;
3300 }
3301 
3302 Status ProcessGDBRemote::DisableWatchpoint(Watchpoint *wp, bool notify) {
3303   Status error;
3304   if (wp) {
3305     user_id_t watchID = wp->GetID();
3306 
3307     Log *log(
3308         ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_WATCHPOINTS));
3309 
3310     addr_t addr = wp->GetLoadAddress();
3311 
3312     LLDB_LOGF(log,
3313               "ProcessGDBRemote::DisableWatchpoint (watchID = %" PRIu64
3314               ") addr = 0x%8.8" PRIx64,
3315               watchID, (uint64_t)addr);
3316 
3317     if (!wp->IsEnabled()) {
3318       LLDB_LOGF(log,
3319                 "ProcessGDBRemote::DisableWatchpoint (watchID = %" PRIu64
3320                 ") addr = 0x%8.8" PRIx64 " -- SUCCESS (already disabled)",
3321                 watchID, (uint64_t)addr);
3322       // See also 'class WatchpointSentry' within StopInfo.cpp. This disabling
3323       // attempt might come from the user-supplied actions, we'll route it in
3324       // order for the watchpoint object to intelligently process this action.
3325       wp->SetEnabled(false, notify);
3326       return error;
3327     }
3328 
3329     if (wp->IsHardware()) {
3330       GDBStoppointType type = GetGDBStoppointType(wp);
3331       // Pass down an appropriate z/Z packet...
3332       if (m_gdb_comm.SendGDBStoppointTypePacket(type, false, addr,
3333                                                 wp->GetByteSize()) == 0) {
3334         wp->SetEnabled(false, notify);
3335         return error;
3336       } else
3337         error.SetErrorString("sending gdb watchpoint packet failed");
3338     }
3339     // TODO: clear software watchpoints if we implement them
3340   } else {
3341     error.SetErrorString("Watchpoint argument was NULL.");
3342   }
3343   if (error.Success())
3344     error.SetErrorToGenericError();
3345   return error;
3346 }
3347 
3348 void ProcessGDBRemote::Clear() {
3349   m_thread_list_real.Clear();
3350   m_thread_list.Clear();
3351 }
3352 
3353 Status ProcessGDBRemote::DoSignal(int signo) {
3354   Status error;
3355   Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
3356   LLDB_LOGF(log, "ProcessGDBRemote::DoSignal (signal = %d)", signo);
3357 
3358   if (!m_gdb_comm.SendAsyncSignal(signo))
3359     error.SetErrorStringWithFormat("failed to send signal %i", signo);
3360   return error;
3361 }
3362 
3363 Status ProcessGDBRemote::ConnectToReplayServer() {
3364   Status status = m_gdb_replay_server.Connect(m_gdb_comm);
3365   if (status.Fail())
3366     return status;
3367 
3368   // Enable replay mode.
3369   m_replay_mode = true;
3370 
3371   // Start server thread.
3372   m_gdb_replay_server.StartAsyncThread();
3373 
3374   // Start client thread.
3375   StartAsyncThread();
3376 
3377   // Do the usual setup.
3378   return ConnectToDebugserver("");
3379 }
3380 
3381 Status
3382 ProcessGDBRemote::EstablishConnectionIfNeeded(const ProcessInfo &process_info) {
3383   // Make sure we aren't already connected?
3384   if (m_gdb_comm.IsConnected())
3385     return Status();
3386 
3387   PlatformSP platform_sp(GetTarget().GetPlatform());
3388   if (platform_sp && !platform_sp->IsHost())
3389     return Status("Lost debug server connection");
3390 
3391   if (repro::Reproducer::Instance().IsReplaying())
3392     return ConnectToReplayServer();
3393 
3394   auto error = LaunchAndConnectToDebugserver(process_info);
3395   if (error.Fail()) {
3396     const char *error_string = error.AsCString();
3397     if (error_string == nullptr)
3398       error_string = "unable to launch " DEBUGSERVER_BASENAME;
3399   }
3400   return error;
3401 }
3402 #if !defined(_WIN32)
3403 #define USE_SOCKETPAIR_FOR_LOCAL_CONNECTION 1
3404 #endif
3405 
3406 #ifdef USE_SOCKETPAIR_FOR_LOCAL_CONNECTION
3407 static bool SetCloexecFlag(int fd) {
3408 #if defined(FD_CLOEXEC)
3409   int flags = ::fcntl(fd, F_GETFD);
3410   if (flags == -1)
3411     return false;
3412   return (::fcntl(fd, F_SETFD, flags | FD_CLOEXEC) == 0);
3413 #else
3414   return false;
3415 #endif
3416 }
3417 #endif
3418 
3419 Status ProcessGDBRemote::LaunchAndConnectToDebugserver(
3420     const ProcessInfo &process_info) {
3421   using namespace std::placeholders; // For _1, _2, etc.
3422 
3423   Status error;
3424   if (m_debugserver_pid == LLDB_INVALID_PROCESS_ID) {
3425     // If we locate debugserver, keep that located version around
3426     static FileSpec g_debugserver_file_spec;
3427 
3428     ProcessLaunchInfo debugserver_launch_info;
3429     // Make debugserver run in its own session so signals generated by special
3430     // terminal key sequences (^C) don't affect debugserver.
3431     debugserver_launch_info.SetLaunchInSeparateProcessGroup(true);
3432 
3433     const std::weak_ptr<ProcessGDBRemote> this_wp =
3434         std::static_pointer_cast<ProcessGDBRemote>(shared_from_this());
3435     debugserver_launch_info.SetMonitorProcessCallback(
3436         std::bind(MonitorDebugserverProcess, this_wp, _1, _2, _3, _4), false);
3437     debugserver_launch_info.SetUserID(process_info.GetUserID());
3438 
3439 #if defined(__APPLE__)
3440     // On macOS 11, we need to support x86_64 applications translated to
3441     // arm64. We check whether a binary is translated and spawn the correct
3442     // debugserver accordingly.
3443     int mib[] = { CTL_KERN, KERN_PROC, KERN_PROC_PID,
3444                   static_cast<int>(process_info.GetProcessID()) };
3445     struct kinfo_proc processInfo;
3446     size_t bufsize = sizeof(processInfo);
3447     if (sysctl(mib, (unsigned)(sizeof(mib)/sizeof(int)), &processInfo,
3448                &bufsize, NULL, 0) == 0 && bufsize > 0) {
3449       if (processInfo.kp_proc.p_flag & P_TRANSLATED) {
3450         FileSpec rosetta_debugserver("/Library/Apple/usr/libexec/oah/debugserver");
3451         debugserver_launch_info.SetExecutableFile(rosetta_debugserver, false);
3452       }
3453     }
3454 #endif
3455 
3456     int communication_fd = -1;
3457 #ifdef USE_SOCKETPAIR_FOR_LOCAL_CONNECTION
3458     // Use a socketpair on non-Windows systems for security and performance
3459     // reasons.
3460     int sockets[2]; /* the pair of socket descriptors */
3461     if (socketpair(AF_UNIX, SOCK_STREAM, 0, sockets) == -1) {
3462       error.SetErrorToErrno();
3463       return error;
3464     }
3465 
3466     int our_socket = sockets[0];
3467     int gdb_socket = sockets[1];
3468     auto cleanup_our = llvm::make_scope_exit([&]() { close(our_socket); });
3469     auto cleanup_gdb = llvm::make_scope_exit([&]() { close(gdb_socket); });
3470 
3471     // Don't let any child processes inherit our communication socket
3472     SetCloexecFlag(our_socket);
3473     communication_fd = gdb_socket;
3474 #endif
3475 
3476     error = m_gdb_comm.StartDebugserverProcess(
3477         nullptr, GetTarget().GetPlatform().get(), debugserver_launch_info,
3478         nullptr, nullptr, communication_fd);
3479 
3480     if (error.Success())
3481       m_debugserver_pid = debugserver_launch_info.GetProcessID();
3482     else
3483       m_debugserver_pid = LLDB_INVALID_PROCESS_ID;
3484 
3485     if (m_debugserver_pid != LLDB_INVALID_PROCESS_ID) {
3486 #ifdef USE_SOCKETPAIR_FOR_LOCAL_CONNECTION
3487       // Our process spawned correctly, we can now set our connection to use
3488       // our end of the socket pair
3489       cleanup_our.release();
3490       m_gdb_comm.SetConnection(
3491           std::make_unique<ConnectionFileDescriptor>(our_socket, true));
3492 #endif
3493       StartAsyncThread();
3494     }
3495 
3496     if (error.Fail()) {
3497       Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
3498 
3499       LLDB_LOGF(log, "failed to start debugserver process: %s",
3500                 error.AsCString());
3501       return error;
3502     }
3503 
3504     if (m_gdb_comm.IsConnected()) {
3505       // Finish the connection process by doing the handshake without
3506       // connecting (send NULL URL)
3507       error = ConnectToDebugserver("");
3508     } else {
3509       error.SetErrorString("connection failed");
3510     }
3511   }
3512   return error;
3513 }
3514 
3515 bool ProcessGDBRemote::MonitorDebugserverProcess(
3516     std::weak_ptr<ProcessGDBRemote> process_wp, lldb::pid_t debugserver_pid,
3517     bool exited,    // True if the process did exit
3518     int signo,      // Zero for no signal
3519     int exit_status // Exit value of process if signal is zero
3520 ) {
3521   // "debugserver_pid" argument passed in is the process ID for debugserver
3522   // that we are tracking...
3523   Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
3524   const bool handled = true;
3525 
3526   LLDB_LOGF(log,
3527             "ProcessGDBRemote::%s(process_wp, pid=%" PRIu64
3528             ", signo=%i (0x%x), exit_status=%i)",
3529             __FUNCTION__, debugserver_pid, signo, signo, exit_status);
3530 
3531   std::shared_ptr<ProcessGDBRemote> process_sp = process_wp.lock();
3532   LLDB_LOGF(log, "ProcessGDBRemote::%s(process = %p)", __FUNCTION__,
3533             static_cast<void *>(process_sp.get()));
3534   if (!process_sp || process_sp->m_debugserver_pid != debugserver_pid)
3535     return handled;
3536 
3537   // Sleep for a half a second to make sure our inferior process has time to
3538   // set its exit status before we set it incorrectly when both the debugserver
3539   // and the inferior process shut down.
3540   std::this_thread::sleep_for(std::chrono::milliseconds(500));
3541 
3542   // If our process hasn't yet exited, debugserver might have died. If the
3543   // process did exit, then we are reaping it.
3544   const StateType state = process_sp->GetState();
3545 
3546   if (state != eStateInvalid && state != eStateUnloaded &&
3547       state != eStateExited && state != eStateDetached) {
3548     char error_str[1024];
3549     if (signo) {
3550       const char *signal_cstr =
3551           process_sp->GetUnixSignals()->GetSignalAsCString(signo);
3552       if (signal_cstr)
3553         ::snprintf(error_str, sizeof(error_str),
3554                    DEBUGSERVER_BASENAME " died with signal %s", signal_cstr);
3555       else
3556         ::snprintf(error_str, sizeof(error_str),
3557                    DEBUGSERVER_BASENAME " died with signal %i", signo);
3558     } else {
3559       ::snprintf(error_str, sizeof(error_str),
3560                  DEBUGSERVER_BASENAME " died with an exit status of 0x%8.8x",
3561                  exit_status);
3562     }
3563 
3564     process_sp->SetExitStatus(-1, error_str);
3565   }
3566   // Debugserver has exited we need to let our ProcessGDBRemote know that it no
3567   // longer has a debugserver instance
3568   process_sp->m_debugserver_pid = LLDB_INVALID_PROCESS_ID;
3569   return handled;
3570 }
3571 
3572 void ProcessGDBRemote::KillDebugserverProcess() {
3573   m_gdb_comm.Disconnect();
3574   if (m_debugserver_pid != LLDB_INVALID_PROCESS_ID) {
3575     Host::Kill(m_debugserver_pid, SIGINT);
3576     m_debugserver_pid = LLDB_INVALID_PROCESS_ID;
3577   }
3578 }
3579 
3580 void ProcessGDBRemote::Initialize() {
3581   static llvm::once_flag g_once_flag;
3582 
3583   llvm::call_once(g_once_flag, []() {
3584     PluginManager::RegisterPlugin(GetPluginNameStatic(),
3585                                   GetPluginDescriptionStatic(), CreateInstance,
3586                                   DebuggerInitialize);
3587   });
3588 }
3589 
3590 void ProcessGDBRemote::DebuggerInitialize(Debugger &debugger) {
3591   if (!PluginManager::GetSettingForProcessPlugin(
3592           debugger, PluginProperties::GetSettingName())) {
3593     const bool is_global_setting = true;
3594     PluginManager::CreateSettingForProcessPlugin(
3595         debugger, GetGlobalPluginProperties()->GetValueProperties(),
3596         ConstString("Properties for the gdb-remote process plug-in."),
3597         is_global_setting);
3598   }
3599 }
3600 
3601 bool ProcessGDBRemote::StartAsyncThread() {
3602   Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
3603 
3604   LLDB_LOGF(log, "ProcessGDBRemote::%s ()", __FUNCTION__);
3605 
3606   std::lock_guard<std::recursive_mutex> guard(m_async_thread_state_mutex);
3607   if (!m_async_thread.IsJoinable()) {
3608     // Create a thread that watches our internal state and controls which
3609     // events make it to clients (into the DCProcess event queue).
3610 
3611     llvm::Expected<HostThread> async_thread = ThreadLauncher::LaunchThread(
3612         "<lldb.process.gdb-remote.async>", ProcessGDBRemote::AsyncThread, this);
3613     if (!async_thread) {
3614       LLDB_LOG_ERROR(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_HOST),
3615                      async_thread.takeError(),
3616                      "failed to launch host thread: {}");
3617       return false;
3618     }
3619     m_async_thread = *async_thread;
3620   } else
3621     LLDB_LOGF(log,
3622               "ProcessGDBRemote::%s () - Called when Async thread was "
3623               "already running.",
3624               __FUNCTION__);
3625 
3626   return m_async_thread.IsJoinable();
3627 }
3628 
3629 void ProcessGDBRemote::StopAsyncThread() {
3630   Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
3631 
3632   LLDB_LOGF(log, "ProcessGDBRemote::%s ()", __FUNCTION__);
3633 
3634   std::lock_guard<std::recursive_mutex> guard(m_async_thread_state_mutex);
3635   if (m_async_thread.IsJoinable()) {
3636     m_async_broadcaster.BroadcastEvent(eBroadcastBitAsyncThreadShouldExit);
3637 
3638     //  This will shut down the async thread.
3639     m_gdb_comm.Disconnect(); // Disconnect from the debug server.
3640 
3641     // Stop the stdio thread
3642     m_async_thread.Join(nullptr);
3643     m_async_thread.Reset();
3644   } else
3645     LLDB_LOGF(
3646         log,
3647         "ProcessGDBRemote::%s () - Called when Async thread was not running.",
3648         __FUNCTION__);
3649 }
3650 
3651 bool ProcessGDBRemote::HandleNotifyPacket(StringExtractorGDBRemote &packet) {
3652   // get the packet at a string
3653   const std::string &pkt = std::string(packet.GetStringRef());
3654   // skip %stop:
3655   StringExtractorGDBRemote stop_info(pkt.c_str() + 5);
3656 
3657   // pass as a thread stop info packet
3658   SetLastStopPacket(stop_info);
3659 
3660   // check for more stop reasons
3661   HandleStopReplySequence();
3662 
3663   // if the process is stopped then we need to fake a resume so that we can
3664   // stop properly with the new break. This is possible due to
3665   // SetPrivateState() broadcasting the state change as a side effect.
3666   if (GetPrivateState() == lldb::StateType::eStateStopped) {
3667     SetPrivateState(lldb::StateType::eStateRunning);
3668   }
3669 
3670   // since we have some stopped packets we can halt the process
3671   SetPrivateState(lldb::StateType::eStateStopped);
3672 
3673   return true;
3674 }
3675 
3676 thread_result_t ProcessGDBRemote::AsyncThread(void *arg) {
3677   ProcessGDBRemote *process = (ProcessGDBRemote *)arg;
3678 
3679   Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
3680   LLDB_LOGF(log,
3681             "ProcessGDBRemote::%s (arg = %p, pid = %" PRIu64
3682             ") thread starting...",
3683             __FUNCTION__, arg, process->GetID());
3684 
3685   EventSP event_sp;
3686   bool done = false;
3687   while (!done) {
3688     LLDB_LOGF(log,
3689               "ProcessGDBRemote::%s (arg = %p, pid = %" PRIu64
3690               ") listener.WaitForEvent (NULL, event_sp)...",
3691               __FUNCTION__, arg, process->GetID());
3692     if (process->m_async_listener_sp->GetEvent(event_sp, llvm::None)) {
3693       const uint32_t event_type = event_sp->GetType();
3694       if (event_sp->BroadcasterIs(&process->m_async_broadcaster)) {
3695         LLDB_LOGF(log,
3696                   "ProcessGDBRemote::%s (arg = %p, pid = %" PRIu64
3697                   ") Got an event of type: %d...",
3698                   __FUNCTION__, arg, process->GetID(), event_type);
3699 
3700         switch (event_type) {
3701         case eBroadcastBitAsyncContinue: {
3702           const EventDataBytes *continue_packet =
3703               EventDataBytes::GetEventDataFromEvent(event_sp.get());
3704 
3705           if (continue_packet) {
3706             const char *continue_cstr =
3707                 (const char *)continue_packet->GetBytes();
3708             const size_t continue_cstr_len = continue_packet->GetByteSize();
3709             LLDB_LOGF(log,
3710                       "ProcessGDBRemote::%s (arg = %p, pid = %" PRIu64
3711                       ") got eBroadcastBitAsyncContinue: %s",
3712                       __FUNCTION__, arg, process->GetID(), continue_cstr);
3713 
3714             if (::strstr(continue_cstr, "vAttach") == nullptr)
3715               process->SetPrivateState(eStateRunning);
3716             StringExtractorGDBRemote response;
3717 
3718             // If in Non-Stop-Mode
3719             if (process->GetTarget().GetNonStopModeEnabled()) {
3720               // send the vCont packet
3721               if (!process->GetGDBRemote().SendvContPacket(
3722                       llvm::StringRef(continue_cstr, continue_cstr_len),
3723                       response)) {
3724                 // Something went wrong
3725                 done = true;
3726                 break;
3727               }
3728             }
3729             // If in All-Stop-Mode
3730             else {
3731               StateType stop_state =
3732                   process->GetGDBRemote().SendContinuePacketAndWaitForResponse(
3733                       *process, *process->GetUnixSignals(),
3734                       llvm::StringRef(continue_cstr, continue_cstr_len),
3735                       response);
3736 
3737               // We need to immediately clear the thread ID list so we are sure
3738               // to get a valid list of threads. The thread ID list might be
3739               // contained within the "response", or the stop reply packet that
3740               // caused the stop. So clear it now before we give the stop reply
3741               // packet to the process using the
3742               // process->SetLastStopPacket()...
3743               process->ClearThreadIDList();
3744 
3745               switch (stop_state) {
3746               case eStateStopped:
3747               case eStateCrashed:
3748               case eStateSuspended:
3749                 process->SetLastStopPacket(response);
3750                 process->SetPrivateState(stop_state);
3751                 break;
3752 
3753               case eStateExited: {
3754                 process->SetLastStopPacket(response);
3755                 process->ClearThreadIDList();
3756                 response.SetFilePos(1);
3757 
3758                 int exit_status = response.GetHexU8();
3759                 std::string desc_string;
3760                 if (response.GetBytesLeft() > 0 &&
3761                     response.GetChar('-') == ';') {
3762                   llvm::StringRef desc_str;
3763                   llvm::StringRef desc_token;
3764                   while (response.GetNameColonValue(desc_token, desc_str)) {
3765                     if (desc_token != "description")
3766                       continue;
3767                     StringExtractor extractor(desc_str);
3768                     extractor.GetHexByteString(desc_string);
3769                   }
3770                 }
3771                 process->SetExitStatus(exit_status, desc_string.c_str());
3772                 done = true;
3773                 break;
3774               }
3775               case eStateInvalid: {
3776                 // Check to see if we were trying to attach and if we got back
3777                 // the "E87" error code from debugserver -- this indicates that
3778                 // the process is not debuggable.  Return a slightly more
3779                 // helpful error message about why the attach failed.
3780                 if (::strstr(continue_cstr, "vAttach") != nullptr &&
3781                     response.GetError() == 0x87) {
3782                   process->SetExitStatus(-1, "cannot attach to process due to "
3783                                              "System Integrity Protection");
3784                 } else if (::strstr(continue_cstr, "vAttach") != nullptr &&
3785                            response.GetStatus().Fail()) {
3786                   process->SetExitStatus(-1, response.GetStatus().AsCString());
3787                 } else {
3788                   process->SetExitStatus(-1, "lost connection");
3789                 }
3790                 break;
3791               }
3792 
3793               default:
3794                 process->SetPrivateState(stop_state);
3795                 break;
3796               } // switch(stop_state)
3797             }   // else // if in All-stop-mode
3798           }     // if (continue_packet)
3799         }       // case eBroadcastBitAsyncContinue
3800         break;
3801 
3802         case eBroadcastBitAsyncThreadShouldExit:
3803           LLDB_LOGF(log,
3804                     "ProcessGDBRemote::%s (arg = %p, pid = %" PRIu64
3805                     ") got eBroadcastBitAsyncThreadShouldExit...",
3806                     __FUNCTION__, arg, process->GetID());
3807           done = true;
3808           break;
3809 
3810         default:
3811           LLDB_LOGF(log,
3812                     "ProcessGDBRemote::%s (arg = %p, pid = %" PRIu64
3813                     ") got unknown event 0x%8.8x",
3814                     __FUNCTION__, arg, process->GetID(), event_type);
3815           done = true;
3816           break;
3817         }
3818       } else if (event_sp->BroadcasterIs(&process->m_gdb_comm)) {
3819         switch (event_type) {
3820         case Communication::eBroadcastBitReadThreadDidExit:
3821           process->SetExitStatus(-1, "lost connection");
3822           done = true;
3823           break;
3824 
3825         case GDBRemoteCommunication::eBroadcastBitGdbReadThreadGotNotify: {
3826           lldb_private::Event *event = event_sp.get();
3827           const EventDataBytes *continue_packet =
3828               EventDataBytes::GetEventDataFromEvent(event);
3829           StringExtractorGDBRemote notify(
3830               (const char *)continue_packet->GetBytes());
3831           // Hand this over to the process to handle
3832           process->HandleNotifyPacket(notify);
3833           break;
3834         }
3835 
3836         default:
3837           LLDB_LOGF(log,
3838                     "ProcessGDBRemote::%s (arg = %p, pid = %" PRIu64
3839                     ") got unknown event 0x%8.8x",
3840                     __FUNCTION__, arg, process->GetID(), event_type);
3841           done = true;
3842           break;
3843         }
3844       }
3845     } else {
3846       LLDB_LOGF(log,
3847                 "ProcessGDBRemote::%s (arg = %p, pid = %" PRIu64
3848                 ") listener.WaitForEvent (NULL, event_sp) => false",
3849                 __FUNCTION__, arg, process->GetID());
3850       done = true;
3851     }
3852   }
3853 
3854   LLDB_LOGF(log,
3855             "ProcessGDBRemote::%s (arg = %p, pid = %" PRIu64
3856             ") thread exiting...",
3857             __FUNCTION__, arg, process->GetID());
3858 
3859   return {};
3860 }
3861 
3862 // uint32_t
3863 // ProcessGDBRemote::ListProcessesMatchingName (const char *name, StringList
3864 // &matches, std::vector<lldb::pid_t> &pids)
3865 //{
3866 //    // If we are planning to launch the debugserver remotely, then we need to
3867 //    fire up a debugserver
3868 //    // process and ask it for the list of processes. But if we are local, we
3869 //    can let the Host do it.
3870 //    if (m_local_debugserver)
3871 //    {
3872 //        return Host::ListProcessesMatchingName (name, matches, pids);
3873 //    }
3874 //    else
3875 //    {
3876 //        // FIXME: Implement talking to the remote debugserver.
3877 //        return 0;
3878 //    }
3879 //
3880 //}
3881 //
3882 bool ProcessGDBRemote::NewThreadNotifyBreakpointHit(
3883     void *baton, StoppointCallbackContext *context, lldb::user_id_t break_id,
3884     lldb::user_id_t break_loc_id) {
3885   // I don't think I have to do anything here, just make sure I notice the new
3886   // thread when it starts to
3887   // run so I can stop it if that's what I want to do.
3888   Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_STEP));
3889   LLDB_LOGF(log, "Hit New Thread Notification breakpoint.");
3890   return false;
3891 }
3892 
3893 Status ProcessGDBRemote::UpdateAutomaticSignalFiltering() {
3894   Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
3895   LLDB_LOG(log, "Check if need to update ignored signals");
3896 
3897   // QPassSignals package is not supported by the server, there is no way we
3898   // can ignore any signals on server side.
3899   if (!m_gdb_comm.GetQPassSignalsSupported())
3900     return Status();
3901 
3902   // No signals, nothing to send.
3903   if (m_unix_signals_sp == nullptr)
3904     return Status();
3905 
3906   // Signals' version hasn't changed, no need to send anything.
3907   uint64_t new_signals_version = m_unix_signals_sp->GetVersion();
3908   if (new_signals_version == m_last_signals_version) {
3909     LLDB_LOG(log, "Signals' version hasn't changed. version={0}",
3910              m_last_signals_version);
3911     return Status();
3912   }
3913 
3914   auto signals_to_ignore =
3915       m_unix_signals_sp->GetFilteredSignals(false, false, false);
3916   Status error = m_gdb_comm.SendSignalsToIgnore(signals_to_ignore);
3917 
3918   LLDB_LOG(log,
3919            "Signals' version changed. old version={0}, new version={1}, "
3920            "signals ignored={2}, update result={3}",
3921            m_last_signals_version, new_signals_version,
3922            signals_to_ignore.size(), error);
3923 
3924   if (error.Success())
3925     m_last_signals_version = new_signals_version;
3926 
3927   return error;
3928 }
3929 
3930 bool ProcessGDBRemote::StartNoticingNewThreads() {
3931   Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_STEP));
3932   if (m_thread_create_bp_sp) {
3933     if (log && log->GetVerbose())
3934       LLDB_LOGF(log, "Enabled noticing new thread breakpoint.");
3935     m_thread_create_bp_sp->SetEnabled(true);
3936   } else {
3937     PlatformSP platform_sp(GetTarget().GetPlatform());
3938     if (platform_sp) {
3939       m_thread_create_bp_sp =
3940           platform_sp->SetThreadCreationBreakpoint(GetTarget());
3941       if (m_thread_create_bp_sp) {
3942         if (log && log->GetVerbose())
3943           LLDB_LOGF(
3944               log, "Successfully created new thread notification breakpoint %i",
3945               m_thread_create_bp_sp->GetID());
3946         m_thread_create_bp_sp->SetCallback(
3947             ProcessGDBRemote::NewThreadNotifyBreakpointHit, this, true);
3948       } else {
3949         LLDB_LOGF(log, "Failed to create new thread notification breakpoint.");
3950       }
3951     }
3952   }
3953   return m_thread_create_bp_sp.get() != nullptr;
3954 }
3955 
3956 bool ProcessGDBRemote::StopNoticingNewThreads() {
3957   Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_STEP));
3958   if (log && log->GetVerbose())
3959     LLDB_LOGF(log, "Disabling new thread notification breakpoint.");
3960 
3961   if (m_thread_create_bp_sp)
3962     m_thread_create_bp_sp->SetEnabled(false);
3963 
3964   return true;
3965 }
3966 
3967 DynamicLoader *ProcessGDBRemote::GetDynamicLoader() {
3968   if (m_dyld_up.get() == nullptr)
3969     m_dyld_up.reset(DynamicLoader::FindPlugin(this, nullptr));
3970   return m_dyld_up.get();
3971 }
3972 
3973 Status ProcessGDBRemote::SendEventData(const char *data) {
3974   int return_value;
3975   bool was_supported;
3976 
3977   Status error;
3978 
3979   return_value = m_gdb_comm.SendLaunchEventDataPacket(data, &was_supported);
3980   if (return_value != 0) {
3981     if (!was_supported)
3982       error.SetErrorString("Sending events is not supported for this process.");
3983     else
3984       error.SetErrorStringWithFormat("Error sending event data: %d.",
3985                                      return_value);
3986   }
3987   return error;
3988 }
3989 
3990 DataExtractor ProcessGDBRemote::GetAuxvData() {
3991   DataBufferSP buf;
3992   if (m_gdb_comm.GetQXferAuxvReadSupported()) {
3993     std::string response_string;
3994     if (m_gdb_comm.SendPacketsAndConcatenateResponses("qXfer:auxv:read::",
3995                                                       response_string) ==
3996         GDBRemoteCommunication::PacketResult::Success)
3997       buf = std::make_shared<DataBufferHeap>(response_string.c_str(),
3998                                              response_string.length());
3999   }
4000   return DataExtractor(buf, GetByteOrder(), GetAddressByteSize());
4001 }
4002 
4003 StructuredData::ObjectSP
4004 ProcessGDBRemote::GetExtendedInfoForThread(lldb::tid_t tid) {
4005   StructuredData::ObjectSP object_sp;
4006 
4007   if (m_gdb_comm.GetThreadExtendedInfoSupported()) {
4008     StructuredData::ObjectSP args_dict(new StructuredData::Dictionary());
4009     SystemRuntime *runtime = GetSystemRuntime();
4010     if (runtime) {
4011       runtime->AddThreadExtendedInfoPacketHints(args_dict);
4012     }
4013     args_dict->GetAsDictionary()->AddIntegerItem("thread", tid);
4014 
4015     StreamString packet;
4016     packet << "jThreadExtendedInfo:";
4017     args_dict->Dump(packet, false);
4018 
4019     // FIXME the final character of a JSON dictionary, '}', is the escape
4020     // character in gdb-remote binary mode.  lldb currently doesn't escape
4021     // these characters in its packet output -- so we add the quoted version of
4022     // the } character here manually in case we talk to a debugserver which un-
4023     // escapes the characters at packet read time.
4024     packet << (char)(0x7d ^ 0x20);
4025 
4026     StringExtractorGDBRemote response;
4027     response.SetResponseValidatorToJSON();
4028     if (m_gdb_comm.SendPacketAndWaitForResponse(packet.GetString(), response,
4029                                                 false) ==
4030         GDBRemoteCommunication::PacketResult::Success) {
4031       StringExtractorGDBRemote::ResponseType response_type =
4032           response.GetResponseType();
4033       if (response_type == StringExtractorGDBRemote::eResponse) {
4034         if (!response.Empty()) {
4035           object_sp =
4036               StructuredData::ParseJSON(std::string(response.GetStringRef()));
4037         }
4038       }
4039     }
4040   }
4041   return object_sp;
4042 }
4043 
4044 StructuredData::ObjectSP ProcessGDBRemote::GetLoadedDynamicLibrariesInfos(
4045     lldb::addr_t image_list_address, lldb::addr_t image_count) {
4046 
4047   StructuredData::ObjectSP args_dict(new StructuredData::Dictionary());
4048   args_dict->GetAsDictionary()->AddIntegerItem("image_list_address",
4049                                                image_list_address);
4050   args_dict->GetAsDictionary()->AddIntegerItem("image_count", image_count);
4051 
4052   return GetLoadedDynamicLibrariesInfos_sender(args_dict);
4053 }
4054 
4055 StructuredData::ObjectSP ProcessGDBRemote::GetLoadedDynamicLibrariesInfos() {
4056   StructuredData::ObjectSP args_dict(new StructuredData::Dictionary());
4057 
4058   args_dict->GetAsDictionary()->AddBooleanItem("fetch_all_solibs", true);
4059 
4060   return GetLoadedDynamicLibrariesInfos_sender(args_dict);
4061 }
4062 
4063 StructuredData::ObjectSP ProcessGDBRemote::GetLoadedDynamicLibrariesInfos(
4064     const std::vector<lldb::addr_t> &load_addresses) {
4065   StructuredData::ObjectSP args_dict(new StructuredData::Dictionary());
4066   StructuredData::ArraySP addresses(new StructuredData::Array);
4067 
4068   for (auto addr : load_addresses) {
4069     StructuredData::ObjectSP addr_sp(new StructuredData::Integer(addr));
4070     addresses->AddItem(addr_sp);
4071   }
4072 
4073   args_dict->GetAsDictionary()->AddItem("solib_addresses", addresses);
4074 
4075   return GetLoadedDynamicLibrariesInfos_sender(args_dict);
4076 }
4077 
4078 StructuredData::ObjectSP
4079 ProcessGDBRemote::GetLoadedDynamicLibrariesInfos_sender(
4080     StructuredData::ObjectSP args_dict) {
4081   StructuredData::ObjectSP object_sp;
4082 
4083   if (m_gdb_comm.GetLoadedDynamicLibrariesInfosSupported()) {
4084     // Scope for the scoped timeout object
4085     GDBRemoteCommunication::ScopedTimeout timeout(m_gdb_comm,
4086                                                   std::chrono::seconds(10));
4087 
4088     StreamString packet;
4089     packet << "jGetLoadedDynamicLibrariesInfos:";
4090     args_dict->Dump(packet, false);
4091 
4092     // FIXME the final character of a JSON dictionary, '}', is the escape
4093     // character in gdb-remote binary mode.  lldb currently doesn't escape
4094     // these characters in its packet output -- so we add the quoted version of
4095     // the } character here manually in case we talk to a debugserver which un-
4096     // escapes the characters at packet read time.
4097     packet << (char)(0x7d ^ 0x20);
4098 
4099     StringExtractorGDBRemote response;
4100     response.SetResponseValidatorToJSON();
4101     if (m_gdb_comm.SendPacketAndWaitForResponse(packet.GetString(), response,
4102                                                 false) ==
4103         GDBRemoteCommunication::PacketResult::Success) {
4104       StringExtractorGDBRemote::ResponseType response_type =
4105           response.GetResponseType();
4106       if (response_type == StringExtractorGDBRemote::eResponse) {
4107         if (!response.Empty()) {
4108           object_sp =
4109               StructuredData::ParseJSON(std::string(response.GetStringRef()));
4110         }
4111       }
4112     }
4113   }
4114   return object_sp;
4115 }
4116 
4117 StructuredData::ObjectSP ProcessGDBRemote::GetSharedCacheInfo() {
4118   StructuredData::ObjectSP object_sp;
4119   StructuredData::ObjectSP args_dict(new StructuredData::Dictionary());
4120 
4121   if (m_gdb_comm.GetSharedCacheInfoSupported()) {
4122     StreamString packet;
4123     packet << "jGetSharedCacheInfo:";
4124     args_dict->Dump(packet, false);
4125 
4126     // FIXME the final character of a JSON dictionary, '}', is the escape
4127     // character in gdb-remote binary mode.  lldb currently doesn't escape
4128     // these characters in its packet output -- so we add the quoted version of
4129     // the } character here manually in case we talk to a debugserver which un-
4130     // escapes the characters at packet read time.
4131     packet << (char)(0x7d ^ 0x20);
4132 
4133     StringExtractorGDBRemote response;
4134     response.SetResponseValidatorToJSON();
4135     if (m_gdb_comm.SendPacketAndWaitForResponse(packet.GetString(), response,
4136                                                 false) ==
4137         GDBRemoteCommunication::PacketResult::Success) {
4138       StringExtractorGDBRemote::ResponseType response_type =
4139           response.GetResponseType();
4140       if (response_type == StringExtractorGDBRemote::eResponse) {
4141         if (!response.Empty()) {
4142           object_sp =
4143               StructuredData::ParseJSON(std::string(response.GetStringRef()));
4144         }
4145       }
4146     }
4147   }
4148   return object_sp;
4149 }
4150 
4151 Status ProcessGDBRemote::ConfigureStructuredData(
4152     ConstString type_name, const StructuredData::ObjectSP &config_sp) {
4153   return m_gdb_comm.ConfigureRemoteStructuredData(type_name, config_sp);
4154 }
4155 
4156 // Establish the largest memory read/write payloads we should use. If the
4157 // remote stub has a max packet size, stay under that size.
4158 //
4159 // If the remote stub's max packet size is crazy large, use a reasonable
4160 // largeish default.
4161 //
4162 // If the remote stub doesn't advertise a max packet size, use a conservative
4163 // default.
4164 
4165 void ProcessGDBRemote::GetMaxMemorySize() {
4166   const uint64_t reasonable_largeish_default = 128 * 1024;
4167   const uint64_t conservative_default = 512;
4168 
4169   if (m_max_memory_size == 0) {
4170     uint64_t stub_max_size = m_gdb_comm.GetRemoteMaxPacketSize();
4171     if (stub_max_size != UINT64_MAX && stub_max_size != 0) {
4172       // Save the stub's claimed maximum packet size
4173       m_remote_stub_max_memory_size = stub_max_size;
4174 
4175       // Even if the stub says it can support ginormous packets, don't exceed
4176       // our reasonable largeish default packet size.
4177       if (stub_max_size > reasonable_largeish_default) {
4178         stub_max_size = reasonable_largeish_default;
4179       }
4180 
4181       // Memory packet have other overheads too like Maddr,size:#NN Instead of
4182       // calculating the bytes taken by size and addr every time, we take a
4183       // maximum guess here.
4184       if (stub_max_size > 70)
4185         stub_max_size -= 32 + 32 + 6;
4186       else {
4187         // In unlikely scenario that max packet size is less then 70, we will
4188         // hope that data being written is small enough to fit.
4189         Log *log(ProcessGDBRemoteLog::GetLogIfAnyCategoryIsSet(
4190             GDBR_LOG_COMM | GDBR_LOG_MEMORY));
4191         if (log)
4192           log->Warning("Packet size is too small. "
4193                        "LLDB may face problems while writing memory");
4194       }
4195 
4196       m_max_memory_size = stub_max_size;
4197     } else {
4198       m_max_memory_size = conservative_default;
4199     }
4200   }
4201 }
4202 
4203 void ProcessGDBRemote::SetUserSpecifiedMaxMemoryTransferSize(
4204     uint64_t user_specified_max) {
4205   if (user_specified_max != 0) {
4206     GetMaxMemorySize();
4207 
4208     if (m_remote_stub_max_memory_size != 0) {
4209       if (m_remote_stub_max_memory_size < user_specified_max) {
4210         m_max_memory_size = m_remote_stub_max_memory_size; // user specified a
4211                                                            // packet size too
4212                                                            // big, go as big
4213         // as the remote stub says we can go.
4214       } else {
4215         m_max_memory_size = user_specified_max; // user's packet size is good
4216       }
4217     } else {
4218       m_max_memory_size =
4219           user_specified_max; // user's packet size is probably fine
4220     }
4221   }
4222 }
4223 
4224 bool ProcessGDBRemote::GetModuleSpec(const FileSpec &module_file_spec,
4225                                      const ArchSpec &arch,
4226                                      ModuleSpec &module_spec) {
4227   Log *log = GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PLATFORM);
4228 
4229   const ModuleCacheKey key(module_file_spec.GetPath(),
4230                            arch.GetTriple().getTriple());
4231   auto cached = m_cached_module_specs.find(key);
4232   if (cached != m_cached_module_specs.end()) {
4233     module_spec = cached->second;
4234     return bool(module_spec);
4235   }
4236 
4237   if (!m_gdb_comm.GetModuleInfo(module_file_spec, arch, module_spec)) {
4238     LLDB_LOGF(log, "ProcessGDBRemote::%s - failed to get module info for %s:%s",
4239               __FUNCTION__, module_file_spec.GetPath().c_str(),
4240               arch.GetTriple().getTriple().c_str());
4241     return false;
4242   }
4243 
4244   if (log) {
4245     StreamString stream;
4246     module_spec.Dump(stream);
4247     LLDB_LOGF(log, "ProcessGDBRemote::%s - got module info for (%s:%s) : %s",
4248               __FUNCTION__, module_file_spec.GetPath().c_str(),
4249               arch.GetTriple().getTriple().c_str(), stream.GetData());
4250   }
4251 
4252   m_cached_module_specs[key] = module_spec;
4253   return true;
4254 }
4255 
4256 void ProcessGDBRemote::PrefetchModuleSpecs(
4257     llvm::ArrayRef<FileSpec> module_file_specs, const llvm::Triple &triple) {
4258   auto module_specs = m_gdb_comm.GetModulesInfo(module_file_specs, triple);
4259   if (module_specs) {
4260     for (const FileSpec &spec : module_file_specs)
4261       m_cached_module_specs[ModuleCacheKey(spec.GetPath(),
4262                                            triple.getTriple())] = ModuleSpec();
4263     for (const ModuleSpec &spec : *module_specs)
4264       m_cached_module_specs[ModuleCacheKey(spec.GetFileSpec().GetPath(),
4265                                            triple.getTriple())] = spec;
4266   }
4267 }
4268 
4269 llvm::VersionTuple ProcessGDBRemote::GetHostOSVersion() {
4270   return m_gdb_comm.GetOSVersion();
4271 }
4272 
4273 llvm::VersionTuple ProcessGDBRemote::GetHostMacCatalystVersion() {
4274   return m_gdb_comm.GetMacCatalystVersion();
4275 }
4276 
4277 namespace {
4278 
4279 typedef std::vector<std::string> stringVec;
4280 
4281 typedef std::vector<struct GdbServerRegisterInfo> GDBServerRegisterVec;
4282 struct RegisterSetInfo {
4283   ConstString name;
4284 };
4285 
4286 typedef std::map<uint32_t, RegisterSetInfo> RegisterSetMap;
4287 
4288 struct GdbServerTargetInfo {
4289   std::string arch;
4290   std::string osabi;
4291   stringVec includes;
4292   RegisterSetMap reg_set_map;
4293 };
4294 
4295 bool ParseRegisters(XMLNode feature_node, GdbServerTargetInfo &target_info,
4296                     GDBRemoteDynamicRegisterInfo &dyn_reg_info, ABISP abi_sp,
4297                     uint32_t &reg_num_remote, uint32_t &reg_num_local) {
4298   if (!feature_node)
4299     return false;
4300 
4301   uint32_t reg_offset = LLDB_INVALID_INDEX32;
4302   feature_node.ForEachChildElementWithName(
4303       "reg", [&target_info, &dyn_reg_info, &reg_num_remote, &reg_num_local,
4304               &reg_offset, &abi_sp](const XMLNode &reg_node) -> bool {
4305         std::string gdb_group;
4306         std::string gdb_type;
4307         ConstString reg_name;
4308         ConstString alt_name;
4309         ConstString set_name;
4310         std::vector<uint32_t> value_regs;
4311         std::vector<uint32_t> invalidate_regs;
4312         std::vector<uint8_t> dwarf_opcode_bytes;
4313         bool encoding_set = false;
4314         bool format_set = false;
4315         RegisterInfo reg_info = {
4316             nullptr,       // Name
4317             nullptr,       // Alt name
4318             0,             // byte size
4319             reg_offset,    // offset
4320             eEncodingUint, // encoding
4321             eFormatHex,    // format
4322             {
4323                 LLDB_INVALID_REGNUM, // eh_frame reg num
4324                 LLDB_INVALID_REGNUM, // DWARF reg num
4325                 LLDB_INVALID_REGNUM, // generic reg num
4326                 reg_num_remote,      // process plugin reg num
4327                 reg_num_local        // native register number
4328             },
4329             nullptr,
4330             nullptr,
4331             nullptr, // Dwarf Expression opcode bytes pointer
4332             0        // Dwarf Expression opcode bytes length
4333         };
4334 
4335         reg_node.ForEachAttribute([&target_info, &gdb_group, &gdb_type,
4336                                    &reg_name, &alt_name, &set_name, &value_regs,
4337                                    &invalidate_regs, &encoding_set, &format_set,
4338                                    &reg_info, &reg_offset, &dwarf_opcode_bytes](
4339                                       const llvm::StringRef &name,
4340                                       const llvm::StringRef &value) -> bool {
4341           if (name == "name") {
4342             reg_name.SetString(value);
4343           } else if (name == "bitsize") {
4344             reg_info.byte_size =
4345                 StringConvert::ToUInt32(value.data(), 0, 0) / CHAR_BIT;
4346           } else if (name == "type") {
4347             gdb_type = value.str();
4348           } else if (name == "group") {
4349             gdb_group = value.str();
4350           } else if (name == "regnum") {
4351             const uint32_t regnum =
4352                 StringConvert::ToUInt32(value.data(), LLDB_INVALID_REGNUM, 0);
4353             if (regnum != LLDB_INVALID_REGNUM) {
4354               reg_info.kinds[eRegisterKindProcessPlugin] = regnum;
4355             }
4356           } else if (name == "offset") {
4357             reg_offset = StringConvert::ToUInt32(value.data(), UINT32_MAX, 0);
4358           } else if (name == "altname") {
4359             alt_name.SetString(value);
4360           } else if (name == "encoding") {
4361             encoding_set = true;
4362             reg_info.encoding = Args::StringToEncoding(value, eEncodingUint);
4363           } else if (name == "format") {
4364             format_set = true;
4365             Format format = eFormatInvalid;
4366             if (OptionArgParser::ToFormat(value.data(), format, nullptr)
4367                     .Success())
4368               reg_info.format = format;
4369             else if (value == "vector-sint8")
4370               reg_info.format = eFormatVectorOfSInt8;
4371             else if (value == "vector-uint8")
4372               reg_info.format = eFormatVectorOfUInt8;
4373             else if (value == "vector-sint16")
4374               reg_info.format = eFormatVectorOfSInt16;
4375             else if (value == "vector-uint16")
4376               reg_info.format = eFormatVectorOfUInt16;
4377             else if (value == "vector-sint32")
4378               reg_info.format = eFormatVectorOfSInt32;
4379             else if (value == "vector-uint32")
4380               reg_info.format = eFormatVectorOfUInt32;
4381             else if (value == "vector-float32")
4382               reg_info.format = eFormatVectorOfFloat32;
4383             else if (value == "vector-uint64")
4384               reg_info.format = eFormatVectorOfUInt64;
4385             else if (value == "vector-uint128")
4386               reg_info.format = eFormatVectorOfUInt128;
4387           } else if (name == "group_id") {
4388             const uint32_t set_id =
4389                 StringConvert::ToUInt32(value.data(), UINT32_MAX, 0);
4390             RegisterSetMap::const_iterator pos =
4391                 target_info.reg_set_map.find(set_id);
4392             if (pos != target_info.reg_set_map.end())
4393               set_name = pos->second.name;
4394           } else if (name == "gcc_regnum" || name == "ehframe_regnum") {
4395             reg_info.kinds[eRegisterKindEHFrame] =
4396                 StringConvert::ToUInt32(value.data(), LLDB_INVALID_REGNUM, 0);
4397           } else if (name == "dwarf_regnum") {
4398             reg_info.kinds[eRegisterKindDWARF] =
4399                 StringConvert::ToUInt32(value.data(), LLDB_INVALID_REGNUM, 0);
4400           } else if (name == "generic") {
4401             reg_info.kinds[eRegisterKindGeneric] =
4402                 Args::StringToGenericRegister(value);
4403           } else if (name == "value_regnums") {
4404             SplitCommaSeparatedRegisterNumberString(value, value_regs, 0);
4405           } else if (name == "invalidate_regnums") {
4406             SplitCommaSeparatedRegisterNumberString(value, invalidate_regs, 0);
4407           } else if (name == "dynamic_size_dwarf_expr_bytes") {
4408             std::string opcode_string = value.str();
4409             size_t dwarf_opcode_len = opcode_string.length() / 2;
4410             assert(dwarf_opcode_len > 0);
4411 
4412             dwarf_opcode_bytes.resize(dwarf_opcode_len);
4413             reg_info.dynamic_size_dwarf_len = dwarf_opcode_len;
4414             StringExtractor opcode_extractor(opcode_string);
4415             uint32_t ret_val =
4416                 opcode_extractor.GetHexBytesAvail(dwarf_opcode_bytes);
4417             assert(dwarf_opcode_len == ret_val);
4418             UNUSED_IF_ASSERT_DISABLED(ret_val);
4419             reg_info.dynamic_size_dwarf_expr_bytes = dwarf_opcode_bytes.data();
4420           } else {
4421             printf("unhandled attribute %s = %s\n", name.data(), value.data());
4422           }
4423           return true; // Keep iterating through all attributes
4424         });
4425 
4426         if (!gdb_type.empty() && !(encoding_set || format_set)) {
4427           if (llvm::StringRef(gdb_type).startswith("int")) {
4428             reg_info.format = eFormatHex;
4429             reg_info.encoding = eEncodingUint;
4430           } else if (gdb_type == "data_ptr" || gdb_type == "code_ptr") {
4431             reg_info.format = eFormatAddressInfo;
4432             reg_info.encoding = eEncodingUint;
4433           } else if (gdb_type == "i387_ext" || gdb_type == "float") {
4434             reg_info.format = eFormatFloat;
4435             reg_info.encoding = eEncodingIEEE754;
4436           }
4437         }
4438 
4439         // Only update the register set name if we didn't get a "reg_set"
4440         // attribute. "set_name" will be empty if we didn't have a "reg_set"
4441         // attribute.
4442         if (!set_name) {
4443           if (!gdb_group.empty()) {
4444             set_name.SetCString(gdb_group.c_str());
4445           } else {
4446             // If no register group name provided anywhere,
4447             // we'll create a 'general' register set
4448             set_name.SetCString("general");
4449           }
4450         }
4451 
4452         reg_info.byte_offset = reg_offset;
4453         assert(reg_info.byte_size != 0);
4454         reg_offset = LLDB_INVALID_INDEX32;
4455         if (!value_regs.empty()) {
4456           value_regs.push_back(LLDB_INVALID_REGNUM);
4457           reg_info.value_regs = value_regs.data();
4458         }
4459         if (!invalidate_regs.empty()) {
4460           invalidate_regs.push_back(LLDB_INVALID_REGNUM);
4461           reg_info.invalidate_regs = invalidate_regs.data();
4462         }
4463 
4464         reg_num_remote = reg_info.kinds[eRegisterKindProcessPlugin] + 1;
4465         ++reg_num_local;
4466         reg_info.name = reg_name.AsCString();
4467         if (abi_sp)
4468           abi_sp->AugmentRegisterInfo(reg_info);
4469         dyn_reg_info.AddRegister(reg_info, reg_name, alt_name, set_name);
4470 
4471         return true; // Keep iterating through all "reg" elements
4472       });
4473   return true;
4474 }
4475 
4476 } // namespace
4477 
4478 // This method fetches a register description feature xml file from
4479 // the remote stub and adds registers/register groupsets/architecture
4480 // information to the current process.  It will call itself recursively
4481 // for nested register definition files.  It returns true if it was able
4482 // to fetch and parse an xml file.
4483 bool ProcessGDBRemote::GetGDBServerRegisterInfoXMLAndProcess(
4484     ArchSpec &arch_to_use, std::string xml_filename, uint32_t &reg_num_remote,
4485     uint32_t &reg_num_local) {
4486   // request the target xml file
4487   std::string raw;
4488   lldb_private::Status lldberr;
4489   if (!m_gdb_comm.ReadExtFeature(ConstString("features"),
4490                                  ConstString(xml_filename.c_str()), raw,
4491                                  lldberr)) {
4492     return false;
4493   }
4494 
4495   XMLDocument xml_document;
4496 
4497   if (xml_document.ParseMemory(raw.c_str(), raw.size(), xml_filename.c_str())) {
4498     GdbServerTargetInfo target_info;
4499     std::vector<XMLNode> feature_nodes;
4500 
4501     // The top level feature XML file will start with a <target> tag.
4502     XMLNode target_node = xml_document.GetRootElement("target");
4503     if (target_node) {
4504       target_node.ForEachChildElement([&target_info, &feature_nodes](
4505                                           const XMLNode &node) -> bool {
4506         llvm::StringRef name = node.GetName();
4507         if (name == "architecture") {
4508           node.GetElementText(target_info.arch);
4509         } else if (name == "osabi") {
4510           node.GetElementText(target_info.osabi);
4511         } else if (name == "xi:include" || name == "include") {
4512           llvm::StringRef href = node.GetAttributeValue("href");
4513           if (!href.empty())
4514             target_info.includes.push_back(href.str());
4515         } else if (name == "feature") {
4516           feature_nodes.push_back(node);
4517         } else if (name == "groups") {
4518           node.ForEachChildElementWithName(
4519               "group", [&target_info](const XMLNode &node) -> bool {
4520                 uint32_t set_id = UINT32_MAX;
4521                 RegisterSetInfo set_info;
4522 
4523                 node.ForEachAttribute(
4524                     [&set_id, &set_info](const llvm::StringRef &name,
4525                                          const llvm::StringRef &value) -> bool {
4526                       if (name == "id")
4527                         set_id = StringConvert::ToUInt32(value.data(),
4528                                                          UINT32_MAX, 0);
4529                       if (name == "name")
4530                         set_info.name = ConstString(value);
4531                       return true; // Keep iterating through all attributes
4532                     });
4533 
4534                 if (set_id != UINT32_MAX)
4535                   target_info.reg_set_map[set_id] = set_info;
4536                 return true; // Keep iterating through all "group" elements
4537               });
4538         }
4539         return true; // Keep iterating through all children of the target_node
4540       });
4541     } else {
4542       // In an included XML feature file, we're already "inside" the <target>
4543       // tag of the initial XML file; this included file will likely only have
4544       // a <feature> tag.  Need to check for any more included files in this
4545       // <feature> element.
4546       XMLNode feature_node = xml_document.GetRootElement("feature");
4547       if (feature_node) {
4548         feature_nodes.push_back(feature_node);
4549         feature_node.ForEachChildElement([&target_info](
4550                                         const XMLNode &node) -> bool {
4551           llvm::StringRef name = node.GetName();
4552           if (name == "xi:include" || name == "include") {
4553             llvm::StringRef href = node.GetAttributeValue("href");
4554             if (!href.empty())
4555               target_info.includes.push_back(href.str());
4556             }
4557             return true;
4558           });
4559       }
4560     }
4561 
4562     // If the target.xml includes an architecture entry like
4563     //   <architecture>i386:x86-64</architecture> (seen from VMWare ESXi)
4564     //   <architecture>arm</architecture> (seen from Segger JLink on unspecified arm board)
4565     // use that if we don't have anything better.
4566     if (!arch_to_use.IsValid() && !target_info.arch.empty()) {
4567       if (target_info.arch == "i386:x86-64") {
4568         // We don't have any information about vendor or OS.
4569         arch_to_use.SetTriple("x86_64--");
4570         GetTarget().MergeArchitecture(arch_to_use);
4571       }
4572 
4573       // SEGGER J-Link jtag boards send this very-generic arch name,
4574       // we'll need to use this if we have absolutely nothing better
4575       // to work with or the register definitions won't be accepted.
4576       if (target_info.arch == "arm") {
4577         arch_to_use.SetTriple("arm--");
4578         GetTarget().MergeArchitecture(arch_to_use);
4579       }
4580     }
4581 
4582     if (arch_to_use.IsValid()) {
4583       // Don't use Process::GetABI, this code gets called from DidAttach, and
4584       // in that context we haven't set the Target's architecture yet, so the
4585       // ABI is also potentially incorrect.
4586       ABISP abi_to_use_sp = ABI::FindPlugin(shared_from_this(), arch_to_use);
4587       for (auto &feature_node : feature_nodes) {
4588         ParseRegisters(feature_node, target_info, *this->m_register_info_sp,
4589                        abi_to_use_sp, reg_num_remote, reg_num_local);
4590       }
4591 
4592       for (const auto &include : target_info.includes) {
4593         GetGDBServerRegisterInfoXMLAndProcess(arch_to_use, include,
4594                                               reg_num_remote, reg_num_local);
4595       }
4596     }
4597   } else {
4598     return false;
4599   }
4600   return true;
4601 }
4602 
4603 // query the target of gdb-remote for extended target information returns
4604 // true on success (got register definitions), false on failure (did not).
4605 bool ProcessGDBRemote::GetGDBServerRegisterInfo(ArchSpec &arch_to_use) {
4606   // Make sure LLDB has an XML parser it can use first
4607   if (!XMLDocument::XMLEnabled())
4608     return false;
4609 
4610   // check that we have extended feature read support
4611   if (!m_gdb_comm.GetQXferFeaturesReadSupported())
4612     return false;
4613 
4614   uint32_t reg_num_remote = 0;
4615   uint32_t reg_num_local = 0;
4616   if (GetGDBServerRegisterInfoXMLAndProcess(arch_to_use, "target.xml",
4617                                             reg_num_remote, reg_num_local))
4618     this->m_register_info_sp->Finalize(arch_to_use);
4619 
4620   return m_register_info_sp->GetNumRegisters() > 0;
4621 }
4622 
4623 llvm::Expected<LoadedModuleInfoList> ProcessGDBRemote::GetLoadedModuleList() {
4624   // Make sure LLDB has an XML parser it can use first
4625   if (!XMLDocument::XMLEnabled())
4626     return llvm::createStringError(llvm::inconvertibleErrorCode(),
4627                                    "XML parsing not available");
4628 
4629   Log *log = GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS);
4630   LLDB_LOGF(log, "ProcessGDBRemote::%s", __FUNCTION__);
4631 
4632   LoadedModuleInfoList list;
4633   GDBRemoteCommunicationClient &comm = m_gdb_comm;
4634   bool can_use_svr4 = GetGlobalPluginProperties()->GetUseSVR4();
4635 
4636   // check that we have extended feature read support
4637   if (can_use_svr4 && comm.GetQXferLibrariesSVR4ReadSupported()) {
4638     // request the loaded library list
4639     std::string raw;
4640     lldb_private::Status lldberr;
4641 
4642     if (!comm.ReadExtFeature(ConstString("libraries-svr4"), ConstString(""),
4643                              raw, lldberr))
4644       return llvm::createStringError(llvm::inconvertibleErrorCode(),
4645                                      "Error in libraries-svr4 packet");
4646 
4647     // parse the xml file in memory
4648     LLDB_LOGF(log, "parsing: %s", raw.c_str());
4649     XMLDocument doc;
4650 
4651     if (!doc.ParseMemory(raw.c_str(), raw.size(), "noname.xml"))
4652       return llvm::createStringError(llvm::inconvertibleErrorCode(),
4653                                      "Error reading noname.xml");
4654 
4655     XMLNode root_element = doc.GetRootElement("library-list-svr4");
4656     if (!root_element)
4657       return llvm::createStringError(
4658           llvm::inconvertibleErrorCode(),
4659           "Error finding library-list-svr4 xml element");
4660 
4661     // main link map structure
4662     llvm::StringRef main_lm = root_element.GetAttributeValue("main-lm");
4663     if (!main_lm.empty()) {
4664       list.m_link_map =
4665           StringConvert::ToUInt64(main_lm.data(), LLDB_INVALID_ADDRESS, 0);
4666     }
4667 
4668     root_element.ForEachChildElementWithName(
4669         "library", [log, &list](const XMLNode &library) -> bool {
4670 
4671           LoadedModuleInfoList::LoadedModuleInfo module;
4672 
4673           library.ForEachAttribute(
4674               [&module](const llvm::StringRef &name,
4675                         const llvm::StringRef &value) -> bool {
4676 
4677                 if (name == "name")
4678                   module.set_name(value.str());
4679                 else if (name == "lm") {
4680                   // the address of the link_map struct.
4681                   module.set_link_map(StringConvert::ToUInt64(
4682                       value.data(), LLDB_INVALID_ADDRESS, 0));
4683                 } else if (name == "l_addr") {
4684                   // the displacement as read from the field 'l_addr' of the
4685                   // link_map struct.
4686                   module.set_base(StringConvert::ToUInt64(
4687                       value.data(), LLDB_INVALID_ADDRESS, 0));
4688                   // base address is always a displacement, not an absolute
4689                   // value.
4690                   module.set_base_is_offset(true);
4691                 } else if (name == "l_ld") {
4692                   // the memory address of the libraries PT_DYNAMIC section.
4693                   module.set_dynamic(StringConvert::ToUInt64(
4694                       value.data(), LLDB_INVALID_ADDRESS, 0));
4695                 }
4696 
4697                 return true; // Keep iterating over all properties of "library"
4698               });
4699 
4700           if (log) {
4701             std::string name;
4702             lldb::addr_t lm = 0, base = 0, ld = 0;
4703             bool base_is_offset;
4704 
4705             module.get_name(name);
4706             module.get_link_map(lm);
4707             module.get_base(base);
4708             module.get_base_is_offset(base_is_offset);
4709             module.get_dynamic(ld);
4710 
4711             LLDB_LOGF(log,
4712                       "found (link_map:0x%08" PRIx64 ", base:0x%08" PRIx64
4713                       "[%s], ld:0x%08" PRIx64 ", name:'%s')",
4714                       lm, base, (base_is_offset ? "offset" : "absolute"), ld,
4715                       name.c_str());
4716           }
4717 
4718           list.add(module);
4719           return true; // Keep iterating over all "library" elements in the root
4720                        // node
4721         });
4722 
4723     if (log)
4724       LLDB_LOGF(log, "found %" PRId32 " modules in total",
4725                 (int)list.m_list.size());
4726     return list;
4727   } else if (comm.GetQXferLibrariesReadSupported()) {
4728     // request the loaded library list
4729     std::string raw;
4730     lldb_private::Status lldberr;
4731 
4732     if (!comm.ReadExtFeature(ConstString("libraries"), ConstString(""), raw,
4733                              lldberr))
4734       return llvm::createStringError(llvm::inconvertibleErrorCode(),
4735                                      "Error in libraries packet");
4736 
4737     LLDB_LOGF(log, "parsing: %s", raw.c_str());
4738     XMLDocument doc;
4739 
4740     if (!doc.ParseMemory(raw.c_str(), raw.size(), "noname.xml"))
4741       return llvm::createStringError(llvm::inconvertibleErrorCode(),
4742                                      "Error reading noname.xml");
4743 
4744     XMLNode root_element = doc.GetRootElement("library-list");
4745     if (!root_element)
4746       return llvm::createStringError(llvm::inconvertibleErrorCode(),
4747                                      "Error finding library-list xml element");
4748 
4749     root_element.ForEachChildElementWithName(
4750         "library", [log, &list](const XMLNode &library) -> bool {
4751           LoadedModuleInfoList::LoadedModuleInfo module;
4752 
4753           llvm::StringRef name = library.GetAttributeValue("name");
4754           module.set_name(name.str());
4755 
4756           // The base address of a given library will be the address of its
4757           // first section. Most remotes send only one section for Windows
4758           // targets for example.
4759           const XMLNode &section =
4760               library.FindFirstChildElementWithName("section");
4761           llvm::StringRef address = section.GetAttributeValue("address");
4762           module.set_base(
4763               StringConvert::ToUInt64(address.data(), LLDB_INVALID_ADDRESS, 0));
4764           // These addresses are absolute values.
4765           module.set_base_is_offset(false);
4766 
4767           if (log) {
4768             std::string name;
4769             lldb::addr_t base = 0;
4770             bool base_is_offset;
4771             module.get_name(name);
4772             module.get_base(base);
4773             module.get_base_is_offset(base_is_offset);
4774 
4775             LLDB_LOGF(log, "found (base:0x%08" PRIx64 "[%s], name:'%s')", base,
4776                       (base_is_offset ? "offset" : "absolute"), name.c_str());
4777           }
4778 
4779           list.add(module);
4780           return true; // Keep iterating over all "library" elements in the root
4781                        // node
4782         });
4783 
4784     if (log)
4785       LLDB_LOGF(log, "found %" PRId32 " modules in total",
4786                 (int)list.m_list.size());
4787     return list;
4788   } else {
4789     return llvm::createStringError(llvm::inconvertibleErrorCode(),
4790                                    "Remote libraries not supported");
4791   }
4792 }
4793 
4794 lldb::ModuleSP ProcessGDBRemote::LoadModuleAtAddress(const FileSpec &file,
4795                                                      lldb::addr_t link_map,
4796                                                      lldb::addr_t base_addr,
4797                                                      bool value_is_offset) {
4798   DynamicLoader *loader = GetDynamicLoader();
4799   if (!loader)
4800     return nullptr;
4801 
4802   return loader->LoadModuleAtAddress(file, link_map, base_addr,
4803                                      value_is_offset);
4804 }
4805 
4806 llvm::Error ProcessGDBRemote::LoadModules() {
4807   using lldb_private::process_gdb_remote::ProcessGDBRemote;
4808 
4809   // request a list of loaded libraries from GDBServer
4810   llvm::Expected<LoadedModuleInfoList> module_list = GetLoadedModuleList();
4811   if (!module_list)
4812     return module_list.takeError();
4813 
4814   // get a list of all the modules
4815   ModuleList new_modules;
4816 
4817   for (LoadedModuleInfoList::LoadedModuleInfo &modInfo : module_list->m_list) {
4818     std::string mod_name;
4819     lldb::addr_t mod_base;
4820     lldb::addr_t link_map;
4821     bool mod_base_is_offset;
4822 
4823     bool valid = true;
4824     valid &= modInfo.get_name(mod_name);
4825     valid &= modInfo.get_base(mod_base);
4826     valid &= modInfo.get_base_is_offset(mod_base_is_offset);
4827     if (!valid)
4828       continue;
4829 
4830     if (!modInfo.get_link_map(link_map))
4831       link_map = LLDB_INVALID_ADDRESS;
4832 
4833     FileSpec file(mod_name);
4834     FileSystem::Instance().Resolve(file);
4835     lldb::ModuleSP module_sp =
4836         LoadModuleAtAddress(file, link_map, mod_base, mod_base_is_offset);
4837 
4838     if (module_sp.get())
4839       new_modules.Append(module_sp);
4840   }
4841 
4842   if (new_modules.GetSize() > 0) {
4843     ModuleList removed_modules;
4844     Target &target = GetTarget();
4845     ModuleList &loaded_modules = m_process->GetTarget().GetImages();
4846 
4847     for (size_t i = 0; i < loaded_modules.GetSize(); ++i) {
4848       const lldb::ModuleSP loaded_module = loaded_modules.GetModuleAtIndex(i);
4849 
4850       bool found = false;
4851       for (size_t j = 0; j < new_modules.GetSize(); ++j) {
4852         if (new_modules.GetModuleAtIndex(j).get() == loaded_module.get())
4853           found = true;
4854       }
4855 
4856       // The main executable will never be included in libraries-svr4, don't
4857       // remove it
4858       if (!found &&
4859           loaded_module.get() != target.GetExecutableModulePointer()) {
4860         removed_modules.Append(loaded_module);
4861       }
4862     }
4863 
4864     loaded_modules.Remove(removed_modules);
4865     m_process->GetTarget().ModulesDidUnload(removed_modules, false);
4866 
4867     new_modules.ForEach([&target](const lldb::ModuleSP module_sp) -> bool {
4868       lldb_private::ObjectFile *obj = module_sp->GetObjectFile();
4869       if (!obj)
4870         return true;
4871 
4872       if (obj->GetType() != ObjectFile::Type::eTypeExecutable)
4873         return true;
4874 
4875       lldb::ModuleSP module_copy_sp = module_sp;
4876       target.SetExecutableModule(module_copy_sp, eLoadDependentsNo);
4877       return false;
4878     });
4879 
4880     loaded_modules.AppendIfNeeded(new_modules);
4881     m_process->GetTarget().ModulesDidLoad(new_modules);
4882   }
4883 
4884   return llvm::ErrorSuccess();
4885 }
4886 
4887 Status ProcessGDBRemote::GetFileLoadAddress(const FileSpec &file,
4888                                             bool &is_loaded,
4889                                             lldb::addr_t &load_addr) {
4890   is_loaded = false;
4891   load_addr = LLDB_INVALID_ADDRESS;
4892 
4893   std::string file_path = file.GetPath(false);
4894   if (file_path.empty())
4895     return Status("Empty file name specified");
4896 
4897   StreamString packet;
4898   packet.PutCString("qFileLoadAddress:");
4899   packet.PutStringAsRawHex8(file_path);
4900 
4901   StringExtractorGDBRemote response;
4902   if (m_gdb_comm.SendPacketAndWaitForResponse(packet.GetString(), response,
4903                                               false) !=
4904       GDBRemoteCommunication::PacketResult::Success)
4905     return Status("Sending qFileLoadAddress packet failed");
4906 
4907   if (response.IsErrorResponse()) {
4908     if (response.GetError() == 1) {
4909       // The file is not loaded into the inferior
4910       is_loaded = false;
4911       load_addr = LLDB_INVALID_ADDRESS;
4912       return Status();
4913     }
4914 
4915     return Status(
4916         "Fetching file load address from remote server returned an error");
4917   }
4918 
4919   if (response.IsNormalResponse()) {
4920     is_loaded = true;
4921     load_addr = response.GetHexMaxU64(false, LLDB_INVALID_ADDRESS);
4922     return Status();
4923   }
4924 
4925   return Status(
4926       "Unknown error happened during sending the load address packet");
4927 }
4928 
4929 void ProcessGDBRemote::ModulesDidLoad(ModuleList &module_list) {
4930   // We must call the lldb_private::Process::ModulesDidLoad () first before we
4931   // do anything
4932   Process::ModulesDidLoad(module_list);
4933 
4934   // After loading shared libraries, we can ask our remote GDB server if it
4935   // needs any symbols.
4936   m_gdb_comm.ServeSymbolLookups(this);
4937 }
4938 
4939 void ProcessGDBRemote::HandleAsyncStdout(llvm::StringRef out) {
4940   AppendSTDOUT(out.data(), out.size());
4941 }
4942 
4943 static const char *end_delimiter = "--end--;";
4944 static const int end_delimiter_len = 8;
4945 
4946 void ProcessGDBRemote::HandleAsyncMisc(llvm::StringRef data) {
4947   std::string input = data.str(); // '1' to move beyond 'A'
4948   if (m_partial_profile_data.length() > 0) {
4949     m_partial_profile_data.append(input);
4950     input = m_partial_profile_data;
4951     m_partial_profile_data.clear();
4952   }
4953 
4954   size_t found, pos = 0, len = input.length();
4955   while ((found = input.find(end_delimiter, pos)) != std::string::npos) {
4956     StringExtractorGDBRemote profileDataExtractor(
4957         input.substr(pos, found).c_str());
4958     std::string profile_data =
4959         HarmonizeThreadIdsForProfileData(profileDataExtractor);
4960     BroadcastAsyncProfileData(profile_data);
4961 
4962     pos = found + end_delimiter_len;
4963   }
4964 
4965   if (pos < len) {
4966     // Last incomplete chunk.
4967     m_partial_profile_data = input.substr(pos);
4968   }
4969 }
4970 
4971 std::string ProcessGDBRemote::HarmonizeThreadIdsForProfileData(
4972     StringExtractorGDBRemote &profileDataExtractor) {
4973   std::map<uint64_t, uint32_t> new_thread_id_to_used_usec_map;
4974   std::string output;
4975   llvm::raw_string_ostream output_stream(output);
4976   llvm::StringRef name, value;
4977 
4978   // Going to assuming thread_used_usec comes first, else bail out.
4979   while (profileDataExtractor.GetNameColonValue(name, value)) {
4980     if (name.compare("thread_used_id") == 0) {
4981       StringExtractor threadIDHexExtractor(value);
4982       uint64_t thread_id = threadIDHexExtractor.GetHexMaxU64(false, 0);
4983 
4984       bool has_used_usec = false;
4985       uint32_t curr_used_usec = 0;
4986       llvm::StringRef usec_name, usec_value;
4987       uint32_t input_file_pos = profileDataExtractor.GetFilePos();
4988       if (profileDataExtractor.GetNameColonValue(usec_name, usec_value)) {
4989         if (usec_name.equals("thread_used_usec")) {
4990           has_used_usec = true;
4991           usec_value.getAsInteger(0, curr_used_usec);
4992         } else {
4993           // We didn't find what we want, it is probably an older version. Bail
4994           // out.
4995           profileDataExtractor.SetFilePos(input_file_pos);
4996         }
4997       }
4998 
4999       if (has_used_usec) {
5000         uint32_t prev_used_usec = 0;
5001         std::map<uint64_t, uint32_t>::iterator iterator =
5002             m_thread_id_to_used_usec_map.find(thread_id);
5003         if (iterator != m_thread_id_to_used_usec_map.end()) {
5004           prev_used_usec = m_thread_id_to_used_usec_map[thread_id];
5005         }
5006 
5007         uint32_t real_used_usec = curr_used_usec - prev_used_usec;
5008         // A good first time record is one that runs for at least 0.25 sec
5009         bool good_first_time =
5010             (prev_used_usec == 0) && (real_used_usec > 250000);
5011         bool good_subsequent_time =
5012             (prev_used_usec > 0) &&
5013             ((real_used_usec > 0) || (HasAssignedIndexIDToThread(thread_id)));
5014 
5015         if (good_first_time || good_subsequent_time) {
5016           // We try to avoid doing too many index id reservation, resulting in
5017           // fast increase of index ids.
5018 
5019           output_stream << name << ":";
5020           int32_t index_id = AssignIndexIDToThread(thread_id);
5021           output_stream << index_id << ";";
5022 
5023           output_stream << usec_name << ":" << usec_value << ";";
5024         } else {
5025           // Skip past 'thread_used_name'.
5026           llvm::StringRef local_name, local_value;
5027           profileDataExtractor.GetNameColonValue(local_name, local_value);
5028         }
5029 
5030         // Store current time as previous time so that they can be compared
5031         // later.
5032         new_thread_id_to_used_usec_map[thread_id] = curr_used_usec;
5033       } else {
5034         // Bail out and use old string.
5035         output_stream << name << ":" << value << ";";
5036       }
5037     } else {
5038       output_stream << name << ":" << value << ";";
5039     }
5040   }
5041   output_stream << end_delimiter;
5042   m_thread_id_to_used_usec_map = new_thread_id_to_used_usec_map;
5043 
5044   return output_stream.str();
5045 }
5046 
5047 void ProcessGDBRemote::HandleStopReply() {
5048   if (GetStopID() != 0)
5049     return;
5050 
5051   if (GetID() == LLDB_INVALID_PROCESS_ID) {
5052     lldb::pid_t pid = m_gdb_comm.GetCurrentProcessID();
5053     if (pid != LLDB_INVALID_PROCESS_ID)
5054       SetID(pid);
5055   }
5056   BuildDynamicRegisterInfo(true);
5057 }
5058 
5059 static const char *const s_async_json_packet_prefix = "JSON-async:";
5060 
5061 static StructuredData::ObjectSP
5062 ParseStructuredDataPacket(llvm::StringRef packet) {
5063   Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
5064 
5065   if (!packet.consume_front(s_async_json_packet_prefix)) {
5066     if (log) {
5067       LLDB_LOGF(
5068           log,
5069           "GDBRemoteCommunicationClientBase::%s() received $J packet "
5070           "but was not a StructuredData packet: packet starts with "
5071           "%s",
5072           __FUNCTION__,
5073           packet.slice(0, strlen(s_async_json_packet_prefix)).str().c_str());
5074     }
5075     return StructuredData::ObjectSP();
5076   }
5077 
5078   // This is an asynchronous JSON packet, destined for a StructuredDataPlugin.
5079   StructuredData::ObjectSP json_sp =
5080       StructuredData::ParseJSON(std::string(packet));
5081   if (log) {
5082     if (json_sp) {
5083       StreamString json_str;
5084       json_sp->Dump(json_str, true);
5085       json_str.Flush();
5086       LLDB_LOGF(log,
5087                 "ProcessGDBRemote::%s() "
5088                 "received Async StructuredData packet: %s",
5089                 __FUNCTION__, json_str.GetData());
5090     } else {
5091       LLDB_LOGF(log,
5092                 "ProcessGDBRemote::%s"
5093                 "() received StructuredData packet:"
5094                 " parse failure",
5095                 __FUNCTION__);
5096     }
5097   }
5098   return json_sp;
5099 }
5100 
5101 void ProcessGDBRemote::HandleAsyncStructuredDataPacket(llvm::StringRef data) {
5102   auto structured_data_sp = ParseStructuredDataPacket(data);
5103   if (structured_data_sp)
5104     RouteAsyncStructuredData(structured_data_sp);
5105 }
5106 
5107 class CommandObjectProcessGDBRemoteSpeedTest : public CommandObjectParsed {
5108 public:
5109   CommandObjectProcessGDBRemoteSpeedTest(CommandInterpreter &interpreter)
5110       : CommandObjectParsed(interpreter, "process plugin packet speed-test",
5111                             "Tests packet speeds of various sizes to determine "
5112                             "the performance characteristics of the GDB remote "
5113                             "connection. ",
5114                             nullptr),
5115         m_option_group(),
5116         m_num_packets(LLDB_OPT_SET_1, false, "count", 'c', 0, eArgTypeCount,
5117                       "The number of packets to send of each varying size "
5118                       "(default is 1000).",
5119                       1000),
5120         m_max_send(LLDB_OPT_SET_1, false, "max-send", 's', 0, eArgTypeCount,
5121                    "The maximum number of bytes to send 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_max_recv(LLDB_OPT_SET_1, false, "max-receive", 'r', 0, eArgTypeCount,
5126                    "The maximum number of bytes to receive in a packet. Sizes "
5127                    "increase in powers of 2 while the size is less than or "
5128                    "equal to this option value. (default 1024).",
5129                    1024),
5130         m_json(LLDB_OPT_SET_1, false, "json", 'j',
5131                "Print the output as JSON data for easy parsing.", false, true) {
5132     m_option_group.Append(&m_num_packets, LLDB_OPT_SET_ALL, LLDB_OPT_SET_1);
5133     m_option_group.Append(&m_max_send, LLDB_OPT_SET_ALL, LLDB_OPT_SET_1);
5134     m_option_group.Append(&m_max_recv, LLDB_OPT_SET_ALL, LLDB_OPT_SET_1);
5135     m_option_group.Append(&m_json, LLDB_OPT_SET_ALL, LLDB_OPT_SET_1);
5136     m_option_group.Finalize();
5137   }
5138 
5139   ~CommandObjectProcessGDBRemoteSpeedTest() override {}
5140 
5141   Options *GetOptions() override { return &m_option_group; }
5142 
5143   bool DoExecute(Args &command, CommandReturnObject &result) override {
5144     const size_t argc = command.GetArgumentCount();
5145     if (argc == 0) {
5146       ProcessGDBRemote *process =
5147           (ProcessGDBRemote *)m_interpreter.GetExecutionContext()
5148               .GetProcessPtr();
5149       if (process) {
5150         StreamSP output_stream_sp(
5151             m_interpreter.GetDebugger().GetAsyncOutputStream());
5152         result.SetImmediateOutputStream(output_stream_sp);
5153 
5154         const uint32_t num_packets =
5155             (uint32_t)m_num_packets.GetOptionValue().GetCurrentValue();
5156         const uint64_t max_send = m_max_send.GetOptionValue().GetCurrentValue();
5157         const uint64_t max_recv = m_max_recv.GetOptionValue().GetCurrentValue();
5158         const bool json = m_json.GetOptionValue().GetCurrentValue();
5159         const uint64_t k_recv_amount =
5160             4 * 1024 * 1024; // Receive amount in bytes
5161         process->GetGDBRemote().TestPacketSpeed(
5162             num_packets, max_send, max_recv, k_recv_amount, json,
5163             output_stream_sp ? *output_stream_sp : result.GetOutputStream());
5164         result.SetStatus(eReturnStatusSuccessFinishResult);
5165         return true;
5166       }
5167     } else {
5168       result.AppendErrorWithFormat("'%s' takes no arguments",
5169                                    m_cmd_name.c_str());
5170     }
5171     result.SetStatus(eReturnStatusFailed);
5172     return false;
5173   }
5174 
5175 protected:
5176   OptionGroupOptions m_option_group;
5177   OptionGroupUInt64 m_num_packets;
5178   OptionGroupUInt64 m_max_send;
5179   OptionGroupUInt64 m_max_recv;
5180   OptionGroupBoolean m_json;
5181 };
5182 
5183 class CommandObjectProcessGDBRemotePacketHistory : public CommandObjectParsed {
5184 private:
5185 public:
5186   CommandObjectProcessGDBRemotePacketHistory(CommandInterpreter &interpreter)
5187       : CommandObjectParsed(interpreter, "process plugin packet history",
5188                             "Dumps the packet history buffer. ", nullptr) {}
5189 
5190   ~CommandObjectProcessGDBRemotePacketHistory() override {}
5191 
5192   bool DoExecute(Args &command, CommandReturnObject &result) override {
5193     const size_t argc = command.GetArgumentCount();
5194     if (argc == 0) {
5195       ProcessGDBRemote *process =
5196           (ProcessGDBRemote *)m_interpreter.GetExecutionContext()
5197               .GetProcessPtr();
5198       if (process) {
5199         process->GetGDBRemote().DumpHistory(result.GetOutputStream());
5200         result.SetStatus(eReturnStatusSuccessFinishResult);
5201         return true;
5202       }
5203     } else {
5204       result.AppendErrorWithFormat("'%s' takes no arguments",
5205                                    m_cmd_name.c_str());
5206     }
5207     result.SetStatus(eReturnStatusFailed);
5208     return false;
5209   }
5210 };
5211 
5212 class CommandObjectProcessGDBRemotePacketXferSize : public CommandObjectParsed {
5213 private:
5214 public:
5215   CommandObjectProcessGDBRemotePacketXferSize(CommandInterpreter &interpreter)
5216       : CommandObjectParsed(
5217             interpreter, "process plugin packet xfer-size",
5218             "Maximum size that lldb will try to read/write one one chunk.",
5219             nullptr) {}
5220 
5221   ~CommandObjectProcessGDBRemotePacketXferSize() override {}
5222 
5223   bool DoExecute(Args &command, CommandReturnObject &result) override {
5224     const size_t argc = command.GetArgumentCount();
5225     if (argc == 0) {
5226       result.AppendErrorWithFormat("'%s' takes an argument to specify the max "
5227                                    "amount to be transferred when "
5228                                    "reading/writing",
5229                                    m_cmd_name.c_str());
5230       result.SetStatus(eReturnStatusFailed);
5231       return false;
5232     }
5233 
5234     ProcessGDBRemote *process =
5235         (ProcessGDBRemote *)m_interpreter.GetExecutionContext().GetProcessPtr();
5236     if (process) {
5237       const char *packet_size = command.GetArgumentAtIndex(0);
5238       errno = 0;
5239       uint64_t user_specified_max = strtoul(packet_size, nullptr, 10);
5240       if (errno == 0 && user_specified_max != 0) {
5241         process->SetUserSpecifiedMaxMemoryTransferSize(user_specified_max);
5242         result.SetStatus(eReturnStatusSuccessFinishResult);
5243         return true;
5244       }
5245     }
5246     result.SetStatus(eReturnStatusFailed);
5247     return false;
5248   }
5249 };
5250 
5251 class CommandObjectProcessGDBRemotePacketSend : public CommandObjectParsed {
5252 private:
5253 public:
5254   CommandObjectProcessGDBRemotePacketSend(CommandInterpreter &interpreter)
5255       : CommandObjectParsed(interpreter, "process plugin packet send",
5256                             "Send a custom packet through the GDB remote "
5257                             "protocol and print the answer. "
5258                             "The packet header and footer will automatically "
5259                             "be added to the packet prior to sending and "
5260                             "stripped from the result.",
5261                             nullptr) {}
5262 
5263   ~CommandObjectProcessGDBRemotePacketSend() override {}
5264 
5265   bool DoExecute(Args &command, CommandReturnObject &result) override {
5266     const size_t argc = command.GetArgumentCount();
5267     if (argc == 0) {
5268       result.AppendErrorWithFormat(
5269           "'%s' takes a one or more packet content arguments",
5270           m_cmd_name.c_str());
5271       result.SetStatus(eReturnStatusFailed);
5272       return false;
5273     }
5274 
5275     ProcessGDBRemote *process =
5276         (ProcessGDBRemote *)m_interpreter.GetExecutionContext().GetProcessPtr();
5277     if (process) {
5278       for (size_t i = 0; i < argc; ++i) {
5279         const char *packet_cstr = command.GetArgumentAtIndex(0);
5280         bool send_async = true;
5281         StringExtractorGDBRemote response;
5282         process->GetGDBRemote().SendPacketAndWaitForResponse(
5283             packet_cstr, response, send_async);
5284         result.SetStatus(eReturnStatusSuccessFinishResult);
5285         Stream &output_strm = result.GetOutputStream();
5286         output_strm.Printf("  packet: %s\n", packet_cstr);
5287         std::string response_str = std::string(response.GetStringRef());
5288 
5289         if (strstr(packet_cstr, "qGetProfileData") != nullptr) {
5290           response_str = process->HarmonizeThreadIdsForProfileData(response);
5291         }
5292 
5293         if (response_str.empty())
5294           output_strm.PutCString("response: \nerror: UNIMPLEMENTED\n");
5295         else
5296           output_strm.Printf("response: %s\n", response.GetStringRef().data());
5297       }
5298     }
5299     return true;
5300   }
5301 };
5302 
5303 class CommandObjectProcessGDBRemotePacketMonitor : public CommandObjectRaw {
5304 private:
5305 public:
5306   CommandObjectProcessGDBRemotePacketMonitor(CommandInterpreter &interpreter)
5307       : CommandObjectRaw(interpreter, "process plugin packet monitor",
5308                          "Send a qRcmd packet through the GDB remote protocol "
5309                          "and print the response."
5310                          "The argument passed to this command will be hex "
5311                          "encoded into a valid 'qRcmd' packet, sent and the "
5312                          "response will be printed.") {}
5313 
5314   ~CommandObjectProcessGDBRemotePacketMonitor() override {}
5315 
5316   bool DoExecute(llvm::StringRef command,
5317                  CommandReturnObject &result) override {
5318     if (command.empty()) {
5319       result.AppendErrorWithFormat("'%s' takes a command string argument",
5320                                    m_cmd_name.c_str());
5321       result.SetStatus(eReturnStatusFailed);
5322       return false;
5323     }
5324 
5325     ProcessGDBRemote *process =
5326         (ProcessGDBRemote *)m_interpreter.GetExecutionContext().GetProcessPtr();
5327     if (process) {
5328       StreamString packet;
5329       packet.PutCString("qRcmd,");
5330       packet.PutBytesAsRawHex8(command.data(), command.size());
5331 
5332       bool send_async = true;
5333       StringExtractorGDBRemote response;
5334       Stream &output_strm = result.GetOutputStream();
5335       process->GetGDBRemote().SendPacketAndReceiveResponseWithOutputSupport(
5336           packet.GetString(), response, send_async,
5337           [&output_strm](llvm::StringRef output) { output_strm << output; });
5338       result.SetStatus(eReturnStatusSuccessFinishResult);
5339       output_strm.Printf("  packet: %s\n", packet.GetData());
5340       const std::string &response_str = std::string(response.GetStringRef());
5341 
5342       if (response_str.empty())
5343         output_strm.PutCString("response: \nerror: UNIMPLEMENTED\n");
5344       else
5345         output_strm.Printf("response: %s\n", response.GetStringRef().data());
5346     }
5347     return true;
5348   }
5349 };
5350 
5351 class CommandObjectProcessGDBRemotePacket : public CommandObjectMultiword {
5352 private:
5353 public:
5354   CommandObjectProcessGDBRemotePacket(CommandInterpreter &interpreter)
5355       : CommandObjectMultiword(interpreter, "process plugin packet",
5356                                "Commands that deal with GDB remote packets.",
5357                                nullptr) {
5358     LoadSubCommand(
5359         "history",
5360         CommandObjectSP(
5361             new CommandObjectProcessGDBRemotePacketHistory(interpreter)));
5362     LoadSubCommand(
5363         "send", CommandObjectSP(
5364                     new CommandObjectProcessGDBRemotePacketSend(interpreter)));
5365     LoadSubCommand(
5366         "monitor",
5367         CommandObjectSP(
5368             new CommandObjectProcessGDBRemotePacketMonitor(interpreter)));
5369     LoadSubCommand(
5370         "xfer-size",
5371         CommandObjectSP(
5372             new CommandObjectProcessGDBRemotePacketXferSize(interpreter)));
5373     LoadSubCommand("speed-test",
5374                    CommandObjectSP(new CommandObjectProcessGDBRemoteSpeedTest(
5375                        interpreter)));
5376   }
5377 
5378   ~CommandObjectProcessGDBRemotePacket() override {}
5379 };
5380 
5381 class CommandObjectMultiwordProcessGDBRemote : public CommandObjectMultiword {
5382 public:
5383   CommandObjectMultiwordProcessGDBRemote(CommandInterpreter &interpreter)
5384       : CommandObjectMultiword(
5385             interpreter, "process plugin",
5386             "Commands for operating on a ProcessGDBRemote process.",
5387             "process plugin <subcommand> [<subcommand-options>]") {
5388     LoadSubCommand(
5389         "packet",
5390         CommandObjectSP(new CommandObjectProcessGDBRemotePacket(interpreter)));
5391   }
5392 
5393   ~CommandObjectMultiwordProcessGDBRemote() override {}
5394 };
5395 
5396 CommandObject *ProcessGDBRemote::GetPluginCommandObject() {
5397   if (!m_command_sp)
5398     m_command_sp = std::make_shared<CommandObjectMultiwordProcessGDBRemote>(
5399         GetTarget().GetDebugger().GetCommandInterpreter());
5400   return m_command_sp.get();
5401 }
5402