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