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