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