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