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