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