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