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