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