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