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