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