]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - contrib/llvm/tools/lldb/source/Plugins/Process/gdb-remote/ProcessGDBRemote.cpp
Merge llvm, clang, lld and lldb trunk r300890, and update build glue.
[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   Error 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   Error 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 Error ProcessGDBRemote::WillLaunch(Module *module) {
643   return WillLaunchOrAttach();
644 }
645
646 Error ProcessGDBRemote::WillAttachToProcessWithID(lldb::pid_t pid) {
647   return WillLaunchOrAttach();
648 }
649
650 Error ProcessGDBRemote::WillAttachToProcessWithName(const char *process_name,
651                                                     bool wait_for_launch) {
652   return WillLaunchOrAttach();
653 }
654
655 Error ProcessGDBRemote::DoConnectRemote(Stream *strm,
656                                         llvm::StringRef remote_url) {
657   Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
658   Error 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 Error ProcessGDBRemote::WillLaunchOrAttach() {
748   Error error;
749   m_stdio_communication.Clear();
750   return error;
751 }
752
753 //----------------------------------------------------------------------
754 // Process Control
755 //----------------------------------------------------------------------
756 Error ProcessGDBRemote::DoLaunch(Module *exe_module,
757                                  ProcessLaunchInfo &launch_info) {
758   Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
759   Error 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 Error ProcessGDBRemote::ConnectToDebugserver(llvm::StringRef connect_url) {
969   Error 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 Error ProcessGDBRemote::DoAttachToProcessWithID(
1173     lldb::pid_t attach_pid, const ProcessAttachInfo &attach_info) {
1174   Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
1175   Error 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 Error ProcessGDBRemote::DoAttachToProcessWithName(
1201     const char *process_name, const ProcessAttachInfo &attach_info) {
1202   Error 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 void ProcessGDBRemote::DidExit() {
1240   // When we exit, disconnect from the GDB server communications
1241   m_gdb_comm.Disconnect();
1242 }
1243
1244 void ProcessGDBRemote::DidAttach(ArchSpec &process_arch) {
1245   // If you can figure out what the architecture is, fill it in here.
1246   process_arch.Clear();
1247   DidLaunchOrAttach(process_arch);
1248 }
1249
1250 Error ProcessGDBRemote::WillResume() {
1251   m_continue_c_tids.clear();
1252   m_continue_C_tids.clear();
1253   m_continue_s_tids.clear();
1254   m_continue_S_tids.clear();
1255   m_jstopinfo_sp.reset();
1256   m_jthreadsinfo_sp.reset();
1257   return Error();
1258 }
1259
1260 Error ProcessGDBRemote::DoResume() {
1261   Error error;
1262   Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
1263   if (log)
1264     log->Printf("ProcessGDBRemote::Resume()");
1265
1266   ListenerSP listener_sp(
1267       Listener::MakeListener("gdb-remote.resume-packet-sent"));
1268   if (listener_sp->StartListeningForEvents(
1269           &m_gdb_comm, GDBRemoteCommunication::eBroadcastBitRunPacketSent)) {
1270     listener_sp->StartListeningForEvents(
1271         &m_async_broadcaster,
1272         ProcessGDBRemote::eBroadcastBitAsyncThreadDidExit);
1273
1274     const size_t num_threads = GetThreadList().GetSize();
1275
1276     StreamString continue_packet;
1277     bool continue_packet_error = false;
1278     if (m_gdb_comm.HasAnyVContSupport()) {
1279       if (!GetTarget().GetNonStopModeEnabled() &&
1280           (m_continue_c_tids.size() == num_threads ||
1281            (m_continue_c_tids.empty() && m_continue_C_tids.empty() &&
1282             m_continue_s_tids.empty() && m_continue_S_tids.empty()))) {
1283         // All threads are continuing, just send a "c" packet
1284         continue_packet.PutCString("c");
1285       } else {
1286         continue_packet.PutCString("vCont");
1287
1288         if (!m_continue_c_tids.empty()) {
1289           if (m_gdb_comm.GetVContSupported('c')) {
1290             for (tid_collection::const_iterator
1291                      t_pos = m_continue_c_tids.begin(),
1292                      t_end = m_continue_c_tids.end();
1293                  t_pos != t_end; ++t_pos)
1294               continue_packet.Printf(";c:%4.4" PRIx64, *t_pos);
1295           } else
1296             continue_packet_error = true;
1297         }
1298
1299         if (!continue_packet_error && !m_continue_C_tids.empty()) {
1300           if (m_gdb_comm.GetVContSupported('C')) {
1301             for (tid_sig_collection::const_iterator
1302                      s_pos = m_continue_C_tids.begin(),
1303                      s_end = m_continue_C_tids.end();
1304                  s_pos != s_end; ++s_pos)
1305               continue_packet.Printf(";C%2.2x:%4.4" PRIx64, s_pos->second,
1306                                      s_pos->first);
1307           } else
1308             continue_packet_error = true;
1309         }
1310
1311         if (!continue_packet_error && !m_continue_s_tids.empty()) {
1312           if (m_gdb_comm.GetVContSupported('s')) {
1313             for (tid_collection::const_iterator
1314                      t_pos = m_continue_s_tids.begin(),
1315                      t_end = m_continue_s_tids.end();
1316                  t_pos != t_end; ++t_pos)
1317               continue_packet.Printf(";s:%4.4" PRIx64, *t_pos);
1318           } else
1319             continue_packet_error = true;
1320         }
1321
1322         if (!continue_packet_error && !m_continue_S_tids.empty()) {
1323           if (m_gdb_comm.GetVContSupported('S')) {
1324             for (tid_sig_collection::const_iterator
1325                      s_pos = m_continue_S_tids.begin(),
1326                      s_end = m_continue_S_tids.end();
1327                  s_pos != s_end; ++s_pos)
1328               continue_packet.Printf(";S%2.2x:%4.4" PRIx64, s_pos->second,
1329                                      s_pos->first);
1330           } else
1331             continue_packet_error = true;
1332         }
1333
1334         if (continue_packet_error)
1335           continue_packet.Clear();
1336       }
1337     } else
1338       continue_packet_error = true;
1339
1340     if (continue_packet_error) {
1341       // Either no vCont support, or we tried to use part of the vCont
1342       // packet that wasn't supported by the remote GDB server.
1343       // We need to try and make a simple packet that can do our continue
1344       const size_t num_continue_c_tids = m_continue_c_tids.size();
1345       const size_t num_continue_C_tids = m_continue_C_tids.size();
1346       const size_t num_continue_s_tids = m_continue_s_tids.size();
1347       const size_t num_continue_S_tids = m_continue_S_tids.size();
1348       if (num_continue_c_tids > 0) {
1349         if (num_continue_c_tids == num_threads) {
1350           // All threads are resuming...
1351           m_gdb_comm.SetCurrentThreadForRun(-1);
1352           continue_packet.PutChar('c');
1353           continue_packet_error = false;
1354         } else if (num_continue_c_tids == 1 && num_continue_C_tids == 0 &&
1355                    num_continue_s_tids == 0 && num_continue_S_tids == 0) {
1356           // Only one thread is continuing
1357           m_gdb_comm.SetCurrentThreadForRun(m_continue_c_tids.front());
1358           continue_packet.PutChar('c');
1359           continue_packet_error = false;
1360         }
1361       }
1362
1363       if (continue_packet_error && num_continue_C_tids > 0) {
1364         if ((num_continue_C_tids + num_continue_c_tids) == num_threads &&
1365             num_continue_C_tids > 0 && num_continue_s_tids == 0 &&
1366             num_continue_S_tids == 0) {
1367           const int continue_signo = m_continue_C_tids.front().second;
1368           // Only one thread is continuing
1369           if (num_continue_C_tids > 1) {
1370             // More that one thread with a signal, yet we don't have
1371             // vCont support and we are being asked to resume each
1372             // thread with a signal, we need to make sure they are
1373             // all the same signal, or we can't issue the continue
1374             // accurately with the current support...
1375             if (num_continue_C_tids > 1) {
1376               continue_packet_error = false;
1377               for (size_t i = 1; i < m_continue_C_tids.size(); ++i) {
1378                 if (m_continue_C_tids[i].second != continue_signo)
1379                   continue_packet_error = true;
1380               }
1381             }
1382             if (!continue_packet_error)
1383               m_gdb_comm.SetCurrentThreadForRun(-1);
1384           } else {
1385             // Set the continue thread ID
1386             continue_packet_error = false;
1387             m_gdb_comm.SetCurrentThreadForRun(m_continue_C_tids.front().first);
1388           }
1389           if (!continue_packet_error) {
1390             // Add threads continuing with the same signo...
1391             continue_packet.Printf("C%2.2x", continue_signo);
1392           }
1393         }
1394       }
1395
1396       if (continue_packet_error && num_continue_s_tids > 0) {
1397         if (num_continue_s_tids == num_threads) {
1398           // All threads are resuming...
1399           m_gdb_comm.SetCurrentThreadForRun(-1);
1400
1401           // If in Non-Stop-Mode use vCont when stepping
1402           if (GetTarget().GetNonStopModeEnabled()) {
1403             if (m_gdb_comm.GetVContSupported('s'))
1404               continue_packet.PutCString("vCont;s");
1405             else
1406               continue_packet.PutChar('s');
1407           } else
1408             continue_packet.PutChar('s');
1409
1410           continue_packet_error = false;
1411         } else if (num_continue_c_tids == 0 && num_continue_C_tids == 0 &&
1412                    num_continue_s_tids == 1 && num_continue_S_tids == 0) {
1413           // Only one thread is stepping
1414           m_gdb_comm.SetCurrentThreadForRun(m_continue_s_tids.front());
1415           continue_packet.PutChar('s');
1416           continue_packet_error = false;
1417         }
1418       }
1419
1420       if (!continue_packet_error && num_continue_S_tids > 0) {
1421         if (num_continue_S_tids == num_threads) {
1422           const int step_signo = m_continue_S_tids.front().second;
1423           // Are all threads trying to step with the same signal?
1424           continue_packet_error = false;
1425           if (num_continue_S_tids > 1) {
1426             for (size_t i = 1; i < num_threads; ++i) {
1427               if (m_continue_S_tids[i].second != step_signo)
1428                 continue_packet_error = true;
1429             }
1430           }
1431           if (!continue_packet_error) {
1432             // Add threads stepping with the same signo...
1433             m_gdb_comm.SetCurrentThreadForRun(-1);
1434             continue_packet.Printf("S%2.2x", step_signo);
1435           }
1436         } else if (num_continue_c_tids == 0 && num_continue_C_tids == 0 &&
1437                    num_continue_s_tids == 0 && num_continue_S_tids == 1) {
1438           // Only one thread is stepping with signal
1439           m_gdb_comm.SetCurrentThreadForRun(m_continue_S_tids.front().first);
1440           continue_packet.Printf("S%2.2x", m_continue_S_tids.front().second);
1441           continue_packet_error = false;
1442         }
1443       }
1444     }
1445
1446     if (continue_packet_error) {
1447       error.SetErrorString("can't make continue packet for this resume");
1448     } else {
1449       EventSP event_sp;
1450       if (!m_async_thread.IsJoinable()) {
1451         error.SetErrorString("Trying to resume but the async thread is dead.");
1452         if (log)
1453           log->Printf("ProcessGDBRemote::DoResume: Trying to resume but the "
1454                       "async thread is dead.");
1455         return error;
1456       }
1457
1458       m_async_broadcaster.BroadcastEvent(
1459           eBroadcastBitAsyncContinue,
1460           new EventDataBytes(continue_packet.GetString().data(),
1461                              continue_packet.GetSize()));
1462
1463       if (listener_sp->GetEvent(event_sp, std::chrono::seconds(5)) == false) {
1464         error.SetErrorString("Resume timed out.");
1465         if (log)
1466           log->Printf("ProcessGDBRemote::DoResume: Resume timed out.");
1467       } else if (event_sp->BroadcasterIs(&m_async_broadcaster)) {
1468         error.SetErrorString("Broadcast continue, but the async thread was "
1469                              "killed before we got an ack back.");
1470         if (log)
1471           log->Printf("ProcessGDBRemote::DoResume: Broadcast continue, but the "
1472                       "async thread was killed before we got an ack back.");
1473         return error;
1474       }
1475     }
1476   }
1477
1478   return error;
1479 }
1480
1481 void ProcessGDBRemote::HandleStopReplySequence() {
1482   while (true) {
1483     // Send vStopped
1484     StringExtractorGDBRemote response;
1485     m_gdb_comm.SendPacketAndWaitForResponse("vStopped", response, false);
1486
1487     // OK represents end of signal list
1488     if (response.IsOKResponse())
1489       break;
1490
1491     // If not OK or a normal packet we have a problem
1492     if (!response.IsNormalResponse())
1493       break;
1494
1495     SetLastStopPacket(response);
1496   }
1497 }
1498
1499 void ProcessGDBRemote::ClearThreadIDList() {
1500   std::lock_guard<std::recursive_mutex> guard(m_thread_list_real.GetMutex());
1501   m_thread_ids.clear();
1502   m_thread_pcs.clear();
1503 }
1504
1505 size_t
1506 ProcessGDBRemote::UpdateThreadIDsFromStopReplyThreadsValue(std::string &value) {
1507   m_thread_ids.clear();
1508   m_thread_pcs.clear();
1509   size_t comma_pos;
1510   lldb::tid_t tid;
1511   while ((comma_pos = value.find(',')) != std::string::npos) {
1512     value[comma_pos] = '\0';
1513     // thread in big endian hex
1514     tid = StringConvert::ToUInt64(value.c_str(), LLDB_INVALID_THREAD_ID, 16);
1515     if (tid != LLDB_INVALID_THREAD_ID)
1516       m_thread_ids.push_back(tid);
1517     value.erase(0, comma_pos + 1);
1518   }
1519   tid = StringConvert::ToUInt64(value.c_str(), LLDB_INVALID_THREAD_ID, 16);
1520   if (tid != LLDB_INVALID_THREAD_ID)
1521     m_thread_ids.push_back(tid);
1522   return m_thread_ids.size();
1523 }
1524
1525 size_t
1526 ProcessGDBRemote::UpdateThreadPCsFromStopReplyThreadsValue(std::string &value) {
1527   m_thread_pcs.clear();
1528   size_t comma_pos;
1529   lldb::addr_t pc;
1530   while ((comma_pos = value.find(',')) != std::string::npos) {
1531     value[comma_pos] = '\0';
1532     pc = StringConvert::ToUInt64(value.c_str(), LLDB_INVALID_ADDRESS, 16);
1533     if (pc != LLDB_INVALID_ADDRESS)
1534       m_thread_pcs.push_back(pc);
1535     value.erase(0, comma_pos + 1);
1536   }
1537   pc = StringConvert::ToUInt64(value.c_str(), LLDB_INVALID_ADDRESS, 16);
1538   if (pc != LLDB_INVALID_THREAD_ID)
1539     m_thread_pcs.push_back(pc);
1540   return m_thread_pcs.size();
1541 }
1542
1543 bool ProcessGDBRemote::UpdateThreadIDList() {
1544   std::lock_guard<std::recursive_mutex> guard(m_thread_list_real.GetMutex());
1545
1546   if (m_jthreadsinfo_sp) {
1547     // If we have the JSON threads info, we can get the thread list from that
1548     StructuredData::Array *thread_infos = m_jthreadsinfo_sp->GetAsArray();
1549     if (thread_infos && thread_infos->GetSize() > 0) {
1550       m_thread_ids.clear();
1551       m_thread_pcs.clear();
1552       thread_infos->ForEach([this](StructuredData::Object *object) -> bool {
1553         StructuredData::Dictionary *thread_dict = object->GetAsDictionary();
1554         if (thread_dict) {
1555           // Set the thread stop info from the JSON dictionary
1556           SetThreadStopInfo(thread_dict);
1557           lldb::tid_t tid = LLDB_INVALID_THREAD_ID;
1558           if (thread_dict->GetValueForKeyAsInteger<lldb::tid_t>("tid", tid))
1559             m_thread_ids.push_back(tid);
1560         }
1561         return true; // Keep iterating through all thread_info objects
1562       });
1563     }
1564     if (!m_thread_ids.empty())
1565       return true;
1566   } else {
1567     // See if we can get the thread IDs from the current stop reply packets
1568     // that might contain a "threads" key/value pair
1569
1570     // Lock the thread stack while we access it
1571     // Mutex::Locker stop_stack_lock(m_last_stop_packet_mutex);
1572     std::unique_lock<std::recursive_mutex> stop_stack_lock(
1573         m_last_stop_packet_mutex, std::defer_lock);
1574     if (stop_stack_lock.try_lock()) {
1575       // Get the number of stop packets on the stack
1576       int nItems = m_stop_packet_stack.size();
1577       // Iterate over them
1578       for (int i = 0; i < nItems; i++) {
1579         // Get the thread stop info
1580         StringExtractorGDBRemote &stop_info = m_stop_packet_stack[i];
1581         const std::string &stop_info_str = stop_info.GetStringRef();
1582
1583         m_thread_pcs.clear();
1584         const size_t thread_pcs_pos = stop_info_str.find(";thread-pcs:");
1585         if (thread_pcs_pos != std::string::npos) {
1586           const size_t start = thread_pcs_pos + strlen(";thread-pcs:");
1587           const size_t end = stop_info_str.find(';', start);
1588           if (end != std::string::npos) {
1589             std::string value = stop_info_str.substr(start, end - start);
1590             UpdateThreadPCsFromStopReplyThreadsValue(value);
1591           }
1592         }
1593
1594         const size_t threads_pos = stop_info_str.find(";threads:");
1595         if (threads_pos != std::string::npos) {
1596           const size_t start = threads_pos + strlen(";threads:");
1597           const size_t end = stop_info_str.find(';', start);
1598           if (end != std::string::npos) {
1599             std::string value = stop_info_str.substr(start, end - start);
1600             if (UpdateThreadIDsFromStopReplyThreadsValue(value))
1601               return true;
1602           }
1603         }
1604       }
1605     }
1606   }
1607
1608   bool sequence_mutex_unavailable = false;
1609   m_gdb_comm.GetCurrentThreadIDs(m_thread_ids, sequence_mutex_unavailable);
1610   if (sequence_mutex_unavailable) {
1611     return false; // We just didn't get the list
1612   }
1613   return true;
1614 }
1615
1616 bool ProcessGDBRemote::UpdateThreadList(ThreadList &old_thread_list,
1617                                         ThreadList &new_thread_list) {
1618   // locker will keep a mutex locked until it goes out of scope
1619   Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_THREAD));
1620   LLDB_LOGV(log, "pid = {0}", GetID());
1621
1622   size_t num_thread_ids = m_thread_ids.size();
1623   // The "m_thread_ids" thread ID list should always be updated after each stop
1624   // reply packet, but in case it isn't, update it here.
1625   if (num_thread_ids == 0) {
1626     if (!UpdateThreadIDList())
1627       return false;
1628     num_thread_ids = m_thread_ids.size();
1629   }
1630
1631   ThreadList old_thread_list_copy(old_thread_list);
1632   if (num_thread_ids > 0) {
1633     for (size_t i = 0; i < num_thread_ids; ++i) {
1634       tid_t tid = m_thread_ids[i];
1635       ThreadSP thread_sp(
1636           old_thread_list_copy.RemoveThreadByProtocolID(tid, false));
1637       if (!thread_sp) {
1638         thread_sp.reset(new ThreadGDBRemote(*this, tid));
1639         LLDB_LOGV(log, "Making new thread: {0} for thread ID: {1:x}.",
1640                   thread_sp.get(), thread_sp->GetID());
1641       } else {
1642         LLDB_LOGV(log, "Found old thread: {0} for thread ID: {1:x}.",
1643                   thread_sp.get(), thread_sp->GetID());
1644       }
1645
1646       SetThreadPc(thread_sp, i);
1647       new_thread_list.AddThreadSortedByIndexID(thread_sp);
1648     }
1649   }
1650
1651   // Whatever that is left in old_thread_list_copy are not
1652   // present in new_thread_list. Remove non-existent threads from internal id
1653   // table.
1654   size_t old_num_thread_ids = old_thread_list_copy.GetSize(false);
1655   for (size_t i = 0; i < old_num_thread_ids; i++) {
1656     ThreadSP old_thread_sp(old_thread_list_copy.GetThreadAtIndex(i, false));
1657     if (old_thread_sp) {
1658       lldb::tid_t old_thread_id = old_thread_sp->GetProtocolID();
1659       m_thread_id_to_index_id_map.erase(old_thread_id);
1660     }
1661   }
1662
1663   return true;
1664 }
1665
1666 void ProcessGDBRemote::SetThreadPc(const ThreadSP &thread_sp, uint64_t index) {
1667   if (m_thread_ids.size() == m_thread_pcs.size() && thread_sp.get() &&
1668       GetByteOrder() != eByteOrderInvalid) {
1669     ThreadGDBRemote *gdb_thread =
1670         static_cast<ThreadGDBRemote *>(thread_sp.get());
1671     RegisterContextSP reg_ctx_sp(thread_sp->GetRegisterContext());
1672     if (reg_ctx_sp) {
1673       uint32_t pc_regnum = reg_ctx_sp->ConvertRegisterKindToRegisterNumber(
1674           eRegisterKindGeneric, LLDB_REGNUM_GENERIC_PC);
1675       if (pc_regnum != LLDB_INVALID_REGNUM) {
1676         gdb_thread->PrivateSetRegisterValue(pc_regnum, m_thread_pcs[index]);
1677       }
1678     }
1679   }
1680 }
1681
1682 bool ProcessGDBRemote::GetThreadStopInfoFromJSON(
1683     ThreadGDBRemote *thread, const StructuredData::ObjectSP &thread_infos_sp) {
1684   // See if we got thread stop infos for all threads via the "jThreadsInfo"
1685   // packet
1686   if (thread_infos_sp) {
1687     StructuredData::Array *thread_infos = thread_infos_sp->GetAsArray();
1688     if (thread_infos) {
1689       lldb::tid_t tid;
1690       const size_t n = thread_infos->GetSize();
1691       for (size_t i = 0; i < n; ++i) {
1692         StructuredData::Dictionary *thread_dict =
1693             thread_infos->GetItemAtIndex(i)->GetAsDictionary();
1694         if (thread_dict) {
1695           if (thread_dict->GetValueForKeyAsInteger<lldb::tid_t>(
1696                   "tid", tid, LLDB_INVALID_THREAD_ID)) {
1697             if (tid == thread->GetID())
1698               return (bool)SetThreadStopInfo(thread_dict);
1699           }
1700         }
1701       }
1702     }
1703   }
1704   return false;
1705 }
1706
1707 bool ProcessGDBRemote::CalculateThreadStopInfo(ThreadGDBRemote *thread) {
1708   // See if we got thread stop infos for all threads via the "jThreadsInfo"
1709   // packet
1710   if (GetThreadStopInfoFromJSON(thread, m_jthreadsinfo_sp))
1711     return true;
1712
1713   // See if we got thread stop info for any threads valid stop info reasons
1714   // threads
1715   // via the "jstopinfo" packet stop reply packet key/value pair?
1716   if (m_jstopinfo_sp) {
1717     // If we have "jstopinfo" then we have stop descriptions for all threads
1718     // that have stop reasons, and if there is no entry for a thread, then
1719     // it has no stop reason.
1720     thread->GetRegisterContext()->InvalidateIfNeeded(true);
1721     if (!GetThreadStopInfoFromJSON(thread, m_jstopinfo_sp)) {
1722       thread->SetStopInfo(StopInfoSP());
1723     }
1724     return true;
1725   }
1726
1727   // Fall back to using the qThreadStopInfo packet
1728   StringExtractorGDBRemote stop_packet;
1729   if (GetGDBRemote().GetThreadStopInfo(thread->GetProtocolID(), stop_packet))
1730     return SetThreadStopInfo(stop_packet) == eStateStopped;
1731   return false;
1732 }
1733
1734 ThreadSP ProcessGDBRemote::SetThreadStopInfo(
1735     lldb::tid_t tid, ExpeditedRegisterMap &expedited_register_map,
1736     uint8_t signo, const std::string &thread_name, const std::string &reason,
1737     const std::string &description, uint32_t exc_type,
1738     const std::vector<addr_t> &exc_data, addr_t thread_dispatch_qaddr,
1739     bool queue_vars_valid, // Set to true if queue_name, queue_kind and
1740                            // queue_serial are valid
1741     LazyBool associated_with_dispatch_queue, addr_t dispatch_queue_t,
1742     std::string &queue_name, QueueKind queue_kind, uint64_t queue_serial) {
1743   ThreadSP thread_sp;
1744   if (tid != LLDB_INVALID_THREAD_ID) {
1745     // Scope for "locker" below
1746     {
1747       // m_thread_list_real does have its own mutex, but we need to
1748       // hold onto the mutex between the call to
1749       // m_thread_list_real.FindThreadByID(...)
1750       // and the m_thread_list_real.AddThread(...) so it doesn't change on us
1751       std::lock_guard<std::recursive_mutex> guard(
1752           m_thread_list_real.GetMutex());
1753       thread_sp = m_thread_list_real.FindThreadByProtocolID(tid, false);
1754
1755       if (!thread_sp) {
1756         // Create the thread if we need to
1757         thread_sp.reset(new ThreadGDBRemote(*this, tid));
1758         m_thread_list_real.AddThread(thread_sp);
1759       }
1760     }
1761
1762     if (thread_sp) {
1763       ThreadGDBRemote *gdb_thread =
1764           static_cast<ThreadGDBRemote *>(thread_sp.get());
1765       gdb_thread->GetRegisterContext()->InvalidateIfNeeded(true);
1766
1767       auto iter = std::find(m_thread_ids.begin(), m_thread_ids.end(), tid);
1768       if (iter != m_thread_ids.end()) {
1769         SetThreadPc(thread_sp, iter - m_thread_ids.begin());
1770       }
1771
1772       for (const auto &pair : expedited_register_map) {
1773         StringExtractor reg_value_extractor;
1774         reg_value_extractor.GetStringRef() = pair.second;
1775         DataBufferSP buffer_sp(new DataBufferHeap(
1776             reg_value_extractor.GetStringRef().size() / 2, 0));
1777         reg_value_extractor.GetHexBytes(buffer_sp->GetData(), '\xcc');
1778         gdb_thread->PrivateSetRegisterValue(pair.first, buffer_sp->GetData());
1779       }
1780
1781       thread_sp->SetName(thread_name.empty() ? NULL : thread_name.c_str());
1782
1783       gdb_thread->SetThreadDispatchQAddr(thread_dispatch_qaddr);
1784       // Check if the GDB server was able to provide the queue name, kind and
1785       // serial number
1786       if (queue_vars_valid)
1787         gdb_thread->SetQueueInfo(std::move(queue_name), queue_kind,
1788                                  queue_serial, dispatch_queue_t,
1789                                  associated_with_dispatch_queue);
1790       else
1791         gdb_thread->ClearQueueInfo();
1792
1793       gdb_thread->SetAssociatedWithLibdispatchQueue(
1794           associated_with_dispatch_queue);
1795
1796       if (dispatch_queue_t != LLDB_INVALID_ADDRESS)
1797         gdb_thread->SetQueueLibdispatchQueueAddress(dispatch_queue_t);
1798
1799       // Make sure we update our thread stop reason just once
1800       if (!thread_sp->StopInfoIsUpToDate()) {
1801         thread_sp->SetStopInfo(StopInfoSP());
1802         // If there's a memory thread backed by this thread, we need to use it
1803         // to calcualte StopInfo.
1804         ThreadSP memory_thread_sp =
1805             m_thread_list.FindThreadByProtocolID(thread_sp->GetProtocolID());
1806         if (memory_thread_sp)
1807           thread_sp = memory_thread_sp;
1808
1809         if (exc_type != 0) {
1810           const size_t exc_data_size = exc_data.size();
1811
1812           thread_sp->SetStopInfo(
1813               StopInfoMachException::CreateStopReasonWithMachException(
1814                   *thread_sp, exc_type, exc_data_size,
1815                   exc_data_size >= 1 ? exc_data[0] : 0,
1816                   exc_data_size >= 2 ? exc_data[1] : 0,
1817                   exc_data_size >= 3 ? exc_data[2] : 0));
1818         } else {
1819           bool handled = false;
1820           bool did_exec = false;
1821           if (!reason.empty()) {
1822             if (reason.compare("trace") == 0) {
1823               addr_t pc = thread_sp->GetRegisterContext()->GetPC();
1824               lldb::BreakpointSiteSP bp_site_sp = thread_sp->GetProcess()
1825                                                       ->GetBreakpointSiteList()
1826                                                       .FindByAddress(pc);
1827
1828               // If the current pc is a breakpoint site then the StopInfo should
1829               // be set to Breakpoint
1830               // Otherwise, it will be set to Trace.
1831               if (bp_site_sp &&
1832                   bp_site_sp->ValidForThisThread(thread_sp.get())) {
1833                 thread_sp->SetStopInfo(
1834                     StopInfo::CreateStopReasonWithBreakpointSiteID(
1835                         *thread_sp, bp_site_sp->GetID()));
1836               } else
1837                 thread_sp->SetStopInfo(
1838                     StopInfo::CreateStopReasonToTrace(*thread_sp));
1839               handled = true;
1840             } else if (reason.compare("breakpoint") == 0) {
1841               addr_t pc = thread_sp->GetRegisterContext()->GetPC();
1842               lldb::BreakpointSiteSP bp_site_sp = thread_sp->GetProcess()
1843                                                       ->GetBreakpointSiteList()
1844                                                       .FindByAddress(pc);
1845               if (bp_site_sp) {
1846                 // If the breakpoint is for this thread, then we'll report the
1847                 // hit, but if it is for another thread,
1848                 // we can just report no reason.  We don't need to worry about
1849                 // stepping over the breakpoint here, that
1850                 // will be taken care of when the thread resumes and notices
1851                 // that there's a breakpoint under the pc.
1852                 handled = true;
1853                 if (bp_site_sp->ValidForThisThread(thread_sp.get())) {
1854                   thread_sp->SetStopInfo(
1855                       StopInfo::CreateStopReasonWithBreakpointSiteID(
1856                           *thread_sp, bp_site_sp->GetID()));
1857                 } else {
1858                   StopInfoSP invalid_stop_info_sp;
1859                   thread_sp->SetStopInfo(invalid_stop_info_sp);
1860                 }
1861               }
1862             } else if (reason.compare("trap") == 0) {
1863               // Let the trap just use the standard signal stop reason below...
1864             } else if (reason.compare("watchpoint") == 0) {
1865               StringExtractor desc_extractor(description.c_str());
1866               addr_t wp_addr = desc_extractor.GetU64(LLDB_INVALID_ADDRESS);
1867               uint32_t wp_index = desc_extractor.GetU32(LLDB_INVALID_INDEX32);
1868               addr_t wp_hit_addr = desc_extractor.GetU64(LLDB_INVALID_ADDRESS);
1869               watch_id_t watch_id = LLDB_INVALID_WATCH_ID;
1870               if (wp_addr != LLDB_INVALID_ADDRESS) {
1871                 WatchpointSP wp_sp;
1872                 ArchSpec::Core core = GetTarget().GetArchitecture().GetCore();
1873                 if ((core >= ArchSpec::kCore_mips_first &&
1874                      core <= ArchSpec::kCore_mips_last) ||
1875                     (core >= ArchSpec::eCore_arm_generic &&
1876                      core <= ArchSpec::eCore_arm_aarch64))
1877                   wp_sp = GetTarget().GetWatchpointList().FindByAddress(
1878                       wp_hit_addr);
1879                 if (!wp_sp)
1880                   wp_sp =
1881                       GetTarget().GetWatchpointList().FindByAddress(wp_addr);
1882                 if (wp_sp) {
1883                   wp_sp->SetHardwareIndex(wp_index);
1884                   watch_id = wp_sp->GetID();
1885                 }
1886               }
1887               if (watch_id == LLDB_INVALID_WATCH_ID) {
1888                 Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(
1889                     GDBR_LOG_WATCHPOINTS));
1890                 if (log)
1891                   log->Printf("failed to find watchpoint");
1892               }
1893               thread_sp->SetStopInfo(StopInfo::CreateStopReasonWithWatchpointID(
1894                   *thread_sp, watch_id, wp_hit_addr));
1895               handled = true;
1896             } else if (reason.compare("exception") == 0) {
1897               thread_sp->SetStopInfo(StopInfo::CreateStopReasonWithException(
1898                   *thread_sp, description.c_str()));
1899               handled = true;
1900             } else if (reason.compare("exec") == 0) {
1901               did_exec = true;
1902               thread_sp->SetStopInfo(
1903                   StopInfo::CreateStopReasonWithExec(*thread_sp));
1904               handled = true;
1905             }
1906           } else if (!signo) {
1907             addr_t pc = thread_sp->GetRegisterContext()->GetPC();
1908             lldb::BreakpointSiteSP bp_site_sp =
1909                 thread_sp->GetProcess()->GetBreakpointSiteList().FindByAddress(
1910                     pc);
1911
1912             // If the current pc is a breakpoint site then the StopInfo should
1913             // be set to Breakpoint
1914             // even though the remote stub did not set it as such. This can
1915             // happen when
1916             // the thread is involuntarily interrupted (e.g. due to stops on
1917             // other
1918             // threads) just as it is about to execute the breakpoint
1919             // instruction.
1920             if (bp_site_sp && bp_site_sp->ValidForThisThread(thread_sp.get())) {
1921               thread_sp->SetStopInfo(
1922                   StopInfo::CreateStopReasonWithBreakpointSiteID(
1923                       *thread_sp, bp_site_sp->GetID()));
1924               handled = true;
1925             }
1926           }
1927
1928           if (!handled && signo && did_exec == false) {
1929             if (signo == SIGTRAP) {
1930               // Currently we are going to assume SIGTRAP means we are either
1931               // hitting a breakpoint or hardware single stepping.
1932               handled = true;
1933               addr_t pc = thread_sp->GetRegisterContext()->GetPC() +
1934                           m_breakpoint_pc_offset;
1935               lldb::BreakpointSiteSP bp_site_sp = thread_sp->GetProcess()
1936                                                       ->GetBreakpointSiteList()
1937                                                       .FindByAddress(pc);
1938
1939               if (bp_site_sp) {
1940                 // If the breakpoint is for this thread, then we'll report the
1941                 // hit, but if it is for another thread,
1942                 // we can just report no reason.  We don't need to worry about
1943                 // stepping over the breakpoint here, that
1944                 // will be taken care of when the thread resumes and notices
1945                 // that there's a breakpoint under the pc.
1946                 if (bp_site_sp->ValidForThisThread(thread_sp.get())) {
1947                   if (m_breakpoint_pc_offset != 0)
1948                     thread_sp->GetRegisterContext()->SetPC(pc);
1949                   thread_sp->SetStopInfo(
1950                       StopInfo::CreateStopReasonWithBreakpointSiteID(
1951                           *thread_sp, bp_site_sp->GetID()));
1952                 } else {
1953                   StopInfoSP invalid_stop_info_sp;
1954                   thread_sp->SetStopInfo(invalid_stop_info_sp);
1955                 }
1956               } else {
1957                 // If we were stepping then assume the stop was the result of
1958                 // the trace.  If we were
1959                 // not stepping then report the SIGTRAP.
1960                 // FIXME: We are still missing the case where we single step
1961                 // over a trap instruction.
1962                 if (thread_sp->GetTemporaryResumeState() == eStateStepping)
1963                   thread_sp->SetStopInfo(
1964                       StopInfo::CreateStopReasonToTrace(*thread_sp));
1965                 else
1966                   thread_sp->SetStopInfo(StopInfo::CreateStopReasonWithSignal(
1967                       *thread_sp, signo, description.c_str()));
1968               }
1969             }
1970             if (!handled)
1971               thread_sp->SetStopInfo(StopInfo::CreateStopReasonWithSignal(
1972                   *thread_sp, signo, description.c_str()));
1973           }
1974
1975           if (!description.empty()) {
1976             lldb::StopInfoSP stop_info_sp(thread_sp->GetStopInfo());
1977             if (stop_info_sp) {
1978               const char *stop_info_desc = stop_info_sp->GetDescription();
1979               if (!stop_info_desc || !stop_info_desc[0])
1980                 stop_info_sp->SetDescription(description.c_str());
1981             } else {
1982               thread_sp->SetStopInfo(StopInfo::CreateStopReasonWithException(
1983                   *thread_sp, description.c_str()));
1984             }
1985           }
1986         }
1987       }
1988     }
1989   }
1990   return thread_sp;
1991 }
1992
1993 lldb::ThreadSP
1994 ProcessGDBRemote::SetThreadStopInfo(StructuredData::Dictionary *thread_dict) {
1995   static ConstString g_key_tid("tid");
1996   static ConstString g_key_name("name");
1997   static ConstString g_key_reason("reason");
1998   static ConstString g_key_metype("metype");
1999   static ConstString g_key_medata("medata");
2000   static ConstString g_key_qaddr("qaddr");
2001   static ConstString g_key_dispatch_queue_t("dispatch_queue_t");
2002   static ConstString g_key_associated_with_dispatch_queue(
2003       "associated_with_dispatch_queue");
2004   static ConstString g_key_queue_name("qname");
2005   static ConstString g_key_queue_kind("qkind");
2006   static ConstString g_key_queue_serial_number("qserialnum");
2007   static ConstString g_key_registers("registers");
2008   static ConstString g_key_memory("memory");
2009   static ConstString g_key_address("address");
2010   static ConstString g_key_bytes("bytes");
2011   static ConstString g_key_description("description");
2012   static ConstString g_key_signal("signal");
2013
2014   // Stop with signal and thread info
2015   lldb::tid_t tid = LLDB_INVALID_THREAD_ID;
2016   uint8_t signo = 0;
2017   std::string value;
2018   std::string thread_name;
2019   std::string reason;
2020   std::string description;
2021   uint32_t exc_type = 0;
2022   std::vector<addr_t> exc_data;
2023   addr_t thread_dispatch_qaddr = LLDB_INVALID_ADDRESS;
2024   ExpeditedRegisterMap expedited_register_map;
2025   bool queue_vars_valid = false;
2026   addr_t dispatch_queue_t = LLDB_INVALID_ADDRESS;
2027   LazyBool associated_with_dispatch_queue = eLazyBoolCalculate;
2028   std::string queue_name;
2029   QueueKind queue_kind = eQueueKindUnknown;
2030   uint64_t queue_serial_number = 0;
2031   // Iterate through all of the thread dictionary key/value pairs from the
2032   // structured data dictionary
2033
2034   thread_dict->ForEach([this, &tid, &expedited_register_map, &thread_name,
2035                         &signo, &reason, &description, &exc_type, &exc_data,
2036                         &thread_dispatch_qaddr, &queue_vars_valid,
2037                         &associated_with_dispatch_queue, &dispatch_queue_t,
2038                         &queue_name, &queue_kind, &queue_serial_number](
2039                            ConstString key,
2040                            StructuredData::Object *object) -> bool {
2041     if (key == g_key_tid) {
2042       // thread in big endian hex
2043       tid = object->GetIntegerValue(LLDB_INVALID_THREAD_ID);
2044     } else if (key == g_key_metype) {
2045       // exception type in big endian hex
2046       exc_type = object->GetIntegerValue(0);
2047     } else if (key == g_key_medata) {
2048       // exception data in big endian hex
2049       StructuredData::Array *array = object->GetAsArray();
2050       if (array) {
2051         array->ForEach([&exc_data](StructuredData::Object *object) -> bool {
2052           exc_data.push_back(object->GetIntegerValue());
2053           return true; // Keep iterating through all array items
2054         });
2055       }
2056     } else if (key == g_key_name) {
2057       thread_name = object->GetStringValue();
2058     } else if (key == g_key_qaddr) {
2059       thread_dispatch_qaddr = object->GetIntegerValue(LLDB_INVALID_ADDRESS);
2060     } else if (key == g_key_queue_name) {
2061       queue_vars_valid = true;
2062       queue_name = object->GetStringValue();
2063     } else if (key == g_key_queue_kind) {
2064       std::string queue_kind_str = object->GetStringValue();
2065       if (queue_kind_str == "serial") {
2066         queue_vars_valid = true;
2067         queue_kind = eQueueKindSerial;
2068       } else if (queue_kind_str == "concurrent") {
2069         queue_vars_valid = true;
2070         queue_kind = eQueueKindConcurrent;
2071       }
2072     } else if (key == g_key_queue_serial_number) {
2073       queue_serial_number = object->GetIntegerValue(0);
2074       if (queue_serial_number != 0)
2075         queue_vars_valid = true;
2076     } else if (key == g_key_dispatch_queue_t) {
2077       dispatch_queue_t = object->GetIntegerValue(0);
2078       if (dispatch_queue_t != 0 && dispatch_queue_t != LLDB_INVALID_ADDRESS)
2079         queue_vars_valid = true;
2080     } else if (key == g_key_associated_with_dispatch_queue) {
2081       queue_vars_valid = true;
2082       bool associated = object->GetBooleanValue();
2083       if (associated)
2084         associated_with_dispatch_queue = eLazyBoolYes;
2085       else
2086         associated_with_dispatch_queue = eLazyBoolNo;
2087     } else if (key == g_key_reason) {
2088       reason = object->GetStringValue();
2089     } else if (key == g_key_description) {
2090       description = object->GetStringValue();
2091     } else if (key == g_key_registers) {
2092       StructuredData::Dictionary *registers_dict = object->GetAsDictionary();
2093
2094       if (registers_dict) {
2095         registers_dict->ForEach(
2096             [&expedited_register_map](ConstString key,
2097                                       StructuredData::Object *object) -> bool {
2098               const uint32_t reg =
2099                   StringConvert::ToUInt32(key.GetCString(), UINT32_MAX, 10);
2100               if (reg != UINT32_MAX)
2101                 expedited_register_map[reg] = object->GetStringValue();
2102               return true; // Keep iterating through all array items
2103             });
2104       }
2105     } else if (key == g_key_memory) {
2106       StructuredData::Array *array = object->GetAsArray();
2107       if (array) {
2108         array->ForEach([this](StructuredData::Object *object) -> bool {
2109           StructuredData::Dictionary *mem_cache_dict =
2110               object->GetAsDictionary();
2111           if (mem_cache_dict) {
2112             lldb::addr_t mem_cache_addr = LLDB_INVALID_ADDRESS;
2113             if (mem_cache_dict->GetValueForKeyAsInteger<lldb::addr_t>(
2114                     "address", mem_cache_addr)) {
2115               if (mem_cache_addr != LLDB_INVALID_ADDRESS) {
2116                 StringExtractor bytes;
2117                 if (mem_cache_dict->GetValueForKeyAsString(
2118                         "bytes", bytes.GetStringRef())) {
2119                   bytes.SetFilePos(0);
2120
2121                   const size_t byte_size = bytes.GetStringRef().size() / 2;
2122                   DataBufferSP data_buffer_sp(new DataBufferHeap(byte_size, 0));
2123                   const size_t bytes_copied =
2124                       bytes.GetHexBytes(data_buffer_sp->GetData(), 0);
2125                   if (bytes_copied == byte_size)
2126                     m_memory_cache.AddL1CacheData(mem_cache_addr,
2127                                                   data_buffer_sp);
2128                 }
2129               }
2130             }
2131           }
2132           return true; // Keep iterating through all array items
2133         });
2134       }
2135
2136     } else if (key == g_key_signal)
2137       signo = object->GetIntegerValue(LLDB_INVALID_SIGNAL_NUMBER);
2138     return true; // Keep iterating through all dictionary key/value pairs
2139   });
2140
2141   return SetThreadStopInfo(tid, expedited_register_map, signo, thread_name,
2142                            reason, description, exc_type, exc_data,
2143                            thread_dispatch_qaddr, queue_vars_valid,
2144                            associated_with_dispatch_queue, dispatch_queue_t,
2145                            queue_name, queue_kind, queue_serial_number);
2146 }
2147
2148 StateType ProcessGDBRemote::SetThreadStopInfo(StringExtractor &stop_packet) {
2149   stop_packet.SetFilePos(0);
2150   const char stop_type = stop_packet.GetChar();
2151   switch (stop_type) {
2152   case 'T':
2153   case 'S': {
2154     // This is a bit of a hack, but is is required. If we did exec, we
2155     // need to clear our thread lists and also know to rebuild our dynamic
2156     // register info before we lookup and threads and populate the expedited
2157     // register values so we need to know this right away so we can cleanup
2158     // and update our registers.
2159     const uint32_t stop_id = GetStopID();
2160     if (stop_id == 0) {
2161       // Our first stop, make sure we have a process ID, and also make
2162       // sure we know about our registers
2163       if (GetID() == LLDB_INVALID_PROCESS_ID) {
2164         lldb::pid_t pid = m_gdb_comm.GetCurrentProcessID();
2165         if (pid != LLDB_INVALID_PROCESS_ID)
2166           SetID(pid);
2167       }
2168       BuildDynamicRegisterInfo(true);
2169     }
2170     // Stop with signal and thread info
2171     lldb::tid_t tid = LLDB_INVALID_THREAD_ID;
2172     const uint8_t signo = stop_packet.GetHexU8();
2173     llvm::StringRef key;
2174     llvm::StringRef value;
2175     std::string thread_name;
2176     std::string reason;
2177     std::string description;
2178     uint32_t exc_type = 0;
2179     std::vector<addr_t> exc_data;
2180     addr_t thread_dispatch_qaddr = LLDB_INVALID_ADDRESS;
2181     bool queue_vars_valid =
2182         false; // says if locals below that start with "queue_" are valid
2183     addr_t dispatch_queue_t = LLDB_INVALID_ADDRESS;
2184     LazyBool associated_with_dispatch_queue = eLazyBoolCalculate;
2185     std::string queue_name;
2186     QueueKind queue_kind = eQueueKindUnknown;
2187     uint64_t queue_serial_number = 0;
2188     ExpeditedRegisterMap expedited_register_map;
2189     while (stop_packet.GetNameColonValue(key, value)) {
2190       if (key.compare("metype") == 0) {
2191         // exception type in big endian hex
2192         value.getAsInteger(16, exc_type);
2193       } else if (key.compare("medata") == 0) {
2194         // exception data in big endian hex
2195         uint64_t x;
2196         value.getAsInteger(16, x);
2197         exc_data.push_back(x);
2198       } else if (key.compare("thread") == 0) {
2199         // thread in big endian hex
2200         if (value.getAsInteger(16, tid))
2201           tid = LLDB_INVALID_THREAD_ID;
2202       } else if (key.compare("threads") == 0) {
2203         std::lock_guard<std::recursive_mutex> guard(
2204             m_thread_list_real.GetMutex());
2205
2206         m_thread_ids.clear();
2207         // A comma separated list of all threads in the current
2208         // process that includes the thread for this stop reply
2209         // packet
2210         lldb::tid_t tid;
2211         while (!value.empty()) {
2212           llvm::StringRef tid_str;
2213           std::tie(tid_str, value) = value.split(',');
2214           if (tid_str.getAsInteger(16, tid))
2215             tid = LLDB_INVALID_THREAD_ID;
2216           m_thread_ids.push_back(tid);
2217         }
2218       } else if (key.compare("thread-pcs") == 0) {
2219         m_thread_pcs.clear();
2220         // A comma separated list of all threads in the current
2221         // process that includes the thread for this stop reply
2222         // packet
2223         lldb::addr_t pc;
2224         while (!value.empty()) {
2225           llvm::StringRef pc_str;
2226           std::tie(pc_str, value) = value.split(',');
2227           if (pc_str.getAsInteger(16, pc))
2228             pc = LLDB_INVALID_ADDRESS;
2229           m_thread_pcs.push_back(pc);
2230         }
2231       } else if (key.compare("jstopinfo") == 0) {
2232         StringExtractor json_extractor(value);
2233         std::string json;
2234         // Now convert the HEX bytes into a string value
2235         json_extractor.GetHexByteString(json);
2236
2237         // This JSON contains thread IDs and thread stop info for all threads.
2238         // It doesn't contain expedited registers, memory or queue info.
2239         m_jstopinfo_sp = StructuredData::ParseJSON(json);
2240       } else if (key.compare("hexname") == 0) {
2241         StringExtractor name_extractor(value);
2242         std::string name;
2243         // Now convert the HEX bytes into a string value
2244         name_extractor.GetHexByteString(thread_name);
2245       } else if (key.compare("name") == 0) {
2246         thread_name = value;
2247       } else if (key.compare("qaddr") == 0) {
2248         value.getAsInteger(16, thread_dispatch_qaddr);
2249       } else if (key.compare("dispatch_queue_t") == 0) {
2250         queue_vars_valid = true;
2251         value.getAsInteger(16, dispatch_queue_t);
2252       } else if (key.compare("qname") == 0) {
2253         queue_vars_valid = true;
2254         StringExtractor name_extractor(value);
2255         // Now convert the HEX bytes into a string value
2256         name_extractor.GetHexByteString(queue_name);
2257       } else if (key.compare("qkind") == 0) {
2258         queue_kind = llvm::StringSwitch<QueueKind>(value)
2259                          .Case("serial", eQueueKindSerial)
2260                          .Case("concurrent", eQueueKindConcurrent)
2261                          .Default(eQueueKindUnknown);
2262         queue_vars_valid = queue_kind != eQueueKindUnknown;
2263       } else if (key.compare("qserialnum") == 0) {
2264         if (!value.getAsInteger(0, queue_serial_number))
2265           queue_vars_valid = true;
2266       } else if (key.compare("reason") == 0) {
2267         reason = value;
2268       } else if (key.compare("description") == 0) {
2269         StringExtractor desc_extractor(value);
2270         // Now convert the HEX bytes into a string value
2271         desc_extractor.GetHexByteString(description);
2272       } else if (key.compare("memory") == 0) {
2273         // Expedited memory. GDB servers can choose to send back expedited
2274         // memory
2275         // that can populate the L1 memory cache in the process so that things
2276         // like
2277         // the frame pointer backchain can be expedited. This will help stack
2278         // backtracing be more efficient by not having to send as many memory
2279         // read
2280         // requests down the remote GDB server.
2281
2282         // Key/value pair format: memory:<addr>=<bytes>;
2283         // <addr> is a number whose base will be interpreted by the prefix:
2284         //      "0x[0-9a-fA-F]+" for hex
2285         //      "0[0-7]+" for octal
2286         //      "[1-9]+" for decimal
2287         // <bytes> is native endian ASCII hex bytes just like the register
2288         // values
2289         llvm::StringRef addr_str, bytes_str;
2290         std::tie(addr_str, bytes_str) = value.split('=');
2291         if (!addr_str.empty() && !bytes_str.empty()) {
2292           lldb::addr_t mem_cache_addr = LLDB_INVALID_ADDRESS;
2293           if (!addr_str.getAsInteger(0, mem_cache_addr)) {
2294             StringExtractor bytes(bytes_str);
2295             const size_t byte_size = bytes.GetBytesLeft() / 2;
2296             DataBufferSP data_buffer_sp(new DataBufferHeap(byte_size, 0));
2297             const size_t bytes_copied =
2298                 bytes.GetHexBytes(data_buffer_sp->GetData(), 0);
2299             if (bytes_copied == byte_size)
2300               m_memory_cache.AddL1CacheData(mem_cache_addr, data_buffer_sp);
2301           }
2302         }
2303       } else if (key.compare("watch") == 0 || key.compare("rwatch") == 0 ||
2304                  key.compare("awatch") == 0) {
2305         // Support standard GDB remote stop reply packet 'TAAwatch:addr'
2306         lldb::addr_t wp_addr = LLDB_INVALID_ADDRESS;
2307         value.getAsInteger(16, wp_addr);
2308
2309         WatchpointSP wp_sp =
2310             GetTarget().GetWatchpointList().FindByAddress(wp_addr);
2311         uint32_t wp_index = LLDB_INVALID_INDEX32;
2312
2313         if (wp_sp)
2314           wp_index = wp_sp->GetHardwareIndex();
2315
2316         reason = "watchpoint";
2317         StreamString ostr;
2318         ostr.Printf("%" PRIu64 " %" PRIu32, wp_addr, wp_index);
2319         description = ostr.GetString();
2320       } else if (key.compare("library") == 0) {
2321         LoadModules();
2322       } else if (key.size() == 2 && ::isxdigit(key[0]) && ::isxdigit(key[1])) {
2323         uint32_t reg = UINT32_MAX;
2324         if (!key.getAsInteger(16, reg))
2325           expedited_register_map[reg] = std::move(value);
2326       }
2327     }
2328
2329     if (tid == LLDB_INVALID_THREAD_ID) {
2330       // A thread id may be invalid if the response is old style 'S' packet
2331       // which does not provide the
2332       // thread information. So update the thread list and choose the first one.
2333       UpdateThreadIDList();
2334
2335       if (!m_thread_ids.empty()) {
2336         tid = m_thread_ids.front();
2337       }
2338     }
2339
2340     ThreadSP thread_sp = SetThreadStopInfo(
2341         tid, expedited_register_map, signo, thread_name, reason, description,
2342         exc_type, exc_data, thread_dispatch_qaddr, queue_vars_valid,
2343         associated_with_dispatch_queue, dispatch_queue_t, queue_name,
2344         queue_kind, queue_serial_number);
2345
2346     return eStateStopped;
2347   } break;
2348
2349   case 'W':
2350   case 'X':
2351     // process exited
2352     return eStateExited;
2353
2354   default:
2355     break;
2356   }
2357   return eStateInvalid;
2358 }
2359
2360 void ProcessGDBRemote::RefreshStateAfterStop() {
2361   std::lock_guard<std::recursive_mutex> guard(m_thread_list_real.GetMutex());
2362
2363   m_thread_ids.clear();
2364   m_thread_pcs.clear();
2365   // Set the thread stop info. It might have a "threads" key whose value is
2366   // a list of all thread IDs in the current process, so m_thread_ids might
2367   // get set.
2368
2369   // Scope for the lock
2370   {
2371     // Lock the thread stack while we access it
2372     std::lock_guard<std::recursive_mutex> guard(m_last_stop_packet_mutex);
2373     // Get the number of stop packets on the stack
2374     int nItems = m_stop_packet_stack.size();
2375     // Iterate over them
2376     for (int i = 0; i < nItems; i++) {
2377       // Get the thread stop info
2378       StringExtractorGDBRemote stop_info = m_stop_packet_stack[i];
2379       // Process thread stop info
2380       SetThreadStopInfo(stop_info);
2381     }
2382     // Clear the thread stop stack
2383     m_stop_packet_stack.clear();
2384   }
2385
2386   // Check to see if SetThreadStopInfo() filled in m_thread_ids?
2387   if (m_thread_ids.empty()) {
2388     // No, we need to fetch the thread list manually
2389     UpdateThreadIDList();
2390   }
2391
2392   // If we have queried for a default thread id
2393   if (m_initial_tid != LLDB_INVALID_THREAD_ID) {
2394     m_thread_list.SetSelectedThreadByID(m_initial_tid);
2395     m_initial_tid = LLDB_INVALID_THREAD_ID;
2396   }
2397
2398   // Let all threads recover from stopping and do any clean up based
2399   // on the previous thread state (if any).
2400   m_thread_list_real.RefreshStateAfterStop();
2401 }
2402
2403 Error ProcessGDBRemote::DoHalt(bool &caused_stop) {
2404   Error error;
2405
2406   if (m_public_state.GetValue() == eStateAttaching) {
2407     // We are being asked to halt during an attach. We need to just close
2408     // our file handle and debugserver will go away, and we can be done...
2409     m_gdb_comm.Disconnect();
2410   } else
2411     caused_stop = m_gdb_comm.Interrupt();
2412   return error;
2413 }
2414
2415 Error ProcessGDBRemote::DoDetach(bool keep_stopped) {
2416   Error error;
2417   Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
2418   if (log)
2419     log->Printf("ProcessGDBRemote::DoDetach(keep_stopped: %i)", keep_stopped);
2420
2421   error = m_gdb_comm.Detach(keep_stopped);
2422   if (log) {
2423     if (error.Success())
2424       log->PutCString(
2425           "ProcessGDBRemote::DoDetach() detach packet sent successfully");
2426     else
2427       log->Printf("ProcessGDBRemote::DoDetach() detach packet send failed: %s",
2428                   error.AsCString() ? error.AsCString() : "<unknown error>");
2429   }
2430
2431   if (!error.Success())
2432     return error;
2433
2434   // Sleep for one second to let the process get all detached...
2435   StopAsyncThread();
2436
2437   SetPrivateState(eStateDetached);
2438   ResumePrivateStateThread();
2439
2440   // KillDebugserverProcess ();
2441   return error;
2442 }
2443
2444 Error ProcessGDBRemote::DoDestroy() {
2445   Error error;
2446   Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
2447   if (log)
2448     log->Printf("ProcessGDBRemote::DoDestroy()");
2449
2450 #if 0 // XXX Currently no iOS target support on FreeBSD
2451   // There is a bug in older iOS debugservers where they don't shut down the
2452   // process
2453   // they are debugging properly.  If the process is sitting at a breakpoint or
2454   // an exception,
2455   // this can cause problems with restarting.  So we check to see if any of our
2456   // threads are stopped
2457   // at a breakpoint, and if so we remove all the breakpoints, resume the
2458   // process, and THEN
2459   // destroy it again.
2460   //
2461   // Note, we don't have a good way to test the version of debugserver, but I
2462   // happen to know that
2463   // the set of all the iOS debugservers which don't support
2464   // GetThreadSuffixSupported() and that of
2465   // the debugservers with this bug are equal.  There really should be a better
2466   // way to test this!
2467   //
2468   // We also use m_destroy_tried_resuming to make sure we only do this once, if
2469   // we resume and then halt and
2470   // get called here to destroy again and we're still at a breakpoint or
2471   // exception, then we should
2472   // just do the straight-forward kill.
2473   //
2474   // And of course, if we weren't able to stop the process by the time we get
2475   // here, it isn't
2476   // necessary (or helpful) to do any of this.
2477
2478   if (!m_gdb_comm.GetThreadSuffixSupported() &&
2479       m_public_state.GetValue() != eStateRunning) {
2480     PlatformSP platform_sp = GetTarget().GetPlatform();
2481
2482     // FIXME: These should be ConstStrings so we aren't doing strcmp'ing.
2483     if (platform_sp && platform_sp->GetName() &&
2484         platform_sp->GetName() == PlatformRemoteiOS::GetPluginNameStatic()) {
2485       if (m_destroy_tried_resuming) {
2486         if (log)
2487           log->PutCString("ProcessGDBRemote::DoDestroy() - Tried resuming to "
2488                           "destroy once already, not doing it again.");
2489       } else {
2490         // At present, the plans are discarded and the breakpoints disabled
2491         // Process::Destroy,
2492         // but we really need it to happen here and it doesn't matter if we do
2493         // it twice.
2494         m_thread_list.DiscardThreadPlans();
2495         DisableAllBreakpointSites();
2496
2497         bool stop_looks_like_crash = false;
2498         ThreadList &threads = GetThreadList();
2499
2500         {
2501           std::lock_guard<std::recursive_mutex> guard(threads.GetMutex());
2502
2503           size_t num_threads = threads.GetSize();
2504           for (size_t i = 0; i < num_threads; i++) {
2505             ThreadSP thread_sp = threads.GetThreadAtIndex(i);
2506             StopInfoSP stop_info_sp = thread_sp->GetPrivateStopInfo();
2507             StopReason reason = eStopReasonInvalid;
2508             if (stop_info_sp)
2509               reason = stop_info_sp->GetStopReason();
2510             if (reason == eStopReasonBreakpoint ||
2511                 reason == eStopReasonException) {
2512               if (log)
2513                 log->Printf(
2514                     "ProcessGDBRemote::DoDestroy() - thread: 0x%4.4" PRIx64
2515                     " stopped with reason: %s.",
2516                     thread_sp->GetProtocolID(), stop_info_sp->GetDescription());
2517               stop_looks_like_crash = true;
2518               break;
2519             }
2520           }
2521         }
2522
2523         if (stop_looks_like_crash) {
2524           if (log)
2525             log->PutCString("ProcessGDBRemote::DoDestroy() - Stopped at a "
2526                             "breakpoint, continue and then kill.");
2527           m_destroy_tried_resuming = true;
2528
2529           // If we are going to run again before killing, it would be good to
2530           // suspend all the threads
2531           // before resuming so they won't get into more trouble.  Sadly, for
2532           // the threads stopped with
2533           // the breakpoint or exception, the exception doesn't get cleared if
2534           // it is suspended, so we do
2535           // have to run the risk of letting those threads proceed a bit.
2536
2537           {
2538             std::lock_guard<std::recursive_mutex> guard(threads.GetMutex());
2539
2540             size_t num_threads = threads.GetSize();
2541             for (size_t i = 0; i < num_threads; i++) {
2542               ThreadSP thread_sp = threads.GetThreadAtIndex(i);
2543               StopInfoSP stop_info_sp = thread_sp->GetPrivateStopInfo();
2544               StopReason reason = eStopReasonInvalid;
2545               if (stop_info_sp)
2546                 reason = stop_info_sp->GetStopReason();
2547               if (reason != eStopReasonBreakpoint &&
2548                   reason != eStopReasonException) {
2549                 if (log)
2550                   log->Printf("ProcessGDBRemote::DoDestroy() - Suspending "
2551                               "thread: 0x%4.4" PRIx64 " before running.",
2552                               thread_sp->GetProtocolID());
2553                 thread_sp->SetResumeState(eStateSuspended);
2554               }
2555             }
2556           }
2557           Resume();
2558           return Destroy(false);
2559         }
2560       }
2561     }
2562   }
2563 #endif
2564
2565   // Interrupt if our inferior is running...
2566   int exit_status = SIGABRT;
2567   std::string exit_string;
2568
2569   if (m_gdb_comm.IsConnected()) {
2570     if (m_public_state.GetValue() != eStateAttaching) {
2571       StringExtractorGDBRemote response;
2572       bool send_async = true;
2573       GDBRemoteCommunication::ScopedTimeout(m_gdb_comm,
2574                                             std::chrono::seconds(3));
2575
2576       if (m_gdb_comm.SendPacketAndWaitForResponse("k", response, send_async) ==
2577           GDBRemoteCommunication::PacketResult::Success) {
2578         char packet_cmd = response.GetChar(0);
2579
2580         if (packet_cmd == 'W' || packet_cmd == 'X') {
2581 #if defined(__APPLE__)
2582           // For Native processes on Mac OS X, we launch through the Host
2583           // Platform, then hand the process off
2584           // to debugserver, which becomes the parent process through
2585           // "PT_ATTACH".  Then when we go to kill
2586           // the process on Mac OS X we call ptrace(PT_KILL) to kill it, then we
2587           // call waitpid which returns
2588           // with no error and the correct status.  But amusingly enough that
2589           // doesn't seem to actually reap
2590           // the process, but instead it is left around as a Zombie.  Probably
2591           // the kernel is in the process of
2592           // switching ownership back to lldb which was the original parent, and
2593           // gets confused in the handoff.
2594           // Anyway, so call waitpid here to finally reap it.
2595           PlatformSP platform_sp(GetTarget().GetPlatform());
2596           if (platform_sp && platform_sp->IsHost()) {
2597             int status;
2598             ::pid_t reap_pid;
2599             reap_pid = waitpid(GetID(), &status, WNOHANG);
2600             if (log)
2601               log->Printf("Reaped pid: %d, status: %d.\n", reap_pid, status);
2602           }
2603 #endif
2604           SetLastStopPacket(response);
2605           ClearThreadIDList();
2606           exit_status = response.GetHexU8();
2607         } else {
2608           if (log)
2609             log->Printf("ProcessGDBRemote::DoDestroy - got unexpected response "
2610                         "to k packet: %s",
2611                         response.GetStringRef().c_str());
2612           exit_string.assign("got unexpected response to k packet: ");
2613           exit_string.append(response.GetStringRef());
2614         }
2615       } else {
2616         if (log)
2617           log->Printf("ProcessGDBRemote::DoDestroy - failed to send k packet");
2618         exit_string.assign("failed to send the k packet");
2619       }
2620     } else {
2621       if (log)
2622         log->Printf("ProcessGDBRemote::DoDestroy - killed or interrupted while "
2623                     "attaching");
2624       exit_string.assign("killed or interrupted while attaching.");
2625     }
2626   } else {
2627     // If we missed setting the exit status on the way out, do it here.
2628     // NB set exit status can be called multiple times, the first one sets the
2629     // status.
2630     exit_string.assign("destroying when not connected to debugserver");
2631   }
2632
2633   SetExitStatus(exit_status, exit_string.c_str());
2634
2635   StopAsyncThread();
2636   KillDebugserverProcess();
2637   return error;
2638 }
2639
2640 void ProcessGDBRemote::SetLastStopPacket(
2641     const StringExtractorGDBRemote &response) {
2642   const bool did_exec =
2643       response.GetStringRef().find(";reason:exec;") != std::string::npos;
2644   if (did_exec) {
2645     Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
2646     if (log)
2647       log->Printf("ProcessGDBRemote::SetLastStopPacket () - detected exec");
2648
2649     m_thread_list_real.Clear();
2650     m_thread_list.Clear();
2651     BuildDynamicRegisterInfo(true);
2652     m_gdb_comm.ResetDiscoverableSettings(did_exec);
2653   }
2654
2655   // Scope the lock
2656   {
2657     // Lock the thread stack while we access it
2658     std::lock_guard<std::recursive_mutex> guard(m_last_stop_packet_mutex);
2659
2660     // We are are not using non-stop mode, there can only be one last stop
2661     // reply packet, so clear the list.
2662     if (GetTarget().GetNonStopModeEnabled() == false)
2663       m_stop_packet_stack.clear();
2664
2665     // Add this stop packet to the stop packet stack
2666     // This stack will get popped and examined when we switch to the
2667     // Stopped state
2668     m_stop_packet_stack.push_back(response);
2669   }
2670 }
2671
2672 void ProcessGDBRemote::SetUnixSignals(const UnixSignalsSP &signals_sp) {
2673   Process::SetUnixSignals(std::make_shared<GDBRemoteSignals>(signals_sp));
2674 }
2675
2676 //------------------------------------------------------------------
2677 // Process Queries
2678 //------------------------------------------------------------------
2679
2680 bool ProcessGDBRemote::IsAlive() {
2681   return m_gdb_comm.IsConnected() && Process::IsAlive();
2682 }
2683
2684 addr_t ProcessGDBRemote::GetImageInfoAddress() {
2685   // request the link map address via the $qShlibInfoAddr packet
2686   lldb::addr_t addr = m_gdb_comm.GetShlibInfoAddr();
2687
2688   // the loaded module list can also provides a link map address
2689   if (addr == LLDB_INVALID_ADDRESS) {
2690     LoadedModuleInfoList list;
2691     if (GetLoadedModuleList(list).Success())
2692       addr = list.m_link_map;
2693   }
2694
2695   return addr;
2696 }
2697
2698 void ProcessGDBRemote::WillPublicStop() {
2699   // See if the GDB remote client supports the JSON threads info.
2700   // If so, we gather stop info for all threads, expedited registers,
2701   // expedited memory, runtime queue information (iOS and MacOSX only),
2702   // and more. Expediting memory will help stack backtracing be much
2703   // faster. Expediting registers will make sure we don't have to read
2704   // the thread registers for GPRs.
2705   m_jthreadsinfo_sp = m_gdb_comm.GetThreadsInfo();
2706
2707   if (m_jthreadsinfo_sp) {
2708     // Now set the stop info for each thread and also expedite any registers
2709     // and memory that was in the jThreadsInfo response.
2710     StructuredData::Array *thread_infos = m_jthreadsinfo_sp->GetAsArray();
2711     if (thread_infos) {
2712       const size_t n = thread_infos->GetSize();
2713       for (size_t i = 0; i < n; ++i) {
2714         StructuredData::Dictionary *thread_dict =
2715             thread_infos->GetItemAtIndex(i)->GetAsDictionary();
2716         if (thread_dict)
2717           SetThreadStopInfo(thread_dict);
2718       }
2719     }
2720   }
2721 }
2722
2723 //------------------------------------------------------------------
2724 // Process Memory
2725 //------------------------------------------------------------------
2726 size_t ProcessGDBRemote::DoReadMemory(addr_t addr, void *buf, size_t size,
2727                                       Error &error) {
2728   GetMaxMemorySize();
2729   bool binary_memory_read = m_gdb_comm.GetxPacketSupported();
2730   // M and m packets take 2 bytes for 1 byte of memory
2731   size_t max_memory_size =
2732       binary_memory_read ? m_max_memory_size : m_max_memory_size / 2;
2733   if (size > max_memory_size) {
2734     // Keep memory read sizes down to a sane limit. This function will be
2735     // called multiple times in order to complete the task by
2736     // lldb_private::Process so it is ok to do this.
2737     size = max_memory_size;
2738   }
2739
2740   char packet[64];
2741   int packet_len;
2742   packet_len = ::snprintf(packet, sizeof(packet), "%c%" PRIx64 ",%" PRIx64,
2743                           binary_memory_read ? 'x' : 'm', (uint64_t)addr,
2744                           (uint64_t)size);
2745   assert(packet_len + 1 < (int)sizeof(packet));
2746   UNUSED_IF_ASSERT_DISABLED(packet_len);
2747   StringExtractorGDBRemote response;
2748   if (m_gdb_comm.SendPacketAndWaitForResponse(packet, response, true) ==
2749       GDBRemoteCommunication::PacketResult::Success) {
2750     if (response.IsNormalResponse()) {
2751       error.Clear();
2752       if (binary_memory_read) {
2753         // The lower level GDBRemoteCommunication packet receive layer has
2754         // already de-quoted any
2755         // 0x7d character escaping that was present in the packet
2756
2757         size_t data_received_size = response.GetBytesLeft();
2758         if (data_received_size > size) {
2759           // Don't write past the end of BUF if the remote debug server gave us
2760           // too
2761           // much data for some reason.
2762           data_received_size = size;
2763         }
2764         memcpy(buf, response.GetStringRef().data(), data_received_size);
2765         return data_received_size;
2766       } else {
2767         return response.GetHexBytes(
2768             llvm::MutableArrayRef<uint8_t>((uint8_t *)buf, size), '\xdd');
2769       }
2770     } else if (response.IsErrorResponse())
2771       error.SetErrorStringWithFormat("memory read failed for 0x%" PRIx64, addr);
2772     else if (response.IsUnsupportedResponse())
2773       error.SetErrorStringWithFormat(
2774           "GDB server does not support reading memory");
2775     else
2776       error.SetErrorStringWithFormat(
2777           "unexpected response to GDB server memory read packet '%s': '%s'",
2778           packet, response.GetStringRef().c_str());
2779   } else {
2780     error.SetErrorStringWithFormat("failed to send packet: '%s'", packet);
2781   }
2782   return 0;
2783 }
2784
2785 size_t ProcessGDBRemote::DoWriteMemory(addr_t addr, const void *buf,
2786                                        size_t size, Error &error) {
2787   GetMaxMemorySize();
2788   // M and m packets take 2 bytes for 1 byte of memory
2789   size_t max_memory_size = m_max_memory_size / 2;
2790   if (size > max_memory_size) {
2791     // Keep memory read sizes down to a sane limit. This function will be
2792     // called multiple times in order to complete the task by
2793     // lldb_private::Process so it is ok to do this.
2794     size = max_memory_size;
2795   }
2796
2797   StreamString packet;
2798   packet.Printf("M%" PRIx64 ",%" PRIx64 ":", addr, (uint64_t)size);
2799   packet.PutBytesAsRawHex8(buf, size, endian::InlHostByteOrder(),
2800                            endian::InlHostByteOrder());
2801   StringExtractorGDBRemote response;
2802   if (m_gdb_comm.SendPacketAndWaitForResponse(packet.GetString(), response,
2803                                               true) ==
2804       GDBRemoteCommunication::PacketResult::Success) {
2805     if (response.IsOKResponse()) {
2806       error.Clear();
2807       return size;
2808     } else if (response.IsErrorResponse())
2809       error.SetErrorStringWithFormat("memory write failed for 0x%" PRIx64,
2810                                      addr);
2811     else if (response.IsUnsupportedResponse())
2812       error.SetErrorStringWithFormat(
2813           "GDB server does not support writing memory");
2814     else
2815       error.SetErrorStringWithFormat(
2816           "unexpected response to GDB server memory write packet '%s': '%s'",
2817           packet.GetData(), response.GetStringRef().c_str());
2818   } else {
2819     error.SetErrorStringWithFormat("failed to send packet: '%s'",
2820                                    packet.GetData());
2821   }
2822   return 0;
2823 }
2824
2825 lldb::addr_t ProcessGDBRemote::DoAllocateMemory(size_t size,
2826                                                 uint32_t permissions,
2827                                                 Error &error) {
2828   Log *log(
2829       GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS | LIBLLDB_LOG_EXPRESSIONS));
2830   addr_t allocated_addr = LLDB_INVALID_ADDRESS;
2831
2832   if (m_gdb_comm.SupportsAllocDeallocMemory() != eLazyBoolNo) {
2833     allocated_addr = m_gdb_comm.AllocateMemory(size, permissions);
2834     if (allocated_addr != LLDB_INVALID_ADDRESS ||
2835         m_gdb_comm.SupportsAllocDeallocMemory() == eLazyBoolYes)
2836       return allocated_addr;
2837   }
2838
2839   if (m_gdb_comm.SupportsAllocDeallocMemory() == eLazyBoolNo) {
2840     // Call mmap() to create memory in the inferior..
2841     unsigned prot = 0;
2842     if (permissions & lldb::ePermissionsReadable)
2843       prot |= eMmapProtRead;
2844     if (permissions & lldb::ePermissionsWritable)
2845       prot |= eMmapProtWrite;
2846     if (permissions & lldb::ePermissionsExecutable)
2847       prot |= eMmapProtExec;
2848
2849     if (InferiorCallMmap(this, allocated_addr, 0, size, prot,
2850                          eMmapFlagsAnon | eMmapFlagsPrivate, -1, 0))
2851       m_addr_to_mmap_size[allocated_addr] = size;
2852     else {
2853       allocated_addr = LLDB_INVALID_ADDRESS;
2854       if (log)
2855         log->Printf("ProcessGDBRemote::%s no direct stub support for memory "
2856                     "allocation, and InferiorCallMmap also failed - is stub "
2857                     "missing register context save/restore capability?",
2858                     __FUNCTION__);
2859     }
2860   }
2861
2862   if (allocated_addr == LLDB_INVALID_ADDRESS)
2863     error.SetErrorStringWithFormat(
2864         "unable to allocate %" PRIu64 " bytes of memory with permissions %s",
2865         (uint64_t)size, GetPermissionsAsCString(permissions));
2866   else
2867     error.Clear();
2868   return allocated_addr;
2869 }
2870
2871 Error ProcessGDBRemote::GetMemoryRegionInfo(addr_t load_addr,
2872                                             MemoryRegionInfo &region_info) {
2873
2874   Error error(m_gdb_comm.GetMemoryRegionInfo(load_addr, region_info));
2875   return error;
2876 }
2877
2878 Error ProcessGDBRemote::GetWatchpointSupportInfo(uint32_t &num) {
2879
2880   Error error(m_gdb_comm.GetWatchpointSupportInfo(num));
2881   return error;
2882 }
2883
2884 Error ProcessGDBRemote::GetWatchpointSupportInfo(uint32_t &num, bool &after) {
2885   Error error(m_gdb_comm.GetWatchpointSupportInfo(
2886       num, after, GetTarget().GetArchitecture()));
2887   return error;
2888 }
2889
2890 Error ProcessGDBRemote::DoDeallocateMemory(lldb::addr_t addr) {
2891   Error error;
2892   LazyBool supported = m_gdb_comm.SupportsAllocDeallocMemory();
2893
2894   switch (supported) {
2895   case eLazyBoolCalculate:
2896     // We should never be deallocating memory without allocating memory
2897     // first so we should never get eLazyBoolCalculate
2898     error.SetErrorString(
2899         "tried to deallocate memory without ever allocating memory");
2900     break;
2901
2902   case eLazyBoolYes:
2903     if (!m_gdb_comm.DeallocateMemory(addr))
2904       error.SetErrorStringWithFormat(
2905           "unable to deallocate memory at 0x%" PRIx64, addr);
2906     break;
2907
2908   case eLazyBoolNo:
2909     // Call munmap() to deallocate memory in the inferior..
2910     {
2911       MMapMap::iterator pos = m_addr_to_mmap_size.find(addr);
2912       if (pos != m_addr_to_mmap_size.end() &&
2913           InferiorCallMunmap(this, addr, pos->second))
2914         m_addr_to_mmap_size.erase(pos);
2915       else
2916         error.SetErrorStringWithFormat(
2917             "unable to deallocate memory at 0x%" PRIx64, addr);
2918     }
2919     break;
2920   }
2921
2922   return error;
2923 }
2924
2925 //------------------------------------------------------------------
2926 // Process STDIO
2927 //------------------------------------------------------------------
2928 size_t ProcessGDBRemote::PutSTDIN(const char *src, size_t src_len,
2929                                   Error &error) {
2930   if (m_stdio_communication.IsConnected()) {
2931     ConnectionStatus status;
2932     m_stdio_communication.Write(src, src_len, status, NULL);
2933   } else if (m_stdin_forward) {
2934     m_gdb_comm.SendStdinNotification(src, src_len);
2935   }
2936   return 0;
2937 }
2938
2939 Error ProcessGDBRemote::EnableBreakpointSite(BreakpointSite *bp_site) {
2940   Error error;
2941   assert(bp_site != NULL);
2942
2943   // Get logging info
2944   Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_BREAKPOINTS));
2945   user_id_t site_id = bp_site->GetID();
2946
2947   // Get the breakpoint address
2948   const addr_t addr = bp_site->GetLoadAddress();
2949
2950   // Log that a breakpoint was requested
2951   if (log)
2952     log->Printf("ProcessGDBRemote::EnableBreakpointSite (size_id = %" PRIu64
2953                 ") address = 0x%" PRIx64,
2954                 site_id, (uint64_t)addr);
2955
2956   // Breakpoint already exists and is enabled
2957   if (bp_site->IsEnabled()) {
2958     if (log)
2959       log->Printf("ProcessGDBRemote::EnableBreakpointSite (size_id = %" PRIu64
2960                   ") address = 0x%" PRIx64 " -- SUCCESS (already enabled)",
2961                   site_id, (uint64_t)addr);
2962     return error;
2963   }
2964
2965   // Get the software breakpoint trap opcode size
2966   const size_t bp_op_size = GetSoftwareBreakpointTrapOpcode(bp_site);
2967
2968   // SupportsGDBStoppointPacket() simply checks a boolean, indicating if this
2969   // breakpoint type
2970   // is supported by the remote stub. These are set to true by default, and
2971   // later set to false
2972   // only after we receive an unimplemented response when sending a breakpoint
2973   // packet. This means
2974   // initially that unless we were specifically instructed to use a hardware
2975   // breakpoint, LLDB will
2976   // attempt to set a software breakpoint. HardwareRequired() also queries a
2977   // boolean variable which
2978   // indicates if the user specifically asked for hardware breakpoints.  If true
2979   // then we will
2980   // skip over software breakpoints.
2981   if (m_gdb_comm.SupportsGDBStoppointPacket(eBreakpointSoftware) &&
2982       (!bp_site->HardwareRequired())) {
2983     // Try to send off a software breakpoint packet ($Z0)
2984     uint8_t error_no = m_gdb_comm.SendGDBStoppointTypePacket(
2985         eBreakpointSoftware, true, addr, bp_op_size);
2986     if (error_no == 0) {
2987       // The breakpoint was placed successfully
2988       bp_site->SetEnabled(true);
2989       bp_site->SetType(BreakpointSite::eExternal);
2990       return error;
2991     }
2992
2993     // SendGDBStoppointTypePacket() will return an error if it was unable to set
2994     // this
2995     // breakpoint. We need to differentiate between a error specific to placing
2996     // this breakpoint
2997     // or if we have learned that this breakpoint type is unsupported. To do
2998     // this, we
2999     // must test the support boolean for this breakpoint type to see if it now
3000     // indicates that
3001     // this breakpoint type is unsupported.  If they are still supported then we
3002     // should return
3003     // with the error code.  If they are now unsupported, then we would like to
3004     // fall through
3005     // and try another form of breakpoint.
3006     if (m_gdb_comm.SupportsGDBStoppointPacket(eBreakpointSoftware)) {
3007       if (error_no != UINT8_MAX)
3008         error.SetErrorStringWithFormat(
3009             "error: %d sending the breakpoint request", errno);
3010       else
3011         error.SetErrorString("error sending the breakpoint request");
3012       return error;
3013     }
3014
3015     // We reach here when software breakpoints have been found to be
3016     // unsupported. For future
3017     // calls to set a breakpoint, we will not attempt to set a breakpoint with a
3018     // type that is
3019     // known not to be supported.
3020     if (log)
3021       log->Printf("Software breakpoints are unsupported");
3022
3023     // So we will fall through and try a hardware breakpoint
3024   }
3025
3026   // The process of setting a hardware breakpoint is much the same as above.  We
3027   // check the
3028   // supported boolean for this breakpoint type, and if it is thought to be
3029   // supported then we
3030   // will try to set this breakpoint with a hardware breakpoint.
3031   if (m_gdb_comm.SupportsGDBStoppointPacket(eBreakpointHardware)) {
3032     // Try to send off a hardware breakpoint packet ($Z1)
3033     uint8_t error_no = m_gdb_comm.SendGDBStoppointTypePacket(
3034         eBreakpointHardware, true, addr, bp_op_size);
3035     if (error_no == 0) {
3036       // The breakpoint was placed successfully
3037       bp_site->SetEnabled(true);
3038       bp_site->SetType(BreakpointSite::eHardware);
3039       return error;
3040     }
3041
3042     // Check if the error was something other then an unsupported breakpoint
3043     // type
3044     if (m_gdb_comm.SupportsGDBStoppointPacket(eBreakpointHardware)) {
3045       // Unable to set this hardware breakpoint
3046       if (error_no != UINT8_MAX)
3047         error.SetErrorStringWithFormat(
3048             "error: %d sending the hardware breakpoint request "
3049             "(hardware breakpoint resources might be exhausted or unavailable)",
3050             error_no);
3051       else
3052         error.SetErrorString("error sending the hardware breakpoint request "
3053                              "(hardware breakpoint resources "
3054                              "might be exhausted or unavailable)");
3055       return error;
3056     }
3057
3058     // We will reach here when the stub gives an unsupported response to a
3059     // hardware breakpoint
3060     if (log)
3061       log->Printf("Hardware breakpoints are unsupported");
3062
3063     // Finally we will falling through to a #trap style breakpoint
3064   }
3065
3066   // Don't fall through when hardware breakpoints were specifically requested
3067   if (bp_site->HardwareRequired()) {
3068     error.SetErrorString("hardware breakpoints are not supported");
3069     return error;
3070   }
3071
3072   // As a last resort we want to place a manual breakpoint. An instruction
3073   // is placed into the process memory using memory write packets.
3074   return EnableSoftwareBreakpoint(bp_site);
3075 }
3076
3077 Error ProcessGDBRemote::DisableBreakpointSite(BreakpointSite *bp_site) {
3078   Error error;
3079   assert(bp_site != NULL);
3080   addr_t addr = bp_site->GetLoadAddress();
3081   user_id_t site_id = bp_site->GetID();
3082   Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_BREAKPOINTS));
3083   if (log)
3084     log->Printf("ProcessGDBRemote::DisableBreakpointSite (site_id = %" PRIu64
3085                 ") addr = 0x%8.8" PRIx64,
3086                 site_id, (uint64_t)addr);
3087
3088   if (bp_site->IsEnabled()) {
3089     const size_t bp_op_size = GetSoftwareBreakpointTrapOpcode(bp_site);
3090
3091     BreakpointSite::Type bp_type = bp_site->GetType();
3092     switch (bp_type) {
3093     case BreakpointSite::eSoftware:
3094       error = DisableSoftwareBreakpoint(bp_site);
3095       break;
3096
3097     case BreakpointSite::eHardware:
3098       if (m_gdb_comm.SendGDBStoppointTypePacket(eBreakpointHardware, false,
3099                                                 addr, bp_op_size))
3100         error.SetErrorToGenericError();
3101       break;
3102
3103     case BreakpointSite::eExternal: {
3104       GDBStoppointType stoppoint_type;
3105       if (bp_site->IsHardware())
3106         stoppoint_type = eBreakpointHardware;
3107       else
3108         stoppoint_type = eBreakpointSoftware;
3109
3110       if (m_gdb_comm.SendGDBStoppointTypePacket(stoppoint_type, false, addr,
3111                                                 bp_op_size))
3112         error.SetErrorToGenericError();
3113     } break;
3114     }
3115     if (error.Success())
3116       bp_site->SetEnabled(false);
3117   } else {
3118     if (log)
3119       log->Printf("ProcessGDBRemote::DisableBreakpointSite (site_id = %" PRIu64
3120                   ") addr = 0x%8.8" PRIx64 " -- SUCCESS (already disabled)",
3121                   site_id, (uint64_t)addr);
3122     return error;
3123   }
3124
3125   if (error.Success())
3126     error.SetErrorToGenericError();
3127   return error;
3128 }
3129
3130 // Pre-requisite: wp != NULL.
3131 static GDBStoppointType GetGDBStoppointType(Watchpoint *wp) {
3132   assert(wp);
3133   bool watch_read = wp->WatchpointRead();
3134   bool watch_write = wp->WatchpointWrite();
3135
3136   // watch_read and watch_write cannot both be false.
3137   assert(watch_read || watch_write);
3138   if (watch_read && watch_write)
3139     return eWatchpointReadWrite;
3140   else if (watch_read)
3141     return eWatchpointRead;
3142   else // Must be watch_write, then.
3143     return eWatchpointWrite;
3144 }
3145
3146 Error ProcessGDBRemote::EnableWatchpoint(Watchpoint *wp, bool notify) {
3147   Error error;
3148   if (wp) {
3149     user_id_t watchID = wp->GetID();
3150     addr_t addr = wp->GetLoadAddress();
3151     Log *log(
3152         ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_WATCHPOINTS));
3153     if (log)
3154       log->Printf("ProcessGDBRemote::EnableWatchpoint(watchID = %" PRIu64 ")",
3155                   watchID);
3156     if (wp->IsEnabled()) {
3157       if (log)
3158         log->Printf("ProcessGDBRemote::EnableWatchpoint(watchID = %" PRIu64
3159                     ") addr = 0x%8.8" PRIx64 ": watchpoint already enabled.",
3160                     watchID, (uint64_t)addr);
3161       return error;
3162     }
3163
3164     GDBStoppointType type = GetGDBStoppointType(wp);
3165     // Pass down an appropriate z/Z packet...
3166     if (m_gdb_comm.SupportsGDBStoppointPacket(type)) {
3167       if (m_gdb_comm.SendGDBStoppointTypePacket(type, true, addr,
3168                                                 wp->GetByteSize()) == 0) {
3169         wp->SetEnabled(true, notify);
3170         return error;
3171       } else
3172         error.SetErrorString("sending gdb watchpoint packet failed");
3173     } else
3174       error.SetErrorString("watchpoints not supported");
3175   } else {
3176     error.SetErrorString("Watchpoint argument was NULL.");
3177   }
3178   if (error.Success())
3179     error.SetErrorToGenericError();
3180   return error;
3181 }
3182
3183 Error ProcessGDBRemote::DisableWatchpoint(Watchpoint *wp, bool notify) {
3184   Error error;
3185   if (wp) {
3186     user_id_t watchID = wp->GetID();
3187
3188     Log *log(
3189         ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_WATCHPOINTS));
3190
3191     addr_t addr = wp->GetLoadAddress();
3192
3193     if (log)
3194       log->Printf("ProcessGDBRemote::DisableWatchpoint (watchID = %" PRIu64
3195                   ") addr = 0x%8.8" PRIx64,
3196                   watchID, (uint64_t)addr);
3197
3198     if (!wp->IsEnabled()) {
3199       if (log)
3200         log->Printf("ProcessGDBRemote::DisableWatchpoint (watchID = %" PRIu64
3201                     ") addr = 0x%8.8" PRIx64 " -- SUCCESS (already disabled)",
3202                     watchID, (uint64_t)addr);
3203       // See also 'class WatchpointSentry' within StopInfo.cpp.
3204       // This disabling attempt might come from the user-supplied actions, we'll
3205       // route it in order for
3206       // the watchpoint object to intelligently process this action.
3207       wp->SetEnabled(false, notify);
3208       return error;
3209     }
3210
3211     if (wp->IsHardware()) {
3212       GDBStoppointType type = GetGDBStoppointType(wp);
3213       // Pass down an appropriate z/Z packet...
3214       if (m_gdb_comm.SendGDBStoppointTypePacket(type, false, addr,
3215                                                 wp->GetByteSize()) == 0) {
3216         wp->SetEnabled(false, notify);
3217         return error;
3218       } else
3219         error.SetErrorString("sending gdb watchpoint packet failed");
3220     }
3221     // TODO: clear software watchpoints if we implement them
3222   } else {
3223     error.SetErrorString("Watchpoint argument was NULL.");
3224   }
3225   if (error.Success())
3226     error.SetErrorToGenericError();
3227   return error;
3228 }
3229
3230 void ProcessGDBRemote::Clear() {
3231   m_flags = 0;
3232   m_thread_list_real.Clear();
3233   m_thread_list.Clear();
3234 }
3235
3236 Error ProcessGDBRemote::DoSignal(int signo) {
3237   Error error;
3238   Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
3239   if (log)
3240     log->Printf("ProcessGDBRemote::DoSignal (signal = %d)", signo);
3241
3242   if (!m_gdb_comm.SendAsyncSignal(signo))
3243     error.SetErrorStringWithFormat("failed to send signal %i", signo);
3244   return error;
3245 }
3246
3247 Error ProcessGDBRemote::EstablishConnectionIfNeeded(
3248     const ProcessInfo &process_info) {
3249   // Make sure we aren't already connected?
3250   if (m_gdb_comm.IsConnected())
3251     return Error();
3252
3253   PlatformSP platform_sp(GetTarget().GetPlatform());
3254   if (platform_sp && !platform_sp->IsHost())
3255     return Error("Lost debug server connection");
3256
3257   auto error = LaunchAndConnectToDebugserver(process_info);
3258   if (error.Fail()) {
3259     const char *error_string = error.AsCString();
3260     if (error_string == nullptr)
3261       error_string = "unable to launch " DEBUGSERVER_BASENAME;
3262   }
3263   return error;
3264 }
3265 #if defined(__APPLE__)
3266 #define USE_SOCKETPAIR_FOR_LOCAL_CONNECTION 1
3267 #endif
3268
3269 #ifdef USE_SOCKETPAIR_FOR_LOCAL_CONNECTION
3270 static bool SetCloexecFlag(int fd) {
3271 #if defined(FD_CLOEXEC)
3272   int flags = ::fcntl(fd, F_GETFD);
3273   if (flags == -1)
3274     return false;
3275   return (::fcntl(fd, F_SETFD, flags | FD_CLOEXEC) == 0);
3276 #else
3277   return false;
3278 #endif
3279 }
3280 #endif
3281
3282 Error ProcessGDBRemote::LaunchAndConnectToDebugserver(
3283     const ProcessInfo &process_info) {
3284   using namespace std::placeholders; // For _1, _2, etc.
3285
3286   Error error;
3287   if (m_debugserver_pid == LLDB_INVALID_PROCESS_ID) {
3288     // If we locate debugserver, keep that located version around
3289     static FileSpec g_debugserver_file_spec;
3290
3291     ProcessLaunchInfo debugserver_launch_info;
3292     // Make debugserver run in its own session so signals generated by
3293     // special terminal key sequences (^C) don't affect debugserver.
3294     debugserver_launch_info.SetLaunchInSeparateProcessGroup(true);
3295
3296     const std::weak_ptr<ProcessGDBRemote> this_wp =
3297         std::static_pointer_cast<ProcessGDBRemote>(shared_from_this());
3298     debugserver_launch_info.SetMonitorProcessCallback(
3299         std::bind(MonitorDebugserverProcess, this_wp, _1, _2, _3, _4), false);
3300     debugserver_launch_info.SetUserID(process_info.GetUserID());
3301
3302     int communication_fd = -1;
3303 #ifdef USE_SOCKETPAIR_FOR_LOCAL_CONNECTION
3304     // Auto close the sockets we might open up unless everything goes OK. This
3305     // helps us not leak file descriptors when things go wrong.
3306     lldb_utility::CleanUp<int, int> our_socket(-1, -1, close);
3307     lldb_utility::CleanUp<int, int> gdb_socket(-1, -1, close);
3308
3309     // Use a socketpair on Apple for now until other platforms can verify it
3310     // works and is fast enough
3311     {
3312       int sockets[2]; /* the pair of socket descriptors */
3313       if (socketpair(AF_UNIX, SOCK_STREAM, 0, sockets) == -1) {
3314         error.SetErrorToErrno();
3315         return error;
3316       }
3317
3318       our_socket.set(sockets[0]);
3319       gdb_socket.set(sockets[1]);
3320     }
3321
3322     // Don't let any child processes inherit our communication socket
3323     SetCloexecFlag(our_socket.get());
3324     communication_fd = gdb_socket.get();
3325 #endif
3326
3327     error = m_gdb_comm.StartDebugserverProcess(
3328         nullptr, GetTarget().GetPlatform().get(), debugserver_launch_info,
3329         nullptr, nullptr, communication_fd);
3330
3331     if (error.Success())
3332       m_debugserver_pid = debugserver_launch_info.GetProcessID();
3333     else
3334       m_debugserver_pid = LLDB_INVALID_PROCESS_ID;
3335
3336     if (m_debugserver_pid != LLDB_INVALID_PROCESS_ID) {
3337 #ifdef USE_SOCKETPAIR_FOR_LOCAL_CONNECTION
3338       // Our process spawned correctly, we can now set our connection to use our
3339       // end of the socket pair
3340       m_gdb_comm.SetConnection(
3341           new ConnectionFileDescriptor(our_socket.release(), true));
3342 #endif
3343       StartAsyncThread();
3344     }
3345
3346     if (error.Fail()) {
3347       Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
3348
3349       if (log)
3350         log->Printf("failed to start debugserver process: %s",
3351                     error.AsCString());
3352       return error;
3353     }
3354
3355     if (m_gdb_comm.IsConnected()) {
3356       // Finish the connection process by doing the handshake without connecting
3357       // (send NULL URL)
3358       ConnectToDebugserver("");
3359     } else {
3360       error.SetErrorString("connection failed");
3361     }
3362   }
3363   return error;
3364 }
3365
3366 bool ProcessGDBRemote::MonitorDebugserverProcess(
3367     std::weak_ptr<ProcessGDBRemote> process_wp, lldb::pid_t debugserver_pid,
3368     bool exited,    // True if the process did exit
3369     int signo,      // Zero for no signal
3370     int exit_status // Exit value of process if signal is zero
3371     ) {
3372   // "debugserver_pid" argument passed in is the process ID for
3373   // debugserver that we are tracking...
3374   Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
3375   const bool handled = true;
3376
3377   if (log)
3378     log->Printf("ProcessGDBRemote::%s(process_wp, pid=%" PRIu64
3379                 ", signo=%i (0x%x), exit_status=%i)",
3380                 __FUNCTION__, debugserver_pid, signo, signo, exit_status);
3381
3382   std::shared_ptr<ProcessGDBRemote> process_sp = process_wp.lock();
3383   if (log)
3384     log->Printf("ProcessGDBRemote::%s(process = %p)", __FUNCTION__,
3385                 static_cast<void *>(process_sp.get()));
3386   if (!process_sp || process_sp->m_debugserver_pid != debugserver_pid)
3387     return handled;
3388
3389   // Sleep for a half a second to make sure our inferior process has
3390   // time to set its exit status before we set it incorrectly when
3391   // both the debugserver and the inferior process shut down.
3392   usleep(500000);
3393   // If our process hasn't yet exited, debugserver might have died.
3394   // If the process did exit, then we are reaping it.
3395   const StateType state = process_sp->GetState();
3396
3397   if (state != eStateInvalid && state != eStateUnloaded &&
3398       state != eStateExited && state != eStateDetached) {
3399     char error_str[1024];
3400     if (signo) {
3401       const char *signal_cstr =
3402           process_sp->GetUnixSignals()->GetSignalAsCString(signo);
3403       if (signal_cstr)
3404         ::snprintf(error_str, sizeof(error_str),
3405                    DEBUGSERVER_BASENAME " died with signal %s", signal_cstr);
3406       else
3407         ::snprintf(error_str, sizeof(error_str),
3408                    DEBUGSERVER_BASENAME " died with signal %i", signo);
3409     } else {
3410       ::snprintf(error_str, sizeof(error_str),
3411                  DEBUGSERVER_BASENAME " died with an exit status of 0x%8.8x",
3412                  exit_status);
3413     }
3414
3415     process_sp->SetExitStatus(-1, error_str);
3416   }
3417   // Debugserver has exited we need to let our ProcessGDBRemote
3418   // know that it no longer has a debugserver instance
3419   process_sp->m_debugserver_pid = LLDB_INVALID_PROCESS_ID;
3420   return handled;
3421 }
3422
3423 void ProcessGDBRemote::KillDebugserverProcess() {
3424   m_gdb_comm.Disconnect();
3425   if (m_debugserver_pid != LLDB_INVALID_PROCESS_ID) {
3426     Host::Kill(m_debugserver_pid, SIGINT);
3427     m_debugserver_pid = LLDB_INVALID_PROCESS_ID;
3428   }
3429 }
3430
3431 void ProcessGDBRemote::Initialize() {
3432   static llvm::once_flag g_once_flag;
3433
3434   llvm::call_once(g_once_flag, []() {
3435     PluginManager::RegisterPlugin(GetPluginNameStatic(),
3436                                   GetPluginDescriptionStatic(), CreateInstance,
3437                                   DebuggerInitialize);
3438   });
3439 }
3440
3441 void ProcessGDBRemote::DebuggerInitialize(Debugger &debugger) {
3442   if (!PluginManager::GetSettingForProcessPlugin(
3443           debugger, PluginProperties::GetSettingName())) {
3444     const bool is_global_setting = true;
3445     PluginManager::CreateSettingForProcessPlugin(
3446         debugger, GetGlobalPluginProperties()->GetValueProperties(),
3447         ConstString("Properties for the gdb-remote process plug-in."),
3448         is_global_setting);
3449   }
3450 }
3451
3452 bool ProcessGDBRemote::StartAsyncThread() {
3453   Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
3454
3455   if (log)
3456     log->Printf("ProcessGDBRemote::%s ()", __FUNCTION__);
3457
3458   std::lock_guard<std::recursive_mutex> guard(m_async_thread_state_mutex);
3459   if (!m_async_thread.IsJoinable()) {
3460     // Create a thread that watches our internal state and controls which
3461     // events make it to clients (into the DCProcess event queue).
3462
3463     m_async_thread =
3464         ThreadLauncher::LaunchThread("<lldb.process.gdb-remote.async>",
3465                                      ProcessGDBRemote::AsyncThread, this, NULL);
3466   } else if (log)
3467     log->Printf("ProcessGDBRemote::%s () - Called when Async thread was "
3468                 "already running.",
3469                 __FUNCTION__);
3470
3471   return m_async_thread.IsJoinable();
3472 }
3473
3474 void ProcessGDBRemote::StopAsyncThread() {
3475   Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
3476
3477   if (log)
3478     log->Printf("ProcessGDBRemote::%s ()", __FUNCTION__);
3479
3480   std::lock_guard<std::recursive_mutex> guard(m_async_thread_state_mutex);
3481   if (m_async_thread.IsJoinable()) {
3482     m_async_broadcaster.BroadcastEvent(eBroadcastBitAsyncThreadShouldExit);
3483
3484     //  This will shut down the async thread.
3485     m_gdb_comm.Disconnect(); // Disconnect from the debug server.
3486
3487     // Stop the stdio thread
3488     m_async_thread.Join(nullptr);
3489     m_async_thread.Reset();
3490   } else if (log)
3491     log->Printf(
3492         "ProcessGDBRemote::%s () - Called when Async thread was not running.",
3493         __FUNCTION__);
3494 }
3495
3496 bool ProcessGDBRemote::HandleNotifyPacket(StringExtractorGDBRemote &packet) {
3497   // get the packet at a string
3498   const std::string &pkt = packet.GetStringRef();
3499   // skip %stop:
3500   StringExtractorGDBRemote stop_info(pkt.c_str() + 5);
3501
3502   // pass as a thread stop info packet
3503   SetLastStopPacket(stop_info);
3504
3505   // check for more stop reasons
3506   HandleStopReplySequence();
3507
3508   // if the process is stopped then we need to fake a resume
3509   // so that we can stop properly with the new break. This
3510   // is possible due to SetPrivateState() broadcasting the
3511   // state change as a side effect.
3512   if (GetPrivateState() == lldb::StateType::eStateStopped) {
3513     SetPrivateState(lldb::StateType::eStateRunning);
3514   }
3515
3516   // since we have some stopped packets we can halt the process
3517   SetPrivateState(lldb::StateType::eStateStopped);
3518
3519   return true;
3520 }
3521
3522 thread_result_t ProcessGDBRemote::AsyncThread(void *arg) {
3523   ProcessGDBRemote *process = (ProcessGDBRemote *)arg;
3524
3525   Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
3526   if (log)
3527     log->Printf("ProcessGDBRemote::%s (arg = %p, pid = %" PRIu64
3528                 ") thread starting...",
3529                 __FUNCTION__, arg, process->GetID());
3530
3531   EventSP event_sp;
3532   bool done = false;
3533   while (!done) {
3534     if (log)
3535       log->Printf("ProcessGDBRemote::%s (arg = %p, pid = %" PRIu64
3536                   ") listener.WaitForEvent (NULL, event_sp)...",
3537                   __FUNCTION__, arg, process->GetID());
3538     if (process->m_async_listener_sp->GetEvent(event_sp, llvm::None)) {
3539       const uint32_t event_type = event_sp->GetType();
3540       if (event_sp->BroadcasterIs(&process->m_async_broadcaster)) {
3541         if (log)
3542           log->Printf("ProcessGDBRemote::%s (arg = %p, pid = %" PRIu64
3543                       ") Got an event of type: %d...",
3544                       __FUNCTION__, arg, process->GetID(), event_type);
3545
3546         switch (event_type) {
3547         case eBroadcastBitAsyncContinue: {
3548           const EventDataBytes *continue_packet =
3549               EventDataBytes::GetEventDataFromEvent(event_sp.get());
3550
3551           if (continue_packet) {
3552             const char *continue_cstr =
3553                 (const char *)continue_packet->GetBytes();
3554             const size_t continue_cstr_len = continue_packet->GetByteSize();
3555             if (log)
3556               log->Printf("ProcessGDBRemote::%s (arg = %p, pid = %" PRIu64
3557                           ") got eBroadcastBitAsyncContinue: %s",
3558                           __FUNCTION__, arg, process->GetID(), continue_cstr);
3559
3560             if (::strstr(continue_cstr, "vAttach") == NULL)
3561               process->SetPrivateState(eStateRunning);
3562             StringExtractorGDBRemote response;
3563
3564             // If in Non-Stop-Mode
3565             if (process->GetTarget().GetNonStopModeEnabled()) {
3566               // send the vCont packet
3567               if (!process->GetGDBRemote().SendvContPacket(
3568                       llvm::StringRef(continue_cstr, continue_cstr_len),
3569                       response)) {
3570                 // Something went wrong
3571                 done = true;
3572                 break;
3573               }
3574             }
3575             // If in All-Stop-Mode
3576             else {
3577               StateType stop_state =
3578                   process->GetGDBRemote().SendContinuePacketAndWaitForResponse(
3579                       *process, *process->GetUnixSignals(),
3580                       llvm::StringRef(continue_cstr, continue_cstr_len),
3581                       response);
3582
3583               // We need to immediately clear the thread ID list so we are sure
3584               // to get a valid list of threads.
3585               // The thread ID list might be contained within the "response", or
3586               // the stop reply packet that
3587               // caused the stop. So clear it now before we give the stop reply
3588               // packet to the process
3589               // using the process->SetLastStopPacket()...
3590               process->ClearThreadIDList();
3591
3592               switch (stop_state) {
3593               case eStateStopped:
3594               case eStateCrashed:
3595               case eStateSuspended:
3596                 process->SetLastStopPacket(response);
3597                 process->SetPrivateState(stop_state);
3598                 break;
3599
3600               case eStateExited: {
3601                 process->SetLastStopPacket(response);
3602                 process->ClearThreadIDList();
3603                 response.SetFilePos(1);
3604
3605                 int exit_status = response.GetHexU8();
3606                 std::string desc_string;
3607                 if (response.GetBytesLeft() > 0 &&
3608                     response.GetChar('-') == ';') {
3609                   llvm::StringRef desc_str;
3610                   llvm::StringRef desc_token;
3611                   while (response.GetNameColonValue(desc_token, desc_str)) {
3612                     if (desc_token != "description")
3613                       continue;
3614                     StringExtractor extractor(desc_str);
3615                     extractor.GetHexByteString(desc_string);
3616                   }
3617                 }
3618                 process->SetExitStatus(exit_status, desc_string.c_str());
3619                 done = true;
3620                 break;
3621               }
3622               case eStateInvalid: {
3623                 // Check to see if we were trying to attach and if we got back
3624                 // the "E87" error code from debugserver -- this indicates that
3625                 // the process is not debuggable.  Return a slightly more
3626                 // helpful
3627                 // error message about why the attach failed.
3628                 if (::strstr(continue_cstr, "vAttach") != NULL &&
3629                     response.GetError() == 0x87) {
3630                   process->SetExitStatus(-1, "cannot attach to process due to "
3631                                              "System Integrity Protection");
3632                 }
3633                 // E01 code from vAttach means that the attach failed
3634                 if (::strstr(continue_cstr, "vAttach") != NULL &&
3635                     response.GetError() == 0x1) {
3636                   process->SetExitStatus(-1, "unable to attach");
3637                 } else {
3638                   process->SetExitStatus(-1, "lost connection");
3639                 }
3640                 break;
3641               }
3642
3643               default:
3644                 process->SetPrivateState(stop_state);
3645                 break;
3646               } // switch(stop_state)
3647             }   // else // if in All-stop-mode
3648           }     // if (continue_packet)
3649         }       // case eBroadcastBitAysncContinue
3650         break;
3651
3652         case eBroadcastBitAsyncThreadShouldExit:
3653           if (log)
3654             log->Printf("ProcessGDBRemote::%s (arg = %p, pid = %" PRIu64
3655                         ") got eBroadcastBitAsyncThreadShouldExit...",
3656                         __FUNCTION__, arg, process->GetID());
3657           done = true;
3658           break;
3659
3660         default:
3661           if (log)
3662             log->Printf("ProcessGDBRemote::%s (arg = %p, pid = %" PRIu64
3663                         ") got unknown event 0x%8.8x",
3664                         __FUNCTION__, arg, process->GetID(), event_type);
3665           done = true;
3666           break;
3667         }
3668       } else if (event_sp->BroadcasterIs(&process->m_gdb_comm)) {
3669         switch (event_type) {
3670         case Communication::eBroadcastBitReadThreadDidExit:
3671           process->SetExitStatus(-1, "lost connection");
3672           done = true;
3673           break;
3674
3675         case GDBRemoteCommunication::eBroadcastBitGdbReadThreadGotNotify: {
3676           lldb_private::Event *event = event_sp.get();
3677           const EventDataBytes *continue_packet =
3678               EventDataBytes::GetEventDataFromEvent(event);
3679           StringExtractorGDBRemote notify(
3680               (const char *)continue_packet->GetBytes());
3681           // Hand this over to the process to handle
3682           process->HandleNotifyPacket(notify);
3683           break;
3684         }
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       }
3695     } else {
3696       if (log)
3697         log->Printf("ProcessGDBRemote::%s (arg = %p, pid = %" PRIu64
3698                     ") listener.WaitForEvent (NULL, event_sp) => false",
3699                     __FUNCTION__, arg, process->GetID());
3700       done = true;
3701     }
3702   }
3703
3704   if (log)
3705     log->Printf("ProcessGDBRemote::%s (arg = %p, pid = %" PRIu64
3706                 ") thread exiting...",
3707                 __FUNCTION__, arg, process->GetID());
3708
3709   return NULL;
3710 }
3711
3712 // uint32_t
3713 // ProcessGDBRemote::ListProcessesMatchingName (const char *name, StringList
3714 // &matches, std::vector<lldb::pid_t> &pids)
3715 //{
3716 //    // If we are planning to launch the debugserver remotely, then we need to
3717 //    fire up a debugserver
3718 //    // process and ask it for the list of processes. But if we are local, we
3719 //    can let the Host do it.
3720 //    if (m_local_debugserver)
3721 //    {
3722 //        return Host::ListProcessesMatchingName (name, matches, pids);
3723 //    }
3724 //    else
3725 //    {
3726 //        // FIXME: Implement talking to the remote debugserver.
3727 //        return 0;
3728 //    }
3729 //
3730 //}
3731 //
3732 bool ProcessGDBRemote::NewThreadNotifyBreakpointHit(
3733     void *baton, StoppointCallbackContext *context, lldb::user_id_t break_id,
3734     lldb::user_id_t break_loc_id) {
3735   // I don't think I have to do anything here, just make sure I notice the new
3736   // thread when it starts to
3737   // run so I can stop it if that's what I want to do.
3738   Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_STEP));
3739   if (log)
3740     log->Printf("Hit New Thread Notification breakpoint.");
3741   return false;
3742 }
3743
3744 Error ProcessGDBRemote::UpdateAutomaticSignalFiltering() {
3745   Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
3746   LLDB_LOG(log, "Check if need to update ignored signals");
3747
3748   // QPassSignals package is not supported by the server,
3749   // there is no way we can ignore any signals on server side.
3750   if (!m_gdb_comm.GetQPassSignalsSupported())
3751     return Error();
3752
3753   // No signals, nothing to send.
3754   if (m_unix_signals_sp == nullptr)
3755     return Error();
3756
3757   // Signals' version hasn't changed, no need to send anything.
3758   uint64_t new_signals_version = m_unix_signals_sp->GetVersion();
3759   if (new_signals_version == m_last_signals_version) {
3760     LLDB_LOG(log, "Signals' version hasn't changed. version={0}",
3761              m_last_signals_version);
3762     return Error();
3763   }
3764
3765   auto signals_to_ignore =
3766       m_unix_signals_sp->GetFilteredSignals(false, false, false);
3767   Error error = m_gdb_comm.SendSignalsToIgnore(signals_to_ignore);
3768
3769   LLDB_LOG(log,
3770            "Signals' version changed. old version={0}, new version={1}, "
3771            "signals ignored={2}, update result={3}",
3772            m_last_signals_version, new_signals_version,
3773            signals_to_ignore.size(), error);
3774
3775   if (error.Success())
3776     m_last_signals_version = new_signals_version;
3777
3778   return error;
3779 }
3780
3781 bool ProcessGDBRemote::StartNoticingNewThreads() {
3782   Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_STEP));
3783   if (m_thread_create_bp_sp) {
3784     if (log && log->GetVerbose())
3785       log->Printf("Enabled noticing new thread breakpoint.");
3786     m_thread_create_bp_sp->SetEnabled(true);
3787   } else {
3788     PlatformSP platform_sp(GetTarget().GetPlatform());
3789     if (platform_sp) {
3790       m_thread_create_bp_sp =
3791           platform_sp->SetThreadCreationBreakpoint(GetTarget());
3792       if (m_thread_create_bp_sp) {
3793         if (log && log->GetVerbose())
3794           log->Printf(
3795               "Successfully created new thread notification breakpoint %i",
3796               m_thread_create_bp_sp->GetID());
3797         m_thread_create_bp_sp->SetCallback(
3798             ProcessGDBRemote::NewThreadNotifyBreakpointHit, this, true);
3799       } else {
3800         if (log)
3801           log->Printf("Failed to create new thread notification breakpoint.");
3802       }
3803     }
3804   }
3805   return m_thread_create_bp_sp.get() != NULL;
3806 }
3807
3808 bool ProcessGDBRemote::StopNoticingNewThreads() {
3809   Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_STEP));
3810   if (log && log->GetVerbose())
3811     log->Printf("Disabling new thread notification breakpoint.");
3812
3813   if (m_thread_create_bp_sp)
3814     m_thread_create_bp_sp->SetEnabled(false);
3815
3816   return true;
3817 }
3818
3819 DynamicLoader *ProcessGDBRemote::GetDynamicLoader() {
3820   if (m_dyld_ap.get() == NULL)
3821     m_dyld_ap.reset(DynamicLoader::FindPlugin(this, NULL));
3822   return m_dyld_ap.get();
3823 }
3824
3825 Error ProcessGDBRemote::SendEventData(const char *data) {
3826   int return_value;
3827   bool was_supported;
3828
3829   Error error;
3830
3831   return_value = m_gdb_comm.SendLaunchEventDataPacket(data, &was_supported);
3832   if (return_value != 0) {
3833     if (!was_supported)
3834       error.SetErrorString("Sending events is not supported for this process.");
3835     else
3836       error.SetErrorStringWithFormat("Error sending event data: %d.",
3837                                      return_value);
3838   }
3839   return error;
3840 }
3841
3842 const DataBufferSP ProcessGDBRemote::GetAuxvData() {
3843   DataBufferSP buf;
3844   if (m_gdb_comm.GetQXferAuxvReadSupported()) {
3845     std::string response_string;
3846     if (m_gdb_comm.SendPacketsAndConcatenateResponses("qXfer:auxv:read::",
3847                                                       response_string) ==
3848         GDBRemoteCommunication::PacketResult::Success)
3849       buf.reset(new DataBufferHeap(response_string.c_str(),
3850                                    response_string.length()));
3851   }
3852   return buf;
3853 }
3854
3855 StructuredData::ObjectSP
3856 ProcessGDBRemote::GetExtendedInfoForThread(lldb::tid_t tid) {
3857   StructuredData::ObjectSP object_sp;
3858
3859   if (m_gdb_comm.GetThreadExtendedInfoSupported()) {
3860     StructuredData::ObjectSP args_dict(new StructuredData::Dictionary());
3861     SystemRuntime *runtime = GetSystemRuntime();
3862     if (runtime) {
3863       runtime->AddThreadExtendedInfoPacketHints(args_dict);
3864     }
3865     args_dict->GetAsDictionary()->AddIntegerItem("thread", tid);
3866
3867     StreamString packet;
3868     packet << "jThreadExtendedInfo:";
3869     args_dict->Dump(packet, false);
3870
3871     // FIXME the final character of a JSON dictionary, '}', is the escape
3872     // character in gdb-remote binary mode.  lldb currently doesn't escape
3873     // these characters in its packet output -- so we add the quoted version
3874     // of the } character here manually in case we talk to a debugserver which
3875     // un-escapes the characters at packet read time.
3876     packet << (char)(0x7d ^ 0x20);
3877
3878     StringExtractorGDBRemote response;
3879     response.SetResponseValidatorToJSON();
3880     if (m_gdb_comm.SendPacketAndWaitForResponse(packet.GetString(), response,
3881                                                 false) ==
3882         GDBRemoteCommunication::PacketResult::Success) {
3883       StringExtractorGDBRemote::ResponseType response_type =
3884           response.GetResponseType();
3885       if (response_type == StringExtractorGDBRemote::eResponse) {
3886         if (!response.Empty()) {
3887           object_sp = StructuredData::ParseJSON(response.GetStringRef());
3888         }
3889       }
3890     }
3891   }
3892   return object_sp;
3893 }
3894
3895 StructuredData::ObjectSP ProcessGDBRemote::GetLoadedDynamicLibrariesInfos(
3896     lldb::addr_t image_list_address, lldb::addr_t image_count) {
3897
3898   StructuredData::ObjectSP args_dict(new StructuredData::Dictionary());
3899   args_dict->GetAsDictionary()->AddIntegerItem("image_list_address",
3900                                                image_list_address);
3901   args_dict->GetAsDictionary()->AddIntegerItem("image_count", image_count);
3902
3903   return GetLoadedDynamicLibrariesInfos_sender(args_dict);
3904 }
3905
3906 StructuredData::ObjectSP ProcessGDBRemote::GetLoadedDynamicLibrariesInfos() {
3907   StructuredData::ObjectSP args_dict(new StructuredData::Dictionary());
3908
3909   args_dict->GetAsDictionary()->AddBooleanItem("fetch_all_solibs", true);
3910
3911   return GetLoadedDynamicLibrariesInfos_sender(args_dict);
3912 }
3913
3914 StructuredData::ObjectSP ProcessGDBRemote::GetLoadedDynamicLibrariesInfos(
3915     const std::vector<lldb::addr_t> &load_addresses) {
3916   StructuredData::ObjectSP args_dict(new StructuredData::Dictionary());
3917   StructuredData::ArraySP addresses(new StructuredData::Array);
3918
3919   for (auto addr : load_addresses) {
3920     StructuredData::ObjectSP addr_sp(new StructuredData::Integer(addr));
3921     addresses->AddItem(addr_sp);
3922   }
3923
3924   args_dict->GetAsDictionary()->AddItem("solib_addresses", addresses);
3925
3926   return GetLoadedDynamicLibrariesInfos_sender(args_dict);
3927 }
3928
3929 StructuredData::ObjectSP
3930 ProcessGDBRemote::GetLoadedDynamicLibrariesInfos_sender(
3931     StructuredData::ObjectSP args_dict) {
3932   StructuredData::ObjectSP object_sp;
3933
3934   if (m_gdb_comm.GetLoadedDynamicLibrariesInfosSupported()) {
3935     // Scope for the scoped timeout object
3936     GDBRemoteCommunication::ScopedTimeout timeout(m_gdb_comm,
3937                                                   std::chrono::seconds(10));
3938
3939     StreamString packet;
3940     packet << "jGetLoadedDynamicLibrariesInfos:";
3941     args_dict->Dump(packet, false);
3942
3943     // FIXME the final character of a JSON dictionary, '}', is the escape
3944     // character in gdb-remote binary mode.  lldb currently doesn't escape
3945     // these characters in its packet output -- so we add the quoted version
3946     // of the } character here manually in case we talk to a debugserver which
3947     // un-escapes the characters at packet read time.
3948     packet << (char)(0x7d ^ 0x20);
3949
3950     StringExtractorGDBRemote response;
3951     response.SetResponseValidatorToJSON();
3952     if (m_gdb_comm.SendPacketAndWaitForResponse(packet.GetString(), response,
3953                                                 false) ==
3954         GDBRemoteCommunication::PacketResult::Success) {
3955       StringExtractorGDBRemote::ResponseType response_type =
3956           response.GetResponseType();
3957       if (response_type == StringExtractorGDBRemote::eResponse) {
3958         if (!response.Empty()) {
3959           object_sp = StructuredData::ParseJSON(response.GetStringRef());
3960         }
3961       }
3962     }
3963   }
3964   return object_sp;
3965 }
3966
3967 StructuredData::ObjectSP ProcessGDBRemote::GetSharedCacheInfo() {
3968   StructuredData::ObjectSP object_sp;
3969   StructuredData::ObjectSP args_dict(new StructuredData::Dictionary());
3970
3971   if (m_gdb_comm.GetSharedCacheInfoSupported()) {
3972     StreamString packet;
3973     packet << "jGetSharedCacheInfo:";
3974     args_dict->Dump(packet, false);
3975
3976     // FIXME the final character of a JSON dictionary, '}', is the escape
3977     // character in gdb-remote binary mode.  lldb currently doesn't escape
3978     // these characters in its packet output -- so we add the quoted version
3979     // of the } character here manually in case we talk to a debugserver which
3980     // un-escapes the characters at packet read time.
3981     packet << (char)(0x7d ^ 0x20);
3982
3983     StringExtractorGDBRemote response;
3984     response.SetResponseValidatorToJSON();
3985     if (m_gdb_comm.SendPacketAndWaitForResponse(packet.GetString(), response,
3986                                                 false) ==
3987         GDBRemoteCommunication::PacketResult::Success) {
3988       StringExtractorGDBRemote::ResponseType response_type =
3989           response.GetResponseType();
3990       if (response_type == StringExtractorGDBRemote::eResponse) {
3991         if (!response.Empty()) {
3992           object_sp = StructuredData::ParseJSON(response.GetStringRef());
3993         }
3994       }
3995     }
3996   }
3997   return object_sp;
3998 }
3999
4000 Error ProcessGDBRemote::ConfigureStructuredData(
4001     const ConstString &type_name, const StructuredData::ObjectSP &config_sp) {
4002   return m_gdb_comm.ConfigureRemoteStructuredData(type_name, config_sp);
4003 }
4004
4005 // Establish the largest memory read/write payloads we should use.
4006 // If the remote stub has a max packet size, stay under that size.
4007 //
4008 // If the remote stub's max packet size is crazy large, use a
4009 // reasonable largeish default.
4010 //
4011 // If the remote stub doesn't advertise a max packet size, use a
4012 // conservative default.
4013
4014 void ProcessGDBRemote::GetMaxMemorySize() {
4015   const uint64_t reasonable_largeish_default = 128 * 1024;
4016   const uint64_t conservative_default = 512;
4017
4018   if (m_max_memory_size == 0) {
4019     uint64_t stub_max_size = m_gdb_comm.GetRemoteMaxPacketSize();
4020     if (stub_max_size != UINT64_MAX && stub_max_size != 0) {
4021       // Save the stub's claimed maximum packet size
4022       m_remote_stub_max_memory_size = stub_max_size;
4023
4024       // Even if the stub says it can support ginormous packets,
4025       // don't exceed our reasonable largeish default packet size.
4026       if (stub_max_size > reasonable_largeish_default) {
4027         stub_max_size = reasonable_largeish_default;
4028       }
4029
4030       // Memory packet have other overheads too like Maddr,size:#NN
4031       // Instead of calculating the bytes taken by size and addr every
4032       // time, we take a maximum guess here.
4033       if (stub_max_size > 70)
4034         stub_max_size -= 32 + 32 + 6;
4035       else {
4036         // In unlikely scenario that max packet size is less then 70, we will
4037         // hope that data being written is small enough to fit.
4038         Log *log(ProcessGDBRemoteLog::GetLogIfAnyCategoryIsSet(
4039             GDBR_LOG_COMM | GDBR_LOG_MEMORY));
4040         if (log)
4041           log->Warning("Packet size is too small. "
4042                        "LLDB may face problems while writing memory");
4043       }
4044
4045       m_max_memory_size = stub_max_size;
4046     } else {
4047       m_max_memory_size = conservative_default;
4048     }
4049   }
4050 }
4051
4052 void ProcessGDBRemote::SetUserSpecifiedMaxMemoryTransferSize(
4053     uint64_t user_specified_max) {
4054   if (user_specified_max != 0) {
4055     GetMaxMemorySize();
4056
4057     if (m_remote_stub_max_memory_size != 0) {
4058       if (m_remote_stub_max_memory_size < user_specified_max) {
4059         m_max_memory_size = m_remote_stub_max_memory_size; // user specified a
4060                                                            // packet size too
4061                                                            // big, go as big
4062         // as the remote stub says we can go.
4063       } else {
4064         m_max_memory_size = user_specified_max; // user's packet size is good
4065       }
4066     } else {
4067       m_max_memory_size =
4068           user_specified_max; // user's packet size is probably fine
4069     }
4070   }
4071 }
4072
4073 bool ProcessGDBRemote::GetModuleSpec(const FileSpec &module_file_spec,
4074                                      const ArchSpec &arch,
4075                                      ModuleSpec &module_spec) {
4076   Log *log = GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PLATFORM);
4077
4078   const ModuleCacheKey key(module_file_spec.GetPath(),
4079                            arch.GetTriple().getTriple());
4080   auto cached = m_cached_module_specs.find(key);
4081   if (cached != m_cached_module_specs.end()) {
4082     module_spec = cached->second;
4083     return bool(module_spec);
4084   }
4085
4086   if (!m_gdb_comm.GetModuleInfo(module_file_spec, arch, module_spec)) {
4087     if (log)
4088       log->Printf("ProcessGDBRemote::%s - failed to get module info for %s:%s",
4089                   __FUNCTION__, module_file_spec.GetPath().c_str(),
4090                   arch.GetTriple().getTriple().c_str());
4091     return false;
4092   }
4093
4094   if (log) {
4095     StreamString stream;
4096     module_spec.Dump(stream);
4097     log->Printf("ProcessGDBRemote::%s - got module info for (%s:%s) : %s",
4098                 __FUNCTION__, module_file_spec.GetPath().c_str(),
4099                 arch.GetTriple().getTriple().c_str(), stream.GetData());
4100   }
4101
4102   m_cached_module_specs[key] = module_spec;
4103   return true;
4104 }
4105
4106 void ProcessGDBRemote::PrefetchModuleSpecs(
4107     llvm::ArrayRef<FileSpec> module_file_specs, const llvm::Triple &triple) {
4108   auto module_specs = m_gdb_comm.GetModulesInfo(module_file_specs, triple);
4109   if (module_specs) {
4110     for (const FileSpec &spec : module_file_specs)
4111       m_cached_module_specs[ModuleCacheKey(spec.GetPath(),
4112                                            triple.getTriple())] = ModuleSpec();
4113     for (const ModuleSpec &spec : *module_specs)
4114       m_cached_module_specs[ModuleCacheKey(spec.GetFileSpec().GetPath(),
4115                                            triple.getTriple())] = spec;
4116   }
4117 }
4118
4119 bool ProcessGDBRemote::GetHostOSVersion(uint32_t &major, uint32_t &minor,
4120                                         uint32_t &update) {
4121   if (m_gdb_comm.GetOSVersion(major, minor, update))
4122     return true;
4123   // We failed to get the host OS version, defer to the base
4124   // implementation to correctly invalidate the arguments.
4125   return Process::GetHostOSVersion(major, minor, update);
4126 }
4127
4128 namespace {
4129
4130 typedef std::vector<std::string> stringVec;
4131
4132 typedef std::vector<struct GdbServerRegisterInfo> GDBServerRegisterVec;
4133 struct RegisterSetInfo {
4134   ConstString name;
4135 };
4136
4137 typedef std::map<uint32_t, RegisterSetInfo> RegisterSetMap;
4138
4139 struct GdbServerTargetInfo {
4140   std::string arch;
4141   std::string osabi;
4142   stringVec includes;
4143   RegisterSetMap reg_set_map;
4144   XMLNode feature_node;
4145 };
4146
4147 bool ParseRegisters(XMLNode feature_node, GdbServerTargetInfo &target_info,
4148                     GDBRemoteDynamicRegisterInfo &dyn_reg_info, ABISP abi_sp,
4149                     uint32_t &cur_reg_num, uint32_t &reg_offset) {
4150   if (!feature_node)
4151     return false;
4152
4153   feature_node.ForEachChildElementWithName(
4154       "reg", [&target_info, &dyn_reg_info, &cur_reg_num, &reg_offset,
4155               &abi_sp](const XMLNode &reg_node) -> bool {
4156         std::string gdb_group;
4157         std::string gdb_type;
4158         ConstString reg_name;
4159         ConstString alt_name;
4160         ConstString set_name;
4161         std::vector<uint32_t> value_regs;
4162         std::vector<uint32_t> invalidate_regs;
4163         std::vector<uint8_t> dwarf_opcode_bytes;
4164         bool encoding_set = false;
4165         bool format_set = false;
4166         RegisterInfo reg_info = {
4167             NULL,          // Name
4168             NULL,          // Alt name
4169             0,             // byte size
4170             reg_offset,    // offset
4171             eEncodingUint, // encoding
4172             eFormatHex,    // format
4173             {
4174                 LLDB_INVALID_REGNUM, // eh_frame reg num
4175                 LLDB_INVALID_REGNUM, // DWARF reg num
4176                 LLDB_INVALID_REGNUM, // generic reg num
4177                 cur_reg_num,         // process plugin reg num
4178                 cur_reg_num          // native register number
4179             },
4180             NULL,
4181             NULL,
4182             NULL, // Dwarf Expression opcode bytes pointer
4183             0     // Dwarf Expression opcode bytes length
4184         };
4185
4186         reg_node.ForEachAttribute([&target_info, &gdb_group, &gdb_type,
4187                                    &reg_name, &alt_name, &set_name, &value_regs,
4188                                    &invalidate_regs, &encoding_set, &format_set,
4189                                    &reg_info, &reg_offset, &dwarf_opcode_bytes](
4190                                       const llvm::StringRef &name,
4191                                       const llvm::StringRef &value) -> bool {
4192           if (name == "name") {
4193             reg_name.SetString(value);
4194           } else if (name == "bitsize") {
4195             reg_info.byte_size =
4196                 StringConvert::ToUInt32(value.data(), 0, 0) / CHAR_BIT;
4197           } else if (name == "type") {
4198             gdb_type = value.str();
4199           } else if (name == "group") {
4200             gdb_group = value.str();
4201           } else if (name == "regnum") {
4202             const uint32_t regnum =
4203                 StringConvert::ToUInt32(value.data(), LLDB_INVALID_REGNUM, 0);
4204             if (regnum != LLDB_INVALID_REGNUM) {
4205               reg_info.kinds[eRegisterKindProcessPlugin] = regnum;
4206             }
4207           } else if (name == "offset") {
4208             reg_offset = StringConvert::ToUInt32(value.data(), UINT32_MAX, 0);
4209           } else if (name == "altname") {
4210             alt_name.SetString(value);
4211           } else if (name == "encoding") {
4212             encoding_set = true;
4213             reg_info.encoding = Args::StringToEncoding(value, eEncodingUint);
4214           } else if (name == "format") {
4215             format_set = true;
4216             Format format = eFormatInvalid;
4217             if (Args::StringToFormat(value.data(), format, NULL).Success())
4218               reg_info.format = format;
4219             else if (value == "vector-sint8")
4220               reg_info.format = eFormatVectorOfSInt8;
4221             else if (value == "vector-uint8")
4222               reg_info.format = eFormatVectorOfUInt8;
4223             else if (value == "vector-sint16")
4224               reg_info.format = eFormatVectorOfSInt16;
4225             else if (value == "vector-uint16")
4226               reg_info.format = eFormatVectorOfUInt16;
4227             else if (value == "vector-sint32")
4228               reg_info.format = eFormatVectorOfSInt32;
4229             else if (value == "vector-uint32")
4230               reg_info.format = eFormatVectorOfUInt32;
4231             else if (value == "vector-float32")
4232               reg_info.format = eFormatVectorOfFloat32;
4233             else if (value == "vector-uint64")
4234               reg_info.format = eFormatVectorOfUInt64;
4235             else if (value == "vector-uint128")
4236               reg_info.format = eFormatVectorOfUInt128;
4237           } else if (name == "group_id") {
4238             const uint32_t set_id =
4239                 StringConvert::ToUInt32(value.data(), UINT32_MAX, 0);
4240             RegisterSetMap::const_iterator pos =
4241                 target_info.reg_set_map.find(set_id);
4242             if (pos != target_info.reg_set_map.end())
4243               set_name = pos->second.name;
4244           } else if (name == "gcc_regnum" || name == "ehframe_regnum") {
4245             reg_info.kinds[eRegisterKindEHFrame] =
4246                 StringConvert::ToUInt32(value.data(), LLDB_INVALID_REGNUM, 0);
4247           } else if (name == "dwarf_regnum") {
4248             reg_info.kinds[eRegisterKindDWARF] =
4249                 StringConvert::ToUInt32(value.data(), LLDB_INVALID_REGNUM, 0);
4250           } else if (name == "generic") {
4251             reg_info.kinds[eRegisterKindGeneric] =
4252                 Args::StringToGenericRegister(value);
4253           } else if (name == "value_regnums") {
4254             SplitCommaSeparatedRegisterNumberString(value, value_regs, 0);
4255           } else if (name == "invalidate_regnums") {
4256             SplitCommaSeparatedRegisterNumberString(value, invalidate_regs, 0);
4257           } else if (name == "dynamic_size_dwarf_expr_bytes") {
4258             StringExtractor opcode_extractor;
4259             std::string opcode_string = value.str();
4260             size_t dwarf_opcode_len = opcode_string.length() / 2;
4261             assert(dwarf_opcode_len > 0);
4262
4263             dwarf_opcode_bytes.resize(dwarf_opcode_len);
4264             reg_info.dynamic_size_dwarf_len = dwarf_opcode_len;
4265             opcode_extractor.GetStringRef().swap(opcode_string);
4266             uint32_t ret_val =
4267                 opcode_extractor.GetHexBytesAvail(dwarf_opcode_bytes);
4268             assert(dwarf_opcode_len == ret_val);
4269             UNUSED_IF_ASSERT_DISABLED(ret_val);
4270             reg_info.dynamic_size_dwarf_expr_bytes = dwarf_opcode_bytes.data();
4271           } else {
4272             printf("unhandled attribute %s = %s\n", name.data(), value.data());
4273           }
4274           return true; // Keep iterating through all attributes
4275         });
4276
4277         if (!gdb_type.empty() && !(encoding_set || format_set)) {
4278           if (gdb_type.find("int") == 0) {
4279             reg_info.format = eFormatHex;
4280             reg_info.encoding = eEncodingUint;
4281           } else if (gdb_type == "data_ptr" || gdb_type == "code_ptr") {
4282             reg_info.format = eFormatAddressInfo;
4283             reg_info.encoding = eEncodingUint;
4284           } else if (gdb_type == "i387_ext" || gdb_type == "float") {
4285             reg_info.format = eFormatFloat;
4286             reg_info.encoding = eEncodingIEEE754;
4287           }
4288         }
4289
4290         // Only update the register set name if we didn't get a "reg_set"
4291         // attribute.
4292         // "set_name" will be empty if we didn't have a "reg_set" attribute.
4293         if (!set_name && !gdb_group.empty())
4294           set_name.SetCString(gdb_group.c_str());
4295
4296         reg_info.byte_offset = reg_offset;
4297         assert(reg_info.byte_size != 0);
4298         reg_offset += reg_info.byte_size;
4299         if (!value_regs.empty()) {
4300           value_regs.push_back(LLDB_INVALID_REGNUM);
4301           reg_info.value_regs = value_regs.data();
4302         }
4303         if (!invalidate_regs.empty()) {
4304           invalidate_regs.push_back(LLDB_INVALID_REGNUM);
4305           reg_info.invalidate_regs = invalidate_regs.data();
4306         }
4307
4308         ++cur_reg_num;
4309         AugmentRegisterInfoViaABI(reg_info, reg_name, abi_sp);
4310         dyn_reg_info.AddRegister(reg_info, reg_name, alt_name, set_name);
4311
4312         return true; // Keep iterating through all "reg" elements
4313       });
4314   return true;
4315 }
4316
4317 } // namespace {}
4318
4319 // query the target of gdb-remote for extended target information
4320 // return:  'true'  on success
4321 //          'false' on failure
4322 bool ProcessGDBRemote::GetGDBServerRegisterInfo(ArchSpec &arch_to_use) {
4323   // Make sure LLDB has an XML parser it can use first
4324   if (!XMLDocument::XMLEnabled())
4325     return false;
4326
4327   // redirect libxml2's error handler since the default prints to stdout
4328
4329   GDBRemoteCommunicationClient &comm = m_gdb_comm;
4330
4331   // check that we have extended feature read support
4332   if (!comm.GetQXferFeaturesReadSupported())
4333     return false;
4334
4335   // request the target xml file
4336   std::string raw;
4337   lldb_private::Error lldberr;
4338   if (!comm.ReadExtFeature(ConstString("features"), ConstString("target.xml"),
4339                            raw, lldberr)) {
4340     return false;
4341   }
4342
4343   XMLDocument xml_document;
4344
4345   if (xml_document.ParseMemory(raw.c_str(), raw.size(), "target.xml")) {
4346     GdbServerTargetInfo target_info;
4347
4348     XMLNode target_node = xml_document.GetRootElement("target");
4349     if (target_node) {
4350       XMLNode feature_node;
4351       target_node.ForEachChildElement([&target_info, &feature_node](
4352                                           const XMLNode &node) -> bool {
4353         llvm::StringRef name = node.GetName();
4354         if (name == "architecture") {
4355           node.GetElementText(target_info.arch);
4356         } else if (name == "osabi") {
4357           node.GetElementText(target_info.osabi);
4358         } else if (name == "xi:include" || name == "include") {
4359           llvm::StringRef href = node.GetAttributeValue("href");
4360           if (!href.empty())
4361             target_info.includes.push_back(href.str());
4362         } else if (name == "feature") {
4363           feature_node = node;
4364         } else if (name == "groups") {
4365           node.ForEachChildElementWithName(
4366               "group", [&target_info](const XMLNode &node) -> bool {
4367                 uint32_t set_id = UINT32_MAX;
4368                 RegisterSetInfo set_info;
4369
4370                 node.ForEachAttribute(
4371                     [&set_id, &set_info](const llvm::StringRef &name,
4372                                          const llvm::StringRef &value) -> bool {
4373                       if (name == "id")
4374                         set_id = StringConvert::ToUInt32(value.data(),
4375                                                          UINT32_MAX, 0);
4376                       if (name == "name")
4377                         set_info.name = ConstString(value);
4378                       return true; // Keep iterating through all attributes
4379                     });
4380
4381                 if (set_id != UINT32_MAX)
4382                   target_info.reg_set_map[set_id] = set_info;
4383                 return true; // Keep iterating through all "group" elements
4384               });
4385         }
4386         return true; // Keep iterating through all children of the target_node
4387       });
4388
4389       // Initialize these outside of ParseRegisters, since they should not be
4390       // reset inside each include feature
4391       uint32_t cur_reg_num = 0;
4392       uint32_t reg_offset = 0;
4393
4394       // Don't use Process::GetABI, this code gets called from DidAttach, and in
4395       // that context we haven't
4396       // set the Target's architecture yet, so the ABI is also potentially
4397       // incorrect.
4398       ABISP abi_to_use_sp = ABI::FindPlugin(arch_to_use);
4399       if (feature_node) {
4400         ParseRegisters(feature_node, target_info, this->m_register_info,
4401                        abi_to_use_sp, cur_reg_num, reg_offset);
4402       }
4403
4404       for (const auto &include : target_info.includes) {
4405         // request register file
4406         std::string xml_data;
4407         if (!comm.ReadExtFeature(ConstString("features"), ConstString(include),
4408                                  xml_data, lldberr))
4409           continue;
4410
4411         XMLDocument include_xml_document;
4412         include_xml_document.ParseMemory(xml_data.data(), xml_data.size(),
4413                                          include.c_str());
4414         XMLNode include_feature_node =
4415             include_xml_document.GetRootElement("feature");
4416         if (include_feature_node) {
4417           ParseRegisters(include_feature_node, target_info,
4418                          this->m_register_info, abi_to_use_sp, cur_reg_num,
4419                          reg_offset);
4420         }
4421       }
4422       this->m_register_info.Finalize(arch_to_use);
4423     }
4424   }
4425
4426   return m_register_info.GetNumRegisters() > 0;
4427 }
4428
4429 Error ProcessGDBRemote::GetLoadedModuleList(LoadedModuleInfoList &list) {
4430   // Make sure LLDB has an XML parser it can use first
4431   if (!XMLDocument::XMLEnabled())
4432     return Error(0, ErrorType::eErrorTypeGeneric);
4433
4434   Log *log = GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS);
4435   if (log)
4436     log->Printf("ProcessGDBRemote::%s", __FUNCTION__);
4437
4438   GDBRemoteCommunicationClient &comm = m_gdb_comm;
4439
4440   // check that we have extended feature read support
4441   if (comm.GetQXferLibrariesSVR4ReadSupported()) {
4442     list.clear();
4443
4444     // request the loaded library list
4445     std::string raw;
4446     lldb_private::Error lldberr;
4447
4448     if (!comm.ReadExtFeature(ConstString("libraries-svr4"), ConstString(""),
4449                              raw, lldberr))
4450       return Error(0, ErrorType::eErrorTypeGeneric);
4451
4452     // parse the xml file in memory
4453     if (log)
4454       log->Printf("parsing: %s", raw.c_str());
4455     XMLDocument doc;
4456
4457     if (!doc.ParseMemory(raw.c_str(), raw.size(), "noname.xml"))
4458       return Error(0, ErrorType::eErrorTypeGeneric);
4459
4460     XMLNode root_element = doc.GetRootElement("library-list-svr4");
4461     if (!root_element)
4462       return Error();
4463
4464     // main link map structure
4465     llvm::StringRef main_lm = root_element.GetAttributeValue("main-lm");
4466     if (!main_lm.empty()) {
4467       list.m_link_map =
4468           StringConvert::ToUInt64(main_lm.data(), LLDB_INVALID_ADDRESS, 0);
4469     }
4470
4471     root_element.ForEachChildElementWithName(
4472         "library", [log, &list](const XMLNode &library) -> bool {
4473
4474           LoadedModuleInfoList::LoadedModuleInfo module;
4475
4476           library.ForEachAttribute(
4477               [&module](const llvm::StringRef &name,
4478                         const llvm::StringRef &value) -> bool {
4479
4480                 if (name == "name")
4481                   module.set_name(value.str());
4482                 else if (name == "lm") {
4483                   // the address of the link_map struct.
4484                   module.set_link_map(StringConvert::ToUInt64(
4485                       value.data(), LLDB_INVALID_ADDRESS, 0));
4486                 } else if (name == "l_addr") {
4487                   // the displacement as read from the field 'l_addr' of the
4488                   // link_map struct.
4489                   module.set_base(StringConvert::ToUInt64(
4490                       value.data(), LLDB_INVALID_ADDRESS, 0));
4491                   // base address is always a displacement, not an absolute
4492                   // value.
4493                   module.set_base_is_offset(true);
4494                 } else if (name == "l_ld") {
4495                   // the memory address of the libraries PT_DYAMIC section.
4496                   module.set_dynamic(StringConvert::ToUInt64(
4497                       value.data(), LLDB_INVALID_ADDRESS, 0));
4498                 }
4499
4500                 return true; // Keep iterating over all properties of "library"
4501               });
4502
4503           if (log) {
4504             std::string name;
4505             lldb::addr_t lm = 0, base = 0, ld = 0;
4506             bool base_is_offset;
4507
4508             module.get_name(name);
4509             module.get_link_map(lm);
4510             module.get_base(base);
4511             module.get_base_is_offset(base_is_offset);
4512             module.get_dynamic(ld);
4513
4514             log->Printf("found (link_map:0x%08" PRIx64 ", base:0x%08" PRIx64
4515                         "[%s], ld:0x%08" PRIx64 ", name:'%s')",
4516                         lm, base, (base_is_offset ? "offset" : "absolute"), ld,
4517                         name.c_str());
4518           }
4519
4520           list.add(module);
4521           return true; // Keep iterating over all "library" elements in the root
4522                        // node
4523         });
4524
4525     if (log)
4526       log->Printf("found %" PRId32 " modules in total",
4527                   (int)list.m_list.size());
4528   } else if (comm.GetQXferLibrariesReadSupported()) {
4529     list.clear();
4530
4531     // request the loaded library list
4532     std::string raw;
4533     lldb_private::Error lldberr;
4534
4535     if (!comm.ReadExtFeature(ConstString("libraries"), ConstString(""), raw,
4536                              lldberr))
4537       return Error(0, ErrorType::eErrorTypeGeneric);
4538
4539     if (log)
4540       log->Printf("parsing: %s", raw.c_str());
4541     XMLDocument doc;
4542
4543     if (!doc.ParseMemory(raw.c_str(), raw.size(), "noname.xml"))
4544       return Error(0, ErrorType::eErrorTypeGeneric);
4545
4546     XMLNode root_element = doc.GetRootElement("library-list");
4547     if (!root_element)
4548       return Error();
4549
4550     root_element.ForEachChildElementWithName(
4551         "library", [log, &list](const XMLNode &library) -> bool {
4552           LoadedModuleInfoList::LoadedModuleInfo module;
4553
4554           llvm::StringRef name = library.GetAttributeValue("name");
4555           module.set_name(name.str());
4556
4557           // The base address of a given library will be the address of its
4558           // first section. Most remotes send only one section for Windows
4559           // targets for example.
4560           const XMLNode &section =
4561               library.FindFirstChildElementWithName("section");
4562           llvm::StringRef address = section.GetAttributeValue("address");
4563           module.set_base(
4564               StringConvert::ToUInt64(address.data(), LLDB_INVALID_ADDRESS, 0));
4565           // These addresses are absolute values.
4566           module.set_base_is_offset(false);
4567
4568           if (log) {
4569             std::string name;
4570             lldb::addr_t base = 0;
4571             bool base_is_offset;
4572             module.get_name(name);
4573             module.get_base(base);
4574             module.get_base_is_offset(base_is_offset);
4575
4576             log->Printf("found (base:0x%08" PRIx64 "[%s], name:'%s')", base,
4577                         (base_is_offset ? "offset" : "absolute"), name.c_str());
4578           }
4579
4580           list.add(module);
4581           return true; // Keep iterating over all "library" elements in the root
4582                        // node
4583         });
4584
4585     if (log)
4586       log->Printf("found %" PRId32 " modules in total",
4587                   (int)list.m_list.size());
4588   } else {
4589     return Error(0, ErrorType::eErrorTypeGeneric);
4590   }
4591
4592   return Error();
4593 }
4594
4595 lldb::ModuleSP ProcessGDBRemote::LoadModuleAtAddress(const FileSpec &file,
4596                                                      lldb::addr_t link_map,
4597                                                      lldb::addr_t base_addr,
4598                                                      bool value_is_offset) {
4599   DynamicLoader *loader = GetDynamicLoader();
4600   if (!loader)
4601     return nullptr;
4602
4603   return loader->LoadModuleAtAddress(file, link_map, base_addr,
4604                                      value_is_offset);
4605 }
4606
4607 size_t ProcessGDBRemote::LoadModules(LoadedModuleInfoList &module_list) {
4608   using lldb_private::process_gdb_remote::ProcessGDBRemote;
4609
4610   // request a list of loaded libraries from GDBServer
4611   if (GetLoadedModuleList(module_list).Fail())
4612     return 0;
4613
4614   // get a list of all the modules
4615   ModuleList new_modules;
4616
4617   for (LoadedModuleInfoList::LoadedModuleInfo &modInfo : module_list.m_list) {
4618     std::string mod_name;
4619     lldb::addr_t mod_base;
4620     lldb::addr_t link_map;
4621     bool mod_base_is_offset;
4622
4623     bool valid = true;
4624     valid &= modInfo.get_name(mod_name);
4625     valid &= modInfo.get_base(mod_base);
4626     valid &= modInfo.get_base_is_offset(mod_base_is_offset);
4627     if (!valid)
4628       continue;
4629
4630     if (!modInfo.get_link_map(link_map))
4631       link_map = LLDB_INVALID_ADDRESS;
4632
4633     FileSpec file(mod_name, true);
4634     lldb::ModuleSP module_sp =
4635         LoadModuleAtAddress(file, link_map, mod_base, mod_base_is_offset);
4636
4637     if (module_sp.get())
4638       new_modules.Append(module_sp);
4639   }
4640
4641   if (new_modules.GetSize() > 0) {
4642     ModuleList removed_modules;
4643     Target &target = GetTarget();
4644     ModuleList &loaded_modules = m_process->GetTarget().GetImages();
4645
4646     for (size_t i = 0; i < loaded_modules.GetSize(); ++i) {
4647       const lldb::ModuleSP loaded_module = loaded_modules.GetModuleAtIndex(i);
4648
4649       bool found = false;
4650       for (size_t j = 0; j < new_modules.GetSize(); ++j) {
4651         if (new_modules.GetModuleAtIndex(j).get() == loaded_module.get())
4652           found = true;
4653       }
4654
4655       // The main executable will never be included in libraries-svr4, don't
4656       // remove it
4657       if (!found &&
4658           loaded_module.get() != target.GetExecutableModulePointer()) {
4659         removed_modules.Append(loaded_module);
4660       }
4661     }
4662
4663     loaded_modules.Remove(removed_modules);
4664     m_process->GetTarget().ModulesDidUnload(removed_modules, false);
4665
4666     new_modules.ForEach([&target](const lldb::ModuleSP module_sp) -> bool {
4667       lldb_private::ObjectFile *obj = module_sp->GetObjectFile();
4668       if (!obj)
4669         return true;
4670
4671       if (obj->GetType() != ObjectFile::Type::eTypeExecutable)
4672         return true;
4673
4674       lldb::ModuleSP module_copy_sp = module_sp;
4675       target.SetExecutableModule(module_copy_sp, false);
4676       return false;
4677     });
4678
4679     loaded_modules.AppendIfNeeded(new_modules);
4680     m_process->GetTarget().ModulesDidLoad(new_modules);
4681   }
4682
4683   return new_modules.GetSize();
4684 }
4685
4686 size_t ProcessGDBRemote::LoadModules() {
4687   LoadedModuleInfoList module_list;
4688   return LoadModules(module_list);
4689 }
4690
4691 Error ProcessGDBRemote::GetFileLoadAddress(const FileSpec &file,
4692                                            bool &is_loaded,
4693                                            lldb::addr_t &load_addr) {
4694   is_loaded = false;
4695   load_addr = LLDB_INVALID_ADDRESS;
4696
4697   std::string file_path = file.GetPath(false);
4698   if (file_path.empty())
4699     return Error("Empty file name specified");
4700
4701   StreamString packet;
4702   packet.PutCString("qFileLoadAddress:");
4703   packet.PutCStringAsRawHex8(file_path.c_str());
4704
4705   StringExtractorGDBRemote response;
4706   if (m_gdb_comm.SendPacketAndWaitForResponse(packet.GetString(), response,
4707                                               false) !=
4708       GDBRemoteCommunication::PacketResult::Success)
4709     return Error("Sending qFileLoadAddress packet failed");
4710
4711   if (response.IsErrorResponse()) {
4712     if (response.GetError() == 1) {
4713       // The file is not loaded into the inferior
4714       is_loaded = false;
4715       load_addr = LLDB_INVALID_ADDRESS;
4716       return Error();
4717     }
4718
4719     return Error(
4720         "Fetching file load address from remote server returned an error");
4721   }
4722
4723   if (response.IsNormalResponse()) {
4724     is_loaded = true;
4725     load_addr = response.GetHexMaxU64(false, LLDB_INVALID_ADDRESS);
4726     return Error();
4727   }
4728
4729   return Error("Unknown error happened during sending the load address packet");
4730 }
4731
4732 void ProcessGDBRemote::ModulesDidLoad(ModuleList &module_list) {
4733   // We must call the lldb_private::Process::ModulesDidLoad () first before we
4734   // do anything
4735   Process::ModulesDidLoad(module_list);
4736
4737   // After loading shared libraries, we can ask our remote GDB server if
4738   // it needs any symbols.
4739   m_gdb_comm.ServeSymbolLookups(this);
4740 }
4741
4742 void ProcessGDBRemote::HandleAsyncStdout(llvm::StringRef out) {
4743   AppendSTDOUT(out.data(), out.size());
4744 }
4745
4746 static const char *end_delimiter = "--end--;";
4747 static const int end_delimiter_len = 8;
4748
4749 void ProcessGDBRemote::HandleAsyncMisc(llvm::StringRef data) {
4750   std::string input = data.str(); // '1' to move beyond 'A'
4751   if (m_partial_profile_data.length() > 0) {
4752     m_partial_profile_data.append(input);
4753     input = m_partial_profile_data;
4754     m_partial_profile_data.clear();
4755   }
4756
4757   size_t found, pos = 0, len = input.length();
4758   while ((found = input.find(end_delimiter, pos)) != std::string::npos) {
4759     StringExtractorGDBRemote profileDataExtractor(
4760         input.substr(pos, found).c_str());
4761     std::string profile_data =
4762         HarmonizeThreadIdsForProfileData(profileDataExtractor);
4763     BroadcastAsyncProfileData(profile_data);
4764
4765     pos = found + end_delimiter_len;
4766   }
4767
4768   if (pos < len) {
4769     // Last incomplete chunk.
4770     m_partial_profile_data = input.substr(pos);
4771   }
4772 }
4773
4774 std::string ProcessGDBRemote::HarmonizeThreadIdsForProfileData(
4775     StringExtractorGDBRemote &profileDataExtractor) {
4776   std::map<uint64_t, uint32_t> new_thread_id_to_used_usec_map;
4777   std::string output;
4778   llvm::raw_string_ostream output_stream(output);
4779   llvm::StringRef name, value;
4780
4781   // Going to assuming thread_used_usec comes first, else bail out.
4782   while (profileDataExtractor.GetNameColonValue(name, value)) {
4783     if (name.compare("thread_used_id") == 0) {
4784       StringExtractor threadIDHexExtractor(value);
4785       uint64_t thread_id = threadIDHexExtractor.GetHexMaxU64(false, 0);
4786
4787       bool has_used_usec = false;
4788       uint32_t curr_used_usec = 0;
4789       llvm::StringRef usec_name, usec_value;
4790       uint32_t input_file_pos = profileDataExtractor.GetFilePos();
4791       if (profileDataExtractor.GetNameColonValue(usec_name, usec_value)) {
4792         if (usec_name.equals("thread_used_usec")) {
4793           has_used_usec = true;
4794           usec_value.getAsInteger(0, curr_used_usec);
4795         } else {
4796           // We didn't find what we want, it is probably
4797           // an older version. Bail out.
4798           profileDataExtractor.SetFilePos(input_file_pos);
4799         }
4800       }
4801
4802       if (has_used_usec) {
4803         uint32_t prev_used_usec = 0;
4804         std::map<uint64_t, uint32_t>::iterator iterator =
4805             m_thread_id_to_used_usec_map.find(thread_id);
4806         if (iterator != m_thread_id_to_used_usec_map.end()) {
4807           prev_used_usec = m_thread_id_to_used_usec_map[thread_id];
4808         }
4809
4810         uint32_t real_used_usec = curr_used_usec - prev_used_usec;
4811         // A good first time record is one that runs for at least 0.25 sec
4812         bool good_first_time =
4813             (prev_used_usec == 0) && (real_used_usec > 250000);
4814         bool good_subsequent_time =
4815             (prev_used_usec > 0) &&
4816             ((real_used_usec > 0) || (HasAssignedIndexIDToThread(thread_id)));
4817
4818         if (good_first_time || good_subsequent_time) {
4819           // We try to avoid doing too many index id reservation,
4820           // resulting in fast increase of index ids.
4821
4822           output_stream << name << ":";
4823           int32_t index_id = AssignIndexIDToThread(thread_id);
4824           output_stream << index_id << ";";
4825
4826           output_stream << usec_name << ":" << usec_value << ";";
4827         } else {
4828           // Skip past 'thread_used_name'.
4829           llvm::StringRef local_name, local_value;
4830           profileDataExtractor.GetNameColonValue(local_name, local_value);
4831         }
4832
4833         // Store current time as previous time so that they can be compared
4834         // later.
4835         new_thread_id_to_used_usec_map[thread_id] = curr_used_usec;
4836       } else {
4837         // Bail out and use old string.
4838         output_stream << name << ":" << value << ";";
4839       }
4840     } else {
4841       output_stream << name << ":" << value << ";";
4842     }
4843   }
4844   output_stream << end_delimiter;
4845   m_thread_id_to_used_usec_map = new_thread_id_to_used_usec_map;
4846
4847   return output_stream.str();
4848 }
4849
4850 void ProcessGDBRemote::HandleStopReply() {
4851   if (GetStopID() != 0)
4852     return;
4853
4854   if (GetID() == LLDB_INVALID_PROCESS_ID) {
4855     lldb::pid_t pid = m_gdb_comm.GetCurrentProcessID();
4856     if (pid != LLDB_INVALID_PROCESS_ID)
4857       SetID(pid);
4858   }
4859   BuildDynamicRegisterInfo(true);
4860 }
4861
4862 static const char *const s_async_json_packet_prefix = "JSON-async:";
4863
4864 static StructuredData::ObjectSP
4865 ParseStructuredDataPacket(llvm::StringRef packet) {
4866   Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
4867
4868   if (!packet.consume_front(s_async_json_packet_prefix)) {
4869     if (log) {
4870       log->Printf(
4871           "GDBRemoteCommmunicationClientBase::%s() received $J packet "
4872           "but was not a StructuredData packet: packet starts with "
4873           "%s",
4874           __FUNCTION__,
4875           packet.slice(0, strlen(s_async_json_packet_prefix)).str().c_str());
4876     }
4877     return StructuredData::ObjectSP();
4878   }
4879
4880   // This is an asynchronous JSON packet, destined for a
4881   // StructuredDataPlugin.
4882   StructuredData::ObjectSP json_sp = StructuredData::ParseJSON(packet);
4883   if (log) {
4884     if (json_sp) {
4885       StreamString json_str;
4886       json_sp->Dump(json_str);
4887       json_str.Flush();
4888       log->Printf("ProcessGDBRemote::%s() "
4889                   "received Async StructuredData packet: %s",
4890                   __FUNCTION__, json_str.GetData());
4891     } else {
4892       log->Printf("ProcessGDBRemote::%s"
4893                   "() received StructuredData packet:"
4894                   " parse failure",
4895                   __FUNCTION__);
4896     }
4897   }
4898   return json_sp;
4899 }
4900
4901 void ProcessGDBRemote::HandleAsyncStructuredDataPacket(llvm::StringRef data) {
4902   auto structured_data_sp = ParseStructuredDataPacket(data);
4903   if (structured_data_sp)
4904     RouteAsyncStructuredData(structured_data_sp);
4905 }
4906
4907 class CommandObjectProcessGDBRemoteSpeedTest : public CommandObjectParsed {
4908 public:
4909   CommandObjectProcessGDBRemoteSpeedTest(CommandInterpreter &interpreter)
4910       : CommandObjectParsed(interpreter, "process plugin packet speed-test",
4911                             "Tests packet speeds of various sizes to determine "
4912                             "the performance characteristics of the GDB remote "
4913                             "connection. ",
4914                             NULL),
4915         m_option_group(),
4916         m_num_packets(LLDB_OPT_SET_1, false, "count", 'c', 0, eArgTypeCount,
4917                       "The number of packets to send of each varying size "
4918                       "(default is 1000).",
4919                       1000),
4920         m_max_send(LLDB_OPT_SET_1, false, "max-send", 's', 0, eArgTypeCount,
4921                    "The maximum number of bytes to send in a packet. Sizes "
4922                    "increase in powers of 2 while the size is less than or "
4923                    "equal to this option value. (default 1024).",
4924                    1024),
4925         m_max_recv(LLDB_OPT_SET_1, false, "max-receive", 'r', 0, eArgTypeCount,
4926                    "The maximum number of bytes to receive in a packet. Sizes "
4927                    "increase in powers of 2 while the size is less than or "
4928                    "equal to this option value. (default 1024).",
4929                    1024),
4930         m_json(LLDB_OPT_SET_1, false, "json", 'j',
4931                "Print the output as JSON data for easy parsing.", false, true) {
4932     m_option_group.Append(&m_num_packets, LLDB_OPT_SET_ALL, LLDB_OPT_SET_1);
4933     m_option_group.Append(&m_max_send, LLDB_OPT_SET_ALL, LLDB_OPT_SET_1);
4934     m_option_group.Append(&m_max_recv, LLDB_OPT_SET_ALL, LLDB_OPT_SET_1);
4935     m_option_group.Append(&m_json, LLDB_OPT_SET_ALL, LLDB_OPT_SET_1);
4936     m_option_group.Finalize();
4937   }
4938
4939   ~CommandObjectProcessGDBRemoteSpeedTest() {}
4940
4941   Options *GetOptions() override { return &m_option_group; }
4942
4943   bool DoExecute(Args &command, CommandReturnObject &result) override {
4944     const size_t argc = command.GetArgumentCount();
4945     if (argc == 0) {
4946       ProcessGDBRemote *process =
4947           (ProcessGDBRemote *)m_interpreter.GetExecutionContext()
4948               .GetProcessPtr();
4949       if (process) {
4950         StreamSP output_stream_sp(
4951             m_interpreter.GetDebugger().GetAsyncOutputStream());
4952         result.SetImmediateOutputStream(output_stream_sp);
4953
4954         const uint32_t num_packets =
4955             (uint32_t)m_num_packets.GetOptionValue().GetCurrentValue();
4956         const uint64_t max_send = m_max_send.GetOptionValue().GetCurrentValue();
4957         const uint64_t max_recv = m_max_recv.GetOptionValue().GetCurrentValue();
4958         const bool json = m_json.GetOptionValue().GetCurrentValue();
4959         const uint64_t k_recv_amount =
4960             4 * 1024 * 1024; // Receive amount in bytes
4961         process->GetGDBRemote().TestPacketSpeed(
4962             num_packets, max_send, max_recv, k_recv_amount, json,
4963             output_stream_sp ? *output_stream_sp : result.GetOutputStream());
4964         result.SetStatus(eReturnStatusSuccessFinishResult);
4965         return true;
4966       }
4967     } else {
4968       result.AppendErrorWithFormat("'%s' takes no arguments",
4969                                    m_cmd_name.c_str());
4970     }
4971     result.SetStatus(eReturnStatusFailed);
4972     return false;
4973   }
4974
4975 protected:
4976   OptionGroupOptions m_option_group;
4977   OptionGroupUInt64 m_num_packets;
4978   OptionGroupUInt64 m_max_send;
4979   OptionGroupUInt64 m_max_recv;
4980   OptionGroupBoolean m_json;
4981 };
4982
4983 class CommandObjectProcessGDBRemotePacketHistory : public CommandObjectParsed {
4984 private:
4985 public:
4986   CommandObjectProcessGDBRemotePacketHistory(CommandInterpreter &interpreter)
4987       : CommandObjectParsed(interpreter, "process plugin packet history",
4988                             "Dumps the packet history buffer. ", NULL) {}
4989
4990   ~CommandObjectProcessGDBRemotePacketHistory() {}
4991
4992   bool DoExecute(Args &command, CommandReturnObject &result) override {
4993     const size_t argc = command.GetArgumentCount();
4994     if (argc == 0) {
4995       ProcessGDBRemote *process =
4996           (ProcessGDBRemote *)m_interpreter.GetExecutionContext()
4997               .GetProcessPtr();
4998       if (process) {
4999         process->GetGDBRemote().DumpHistory(result.GetOutputStream());
5000         result.SetStatus(eReturnStatusSuccessFinishResult);
5001         return true;
5002       }
5003     } else {
5004       result.AppendErrorWithFormat("'%s' takes no arguments",
5005                                    m_cmd_name.c_str());
5006     }
5007     result.SetStatus(eReturnStatusFailed);
5008     return false;
5009   }
5010 };
5011
5012 class CommandObjectProcessGDBRemotePacketXferSize : public CommandObjectParsed {
5013 private:
5014 public:
5015   CommandObjectProcessGDBRemotePacketXferSize(CommandInterpreter &interpreter)
5016       : CommandObjectParsed(
5017             interpreter, "process plugin packet xfer-size",
5018             "Maximum size that lldb will try to read/write one one chunk.",
5019             NULL) {}
5020
5021   ~CommandObjectProcessGDBRemotePacketXferSize() {}
5022
5023   bool DoExecute(Args &command, CommandReturnObject &result) override {
5024     const size_t argc = command.GetArgumentCount();
5025     if (argc == 0) {
5026       result.AppendErrorWithFormat("'%s' takes an argument to specify the max "
5027                                    "amount to be transferred when "
5028                                    "reading/writing",
5029                                    m_cmd_name.c_str());
5030       result.SetStatus(eReturnStatusFailed);
5031       return false;
5032     }
5033
5034     ProcessGDBRemote *process =
5035         (ProcessGDBRemote *)m_interpreter.GetExecutionContext().GetProcessPtr();
5036     if (process) {
5037       const char *packet_size = command.GetArgumentAtIndex(0);
5038       errno = 0;
5039       uint64_t user_specified_max = strtoul(packet_size, NULL, 10);
5040       if (errno == 0 && user_specified_max != 0) {
5041         process->SetUserSpecifiedMaxMemoryTransferSize(user_specified_max);
5042         result.SetStatus(eReturnStatusSuccessFinishResult);
5043         return true;
5044       }
5045     }
5046     result.SetStatus(eReturnStatusFailed);
5047     return false;
5048   }
5049 };
5050
5051 class CommandObjectProcessGDBRemotePacketSend : public CommandObjectParsed {
5052 private:
5053 public:
5054   CommandObjectProcessGDBRemotePacketSend(CommandInterpreter &interpreter)
5055       : CommandObjectParsed(interpreter, "process plugin packet send",
5056                             "Send a custom packet through the GDB remote "
5057                             "protocol and print the answer. "
5058                             "The packet header and footer will automatically "
5059                             "be added to the packet prior to sending and "
5060                             "stripped from the result.",
5061                             NULL) {}
5062
5063   ~CommandObjectProcessGDBRemotePacketSend() {}
5064
5065   bool DoExecute(Args &command, CommandReturnObject &result) override {
5066     const size_t argc = command.GetArgumentCount();
5067     if (argc == 0) {
5068       result.AppendErrorWithFormat(
5069           "'%s' takes a one or more packet content arguments",
5070           m_cmd_name.c_str());
5071       result.SetStatus(eReturnStatusFailed);
5072       return false;
5073     }
5074
5075     ProcessGDBRemote *process =
5076         (ProcessGDBRemote *)m_interpreter.GetExecutionContext().GetProcessPtr();
5077     if (process) {
5078       for (size_t i = 0; i < argc; ++i) {
5079         const char *packet_cstr = command.GetArgumentAtIndex(0);
5080         bool send_async = true;
5081         StringExtractorGDBRemote response;
5082         process->GetGDBRemote().SendPacketAndWaitForResponse(
5083             packet_cstr, response, send_async);
5084         result.SetStatus(eReturnStatusSuccessFinishResult);
5085         Stream &output_strm = result.GetOutputStream();
5086         output_strm.Printf("  packet: %s\n", packet_cstr);
5087         std::string &response_str = response.GetStringRef();
5088
5089         if (strstr(packet_cstr, "qGetProfileData") != NULL) {
5090           response_str = process->HarmonizeThreadIdsForProfileData(response);
5091         }
5092
5093         if (response_str.empty())
5094           output_strm.PutCString("response: \nerror: UNIMPLEMENTED\n");
5095         else
5096           output_strm.Printf("response: %s\n", response.GetStringRef().c_str());
5097       }
5098     }
5099     return true;
5100   }
5101 };
5102
5103 class CommandObjectProcessGDBRemotePacketMonitor : public CommandObjectRaw {
5104 private:
5105 public:
5106   CommandObjectProcessGDBRemotePacketMonitor(CommandInterpreter &interpreter)
5107       : CommandObjectRaw(interpreter, "process plugin packet monitor",
5108                          "Send a qRcmd packet through the GDB remote protocol "
5109                          "and print the response."
5110                          "The argument passed to this command will be hex "
5111                          "encoded into a valid 'qRcmd' packet, sent and the "
5112                          "response will be printed.") {}
5113
5114   ~CommandObjectProcessGDBRemotePacketMonitor() {}
5115
5116   bool DoExecute(const char *command, CommandReturnObject &result) override {
5117     if (command == NULL || command[0] == '\0') {
5118       result.AppendErrorWithFormat("'%s' takes a command string argument",
5119                                    m_cmd_name.c_str());
5120       result.SetStatus(eReturnStatusFailed);
5121       return false;
5122     }
5123
5124     ProcessGDBRemote *process =
5125         (ProcessGDBRemote *)m_interpreter.GetExecutionContext().GetProcessPtr();
5126     if (process) {
5127       StreamString packet;
5128       packet.PutCString("qRcmd,");
5129       packet.PutBytesAsRawHex8(command, strlen(command));
5130
5131       bool send_async = true;
5132       StringExtractorGDBRemote response;
5133       process->GetGDBRemote().SendPacketAndWaitForResponse(
5134           packet.GetString(), response, send_async);
5135       result.SetStatus(eReturnStatusSuccessFinishResult);
5136       Stream &output_strm = result.GetOutputStream();
5137       output_strm.Printf("  packet: %s\n", packet.GetData());
5138       const std::string &response_str = response.GetStringRef();
5139
5140       if (response_str.empty())
5141         output_strm.PutCString("response: \nerror: UNIMPLEMENTED\n");
5142       else
5143         output_strm.Printf("response: %s\n", response.GetStringRef().c_str());
5144     }
5145     return true;
5146   }
5147 };
5148
5149 class CommandObjectProcessGDBRemotePacket : public CommandObjectMultiword {
5150 private:
5151 public:
5152   CommandObjectProcessGDBRemotePacket(CommandInterpreter &interpreter)
5153       : CommandObjectMultiword(interpreter, "process plugin packet",
5154                                "Commands that deal with GDB remote packets.",
5155                                NULL) {
5156     LoadSubCommand(
5157         "history",
5158         CommandObjectSP(
5159             new CommandObjectProcessGDBRemotePacketHistory(interpreter)));
5160     LoadSubCommand(
5161         "send", CommandObjectSP(
5162                     new CommandObjectProcessGDBRemotePacketSend(interpreter)));
5163     LoadSubCommand(
5164         "monitor",
5165         CommandObjectSP(
5166             new CommandObjectProcessGDBRemotePacketMonitor(interpreter)));
5167     LoadSubCommand(
5168         "xfer-size",
5169         CommandObjectSP(
5170             new CommandObjectProcessGDBRemotePacketXferSize(interpreter)));
5171     LoadSubCommand("speed-test",
5172                    CommandObjectSP(new CommandObjectProcessGDBRemoteSpeedTest(
5173                        interpreter)));
5174   }
5175
5176   ~CommandObjectProcessGDBRemotePacket() {}
5177 };
5178
5179 class CommandObjectMultiwordProcessGDBRemote : public CommandObjectMultiword {
5180 public:
5181   CommandObjectMultiwordProcessGDBRemote(CommandInterpreter &interpreter)
5182       : CommandObjectMultiword(
5183             interpreter, "process plugin",
5184             "Commands for operating on a ProcessGDBRemote process.",
5185             "process plugin <subcommand> [<subcommand-options>]") {
5186     LoadSubCommand(
5187         "packet",
5188         CommandObjectSP(new CommandObjectProcessGDBRemotePacket(interpreter)));
5189   }
5190
5191   ~CommandObjectMultiwordProcessGDBRemote() {}
5192 };
5193
5194 CommandObject *ProcessGDBRemote::GetPluginCommandObject() {
5195   if (!m_command_sp)
5196     m_command_sp.reset(new CommandObjectMultiwordProcessGDBRemote(
5197         GetTarget().GetDebugger().GetCommandInterpreter()));
5198   return m_command_sp.get();
5199 }