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