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