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