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