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