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