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