xref: /llvm-project/lldb/source/Plugins/Process/gdb-remote/ProcessGDBRemote.cpp (revision de346cf2ac850be793ee7fc31f99a7671331c289)
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             !errorToBool(pty.OpenFirstAvailablePrimary(O_RDWR | O_NOCTTY))) {
821           FileSpec secondary_name(pty.GetSecondaryName());
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       if (m_gdb_comm.SendGDBStoppointTypePacket(eBreakpointSoftware, false,
3208                                                 addr, bp_op_size))
3209         error.SetErrorToGenericError();
3210     } break;
3211     }
3212     if (error.Success())
3213       bp_site->SetEnabled(false);
3214   } else {
3215     LLDB_LOGF(log,
3216               "ProcessGDBRemote::DisableBreakpointSite (site_id = %" PRIu64
3217               ") addr = 0x%8.8" PRIx64 " -- SUCCESS (already disabled)",
3218               site_id, (uint64_t)addr);
3219     return error;
3220   }
3221 
3222   if (error.Success())
3223     error.SetErrorToGenericError();
3224   return error;
3225 }
3226 
3227 // Pre-requisite: wp != NULL.
3228 static GDBStoppointType GetGDBStoppointType(Watchpoint *wp) {
3229   assert(wp);
3230   bool watch_read = wp->WatchpointRead();
3231   bool watch_write = wp->WatchpointWrite();
3232 
3233   // watch_read and watch_write cannot both be false.
3234   assert(watch_read || watch_write);
3235   if (watch_read && watch_write)
3236     return eWatchpointReadWrite;
3237   else if (watch_read)
3238     return eWatchpointRead;
3239   else // Must be watch_write, then.
3240     return eWatchpointWrite;
3241 }
3242 
3243 Status ProcessGDBRemote::EnableWatchpoint(Watchpoint *wp, bool notify) {
3244   Status error;
3245   if (wp) {
3246     user_id_t watchID = wp->GetID();
3247     addr_t addr = wp->GetLoadAddress();
3248     Log *log(
3249         ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_WATCHPOINTS));
3250     LLDB_LOGF(log, "ProcessGDBRemote::EnableWatchpoint(watchID = %" PRIu64 ")",
3251               watchID);
3252     if (wp->IsEnabled()) {
3253       LLDB_LOGF(log,
3254                 "ProcessGDBRemote::EnableWatchpoint(watchID = %" PRIu64
3255                 ") addr = 0x%8.8" PRIx64 ": watchpoint already enabled.",
3256                 watchID, (uint64_t)addr);
3257       return error;
3258     }
3259 
3260     GDBStoppointType type = GetGDBStoppointType(wp);
3261     // Pass down an appropriate z/Z packet...
3262     if (m_gdb_comm.SupportsGDBStoppointPacket(type)) {
3263       if (m_gdb_comm.SendGDBStoppointTypePacket(type, true, addr,
3264                                                 wp->GetByteSize()) == 0) {
3265         wp->SetEnabled(true, notify);
3266         return error;
3267       } else
3268         error.SetErrorString("sending gdb watchpoint packet failed");
3269     } else
3270       error.SetErrorString("watchpoints not supported");
3271   } else {
3272     error.SetErrorString("Watchpoint argument was NULL.");
3273   }
3274   if (error.Success())
3275     error.SetErrorToGenericError();
3276   return error;
3277 }
3278 
3279 Status ProcessGDBRemote::DisableWatchpoint(Watchpoint *wp, bool notify) {
3280   Status error;
3281   if (wp) {
3282     user_id_t watchID = wp->GetID();
3283 
3284     Log *log(
3285         ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_WATCHPOINTS));
3286 
3287     addr_t addr = wp->GetLoadAddress();
3288 
3289     LLDB_LOGF(log,
3290               "ProcessGDBRemote::DisableWatchpoint (watchID = %" PRIu64
3291               ") addr = 0x%8.8" PRIx64,
3292               watchID, (uint64_t)addr);
3293 
3294     if (!wp->IsEnabled()) {
3295       LLDB_LOGF(log,
3296                 "ProcessGDBRemote::DisableWatchpoint (watchID = %" PRIu64
3297                 ") addr = 0x%8.8" PRIx64 " -- SUCCESS (already disabled)",
3298                 watchID, (uint64_t)addr);
3299       // See also 'class WatchpointSentry' within StopInfo.cpp. This disabling
3300       // attempt might come from the user-supplied actions, we'll route it in
3301       // order for the watchpoint object to intelligently process this action.
3302       wp->SetEnabled(false, notify);
3303       return error;
3304     }
3305 
3306     if (wp->IsHardware()) {
3307       GDBStoppointType type = GetGDBStoppointType(wp);
3308       // Pass down an appropriate z/Z packet...
3309       if (m_gdb_comm.SendGDBStoppointTypePacket(type, false, addr,
3310                                                 wp->GetByteSize()) == 0) {
3311         wp->SetEnabled(false, notify);
3312         return error;
3313       } else
3314         error.SetErrorString("sending gdb watchpoint packet failed");
3315     }
3316     // TODO: clear software watchpoints if we implement them
3317   } else {
3318     error.SetErrorString("Watchpoint argument was NULL.");
3319   }
3320   if (error.Success())
3321     error.SetErrorToGenericError();
3322   return error;
3323 }
3324 
3325 void ProcessGDBRemote::Clear() {
3326   m_thread_list_real.Clear();
3327   m_thread_list.Clear();
3328 }
3329 
3330 Status ProcessGDBRemote::DoSignal(int signo) {
3331   Status error;
3332   Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
3333   LLDB_LOGF(log, "ProcessGDBRemote::DoSignal (signal = %d)", signo);
3334 
3335   if (!m_gdb_comm.SendAsyncSignal(signo))
3336     error.SetErrorStringWithFormat("failed to send signal %i", signo);
3337   return error;
3338 }
3339 
3340 Status ProcessGDBRemote::ConnectToReplayServer() {
3341   Status status = m_gdb_replay_server.Connect(m_gdb_comm);
3342   if (status.Fail())
3343     return status;
3344 
3345   // Enable replay mode.
3346   m_replay_mode = true;
3347 
3348   // Start server thread.
3349   m_gdb_replay_server.StartAsyncThread();
3350 
3351   // Start client thread.
3352   StartAsyncThread();
3353 
3354   // Do the usual setup.
3355   return ConnectToDebugserver("");
3356 }
3357 
3358 Status
3359 ProcessGDBRemote::EstablishConnectionIfNeeded(const ProcessInfo &process_info) {
3360   // Make sure we aren't already connected?
3361   if (m_gdb_comm.IsConnected())
3362     return Status();
3363 
3364   PlatformSP platform_sp(GetTarget().GetPlatform());
3365   if (platform_sp && !platform_sp->IsHost())
3366     return Status("Lost debug server connection");
3367 
3368   if (repro::Reproducer::Instance().IsReplaying())
3369     return ConnectToReplayServer();
3370 
3371   auto error = LaunchAndConnectToDebugserver(process_info);
3372   if (error.Fail()) {
3373     const char *error_string = error.AsCString();
3374     if (error_string == nullptr)
3375       error_string = "unable to launch " DEBUGSERVER_BASENAME;
3376   }
3377   return error;
3378 }
3379 #if !defined(_WIN32)
3380 #define USE_SOCKETPAIR_FOR_LOCAL_CONNECTION 1
3381 #endif
3382 
3383 #ifdef USE_SOCKETPAIR_FOR_LOCAL_CONNECTION
3384 static bool SetCloexecFlag(int fd) {
3385 #if defined(FD_CLOEXEC)
3386   int flags = ::fcntl(fd, F_GETFD);
3387   if (flags == -1)
3388     return false;
3389   return (::fcntl(fd, F_SETFD, flags | FD_CLOEXEC) == 0);
3390 #else
3391   return false;
3392 #endif
3393 }
3394 #endif
3395 
3396 Status ProcessGDBRemote::LaunchAndConnectToDebugserver(
3397     const ProcessInfo &process_info) {
3398   using namespace std::placeholders; // For _1, _2, etc.
3399 
3400   Status error;
3401   if (m_debugserver_pid == LLDB_INVALID_PROCESS_ID) {
3402     // If we locate debugserver, keep that located version around
3403     static FileSpec g_debugserver_file_spec;
3404 
3405     ProcessLaunchInfo debugserver_launch_info;
3406     // Make debugserver run in its own session so signals generated by special
3407     // terminal key sequences (^C) don't affect debugserver.
3408     debugserver_launch_info.SetLaunchInSeparateProcessGroup(true);
3409 
3410     const std::weak_ptr<ProcessGDBRemote> this_wp =
3411         std::static_pointer_cast<ProcessGDBRemote>(shared_from_this());
3412     debugserver_launch_info.SetMonitorProcessCallback(
3413         std::bind(MonitorDebugserverProcess, this_wp, _1, _2, _3, _4), false);
3414     debugserver_launch_info.SetUserID(process_info.GetUserID());
3415 
3416 #if defined(__APPLE__)
3417     // On macOS 11, we need to support x86_64 applications translated to
3418     // arm64. We check whether a binary is translated and spawn the correct
3419     // debugserver accordingly.
3420     int mib[] = { CTL_KERN, KERN_PROC, KERN_PROC_PID,
3421                   static_cast<int>(process_info.GetProcessID()) };
3422     struct kinfo_proc processInfo;
3423     size_t bufsize = sizeof(processInfo);
3424     if (sysctl(mib, (unsigned)(sizeof(mib)/sizeof(int)), &processInfo,
3425                &bufsize, NULL, 0) == 0 && bufsize > 0) {
3426       if (processInfo.kp_proc.p_flag & P_TRANSLATED) {
3427         FileSpec rosetta_debugserver("/Library/Apple/usr/libexec/oah/debugserver");
3428         debugserver_launch_info.SetExecutableFile(rosetta_debugserver, false);
3429       }
3430     }
3431 #endif
3432 
3433     int communication_fd = -1;
3434 #ifdef USE_SOCKETPAIR_FOR_LOCAL_CONNECTION
3435     // Use a socketpair on non-Windows systems for security and performance
3436     // reasons.
3437     int sockets[2]; /* the pair of socket descriptors */
3438     if (socketpair(AF_UNIX, SOCK_STREAM, 0, sockets) == -1) {
3439       error.SetErrorToErrno();
3440       return error;
3441     }
3442 
3443     int our_socket = sockets[0];
3444     int gdb_socket = sockets[1];
3445     auto cleanup_our = llvm::make_scope_exit([&]() { close(our_socket); });
3446     auto cleanup_gdb = llvm::make_scope_exit([&]() { close(gdb_socket); });
3447 
3448     // Don't let any child processes inherit our communication socket
3449     SetCloexecFlag(our_socket);
3450     communication_fd = gdb_socket;
3451 #endif
3452 
3453     error = m_gdb_comm.StartDebugserverProcess(
3454         nullptr, GetTarget().GetPlatform().get(), debugserver_launch_info,
3455         nullptr, nullptr, communication_fd);
3456 
3457     if (error.Success())
3458       m_debugserver_pid = debugserver_launch_info.GetProcessID();
3459     else
3460       m_debugserver_pid = LLDB_INVALID_PROCESS_ID;
3461 
3462     if (m_debugserver_pid != LLDB_INVALID_PROCESS_ID) {
3463 #ifdef USE_SOCKETPAIR_FOR_LOCAL_CONNECTION
3464       // Our process spawned correctly, we can now set our connection to use
3465       // our end of the socket pair
3466       cleanup_our.release();
3467       m_gdb_comm.SetConnection(
3468           std::make_unique<ConnectionFileDescriptor>(our_socket, true));
3469 #endif
3470       StartAsyncThread();
3471     }
3472 
3473     if (error.Fail()) {
3474       Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
3475 
3476       LLDB_LOGF(log, "failed to start debugserver process: %s",
3477                 error.AsCString());
3478       return error;
3479     }
3480 
3481     if (m_gdb_comm.IsConnected()) {
3482       // Finish the connection process by doing the handshake without
3483       // connecting (send NULL URL)
3484       error = ConnectToDebugserver("");
3485     } else {
3486       error.SetErrorString("connection failed");
3487     }
3488   }
3489   return error;
3490 }
3491 
3492 bool ProcessGDBRemote::MonitorDebugserverProcess(
3493     std::weak_ptr<ProcessGDBRemote> process_wp, lldb::pid_t debugserver_pid,
3494     bool exited,    // True if the process did exit
3495     int signo,      // Zero for no signal
3496     int exit_status // Exit value of process if signal is zero
3497 ) {
3498   // "debugserver_pid" argument passed in is the process ID for debugserver
3499   // that we are tracking...
3500   Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
3501   const bool handled = true;
3502 
3503   LLDB_LOGF(log,
3504             "ProcessGDBRemote::%s(process_wp, pid=%" PRIu64
3505             ", signo=%i (0x%x), exit_status=%i)",
3506             __FUNCTION__, debugserver_pid, signo, signo, exit_status);
3507 
3508   std::shared_ptr<ProcessGDBRemote> process_sp = process_wp.lock();
3509   LLDB_LOGF(log, "ProcessGDBRemote::%s(process = %p)", __FUNCTION__,
3510             static_cast<void *>(process_sp.get()));
3511   if (!process_sp || process_sp->m_debugserver_pid != debugserver_pid)
3512     return handled;
3513 
3514   // Sleep for a half a second to make sure our inferior process has time to
3515   // set its exit status before we set it incorrectly when both the debugserver
3516   // and the inferior process shut down.
3517   std::this_thread::sleep_for(std::chrono::milliseconds(500));
3518 
3519   // If our process hasn't yet exited, debugserver might have died. If the
3520   // process did exit, then we are reaping it.
3521   const StateType state = process_sp->GetState();
3522 
3523   if (state != eStateInvalid && state != eStateUnloaded &&
3524       state != eStateExited && state != eStateDetached) {
3525     char error_str[1024];
3526     if (signo) {
3527       const char *signal_cstr =
3528           process_sp->GetUnixSignals()->GetSignalAsCString(signo);
3529       if (signal_cstr)
3530         ::snprintf(error_str, sizeof(error_str),
3531                    DEBUGSERVER_BASENAME " died with signal %s", signal_cstr);
3532       else
3533         ::snprintf(error_str, sizeof(error_str),
3534                    DEBUGSERVER_BASENAME " died with signal %i", signo);
3535     } else {
3536       ::snprintf(error_str, sizeof(error_str),
3537                  DEBUGSERVER_BASENAME " died with an exit status of 0x%8.8x",
3538                  exit_status);
3539     }
3540 
3541     process_sp->SetExitStatus(-1, error_str);
3542   }
3543   // Debugserver has exited we need to let our ProcessGDBRemote know that it no
3544   // longer has a debugserver instance
3545   process_sp->m_debugserver_pid = LLDB_INVALID_PROCESS_ID;
3546   return handled;
3547 }
3548 
3549 void ProcessGDBRemote::KillDebugserverProcess() {
3550   m_gdb_comm.Disconnect();
3551   if (m_debugserver_pid != LLDB_INVALID_PROCESS_ID) {
3552     Host::Kill(m_debugserver_pid, SIGINT);
3553     m_debugserver_pid = LLDB_INVALID_PROCESS_ID;
3554   }
3555 }
3556 
3557 void ProcessGDBRemote::Initialize() {
3558   static llvm::once_flag g_once_flag;
3559 
3560   llvm::call_once(g_once_flag, []() {
3561     PluginManager::RegisterPlugin(GetPluginNameStatic(),
3562                                   GetPluginDescriptionStatic(), CreateInstance,
3563                                   DebuggerInitialize);
3564   });
3565 }
3566 
3567 void ProcessGDBRemote::DebuggerInitialize(Debugger &debugger) {
3568   if (!PluginManager::GetSettingForProcessPlugin(
3569           debugger, PluginProperties::GetSettingName())) {
3570     const bool is_global_setting = true;
3571     PluginManager::CreateSettingForProcessPlugin(
3572         debugger, GetGlobalPluginProperties()->GetValueProperties(),
3573         ConstString("Properties for the gdb-remote process plug-in."),
3574         is_global_setting);
3575   }
3576 }
3577 
3578 bool ProcessGDBRemote::StartAsyncThread() {
3579   Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
3580 
3581   LLDB_LOGF(log, "ProcessGDBRemote::%s ()", __FUNCTION__);
3582 
3583   std::lock_guard<std::recursive_mutex> guard(m_async_thread_state_mutex);
3584   if (!m_async_thread.IsJoinable()) {
3585     // Create a thread that watches our internal state and controls which
3586     // events make it to clients (into the DCProcess event queue).
3587 
3588     llvm::Expected<HostThread> async_thread = ThreadLauncher::LaunchThread(
3589         "<lldb.process.gdb-remote.async>", ProcessGDBRemote::AsyncThread, this);
3590     if (!async_thread) {
3591       LLDB_LOG_ERROR(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_HOST),
3592                      async_thread.takeError(),
3593                      "failed to launch host thread: {}");
3594       return false;
3595     }
3596     m_async_thread = *async_thread;
3597   } else
3598     LLDB_LOGF(log,
3599               "ProcessGDBRemote::%s () - Called when Async thread was "
3600               "already running.",
3601               __FUNCTION__);
3602 
3603   return m_async_thread.IsJoinable();
3604 }
3605 
3606 void ProcessGDBRemote::StopAsyncThread() {
3607   Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
3608 
3609   LLDB_LOGF(log, "ProcessGDBRemote::%s ()", __FUNCTION__);
3610 
3611   std::lock_guard<std::recursive_mutex> guard(m_async_thread_state_mutex);
3612   if (m_async_thread.IsJoinable()) {
3613     m_async_broadcaster.BroadcastEvent(eBroadcastBitAsyncThreadShouldExit);
3614 
3615     //  This will shut down the async thread.
3616     m_gdb_comm.Disconnect(); // Disconnect from the debug server.
3617 
3618     // Stop the stdio thread
3619     m_async_thread.Join(nullptr);
3620     m_async_thread.Reset();
3621   } else
3622     LLDB_LOGF(
3623         log,
3624         "ProcessGDBRemote::%s () - Called when Async thread was not running.",
3625         __FUNCTION__);
3626 }
3627 
3628 bool ProcessGDBRemote::HandleNotifyPacket(StringExtractorGDBRemote &packet) {
3629   // get the packet at a string
3630   const std::string &pkt = std::string(packet.GetStringRef());
3631   // skip %stop:
3632   StringExtractorGDBRemote stop_info(pkt.c_str() + 5);
3633 
3634   // pass as a thread stop info packet
3635   SetLastStopPacket(stop_info);
3636 
3637   // check for more stop reasons
3638   HandleStopReplySequence();
3639 
3640   // if the process is stopped then we need to fake a resume so that we can
3641   // stop properly with the new break. This is possible due to
3642   // SetPrivateState() broadcasting the state change as a side effect.
3643   if (GetPrivateState() == lldb::StateType::eStateStopped) {
3644     SetPrivateState(lldb::StateType::eStateRunning);
3645   }
3646 
3647   // since we have some stopped packets we can halt the process
3648   SetPrivateState(lldb::StateType::eStateStopped);
3649 
3650   return true;
3651 }
3652 
3653 thread_result_t ProcessGDBRemote::AsyncThread(void *arg) {
3654   ProcessGDBRemote *process = (ProcessGDBRemote *)arg;
3655 
3656   Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
3657   LLDB_LOGF(log,
3658             "ProcessGDBRemote::%s (arg = %p, pid = %" PRIu64
3659             ") thread starting...",
3660             __FUNCTION__, arg, process->GetID());
3661 
3662   EventSP event_sp;
3663   bool done = false;
3664   while (!done) {
3665     LLDB_LOGF(log,
3666               "ProcessGDBRemote::%s (arg = %p, pid = %" PRIu64
3667               ") listener.WaitForEvent (NULL, event_sp)...",
3668               __FUNCTION__, arg, process->GetID());
3669     if (process->m_async_listener_sp->GetEvent(event_sp, llvm::None)) {
3670       const uint32_t event_type = event_sp->GetType();
3671       if (event_sp->BroadcasterIs(&process->m_async_broadcaster)) {
3672         LLDB_LOGF(log,
3673                   "ProcessGDBRemote::%s (arg = %p, pid = %" PRIu64
3674                   ") Got an event of type: %d...",
3675                   __FUNCTION__, arg, process->GetID(), event_type);
3676 
3677         switch (event_type) {
3678         case eBroadcastBitAsyncContinue: {
3679           const EventDataBytes *continue_packet =
3680               EventDataBytes::GetEventDataFromEvent(event_sp.get());
3681 
3682           if (continue_packet) {
3683             const char *continue_cstr =
3684                 (const char *)continue_packet->GetBytes();
3685             const size_t continue_cstr_len = continue_packet->GetByteSize();
3686             LLDB_LOGF(log,
3687                       "ProcessGDBRemote::%s (arg = %p, pid = %" PRIu64
3688                       ") got eBroadcastBitAsyncContinue: %s",
3689                       __FUNCTION__, arg, process->GetID(), continue_cstr);
3690 
3691             if (::strstr(continue_cstr, "vAttach") == nullptr)
3692               process->SetPrivateState(eStateRunning);
3693             StringExtractorGDBRemote response;
3694 
3695             // If in Non-Stop-Mode
3696             if (process->GetTarget().GetNonStopModeEnabled()) {
3697               // send the vCont packet
3698               if (!process->GetGDBRemote().SendvContPacket(
3699                       llvm::StringRef(continue_cstr, continue_cstr_len),
3700                       response)) {
3701                 // Something went wrong
3702                 done = true;
3703                 break;
3704               }
3705             }
3706             // If in All-Stop-Mode
3707             else {
3708               StateType stop_state =
3709                   process->GetGDBRemote().SendContinuePacketAndWaitForResponse(
3710                       *process, *process->GetUnixSignals(),
3711                       llvm::StringRef(continue_cstr, continue_cstr_len),
3712                       response);
3713 
3714               // We need to immediately clear the thread ID list so we are sure
3715               // to get a valid list of threads. The thread ID list might be
3716               // contained within the "response", or the stop reply packet that
3717               // caused the stop. So clear it now before we give the stop reply
3718               // packet to the process using the
3719               // process->SetLastStopPacket()...
3720               process->ClearThreadIDList();
3721 
3722               switch (stop_state) {
3723               case eStateStopped:
3724               case eStateCrashed:
3725               case eStateSuspended:
3726                 process->SetLastStopPacket(response);
3727                 process->SetPrivateState(stop_state);
3728                 break;
3729 
3730               case eStateExited: {
3731                 process->SetLastStopPacket(response);
3732                 process->ClearThreadIDList();
3733                 response.SetFilePos(1);
3734 
3735                 int exit_status = response.GetHexU8();
3736                 std::string desc_string;
3737                 if (response.GetBytesLeft() > 0 &&
3738                     response.GetChar('-') == ';') {
3739                   llvm::StringRef desc_str;
3740                   llvm::StringRef desc_token;
3741                   while (response.GetNameColonValue(desc_token, desc_str)) {
3742                     if (desc_token != "description")
3743                       continue;
3744                     StringExtractor extractor(desc_str);
3745                     extractor.GetHexByteString(desc_string);
3746                   }
3747                 }
3748                 process->SetExitStatus(exit_status, desc_string.c_str());
3749                 done = true;
3750                 break;
3751               }
3752               case eStateInvalid: {
3753                 // Check to see if we were trying to attach and if we got back
3754                 // the "E87" error code from debugserver -- this indicates that
3755                 // the process is not debuggable.  Return a slightly more
3756                 // helpful error message about why the attach failed.
3757                 if (::strstr(continue_cstr, "vAttach") != nullptr &&
3758                     response.GetError() == 0x87) {
3759                   process->SetExitStatus(-1, "cannot attach to process due to "
3760                                              "System Integrity Protection");
3761                 } else if (::strstr(continue_cstr, "vAttach") != nullptr &&
3762                            response.GetStatus().Fail()) {
3763                   process->SetExitStatus(-1, response.GetStatus().AsCString());
3764                 } else {
3765                   process->SetExitStatus(-1, "lost connection");
3766                 }
3767                 break;
3768               }
3769 
3770               default:
3771                 process->SetPrivateState(stop_state);
3772                 break;
3773               } // switch(stop_state)
3774             }   // else // if in All-stop-mode
3775           }     // if (continue_packet)
3776         }       // case eBroadcastBitAsyncContinue
3777         break;
3778 
3779         case eBroadcastBitAsyncThreadShouldExit:
3780           LLDB_LOGF(log,
3781                     "ProcessGDBRemote::%s (arg = %p, pid = %" PRIu64
3782                     ") got eBroadcastBitAsyncThreadShouldExit...",
3783                     __FUNCTION__, arg, process->GetID());
3784           done = true;
3785           break;
3786 
3787         default:
3788           LLDB_LOGF(log,
3789                     "ProcessGDBRemote::%s (arg = %p, pid = %" PRIu64
3790                     ") got unknown event 0x%8.8x",
3791                     __FUNCTION__, arg, process->GetID(), event_type);
3792           done = true;
3793           break;
3794         }
3795       } else if (event_sp->BroadcasterIs(&process->m_gdb_comm)) {
3796         switch (event_type) {
3797         case Communication::eBroadcastBitReadThreadDidExit:
3798           process->SetExitStatus(-1, "lost connection");
3799           done = true;
3800           break;
3801 
3802         case GDBRemoteCommunication::eBroadcastBitGdbReadThreadGotNotify: {
3803           lldb_private::Event *event = event_sp.get();
3804           const EventDataBytes *continue_packet =
3805               EventDataBytes::GetEventDataFromEvent(event);
3806           StringExtractorGDBRemote notify(
3807               (const char *)continue_packet->GetBytes());
3808           // Hand this over to the process to handle
3809           process->HandleNotifyPacket(notify);
3810           break;
3811         }
3812 
3813         default:
3814           LLDB_LOGF(log,
3815                     "ProcessGDBRemote::%s (arg = %p, pid = %" PRIu64
3816                     ") got unknown event 0x%8.8x",
3817                     __FUNCTION__, arg, process->GetID(), event_type);
3818           done = true;
3819           break;
3820         }
3821       }
3822     } else {
3823       LLDB_LOGF(log,
3824                 "ProcessGDBRemote::%s (arg = %p, pid = %" PRIu64
3825                 ") listener.WaitForEvent (NULL, event_sp) => false",
3826                 __FUNCTION__, arg, process->GetID());
3827       done = true;
3828     }
3829   }
3830 
3831   LLDB_LOGF(log,
3832             "ProcessGDBRemote::%s (arg = %p, pid = %" PRIu64
3833             ") thread exiting...",
3834             __FUNCTION__, arg, process->GetID());
3835 
3836   return {};
3837 }
3838 
3839 // uint32_t
3840 // ProcessGDBRemote::ListProcessesMatchingName (const char *name, StringList
3841 // &matches, std::vector<lldb::pid_t> &pids)
3842 //{
3843 //    // If we are planning to launch the debugserver remotely, then we need to
3844 //    fire up a debugserver
3845 //    // process and ask it for the list of processes. But if we are local, we
3846 //    can let the Host do it.
3847 //    if (m_local_debugserver)
3848 //    {
3849 //        return Host::ListProcessesMatchingName (name, matches, pids);
3850 //    }
3851 //    else
3852 //    {
3853 //        // FIXME: Implement talking to the remote debugserver.
3854 //        return 0;
3855 //    }
3856 //
3857 //}
3858 //
3859 bool ProcessGDBRemote::NewThreadNotifyBreakpointHit(
3860     void *baton, StoppointCallbackContext *context, lldb::user_id_t break_id,
3861     lldb::user_id_t break_loc_id) {
3862   // I don't think I have to do anything here, just make sure I notice the new
3863   // thread when it starts to
3864   // run so I can stop it if that's what I want to do.
3865   Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_STEP));
3866   LLDB_LOGF(log, "Hit New Thread Notification breakpoint.");
3867   return false;
3868 }
3869 
3870 Status ProcessGDBRemote::UpdateAutomaticSignalFiltering() {
3871   Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
3872   LLDB_LOG(log, "Check if need to update ignored signals");
3873 
3874   // QPassSignals package is not supported by the server, there is no way we
3875   // can ignore any signals on server side.
3876   if (!m_gdb_comm.GetQPassSignalsSupported())
3877     return Status();
3878 
3879   // No signals, nothing to send.
3880   if (m_unix_signals_sp == nullptr)
3881     return Status();
3882 
3883   // Signals' version hasn't changed, no need to send anything.
3884   uint64_t new_signals_version = m_unix_signals_sp->GetVersion();
3885   if (new_signals_version == m_last_signals_version) {
3886     LLDB_LOG(log, "Signals' version hasn't changed. version={0}",
3887              m_last_signals_version);
3888     return Status();
3889   }
3890 
3891   auto signals_to_ignore =
3892       m_unix_signals_sp->GetFilteredSignals(false, false, false);
3893   Status error = m_gdb_comm.SendSignalsToIgnore(signals_to_ignore);
3894 
3895   LLDB_LOG(log,
3896            "Signals' version changed. old version={0}, new version={1}, "
3897            "signals ignored={2}, update result={3}",
3898            m_last_signals_version, new_signals_version,
3899            signals_to_ignore.size(), error);
3900 
3901   if (error.Success())
3902     m_last_signals_version = new_signals_version;
3903 
3904   return error;
3905 }
3906 
3907 bool ProcessGDBRemote::StartNoticingNewThreads() {
3908   Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_STEP));
3909   if (m_thread_create_bp_sp) {
3910     if (log && log->GetVerbose())
3911       LLDB_LOGF(log, "Enabled noticing new thread breakpoint.");
3912     m_thread_create_bp_sp->SetEnabled(true);
3913   } else {
3914     PlatformSP platform_sp(GetTarget().GetPlatform());
3915     if (platform_sp) {
3916       m_thread_create_bp_sp =
3917           platform_sp->SetThreadCreationBreakpoint(GetTarget());
3918       if (m_thread_create_bp_sp) {
3919         if (log && log->GetVerbose())
3920           LLDB_LOGF(
3921               log, "Successfully created new thread notification breakpoint %i",
3922               m_thread_create_bp_sp->GetID());
3923         m_thread_create_bp_sp->SetCallback(
3924             ProcessGDBRemote::NewThreadNotifyBreakpointHit, this, true);
3925       } else {
3926         LLDB_LOGF(log, "Failed to create new thread notification breakpoint.");
3927       }
3928     }
3929   }
3930   return m_thread_create_bp_sp.get() != nullptr;
3931 }
3932 
3933 bool ProcessGDBRemote::StopNoticingNewThreads() {
3934   Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_STEP));
3935   if (log && log->GetVerbose())
3936     LLDB_LOGF(log, "Disabling new thread notification breakpoint.");
3937 
3938   if (m_thread_create_bp_sp)
3939     m_thread_create_bp_sp->SetEnabled(false);
3940 
3941   return true;
3942 }
3943 
3944 DynamicLoader *ProcessGDBRemote::GetDynamicLoader() {
3945   if (m_dyld_up.get() == nullptr)
3946     m_dyld_up.reset(DynamicLoader::FindPlugin(this, nullptr));
3947   return m_dyld_up.get();
3948 }
3949 
3950 Status ProcessGDBRemote::SendEventData(const char *data) {
3951   int return_value;
3952   bool was_supported;
3953 
3954   Status error;
3955 
3956   return_value = m_gdb_comm.SendLaunchEventDataPacket(data, &was_supported);
3957   if (return_value != 0) {
3958     if (!was_supported)
3959       error.SetErrorString("Sending events is not supported for this process.");
3960     else
3961       error.SetErrorStringWithFormat("Error sending event data: %d.",
3962                                      return_value);
3963   }
3964   return error;
3965 }
3966 
3967 DataExtractor ProcessGDBRemote::GetAuxvData() {
3968   DataBufferSP buf;
3969   if (m_gdb_comm.GetQXferAuxvReadSupported()) {
3970     std::string response_string;
3971     if (m_gdb_comm.SendPacketsAndConcatenateResponses("qXfer:auxv:read::",
3972                                                       response_string) ==
3973         GDBRemoteCommunication::PacketResult::Success)
3974       buf = std::make_shared<DataBufferHeap>(response_string.c_str(),
3975                                              response_string.length());
3976   }
3977   return DataExtractor(buf, GetByteOrder(), GetAddressByteSize());
3978 }
3979 
3980 StructuredData::ObjectSP
3981 ProcessGDBRemote::GetExtendedInfoForThread(lldb::tid_t tid) {
3982   StructuredData::ObjectSP object_sp;
3983 
3984   if (m_gdb_comm.GetThreadExtendedInfoSupported()) {
3985     StructuredData::ObjectSP args_dict(new StructuredData::Dictionary());
3986     SystemRuntime *runtime = GetSystemRuntime();
3987     if (runtime) {
3988       runtime->AddThreadExtendedInfoPacketHints(args_dict);
3989     }
3990     args_dict->GetAsDictionary()->AddIntegerItem("thread", tid);
3991 
3992     StreamString packet;
3993     packet << "jThreadExtendedInfo:";
3994     args_dict->Dump(packet, false);
3995 
3996     // FIXME the final character of a JSON dictionary, '}', is the escape
3997     // character in gdb-remote binary mode.  lldb currently doesn't escape
3998     // these characters in its packet output -- so we add the quoted version of
3999     // the } character here manually in case we talk to a debugserver which un-
4000     // escapes the characters at packet read time.
4001     packet << (char)(0x7d ^ 0x20);
4002 
4003     StringExtractorGDBRemote response;
4004     response.SetResponseValidatorToJSON();
4005     if (m_gdb_comm.SendPacketAndWaitForResponse(packet.GetString(), response,
4006                                                 false) ==
4007         GDBRemoteCommunication::PacketResult::Success) {
4008       StringExtractorGDBRemote::ResponseType response_type =
4009           response.GetResponseType();
4010       if (response_type == StringExtractorGDBRemote::eResponse) {
4011         if (!response.Empty()) {
4012           object_sp =
4013               StructuredData::ParseJSON(std::string(response.GetStringRef()));
4014         }
4015       }
4016     }
4017   }
4018   return object_sp;
4019 }
4020 
4021 StructuredData::ObjectSP ProcessGDBRemote::GetLoadedDynamicLibrariesInfos(
4022     lldb::addr_t image_list_address, lldb::addr_t image_count) {
4023 
4024   StructuredData::ObjectSP args_dict(new StructuredData::Dictionary());
4025   args_dict->GetAsDictionary()->AddIntegerItem("image_list_address",
4026                                                image_list_address);
4027   args_dict->GetAsDictionary()->AddIntegerItem("image_count", image_count);
4028 
4029   return GetLoadedDynamicLibrariesInfos_sender(args_dict);
4030 }
4031 
4032 StructuredData::ObjectSP ProcessGDBRemote::GetLoadedDynamicLibrariesInfos() {
4033   StructuredData::ObjectSP args_dict(new StructuredData::Dictionary());
4034 
4035   args_dict->GetAsDictionary()->AddBooleanItem("fetch_all_solibs", true);
4036 
4037   return GetLoadedDynamicLibrariesInfos_sender(args_dict);
4038 }
4039 
4040 StructuredData::ObjectSP ProcessGDBRemote::GetLoadedDynamicLibrariesInfos(
4041     const std::vector<lldb::addr_t> &load_addresses) {
4042   StructuredData::ObjectSP args_dict(new StructuredData::Dictionary());
4043   StructuredData::ArraySP addresses(new StructuredData::Array);
4044 
4045   for (auto addr : load_addresses) {
4046     StructuredData::ObjectSP addr_sp(new StructuredData::Integer(addr));
4047     addresses->AddItem(addr_sp);
4048   }
4049 
4050   args_dict->GetAsDictionary()->AddItem("solib_addresses", addresses);
4051 
4052   return GetLoadedDynamicLibrariesInfos_sender(args_dict);
4053 }
4054 
4055 StructuredData::ObjectSP
4056 ProcessGDBRemote::GetLoadedDynamicLibrariesInfos_sender(
4057     StructuredData::ObjectSP args_dict) {
4058   StructuredData::ObjectSP object_sp;
4059 
4060   if (m_gdb_comm.GetLoadedDynamicLibrariesInfosSupported()) {
4061     // Scope for the scoped timeout object
4062     GDBRemoteCommunication::ScopedTimeout timeout(m_gdb_comm,
4063                                                   std::chrono::seconds(10));
4064 
4065     StreamString packet;
4066     packet << "jGetLoadedDynamicLibrariesInfos:";
4067     args_dict->Dump(packet, false);
4068 
4069     // FIXME the final character of a JSON dictionary, '}', is the escape
4070     // character in gdb-remote binary mode.  lldb currently doesn't escape
4071     // these characters in its packet output -- so we add the quoted version of
4072     // the } character here manually in case we talk to a debugserver which un-
4073     // escapes the characters at packet read time.
4074     packet << (char)(0x7d ^ 0x20);
4075 
4076     StringExtractorGDBRemote response;
4077     response.SetResponseValidatorToJSON();
4078     if (m_gdb_comm.SendPacketAndWaitForResponse(packet.GetString(), response,
4079                                                 false) ==
4080         GDBRemoteCommunication::PacketResult::Success) {
4081       StringExtractorGDBRemote::ResponseType response_type =
4082           response.GetResponseType();
4083       if (response_type == StringExtractorGDBRemote::eResponse) {
4084         if (!response.Empty()) {
4085           object_sp =
4086               StructuredData::ParseJSON(std::string(response.GetStringRef()));
4087         }
4088       }
4089     }
4090   }
4091   return object_sp;
4092 }
4093 
4094 StructuredData::ObjectSP ProcessGDBRemote::GetSharedCacheInfo() {
4095   StructuredData::ObjectSP object_sp;
4096   StructuredData::ObjectSP args_dict(new StructuredData::Dictionary());
4097 
4098   if (m_gdb_comm.GetSharedCacheInfoSupported()) {
4099     StreamString packet;
4100     packet << "jGetSharedCacheInfo:";
4101     args_dict->Dump(packet, false);
4102 
4103     // FIXME the final character of a JSON dictionary, '}', is the escape
4104     // character in gdb-remote binary mode.  lldb currently doesn't escape
4105     // these characters in its packet output -- so we add the quoted version of
4106     // the } character here manually in case we talk to a debugserver which un-
4107     // escapes the characters at packet read time.
4108     packet << (char)(0x7d ^ 0x20);
4109 
4110     StringExtractorGDBRemote response;
4111     response.SetResponseValidatorToJSON();
4112     if (m_gdb_comm.SendPacketAndWaitForResponse(packet.GetString(), response,
4113                                                 false) ==
4114         GDBRemoteCommunication::PacketResult::Success) {
4115       StringExtractorGDBRemote::ResponseType response_type =
4116           response.GetResponseType();
4117       if (response_type == StringExtractorGDBRemote::eResponse) {
4118         if (!response.Empty()) {
4119           object_sp =
4120               StructuredData::ParseJSON(std::string(response.GetStringRef()));
4121         }
4122       }
4123     }
4124   }
4125   return object_sp;
4126 }
4127 
4128 Status ProcessGDBRemote::ConfigureStructuredData(
4129     ConstString type_name, const StructuredData::ObjectSP &config_sp) {
4130   return m_gdb_comm.ConfigureRemoteStructuredData(type_name, config_sp);
4131 }
4132 
4133 // Establish the largest memory read/write payloads we should use. If the
4134 // remote stub has a max packet size, stay under that size.
4135 //
4136 // If the remote stub's max packet size is crazy large, use a reasonable
4137 // largeish default.
4138 //
4139 // If the remote stub doesn't advertise a max packet size, use a conservative
4140 // default.
4141 
4142 void ProcessGDBRemote::GetMaxMemorySize() {
4143   const uint64_t reasonable_largeish_default = 128 * 1024;
4144   const uint64_t conservative_default = 512;
4145 
4146   if (m_max_memory_size == 0) {
4147     uint64_t stub_max_size = m_gdb_comm.GetRemoteMaxPacketSize();
4148     if (stub_max_size != UINT64_MAX && stub_max_size != 0) {
4149       // Save the stub's claimed maximum packet size
4150       m_remote_stub_max_memory_size = stub_max_size;
4151 
4152       // Even if the stub says it can support ginormous packets, don't exceed
4153       // our reasonable largeish default packet size.
4154       if (stub_max_size > reasonable_largeish_default) {
4155         stub_max_size = reasonable_largeish_default;
4156       }
4157 
4158       // Memory packet have other overheads too like Maddr,size:#NN Instead of
4159       // calculating the bytes taken by size and addr every time, we take a
4160       // maximum guess here.
4161       if (stub_max_size > 70)
4162         stub_max_size -= 32 + 32 + 6;
4163       else {
4164         // In unlikely scenario that max packet size is less then 70, we will
4165         // hope that data being written is small enough to fit.
4166         Log *log(ProcessGDBRemoteLog::GetLogIfAnyCategoryIsSet(
4167             GDBR_LOG_COMM | GDBR_LOG_MEMORY));
4168         if (log)
4169           log->Warning("Packet size is too small. "
4170                        "LLDB may face problems while writing memory");
4171       }
4172 
4173       m_max_memory_size = stub_max_size;
4174     } else {
4175       m_max_memory_size = conservative_default;
4176     }
4177   }
4178 }
4179 
4180 void ProcessGDBRemote::SetUserSpecifiedMaxMemoryTransferSize(
4181     uint64_t user_specified_max) {
4182   if (user_specified_max != 0) {
4183     GetMaxMemorySize();
4184 
4185     if (m_remote_stub_max_memory_size != 0) {
4186       if (m_remote_stub_max_memory_size < user_specified_max) {
4187         m_max_memory_size = m_remote_stub_max_memory_size; // user specified a
4188                                                            // packet size too
4189                                                            // big, go as big
4190         // as the remote stub says we can go.
4191       } else {
4192         m_max_memory_size = user_specified_max; // user's packet size is good
4193       }
4194     } else {
4195       m_max_memory_size =
4196           user_specified_max; // user's packet size is probably fine
4197     }
4198   }
4199 }
4200 
4201 bool ProcessGDBRemote::GetModuleSpec(const FileSpec &module_file_spec,
4202                                      const ArchSpec &arch,
4203                                      ModuleSpec &module_spec) {
4204   Log *log = GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PLATFORM);
4205 
4206   const ModuleCacheKey key(module_file_spec.GetPath(),
4207                            arch.GetTriple().getTriple());
4208   auto cached = m_cached_module_specs.find(key);
4209   if (cached != m_cached_module_specs.end()) {
4210     module_spec = cached->second;
4211     return bool(module_spec);
4212   }
4213 
4214   if (!m_gdb_comm.GetModuleInfo(module_file_spec, arch, module_spec)) {
4215     LLDB_LOGF(log, "ProcessGDBRemote::%s - failed to get module info for %s:%s",
4216               __FUNCTION__, module_file_spec.GetPath().c_str(),
4217               arch.GetTriple().getTriple().c_str());
4218     return false;
4219   }
4220 
4221   if (log) {
4222     StreamString stream;
4223     module_spec.Dump(stream);
4224     LLDB_LOGF(log, "ProcessGDBRemote::%s - got module info for (%s:%s) : %s",
4225               __FUNCTION__, module_file_spec.GetPath().c_str(),
4226               arch.GetTriple().getTriple().c_str(), stream.GetData());
4227   }
4228 
4229   m_cached_module_specs[key] = module_spec;
4230   return true;
4231 }
4232 
4233 void ProcessGDBRemote::PrefetchModuleSpecs(
4234     llvm::ArrayRef<FileSpec> module_file_specs, const llvm::Triple &triple) {
4235   auto module_specs = m_gdb_comm.GetModulesInfo(module_file_specs, triple);
4236   if (module_specs) {
4237     for (const FileSpec &spec : module_file_specs)
4238       m_cached_module_specs[ModuleCacheKey(spec.GetPath(),
4239                                            triple.getTriple())] = ModuleSpec();
4240     for (const ModuleSpec &spec : *module_specs)
4241       m_cached_module_specs[ModuleCacheKey(spec.GetFileSpec().GetPath(),
4242                                            triple.getTriple())] = spec;
4243   }
4244 }
4245 
4246 llvm::VersionTuple ProcessGDBRemote::GetHostOSVersion() {
4247   return m_gdb_comm.GetOSVersion();
4248 }
4249 
4250 llvm::VersionTuple ProcessGDBRemote::GetHostMacCatalystVersion() {
4251   return m_gdb_comm.GetMacCatalystVersion();
4252 }
4253 
4254 namespace {
4255 
4256 typedef std::vector<std::string> stringVec;
4257 
4258 typedef std::vector<struct GdbServerRegisterInfo> GDBServerRegisterVec;
4259 struct RegisterSetInfo {
4260   ConstString name;
4261 };
4262 
4263 typedef std::map<uint32_t, RegisterSetInfo> RegisterSetMap;
4264 
4265 struct GdbServerTargetInfo {
4266   std::string arch;
4267   std::string osabi;
4268   stringVec includes;
4269   RegisterSetMap reg_set_map;
4270 };
4271 
4272 bool ParseRegisters(XMLNode feature_node, GdbServerTargetInfo &target_info,
4273                     GDBRemoteDynamicRegisterInfo &dyn_reg_info, ABISP abi_sp,
4274                     uint32_t &cur_reg_num, uint32_t &reg_offset) {
4275   if (!feature_node)
4276     return false;
4277 
4278   feature_node.ForEachChildElementWithName(
4279       "reg",
4280       [&target_info, &dyn_reg_info, &cur_reg_num, &reg_offset,
4281        &abi_sp](const XMLNode &reg_node) -> bool {
4282         std::string gdb_group;
4283         std::string gdb_type;
4284         ConstString reg_name;
4285         ConstString alt_name;
4286         ConstString set_name;
4287         std::vector<uint32_t> value_regs;
4288         std::vector<uint32_t> invalidate_regs;
4289         std::vector<uint8_t> dwarf_opcode_bytes;
4290         bool encoding_set = false;
4291         bool format_set = false;
4292         RegisterInfo reg_info = {
4293             nullptr,       // Name
4294             nullptr,       // Alt name
4295             0,             // byte size
4296             reg_offset,    // offset
4297             eEncodingUint, // encoding
4298             eFormatHex,    // format
4299             {
4300                 LLDB_INVALID_REGNUM, // eh_frame reg num
4301                 LLDB_INVALID_REGNUM, // DWARF reg num
4302                 LLDB_INVALID_REGNUM, // generic reg num
4303                 cur_reg_num,         // process plugin reg num
4304                 cur_reg_num          // native register number
4305             },
4306             nullptr,
4307             nullptr,
4308             nullptr, // Dwarf Expression opcode bytes pointer
4309             0        // Dwarf Expression opcode bytes length
4310         };
4311 
4312         reg_node.ForEachAttribute([&target_info, &gdb_group, &gdb_type,
4313                                    &reg_name, &alt_name, &set_name, &value_regs,
4314                                    &invalidate_regs, &encoding_set, &format_set,
4315                                    &reg_info, &reg_offset, &dwarf_opcode_bytes](
4316                                       const llvm::StringRef &name,
4317                                       const llvm::StringRef &value) -> bool {
4318           if (name == "name") {
4319             reg_name.SetString(value);
4320           } else if (name == "bitsize") {
4321             reg_info.byte_size =
4322                 StringConvert::ToUInt32(value.data(), 0, 0) / CHAR_BIT;
4323           } else if (name == "type") {
4324             gdb_type = value.str();
4325           } else if (name == "group") {
4326             gdb_group = value.str();
4327           } else if (name == "regnum") {
4328             const uint32_t regnum =
4329                 StringConvert::ToUInt32(value.data(), LLDB_INVALID_REGNUM, 0);
4330             if (regnum != LLDB_INVALID_REGNUM) {
4331               reg_info.kinds[eRegisterKindProcessPlugin] = regnum;
4332             }
4333           } else if (name == "offset") {
4334             reg_offset = StringConvert::ToUInt32(value.data(), UINT32_MAX, 0);
4335           } else if (name == "altname") {
4336             alt_name.SetString(value);
4337           } else if (name == "encoding") {
4338             encoding_set = true;
4339             reg_info.encoding = Args::StringToEncoding(value, eEncodingUint);
4340           } else if (name == "format") {
4341             format_set = true;
4342             Format format = eFormatInvalid;
4343             if (OptionArgParser::ToFormat(value.data(), format, nullptr)
4344                     .Success())
4345               reg_info.format = format;
4346             else if (value == "vector-sint8")
4347               reg_info.format = eFormatVectorOfSInt8;
4348             else if (value == "vector-uint8")
4349               reg_info.format = eFormatVectorOfUInt8;
4350             else if (value == "vector-sint16")
4351               reg_info.format = eFormatVectorOfSInt16;
4352             else if (value == "vector-uint16")
4353               reg_info.format = eFormatVectorOfUInt16;
4354             else if (value == "vector-sint32")
4355               reg_info.format = eFormatVectorOfSInt32;
4356             else if (value == "vector-uint32")
4357               reg_info.format = eFormatVectorOfUInt32;
4358             else if (value == "vector-float32")
4359               reg_info.format = eFormatVectorOfFloat32;
4360             else if (value == "vector-uint64")
4361               reg_info.format = eFormatVectorOfUInt64;
4362             else if (value == "vector-uint128")
4363               reg_info.format = eFormatVectorOfUInt128;
4364           } else if (name == "group_id") {
4365             const uint32_t set_id =
4366                 StringConvert::ToUInt32(value.data(), UINT32_MAX, 0);
4367             RegisterSetMap::const_iterator pos =
4368                 target_info.reg_set_map.find(set_id);
4369             if (pos != target_info.reg_set_map.end())
4370               set_name = pos->second.name;
4371           } else if (name == "gcc_regnum" || name == "ehframe_regnum") {
4372             reg_info.kinds[eRegisterKindEHFrame] =
4373                 StringConvert::ToUInt32(value.data(), LLDB_INVALID_REGNUM, 0);
4374           } else if (name == "dwarf_regnum") {
4375             reg_info.kinds[eRegisterKindDWARF] =
4376                 StringConvert::ToUInt32(value.data(), LLDB_INVALID_REGNUM, 0);
4377           } else if (name == "generic") {
4378             reg_info.kinds[eRegisterKindGeneric] =
4379                 Args::StringToGenericRegister(value);
4380           } else if (name == "value_regnums") {
4381             SplitCommaSeparatedRegisterNumberString(value, value_regs, 0);
4382           } else if (name == "invalidate_regnums") {
4383             SplitCommaSeparatedRegisterNumberString(value, invalidate_regs, 0);
4384           } else if (name == "dynamic_size_dwarf_expr_bytes") {
4385             std::string opcode_string = value.str();
4386             size_t dwarf_opcode_len = opcode_string.length() / 2;
4387             assert(dwarf_opcode_len > 0);
4388 
4389             dwarf_opcode_bytes.resize(dwarf_opcode_len);
4390             reg_info.dynamic_size_dwarf_len = dwarf_opcode_len;
4391             StringExtractor opcode_extractor(opcode_string);
4392             uint32_t ret_val =
4393                 opcode_extractor.GetHexBytesAvail(dwarf_opcode_bytes);
4394             assert(dwarf_opcode_len == ret_val);
4395             UNUSED_IF_ASSERT_DISABLED(ret_val);
4396             reg_info.dynamic_size_dwarf_expr_bytes = dwarf_opcode_bytes.data();
4397           } else {
4398             printf("unhandled attribute %s = %s\n", name.data(), value.data());
4399           }
4400           return true; // Keep iterating through all attributes
4401         });
4402 
4403         if (!gdb_type.empty() && !(encoding_set || format_set)) {
4404           if (llvm::StringRef(gdb_type).startswith("int")) {
4405             reg_info.format = eFormatHex;
4406             reg_info.encoding = eEncodingUint;
4407           } else if (gdb_type == "data_ptr" || gdb_type == "code_ptr") {
4408             reg_info.format = eFormatAddressInfo;
4409             reg_info.encoding = eEncodingUint;
4410           } else if (gdb_type == "i387_ext" || gdb_type == "float") {
4411             reg_info.format = eFormatFloat;
4412             reg_info.encoding = eEncodingIEEE754;
4413           }
4414         }
4415 
4416         // Only update the register set name if we didn't get a "reg_set"
4417         // attribute. "set_name" will be empty if we didn't have a "reg_set"
4418         // attribute.
4419         if (!set_name) {
4420           if (!gdb_group.empty()) {
4421             set_name.SetCString(gdb_group.c_str());
4422           } else {
4423             // If no register group name provided anywhere,
4424             // we'll create a 'general' register set
4425             set_name.SetCString("general");
4426           }
4427         }
4428 
4429         reg_info.byte_offset = reg_offset;
4430         assert(reg_info.byte_size != 0);
4431         reg_offset += reg_info.byte_size;
4432         if (!value_regs.empty()) {
4433           value_regs.push_back(LLDB_INVALID_REGNUM);
4434           reg_info.value_regs = value_regs.data();
4435         }
4436         if (!invalidate_regs.empty()) {
4437           invalidate_regs.push_back(LLDB_INVALID_REGNUM);
4438           reg_info.invalidate_regs = invalidate_regs.data();
4439         }
4440 
4441         ++cur_reg_num;
4442         reg_info.name = reg_name.AsCString();
4443         if (abi_sp)
4444           abi_sp->AugmentRegisterInfo(reg_info);
4445         dyn_reg_info.AddRegister(reg_info, reg_name, alt_name, set_name);
4446 
4447         return true; // Keep iterating through all "reg" elements
4448       });
4449   return true;
4450 }
4451 
4452 } // namespace
4453 
4454 // This method fetches a register description feature xml file from
4455 // the remote stub and adds registers/register groupsets/architecture
4456 // information to the current process.  It will call itself recursively
4457 // for nested register definition files.  It returns true if it was able
4458 // to fetch and parse an xml file.
4459 bool ProcessGDBRemote::GetGDBServerRegisterInfoXMLAndProcess(
4460     ArchSpec &arch_to_use, std::string xml_filename, uint32_t &cur_reg_num,
4461     uint32_t &reg_offset) {
4462   // request the target xml file
4463   std::string raw;
4464   lldb_private::Status lldberr;
4465   if (!m_gdb_comm.ReadExtFeature(ConstString("features"),
4466                                  ConstString(xml_filename.c_str()), raw,
4467                                  lldberr)) {
4468     return false;
4469   }
4470 
4471   XMLDocument xml_document;
4472 
4473   if (xml_document.ParseMemory(raw.c_str(), raw.size(), xml_filename.c_str())) {
4474     GdbServerTargetInfo target_info;
4475     std::vector<XMLNode> feature_nodes;
4476 
4477     // The top level feature XML file will start with a <target> tag.
4478     XMLNode target_node = xml_document.GetRootElement("target");
4479     if (target_node) {
4480       target_node.ForEachChildElement([&target_info, &feature_nodes](
4481                                           const XMLNode &node) -> bool {
4482         llvm::StringRef name = node.GetName();
4483         if (name == "architecture") {
4484           node.GetElementText(target_info.arch);
4485         } else if (name == "osabi") {
4486           node.GetElementText(target_info.osabi);
4487         } else if (name == "xi:include" || name == "include") {
4488           llvm::StringRef href = node.GetAttributeValue("href");
4489           if (!href.empty())
4490             target_info.includes.push_back(href.str());
4491         } else if (name == "feature") {
4492           feature_nodes.push_back(node);
4493         } else if (name == "groups") {
4494           node.ForEachChildElementWithName(
4495               "group", [&target_info](const XMLNode &node) -> bool {
4496                 uint32_t set_id = UINT32_MAX;
4497                 RegisterSetInfo set_info;
4498 
4499                 node.ForEachAttribute(
4500                     [&set_id, &set_info](const llvm::StringRef &name,
4501                                          const llvm::StringRef &value) -> bool {
4502                       if (name == "id")
4503                         set_id = StringConvert::ToUInt32(value.data(),
4504                                                          UINT32_MAX, 0);
4505                       if (name == "name")
4506                         set_info.name = ConstString(value);
4507                       return true; // Keep iterating through all attributes
4508                     });
4509 
4510                 if (set_id != UINT32_MAX)
4511                   target_info.reg_set_map[set_id] = set_info;
4512                 return true; // Keep iterating through all "group" elements
4513               });
4514         }
4515         return true; // Keep iterating through all children of the target_node
4516       });
4517     } else {
4518       // In an included XML feature file, we're already "inside" the <target>
4519       // tag of the initial XML file; this included file will likely only have
4520       // a <feature> tag.  Need to check for any more included files in this
4521       // <feature> element.
4522       XMLNode feature_node = xml_document.GetRootElement("feature");
4523       if (feature_node) {
4524         feature_nodes.push_back(feature_node);
4525         feature_node.ForEachChildElement([&target_info](
4526                                         const XMLNode &node) -> bool {
4527           llvm::StringRef name = node.GetName();
4528           if (name == "xi:include" || name == "include") {
4529             llvm::StringRef href = node.GetAttributeValue("href");
4530             if (!href.empty())
4531               target_info.includes.push_back(href.str());
4532             }
4533             return true;
4534           });
4535       }
4536     }
4537 
4538     // If the target.xml includes an architecture entry like
4539     //   <architecture>i386:x86-64</architecture> (seen from VMWare ESXi)
4540     //   <architecture>arm</architecture> (seen from Segger JLink on unspecified arm board)
4541     // use that if we don't have anything better.
4542     if (!arch_to_use.IsValid() && !target_info.arch.empty()) {
4543       if (target_info.arch == "i386:x86-64") {
4544         // We don't have any information about vendor or OS.
4545         arch_to_use.SetTriple("x86_64--");
4546         GetTarget().MergeArchitecture(arch_to_use);
4547       }
4548 
4549       // SEGGER J-Link jtag boards send this very-generic arch name,
4550       // we'll need to use this if we have absolutely nothing better
4551       // to work with or the register definitions won't be accepted.
4552       if (target_info.arch == "arm") {
4553         arch_to_use.SetTriple("arm--");
4554         GetTarget().MergeArchitecture(arch_to_use);
4555       }
4556     }
4557 
4558     if (arch_to_use.IsValid()) {
4559       // Don't use Process::GetABI, this code gets called from DidAttach, and
4560       // in that context we haven't set the Target's architecture yet, so the
4561       // ABI is also potentially incorrect.
4562       ABISP abi_to_use_sp = ABI::FindPlugin(shared_from_this(), arch_to_use);
4563       for (auto &feature_node : feature_nodes) {
4564         ParseRegisters(feature_node, target_info, this->m_register_info,
4565                        abi_to_use_sp, cur_reg_num, reg_offset);
4566       }
4567 
4568       for (const auto &include : target_info.includes) {
4569         GetGDBServerRegisterInfoXMLAndProcess(arch_to_use, include, cur_reg_num,
4570                                               reg_offset);
4571       }
4572     }
4573   } else {
4574     return false;
4575   }
4576   return true;
4577 }
4578 
4579 // query the target of gdb-remote for extended target information returns
4580 // true on success (got register definitions), false on failure (did not).
4581 bool ProcessGDBRemote::GetGDBServerRegisterInfo(ArchSpec &arch_to_use) {
4582   // Make sure LLDB has an XML parser it can use first
4583   if (!XMLDocument::XMLEnabled())
4584     return false;
4585 
4586   // check that we have extended feature read support
4587   if (!m_gdb_comm.GetQXferFeaturesReadSupported())
4588     return false;
4589 
4590   uint32_t cur_reg_num = 0;
4591   uint32_t reg_offset = 0;
4592   if (GetGDBServerRegisterInfoXMLAndProcess (arch_to_use, "target.xml", cur_reg_num, reg_offset))
4593     this->m_register_info.Finalize(arch_to_use);
4594 
4595   return m_register_info.GetNumRegisters() > 0;
4596 }
4597 
4598 llvm::Expected<LoadedModuleInfoList> ProcessGDBRemote::GetLoadedModuleList() {
4599   // Make sure LLDB has an XML parser it can use first
4600   if (!XMLDocument::XMLEnabled())
4601     return llvm::createStringError(llvm::inconvertibleErrorCode(),
4602                                    "XML parsing not available");
4603 
4604   Log *log = GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS);
4605   LLDB_LOGF(log, "ProcessGDBRemote::%s", __FUNCTION__);
4606 
4607   LoadedModuleInfoList list;
4608   GDBRemoteCommunicationClient &comm = m_gdb_comm;
4609   bool can_use_svr4 = GetGlobalPluginProperties()->GetUseSVR4();
4610 
4611   // check that we have extended feature read support
4612   if (can_use_svr4 && comm.GetQXferLibrariesSVR4ReadSupported()) {
4613     // request the loaded library list
4614     std::string raw;
4615     lldb_private::Status lldberr;
4616 
4617     if (!comm.ReadExtFeature(ConstString("libraries-svr4"), ConstString(""),
4618                              raw, lldberr))
4619       return llvm::createStringError(llvm::inconvertibleErrorCode(),
4620                                      "Error in libraries-svr4 packet");
4621 
4622     // parse the xml file in memory
4623     LLDB_LOGF(log, "parsing: %s", raw.c_str());
4624     XMLDocument doc;
4625 
4626     if (!doc.ParseMemory(raw.c_str(), raw.size(), "noname.xml"))
4627       return llvm::createStringError(llvm::inconvertibleErrorCode(),
4628                                      "Error reading noname.xml");
4629 
4630     XMLNode root_element = doc.GetRootElement("library-list-svr4");
4631     if (!root_element)
4632       return llvm::createStringError(
4633           llvm::inconvertibleErrorCode(),
4634           "Error finding library-list-svr4 xml element");
4635 
4636     // main link map structure
4637     llvm::StringRef main_lm = root_element.GetAttributeValue("main-lm");
4638     if (!main_lm.empty()) {
4639       list.m_link_map =
4640           StringConvert::ToUInt64(main_lm.data(), LLDB_INVALID_ADDRESS, 0);
4641     }
4642 
4643     root_element.ForEachChildElementWithName(
4644         "library", [log, &list](const XMLNode &library) -> bool {
4645 
4646           LoadedModuleInfoList::LoadedModuleInfo module;
4647 
4648           library.ForEachAttribute(
4649               [&module](const llvm::StringRef &name,
4650                         const llvm::StringRef &value) -> bool {
4651 
4652                 if (name == "name")
4653                   module.set_name(value.str());
4654                 else if (name == "lm") {
4655                   // the address of the link_map struct.
4656                   module.set_link_map(StringConvert::ToUInt64(
4657                       value.data(), LLDB_INVALID_ADDRESS, 0));
4658                 } else if (name == "l_addr") {
4659                   // the displacement as read from the field 'l_addr' of the
4660                   // link_map struct.
4661                   module.set_base(StringConvert::ToUInt64(
4662                       value.data(), LLDB_INVALID_ADDRESS, 0));
4663                   // base address is always a displacement, not an absolute
4664                   // value.
4665                   module.set_base_is_offset(true);
4666                 } else if (name == "l_ld") {
4667                   // the memory address of the libraries PT_DYNAMIC section.
4668                   module.set_dynamic(StringConvert::ToUInt64(
4669                       value.data(), LLDB_INVALID_ADDRESS, 0));
4670                 }
4671 
4672                 return true; // Keep iterating over all properties of "library"
4673               });
4674 
4675           if (log) {
4676             std::string name;
4677             lldb::addr_t lm = 0, base = 0, ld = 0;
4678             bool base_is_offset;
4679 
4680             module.get_name(name);
4681             module.get_link_map(lm);
4682             module.get_base(base);
4683             module.get_base_is_offset(base_is_offset);
4684             module.get_dynamic(ld);
4685 
4686             LLDB_LOGF(log,
4687                       "found (link_map:0x%08" PRIx64 ", base:0x%08" PRIx64
4688                       "[%s], ld:0x%08" PRIx64 ", name:'%s')",
4689                       lm, base, (base_is_offset ? "offset" : "absolute"), ld,
4690                       name.c_str());
4691           }
4692 
4693           list.add(module);
4694           return true; // Keep iterating over all "library" elements in the root
4695                        // node
4696         });
4697 
4698     if (log)
4699       LLDB_LOGF(log, "found %" PRId32 " modules in total",
4700                 (int)list.m_list.size());
4701     return list;
4702   } else if (comm.GetQXferLibrariesReadSupported()) {
4703     // request the loaded library list
4704     std::string raw;
4705     lldb_private::Status lldberr;
4706 
4707     if (!comm.ReadExtFeature(ConstString("libraries"), ConstString(""), raw,
4708                              lldberr))
4709       return llvm::createStringError(llvm::inconvertibleErrorCode(),
4710                                      "Error in libraries packet");
4711 
4712     LLDB_LOGF(log, "parsing: %s", raw.c_str());
4713     XMLDocument doc;
4714 
4715     if (!doc.ParseMemory(raw.c_str(), raw.size(), "noname.xml"))
4716       return llvm::createStringError(llvm::inconvertibleErrorCode(),
4717                                      "Error reading noname.xml");
4718 
4719     XMLNode root_element = doc.GetRootElement("library-list");
4720     if (!root_element)
4721       return llvm::createStringError(llvm::inconvertibleErrorCode(),
4722                                      "Error finding library-list xml element");
4723 
4724     root_element.ForEachChildElementWithName(
4725         "library", [log, &list](const XMLNode &library) -> bool {
4726           LoadedModuleInfoList::LoadedModuleInfo module;
4727 
4728           llvm::StringRef name = library.GetAttributeValue("name");
4729           module.set_name(name.str());
4730 
4731           // The base address of a given library will be the address of its
4732           // first section. Most remotes send only one section for Windows
4733           // targets for example.
4734           const XMLNode &section =
4735               library.FindFirstChildElementWithName("section");
4736           llvm::StringRef address = section.GetAttributeValue("address");
4737           module.set_base(
4738               StringConvert::ToUInt64(address.data(), LLDB_INVALID_ADDRESS, 0));
4739           // These addresses are absolute values.
4740           module.set_base_is_offset(false);
4741 
4742           if (log) {
4743             std::string name;
4744             lldb::addr_t base = 0;
4745             bool base_is_offset;
4746             module.get_name(name);
4747             module.get_base(base);
4748             module.get_base_is_offset(base_is_offset);
4749 
4750             LLDB_LOGF(log, "found (base:0x%08" PRIx64 "[%s], name:'%s')", base,
4751                       (base_is_offset ? "offset" : "absolute"), name.c_str());
4752           }
4753 
4754           list.add(module);
4755           return true; // Keep iterating over all "library" elements in the root
4756                        // node
4757         });
4758 
4759     if (log)
4760       LLDB_LOGF(log, "found %" PRId32 " modules in total",
4761                 (int)list.m_list.size());
4762     return list;
4763   } else {
4764     return llvm::createStringError(llvm::inconvertibleErrorCode(),
4765                                    "Remote libraries not supported");
4766   }
4767 }
4768 
4769 lldb::ModuleSP ProcessGDBRemote::LoadModuleAtAddress(const FileSpec &file,
4770                                                      lldb::addr_t link_map,
4771                                                      lldb::addr_t base_addr,
4772                                                      bool value_is_offset) {
4773   DynamicLoader *loader = GetDynamicLoader();
4774   if (!loader)
4775     return nullptr;
4776 
4777   return loader->LoadModuleAtAddress(file, link_map, base_addr,
4778                                      value_is_offset);
4779 }
4780 
4781 llvm::Error ProcessGDBRemote::LoadModules() {
4782   using lldb_private::process_gdb_remote::ProcessGDBRemote;
4783 
4784   // request a list of loaded libraries from GDBServer
4785   llvm::Expected<LoadedModuleInfoList> module_list = GetLoadedModuleList();
4786   if (!module_list)
4787     return module_list.takeError();
4788 
4789   // get a list of all the modules
4790   ModuleList new_modules;
4791 
4792   for (LoadedModuleInfoList::LoadedModuleInfo &modInfo : module_list->m_list) {
4793     std::string mod_name;
4794     lldb::addr_t mod_base;
4795     lldb::addr_t link_map;
4796     bool mod_base_is_offset;
4797 
4798     bool valid = true;
4799     valid &= modInfo.get_name(mod_name);
4800     valid &= modInfo.get_base(mod_base);
4801     valid &= modInfo.get_base_is_offset(mod_base_is_offset);
4802     if (!valid)
4803       continue;
4804 
4805     if (!modInfo.get_link_map(link_map))
4806       link_map = LLDB_INVALID_ADDRESS;
4807 
4808     FileSpec file(mod_name);
4809     FileSystem::Instance().Resolve(file);
4810     lldb::ModuleSP module_sp =
4811         LoadModuleAtAddress(file, link_map, mod_base, mod_base_is_offset);
4812 
4813     if (module_sp.get())
4814       new_modules.Append(module_sp);
4815   }
4816 
4817   if (new_modules.GetSize() > 0) {
4818     ModuleList removed_modules;
4819     Target &target = GetTarget();
4820     ModuleList &loaded_modules = m_process->GetTarget().GetImages();
4821 
4822     for (size_t i = 0; i < loaded_modules.GetSize(); ++i) {
4823       const lldb::ModuleSP loaded_module = loaded_modules.GetModuleAtIndex(i);
4824 
4825       bool found = false;
4826       for (size_t j = 0; j < new_modules.GetSize(); ++j) {
4827         if (new_modules.GetModuleAtIndex(j).get() == loaded_module.get())
4828           found = true;
4829       }
4830 
4831       // The main executable will never be included in libraries-svr4, don't
4832       // remove it
4833       if (!found &&
4834           loaded_module.get() != target.GetExecutableModulePointer()) {
4835         removed_modules.Append(loaded_module);
4836       }
4837     }
4838 
4839     loaded_modules.Remove(removed_modules);
4840     m_process->GetTarget().ModulesDidUnload(removed_modules, false);
4841 
4842     new_modules.ForEach([&target](const lldb::ModuleSP module_sp) -> bool {
4843       lldb_private::ObjectFile *obj = module_sp->GetObjectFile();
4844       if (!obj)
4845         return true;
4846 
4847       if (obj->GetType() != ObjectFile::Type::eTypeExecutable)
4848         return true;
4849 
4850       lldb::ModuleSP module_copy_sp = module_sp;
4851       target.SetExecutableModule(module_copy_sp, eLoadDependentsNo);
4852       return false;
4853     });
4854 
4855     loaded_modules.AppendIfNeeded(new_modules);
4856     m_process->GetTarget().ModulesDidLoad(new_modules);
4857   }
4858 
4859   return llvm::ErrorSuccess();
4860 }
4861 
4862 Status ProcessGDBRemote::GetFileLoadAddress(const FileSpec &file,
4863                                             bool &is_loaded,
4864                                             lldb::addr_t &load_addr) {
4865   is_loaded = false;
4866   load_addr = LLDB_INVALID_ADDRESS;
4867 
4868   std::string file_path = file.GetPath(false);
4869   if (file_path.empty())
4870     return Status("Empty file name specified");
4871 
4872   StreamString packet;
4873   packet.PutCString("qFileLoadAddress:");
4874   packet.PutStringAsRawHex8(file_path);
4875 
4876   StringExtractorGDBRemote response;
4877   if (m_gdb_comm.SendPacketAndWaitForResponse(packet.GetString(), response,
4878                                               false) !=
4879       GDBRemoteCommunication::PacketResult::Success)
4880     return Status("Sending qFileLoadAddress packet failed");
4881 
4882   if (response.IsErrorResponse()) {
4883     if (response.GetError() == 1) {
4884       // The file is not loaded into the inferior
4885       is_loaded = false;
4886       load_addr = LLDB_INVALID_ADDRESS;
4887       return Status();
4888     }
4889 
4890     return Status(
4891         "Fetching file load address from remote server returned an error");
4892   }
4893 
4894   if (response.IsNormalResponse()) {
4895     is_loaded = true;
4896     load_addr = response.GetHexMaxU64(false, LLDB_INVALID_ADDRESS);
4897     return Status();
4898   }
4899 
4900   return Status(
4901       "Unknown error happened during sending the load address packet");
4902 }
4903 
4904 void ProcessGDBRemote::ModulesDidLoad(ModuleList &module_list) {
4905   // We must call the lldb_private::Process::ModulesDidLoad () first before we
4906   // do anything
4907   Process::ModulesDidLoad(module_list);
4908 
4909   // After loading shared libraries, we can ask our remote GDB server if it
4910   // needs any symbols.
4911   m_gdb_comm.ServeSymbolLookups(this);
4912 }
4913 
4914 void ProcessGDBRemote::HandleAsyncStdout(llvm::StringRef out) {
4915   AppendSTDOUT(out.data(), out.size());
4916 }
4917 
4918 static const char *end_delimiter = "--end--;";
4919 static const int end_delimiter_len = 8;
4920 
4921 void ProcessGDBRemote::HandleAsyncMisc(llvm::StringRef data) {
4922   std::string input = data.str(); // '1' to move beyond 'A'
4923   if (m_partial_profile_data.length() > 0) {
4924     m_partial_profile_data.append(input);
4925     input = m_partial_profile_data;
4926     m_partial_profile_data.clear();
4927   }
4928 
4929   size_t found, pos = 0, len = input.length();
4930   while ((found = input.find(end_delimiter, pos)) != std::string::npos) {
4931     StringExtractorGDBRemote profileDataExtractor(
4932         input.substr(pos, found).c_str());
4933     std::string profile_data =
4934         HarmonizeThreadIdsForProfileData(profileDataExtractor);
4935     BroadcastAsyncProfileData(profile_data);
4936 
4937     pos = found + end_delimiter_len;
4938   }
4939 
4940   if (pos < len) {
4941     // Last incomplete chunk.
4942     m_partial_profile_data = input.substr(pos);
4943   }
4944 }
4945 
4946 std::string ProcessGDBRemote::HarmonizeThreadIdsForProfileData(
4947     StringExtractorGDBRemote &profileDataExtractor) {
4948   std::map<uint64_t, uint32_t> new_thread_id_to_used_usec_map;
4949   std::string output;
4950   llvm::raw_string_ostream output_stream(output);
4951   llvm::StringRef name, value;
4952 
4953   // Going to assuming thread_used_usec comes first, else bail out.
4954   while (profileDataExtractor.GetNameColonValue(name, value)) {
4955     if (name.compare("thread_used_id") == 0) {
4956       StringExtractor threadIDHexExtractor(value);
4957       uint64_t thread_id = threadIDHexExtractor.GetHexMaxU64(false, 0);
4958 
4959       bool has_used_usec = false;
4960       uint32_t curr_used_usec = 0;
4961       llvm::StringRef usec_name, usec_value;
4962       uint32_t input_file_pos = profileDataExtractor.GetFilePos();
4963       if (profileDataExtractor.GetNameColonValue(usec_name, usec_value)) {
4964         if (usec_name.equals("thread_used_usec")) {
4965           has_used_usec = true;
4966           usec_value.getAsInteger(0, curr_used_usec);
4967         } else {
4968           // We didn't find what we want, it is probably an older version. Bail
4969           // out.
4970           profileDataExtractor.SetFilePos(input_file_pos);
4971         }
4972       }
4973 
4974       if (has_used_usec) {
4975         uint32_t prev_used_usec = 0;
4976         std::map<uint64_t, uint32_t>::iterator iterator =
4977             m_thread_id_to_used_usec_map.find(thread_id);
4978         if (iterator != m_thread_id_to_used_usec_map.end()) {
4979           prev_used_usec = m_thread_id_to_used_usec_map[thread_id];
4980         }
4981 
4982         uint32_t real_used_usec = curr_used_usec - prev_used_usec;
4983         // A good first time record is one that runs for at least 0.25 sec
4984         bool good_first_time =
4985             (prev_used_usec == 0) && (real_used_usec > 250000);
4986         bool good_subsequent_time =
4987             (prev_used_usec > 0) &&
4988             ((real_used_usec > 0) || (HasAssignedIndexIDToThread(thread_id)));
4989 
4990         if (good_first_time || good_subsequent_time) {
4991           // We try to avoid doing too many index id reservation, resulting in
4992           // fast increase of index ids.
4993 
4994           output_stream << name << ":";
4995           int32_t index_id = AssignIndexIDToThread(thread_id);
4996           output_stream << index_id << ";";
4997 
4998           output_stream << usec_name << ":" << usec_value << ";";
4999         } else {
5000           // Skip past 'thread_used_name'.
5001           llvm::StringRef local_name, local_value;
5002           profileDataExtractor.GetNameColonValue(local_name, local_value);
5003         }
5004 
5005         // Store current time as previous time so that they can be compared
5006         // later.
5007         new_thread_id_to_used_usec_map[thread_id] = curr_used_usec;
5008       } else {
5009         // Bail out and use old string.
5010         output_stream << name << ":" << value << ";";
5011       }
5012     } else {
5013       output_stream << name << ":" << value << ";";
5014     }
5015   }
5016   output_stream << end_delimiter;
5017   m_thread_id_to_used_usec_map = new_thread_id_to_used_usec_map;
5018 
5019   return output_stream.str();
5020 }
5021 
5022 void ProcessGDBRemote::HandleStopReply() {
5023   if (GetStopID() != 0)
5024     return;
5025 
5026   if (GetID() == LLDB_INVALID_PROCESS_ID) {
5027     lldb::pid_t pid = m_gdb_comm.GetCurrentProcessID();
5028     if (pid != LLDB_INVALID_PROCESS_ID)
5029       SetID(pid);
5030   }
5031   BuildDynamicRegisterInfo(true);
5032 }
5033 
5034 static const char *const s_async_json_packet_prefix = "JSON-async:";
5035 
5036 static StructuredData::ObjectSP
5037 ParseStructuredDataPacket(llvm::StringRef packet) {
5038   Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
5039 
5040   if (!packet.consume_front(s_async_json_packet_prefix)) {
5041     if (log) {
5042       LLDB_LOGF(
5043           log,
5044           "GDBRemoteCommunicationClientBase::%s() received $J packet "
5045           "but was not a StructuredData packet: packet starts with "
5046           "%s",
5047           __FUNCTION__,
5048           packet.slice(0, strlen(s_async_json_packet_prefix)).str().c_str());
5049     }
5050     return StructuredData::ObjectSP();
5051   }
5052 
5053   // This is an asynchronous JSON packet, destined for a StructuredDataPlugin.
5054   StructuredData::ObjectSP json_sp =
5055       StructuredData::ParseJSON(std::string(packet));
5056   if (log) {
5057     if (json_sp) {
5058       StreamString json_str;
5059       json_sp->Dump(json_str, true);
5060       json_str.Flush();
5061       LLDB_LOGF(log,
5062                 "ProcessGDBRemote::%s() "
5063                 "received Async StructuredData packet: %s",
5064                 __FUNCTION__, json_str.GetData());
5065     } else {
5066       LLDB_LOGF(log,
5067                 "ProcessGDBRemote::%s"
5068                 "() received StructuredData packet:"
5069                 " parse failure",
5070                 __FUNCTION__);
5071     }
5072   }
5073   return json_sp;
5074 }
5075 
5076 void ProcessGDBRemote::HandleAsyncStructuredDataPacket(llvm::StringRef data) {
5077   auto structured_data_sp = ParseStructuredDataPacket(data);
5078   if (structured_data_sp)
5079     RouteAsyncStructuredData(structured_data_sp);
5080 }
5081 
5082 class CommandObjectProcessGDBRemoteSpeedTest : public CommandObjectParsed {
5083 public:
5084   CommandObjectProcessGDBRemoteSpeedTest(CommandInterpreter &interpreter)
5085       : CommandObjectParsed(interpreter, "process plugin packet speed-test",
5086                             "Tests packet speeds of various sizes to determine "
5087                             "the performance characteristics of the GDB remote "
5088                             "connection. ",
5089                             nullptr),
5090         m_option_group(),
5091         m_num_packets(LLDB_OPT_SET_1, false, "count", 'c', 0, eArgTypeCount,
5092                       "The number of packets to send of each varying size "
5093                       "(default is 1000).",
5094                       1000),
5095         m_max_send(LLDB_OPT_SET_1, false, "max-send", 's', 0, eArgTypeCount,
5096                    "The maximum number of bytes to send in a packet. Sizes "
5097                    "increase in powers of 2 while the size is less than or "
5098                    "equal to this option value. (default 1024).",
5099                    1024),
5100         m_max_recv(LLDB_OPT_SET_1, false, "max-receive", 'r', 0, eArgTypeCount,
5101                    "The maximum number of bytes to receive in a packet. Sizes "
5102                    "increase in powers of 2 while the size is less than or "
5103                    "equal to this option value. (default 1024).",
5104                    1024),
5105         m_json(LLDB_OPT_SET_1, false, "json", 'j',
5106                "Print the output as JSON data for easy parsing.", false, true) {
5107     m_option_group.Append(&m_num_packets, LLDB_OPT_SET_ALL, LLDB_OPT_SET_1);
5108     m_option_group.Append(&m_max_send, LLDB_OPT_SET_ALL, LLDB_OPT_SET_1);
5109     m_option_group.Append(&m_max_recv, LLDB_OPT_SET_ALL, LLDB_OPT_SET_1);
5110     m_option_group.Append(&m_json, LLDB_OPT_SET_ALL, LLDB_OPT_SET_1);
5111     m_option_group.Finalize();
5112   }
5113 
5114   ~CommandObjectProcessGDBRemoteSpeedTest() override {}
5115 
5116   Options *GetOptions() override { return &m_option_group; }
5117 
5118   bool DoExecute(Args &command, CommandReturnObject &result) override {
5119     const size_t argc = command.GetArgumentCount();
5120     if (argc == 0) {
5121       ProcessGDBRemote *process =
5122           (ProcessGDBRemote *)m_interpreter.GetExecutionContext()
5123               .GetProcessPtr();
5124       if (process) {
5125         StreamSP output_stream_sp(
5126             m_interpreter.GetDebugger().GetAsyncOutputStream());
5127         result.SetImmediateOutputStream(output_stream_sp);
5128 
5129         const uint32_t num_packets =
5130             (uint32_t)m_num_packets.GetOptionValue().GetCurrentValue();
5131         const uint64_t max_send = m_max_send.GetOptionValue().GetCurrentValue();
5132         const uint64_t max_recv = m_max_recv.GetOptionValue().GetCurrentValue();
5133         const bool json = m_json.GetOptionValue().GetCurrentValue();
5134         const uint64_t k_recv_amount =
5135             4 * 1024 * 1024; // Receive amount in bytes
5136         process->GetGDBRemote().TestPacketSpeed(
5137             num_packets, max_send, max_recv, k_recv_amount, json,
5138             output_stream_sp ? *output_stream_sp : result.GetOutputStream());
5139         result.SetStatus(eReturnStatusSuccessFinishResult);
5140         return true;
5141       }
5142     } else {
5143       result.AppendErrorWithFormat("'%s' takes no arguments",
5144                                    m_cmd_name.c_str());
5145     }
5146     result.SetStatus(eReturnStatusFailed);
5147     return false;
5148   }
5149 
5150 protected:
5151   OptionGroupOptions m_option_group;
5152   OptionGroupUInt64 m_num_packets;
5153   OptionGroupUInt64 m_max_send;
5154   OptionGroupUInt64 m_max_recv;
5155   OptionGroupBoolean m_json;
5156 };
5157 
5158 class CommandObjectProcessGDBRemotePacketHistory : public CommandObjectParsed {
5159 private:
5160 public:
5161   CommandObjectProcessGDBRemotePacketHistory(CommandInterpreter &interpreter)
5162       : CommandObjectParsed(interpreter, "process plugin packet history",
5163                             "Dumps the packet history buffer. ", nullptr) {}
5164 
5165   ~CommandObjectProcessGDBRemotePacketHistory() override {}
5166 
5167   bool DoExecute(Args &command, CommandReturnObject &result) override {
5168     const size_t argc = command.GetArgumentCount();
5169     if (argc == 0) {
5170       ProcessGDBRemote *process =
5171           (ProcessGDBRemote *)m_interpreter.GetExecutionContext()
5172               .GetProcessPtr();
5173       if (process) {
5174         process->GetGDBRemote().DumpHistory(result.GetOutputStream());
5175         result.SetStatus(eReturnStatusSuccessFinishResult);
5176         return true;
5177       }
5178     } else {
5179       result.AppendErrorWithFormat("'%s' takes no arguments",
5180                                    m_cmd_name.c_str());
5181     }
5182     result.SetStatus(eReturnStatusFailed);
5183     return false;
5184   }
5185 };
5186 
5187 class CommandObjectProcessGDBRemotePacketXferSize : public CommandObjectParsed {
5188 private:
5189 public:
5190   CommandObjectProcessGDBRemotePacketXferSize(CommandInterpreter &interpreter)
5191       : CommandObjectParsed(
5192             interpreter, "process plugin packet xfer-size",
5193             "Maximum size that lldb will try to read/write one one chunk.",
5194             nullptr) {}
5195 
5196   ~CommandObjectProcessGDBRemotePacketXferSize() override {}
5197 
5198   bool DoExecute(Args &command, CommandReturnObject &result) override {
5199     const size_t argc = command.GetArgumentCount();
5200     if (argc == 0) {
5201       result.AppendErrorWithFormat("'%s' takes an argument to specify the max "
5202                                    "amount to be transferred when "
5203                                    "reading/writing",
5204                                    m_cmd_name.c_str());
5205       result.SetStatus(eReturnStatusFailed);
5206       return false;
5207     }
5208 
5209     ProcessGDBRemote *process =
5210         (ProcessGDBRemote *)m_interpreter.GetExecutionContext().GetProcessPtr();
5211     if (process) {
5212       const char *packet_size = command.GetArgumentAtIndex(0);
5213       errno = 0;
5214       uint64_t user_specified_max = strtoul(packet_size, nullptr, 10);
5215       if (errno == 0 && user_specified_max != 0) {
5216         process->SetUserSpecifiedMaxMemoryTransferSize(user_specified_max);
5217         result.SetStatus(eReturnStatusSuccessFinishResult);
5218         return true;
5219       }
5220     }
5221     result.SetStatus(eReturnStatusFailed);
5222     return false;
5223   }
5224 };
5225 
5226 class CommandObjectProcessGDBRemotePacketSend : public CommandObjectParsed {
5227 private:
5228 public:
5229   CommandObjectProcessGDBRemotePacketSend(CommandInterpreter &interpreter)
5230       : CommandObjectParsed(interpreter, "process plugin packet send",
5231                             "Send a custom packet through the GDB remote "
5232                             "protocol and print the answer. "
5233                             "The packet header and footer will automatically "
5234                             "be added to the packet prior to sending and "
5235                             "stripped from the result.",
5236                             nullptr) {}
5237 
5238   ~CommandObjectProcessGDBRemotePacketSend() override {}
5239 
5240   bool DoExecute(Args &command, CommandReturnObject &result) override {
5241     const size_t argc = command.GetArgumentCount();
5242     if (argc == 0) {
5243       result.AppendErrorWithFormat(
5244           "'%s' takes a one or more packet content arguments",
5245           m_cmd_name.c_str());
5246       result.SetStatus(eReturnStatusFailed);
5247       return false;
5248     }
5249 
5250     ProcessGDBRemote *process =
5251         (ProcessGDBRemote *)m_interpreter.GetExecutionContext().GetProcessPtr();
5252     if (process) {
5253       for (size_t i = 0; i < argc; ++i) {
5254         const char *packet_cstr = command.GetArgumentAtIndex(0);
5255         bool send_async = true;
5256         StringExtractorGDBRemote response;
5257         process->GetGDBRemote().SendPacketAndWaitForResponse(
5258             packet_cstr, response, send_async);
5259         result.SetStatus(eReturnStatusSuccessFinishResult);
5260         Stream &output_strm = result.GetOutputStream();
5261         output_strm.Printf("  packet: %s\n", packet_cstr);
5262         std::string response_str = std::string(response.GetStringRef());
5263 
5264         if (strstr(packet_cstr, "qGetProfileData") != nullptr) {
5265           response_str = process->HarmonizeThreadIdsForProfileData(response);
5266         }
5267 
5268         if (response_str.empty())
5269           output_strm.PutCString("response: \nerror: UNIMPLEMENTED\n");
5270         else
5271           output_strm.Printf("response: %s\n", response.GetStringRef().data());
5272       }
5273     }
5274     return true;
5275   }
5276 };
5277 
5278 class CommandObjectProcessGDBRemotePacketMonitor : public CommandObjectRaw {
5279 private:
5280 public:
5281   CommandObjectProcessGDBRemotePacketMonitor(CommandInterpreter &interpreter)
5282       : CommandObjectRaw(interpreter, "process plugin packet monitor",
5283                          "Send a qRcmd packet through the GDB remote protocol "
5284                          "and print the response."
5285                          "The argument passed to this command will be hex "
5286                          "encoded into a valid 'qRcmd' packet, sent and the "
5287                          "response will be printed.") {}
5288 
5289   ~CommandObjectProcessGDBRemotePacketMonitor() override {}
5290 
5291   bool DoExecute(llvm::StringRef command,
5292                  CommandReturnObject &result) override {
5293     if (command.empty()) {
5294       result.AppendErrorWithFormat("'%s' takes a command string argument",
5295                                    m_cmd_name.c_str());
5296       result.SetStatus(eReturnStatusFailed);
5297       return false;
5298     }
5299 
5300     ProcessGDBRemote *process =
5301         (ProcessGDBRemote *)m_interpreter.GetExecutionContext().GetProcessPtr();
5302     if (process) {
5303       StreamString packet;
5304       packet.PutCString("qRcmd,");
5305       packet.PutBytesAsRawHex8(command.data(), command.size());
5306 
5307       bool send_async = true;
5308       StringExtractorGDBRemote response;
5309       Stream &output_strm = result.GetOutputStream();
5310       process->GetGDBRemote().SendPacketAndReceiveResponseWithOutputSupport(
5311           packet.GetString(), response, send_async,
5312           [&output_strm](llvm::StringRef output) { output_strm << output; });
5313       result.SetStatus(eReturnStatusSuccessFinishResult);
5314       output_strm.Printf("  packet: %s\n", packet.GetData());
5315       const std::string &response_str = std::string(response.GetStringRef());
5316 
5317       if (response_str.empty())
5318         output_strm.PutCString("response: \nerror: UNIMPLEMENTED\n");
5319       else
5320         output_strm.Printf("response: %s\n", response.GetStringRef().data());
5321     }
5322     return true;
5323   }
5324 };
5325 
5326 class CommandObjectProcessGDBRemotePacket : public CommandObjectMultiword {
5327 private:
5328 public:
5329   CommandObjectProcessGDBRemotePacket(CommandInterpreter &interpreter)
5330       : CommandObjectMultiword(interpreter, "process plugin packet",
5331                                "Commands that deal with GDB remote packets.",
5332                                nullptr) {
5333     LoadSubCommand(
5334         "history",
5335         CommandObjectSP(
5336             new CommandObjectProcessGDBRemotePacketHistory(interpreter)));
5337     LoadSubCommand(
5338         "send", CommandObjectSP(
5339                     new CommandObjectProcessGDBRemotePacketSend(interpreter)));
5340     LoadSubCommand(
5341         "monitor",
5342         CommandObjectSP(
5343             new CommandObjectProcessGDBRemotePacketMonitor(interpreter)));
5344     LoadSubCommand(
5345         "xfer-size",
5346         CommandObjectSP(
5347             new CommandObjectProcessGDBRemotePacketXferSize(interpreter)));
5348     LoadSubCommand("speed-test",
5349                    CommandObjectSP(new CommandObjectProcessGDBRemoteSpeedTest(
5350                        interpreter)));
5351   }
5352 
5353   ~CommandObjectProcessGDBRemotePacket() override {}
5354 };
5355 
5356 class CommandObjectMultiwordProcessGDBRemote : public CommandObjectMultiword {
5357 public:
5358   CommandObjectMultiwordProcessGDBRemote(CommandInterpreter &interpreter)
5359       : CommandObjectMultiword(
5360             interpreter, "process plugin",
5361             "Commands for operating on a ProcessGDBRemote process.",
5362             "process plugin <subcommand> [<subcommand-options>]") {
5363     LoadSubCommand(
5364         "packet",
5365         CommandObjectSP(new CommandObjectProcessGDBRemotePacket(interpreter)));
5366   }
5367 
5368   ~CommandObjectMultiwordProcessGDBRemote() override {}
5369 };
5370 
5371 CommandObject *ProcessGDBRemote::GetPluginCommandObject() {
5372   if (!m_command_sp)
5373     m_command_sp = std::make_shared<CommandObjectMultiwordProcessGDBRemote>(
5374         GetTarget().GetDebugger().GetCommandInterpreter());
5375   return m_command_sp.get();
5376 }
5377