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