xref: /freebsd-src/contrib/llvm-project/lldb/source/Plugins/Process/gdb-remote/ProcessGDBRemote.cpp (revision 81ad626541db97eb356e2c1d4a20eb2a26a766ab)
15ffd83dbSDimitry Andric //===-- ProcessGDBRemote.cpp ----------------------------------------------===//
20b57cec5SDimitry Andric //
30b57cec5SDimitry Andric // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
40b57cec5SDimitry Andric // See https://llvm.org/LICENSE.txt for license information.
50b57cec5SDimitry Andric // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
60b57cec5SDimitry Andric //
70b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
80b57cec5SDimitry Andric 
90b57cec5SDimitry Andric #include "lldb/Host/Config.h"
100b57cec5SDimitry Andric 
11fe6060f1SDimitry Andric #include <cerrno>
12fe6060f1SDimitry Andric #include <cstdlib>
13480093f4SDimitry Andric #if LLDB_ENABLE_POSIX
140b57cec5SDimitry Andric #include <netinet/in.h>
150b57cec5SDimitry Andric #include <sys/mman.h>
160b57cec5SDimitry Andric #include <sys/socket.h>
170b57cec5SDimitry Andric #include <unistd.h>
180b57cec5SDimitry Andric #endif
190b57cec5SDimitry Andric #include <sys/stat.h>
205ffd83dbSDimitry Andric #if defined(__APPLE__)
215ffd83dbSDimitry Andric #include <sys/sysctl.h>
225ffd83dbSDimitry Andric #endif
23fe6060f1SDimitry Andric #include <ctime>
240b57cec5SDimitry Andric #include <sys/types.h>
250b57cec5SDimitry Andric 
260b57cec5SDimitry Andric #include "lldb/Breakpoint/Watchpoint.h"
270b57cec5SDimitry Andric #include "lldb/Core/Debugger.h"
280b57cec5SDimitry Andric #include "lldb/Core/Module.h"
290b57cec5SDimitry Andric #include "lldb/Core/ModuleSpec.h"
300b57cec5SDimitry Andric #include "lldb/Core/PluginManager.h"
310b57cec5SDimitry Andric #include "lldb/Core/StreamFile.h"
320b57cec5SDimitry Andric #include "lldb/Core/Value.h"
330b57cec5SDimitry Andric #include "lldb/DataFormatters/FormatManager.h"
340b57cec5SDimitry Andric #include "lldb/Host/ConnectionFileDescriptor.h"
350b57cec5SDimitry Andric #include "lldb/Host/FileSystem.h"
360b57cec5SDimitry Andric #include "lldb/Host/HostThread.h"
370b57cec5SDimitry Andric #include "lldb/Host/PosixApi.h"
380b57cec5SDimitry Andric #include "lldb/Host/PseudoTerminal.h"
390b57cec5SDimitry Andric #include "lldb/Host/ThreadLauncher.h"
400b57cec5SDimitry Andric #include "lldb/Host/XML.h"
410b57cec5SDimitry Andric #include "lldb/Interpreter/CommandInterpreter.h"
420b57cec5SDimitry Andric #include "lldb/Interpreter/CommandObject.h"
430b57cec5SDimitry Andric #include "lldb/Interpreter/CommandObjectMultiword.h"
440b57cec5SDimitry Andric #include "lldb/Interpreter/CommandReturnObject.h"
450b57cec5SDimitry Andric #include "lldb/Interpreter/OptionArgParser.h"
460b57cec5SDimitry Andric #include "lldb/Interpreter/OptionGroupBoolean.h"
470b57cec5SDimitry Andric #include "lldb/Interpreter/OptionGroupUInt64.h"
480b57cec5SDimitry Andric #include "lldb/Interpreter/OptionValueProperties.h"
490b57cec5SDimitry Andric #include "lldb/Interpreter/Options.h"
500b57cec5SDimitry Andric #include "lldb/Interpreter/Property.h"
510b57cec5SDimitry Andric #include "lldb/Symbol/LocateSymbolFile.h"
520b57cec5SDimitry Andric #include "lldb/Symbol/ObjectFile.h"
530b57cec5SDimitry Andric #include "lldb/Target/ABI.h"
540b57cec5SDimitry Andric #include "lldb/Target/DynamicLoader.h"
550b57cec5SDimitry Andric #include "lldb/Target/MemoryRegionInfo.h"
560b57cec5SDimitry Andric #include "lldb/Target/SystemRuntime.h"
570b57cec5SDimitry Andric #include "lldb/Target/Target.h"
580b57cec5SDimitry Andric #include "lldb/Target/TargetList.h"
590b57cec5SDimitry Andric #include "lldb/Target/ThreadPlanCallFunction.h"
600b57cec5SDimitry Andric #include "lldb/Utility/Args.h"
610b57cec5SDimitry Andric #include "lldb/Utility/FileSpec.h"
62*81ad6265SDimitry Andric #include "lldb/Utility/LLDBLog.h"
630b57cec5SDimitry Andric #include "lldb/Utility/Reproducer.h"
640b57cec5SDimitry Andric #include "lldb/Utility/State.h"
650b57cec5SDimitry Andric #include "lldb/Utility/StreamString.h"
660b57cec5SDimitry Andric #include "lldb/Utility/Timer.h"
6704eeddc0SDimitry Andric #include <algorithm>
6804eeddc0SDimitry Andric #include <csignal>
6904eeddc0SDimitry Andric #include <map>
7004eeddc0SDimitry Andric #include <memory>
7104eeddc0SDimitry Andric #include <mutex>
7204eeddc0SDimitry Andric #include <sstream>
7304eeddc0SDimitry Andric #include <thread>
740b57cec5SDimitry Andric 
750b57cec5SDimitry Andric #include "GDBRemoteRegisterContext.h"
7604eeddc0SDimitry Andric #include "GDBRemoteRegisterFallback.h"
770b57cec5SDimitry Andric #include "Plugins/Process/Utility/GDBRemoteSignals.h"
780b57cec5SDimitry Andric #include "Plugins/Process/Utility/InferiorCallPOSIX.h"
790b57cec5SDimitry Andric #include "Plugins/Process/Utility/StopInfoMachException.h"
800b57cec5SDimitry Andric #include "ProcessGDBRemote.h"
810b57cec5SDimitry Andric #include "ProcessGDBRemoteLog.h"
820b57cec5SDimitry Andric #include "ThreadGDBRemote.h"
830b57cec5SDimitry Andric #include "lldb/Host/Host.h"
840b57cec5SDimitry Andric #include "lldb/Utility/StringExtractorGDBRemote.h"
850b57cec5SDimitry Andric 
869dba64beSDimitry Andric #include "llvm/ADT/ScopeExit.h"
870b57cec5SDimitry Andric #include "llvm/ADT/StringSwitch.h"
880b57cec5SDimitry Andric #include "llvm/Support/Threading.h"
890b57cec5SDimitry Andric #include "llvm/Support/raw_ostream.h"
900b57cec5SDimitry Andric 
910b57cec5SDimitry Andric #define DEBUGSERVER_BASENAME "debugserver"
920b57cec5SDimitry Andric using namespace lldb;
930b57cec5SDimitry Andric using namespace lldb_private;
940b57cec5SDimitry Andric using namespace lldb_private::process_gdb_remote;
950b57cec5SDimitry Andric 
965ffd83dbSDimitry Andric LLDB_PLUGIN_DEFINE(ProcessGDBRemote)
975ffd83dbSDimitry Andric 
980b57cec5SDimitry Andric namespace lldb {
990b57cec5SDimitry Andric // Provide a function that can easily dump the packet history if we know a
1000b57cec5SDimitry Andric // ProcessGDBRemote * value (which we can get from logs or from debugging). We
1010b57cec5SDimitry Andric // need the function in the lldb namespace so it makes it into the final
1020b57cec5SDimitry Andric // executable since the LLDB shared library only exports stuff in the lldb
1030b57cec5SDimitry Andric // namespace. This allows you to attach with a debugger and call this function
1040b57cec5SDimitry Andric // and get the packet history dumped to a file.
1050b57cec5SDimitry Andric void DumpProcessGDBRemotePacketHistory(void *p, const char *path) {
1069dba64beSDimitry Andric   auto file = FileSystem::Instance().Open(
107349cc55cSDimitry Andric       FileSpec(path), File::eOpenOptionWriteOnly | File::eOpenOptionCanCreate);
1089dba64beSDimitry Andric   if (!file) {
1099dba64beSDimitry Andric     llvm::consumeError(file.takeError());
1109dba64beSDimitry Andric     return;
1119dba64beSDimitry Andric   }
1129dba64beSDimitry Andric   StreamFile stream(std::move(file.get()));
1139dba64beSDimitry Andric   ((ProcessGDBRemote *)p)->GetGDBRemote().DumpHistory(stream);
1140b57cec5SDimitry Andric }
1150b57cec5SDimitry Andric } // namespace lldb
1160b57cec5SDimitry Andric 
1170b57cec5SDimitry Andric namespace {
1180b57cec5SDimitry Andric 
1199dba64beSDimitry Andric #define LLDB_PROPERTIES_processgdbremote
1209dba64beSDimitry Andric #include "ProcessGDBRemoteProperties.inc"
1210b57cec5SDimitry Andric 
1220b57cec5SDimitry Andric enum {
1239dba64beSDimitry Andric #define LLDB_PROPERTIES_processgdbremote
1249dba64beSDimitry Andric #include "ProcessGDBRemotePropertiesEnum.inc"
1250b57cec5SDimitry Andric };
1260b57cec5SDimitry Andric 
1270b57cec5SDimitry Andric class PluginProperties : public Properties {
1280b57cec5SDimitry Andric public:
1290b57cec5SDimitry Andric   static ConstString GetSettingName() {
130349cc55cSDimitry Andric     return ConstString(ProcessGDBRemote::GetPluginNameStatic());
1310b57cec5SDimitry Andric   }
1320b57cec5SDimitry Andric 
1330b57cec5SDimitry Andric   PluginProperties() : Properties() {
1340b57cec5SDimitry Andric     m_collection_sp = std::make_shared<OptionValueProperties>(GetSettingName());
1359dba64beSDimitry Andric     m_collection_sp->Initialize(g_processgdbremote_properties);
1360b57cec5SDimitry Andric   }
1370b57cec5SDimitry Andric 
138fe6060f1SDimitry Andric   ~PluginProperties() override = default;
1390b57cec5SDimitry Andric 
1400b57cec5SDimitry Andric   uint64_t GetPacketTimeout() {
1410b57cec5SDimitry Andric     const uint32_t idx = ePropertyPacketTimeout;
1420b57cec5SDimitry Andric     return m_collection_sp->GetPropertyAtIndexAsUInt64(
1439dba64beSDimitry Andric         nullptr, idx, g_processgdbremote_properties[idx].default_uint_value);
1440b57cec5SDimitry Andric   }
1450b57cec5SDimitry Andric 
1460b57cec5SDimitry Andric   bool SetPacketTimeout(uint64_t timeout) {
1470b57cec5SDimitry Andric     const uint32_t idx = ePropertyPacketTimeout;
1480b57cec5SDimitry Andric     return m_collection_sp->SetPropertyAtIndexAsUInt64(nullptr, idx, timeout);
1490b57cec5SDimitry Andric   }
1500b57cec5SDimitry Andric 
1510b57cec5SDimitry Andric   FileSpec GetTargetDefinitionFile() const {
1520b57cec5SDimitry Andric     const uint32_t idx = ePropertyTargetDefinitionFile;
1530b57cec5SDimitry Andric     return m_collection_sp->GetPropertyAtIndexAsFileSpec(nullptr, idx);
1540b57cec5SDimitry Andric   }
1550b57cec5SDimitry Andric 
1560b57cec5SDimitry Andric   bool GetUseSVR4() const {
1570b57cec5SDimitry Andric     const uint32_t idx = ePropertyUseSVR4;
1580b57cec5SDimitry Andric     return m_collection_sp->GetPropertyAtIndexAsBoolean(
1599dba64beSDimitry Andric         nullptr, idx,
1609dba64beSDimitry Andric         g_processgdbremote_properties[idx].default_uint_value != 0);
1610b57cec5SDimitry Andric   }
162480093f4SDimitry Andric 
163480093f4SDimitry Andric   bool GetUseGPacketForReading() const {
164480093f4SDimitry Andric     const uint32_t idx = ePropertyUseGPacketForReading;
165480093f4SDimitry Andric     return m_collection_sp->GetPropertyAtIndexAsBoolean(nullptr, idx, true);
166480093f4SDimitry Andric   }
1670b57cec5SDimitry Andric };
1680b57cec5SDimitry Andric 
169349cc55cSDimitry Andric static PluginProperties &GetGlobalPluginProperties() {
170349cc55cSDimitry Andric   static PluginProperties g_settings;
171349cc55cSDimitry Andric   return g_settings;
1720b57cec5SDimitry Andric }
1730b57cec5SDimitry Andric 
1740b57cec5SDimitry Andric } // namespace
1750b57cec5SDimitry Andric 
1760b57cec5SDimitry Andric // TODO Randomly assigning a port is unsafe.  We should get an unused
1770b57cec5SDimitry Andric // ephemeral port from the kernel and make sure we reserve it before passing it
1780b57cec5SDimitry Andric // to debugserver.
1790b57cec5SDimitry Andric 
1800b57cec5SDimitry Andric #if defined(__APPLE__)
1810b57cec5SDimitry Andric #define LOW_PORT (IPPORT_RESERVED)
1820b57cec5SDimitry Andric #define HIGH_PORT (IPPORT_HIFIRSTAUTO)
1830b57cec5SDimitry Andric #else
1840b57cec5SDimitry Andric #define LOW_PORT (1024u)
1850b57cec5SDimitry Andric #define HIGH_PORT (49151u)
1860b57cec5SDimitry Andric #endif
1870b57cec5SDimitry Andric 
188349cc55cSDimitry Andric llvm::StringRef ProcessGDBRemote::GetPluginDescriptionStatic() {
1890b57cec5SDimitry Andric   return "GDB Remote protocol based debugging plug-in.";
1900b57cec5SDimitry Andric }
1910b57cec5SDimitry Andric 
1920b57cec5SDimitry Andric void ProcessGDBRemote::Terminate() {
1930b57cec5SDimitry Andric   PluginManager::UnregisterPlugin(ProcessGDBRemote::CreateInstance);
1940b57cec5SDimitry Andric }
1950b57cec5SDimitry Andric 
1960b57cec5SDimitry Andric lldb::ProcessSP
1970b57cec5SDimitry Andric ProcessGDBRemote::CreateInstance(lldb::TargetSP target_sp,
1980b57cec5SDimitry Andric                                  ListenerSP listener_sp,
199e8d8bef9SDimitry Andric                                  const FileSpec *crash_file_path,
200e8d8bef9SDimitry Andric                                  bool can_connect) {
2010b57cec5SDimitry Andric   lldb::ProcessSP process_sp;
2020b57cec5SDimitry Andric   if (crash_file_path == nullptr)
2030b57cec5SDimitry Andric     process_sp = std::make_shared<ProcessGDBRemote>(target_sp, listener_sp);
2040b57cec5SDimitry Andric   return process_sp;
2050b57cec5SDimitry Andric }
2060b57cec5SDimitry Andric 
207fe6060f1SDimitry Andric std::chrono::seconds ProcessGDBRemote::GetPacketTimeout() {
208349cc55cSDimitry Andric   return std::chrono::seconds(GetGlobalPluginProperties().GetPacketTimeout());
209fe6060f1SDimitry Andric }
210fe6060f1SDimitry Andric 
211*81ad6265SDimitry Andric ArchSpec ProcessGDBRemote::GetSystemArchitecture() {
212*81ad6265SDimitry Andric   return m_gdb_comm.GetHostArchitecture();
213*81ad6265SDimitry Andric }
214*81ad6265SDimitry Andric 
2150b57cec5SDimitry Andric bool ProcessGDBRemote::CanDebug(lldb::TargetSP target_sp,
2160b57cec5SDimitry Andric                                 bool plugin_specified_by_name) {
2170b57cec5SDimitry Andric   if (plugin_specified_by_name)
2180b57cec5SDimitry Andric     return true;
2190b57cec5SDimitry Andric 
2200b57cec5SDimitry Andric   // For now we are just making sure the file exists for a given module
2210b57cec5SDimitry Andric   Module *exe_module = target_sp->GetExecutableModulePointer();
2220b57cec5SDimitry Andric   if (exe_module) {
2230b57cec5SDimitry Andric     ObjectFile *exe_objfile = exe_module->GetObjectFile();
2240b57cec5SDimitry Andric     // We can't debug core files...
2250b57cec5SDimitry Andric     switch (exe_objfile->GetType()) {
2260b57cec5SDimitry Andric     case ObjectFile::eTypeInvalid:
2270b57cec5SDimitry Andric     case ObjectFile::eTypeCoreFile:
2280b57cec5SDimitry Andric     case ObjectFile::eTypeDebugInfo:
2290b57cec5SDimitry Andric     case ObjectFile::eTypeObjectFile:
2300b57cec5SDimitry Andric     case ObjectFile::eTypeSharedLibrary:
2310b57cec5SDimitry Andric     case ObjectFile::eTypeStubLibrary:
2320b57cec5SDimitry Andric     case ObjectFile::eTypeJIT:
2330b57cec5SDimitry Andric       return false;
2340b57cec5SDimitry Andric     case ObjectFile::eTypeExecutable:
2350b57cec5SDimitry Andric     case ObjectFile::eTypeDynamicLinker:
2360b57cec5SDimitry Andric     case ObjectFile::eTypeUnknown:
2370b57cec5SDimitry Andric       break;
2380b57cec5SDimitry Andric     }
2390b57cec5SDimitry Andric     return FileSystem::Instance().Exists(exe_module->GetFileSpec());
2400b57cec5SDimitry Andric   }
2410b57cec5SDimitry Andric   // However, if there is no executable module, we return true since we might
2420b57cec5SDimitry Andric   // be preparing to attach.
2430b57cec5SDimitry Andric   return true;
2440b57cec5SDimitry Andric }
2450b57cec5SDimitry Andric 
2460b57cec5SDimitry Andric // ProcessGDBRemote constructor
2470b57cec5SDimitry Andric ProcessGDBRemote::ProcessGDBRemote(lldb::TargetSP target_sp,
2480b57cec5SDimitry Andric                                    ListenerSP listener_sp)
2490b57cec5SDimitry Andric     : Process(target_sp, listener_sp),
250349cc55cSDimitry Andric       m_debugserver_pid(LLDB_INVALID_PROCESS_ID), m_register_info_sp(nullptr),
2510b57cec5SDimitry Andric       m_async_broadcaster(nullptr, "lldb.process.gdb-remote.async-broadcaster"),
2520b57cec5SDimitry Andric       m_async_listener_sp(
2530b57cec5SDimitry Andric           Listener::MakeListener("lldb.process.gdb-remote.async-listener")),
2540b57cec5SDimitry Andric       m_async_thread_state_mutex(), m_thread_ids(), m_thread_pcs(),
2550b57cec5SDimitry Andric       m_jstopinfo_sp(), m_jthreadsinfo_sp(), m_continue_c_tids(),
2560b57cec5SDimitry Andric       m_continue_C_tids(), m_continue_s_tids(), m_continue_S_tids(),
2570b57cec5SDimitry Andric       m_max_memory_size(0), m_remote_stub_max_memory_size(0),
2580b57cec5SDimitry Andric       m_addr_to_mmap_size(), m_thread_create_bp_sp(),
259*81ad6265SDimitry Andric       m_waiting_for_attach(false),
2600b57cec5SDimitry Andric       m_command_sp(), m_breakpoint_pc_offset(0),
26104eeddc0SDimitry Andric       m_initial_tid(LLDB_INVALID_THREAD_ID), m_allow_flash_writes(false),
26204eeddc0SDimitry Andric       m_erased_flash_ranges(), m_vfork_in_progress(false) {
2630b57cec5SDimitry Andric   m_async_broadcaster.SetEventName(eBroadcastBitAsyncThreadShouldExit,
2640b57cec5SDimitry Andric                                    "async thread should exit");
2650b57cec5SDimitry Andric   m_async_broadcaster.SetEventName(eBroadcastBitAsyncContinue,
2660b57cec5SDimitry Andric                                    "async thread continue");
2670b57cec5SDimitry Andric   m_async_broadcaster.SetEventName(eBroadcastBitAsyncThreadDidExit,
2680b57cec5SDimitry Andric                                    "async thread did exit");
2690b57cec5SDimitry Andric 
2700b57cec5SDimitry Andric   if (repro::Generator *g = repro::Reproducer::Instance().GetGenerator()) {
271480093f4SDimitry Andric     repro::GDBRemoteProvider &provider =
272480093f4SDimitry Andric         g->GetOrCreate<repro::GDBRemoteProvider>();
273480093f4SDimitry Andric     m_gdb_comm.SetPacketRecorder(provider.GetNewPacketRecorder());
2740b57cec5SDimitry Andric   }
2750b57cec5SDimitry Andric 
2761fd87a68SDimitry Andric   Log *log = GetLog(GDBRLog::Async);
2770b57cec5SDimitry Andric 
2780b57cec5SDimitry Andric   const uint32_t async_event_mask =
2790b57cec5SDimitry Andric       eBroadcastBitAsyncContinue | eBroadcastBitAsyncThreadShouldExit;
2800b57cec5SDimitry Andric 
2810b57cec5SDimitry Andric   if (m_async_listener_sp->StartListeningForEvents(
2820b57cec5SDimitry Andric           &m_async_broadcaster, async_event_mask) != async_event_mask) {
2839dba64beSDimitry Andric     LLDB_LOGF(log,
2849dba64beSDimitry Andric               "ProcessGDBRemote::%s failed to listen for "
2850b57cec5SDimitry Andric               "m_async_broadcaster events",
2860b57cec5SDimitry Andric               __FUNCTION__);
2870b57cec5SDimitry Andric   }
2880b57cec5SDimitry Andric 
2894824e7fdSDimitry Andric   const uint32_t gdb_event_mask = Communication::eBroadcastBitReadThreadDidExit;
2900b57cec5SDimitry Andric   if (m_async_listener_sp->StartListeningForEvents(
2910b57cec5SDimitry Andric           &m_gdb_comm, gdb_event_mask) != gdb_event_mask) {
2929dba64beSDimitry Andric     LLDB_LOGF(log,
2939dba64beSDimitry Andric               "ProcessGDBRemote::%s failed to listen for m_gdb_comm events",
2940b57cec5SDimitry Andric               __FUNCTION__);
2950b57cec5SDimitry Andric   }
2960b57cec5SDimitry Andric 
2970b57cec5SDimitry Andric   const uint64_t timeout_seconds =
298349cc55cSDimitry Andric       GetGlobalPluginProperties().GetPacketTimeout();
2990b57cec5SDimitry Andric   if (timeout_seconds > 0)
3000b57cec5SDimitry Andric     m_gdb_comm.SetPacketTimeout(std::chrono::seconds(timeout_seconds));
301480093f4SDimitry Andric 
302480093f4SDimitry Andric   m_use_g_packet_for_reading =
303349cc55cSDimitry Andric       GetGlobalPluginProperties().GetUseGPacketForReading();
3040b57cec5SDimitry Andric }
3050b57cec5SDimitry Andric 
3060b57cec5SDimitry Andric // Destructor
3070b57cec5SDimitry Andric ProcessGDBRemote::~ProcessGDBRemote() {
3080b57cec5SDimitry Andric   //  m_mach_process.UnregisterNotificationCallbacks (this);
3090b57cec5SDimitry Andric   Clear();
3100b57cec5SDimitry Andric   // We need to call finalize on the process before destroying ourselves to
3110b57cec5SDimitry Andric   // make sure all of the broadcaster cleanup goes as planned. If we destruct
3120b57cec5SDimitry Andric   // this class, then Process::~Process() might have problems trying to fully
3130b57cec5SDimitry Andric   // destroy the broadcaster.
3140b57cec5SDimitry Andric   Finalize();
3150b57cec5SDimitry Andric 
3160b57cec5SDimitry Andric   // The general Finalize is going to try to destroy the process and that
3170b57cec5SDimitry Andric   // SHOULD shut down the async thread.  However, if we don't kill it it will
3180b57cec5SDimitry Andric   // get stranded and its connection will go away so when it wakes up it will
3190b57cec5SDimitry Andric   // crash.  So kill it for sure here.
3200b57cec5SDimitry Andric   StopAsyncThread();
3210b57cec5SDimitry Andric   KillDebugserverProcess();
3220b57cec5SDimitry Andric }
3230b57cec5SDimitry Andric 
3240b57cec5SDimitry Andric bool ProcessGDBRemote::ParsePythonTargetDefinition(
3250b57cec5SDimitry Andric     const FileSpec &target_definition_fspec) {
3260b57cec5SDimitry Andric   ScriptInterpreter *interpreter =
3270b57cec5SDimitry Andric       GetTarget().GetDebugger().GetScriptInterpreter();
3280b57cec5SDimitry Andric   Status error;
3290b57cec5SDimitry Andric   StructuredData::ObjectSP module_object_sp(
3300b57cec5SDimitry Andric       interpreter->LoadPluginModule(target_definition_fspec, error));
3310b57cec5SDimitry Andric   if (module_object_sp) {
3320b57cec5SDimitry Andric     StructuredData::DictionarySP target_definition_sp(
3330b57cec5SDimitry Andric         interpreter->GetDynamicSettings(module_object_sp, &GetTarget(),
3340b57cec5SDimitry Andric                                         "gdb-server-target-definition", error));
3350b57cec5SDimitry Andric 
3360b57cec5SDimitry Andric     if (target_definition_sp) {
3370b57cec5SDimitry Andric       StructuredData::ObjectSP target_object(
3380b57cec5SDimitry Andric           target_definition_sp->GetValueForKey("host-info"));
3390b57cec5SDimitry Andric       if (target_object) {
3400b57cec5SDimitry Andric         if (auto host_info_dict = target_object->GetAsDictionary()) {
3410b57cec5SDimitry Andric           StructuredData::ObjectSP triple_value =
3420b57cec5SDimitry Andric               host_info_dict->GetValueForKey("triple");
3430b57cec5SDimitry Andric           if (auto triple_string_value = triple_value->GetAsString()) {
3445ffd83dbSDimitry Andric             std::string triple_string =
3455ffd83dbSDimitry Andric                 std::string(triple_string_value->GetValue());
3460b57cec5SDimitry Andric             ArchSpec host_arch(triple_string.c_str());
3470b57cec5SDimitry Andric             if (!host_arch.IsCompatibleMatch(GetTarget().GetArchitecture())) {
3480b57cec5SDimitry Andric               GetTarget().SetArchitecture(host_arch);
3490b57cec5SDimitry Andric             }
3500b57cec5SDimitry Andric           }
3510b57cec5SDimitry Andric         }
3520b57cec5SDimitry Andric       }
3530b57cec5SDimitry Andric       m_breakpoint_pc_offset = 0;
3540b57cec5SDimitry Andric       StructuredData::ObjectSP breakpoint_pc_offset_value =
3550b57cec5SDimitry Andric           target_definition_sp->GetValueForKey("breakpoint-pc-offset");
3560b57cec5SDimitry Andric       if (breakpoint_pc_offset_value) {
3570b57cec5SDimitry Andric         if (auto breakpoint_pc_int_value =
3580b57cec5SDimitry Andric                 breakpoint_pc_offset_value->GetAsInteger())
3590b57cec5SDimitry Andric           m_breakpoint_pc_offset = breakpoint_pc_int_value->GetValue();
3600b57cec5SDimitry Andric       }
3610b57cec5SDimitry Andric 
362e8d8bef9SDimitry Andric       if (m_register_info_sp->SetRegisterInfo(
363e8d8bef9SDimitry Andric               *target_definition_sp, GetTarget().GetArchitecture()) > 0) {
3640b57cec5SDimitry Andric         return true;
3650b57cec5SDimitry Andric       }
3660b57cec5SDimitry Andric     }
3670b57cec5SDimitry Andric   }
3680b57cec5SDimitry Andric   return false;
3690b57cec5SDimitry Andric }
3700b57cec5SDimitry Andric 
3710b57cec5SDimitry Andric static size_t SplitCommaSeparatedRegisterNumberString(
372349cc55cSDimitry Andric     const llvm::StringRef &comma_separated_register_numbers,
3730b57cec5SDimitry Andric     std::vector<uint32_t> &regnums, int base) {
3740b57cec5SDimitry Andric   regnums.clear();
375349cc55cSDimitry Andric   for (llvm::StringRef x : llvm::split(comma_separated_register_numbers, ',')) {
376349cc55cSDimitry Andric     uint32_t reg;
377349cc55cSDimitry Andric     if (llvm::to_integer(x, reg, base))
3780b57cec5SDimitry Andric       regnums.push_back(reg);
3790b57cec5SDimitry Andric   }
3800b57cec5SDimitry Andric   return regnums.size();
3810b57cec5SDimitry Andric }
3820b57cec5SDimitry Andric 
3830b57cec5SDimitry Andric void ProcessGDBRemote::BuildDynamicRegisterInfo(bool force) {
384e8d8bef9SDimitry Andric   if (!force && m_register_info_sp)
3850b57cec5SDimitry Andric     return;
3860b57cec5SDimitry Andric 
387e8d8bef9SDimitry Andric   m_register_info_sp = std::make_shared<GDBRemoteDynamicRegisterInfo>();
3880b57cec5SDimitry Andric 
3890b57cec5SDimitry Andric   // Check if qHostInfo specified a specific packet timeout for this
3900b57cec5SDimitry Andric   // connection. If so then lets update our setting so the user knows what the
3910b57cec5SDimitry Andric   // timeout is and can see it.
3920b57cec5SDimitry Andric   const auto host_packet_timeout = m_gdb_comm.GetHostDefaultPacketTimeout();
3930b57cec5SDimitry Andric   if (host_packet_timeout > std::chrono::seconds(0)) {
394349cc55cSDimitry Andric     GetGlobalPluginProperties().SetPacketTimeout(host_packet_timeout.count());
3950b57cec5SDimitry Andric   }
3960b57cec5SDimitry Andric 
3970b57cec5SDimitry Andric   // Register info search order:
3980b57cec5SDimitry Andric   //     1 - Use the target definition python file if one is specified.
3990b57cec5SDimitry Andric   //     2 - If the target definition doesn't have any of the info from the
4000b57cec5SDimitry Andric   //     target.xml (registers) then proceed to read the target.xml.
4010b57cec5SDimitry Andric   //     3 - Fall back on the qRegisterInfo packets.
40204eeddc0SDimitry Andric   //     4 - Use hardcoded defaults if available.
4030b57cec5SDimitry Andric 
4040b57cec5SDimitry Andric   FileSpec target_definition_fspec =
405349cc55cSDimitry Andric       GetGlobalPluginProperties().GetTargetDefinitionFile();
4060b57cec5SDimitry Andric   if (!FileSystem::Instance().Exists(target_definition_fspec)) {
4070b57cec5SDimitry Andric     // If the filename doesn't exist, it may be a ~ not having been expanded -
4080b57cec5SDimitry Andric     // try to resolve it.
4090b57cec5SDimitry Andric     FileSystem::Instance().Resolve(target_definition_fspec);
4100b57cec5SDimitry Andric   }
4110b57cec5SDimitry Andric   if (target_definition_fspec) {
4120b57cec5SDimitry Andric     // See if we can get register definitions from a python file
413*81ad6265SDimitry Andric     if (ParsePythonTargetDefinition(target_definition_fspec))
4140b57cec5SDimitry Andric       return;
415*81ad6265SDimitry Andric 
416*81ad6265SDimitry Andric     Debugger::ReportError("target description file " +
417*81ad6265SDimitry Andric                               target_definition_fspec.GetPath() +
418*81ad6265SDimitry Andric                               " failed to parse",
419*81ad6265SDimitry Andric                           GetTarget().GetDebugger().GetID());
4200b57cec5SDimitry Andric   }
4210b57cec5SDimitry Andric 
4220b57cec5SDimitry Andric   const ArchSpec &target_arch = GetTarget().GetArchitecture();
4230b57cec5SDimitry Andric   const ArchSpec &remote_host_arch = m_gdb_comm.GetHostArchitecture();
4240b57cec5SDimitry Andric   const ArchSpec &remote_process_arch = m_gdb_comm.GetProcessArchitecture();
4250b57cec5SDimitry Andric 
4260b57cec5SDimitry Andric   // Use the process' architecture instead of the host arch, if available
4270b57cec5SDimitry Andric   ArchSpec arch_to_use;
4280b57cec5SDimitry Andric   if (remote_process_arch.IsValid())
4290b57cec5SDimitry Andric     arch_to_use = remote_process_arch;
4300b57cec5SDimitry Andric   else
4310b57cec5SDimitry Andric     arch_to_use = remote_host_arch;
4320b57cec5SDimitry Andric 
4330b57cec5SDimitry Andric   if (!arch_to_use.IsValid())
4340b57cec5SDimitry Andric     arch_to_use = target_arch;
4350b57cec5SDimitry Andric 
4360b57cec5SDimitry Andric   if (GetGDBServerRegisterInfo(arch_to_use))
4370b57cec5SDimitry Andric     return;
4380b57cec5SDimitry Andric 
4390b57cec5SDimitry Andric   char packet[128];
440349cc55cSDimitry Andric   std::vector<DynamicRegisterInfo::Register> registers;
4410b57cec5SDimitry Andric   uint32_t reg_num = 0;
4420b57cec5SDimitry Andric   for (StringExtractorGDBRemote::ResponseType response_type =
4430b57cec5SDimitry Andric            StringExtractorGDBRemote::eResponse;
4440b57cec5SDimitry Andric        response_type == StringExtractorGDBRemote::eResponse; ++reg_num) {
4450b57cec5SDimitry Andric     const int packet_len =
4460b57cec5SDimitry Andric         ::snprintf(packet, sizeof(packet), "qRegisterInfo%x", reg_num);
4470b57cec5SDimitry Andric     assert(packet_len < (int)sizeof(packet));
4480b57cec5SDimitry Andric     UNUSED_IF_ASSERT_DISABLED(packet_len);
4490b57cec5SDimitry Andric     StringExtractorGDBRemote response;
450fe6060f1SDimitry Andric     if (m_gdb_comm.SendPacketAndWaitForResponse(packet, response) ==
4510b57cec5SDimitry Andric         GDBRemoteCommunication::PacketResult::Success) {
4520b57cec5SDimitry Andric       response_type = response.GetResponseType();
4530b57cec5SDimitry Andric       if (response_type == StringExtractorGDBRemote::eResponse) {
4540b57cec5SDimitry Andric         llvm::StringRef name;
4550b57cec5SDimitry Andric         llvm::StringRef value;
456349cc55cSDimitry Andric         DynamicRegisterInfo::Register reg_info;
4570b57cec5SDimitry Andric 
4580b57cec5SDimitry Andric         while (response.GetNameColonValue(name, value)) {
4590b57cec5SDimitry Andric           if (name.equals("name")) {
460349cc55cSDimitry Andric             reg_info.name.SetString(value);
4610b57cec5SDimitry Andric           } else if (name.equals("alt-name")) {
462349cc55cSDimitry Andric             reg_info.alt_name.SetString(value);
4630b57cec5SDimitry Andric           } else if (name.equals("bitsize")) {
464349cc55cSDimitry Andric             if (!value.getAsInteger(0, reg_info.byte_size))
4650b57cec5SDimitry Andric               reg_info.byte_size /= CHAR_BIT;
4660b57cec5SDimitry Andric           } else if (name.equals("offset")) {
467349cc55cSDimitry Andric             value.getAsInteger(0, reg_info.byte_offset);
4680b57cec5SDimitry Andric           } else if (name.equals("encoding")) {
4690b57cec5SDimitry Andric             const Encoding encoding = Args::StringToEncoding(value);
4700b57cec5SDimitry Andric             if (encoding != eEncodingInvalid)
4710b57cec5SDimitry Andric               reg_info.encoding = encoding;
4720b57cec5SDimitry Andric           } else if (name.equals("format")) {
473349cc55cSDimitry Andric             if (!OptionArgParser::ToFormat(value.str().c_str(), reg_info.format, nullptr)
4740b57cec5SDimitry Andric                     .Success())
4750b57cec5SDimitry Andric               reg_info.format =
4760b57cec5SDimitry Andric                   llvm::StringSwitch<Format>(value)
4770b57cec5SDimitry Andric                       .Case("binary", eFormatBinary)
4780b57cec5SDimitry Andric                       .Case("decimal", eFormatDecimal)
4790b57cec5SDimitry Andric                       .Case("hex", eFormatHex)
4800b57cec5SDimitry Andric                       .Case("float", eFormatFloat)
4810b57cec5SDimitry Andric                       .Case("vector-sint8", eFormatVectorOfSInt8)
4820b57cec5SDimitry Andric                       .Case("vector-uint8", eFormatVectorOfUInt8)
4830b57cec5SDimitry Andric                       .Case("vector-sint16", eFormatVectorOfSInt16)
4840b57cec5SDimitry Andric                       .Case("vector-uint16", eFormatVectorOfUInt16)
4850b57cec5SDimitry Andric                       .Case("vector-sint32", eFormatVectorOfSInt32)
4860b57cec5SDimitry Andric                       .Case("vector-uint32", eFormatVectorOfUInt32)
4870b57cec5SDimitry Andric                       .Case("vector-float32", eFormatVectorOfFloat32)
4880b57cec5SDimitry Andric                       .Case("vector-uint64", eFormatVectorOfUInt64)
4890b57cec5SDimitry Andric                       .Case("vector-uint128", eFormatVectorOfUInt128)
4900b57cec5SDimitry Andric                       .Default(eFormatInvalid);
4910b57cec5SDimitry Andric           } else if (name.equals("set")) {
492349cc55cSDimitry Andric             reg_info.set_name.SetString(value);
4930b57cec5SDimitry Andric           } else if (name.equals("gcc") || name.equals("ehframe")) {
494349cc55cSDimitry Andric             value.getAsInteger(0, reg_info.regnum_ehframe);
4950b57cec5SDimitry Andric           } else if (name.equals("dwarf")) {
496349cc55cSDimitry Andric             value.getAsInteger(0, reg_info.regnum_dwarf);
4970b57cec5SDimitry Andric           } else if (name.equals("generic")) {
498349cc55cSDimitry Andric             reg_info.regnum_generic = Args::StringToGenericRegister(value);
4990b57cec5SDimitry Andric           } else if (name.equals("container-regs")) {
500349cc55cSDimitry Andric             SplitCommaSeparatedRegisterNumberString(value, reg_info.value_regs, 16);
5010b57cec5SDimitry Andric           } else if (name.equals("invalidate-regs")) {
502349cc55cSDimitry Andric             SplitCommaSeparatedRegisterNumberString(value, reg_info.invalidate_regs, 16);
5030b57cec5SDimitry Andric           }
5040b57cec5SDimitry Andric         }
5050b57cec5SDimitry Andric 
5060b57cec5SDimitry Andric         assert(reg_info.byte_size != 0);
507349cc55cSDimitry Andric         registers.push_back(reg_info);
5080b57cec5SDimitry Andric       } else {
5090b57cec5SDimitry Andric         break; // ensure exit before reg_num is incremented
5100b57cec5SDimitry Andric       }
5110b57cec5SDimitry Andric     } else {
5120b57cec5SDimitry Andric       break;
5130b57cec5SDimitry Andric     }
5140b57cec5SDimitry Andric   }
5150b57cec5SDimitry Andric 
51604eeddc0SDimitry Andric   if (registers.empty())
51704eeddc0SDimitry Andric     registers = GetFallbackRegisters(arch_to_use);
51804eeddc0SDimitry Andric 
519349cc55cSDimitry Andric   AddRemoteRegisters(registers, arch_to_use);
5200b57cec5SDimitry Andric }
5210b57cec5SDimitry Andric 
5220b57cec5SDimitry Andric Status ProcessGDBRemote::WillLaunch(lldb_private::Module *module) {
5230b57cec5SDimitry Andric   return WillLaunchOrAttach();
5240b57cec5SDimitry Andric }
5250b57cec5SDimitry Andric 
5260b57cec5SDimitry Andric Status ProcessGDBRemote::WillAttachToProcessWithID(lldb::pid_t pid) {
5270b57cec5SDimitry Andric   return WillLaunchOrAttach();
5280b57cec5SDimitry Andric }
5290b57cec5SDimitry Andric 
5300b57cec5SDimitry Andric Status ProcessGDBRemote::WillAttachToProcessWithName(const char *process_name,
5310b57cec5SDimitry Andric                                                      bool wait_for_launch) {
5320b57cec5SDimitry Andric   return WillLaunchOrAttach();
5330b57cec5SDimitry Andric }
5340b57cec5SDimitry Andric 
5355ffd83dbSDimitry Andric Status ProcessGDBRemote::DoConnectRemote(llvm::StringRef remote_url) {
53604eeddc0SDimitry Andric   Log *log = GetLog(GDBRLog::Process);
5370eae32dcSDimitry Andric 
5380b57cec5SDimitry Andric   Status error(WillLaunchOrAttach());
5390b57cec5SDimitry Andric   if (error.Fail())
5400b57cec5SDimitry Andric     return error;
5410b57cec5SDimitry Andric 
5420b57cec5SDimitry Andric   error = ConnectToDebugserver(remote_url);
5430b57cec5SDimitry Andric   if (error.Fail())
5440b57cec5SDimitry Andric     return error;
5450eae32dcSDimitry Andric 
5460b57cec5SDimitry Andric   StartAsyncThread();
5470b57cec5SDimitry Andric 
5480b57cec5SDimitry Andric   lldb::pid_t pid = m_gdb_comm.GetCurrentProcessID();
5490b57cec5SDimitry Andric   if (pid == LLDB_INVALID_PROCESS_ID) {
5500b57cec5SDimitry Andric     // We don't have a valid process ID, so note that we are connected and
5510b57cec5SDimitry Andric     // could now request to launch or attach, or get remote process listings...
5520b57cec5SDimitry Andric     SetPrivateState(eStateConnected);
5530b57cec5SDimitry Andric   } else {
5540b57cec5SDimitry Andric     // We have a valid process
5550b57cec5SDimitry Andric     SetID(pid);
5560b57cec5SDimitry Andric     GetThreadList();
5570b57cec5SDimitry Andric     StringExtractorGDBRemote response;
5580b57cec5SDimitry Andric     if (m_gdb_comm.GetStopReply(response)) {
5590b57cec5SDimitry Andric       SetLastStopPacket(response);
5600b57cec5SDimitry Andric 
5610b57cec5SDimitry Andric       Target &target = GetTarget();
5620b57cec5SDimitry Andric       if (!target.GetArchitecture().IsValid()) {
5630b57cec5SDimitry Andric         if (m_gdb_comm.GetProcessArchitecture().IsValid()) {
5640b57cec5SDimitry Andric           target.SetArchitecture(m_gdb_comm.GetProcessArchitecture());
5650b57cec5SDimitry Andric         } else {
5660b57cec5SDimitry Andric           if (m_gdb_comm.GetHostArchitecture().IsValid()) {
5670b57cec5SDimitry Andric             target.SetArchitecture(m_gdb_comm.GetHostArchitecture());
5680b57cec5SDimitry Andric           }
5690b57cec5SDimitry Andric         }
5700b57cec5SDimitry Andric       }
5710b57cec5SDimitry Andric 
5720eae32dcSDimitry Andric       // The remote stub may know about the "main binary" in
5730eae32dcSDimitry Andric       // the context of a firmware debug session, and can
5740eae32dcSDimitry Andric       // give us a UUID and an address/slide of where the
5750eae32dcSDimitry Andric       // binary is loaded in memory.
5760eae32dcSDimitry Andric       UUID standalone_uuid;
5770eae32dcSDimitry Andric       addr_t standalone_value;
5780eae32dcSDimitry Andric       bool standalone_value_is_offset;
5790eae32dcSDimitry Andric       if (m_gdb_comm.GetProcessStandaloneBinary(
5800eae32dcSDimitry Andric               standalone_uuid, standalone_value, standalone_value_is_offset)) {
5810eae32dcSDimitry Andric         ModuleSP module_sp;
5820eae32dcSDimitry Andric 
5830eae32dcSDimitry Andric         if (standalone_uuid.IsValid()) {
5840eae32dcSDimitry Andric           ModuleSpec module_spec;
5850eae32dcSDimitry Andric           module_spec.GetUUID() = standalone_uuid;
5860eae32dcSDimitry Andric 
5870eae32dcSDimitry Andric           // Look up UUID in global module cache before attempting
5880eae32dcSDimitry Andric           // a more expensive search.
5890eae32dcSDimitry Andric           Status error = ModuleList::GetSharedModule(module_spec, module_sp,
5900eae32dcSDimitry Andric                                                      nullptr, nullptr, nullptr);
5910eae32dcSDimitry Andric 
5920eae32dcSDimitry Andric           if (!module_sp) {
5930eae32dcSDimitry Andric             // Force a an external lookup, if that tool is available.
594*81ad6265SDimitry Andric             if (!module_spec.GetSymbolFileSpec()) {
595*81ad6265SDimitry Andric               Status error;
596*81ad6265SDimitry Andric               Symbols::DownloadObjectAndSymbolFile(module_spec, error, true);
597*81ad6265SDimitry Andric             }
5980eae32dcSDimitry Andric 
5990eae32dcSDimitry Andric             if (FileSystem::Instance().Exists(module_spec.GetFileSpec())) {
6000eae32dcSDimitry Andric               module_sp = std::make_shared<Module>(module_spec);
6010eae32dcSDimitry Andric             }
6020eae32dcSDimitry Andric           }
6030eae32dcSDimitry Andric 
6040eae32dcSDimitry Andric           // If we couldn't find the binary anywhere else, as a last resort,
6050eae32dcSDimitry Andric           // read it out of memory.
6060eae32dcSDimitry Andric           if (!module_sp.get() && standalone_value != LLDB_INVALID_ADDRESS &&
6070eae32dcSDimitry Andric               !standalone_value_is_offset) {
6080eae32dcSDimitry Andric             char namebuf[80];
6090eae32dcSDimitry Andric             snprintf(namebuf, sizeof(namebuf), "mem-image-0x%" PRIx64,
6100eae32dcSDimitry Andric                      standalone_value);
6110eae32dcSDimitry Andric             module_sp =
6120eae32dcSDimitry Andric                 ReadModuleFromMemory(FileSpec(namebuf), standalone_value);
6130eae32dcSDimitry Andric           }
6140eae32dcSDimitry Andric 
615*81ad6265SDimitry Andric           Log *log = GetLog(LLDBLog::DynamicLoader);
6160eae32dcSDimitry Andric           if (module_sp.get()) {
6170eae32dcSDimitry Andric             target.GetImages().AppendIfNeeded(module_sp, false);
6180eae32dcSDimitry Andric 
6190eae32dcSDimitry Andric             bool changed = false;
6200eae32dcSDimitry Andric             if (module_sp->GetObjectFile()) {
6210eae32dcSDimitry Andric               if (standalone_value != LLDB_INVALID_ADDRESS) {
6220eae32dcSDimitry Andric                 if (log)
6230eae32dcSDimitry Andric                   log->Printf("Loading binary UUID %s at %s 0x%" PRIx64,
6240eae32dcSDimitry Andric                               standalone_uuid.GetAsString().c_str(),
6250eae32dcSDimitry Andric                               standalone_value_is_offset ? "offset" : "address",
6260eae32dcSDimitry Andric                               standalone_value);
6270eae32dcSDimitry Andric                 module_sp->SetLoadAddress(target, standalone_value,
6280eae32dcSDimitry Andric                                           standalone_value_is_offset, changed);
6290eae32dcSDimitry Andric               } else {
6300eae32dcSDimitry Andric                 // No address/offset/slide, load the binary at file address,
6310eae32dcSDimitry Andric                 // offset 0.
6320eae32dcSDimitry Andric                 if (log)
6330eae32dcSDimitry Andric                   log->Printf("Loading binary UUID %s at file address",
6340eae32dcSDimitry Andric                               standalone_uuid.GetAsString().c_str());
6350eae32dcSDimitry Andric                 const bool value_is_slide = true;
6360eae32dcSDimitry Andric                 module_sp->SetLoadAddress(target, 0, value_is_slide, changed);
6370eae32dcSDimitry Andric               }
6380eae32dcSDimitry Andric             } else {
6390eae32dcSDimitry Andric               // In-memory image, load at its true address, offset 0.
6400eae32dcSDimitry Andric               if (log)
6410eae32dcSDimitry Andric                 log->Printf("Loading binary UUID %s from memory",
6420eae32dcSDimitry Andric                             standalone_uuid.GetAsString().c_str());
6430eae32dcSDimitry Andric               const bool value_is_slide = true;
6440eae32dcSDimitry Andric               module_sp->SetLoadAddress(target, 0, value_is_slide, changed);
6450eae32dcSDimitry Andric             }
6460eae32dcSDimitry Andric 
6470eae32dcSDimitry Andric             ModuleList added_module;
6480eae32dcSDimitry Andric             added_module.Append(module_sp, false);
6490eae32dcSDimitry Andric             target.ModulesDidLoad(added_module);
6500eae32dcSDimitry Andric           } else {
6510eae32dcSDimitry Andric             if (log)
6520eae32dcSDimitry Andric               log->Printf("Unable to find binary with UUID %s and load it at "
6530eae32dcSDimitry Andric                           "%s 0x%" PRIx64,
6540eae32dcSDimitry Andric                           standalone_uuid.GetAsString().c_str(),
6550eae32dcSDimitry Andric                           standalone_value_is_offset ? "offset" : "address",
6560eae32dcSDimitry Andric                           standalone_value);
6570eae32dcSDimitry Andric           }
6580eae32dcSDimitry Andric         }
6590eae32dcSDimitry Andric       }
6600eae32dcSDimitry Andric 
6610b57cec5SDimitry Andric       const StateType state = SetThreadStopInfo(response);
6620b57cec5SDimitry Andric       if (state != eStateInvalid) {
6630b57cec5SDimitry Andric         SetPrivateState(state);
6640b57cec5SDimitry Andric       } else
6650b57cec5SDimitry Andric         error.SetErrorStringWithFormat(
6660b57cec5SDimitry Andric             "Process %" PRIu64 " was reported after connecting to "
6670b57cec5SDimitry Andric             "'%s', but state was not stopped: %s",
6680b57cec5SDimitry Andric             pid, remote_url.str().c_str(), StateAsCString(state));
6690b57cec5SDimitry Andric     } else
6700b57cec5SDimitry Andric       error.SetErrorStringWithFormat("Process %" PRIu64
6710b57cec5SDimitry Andric                                      " was reported after connecting to '%s', "
6720b57cec5SDimitry Andric                                      "but no stop reply packet was received",
6730b57cec5SDimitry Andric                                      pid, remote_url.str().c_str());
6740b57cec5SDimitry Andric   }
6750b57cec5SDimitry Andric 
6769dba64beSDimitry Andric   LLDB_LOGF(log,
6779dba64beSDimitry Andric             "ProcessGDBRemote::%s pid %" PRIu64
6780b57cec5SDimitry Andric             ": normalizing target architecture initial triple: %s "
6790b57cec5SDimitry Andric             "(GetTarget().GetArchitecture().IsValid() %s, "
6800b57cec5SDimitry Andric             "m_gdb_comm.GetHostArchitecture().IsValid(): %s)",
6810b57cec5SDimitry Andric             __FUNCTION__, GetID(),
6820b57cec5SDimitry Andric             GetTarget().GetArchitecture().GetTriple().getTriple().c_str(),
6830b57cec5SDimitry Andric             GetTarget().GetArchitecture().IsValid() ? "true" : "false",
6840b57cec5SDimitry Andric             m_gdb_comm.GetHostArchitecture().IsValid() ? "true" : "false");
6850b57cec5SDimitry Andric 
6860b57cec5SDimitry Andric   if (error.Success() && !GetTarget().GetArchitecture().IsValid() &&
6870b57cec5SDimitry Andric       m_gdb_comm.GetHostArchitecture().IsValid()) {
6880b57cec5SDimitry Andric     // Prefer the *process'* architecture over that of the *host*, if
6890b57cec5SDimitry Andric     // available.
6900b57cec5SDimitry Andric     if (m_gdb_comm.GetProcessArchitecture().IsValid())
6910b57cec5SDimitry Andric       GetTarget().SetArchitecture(m_gdb_comm.GetProcessArchitecture());
6920b57cec5SDimitry Andric     else
6930b57cec5SDimitry Andric       GetTarget().SetArchitecture(m_gdb_comm.GetHostArchitecture());
6940b57cec5SDimitry Andric   }
6950b57cec5SDimitry Andric 
6969dba64beSDimitry Andric   LLDB_LOGF(log,
6979dba64beSDimitry Andric             "ProcessGDBRemote::%s pid %" PRIu64
6980b57cec5SDimitry Andric             ": normalized target architecture triple: %s",
6990b57cec5SDimitry Andric             __FUNCTION__, GetID(),
7000b57cec5SDimitry Andric             GetTarget().GetArchitecture().GetTriple().getTriple().c_str());
7010b57cec5SDimitry Andric 
7020b57cec5SDimitry Andric   return error;
7030b57cec5SDimitry Andric }
7040b57cec5SDimitry Andric 
7050b57cec5SDimitry Andric Status ProcessGDBRemote::WillLaunchOrAttach() {
7060b57cec5SDimitry Andric   Status error;
7070b57cec5SDimitry Andric   m_stdio_communication.Clear();
7080b57cec5SDimitry Andric   return error;
7090b57cec5SDimitry Andric }
7100b57cec5SDimitry Andric 
7110b57cec5SDimitry Andric // Process Control
7120b57cec5SDimitry Andric Status ProcessGDBRemote::DoLaunch(lldb_private::Module *exe_module,
7130b57cec5SDimitry Andric                                   ProcessLaunchInfo &launch_info) {
7141fd87a68SDimitry Andric   Log *log = GetLog(GDBRLog::Process);
7150b57cec5SDimitry Andric   Status error;
7160b57cec5SDimitry Andric 
7179dba64beSDimitry Andric   LLDB_LOGF(log, "ProcessGDBRemote::%s() entered", __FUNCTION__);
7180b57cec5SDimitry Andric 
7190b57cec5SDimitry Andric   uint32_t launch_flags = launch_info.GetFlags().Get();
7200b57cec5SDimitry Andric   FileSpec stdin_file_spec{};
7210b57cec5SDimitry Andric   FileSpec stdout_file_spec{};
7220b57cec5SDimitry Andric   FileSpec stderr_file_spec{};
7230b57cec5SDimitry Andric   FileSpec working_dir = launch_info.GetWorkingDirectory();
7240b57cec5SDimitry Andric 
7250b57cec5SDimitry Andric   const FileAction *file_action;
7260b57cec5SDimitry Andric   file_action = launch_info.GetFileActionForFD(STDIN_FILENO);
7270b57cec5SDimitry Andric   if (file_action) {
7280b57cec5SDimitry Andric     if (file_action->GetAction() == FileAction::eFileActionOpen)
7290b57cec5SDimitry Andric       stdin_file_spec = file_action->GetFileSpec();
7300b57cec5SDimitry Andric   }
7310b57cec5SDimitry Andric   file_action = launch_info.GetFileActionForFD(STDOUT_FILENO);
7320b57cec5SDimitry Andric   if (file_action) {
7330b57cec5SDimitry Andric     if (file_action->GetAction() == FileAction::eFileActionOpen)
7340b57cec5SDimitry Andric       stdout_file_spec = file_action->GetFileSpec();
7350b57cec5SDimitry Andric   }
7360b57cec5SDimitry Andric   file_action = launch_info.GetFileActionForFD(STDERR_FILENO);
7370b57cec5SDimitry Andric   if (file_action) {
7380b57cec5SDimitry Andric     if (file_action->GetAction() == FileAction::eFileActionOpen)
7390b57cec5SDimitry Andric       stderr_file_spec = file_action->GetFileSpec();
7400b57cec5SDimitry Andric   }
7410b57cec5SDimitry Andric 
7420b57cec5SDimitry Andric   if (log) {
7430b57cec5SDimitry Andric     if (stdin_file_spec || stdout_file_spec || stderr_file_spec)
7449dba64beSDimitry Andric       LLDB_LOGF(log,
7459dba64beSDimitry Andric                 "ProcessGDBRemote::%s provided with STDIO paths via "
7460b57cec5SDimitry Andric                 "launch_info: stdin=%s, stdout=%s, stderr=%s",
7470b57cec5SDimitry Andric                 __FUNCTION__,
7480b57cec5SDimitry Andric                 stdin_file_spec ? stdin_file_spec.GetCString() : "<null>",
7490b57cec5SDimitry Andric                 stdout_file_spec ? stdout_file_spec.GetCString() : "<null>",
7500b57cec5SDimitry Andric                 stderr_file_spec ? stderr_file_spec.GetCString() : "<null>");
7510b57cec5SDimitry Andric     else
7529dba64beSDimitry Andric       LLDB_LOGF(log,
7539dba64beSDimitry Andric                 "ProcessGDBRemote::%s no STDIO paths given via launch_info",
7540b57cec5SDimitry Andric                 __FUNCTION__);
7550b57cec5SDimitry Andric   }
7560b57cec5SDimitry Andric 
7570b57cec5SDimitry Andric   const bool disable_stdio = (launch_flags & eLaunchFlagDisableSTDIO) != 0;
7580b57cec5SDimitry Andric   if (stdin_file_spec || disable_stdio) {
7590b57cec5SDimitry Andric     // the inferior will be reading stdin from the specified file or stdio is
7600b57cec5SDimitry Andric     // completely disabled
7610b57cec5SDimitry Andric     m_stdin_forward = false;
7620b57cec5SDimitry Andric   } else {
7630b57cec5SDimitry Andric     m_stdin_forward = true;
7640b57cec5SDimitry Andric   }
7650b57cec5SDimitry Andric 
7660b57cec5SDimitry Andric   //  ::LogSetBitMask (GDBR_LOG_DEFAULT);
7670b57cec5SDimitry Andric   //  ::LogSetOptions (LLDB_LOG_OPTION_THREADSAFE |
7680b57cec5SDimitry Andric   //  LLDB_LOG_OPTION_PREPEND_TIMESTAMP |
7690b57cec5SDimitry Andric   //  LLDB_LOG_OPTION_PREPEND_PROC_AND_THREAD);
7700b57cec5SDimitry Andric   //  ::LogSetLogFile ("/dev/stdout");
7710b57cec5SDimitry Andric 
7720b57cec5SDimitry Andric   error = EstablishConnectionIfNeeded(launch_info);
7730b57cec5SDimitry Andric   if (error.Success()) {
7740b57cec5SDimitry Andric     PseudoTerminal pty;
7750b57cec5SDimitry Andric     const bool disable_stdio = (launch_flags & eLaunchFlagDisableSTDIO) != 0;
7760b57cec5SDimitry Andric 
7770b57cec5SDimitry Andric     PlatformSP platform_sp(GetTarget().GetPlatform());
7780b57cec5SDimitry Andric     if (disable_stdio) {
7790b57cec5SDimitry Andric       // set to /dev/null unless redirected to a file above
7800b57cec5SDimitry Andric       if (!stdin_file_spec)
7810b57cec5SDimitry Andric         stdin_file_spec.SetFile(FileSystem::DEV_NULL,
7820b57cec5SDimitry Andric                                 FileSpec::Style::native);
7830b57cec5SDimitry Andric       if (!stdout_file_spec)
7840b57cec5SDimitry Andric         stdout_file_spec.SetFile(FileSystem::DEV_NULL,
7850b57cec5SDimitry Andric                                  FileSpec::Style::native);
7860b57cec5SDimitry Andric       if (!stderr_file_spec)
7870b57cec5SDimitry Andric         stderr_file_spec.SetFile(FileSystem::DEV_NULL,
7880b57cec5SDimitry Andric                                  FileSpec::Style::native);
7890b57cec5SDimitry Andric     } else if (platform_sp && platform_sp->IsHost()) {
7900b57cec5SDimitry Andric       // If the debugserver is local and we aren't disabling STDIO, lets use
7910b57cec5SDimitry Andric       // a pseudo terminal to instead of relying on the 'O' packets for stdio
7920b57cec5SDimitry Andric       // since 'O' packets can really slow down debugging if the inferior
7930b57cec5SDimitry Andric       // does a lot of output.
7940b57cec5SDimitry Andric       if ((!stdin_file_spec || !stdout_file_spec || !stderr_file_spec) &&
795e8d8bef9SDimitry Andric           !errorToBool(pty.OpenFirstAvailablePrimary(O_RDWR | O_NOCTTY))) {
796e8d8bef9SDimitry Andric         FileSpec secondary_name(pty.GetSecondaryName());
7970b57cec5SDimitry Andric 
7980b57cec5SDimitry Andric         if (!stdin_file_spec)
7995ffd83dbSDimitry Andric           stdin_file_spec = secondary_name;
8000b57cec5SDimitry Andric 
8010b57cec5SDimitry Andric         if (!stdout_file_spec)
8025ffd83dbSDimitry Andric           stdout_file_spec = secondary_name;
8030b57cec5SDimitry Andric 
8040b57cec5SDimitry Andric         if (!stderr_file_spec)
8055ffd83dbSDimitry Andric           stderr_file_spec = secondary_name;
8060b57cec5SDimitry Andric       }
8079dba64beSDimitry Andric       LLDB_LOGF(
8089dba64beSDimitry Andric           log,
8090b57cec5SDimitry Andric           "ProcessGDBRemote::%s adjusted STDIO paths for local platform "
8105ffd83dbSDimitry Andric           "(IsHost() is true) using secondary: stdin=%s, stdout=%s, "
8115ffd83dbSDimitry Andric           "stderr=%s",
8120b57cec5SDimitry Andric           __FUNCTION__,
8130b57cec5SDimitry Andric           stdin_file_spec ? stdin_file_spec.GetCString() : "<null>",
8140b57cec5SDimitry Andric           stdout_file_spec ? stdout_file_spec.GetCString() : "<null>",
8150b57cec5SDimitry Andric           stderr_file_spec ? stderr_file_spec.GetCString() : "<null>");
8160b57cec5SDimitry Andric     }
8170b57cec5SDimitry Andric 
8189dba64beSDimitry Andric     LLDB_LOGF(log,
8199dba64beSDimitry Andric               "ProcessGDBRemote::%s final STDIO paths after all "
8200b57cec5SDimitry Andric               "adjustments: stdin=%s, stdout=%s, stderr=%s",
8210b57cec5SDimitry Andric               __FUNCTION__,
8220b57cec5SDimitry Andric               stdin_file_spec ? stdin_file_spec.GetCString() : "<null>",
8230b57cec5SDimitry Andric               stdout_file_spec ? stdout_file_spec.GetCString() : "<null>",
8249dba64beSDimitry Andric               stderr_file_spec ? stderr_file_spec.GetCString() : "<null>");
8250b57cec5SDimitry Andric 
8260b57cec5SDimitry Andric     if (stdin_file_spec)
8270b57cec5SDimitry Andric       m_gdb_comm.SetSTDIN(stdin_file_spec);
8280b57cec5SDimitry Andric     if (stdout_file_spec)
8290b57cec5SDimitry Andric       m_gdb_comm.SetSTDOUT(stdout_file_spec);
8300b57cec5SDimitry Andric     if (stderr_file_spec)
8310b57cec5SDimitry Andric       m_gdb_comm.SetSTDERR(stderr_file_spec);
8320b57cec5SDimitry Andric 
8330b57cec5SDimitry Andric     m_gdb_comm.SetDisableASLR(launch_flags & eLaunchFlagDisableASLR);
8340b57cec5SDimitry Andric     m_gdb_comm.SetDetachOnError(launch_flags & eLaunchFlagDetachOnError);
8350b57cec5SDimitry Andric 
8360b57cec5SDimitry Andric     m_gdb_comm.SendLaunchArchPacket(
8370b57cec5SDimitry Andric         GetTarget().GetArchitecture().GetArchitectureName());
8380b57cec5SDimitry Andric 
8390b57cec5SDimitry Andric     const char *launch_event_data = launch_info.GetLaunchEventData();
8400b57cec5SDimitry Andric     if (launch_event_data != nullptr && *launch_event_data != '\0')
8410b57cec5SDimitry Andric       m_gdb_comm.SendLaunchEventDataPacket(launch_event_data);
8420b57cec5SDimitry Andric 
8430b57cec5SDimitry Andric     if (working_dir) {
8440b57cec5SDimitry Andric       m_gdb_comm.SetWorkingDir(working_dir);
8450b57cec5SDimitry Andric     }
8460b57cec5SDimitry Andric 
8470b57cec5SDimitry Andric     // Send the environment and the program + arguments after we connect
8480b57cec5SDimitry Andric     m_gdb_comm.SendEnvironment(launch_info.GetEnvironment());
8490b57cec5SDimitry Andric 
8500b57cec5SDimitry Andric     {
8510b57cec5SDimitry Andric       // Scope for the scoped timeout object
8520b57cec5SDimitry Andric       GDBRemoteCommunication::ScopedTimeout timeout(m_gdb_comm,
8530b57cec5SDimitry Andric                                                     std::chrono::seconds(10));
8540b57cec5SDimitry Andric 
8550b57cec5SDimitry Andric       int arg_packet_err = m_gdb_comm.SendArgumentsPacket(launch_info);
8560b57cec5SDimitry Andric       if (arg_packet_err == 0) {
8570b57cec5SDimitry Andric         std::string error_str;
8580b57cec5SDimitry Andric         if (m_gdb_comm.GetLaunchSuccess(error_str)) {
8590b57cec5SDimitry Andric           SetID(m_gdb_comm.GetCurrentProcessID());
8600b57cec5SDimitry Andric         } else {
8610b57cec5SDimitry Andric           error.SetErrorString(error_str.c_str());
8620b57cec5SDimitry Andric         }
8630b57cec5SDimitry Andric       } else {
8640b57cec5SDimitry Andric         error.SetErrorStringWithFormat("'A' packet returned an error: %i",
8650b57cec5SDimitry Andric                                        arg_packet_err);
8660b57cec5SDimitry Andric       }
8670b57cec5SDimitry Andric     }
8680b57cec5SDimitry Andric 
8690b57cec5SDimitry Andric     if (GetID() == LLDB_INVALID_PROCESS_ID) {
8709dba64beSDimitry Andric       LLDB_LOGF(log, "failed to connect to debugserver: %s",
8710b57cec5SDimitry Andric                 error.AsCString());
8720b57cec5SDimitry Andric       KillDebugserverProcess();
8730b57cec5SDimitry Andric       return error;
8740b57cec5SDimitry Andric     }
8750b57cec5SDimitry Andric 
8760b57cec5SDimitry Andric     StringExtractorGDBRemote response;
8770b57cec5SDimitry Andric     if (m_gdb_comm.GetStopReply(response)) {
8780b57cec5SDimitry Andric       SetLastStopPacket(response);
8790b57cec5SDimitry Andric 
8800b57cec5SDimitry Andric       const ArchSpec &process_arch = m_gdb_comm.GetProcessArchitecture();
8810b57cec5SDimitry Andric 
8820b57cec5SDimitry Andric       if (process_arch.IsValid()) {
8830b57cec5SDimitry Andric         GetTarget().MergeArchitecture(process_arch);
8840b57cec5SDimitry Andric       } else {
8850b57cec5SDimitry Andric         const ArchSpec &host_arch = m_gdb_comm.GetHostArchitecture();
8860b57cec5SDimitry Andric         if (host_arch.IsValid())
8870b57cec5SDimitry Andric           GetTarget().MergeArchitecture(host_arch);
8880b57cec5SDimitry Andric       }
8890b57cec5SDimitry Andric 
8900b57cec5SDimitry Andric       SetPrivateState(SetThreadStopInfo(response));
8910b57cec5SDimitry Andric 
8920b57cec5SDimitry Andric       if (!disable_stdio) {
8935ffd83dbSDimitry Andric         if (pty.GetPrimaryFileDescriptor() != PseudoTerminal::invalid_fd)
8945ffd83dbSDimitry Andric           SetSTDIOFileDescriptor(pty.ReleasePrimaryFileDescriptor());
8950b57cec5SDimitry Andric       }
8960b57cec5SDimitry Andric     }
8970b57cec5SDimitry Andric   } else {
8989dba64beSDimitry Andric     LLDB_LOGF(log, "failed to connect to debugserver: %s", error.AsCString());
8990b57cec5SDimitry Andric   }
9000b57cec5SDimitry Andric   return error;
9010b57cec5SDimitry Andric }
9020b57cec5SDimitry Andric 
9030b57cec5SDimitry Andric Status ProcessGDBRemote::ConnectToDebugserver(llvm::StringRef connect_url) {
9040b57cec5SDimitry Andric   Status error;
9050b57cec5SDimitry Andric   // Only connect if we have a valid connect URL
9061fd87a68SDimitry Andric   Log *log = GetLog(GDBRLog::Process);
9070b57cec5SDimitry Andric 
9080b57cec5SDimitry Andric   if (!connect_url.empty()) {
9099dba64beSDimitry Andric     LLDB_LOGF(log, "ProcessGDBRemote::%s Connecting to %s", __FUNCTION__,
9100b57cec5SDimitry Andric               connect_url.str().c_str());
9110b57cec5SDimitry Andric     std::unique_ptr<ConnectionFileDescriptor> conn_up(
9120b57cec5SDimitry Andric         new ConnectionFileDescriptor());
9130b57cec5SDimitry Andric     if (conn_up) {
9140b57cec5SDimitry Andric       const uint32_t max_retry_count = 50;
9150b57cec5SDimitry Andric       uint32_t retry_count = 0;
9160b57cec5SDimitry Andric       while (!m_gdb_comm.IsConnected()) {
9170b57cec5SDimitry Andric         if (conn_up->Connect(connect_url, &error) == eConnectionStatusSuccess) {
9185ffd83dbSDimitry Andric           m_gdb_comm.SetConnection(std::move(conn_up));
9190b57cec5SDimitry Andric           break;
9200b57cec5SDimitry Andric         }
9210b57cec5SDimitry Andric 
9220b57cec5SDimitry Andric         retry_count++;
9230b57cec5SDimitry Andric 
9240b57cec5SDimitry Andric         if (retry_count >= max_retry_count)
9250b57cec5SDimitry Andric           break;
9260b57cec5SDimitry Andric 
9279dba64beSDimitry Andric         std::this_thread::sleep_for(std::chrono::milliseconds(100));
9280b57cec5SDimitry Andric       }
9290b57cec5SDimitry Andric     }
9300b57cec5SDimitry Andric   }
9310b57cec5SDimitry Andric 
9320b57cec5SDimitry Andric   if (!m_gdb_comm.IsConnected()) {
9330b57cec5SDimitry Andric     if (error.Success())
9340b57cec5SDimitry Andric       error.SetErrorString("not connected to remote gdb server");
9350b57cec5SDimitry Andric     return error;
9360b57cec5SDimitry Andric   }
9370b57cec5SDimitry Andric 
9380b57cec5SDimitry Andric   // We always seem to be able to open a connection to a local port so we need
9390b57cec5SDimitry Andric   // to make sure we can then send data to it. If we can't then we aren't
9400b57cec5SDimitry Andric   // actually connected to anything, so try and do the handshake with the
9410b57cec5SDimitry Andric   // remote GDB server and make sure that goes alright.
9420b57cec5SDimitry Andric   if (!m_gdb_comm.HandshakeWithServer(&error)) {
9430b57cec5SDimitry Andric     m_gdb_comm.Disconnect();
9440b57cec5SDimitry Andric     if (error.Success())
9450b57cec5SDimitry Andric       error.SetErrorString("not connected to remote gdb server");
9460b57cec5SDimitry Andric     return error;
9470b57cec5SDimitry Andric   }
9480b57cec5SDimitry Andric 
9490b57cec5SDimitry Andric   m_gdb_comm.GetEchoSupported();
9500b57cec5SDimitry Andric   m_gdb_comm.GetThreadSuffixSupported();
9510b57cec5SDimitry Andric   m_gdb_comm.GetListThreadsInStopReplySupported();
9520b57cec5SDimitry Andric   m_gdb_comm.GetHostInfo();
9530b57cec5SDimitry Andric   m_gdb_comm.GetVContSupported('c');
9540b57cec5SDimitry Andric   m_gdb_comm.GetVAttachOrWaitSupported();
9550b57cec5SDimitry Andric   m_gdb_comm.EnableErrorStringInPacket();
9560b57cec5SDimitry Andric 
957*81ad6265SDimitry Andric   // First dispatch any commands from the platform:
958*81ad6265SDimitry Andric   auto handle_cmds = [&] (const Args &args) ->  void {
959*81ad6265SDimitry Andric     for (const Args::ArgEntry &entry : args) {
9600b57cec5SDimitry Andric       StringExtractorGDBRemote response;
9610b57cec5SDimitry Andric       m_gdb_comm.SendPacketAndWaitForResponse(
962*81ad6265SDimitry Andric           entry.c_str(), response);
9630b57cec5SDimitry Andric     }
964*81ad6265SDimitry Andric   };
965*81ad6265SDimitry Andric 
966*81ad6265SDimitry Andric   PlatformSP platform_sp = GetTarget().GetPlatform();
967*81ad6265SDimitry Andric   if (platform_sp) {
968*81ad6265SDimitry Andric     handle_cmds(platform_sp->GetExtraStartupCommands());
969*81ad6265SDimitry Andric   }
970*81ad6265SDimitry Andric 
971*81ad6265SDimitry Andric   // Then dispatch any process commands:
972*81ad6265SDimitry Andric   handle_cmds(GetExtraStartupCommands());
973*81ad6265SDimitry Andric 
9740b57cec5SDimitry Andric   return error;
9750b57cec5SDimitry Andric }
9760b57cec5SDimitry Andric 
9770b57cec5SDimitry Andric void ProcessGDBRemote::DidLaunchOrAttach(ArchSpec &process_arch) {
9781fd87a68SDimitry Andric   Log *log = GetLog(GDBRLog::Process);
9790b57cec5SDimitry Andric   BuildDynamicRegisterInfo(false);
9800b57cec5SDimitry Andric 
9815ffd83dbSDimitry Andric   // See if the GDB server supports qHostInfo or qProcessInfo packets. Prefer
9825ffd83dbSDimitry Andric   // qProcessInfo as it will be more specific to our process.
9830b57cec5SDimitry Andric 
9840b57cec5SDimitry Andric   const ArchSpec &remote_process_arch = m_gdb_comm.GetProcessArchitecture();
9850b57cec5SDimitry Andric   if (remote_process_arch.IsValid()) {
9860b57cec5SDimitry Andric     process_arch = remote_process_arch;
9875ffd83dbSDimitry Andric     LLDB_LOG(log, "gdb-remote had process architecture, using {0} {1}",
9885ffd83dbSDimitry Andric              process_arch.GetArchitectureName(),
9895ffd83dbSDimitry Andric              process_arch.GetTriple().getTriple());
9900b57cec5SDimitry Andric   } else {
9910b57cec5SDimitry Andric     process_arch = m_gdb_comm.GetHostArchitecture();
9925ffd83dbSDimitry Andric     LLDB_LOG(log,
9935ffd83dbSDimitry Andric              "gdb-remote did not have process architecture, using gdb-remote "
9945ffd83dbSDimitry Andric              "host architecture {0} {1}",
9955ffd83dbSDimitry Andric              process_arch.GetArchitectureName(),
9965ffd83dbSDimitry Andric              process_arch.GetTriple().getTriple());
9970b57cec5SDimitry Andric   }
9980b57cec5SDimitry Andric 
999fe6060f1SDimitry Andric   if (int addresssable_bits = m_gdb_comm.GetAddressingBits()) {
1000fe6060f1SDimitry Andric     lldb::addr_t address_mask = ~((1ULL << addresssable_bits) - 1);
1001fe6060f1SDimitry Andric     SetCodeAddressMask(address_mask);
1002fe6060f1SDimitry Andric     SetDataAddressMask(address_mask);
1003fe6060f1SDimitry Andric   }
1004fe6060f1SDimitry Andric 
10050b57cec5SDimitry Andric   if (process_arch.IsValid()) {
10060b57cec5SDimitry Andric     const ArchSpec &target_arch = GetTarget().GetArchitecture();
10070b57cec5SDimitry Andric     if (target_arch.IsValid()) {
10085ffd83dbSDimitry Andric       LLDB_LOG(log, "analyzing target arch, currently {0} {1}",
10095ffd83dbSDimitry Andric                target_arch.GetArchitectureName(),
10105ffd83dbSDimitry Andric                target_arch.GetTriple().getTriple());
10110b57cec5SDimitry Andric 
10120b57cec5SDimitry Andric       // If the remote host is ARM and we have apple as the vendor, then
10130b57cec5SDimitry Andric       // ARM executables and shared libraries can have mixed ARM
10140b57cec5SDimitry Andric       // architectures.
10150b57cec5SDimitry Andric       // You can have an armv6 executable, and if the host is armv7, then the
10160b57cec5SDimitry Andric       // system will load the best possible architecture for all shared
10170b57cec5SDimitry Andric       // libraries it has, so we really need to take the remote host
10180b57cec5SDimitry Andric       // architecture as our defacto architecture in this case.
10190b57cec5SDimitry Andric 
10200b57cec5SDimitry Andric       if ((process_arch.GetMachine() == llvm::Triple::arm ||
10210b57cec5SDimitry Andric            process_arch.GetMachine() == llvm::Triple::thumb) &&
10220b57cec5SDimitry Andric           process_arch.GetTriple().getVendor() == llvm::Triple::Apple) {
10230b57cec5SDimitry Andric         GetTarget().SetArchitecture(process_arch);
10245ffd83dbSDimitry Andric         LLDB_LOG(log,
10255ffd83dbSDimitry Andric                  "remote process is ARM/Apple, "
10265ffd83dbSDimitry Andric                  "setting target arch to {0} {1}",
10275ffd83dbSDimitry Andric                  process_arch.GetArchitectureName(),
10285ffd83dbSDimitry Andric                  process_arch.GetTriple().getTriple());
10290b57cec5SDimitry Andric       } else {
10300b57cec5SDimitry Andric         // Fill in what is missing in the triple
10310b57cec5SDimitry Andric         const llvm::Triple &remote_triple = process_arch.GetTriple();
10320b57cec5SDimitry Andric         llvm::Triple new_target_triple = target_arch.GetTriple();
10330b57cec5SDimitry Andric         if (new_target_triple.getVendorName().size() == 0) {
10340b57cec5SDimitry Andric           new_target_triple.setVendor(remote_triple.getVendor());
10350b57cec5SDimitry Andric 
10360b57cec5SDimitry Andric           if (new_target_triple.getOSName().size() == 0) {
10370b57cec5SDimitry Andric             new_target_triple.setOS(remote_triple.getOS());
10380b57cec5SDimitry Andric 
10390b57cec5SDimitry Andric             if (new_target_triple.getEnvironmentName().size() == 0)
10405ffd83dbSDimitry Andric               new_target_triple.setEnvironment(remote_triple.getEnvironment());
10410b57cec5SDimitry Andric           }
10420b57cec5SDimitry Andric 
10430b57cec5SDimitry Andric           ArchSpec new_target_arch = target_arch;
10440b57cec5SDimitry Andric           new_target_arch.SetTriple(new_target_triple);
10450b57cec5SDimitry Andric           GetTarget().SetArchitecture(new_target_arch);
10460b57cec5SDimitry Andric         }
10470b57cec5SDimitry Andric       }
10480b57cec5SDimitry Andric 
10495ffd83dbSDimitry Andric       LLDB_LOG(log,
10505ffd83dbSDimitry Andric                "final target arch after adjustments for remote architecture: "
10515ffd83dbSDimitry Andric                "{0} {1}",
10525ffd83dbSDimitry Andric                target_arch.GetArchitectureName(),
10535ffd83dbSDimitry Andric                target_arch.GetTriple().getTriple());
10540b57cec5SDimitry Andric     } else {
10550b57cec5SDimitry Andric       // The target doesn't have a valid architecture yet, set it from the
10560b57cec5SDimitry Andric       // architecture we got from the remote GDB server
10570b57cec5SDimitry Andric       GetTarget().SetArchitecture(process_arch);
10580b57cec5SDimitry Andric     }
10590b57cec5SDimitry Andric   }
10600b57cec5SDimitry Andric 
10615ffd83dbSDimitry Andric   MaybeLoadExecutableModule();
10625ffd83dbSDimitry Andric 
10630b57cec5SDimitry Andric   // Find out which StructuredDataPlugins are supported by the debug monitor.
10640b57cec5SDimitry Andric   // These plugins transmit data over async $J packets.
10655ffd83dbSDimitry Andric   if (StructuredData::Array *supported_packets =
10665ffd83dbSDimitry Andric           m_gdb_comm.GetSupportedStructuredDataPlugins())
10675ffd83dbSDimitry Andric     MapSupportedStructuredDataPlugins(*supported_packets);
1068349cc55cSDimitry Andric 
1069349cc55cSDimitry Andric   // If connected to LLDB ("native-signals+"), use signal defs for
1070349cc55cSDimitry Andric   // the remote platform.  If connected to GDB, just use the standard set.
1071349cc55cSDimitry Andric   if (!m_gdb_comm.UsesNativeSignals()) {
1072349cc55cSDimitry Andric     SetUnixSignals(std::make_shared<GDBRemoteSignals>());
1073349cc55cSDimitry Andric   } else {
1074349cc55cSDimitry Andric     PlatformSP platform_sp = GetTarget().GetPlatform();
1075349cc55cSDimitry Andric     if (platform_sp && platform_sp->IsConnected())
1076349cc55cSDimitry Andric       SetUnixSignals(platform_sp->GetUnixSignals());
1077349cc55cSDimitry Andric     else
1078349cc55cSDimitry Andric       SetUnixSignals(UnixSignals::Create(GetTarget().GetArchitecture()));
1079349cc55cSDimitry Andric   }
10805ffd83dbSDimitry Andric }
10815ffd83dbSDimitry Andric 
10825ffd83dbSDimitry Andric void ProcessGDBRemote::MaybeLoadExecutableModule() {
10835ffd83dbSDimitry Andric   ModuleSP module_sp = GetTarget().GetExecutableModule();
10845ffd83dbSDimitry Andric   if (!module_sp)
10855ffd83dbSDimitry Andric     return;
10865ffd83dbSDimitry Andric 
10875ffd83dbSDimitry Andric   llvm::Optional<QOffsets> offsets = m_gdb_comm.GetQOffsets();
10885ffd83dbSDimitry Andric   if (!offsets)
10895ffd83dbSDimitry Andric     return;
10905ffd83dbSDimitry Andric 
10915ffd83dbSDimitry Andric   bool is_uniform =
10925ffd83dbSDimitry Andric       size_t(llvm::count(offsets->offsets, offsets->offsets[0])) ==
10935ffd83dbSDimitry Andric       offsets->offsets.size();
10945ffd83dbSDimitry Andric   if (!is_uniform)
10955ffd83dbSDimitry Andric     return; // TODO: Handle non-uniform responses.
10965ffd83dbSDimitry Andric 
10975ffd83dbSDimitry Andric   bool changed = false;
10985ffd83dbSDimitry Andric   module_sp->SetLoadAddress(GetTarget(), offsets->offsets[0],
10995ffd83dbSDimitry Andric                             /*value_is_offset=*/true, changed);
11005ffd83dbSDimitry Andric   if (changed) {
11015ffd83dbSDimitry Andric     ModuleList list;
11025ffd83dbSDimitry Andric     list.Append(module_sp);
11035ffd83dbSDimitry Andric     m_process->GetTarget().ModulesDidLoad(list);
11040b57cec5SDimitry Andric   }
11050b57cec5SDimitry Andric }
11060b57cec5SDimitry Andric 
11070b57cec5SDimitry Andric void ProcessGDBRemote::DidLaunch() {
11080b57cec5SDimitry Andric   ArchSpec process_arch;
11090b57cec5SDimitry Andric   DidLaunchOrAttach(process_arch);
11100b57cec5SDimitry Andric }
11110b57cec5SDimitry Andric 
11120b57cec5SDimitry Andric Status ProcessGDBRemote::DoAttachToProcessWithID(
11130b57cec5SDimitry Andric     lldb::pid_t attach_pid, const ProcessAttachInfo &attach_info) {
11141fd87a68SDimitry Andric   Log *log = GetLog(GDBRLog::Process);
11150b57cec5SDimitry Andric   Status error;
11160b57cec5SDimitry Andric 
11179dba64beSDimitry Andric   LLDB_LOGF(log, "ProcessGDBRemote::%s()", __FUNCTION__);
11180b57cec5SDimitry Andric 
11190b57cec5SDimitry Andric   // Clear out and clean up from any current state
11200b57cec5SDimitry Andric   Clear();
11210b57cec5SDimitry Andric   if (attach_pid != LLDB_INVALID_PROCESS_ID) {
11220b57cec5SDimitry Andric     error = EstablishConnectionIfNeeded(attach_info);
11230b57cec5SDimitry Andric     if (error.Success()) {
11240b57cec5SDimitry Andric       m_gdb_comm.SetDetachOnError(attach_info.GetDetachOnError());
11250b57cec5SDimitry Andric 
11260b57cec5SDimitry Andric       char packet[64];
11270b57cec5SDimitry Andric       const int packet_len =
11280b57cec5SDimitry Andric           ::snprintf(packet, sizeof(packet), "vAttach;%" PRIx64, attach_pid);
11290b57cec5SDimitry Andric       SetID(attach_pid);
11300b57cec5SDimitry Andric       m_async_broadcaster.BroadcastEvent(
11310b57cec5SDimitry Andric           eBroadcastBitAsyncContinue, new EventDataBytes(packet, packet_len));
11320b57cec5SDimitry Andric     } else
11330b57cec5SDimitry Andric       SetExitStatus(-1, error.AsCString());
11340b57cec5SDimitry Andric   }
11350b57cec5SDimitry Andric 
11360b57cec5SDimitry Andric   return error;
11370b57cec5SDimitry Andric }
11380b57cec5SDimitry Andric 
11390b57cec5SDimitry Andric Status ProcessGDBRemote::DoAttachToProcessWithName(
11400b57cec5SDimitry Andric     const char *process_name, const ProcessAttachInfo &attach_info) {
11410b57cec5SDimitry Andric   Status error;
11420b57cec5SDimitry Andric   // Clear out and clean up from any current state
11430b57cec5SDimitry Andric   Clear();
11440b57cec5SDimitry Andric 
11450b57cec5SDimitry Andric   if (process_name && process_name[0]) {
11460b57cec5SDimitry Andric     error = EstablishConnectionIfNeeded(attach_info);
11470b57cec5SDimitry Andric     if (error.Success()) {
11480b57cec5SDimitry Andric       StreamString packet;
11490b57cec5SDimitry Andric 
11500b57cec5SDimitry Andric       m_gdb_comm.SetDetachOnError(attach_info.GetDetachOnError());
11510b57cec5SDimitry Andric 
11520b57cec5SDimitry Andric       if (attach_info.GetWaitForLaunch()) {
11530b57cec5SDimitry Andric         if (!m_gdb_comm.GetVAttachOrWaitSupported()) {
11540b57cec5SDimitry Andric           packet.PutCString("vAttachWait");
11550b57cec5SDimitry Andric         } else {
11560b57cec5SDimitry Andric           if (attach_info.GetIgnoreExisting())
11570b57cec5SDimitry Andric             packet.PutCString("vAttachWait");
11580b57cec5SDimitry Andric           else
11590b57cec5SDimitry Andric             packet.PutCString("vAttachOrWait");
11600b57cec5SDimitry Andric         }
11610b57cec5SDimitry Andric       } else
11620b57cec5SDimitry Andric         packet.PutCString("vAttachName");
11630b57cec5SDimitry Andric       packet.PutChar(';');
11640b57cec5SDimitry Andric       packet.PutBytesAsRawHex8(process_name, strlen(process_name),
11650b57cec5SDimitry Andric                                endian::InlHostByteOrder(),
11660b57cec5SDimitry Andric                                endian::InlHostByteOrder());
11670b57cec5SDimitry Andric 
11680b57cec5SDimitry Andric       m_async_broadcaster.BroadcastEvent(
11690b57cec5SDimitry Andric           eBroadcastBitAsyncContinue,
11700b57cec5SDimitry Andric           new EventDataBytes(packet.GetString().data(), packet.GetSize()));
11710b57cec5SDimitry Andric 
11720b57cec5SDimitry Andric     } else
11730b57cec5SDimitry Andric       SetExitStatus(-1, error.AsCString());
11740b57cec5SDimitry Andric   }
11750b57cec5SDimitry Andric   return error;
11760b57cec5SDimitry Andric }
11770b57cec5SDimitry Andric 
1178fe6060f1SDimitry Andric llvm::Expected<TraceSupportedResponse> ProcessGDBRemote::TraceSupported() {
1179fe6060f1SDimitry Andric   return m_gdb_comm.SendTraceSupported(GetInterruptTimeout());
11800b57cec5SDimitry Andric }
11810b57cec5SDimitry Andric 
1182fe6060f1SDimitry Andric llvm::Error ProcessGDBRemote::TraceStop(const TraceStopRequest &request) {
1183fe6060f1SDimitry Andric   return m_gdb_comm.SendTraceStop(request, GetInterruptTimeout());
11840b57cec5SDimitry Andric }
11850b57cec5SDimitry Andric 
1186fe6060f1SDimitry Andric llvm::Error ProcessGDBRemote::TraceStart(const llvm::json::Value &request) {
1187fe6060f1SDimitry Andric   return m_gdb_comm.SendTraceStart(request, GetInterruptTimeout());
11880b57cec5SDimitry Andric }
11890b57cec5SDimitry Andric 
1190fe6060f1SDimitry Andric llvm::Expected<std::string>
1191fe6060f1SDimitry Andric ProcessGDBRemote::TraceGetState(llvm::StringRef type) {
1192fe6060f1SDimitry Andric   return m_gdb_comm.SendTraceGetState(type, GetInterruptTimeout());
11930b57cec5SDimitry Andric }
11940b57cec5SDimitry Andric 
1195fe6060f1SDimitry Andric llvm::Expected<std::vector<uint8_t>>
1196fe6060f1SDimitry Andric ProcessGDBRemote::TraceGetBinaryData(const TraceGetBinaryDataRequest &request) {
1197fe6060f1SDimitry Andric   return m_gdb_comm.SendTraceGetBinaryData(request, GetInterruptTimeout());
1198e8d8bef9SDimitry Andric }
1199e8d8bef9SDimitry Andric 
12000b57cec5SDimitry Andric void ProcessGDBRemote::DidExit() {
12010b57cec5SDimitry Andric   // When we exit, disconnect from the GDB server communications
12020b57cec5SDimitry Andric   m_gdb_comm.Disconnect();
12030b57cec5SDimitry Andric }
12040b57cec5SDimitry Andric 
12050b57cec5SDimitry Andric void ProcessGDBRemote::DidAttach(ArchSpec &process_arch) {
12060b57cec5SDimitry Andric   // If you can figure out what the architecture is, fill it in here.
12070b57cec5SDimitry Andric   process_arch.Clear();
12080b57cec5SDimitry Andric   DidLaunchOrAttach(process_arch);
12090b57cec5SDimitry Andric }
12100b57cec5SDimitry Andric 
12110b57cec5SDimitry Andric Status ProcessGDBRemote::WillResume() {
12120b57cec5SDimitry Andric   m_continue_c_tids.clear();
12130b57cec5SDimitry Andric   m_continue_C_tids.clear();
12140b57cec5SDimitry Andric   m_continue_s_tids.clear();
12150b57cec5SDimitry Andric   m_continue_S_tids.clear();
12160b57cec5SDimitry Andric   m_jstopinfo_sp.reset();
12170b57cec5SDimitry Andric   m_jthreadsinfo_sp.reset();
12180b57cec5SDimitry Andric   return Status();
12190b57cec5SDimitry Andric }
12200b57cec5SDimitry Andric 
12210b57cec5SDimitry Andric Status ProcessGDBRemote::DoResume() {
12220b57cec5SDimitry Andric   Status error;
12231fd87a68SDimitry Andric   Log *log = GetLog(GDBRLog::Process);
12249dba64beSDimitry Andric   LLDB_LOGF(log, "ProcessGDBRemote::Resume()");
12250b57cec5SDimitry Andric 
12260b57cec5SDimitry Andric   ListenerSP listener_sp(
12270b57cec5SDimitry Andric       Listener::MakeListener("gdb-remote.resume-packet-sent"));
12280b57cec5SDimitry Andric   if (listener_sp->StartListeningForEvents(
12290b57cec5SDimitry Andric           &m_gdb_comm, GDBRemoteCommunication::eBroadcastBitRunPacketSent)) {
12300b57cec5SDimitry Andric     listener_sp->StartListeningForEvents(
12310b57cec5SDimitry Andric         &m_async_broadcaster,
12320b57cec5SDimitry Andric         ProcessGDBRemote::eBroadcastBitAsyncThreadDidExit);
12330b57cec5SDimitry Andric 
12340b57cec5SDimitry Andric     const size_t num_threads = GetThreadList().GetSize();
12350b57cec5SDimitry Andric 
12360b57cec5SDimitry Andric     StreamString continue_packet;
12370b57cec5SDimitry Andric     bool continue_packet_error = false;
12380b57cec5SDimitry Andric     if (m_gdb_comm.HasAnyVContSupport()) {
1239349cc55cSDimitry Andric       if (m_continue_c_tids.size() == num_threads ||
12400b57cec5SDimitry Andric           (m_continue_c_tids.empty() && m_continue_C_tids.empty() &&
1241349cc55cSDimitry Andric            m_continue_s_tids.empty() && m_continue_S_tids.empty())) {
12420b57cec5SDimitry Andric         // All threads are continuing, just send a "c" packet
12430b57cec5SDimitry Andric         continue_packet.PutCString("c");
12440b57cec5SDimitry Andric       } else {
12450b57cec5SDimitry Andric         continue_packet.PutCString("vCont");
12460b57cec5SDimitry Andric 
12470b57cec5SDimitry Andric         if (!m_continue_c_tids.empty()) {
12480b57cec5SDimitry Andric           if (m_gdb_comm.GetVContSupported('c')) {
12490b57cec5SDimitry Andric             for (tid_collection::const_iterator
12500b57cec5SDimitry Andric                      t_pos = m_continue_c_tids.begin(),
12510b57cec5SDimitry Andric                      t_end = m_continue_c_tids.end();
12520b57cec5SDimitry Andric                  t_pos != t_end; ++t_pos)
12530b57cec5SDimitry Andric               continue_packet.Printf(";c:%4.4" PRIx64, *t_pos);
12540b57cec5SDimitry Andric           } else
12550b57cec5SDimitry Andric             continue_packet_error = true;
12560b57cec5SDimitry Andric         }
12570b57cec5SDimitry Andric 
12580b57cec5SDimitry Andric         if (!continue_packet_error && !m_continue_C_tids.empty()) {
12590b57cec5SDimitry Andric           if (m_gdb_comm.GetVContSupported('C')) {
12600b57cec5SDimitry Andric             for (tid_sig_collection::const_iterator
12610b57cec5SDimitry Andric                      s_pos = m_continue_C_tids.begin(),
12620b57cec5SDimitry Andric                      s_end = m_continue_C_tids.end();
12630b57cec5SDimitry Andric                  s_pos != s_end; ++s_pos)
12640b57cec5SDimitry Andric               continue_packet.Printf(";C%2.2x:%4.4" PRIx64, s_pos->second,
12650b57cec5SDimitry Andric                                      s_pos->first);
12660b57cec5SDimitry Andric           } else
12670b57cec5SDimitry Andric             continue_packet_error = true;
12680b57cec5SDimitry Andric         }
12690b57cec5SDimitry Andric 
12700b57cec5SDimitry Andric         if (!continue_packet_error && !m_continue_s_tids.empty()) {
12710b57cec5SDimitry Andric           if (m_gdb_comm.GetVContSupported('s')) {
12720b57cec5SDimitry Andric             for (tid_collection::const_iterator
12730b57cec5SDimitry Andric                      t_pos = m_continue_s_tids.begin(),
12740b57cec5SDimitry Andric                      t_end = m_continue_s_tids.end();
12750b57cec5SDimitry Andric                  t_pos != t_end; ++t_pos)
12760b57cec5SDimitry Andric               continue_packet.Printf(";s:%4.4" PRIx64, *t_pos);
12770b57cec5SDimitry Andric           } else
12780b57cec5SDimitry Andric             continue_packet_error = true;
12790b57cec5SDimitry Andric         }
12800b57cec5SDimitry Andric 
12810b57cec5SDimitry Andric         if (!continue_packet_error && !m_continue_S_tids.empty()) {
12820b57cec5SDimitry Andric           if (m_gdb_comm.GetVContSupported('S')) {
12830b57cec5SDimitry Andric             for (tid_sig_collection::const_iterator
12840b57cec5SDimitry Andric                      s_pos = m_continue_S_tids.begin(),
12850b57cec5SDimitry Andric                      s_end = m_continue_S_tids.end();
12860b57cec5SDimitry Andric                  s_pos != s_end; ++s_pos)
12870b57cec5SDimitry Andric               continue_packet.Printf(";S%2.2x:%4.4" PRIx64, s_pos->second,
12880b57cec5SDimitry Andric                                      s_pos->first);
12890b57cec5SDimitry Andric           } else
12900b57cec5SDimitry Andric             continue_packet_error = true;
12910b57cec5SDimitry Andric         }
12920b57cec5SDimitry Andric 
12930b57cec5SDimitry Andric         if (continue_packet_error)
12940b57cec5SDimitry Andric           continue_packet.Clear();
12950b57cec5SDimitry Andric       }
12960b57cec5SDimitry Andric     } else
12970b57cec5SDimitry Andric       continue_packet_error = true;
12980b57cec5SDimitry Andric 
12990b57cec5SDimitry Andric     if (continue_packet_error) {
13000b57cec5SDimitry Andric       // Either no vCont support, or we tried to use part of the vCont packet
13010b57cec5SDimitry Andric       // that wasn't supported by the remote GDB server. We need to try and
13020b57cec5SDimitry Andric       // make a simple packet that can do our continue
13030b57cec5SDimitry Andric       const size_t num_continue_c_tids = m_continue_c_tids.size();
13040b57cec5SDimitry Andric       const size_t num_continue_C_tids = m_continue_C_tids.size();
13050b57cec5SDimitry Andric       const size_t num_continue_s_tids = m_continue_s_tids.size();
13060b57cec5SDimitry Andric       const size_t num_continue_S_tids = m_continue_S_tids.size();
13070b57cec5SDimitry Andric       if (num_continue_c_tids > 0) {
13080b57cec5SDimitry Andric         if (num_continue_c_tids == num_threads) {
13090b57cec5SDimitry Andric           // All threads are resuming...
13100b57cec5SDimitry Andric           m_gdb_comm.SetCurrentThreadForRun(-1);
13110b57cec5SDimitry Andric           continue_packet.PutChar('c');
13120b57cec5SDimitry Andric           continue_packet_error = false;
13130b57cec5SDimitry Andric         } else if (num_continue_c_tids == 1 && num_continue_C_tids == 0 &&
13140b57cec5SDimitry Andric                    num_continue_s_tids == 0 && num_continue_S_tids == 0) {
13150b57cec5SDimitry Andric           // Only one thread is continuing
13160b57cec5SDimitry Andric           m_gdb_comm.SetCurrentThreadForRun(m_continue_c_tids.front());
13170b57cec5SDimitry Andric           continue_packet.PutChar('c');
13180b57cec5SDimitry Andric           continue_packet_error = false;
13190b57cec5SDimitry Andric         }
13200b57cec5SDimitry Andric       }
13210b57cec5SDimitry Andric 
13220b57cec5SDimitry Andric       if (continue_packet_error && num_continue_C_tids > 0) {
13230b57cec5SDimitry Andric         if ((num_continue_C_tids + num_continue_c_tids) == num_threads &&
13240b57cec5SDimitry Andric             num_continue_C_tids > 0 && num_continue_s_tids == 0 &&
13250b57cec5SDimitry Andric             num_continue_S_tids == 0) {
13260b57cec5SDimitry Andric           const int continue_signo = m_continue_C_tids.front().second;
13270b57cec5SDimitry Andric           // Only one thread is continuing
13280b57cec5SDimitry Andric           if (num_continue_C_tids > 1) {
13290b57cec5SDimitry Andric             // More that one thread with a signal, yet we don't have vCont
13300b57cec5SDimitry Andric             // support and we are being asked to resume each thread with a
13310b57cec5SDimitry Andric             // signal, we need to make sure they are all the same signal, or we
13320b57cec5SDimitry Andric             // can't issue the continue accurately with the current support...
13330b57cec5SDimitry Andric             if (num_continue_C_tids > 1) {
13340b57cec5SDimitry Andric               continue_packet_error = false;
13350b57cec5SDimitry Andric               for (size_t i = 1; i < m_continue_C_tids.size(); ++i) {
13360b57cec5SDimitry Andric                 if (m_continue_C_tids[i].second != continue_signo)
13370b57cec5SDimitry Andric                   continue_packet_error = true;
13380b57cec5SDimitry Andric               }
13390b57cec5SDimitry Andric             }
13400b57cec5SDimitry Andric             if (!continue_packet_error)
13410b57cec5SDimitry Andric               m_gdb_comm.SetCurrentThreadForRun(-1);
13420b57cec5SDimitry Andric           } else {
13430b57cec5SDimitry Andric             // Set the continue thread ID
13440b57cec5SDimitry Andric             continue_packet_error = false;
13450b57cec5SDimitry Andric             m_gdb_comm.SetCurrentThreadForRun(m_continue_C_tids.front().first);
13460b57cec5SDimitry Andric           }
13470b57cec5SDimitry Andric           if (!continue_packet_error) {
13480b57cec5SDimitry Andric             // Add threads continuing with the same signo...
13490b57cec5SDimitry Andric             continue_packet.Printf("C%2.2x", continue_signo);
13500b57cec5SDimitry Andric           }
13510b57cec5SDimitry Andric         }
13520b57cec5SDimitry Andric       }
13530b57cec5SDimitry Andric 
13540b57cec5SDimitry Andric       if (continue_packet_error && num_continue_s_tids > 0) {
13550b57cec5SDimitry Andric         if (num_continue_s_tids == num_threads) {
13560b57cec5SDimitry Andric           // All threads are resuming...
13570b57cec5SDimitry Andric           m_gdb_comm.SetCurrentThreadForRun(-1);
13580b57cec5SDimitry Andric 
13590b57cec5SDimitry Andric           continue_packet.PutChar('s');
13600b57cec5SDimitry Andric 
13610b57cec5SDimitry Andric           continue_packet_error = false;
13620b57cec5SDimitry Andric         } else if (num_continue_c_tids == 0 && num_continue_C_tids == 0 &&
13630b57cec5SDimitry Andric                    num_continue_s_tids == 1 && num_continue_S_tids == 0) {
13640b57cec5SDimitry Andric           // Only one thread is stepping
13650b57cec5SDimitry Andric           m_gdb_comm.SetCurrentThreadForRun(m_continue_s_tids.front());
13660b57cec5SDimitry Andric           continue_packet.PutChar('s');
13670b57cec5SDimitry Andric           continue_packet_error = false;
13680b57cec5SDimitry Andric         }
13690b57cec5SDimitry Andric       }
13700b57cec5SDimitry Andric 
13710b57cec5SDimitry Andric       if (!continue_packet_error && num_continue_S_tids > 0) {
13720b57cec5SDimitry Andric         if (num_continue_S_tids == num_threads) {
13730b57cec5SDimitry Andric           const int step_signo = m_continue_S_tids.front().second;
13740b57cec5SDimitry Andric           // Are all threads trying to step with the same signal?
13750b57cec5SDimitry Andric           continue_packet_error = false;
13760b57cec5SDimitry Andric           if (num_continue_S_tids > 1) {
13770b57cec5SDimitry Andric             for (size_t i = 1; i < num_threads; ++i) {
13780b57cec5SDimitry Andric               if (m_continue_S_tids[i].second != step_signo)
13790b57cec5SDimitry Andric                 continue_packet_error = true;
13800b57cec5SDimitry Andric             }
13810b57cec5SDimitry Andric           }
13820b57cec5SDimitry Andric           if (!continue_packet_error) {
13830b57cec5SDimitry Andric             // Add threads stepping with the same signo...
13840b57cec5SDimitry Andric             m_gdb_comm.SetCurrentThreadForRun(-1);
13850b57cec5SDimitry Andric             continue_packet.Printf("S%2.2x", step_signo);
13860b57cec5SDimitry Andric           }
13870b57cec5SDimitry Andric         } else if (num_continue_c_tids == 0 && num_continue_C_tids == 0 &&
13880b57cec5SDimitry Andric                    num_continue_s_tids == 0 && num_continue_S_tids == 1) {
13890b57cec5SDimitry Andric           // Only one thread is stepping with signal
13900b57cec5SDimitry Andric           m_gdb_comm.SetCurrentThreadForRun(m_continue_S_tids.front().first);
13910b57cec5SDimitry Andric           continue_packet.Printf("S%2.2x", m_continue_S_tids.front().second);
13920b57cec5SDimitry Andric           continue_packet_error = false;
13930b57cec5SDimitry Andric         }
13940b57cec5SDimitry Andric       }
13950b57cec5SDimitry Andric     }
13960b57cec5SDimitry Andric 
13970b57cec5SDimitry Andric     if (continue_packet_error) {
13980b57cec5SDimitry Andric       error.SetErrorString("can't make continue packet for this resume");
13990b57cec5SDimitry Andric     } else {
14000b57cec5SDimitry Andric       EventSP event_sp;
14010b57cec5SDimitry Andric       if (!m_async_thread.IsJoinable()) {
14020b57cec5SDimitry Andric         error.SetErrorString("Trying to resume but the async thread is dead.");
14039dba64beSDimitry Andric         LLDB_LOGF(log, "ProcessGDBRemote::DoResume: Trying to resume but the "
14040b57cec5SDimitry Andric                        "async thread is dead.");
14050b57cec5SDimitry Andric         return error;
14060b57cec5SDimitry Andric       }
14070b57cec5SDimitry Andric 
14080b57cec5SDimitry Andric       m_async_broadcaster.BroadcastEvent(
14090b57cec5SDimitry Andric           eBroadcastBitAsyncContinue,
14100b57cec5SDimitry Andric           new EventDataBytes(continue_packet.GetString().data(),
14110b57cec5SDimitry Andric                              continue_packet.GetSize()));
14120b57cec5SDimitry Andric 
14130b57cec5SDimitry Andric       if (!listener_sp->GetEvent(event_sp, std::chrono::seconds(5))) {
14140b57cec5SDimitry Andric         error.SetErrorString("Resume timed out.");
14159dba64beSDimitry Andric         LLDB_LOGF(log, "ProcessGDBRemote::DoResume: Resume timed out.");
14160b57cec5SDimitry Andric       } else if (event_sp->BroadcasterIs(&m_async_broadcaster)) {
14170b57cec5SDimitry Andric         error.SetErrorString("Broadcast continue, but the async thread was "
14180b57cec5SDimitry Andric                              "killed before we got an ack back.");
14199dba64beSDimitry Andric         LLDB_LOGF(log,
14209dba64beSDimitry Andric                   "ProcessGDBRemote::DoResume: Broadcast continue, but the "
14210b57cec5SDimitry Andric                   "async thread was killed before we got an ack back.");
14220b57cec5SDimitry Andric         return error;
14230b57cec5SDimitry Andric       }
14240b57cec5SDimitry Andric     }
14250b57cec5SDimitry Andric   }
14260b57cec5SDimitry Andric 
14270b57cec5SDimitry Andric   return error;
14280b57cec5SDimitry Andric }
14290b57cec5SDimitry Andric 
14300b57cec5SDimitry Andric void ProcessGDBRemote::ClearThreadIDList() {
14310b57cec5SDimitry Andric   std::lock_guard<std::recursive_mutex> guard(m_thread_list_real.GetMutex());
14320b57cec5SDimitry Andric   m_thread_ids.clear();
14330b57cec5SDimitry Andric   m_thread_pcs.clear();
14340b57cec5SDimitry Andric }
14350b57cec5SDimitry Andric 
1436fe6060f1SDimitry Andric size_t ProcessGDBRemote::UpdateThreadIDsFromStopReplyThreadsValue(
1437fe6060f1SDimitry Andric     llvm::StringRef value) {
14380b57cec5SDimitry Andric   m_thread_ids.clear();
1439fe6060f1SDimitry Andric   lldb::pid_t pid = m_gdb_comm.GetCurrentProcessID();
1440fe6060f1SDimitry Andric   StringExtractorGDBRemote thread_ids{value};
1441fe6060f1SDimitry Andric 
1442fe6060f1SDimitry Andric   do {
1443fe6060f1SDimitry Andric     auto pid_tid = thread_ids.GetPidTid(pid);
1444fe6060f1SDimitry Andric     if (pid_tid && pid_tid->first == pid) {
1445fe6060f1SDimitry Andric       lldb::tid_t tid = pid_tid->second;
1446fe6060f1SDimitry Andric       if (tid != LLDB_INVALID_THREAD_ID &&
1447fe6060f1SDimitry Andric           tid != StringExtractorGDBRemote::AllProcesses)
14480b57cec5SDimitry Andric         m_thread_ids.push_back(tid);
14490b57cec5SDimitry Andric     }
1450fe6060f1SDimitry Andric   } while (thread_ids.GetChar() == ',');
1451fe6060f1SDimitry Andric 
14520b57cec5SDimitry Andric   return m_thread_ids.size();
14530b57cec5SDimitry Andric }
14540b57cec5SDimitry Andric 
1455349cc55cSDimitry Andric size_t ProcessGDBRemote::UpdateThreadPCsFromStopReplyThreadsValue(
1456349cc55cSDimitry Andric     llvm::StringRef value) {
14570b57cec5SDimitry Andric   m_thread_pcs.clear();
1458349cc55cSDimitry Andric   for (llvm::StringRef x : llvm::split(value, ',')) {
14590b57cec5SDimitry Andric     lldb::addr_t pc;
1460349cc55cSDimitry Andric     if (llvm::to_integer(x, pc, 16))
14610b57cec5SDimitry Andric       m_thread_pcs.push_back(pc);
14620b57cec5SDimitry Andric   }
14630b57cec5SDimitry Andric   return m_thread_pcs.size();
14640b57cec5SDimitry Andric }
14650b57cec5SDimitry Andric 
14660b57cec5SDimitry Andric bool ProcessGDBRemote::UpdateThreadIDList() {
14670b57cec5SDimitry Andric   std::lock_guard<std::recursive_mutex> guard(m_thread_list_real.GetMutex());
14680b57cec5SDimitry Andric 
14690b57cec5SDimitry Andric   if (m_jthreadsinfo_sp) {
14700b57cec5SDimitry Andric     // If we have the JSON threads info, we can get the thread list from that
14710b57cec5SDimitry Andric     StructuredData::Array *thread_infos = m_jthreadsinfo_sp->GetAsArray();
14720b57cec5SDimitry Andric     if (thread_infos && thread_infos->GetSize() > 0) {
14730b57cec5SDimitry Andric       m_thread_ids.clear();
14740b57cec5SDimitry Andric       m_thread_pcs.clear();
14750b57cec5SDimitry Andric       thread_infos->ForEach([this](StructuredData::Object *object) -> bool {
14760b57cec5SDimitry Andric         StructuredData::Dictionary *thread_dict = object->GetAsDictionary();
14770b57cec5SDimitry Andric         if (thread_dict) {
14780b57cec5SDimitry Andric           // Set the thread stop info from the JSON dictionary
14790b57cec5SDimitry Andric           SetThreadStopInfo(thread_dict);
14800b57cec5SDimitry Andric           lldb::tid_t tid = LLDB_INVALID_THREAD_ID;
14810b57cec5SDimitry Andric           if (thread_dict->GetValueForKeyAsInteger<lldb::tid_t>("tid", tid))
14820b57cec5SDimitry Andric             m_thread_ids.push_back(tid);
14830b57cec5SDimitry Andric         }
14840b57cec5SDimitry Andric         return true; // Keep iterating through all thread_info objects
14850b57cec5SDimitry Andric       });
14860b57cec5SDimitry Andric     }
14870b57cec5SDimitry Andric     if (!m_thread_ids.empty())
14880b57cec5SDimitry Andric       return true;
14890b57cec5SDimitry Andric   } else {
14900b57cec5SDimitry Andric     // See if we can get the thread IDs from the current stop reply packets
14910b57cec5SDimitry Andric     // that might contain a "threads" key/value pair
14920b57cec5SDimitry Andric 
1493349cc55cSDimitry Andric     if (m_last_stop_packet) {
14940b57cec5SDimitry Andric       // Get the thread stop info
1495349cc55cSDimitry Andric       StringExtractorGDBRemote &stop_info = *m_last_stop_packet;
1496349cc55cSDimitry Andric       const std::string &stop_info_str = std::string(stop_info.GetStringRef());
14970b57cec5SDimitry Andric 
14980b57cec5SDimitry Andric       m_thread_pcs.clear();
14990b57cec5SDimitry Andric       const size_t thread_pcs_pos = stop_info_str.find(";thread-pcs:");
15000b57cec5SDimitry Andric       if (thread_pcs_pos != std::string::npos) {
15010b57cec5SDimitry Andric         const size_t start = thread_pcs_pos + strlen(";thread-pcs:");
15020b57cec5SDimitry Andric         const size_t end = stop_info_str.find(';', start);
15030b57cec5SDimitry Andric         if (end != std::string::npos) {
15040b57cec5SDimitry Andric           std::string value = stop_info_str.substr(start, end - start);
15050b57cec5SDimitry Andric           UpdateThreadPCsFromStopReplyThreadsValue(value);
15060b57cec5SDimitry Andric         }
15070b57cec5SDimitry Andric       }
15080b57cec5SDimitry Andric 
15090b57cec5SDimitry Andric       const size_t threads_pos = stop_info_str.find(";threads:");
15100b57cec5SDimitry Andric       if (threads_pos != std::string::npos) {
15110b57cec5SDimitry Andric         const size_t start = threads_pos + strlen(";threads:");
15120b57cec5SDimitry Andric         const size_t end = stop_info_str.find(';', start);
15130b57cec5SDimitry Andric         if (end != std::string::npos) {
15140b57cec5SDimitry Andric           std::string value = stop_info_str.substr(start, end - start);
15150b57cec5SDimitry Andric           if (UpdateThreadIDsFromStopReplyThreadsValue(value))
15160b57cec5SDimitry Andric             return true;
15170b57cec5SDimitry Andric         }
15180b57cec5SDimitry Andric       }
15190b57cec5SDimitry Andric     }
15200b57cec5SDimitry Andric   }
15210b57cec5SDimitry Andric 
15220b57cec5SDimitry Andric   bool sequence_mutex_unavailable = false;
15230b57cec5SDimitry Andric   m_gdb_comm.GetCurrentThreadIDs(m_thread_ids, sequence_mutex_unavailable);
15240b57cec5SDimitry Andric   if (sequence_mutex_unavailable) {
15250b57cec5SDimitry Andric     return false; // We just didn't get the list
15260b57cec5SDimitry Andric   }
15270b57cec5SDimitry Andric   return true;
15280b57cec5SDimitry Andric }
15290b57cec5SDimitry Andric 
1530e8d8bef9SDimitry Andric bool ProcessGDBRemote::DoUpdateThreadList(ThreadList &old_thread_list,
15310b57cec5SDimitry Andric                                           ThreadList &new_thread_list) {
15320b57cec5SDimitry Andric   // locker will keep a mutex locked until it goes out of scope
15331fd87a68SDimitry Andric   Log *log = GetLog(GDBRLog::Thread);
15340b57cec5SDimitry Andric   LLDB_LOGV(log, "pid = {0}", GetID());
15350b57cec5SDimitry Andric 
15360b57cec5SDimitry Andric   size_t num_thread_ids = m_thread_ids.size();
15370b57cec5SDimitry Andric   // The "m_thread_ids" thread ID list should always be updated after each stop
15380b57cec5SDimitry Andric   // reply packet, but in case it isn't, update it here.
15390b57cec5SDimitry Andric   if (num_thread_ids == 0) {
15400b57cec5SDimitry Andric     if (!UpdateThreadIDList())
15410b57cec5SDimitry Andric       return false;
15420b57cec5SDimitry Andric     num_thread_ids = m_thread_ids.size();
15430b57cec5SDimitry Andric   }
15440b57cec5SDimitry Andric 
15450b57cec5SDimitry Andric   ThreadList old_thread_list_copy(old_thread_list);
15460b57cec5SDimitry Andric   if (num_thread_ids > 0) {
15470b57cec5SDimitry Andric     for (size_t i = 0; i < num_thread_ids; ++i) {
15480b57cec5SDimitry Andric       tid_t tid = m_thread_ids[i];
15490b57cec5SDimitry Andric       ThreadSP thread_sp(
15500b57cec5SDimitry Andric           old_thread_list_copy.RemoveThreadByProtocolID(tid, false));
15510b57cec5SDimitry Andric       if (!thread_sp) {
15520b57cec5SDimitry Andric         thread_sp = std::make_shared<ThreadGDBRemote>(*this, tid);
15530b57cec5SDimitry Andric         LLDB_LOGV(log, "Making new thread: {0} for thread ID: {1:x}.",
15540b57cec5SDimitry Andric                   thread_sp.get(), thread_sp->GetID());
15550b57cec5SDimitry Andric       } else {
15560b57cec5SDimitry Andric         LLDB_LOGV(log, "Found old thread: {0} for thread ID: {1:x}.",
15570b57cec5SDimitry Andric                   thread_sp.get(), thread_sp->GetID());
15580b57cec5SDimitry Andric       }
15590b57cec5SDimitry Andric 
15600b57cec5SDimitry Andric       SetThreadPc(thread_sp, i);
15610b57cec5SDimitry Andric       new_thread_list.AddThreadSortedByIndexID(thread_sp);
15620b57cec5SDimitry Andric     }
15630b57cec5SDimitry Andric   }
15640b57cec5SDimitry Andric 
15650b57cec5SDimitry Andric   // Whatever that is left in old_thread_list_copy are not present in
15660b57cec5SDimitry Andric   // new_thread_list. Remove non-existent threads from internal id table.
15670b57cec5SDimitry Andric   size_t old_num_thread_ids = old_thread_list_copy.GetSize(false);
15680b57cec5SDimitry Andric   for (size_t i = 0; i < old_num_thread_ids; i++) {
15690b57cec5SDimitry Andric     ThreadSP old_thread_sp(old_thread_list_copy.GetThreadAtIndex(i, false));
15700b57cec5SDimitry Andric     if (old_thread_sp) {
15710b57cec5SDimitry Andric       lldb::tid_t old_thread_id = old_thread_sp->GetProtocolID();
15720b57cec5SDimitry Andric       m_thread_id_to_index_id_map.erase(old_thread_id);
15730b57cec5SDimitry Andric     }
15740b57cec5SDimitry Andric   }
15750b57cec5SDimitry Andric 
15760b57cec5SDimitry Andric   return true;
15770b57cec5SDimitry Andric }
15780b57cec5SDimitry Andric 
15790b57cec5SDimitry Andric void ProcessGDBRemote::SetThreadPc(const ThreadSP &thread_sp, uint64_t index) {
15800b57cec5SDimitry Andric   if (m_thread_ids.size() == m_thread_pcs.size() && thread_sp.get() &&
15810b57cec5SDimitry Andric       GetByteOrder() != eByteOrderInvalid) {
15820b57cec5SDimitry Andric     ThreadGDBRemote *gdb_thread =
15830b57cec5SDimitry Andric         static_cast<ThreadGDBRemote *>(thread_sp.get());
15840b57cec5SDimitry Andric     RegisterContextSP reg_ctx_sp(thread_sp->GetRegisterContext());
15850b57cec5SDimitry Andric     if (reg_ctx_sp) {
15860b57cec5SDimitry Andric       uint32_t pc_regnum = reg_ctx_sp->ConvertRegisterKindToRegisterNumber(
15870b57cec5SDimitry Andric           eRegisterKindGeneric, LLDB_REGNUM_GENERIC_PC);
15880b57cec5SDimitry Andric       if (pc_regnum != LLDB_INVALID_REGNUM) {
15890b57cec5SDimitry Andric         gdb_thread->PrivateSetRegisterValue(pc_regnum, m_thread_pcs[index]);
15900b57cec5SDimitry Andric       }
15910b57cec5SDimitry Andric     }
15920b57cec5SDimitry Andric   }
15930b57cec5SDimitry Andric }
15940b57cec5SDimitry Andric 
15950b57cec5SDimitry Andric bool ProcessGDBRemote::GetThreadStopInfoFromJSON(
15960b57cec5SDimitry Andric     ThreadGDBRemote *thread, const StructuredData::ObjectSP &thread_infos_sp) {
15970b57cec5SDimitry Andric   // See if we got thread stop infos for all threads via the "jThreadsInfo"
15980b57cec5SDimitry Andric   // packet
15990b57cec5SDimitry Andric   if (thread_infos_sp) {
16000b57cec5SDimitry Andric     StructuredData::Array *thread_infos = thread_infos_sp->GetAsArray();
16010b57cec5SDimitry Andric     if (thread_infos) {
16020b57cec5SDimitry Andric       lldb::tid_t tid;
16030b57cec5SDimitry Andric       const size_t n = thread_infos->GetSize();
16040b57cec5SDimitry Andric       for (size_t i = 0; i < n; ++i) {
16050b57cec5SDimitry Andric         StructuredData::Dictionary *thread_dict =
16060b57cec5SDimitry Andric             thread_infos->GetItemAtIndex(i)->GetAsDictionary();
16070b57cec5SDimitry Andric         if (thread_dict) {
16080b57cec5SDimitry Andric           if (thread_dict->GetValueForKeyAsInteger<lldb::tid_t>(
16090b57cec5SDimitry Andric                   "tid", tid, LLDB_INVALID_THREAD_ID)) {
16100b57cec5SDimitry Andric             if (tid == thread->GetID())
16110b57cec5SDimitry Andric               return (bool)SetThreadStopInfo(thread_dict);
16120b57cec5SDimitry Andric           }
16130b57cec5SDimitry Andric         }
16140b57cec5SDimitry Andric       }
16150b57cec5SDimitry Andric     }
16160b57cec5SDimitry Andric   }
16170b57cec5SDimitry Andric   return false;
16180b57cec5SDimitry Andric }
16190b57cec5SDimitry Andric 
16200b57cec5SDimitry Andric bool ProcessGDBRemote::CalculateThreadStopInfo(ThreadGDBRemote *thread) {
16210b57cec5SDimitry Andric   // See if we got thread stop infos for all threads via the "jThreadsInfo"
16220b57cec5SDimitry Andric   // packet
16230b57cec5SDimitry Andric   if (GetThreadStopInfoFromJSON(thread, m_jthreadsinfo_sp))
16240b57cec5SDimitry Andric     return true;
16250b57cec5SDimitry Andric 
16260b57cec5SDimitry Andric   // See if we got thread stop info for any threads valid stop info reasons
16270b57cec5SDimitry Andric   // threads via the "jstopinfo" packet stop reply packet key/value pair?
16280b57cec5SDimitry Andric   if (m_jstopinfo_sp) {
16290b57cec5SDimitry Andric     // If we have "jstopinfo" then we have stop descriptions for all threads
16300b57cec5SDimitry Andric     // that have stop reasons, and if there is no entry for a thread, then it
16310b57cec5SDimitry Andric     // has no stop reason.
16320b57cec5SDimitry Andric     thread->GetRegisterContext()->InvalidateIfNeeded(true);
16330b57cec5SDimitry Andric     if (!GetThreadStopInfoFromJSON(thread, m_jstopinfo_sp)) {
16340b57cec5SDimitry Andric       thread->SetStopInfo(StopInfoSP());
16350b57cec5SDimitry Andric     }
16360b57cec5SDimitry Andric     return true;
16370b57cec5SDimitry Andric   }
16380b57cec5SDimitry Andric 
16390b57cec5SDimitry Andric   // Fall back to using the qThreadStopInfo packet
16400b57cec5SDimitry Andric   StringExtractorGDBRemote stop_packet;
16410b57cec5SDimitry Andric   if (GetGDBRemote().GetThreadStopInfo(thread->GetProtocolID(), stop_packet))
16420b57cec5SDimitry Andric     return SetThreadStopInfo(stop_packet) == eStateStopped;
16430b57cec5SDimitry Andric   return false;
16440b57cec5SDimitry Andric }
16450b57cec5SDimitry Andric 
16460b57cec5SDimitry Andric ThreadSP ProcessGDBRemote::SetThreadStopInfo(
16470b57cec5SDimitry Andric     lldb::tid_t tid, ExpeditedRegisterMap &expedited_register_map,
16480b57cec5SDimitry Andric     uint8_t signo, const std::string &thread_name, const std::string &reason,
16490b57cec5SDimitry Andric     const std::string &description, uint32_t exc_type,
16500b57cec5SDimitry Andric     const std::vector<addr_t> &exc_data, addr_t thread_dispatch_qaddr,
16510b57cec5SDimitry Andric     bool queue_vars_valid, // Set to true if queue_name, queue_kind and
16520b57cec5SDimitry Andric                            // queue_serial are valid
16530b57cec5SDimitry Andric     LazyBool associated_with_dispatch_queue, addr_t dispatch_queue_t,
16540b57cec5SDimitry Andric     std::string &queue_name, QueueKind queue_kind, uint64_t queue_serial) {
16550b57cec5SDimitry Andric   ThreadSP thread_sp;
16560b57cec5SDimitry Andric   if (tid != LLDB_INVALID_THREAD_ID) {
16570b57cec5SDimitry Andric     // Scope for "locker" below
16580b57cec5SDimitry Andric     {
16590b57cec5SDimitry Andric       // m_thread_list_real does have its own mutex, but we need to hold onto
16600b57cec5SDimitry Andric       // the mutex between the call to m_thread_list_real.FindThreadByID(...)
16610b57cec5SDimitry Andric       // and the m_thread_list_real.AddThread(...) so it doesn't change on us
16620b57cec5SDimitry Andric       std::lock_guard<std::recursive_mutex> guard(
16630b57cec5SDimitry Andric           m_thread_list_real.GetMutex());
16640b57cec5SDimitry Andric       thread_sp = m_thread_list_real.FindThreadByProtocolID(tid, false);
16650b57cec5SDimitry Andric 
16660b57cec5SDimitry Andric       if (!thread_sp) {
16670b57cec5SDimitry Andric         // Create the thread if we need to
16680b57cec5SDimitry Andric         thread_sp = std::make_shared<ThreadGDBRemote>(*this, tid);
16690b57cec5SDimitry Andric         m_thread_list_real.AddThread(thread_sp);
16700b57cec5SDimitry Andric       }
16710b57cec5SDimitry Andric     }
16720b57cec5SDimitry Andric 
16730b57cec5SDimitry Andric     if (thread_sp) {
16740b57cec5SDimitry Andric       ThreadGDBRemote *gdb_thread =
16750b57cec5SDimitry Andric           static_cast<ThreadGDBRemote *>(thread_sp.get());
1676fe6060f1SDimitry Andric       RegisterContextSP gdb_reg_ctx_sp(gdb_thread->GetRegisterContext());
1677fe6060f1SDimitry Andric 
1678fe6060f1SDimitry Andric       gdb_reg_ctx_sp->InvalidateIfNeeded(true);
16790b57cec5SDimitry Andric 
16800b57cec5SDimitry Andric       auto iter = std::find(m_thread_ids.begin(), m_thread_ids.end(), tid);
16810b57cec5SDimitry Andric       if (iter != m_thread_ids.end()) {
16820b57cec5SDimitry Andric         SetThreadPc(thread_sp, iter - m_thread_ids.begin());
16830b57cec5SDimitry Andric       }
16840b57cec5SDimitry Andric 
16850b57cec5SDimitry Andric       for (const auto &pair : expedited_register_map) {
16869dba64beSDimitry Andric         StringExtractor reg_value_extractor(pair.second);
1687*81ad6265SDimitry Andric         WritableDataBufferSP buffer_sp(new DataBufferHeap(
16880b57cec5SDimitry Andric             reg_value_extractor.GetStringRef().size() / 2, 0));
16890b57cec5SDimitry Andric         reg_value_extractor.GetHexBytes(buffer_sp->GetData(), '\xcc');
1690fe6060f1SDimitry Andric         uint32_t lldb_regnum =
1691fe6060f1SDimitry Andric             gdb_reg_ctx_sp->ConvertRegisterKindToRegisterNumber(
1692fe6060f1SDimitry Andric                 eRegisterKindProcessPlugin, pair.first);
1693fe6060f1SDimitry Andric         gdb_thread->PrivateSetRegisterValue(lldb_regnum, buffer_sp->GetData());
16940b57cec5SDimitry Andric       }
16950b57cec5SDimitry Andric 
1696e8d8bef9SDimitry Andric       // AArch64 SVE specific code below calls AArch64SVEReconfigure to update
1697e8d8bef9SDimitry Andric       // SVE register sizes and offsets if value of VG register has changed
1698e8d8bef9SDimitry Andric       // since last stop.
1699e8d8bef9SDimitry Andric       const ArchSpec &arch = GetTarget().GetArchitecture();
1700e8d8bef9SDimitry Andric       if (arch.IsValid() && arch.GetTriple().isAArch64()) {
1701e8d8bef9SDimitry Andric         GDBRemoteRegisterContext *reg_ctx_sp =
1702e8d8bef9SDimitry Andric             static_cast<GDBRemoteRegisterContext *>(
1703e8d8bef9SDimitry Andric                 gdb_thread->GetRegisterContext().get());
1704e8d8bef9SDimitry Andric 
1705e8d8bef9SDimitry Andric         if (reg_ctx_sp)
1706e8d8bef9SDimitry Andric           reg_ctx_sp->AArch64SVEReconfigure();
1707e8d8bef9SDimitry Andric       }
1708e8d8bef9SDimitry Andric 
17090b57cec5SDimitry Andric       thread_sp->SetName(thread_name.empty() ? nullptr : thread_name.c_str());
17100b57cec5SDimitry Andric 
17110b57cec5SDimitry Andric       gdb_thread->SetThreadDispatchQAddr(thread_dispatch_qaddr);
17120b57cec5SDimitry Andric       // Check if the GDB server was able to provide the queue name, kind and
17130b57cec5SDimitry Andric       // serial number
17140b57cec5SDimitry Andric       if (queue_vars_valid)
17150b57cec5SDimitry Andric         gdb_thread->SetQueueInfo(std::move(queue_name), queue_kind,
17160b57cec5SDimitry Andric                                  queue_serial, dispatch_queue_t,
17170b57cec5SDimitry Andric                                  associated_with_dispatch_queue);
17180b57cec5SDimitry Andric       else
17190b57cec5SDimitry Andric         gdb_thread->ClearQueueInfo();
17200b57cec5SDimitry Andric 
17210b57cec5SDimitry Andric       gdb_thread->SetAssociatedWithLibdispatchQueue(
17220b57cec5SDimitry Andric           associated_with_dispatch_queue);
17230b57cec5SDimitry Andric 
17240b57cec5SDimitry Andric       if (dispatch_queue_t != LLDB_INVALID_ADDRESS)
17250b57cec5SDimitry Andric         gdb_thread->SetQueueLibdispatchQueueAddress(dispatch_queue_t);
17260b57cec5SDimitry Andric 
17270b57cec5SDimitry Andric       // Make sure we update our thread stop reason just once
17280b57cec5SDimitry Andric       if (!thread_sp->StopInfoIsUpToDate()) {
17290b57cec5SDimitry Andric         thread_sp->SetStopInfo(StopInfoSP());
17300b57cec5SDimitry Andric         // If there's a memory thread backed by this thread, we need to use it
17310b57cec5SDimitry Andric         // to calculate StopInfo.
17320b57cec5SDimitry Andric         if (ThreadSP memory_thread_sp =
17330b57cec5SDimitry Andric                 m_thread_list.GetBackingThread(thread_sp))
17340b57cec5SDimitry Andric           thread_sp = memory_thread_sp;
17350b57cec5SDimitry Andric 
17360b57cec5SDimitry Andric         if (exc_type != 0) {
17370b57cec5SDimitry Andric           const size_t exc_data_size = exc_data.size();
17380b57cec5SDimitry Andric 
17390b57cec5SDimitry Andric           thread_sp->SetStopInfo(
17400b57cec5SDimitry Andric               StopInfoMachException::CreateStopReasonWithMachException(
17410b57cec5SDimitry Andric                   *thread_sp, exc_type, exc_data_size,
17420b57cec5SDimitry Andric                   exc_data_size >= 1 ? exc_data[0] : 0,
17430b57cec5SDimitry Andric                   exc_data_size >= 2 ? exc_data[1] : 0,
17440b57cec5SDimitry Andric                   exc_data_size >= 3 ? exc_data[2] : 0));
17450b57cec5SDimitry Andric         } else {
17460b57cec5SDimitry Andric           bool handled = false;
17470b57cec5SDimitry Andric           bool did_exec = false;
17480b57cec5SDimitry Andric           if (!reason.empty()) {
17490b57cec5SDimitry Andric             if (reason == "trace") {
17500b57cec5SDimitry Andric               addr_t pc = thread_sp->GetRegisterContext()->GetPC();
17510b57cec5SDimitry Andric               lldb::BreakpointSiteSP bp_site_sp = thread_sp->GetProcess()
17520b57cec5SDimitry Andric                                                       ->GetBreakpointSiteList()
17530b57cec5SDimitry Andric                                                       .FindByAddress(pc);
17540b57cec5SDimitry Andric 
17550b57cec5SDimitry Andric               // If the current pc is a breakpoint site then the StopInfo
17560b57cec5SDimitry Andric               // should be set to Breakpoint Otherwise, it will be set to
17570b57cec5SDimitry Andric               // Trace.
1758fe6060f1SDimitry Andric               if (bp_site_sp && bp_site_sp->ValidForThisThread(*thread_sp)) {
17590b57cec5SDimitry Andric                 thread_sp->SetStopInfo(
17600b57cec5SDimitry Andric                     StopInfo::CreateStopReasonWithBreakpointSiteID(
17610b57cec5SDimitry Andric                         *thread_sp, bp_site_sp->GetID()));
17620b57cec5SDimitry Andric               } else
17630b57cec5SDimitry Andric                 thread_sp->SetStopInfo(
17640b57cec5SDimitry Andric                     StopInfo::CreateStopReasonToTrace(*thread_sp));
17650b57cec5SDimitry Andric               handled = true;
17660b57cec5SDimitry Andric             } else if (reason == "breakpoint") {
17670b57cec5SDimitry Andric               addr_t pc = thread_sp->GetRegisterContext()->GetPC();
17680b57cec5SDimitry Andric               lldb::BreakpointSiteSP bp_site_sp = thread_sp->GetProcess()
17690b57cec5SDimitry Andric                                                       ->GetBreakpointSiteList()
17700b57cec5SDimitry Andric                                                       .FindByAddress(pc);
17710b57cec5SDimitry Andric               if (bp_site_sp) {
17720b57cec5SDimitry Andric                 // If the breakpoint is for this thread, then we'll report the
17730b57cec5SDimitry Andric                 // hit, but if it is for another thread, we can just report no
17740b57cec5SDimitry Andric                 // reason.  We don't need to worry about stepping over the
17750b57cec5SDimitry Andric                 // breakpoint here, that will be taken care of when the thread
17760b57cec5SDimitry Andric                 // resumes and notices that there's a breakpoint under the pc.
17770b57cec5SDimitry Andric                 handled = true;
1778fe6060f1SDimitry Andric                 if (bp_site_sp->ValidForThisThread(*thread_sp)) {
17790b57cec5SDimitry Andric                   thread_sp->SetStopInfo(
17800b57cec5SDimitry Andric                       StopInfo::CreateStopReasonWithBreakpointSiteID(
17810b57cec5SDimitry Andric                           *thread_sp, bp_site_sp->GetID()));
17820b57cec5SDimitry Andric                 } else {
17830b57cec5SDimitry Andric                   StopInfoSP invalid_stop_info_sp;
17840b57cec5SDimitry Andric                   thread_sp->SetStopInfo(invalid_stop_info_sp);
17850b57cec5SDimitry Andric                 }
17860b57cec5SDimitry Andric               }
17870b57cec5SDimitry Andric             } else if (reason == "trap") {
17880b57cec5SDimitry Andric               // Let the trap just use the standard signal stop reason below...
17890b57cec5SDimitry Andric             } else if (reason == "watchpoint") {
17900b57cec5SDimitry Andric               StringExtractor desc_extractor(description.c_str());
17910b57cec5SDimitry Andric               addr_t wp_addr = desc_extractor.GetU64(LLDB_INVALID_ADDRESS);
17920b57cec5SDimitry Andric               uint32_t wp_index = desc_extractor.GetU32(LLDB_INVALID_INDEX32);
17930b57cec5SDimitry Andric               addr_t wp_hit_addr = desc_extractor.GetU64(LLDB_INVALID_ADDRESS);
17940b57cec5SDimitry Andric               watch_id_t watch_id = LLDB_INVALID_WATCH_ID;
17950b57cec5SDimitry Andric               if (wp_addr != LLDB_INVALID_ADDRESS) {
17960b57cec5SDimitry Andric                 WatchpointSP wp_sp;
17970b57cec5SDimitry Andric                 ArchSpec::Core core = GetTarget().GetArchitecture().GetCore();
17980b57cec5SDimitry Andric                 if ((core >= ArchSpec::kCore_mips_first &&
17990b57cec5SDimitry Andric                      core <= ArchSpec::kCore_mips_last) ||
18000b57cec5SDimitry Andric                     (core >= ArchSpec::eCore_arm_generic &&
18010b57cec5SDimitry Andric                      core <= ArchSpec::eCore_arm_aarch64))
18020b57cec5SDimitry Andric                   wp_sp = GetTarget().GetWatchpointList().FindByAddress(
18030b57cec5SDimitry Andric                       wp_hit_addr);
18040b57cec5SDimitry Andric                 if (!wp_sp)
18050b57cec5SDimitry Andric                   wp_sp =
18060b57cec5SDimitry Andric                       GetTarget().GetWatchpointList().FindByAddress(wp_addr);
18070b57cec5SDimitry Andric                 if (wp_sp) {
18080b57cec5SDimitry Andric                   wp_sp->SetHardwareIndex(wp_index);
18090b57cec5SDimitry Andric                   watch_id = wp_sp->GetID();
18100b57cec5SDimitry Andric                 }
18110b57cec5SDimitry Andric               }
18120b57cec5SDimitry Andric               if (watch_id == LLDB_INVALID_WATCH_ID) {
18131fd87a68SDimitry Andric                 Log *log(GetLog(GDBRLog::Watchpoints));
18149dba64beSDimitry Andric                 LLDB_LOGF(log, "failed to find watchpoint");
18150b57cec5SDimitry Andric               }
18160b57cec5SDimitry Andric               thread_sp->SetStopInfo(StopInfo::CreateStopReasonWithWatchpointID(
18170b57cec5SDimitry Andric                   *thread_sp, watch_id, wp_hit_addr));
18180b57cec5SDimitry Andric               handled = true;
18190b57cec5SDimitry Andric             } else if (reason == "exception") {
18200b57cec5SDimitry Andric               thread_sp->SetStopInfo(StopInfo::CreateStopReasonWithException(
18210b57cec5SDimitry Andric                   *thread_sp, description.c_str()));
18220b57cec5SDimitry Andric               handled = true;
18230b57cec5SDimitry Andric             } else if (reason == "exec") {
18240b57cec5SDimitry Andric               did_exec = true;
18250b57cec5SDimitry Andric               thread_sp->SetStopInfo(
18260b57cec5SDimitry Andric                   StopInfo::CreateStopReasonWithExec(*thread_sp));
18270b57cec5SDimitry Andric               handled = true;
1828fe6060f1SDimitry Andric             } else if (reason == "processor trace") {
1829fe6060f1SDimitry Andric               thread_sp->SetStopInfo(StopInfo::CreateStopReasonProcessorTrace(
1830fe6060f1SDimitry Andric                   *thread_sp, description.c_str()));
1831349cc55cSDimitry Andric             } else if (reason == "fork") {
1832349cc55cSDimitry Andric               StringExtractor desc_extractor(description.c_str());
1833349cc55cSDimitry Andric               lldb::pid_t child_pid = desc_extractor.GetU64(
1834349cc55cSDimitry Andric                   LLDB_INVALID_PROCESS_ID);
1835349cc55cSDimitry Andric               lldb::tid_t child_tid = desc_extractor.GetU64(
1836349cc55cSDimitry Andric                   LLDB_INVALID_THREAD_ID);
1837349cc55cSDimitry Andric               thread_sp->SetStopInfo(StopInfo::CreateStopReasonFork(
1838349cc55cSDimitry Andric                   *thread_sp, child_pid, child_tid));
1839349cc55cSDimitry Andric               handled = true;
1840349cc55cSDimitry Andric             } else if (reason == "vfork") {
1841349cc55cSDimitry Andric               StringExtractor desc_extractor(description.c_str());
1842349cc55cSDimitry Andric               lldb::pid_t child_pid = desc_extractor.GetU64(
1843349cc55cSDimitry Andric                   LLDB_INVALID_PROCESS_ID);
1844349cc55cSDimitry Andric               lldb::tid_t child_tid = desc_extractor.GetU64(
1845349cc55cSDimitry Andric                   LLDB_INVALID_THREAD_ID);
1846349cc55cSDimitry Andric               thread_sp->SetStopInfo(StopInfo::CreateStopReasonVFork(
1847349cc55cSDimitry Andric                   *thread_sp, child_pid, child_tid));
1848349cc55cSDimitry Andric               handled = true;
1849349cc55cSDimitry Andric             } else if (reason == "vforkdone") {
1850349cc55cSDimitry Andric               thread_sp->SetStopInfo(
1851349cc55cSDimitry Andric                   StopInfo::CreateStopReasonVForkDone(*thread_sp));
1852349cc55cSDimitry Andric               handled = true;
18530b57cec5SDimitry Andric             }
18540b57cec5SDimitry Andric           } else if (!signo) {
18550b57cec5SDimitry Andric             addr_t pc = thread_sp->GetRegisterContext()->GetPC();
18560b57cec5SDimitry Andric             lldb::BreakpointSiteSP bp_site_sp =
18570b57cec5SDimitry Andric                 thread_sp->GetProcess()->GetBreakpointSiteList().FindByAddress(
18580b57cec5SDimitry Andric                     pc);
18590b57cec5SDimitry Andric 
18600b57cec5SDimitry Andric             // If the current pc is a breakpoint site then the StopInfo should
18610b57cec5SDimitry Andric             // be set to Breakpoint even though the remote stub did not set it
18620b57cec5SDimitry Andric             // as such. This can happen when the thread is involuntarily
18630b57cec5SDimitry Andric             // interrupted (e.g. due to stops on other threads) just as it is
18640b57cec5SDimitry Andric             // about to execute the breakpoint instruction.
1865fe6060f1SDimitry Andric             if (bp_site_sp && bp_site_sp->ValidForThisThread(*thread_sp)) {
18660b57cec5SDimitry Andric               thread_sp->SetStopInfo(
18670b57cec5SDimitry Andric                   StopInfo::CreateStopReasonWithBreakpointSiteID(
18680b57cec5SDimitry Andric                       *thread_sp, bp_site_sp->GetID()));
18690b57cec5SDimitry Andric               handled = true;
18700b57cec5SDimitry Andric             }
18710b57cec5SDimitry Andric           }
18720b57cec5SDimitry Andric 
18730b57cec5SDimitry Andric           if (!handled && signo && !did_exec) {
18740b57cec5SDimitry Andric             if (signo == SIGTRAP) {
18750b57cec5SDimitry Andric               // Currently we are going to assume SIGTRAP means we are either
18760b57cec5SDimitry Andric               // hitting a breakpoint or hardware single stepping.
18770b57cec5SDimitry Andric               handled = true;
18780b57cec5SDimitry Andric               addr_t pc = thread_sp->GetRegisterContext()->GetPC() +
18790b57cec5SDimitry Andric                           m_breakpoint_pc_offset;
18800b57cec5SDimitry Andric               lldb::BreakpointSiteSP bp_site_sp = thread_sp->GetProcess()
18810b57cec5SDimitry Andric                                                       ->GetBreakpointSiteList()
18820b57cec5SDimitry Andric                                                       .FindByAddress(pc);
18830b57cec5SDimitry Andric 
18840b57cec5SDimitry Andric               if (bp_site_sp) {
18850b57cec5SDimitry Andric                 // If the breakpoint is for this thread, then we'll report the
18860b57cec5SDimitry Andric                 // hit, but if it is for another thread, we can just report no
18870b57cec5SDimitry Andric                 // reason.  We don't need to worry about stepping over the
18880b57cec5SDimitry Andric                 // breakpoint here, that will be taken care of when the thread
18890b57cec5SDimitry Andric                 // resumes and notices that there's a breakpoint under the pc.
1890fe6060f1SDimitry Andric                 if (bp_site_sp->ValidForThisThread(*thread_sp)) {
18910b57cec5SDimitry Andric                   if (m_breakpoint_pc_offset != 0)
18920b57cec5SDimitry Andric                     thread_sp->GetRegisterContext()->SetPC(pc);
18930b57cec5SDimitry Andric                   thread_sp->SetStopInfo(
18940b57cec5SDimitry Andric                       StopInfo::CreateStopReasonWithBreakpointSiteID(
18950b57cec5SDimitry Andric                           *thread_sp, bp_site_sp->GetID()));
18960b57cec5SDimitry Andric                 } else {
18970b57cec5SDimitry Andric                   StopInfoSP invalid_stop_info_sp;
18980b57cec5SDimitry Andric                   thread_sp->SetStopInfo(invalid_stop_info_sp);
18990b57cec5SDimitry Andric                 }
19000b57cec5SDimitry Andric               } else {
19010b57cec5SDimitry Andric                 // If we were stepping then assume the stop was the result of
19020b57cec5SDimitry Andric                 // the trace.  If we were not stepping then report the SIGTRAP.
19030b57cec5SDimitry Andric                 // FIXME: We are still missing the case where we single step
19040b57cec5SDimitry Andric                 // over a trap instruction.
19050b57cec5SDimitry Andric                 if (thread_sp->GetTemporaryResumeState() == eStateStepping)
19060b57cec5SDimitry Andric                   thread_sp->SetStopInfo(
19070b57cec5SDimitry Andric                       StopInfo::CreateStopReasonToTrace(*thread_sp));
19080b57cec5SDimitry Andric                 else
19090b57cec5SDimitry Andric                   thread_sp->SetStopInfo(StopInfo::CreateStopReasonWithSignal(
19100b57cec5SDimitry Andric                       *thread_sp, signo, description.c_str()));
19110b57cec5SDimitry Andric               }
19120b57cec5SDimitry Andric             }
19130b57cec5SDimitry Andric             if (!handled)
19140b57cec5SDimitry Andric               thread_sp->SetStopInfo(StopInfo::CreateStopReasonWithSignal(
19150b57cec5SDimitry Andric                   *thread_sp, signo, description.c_str()));
19160b57cec5SDimitry Andric           }
19170b57cec5SDimitry Andric 
19180b57cec5SDimitry Andric           if (!description.empty()) {
19190b57cec5SDimitry Andric             lldb::StopInfoSP stop_info_sp(thread_sp->GetStopInfo());
19200b57cec5SDimitry Andric             if (stop_info_sp) {
19210b57cec5SDimitry Andric               const char *stop_info_desc = stop_info_sp->GetDescription();
19220b57cec5SDimitry Andric               if (!stop_info_desc || !stop_info_desc[0])
19230b57cec5SDimitry Andric                 stop_info_sp->SetDescription(description.c_str());
19240b57cec5SDimitry Andric             } else {
19250b57cec5SDimitry Andric               thread_sp->SetStopInfo(StopInfo::CreateStopReasonWithException(
19260b57cec5SDimitry Andric                   *thread_sp, description.c_str()));
19270b57cec5SDimitry Andric             }
19280b57cec5SDimitry Andric           }
19290b57cec5SDimitry Andric         }
19300b57cec5SDimitry Andric       }
19310b57cec5SDimitry Andric     }
19320b57cec5SDimitry Andric   }
19330b57cec5SDimitry Andric   return thread_sp;
19340b57cec5SDimitry Andric }
19350b57cec5SDimitry Andric 
19360b57cec5SDimitry Andric lldb::ThreadSP
19370b57cec5SDimitry Andric ProcessGDBRemote::SetThreadStopInfo(StructuredData::Dictionary *thread_dict) {
19380b57cec5SDimitry Andric   static ConstString g_key_tid("tid");
19390b57cec5SDimitry Andric   static ConstString g_key_name("name");
19400b57cec5SDimitry Andric   static ConstString g_key_reason("reason");
19410b57cec5SDimitry Andric   static ConstString g_key_metype("metype");
19420b57cec5SDimitry Andric   static ConstString g_key_medata("medata");
19430b57cec5SDimitry Andric   static ConstString g_key_qaddr("qaddr");
19440b57cec5SDimitry Andric   static ConstString g_key_dispatch_queue_t("dispatch_queue_t");
19450b57cec5SDimitry Andric   static ConstString g_key_associated_with_dispatch_queue(
19460b57cec5SDimitry Andric       "associated_with_dispatch_queue");
19470b57cec5SDimitry Andric   static ConstString g_key_queue_name("qname");
19480b57cec5SDimitry Andric   static ConstString g_key_queue_kind("qkind");
19490b57cec5SDimitry Andric   static ConstString g_key_queue_serial_number("qserialnum");
19500b57cec5SDimitry Andric   static ConstString g_key_registers("registers");
19510b57cec5SDimitry Andric   static ConstString g_key_memory("memory");
19520b57cec5SDimitry Andric   static ConstString g_key_address("address");
19530b57cec5SDimitry Andric   static ConstString g_key_bytes("bytes");
19540b57cec5SDimitry Andric   static ConstString g_key_description("description");
19550b57cec5SDimitry Andric   static ConstString g_key_signal("signal");
19560b57cec5SDimitry Andric 
19570b57cec5SDimitry Andric   // Stop with signal and thread info
19580b57cec5SDimitry Andric   lldb::tid_t tid = LLDB_INVALID_THREAD_ID;
19590b57cec5SDimitry Andric   uint8_t signo = 0;
19600b57cec5SDimitry Andric   std::string value;
19610b57cec5SDimitry Andric   std::string thread_name;
19620b57cec5SDimitry Andric   std::string reason;
19630b57cec5SDimitry Andric   std::string description;
19640b57cec5SDimitry Andric   uint32_t exc_type = 0;
19650b57cec5SDimitry Andric   std::vector<addr_t> exc_data;
19660b57cec5SDimitry Andric   addr_t thread_dispatch_qaddr = LLDB_INVALID_ADDRESS;
19670b57cec5SDimitry Andric   ExpeditedRegisterMap expedited_register_map;
19680b57cec5SDimitry Andric   bool queue_vars_valid = false;
19690b57cec5SDimitry Andric   addr_t dispatch_queue_t = LLDB_INVALID_ADDRESS;
19700b57cec5SDimitry Andric   LazyBool associated_with_dispatch_queue = eLazyBoolCalculate;
19710b57cec5SDimitry Andric   std::string queue_name;
19720b57cec5SDimitry Andric   QueueKind queue_kind = eQueueKindUnknown;
19730b57cec5SDimitry Andric   uint64_t queue_serial_number = 0;
19740b57cec5SDimitry Andric   // Iterate through all of the thread dictionary key/value pairs from the
19750b57cec5SDimitry Andric   // structured data dictionary
19760b57cec5SDimitry Andric 
1977349cc55cSDimitry Andric   // FIXME: we're silently ignoring invalid data here
19780b57cec5SDimitry Andric   thread_dict->ForEach([this, &tid, &expedited_register_map, &thread_name,
19790b57cec5SDimitry Andric                         &signo, &reason, &description, &exc_type, &exc_data,
19800b57cec5SDimitry Andric                         &thread_dispatch_qaddr, &queue_vars_valid,
19810b57cec5SDimitry Andric                         &associated_with_dispatch_queue, &dispatch_queue_t,
19820b57cec5SDimitry Andric                         &queue_name, &queue_kind, &queue_serial_number](
19830b57cec5SDimitry Andric                            ConstString key,
19840b57cec5SDimitry Andric                            StructuredData::Object *object) -> bool {
19850b57cec5SDimitry Andric     if (key == g_key_tid) {
19860b57cec5SDimitry Andric       // thread in big endian hex
19870b57cec5SDimitry Andric       tid = object->GetIntegerValue(LLDB_INVALID_THREAD_ID);
19880b57cec5SDimitry Andric     } else if (key == g_key_metype) {
19890b57cec5SDimitry Andric       // exception type in big endian hex
19900b57cec5SDimitry Andric       exc_type = object->GetIntegerValue(0);
19910b57cec5SDimitry Andric     } else if (key == g_key_medata) {
19920b57cec5SDimitry Andric       // exception data in big endian hex
19930b57cec5SDimitry Andric       StructuredData::Array *array = object->GetAsArray();
19940b57cec5SDimitry Andric       if (array) {
19950b57cec5SDimitry Andric         array->ForEach([&exc_data](StructuredData::Object *object) -> bool {
19960b57cec5SDimitry Andric           exc_data.push_back(object->GetIntegerValue());
19970b57cec5SDimitry Andric           return true; // Keep iterating through all array items
19980b57cec5SDimitry Andric         });
19990b57cec5SDimitry Andric       }
20000b57cec5SDimitry Andric     } else if (key == g_key_name) {
20015ffd83dbSDimitry Andric       thread_name = std::string(object->GetStringValue());
20020b57cec5SDimitry Andric     } else if (key == g_key_qaddr) {
20030b57cec5SDimitry Andric       thread_dispatch_qaddr = object->GetIntegerValue(LLDB_INVALID_ADDRESS);
20040b57cec5SDimitry Andric     } else if (key == g_key_queue_name) {
20050b57cec5SDimitry Andric       queue_vars_valid = true;
20065ffd83dbSDimitry Andric       queue_name = std::string(object->GetStringValue());
20070b57cec5SDimitry Andric     } else if (key == g_key_queue_kind) {
20085ffd83dbSDimitry Andric       std::string queue_kind_str = std::string(object->GetStringValue());
20090b57cec5SDimitry Andric       if (queue_kind_str == "serial") {
20100b57cec5SDimitry Andric         queue_vars_valid = true;
20110b57cec5SDimitry Andric         queue_kind = eQueueKindSerial;
20120b57cec5SDimitry Andric       } else if (queue_kind_str == "concurrent") {
20130b57cec5SDimitry Andric         queue_vars_valid = true;
20140b57cec5SDimitry Andric         queue_kind = eQueueKindConcurrent;
20150b57cec5SDimitry Andric       }
20160b57cec5SDimitry Andric     } else if (key == g_key_queue_serial_number) {
20170b57cec5SDimitry Andric       queue_serial_number = object->GetIntegerValue(0);
20180b57cec5SDimitry Andric       if (queue_serial_number != 0)
20190b57cec5SDimitry Andric         queue_vars_valid = true;
20200b57cec5SDimitry Andric     } else if (key == g_key_dispatch_queue_t) {
20210b57cec5SDimitry Andric       dispatch_queue_t = object->GetIntegerValue(0);
20220b57cec5SDimitry Andric       if (dispatch_queue_t != 0 && dispatch_queue_t != LLDB_INVALID_ADDRESS)
20230b57cec5SDimitry Andric         queue_vars_valid = true;
20240b57cec5SDimitry Andric     } else if (key == g_key_associated_with_dispatch_queue) {
20250b57cec5SDimitry Andric       queue_vars_valid = true;
20260b57cec5SDimitry Andric       bool associated = object->GetBooleanValue();
20270b57cec5SDimitry Andric       if (associated)
20280b57cec5SDimitry Andric         associated_with_dispatch_queue = eLazyBoolYes;
20290b57cec5SDimitry Andric       else
20300b57cec5SDimitry Andric         associated_with_dispatch_queue = eLazyBoolNo;
20310b57cec5SDimitry Andric     } else if (key == g_key_reason) {
20325ffd83dbSDimitry Andric       reason = std::string(object->GetStringValue());
20330b57cec5SDimitry Andric     } else if (key == g_key_description) {
20345ffd83dbSDimitry Andric       description = std::string(object->GetStringValue());
20350b57cec5SDimitry Andric     } else if (key == g_key_registers) {
20360b57cec5SDimitry Andric       StructuredData::Dictionary *registers_dict = object->GetAsDictionary();
20370b57cec5SDimitry Andric 
20380b57cec5SDimitry Andric       if (registers_dict) {
20390b57cec5SDimitry Andric         registers_dict->ForEach(
20400b57cec5SDimitry Andric             [&expedited_register_map](ConstString key,
20410b57cec5SDimitry Andric                                       StructuredData::Object *object) -> bool {
2042349cc55cSDimitry Andric               uint32_t reg;
2043349cc55cSDimitry Andric               if (llvm::to_integer(key.AsCString(), reg))
20445ffd83dbSDimitry Andric                 expedited_register_map[reg] =
20455ffd83dbSDimitry Andric                     std::string(object->GetStringValue());
20460b57cec5SDimitry Andric               return true; // Keep iterating through all array items
20470b57cec5SDimitry Andric             });
20480b57cec5SDimitry Andric       }
20490b57cec5SDimitry Andric     } else if (key == g_key_memory) {
20500b57cec5SDimitry Andric       StructuredData::Array *array = object->GetAsArray();
20510b57cec5SDimitry Andric       if (array) {
20520b57cec5SDimitry Andric         array->ForEach([this](StructuredData::Object *object) -> bool {
20530b57cec5SDimitry Andric           StructuredData::Dictionary *mem_cache_dict =
20540b57cec5SDimitry Andric               object->GetAsDictionary();
20550b57cec5SDimitry Andric           if (mem_cache_dict) {
20560b57cec5SDimitry Andric             lldb::addr_t mem_cache_addr = LLDB_INVALID_ADDRESS;
20570b57cec5SDimitry Andric             if (mem_cache_dict->GetValueForKeyAsInteger<lldb::addr_t>(
20580b57cec5SDimitry Andric                     "address", mem_cache_addr)) {
20590b57cec5SDimitry Andric               if (mem_cache_addr != LLDB_INVALID_ADDRESS) {
20600b57cec5SDimitry Andric                 llvm::StringRef str;
20610b57cec5SDimitry Andric                 if (mem_cache_dict->GetValueForKeyAsString("bytes", str)) {
20620b57cec5SDimitry Andric                   StringExtractor bytes(str);
20630b57cec5SDimitry Andric                   bytes.SetFilePos(0);
20640b57cec5SDimitry Andric 
20650b57cec5SDimitry Andric                   const size_t byte_size = bytes.GetStringRef().size() / 2;
2066*81ad6265SDimitry Andric                   WritableDataBufferSP data_buffer_sp(
2067*81ad6265SDimitry Andric                       new DataBufferHeap(byte_size, 0));
20680b57cec5SDimitry Andric                   const size_t bytes_copied =
20690b57cec5SDimitry Andric                       bytes.GetHexBytes(data_buffer_sp->GetData(), 0);
20700b57cec5SDimitry Andric                   if (bytes_copied == byte_size)
20710b57cec5SDimitry Andric                     m_memory_cache.AddL1CacheData(mem_cache_addr,
20720b57cec5SDimitry Andric                                                   data_buffer_sp);
20730b57cec5SDimitry Andric                 }
20740b57cec5SDimitry Andric               }
20750b57cec5SDimitry Andric             }
20760b57cec5SDimitry Andric           }
20770b57cec5SDimitry Andric           return true; // Keep iterating through all array items
20780b57cec5SDimitry Andric         });
20790b57cec5SDimitry Andric       }
20800b57cec5SDimitry Andric 
20810b57cec5SDimitry Andric     } else if (key == g_key_signal)
20820b57cec5SDimitry Andric       signo = object->GetIntegerValue(LLDB_INVALID_SIGNAL_NUMBER);
20830b57cec5SDimitry Andric     return true; // Keep iterating through all dictionary key/value pairs
20840b57cec5SDimitry Andric   });
20850b57cec5SDimitry Andric 
20860b57cec5SDimitry Andric   return SetThreadStopInfo(tid, expedited_register_map, signo, thread_name,
20870b57cec5SDimitry Andric                            reason, description, exc_type, exc_data,
20880b57cec5SDimitry Andric                            thread_dispatch_qaddr, queue_vars_valid,
20890b57cec5SDimitry Andric                            associated_with_dispatch_queue, dispatch_queue_t,
20900b57cec5SDimitry Andric                            queue_name, queue_kind, queue_serial_number);
20910b57cec5SDimitry Andric }
20920b57cec5SDimitry Andric 
20930b57cec5SDimitry Andric StateType ProcessGDBRemote::SetThreadStopInfo(StringExtractor &stop_packet) {
2094fe6060f1SDimitry Andric   lldb::pid_t pid = m_gdb_comm.GetCurrentProcessID();
20950b57cec5SDimitry Andric   stop_packet.SetFilePos(0);
20960b57cec5SDimitry Andric   const char stop_type = stop_packet.GetChar();
20970b57cec5SDimitry Andric   switch (stop_type) {
20980b57cec5SDimitry Andric   case 'T':
20990b57cec5SDimitry Andric   case 'S': {
21000b57cec5SDimitry Andric     // This is a bit of a hack, but is is required. If we did exec, we need to
21010b57cec5SDimitry Andric     // clear our thread lists and also know to rebuild our dynamic register
21020b57cec5SDimitry Andric     // info before we lookup and threads and populate the expedited register
21030b57cec5SDimitry Andric     // values so we need to know this right away so we can cleanup and update
21040b57cec5SDimitry Andric     // our registers.
21050b57cec5SDimitry Andric     const uint32_t stop_id = GetStopID();
21060b57cec5SDimitry Andric     if (stop_id == 0) {
21070b57cec5SDimitry Andric       // Our first stop, make sure we have a process ID, and also make sure we
21080b57cec5SDimitry Andric       // know about our registers
2109fe6060f1SDimitry Andric       if (GetID() == LLDB_INVALID_PROCESS_ID && pid != LLDB_INVALID_PROCESS_ID)
21100b57cec5SDimitry Andric         SetID(pid);
21110b57cec5SDimitry Andric       BuildDynamicRegisterInfo(true);
21120b57cec5SDimitry Andric     }
21130b57cec5SDimitry Andric     // Stop with signal and thread info
2114fe6060f1SDimitry Andric     lldb::pid_t stop_pid = LLDB_INVALID_PROCESS_ID;
21150b57cec5SDimitry Andric     lldb::tid_t tid = LLDB_INVALID_THREAD_ID;
21160b57cec5SDimitry Andric     const uint8_t signo = stop_packet.GetHexU8();
21170b57cec5SDimitry Andric     llvm::StringRef key;
21180b57cec5SDimitry Andric     llvm::StringRef value;
21190b57cec5SDimitry Andric     std::string thread_name;
21200b57cec5SDimitry Andric     std::string reason;
21210b57cec5SDimitry Andric     std::string description;
21220b57cec5SDimitry Andric     uint32_t exc_type = 0;
21230b57cec5SDimitry Andric     std::vector<addr_t> exc_data;
21240b57cec5SDimitry Andric     addr_t thread_dispatch_qaddr = LLDB_INVALID_ADDRESS;
21250b57cec5SDimitry Andric     bool queue_vars_valid =
21260b57cec5SDimitry Andric         false; // says if locals below that start with "queue_" are valid
21270b57cec5SDimitry Andric     addr_t dispatch_queue_t = LLDB_INVALID_ADDRESS;
21280b57cec5SDimitry Andric     LazyBool associated_with_dispatch_queue = eLazyBoolCalculate;
21290b57cec5SDimitry Andric     std::string queue_name;
21300b57cec5SDimitry Andric     QueueKind queue_kind = eQueueKindUnknown;
21310b57cec5SDimitry Andric     uint64_t queue_serial_number = 0;
21320b57cec5SDimitry Andric     ExpeditedRegisterMap expedited_register_map;
21330b57cec5SDimitry Andric     while (stop_packet.GetNameColonValue(key, value)) {
21340b57cec5SDimitry Andric       if (key.compare("metype") == 0) {
21350b57cec5SDimitry Andric         // exception type in big endian hex
21360b57cec5SDimitry Andric         value.getAsInteger(16, exc_type);
21370b57cec5SDimitry Andric       } else if (key.compare("medata") == 0) {
21380b57cec5SDimitry Andric         // exception data in big endian hex
21390b57cec5SDimitry Andric         uint64_t x;
21400b57cec5SDimitry Andric         value.getAsInteger(16, x);
21410b57cec5SDimitry Andric         exc_data.push_back(x);
21420b57cec5SDimitry Andric       } else if (key.compare("thread") == 0) {
2143fe6060f1SDimitry Andric         // thread-id
2144fe6060f1SDimitry Andric         StringExtractorGDBRemote thread_id{value};
2145fe6060f1SDimitry Andric         auto pid_tid = thread_id.GetPidTid(pid);
2146fe6060f1SDimitry Andric         if (pid_tid) {
2147fe6060f1SDimitry Andric           stop_pid = pid_tid->first;
2148fe6060f1SDimitry Andric           tid = pid_tid->second;
2149fe6060f1SDimitry Andric         } else
21500b57cec5SDimitry Andric           tid = LLDB_INVALID_THREAD_ID;
21510b57cec5SDimitry Andric       } else if (key.compare("threads") == 0) {
21520b57cec5SDimitry Andric         std::lock_guard<std::recursive_mutex> guard(
21530b57cec5SDimitry Andric             m_thread_list_real.GetMutex());
2154fe6060f1SDimitry Andric         UpdateThreadIDsFromStopReplyThreadsValue(value);
21550b57cec5SDimitry Andric       } else if (key.compare("thread-pcs") == 0) {
21560b57cec5SDimitry Andric         m_thread_pcs.clear();
21570b57cec5SDimitry Andric         // A comma separated list of all threads in the current
21580b57cec5SDimitry Andric         // process that includes the thread for this stop reply packet
21590b57cec5SDimitry Andric         lldb::addr_t pc;
21600b57cec5SDimitry Andric         while (!value.empty()) {
21610b57cec5SDimitry Andric           llvm::StringRef pc_str;
21620b57cec5SDimitry Andric           std::tie(pc_str, value) = value.split(',');
21630b57cec5SDimitry Andric           if (pc_str.getAsInteger(16, pc))
21640b57cec5SDimitry Andric             pc = LLDB_INVALID_ADDRESS;
21650b57cec5SDimitry Andric           m_thread_pcs.push_back(pc);
21660b57cec5SDimitry Andric         }
21670b57cec5SDimitry Andric       } else if (key.compare("jstopinfo") == 0) {
21680b57cec5SDimitry Andric         StringExtractor json_extractor(value);
21690b57cec5SDimitry Andric         std::string json;
21700b57cec5SDimitry Andric         // Now convert the HEX bytes into a string value
21710b57cec5SDimitry Andric         json_extractor.GetHexByteString(json);
21720b57cec5SDimitry Andric 
21730b57cec5SDimitry Andric         // This JSON contains thread IDs and thread stop info for all threads.
21740b57cec5SDimitry Andric         // It doesn't contain expedited registers, memory or queue info.
21750b57cec5SDimitry Andric         m_jstopinfo_sp = StructuredData::ParseJSON(json);
21760b57cec5SDimitry Andric       } else if (key.compare("hexname") == 0) {
21770b57cec5SDimitry Andric         StringExtractor name_extractor(value);
21780b57cec5SDimitry Andric         std::string name;
21790b57cec5SDimitry Andric         // Now convert the HEX bytes into a string value
21800b57cec5SDimitry Andric         name_extractor.GetHexByteString(thread_name);
21810b57cec5SDimitry Andric       } else if (key.compare("name") == 0) {
21825ffd83dbSDimitry Andric         thread_name = std::string(value);
21830b57cec5SDimitry Andric       } else if (key.compare("qaddr") == 0) {
21840b57cec5SDimitry Andric         value.getAsInteger(16, thread_dispatch_qaddr);
21850b57cec5SDimitry Andric       } else if (key.compare("dispatch_queue_t") == 0) {
21860b57cec5SDimitry Andric         queue_vars_valid = true;
21870b57cec5SDimitry Andric         value.getAsInteger(16, dispatch_queue_t);
21880b57cec5SDimitry Andric       } else if (key.compare("qname") == 0) {
21890b57cec5SDimitry Andric         queue_vars_valid = true;
21900b57cec5SDimitry Andric         StringExtractor name_extractor(value);
21910b57cec5SDimitry Andric         // Now convert the HEX bytes into a string value
21920b57cec5SDimitry Andric         name_extractor.GetHexByteString(queue_name);
21930b57cec5SDimitry Andric       } else if (key.compare("qkind") == 0) {
21940b57cec5SDimitry Andric         queue_kind = llvm::StringSwitch<QueueKind>(value)
21950b57cec5SDimitry Andric                          .Case("serial", eQueueKindSerial)
21960b57cec5SDimitry Andric                          .Case("concurrent", eQueueKindConcurrent)
21970b57cec5SDimitry Andric                          .Default(eQueueKindUnknown);
21980b57cec5SDimitry Andric         queue_vars_valid = queue_kind != eQueueKindUnknown;
21990b57cec5SDimitry Andric       } else if (key.compare("qserialnum") == 0) {
22000b57cec5SDimitry Andric         if (!value.getAsInteger(0, queue_serial_number))
22010b57cec5SDimitry Andric           queue_vars_valid = true;
22020b57cec5SDimitry Andric       } else if (key.compare("reason") == 0) {
22035ffd83dbSDimitry Andric         reason = std::string(value);
22040b57cec5SDimitry Andric       } else if (key.compare("description") == 0) {
22050b57cec5SDimitry Andric         StringExtractor desc_extractor(value);
22060b57cec5SDimitry Andric         // Now convert the HEX bytes into a string value
22070b57cec5SDimitry Andric         desc_extractor.GetHexByteString(description);
22080b57cec5SDimitry Andric       } else if (key.compare("memory") == 0) {
22090b57cec5SDimitry Andric         // Expedited memory. GDB servers can choose to send back expedited
22100b57cec5SDimitry Andric         // memory that can populate the L1 memory cache in the process so that
22110b57cec5SDimitry Andric         // things like the frame pointer backchain can be expedited. This will
22120b57cec5SDimitry Andric         // help stack backtracing be more efficient by not having to send as
22130b57cec5SDimitry Andric         // many memory read requests down the remote GDB server.
22140b57cec5SDimitry Andric 
22150b57cec5SDimitry Andric         // Key/value pair format: memory:<addr>=<bytes>;
22160b57cec5SDimitry Andric         // <addr> is a number whose base will be interpreted by the prefix:
22170b57cec5SDimitry Andric         //      "0x[0-9a-fA-F]+" for hex
22180b57cec5SDimitry Andric         //      "0[0-7]+" for octal
22190b57cec5SDimitry Andric         //      "[1-9]+" for decimal
22200b57cec5SDimitry Andric         // <bytes> is native endian ASCII hex bytes just like the register
22210b57cec5SDimitry Andric         // values
22220b57cec5SDimitry Andric         llvm::StringRef addr_str, bytes_str;
22230b57cec5SDimitry Andric         std::tie(addr_str, bytes_str) = value.split('=');
22240b57cec5SDimitry Andric         if (!addr_str.empty() && !bytes_str.empty()) {
22250b57cec5SDimitry Andric           lldb::addr_t mem_cache_addr = LLDB_INVALID_ADDRESS;
22260b57cec5SDimitry Andric           if (!addr_str.getAsInteger(0, mem_cache_addr)) {
22270b57cec5SDimitry Andric             StringExtractor bytes(bytes_str);
22280b57cec5SDimitry Andric             const size_t byte_size = bytes.GetBytesLeft() / 2;
2229*81ad6265SDimitry Andric             WritableDataBufferSP data_buffer_sp(
2230*81ad6265SDimitry Andric                 new DataBufferHeap(byte_size, 0));
22310b57cec5SDimitry Andric             const size_t bytes_copied =
22320b57cec5SDimitry Andric                 bytes.GetHexBytes(data_buffer_sp->GetData(), 0);
22330b57cec5SDimitry Andric             if (bytes_copied == byte_size)
22340b57cec5SDimitry Andric               m_memory_cache.AddL1CacheData(mem_cache_addr, data_buffer_sp);
22350b57cec5SDimitry Andric           }
22360b57cec5SDimitry Andric         }
22370b57cec5SDimitry Andric       } else if (key.compare("watch") == 0 || key.compare("rwatch") == 0 ||
22380b57cec5SDimitry Andric                  key.compare("awatch") == 0) {
22390b57cec5SDimitry Andric         // Support standard GDB remote stop reply packet 'TAAwatch:addr'
22400b57cec5SDimitry Andric         lldb::addr_t wp_addr = LLDB_INVALID_ADDRESS;
22410b57cec5SDimitry Andric         value.getAsInteger(16, wp_addr);
22420b57cec5SDimitry Andric 
22430b57cec5SDimitry Andric         WatchpointSP wp_sp =
22440b57cec5SDimitry Andric             GetTarget().GetWatchpointList().FindByAddress(wp_addr);
22450b57cec5SDimitry Andric         uint32_t wp_index = LLDB_INVALID_INDEX32;
22460b57cec5SDimitry Andric 
22470b57cec5SDimitry Andric         if (wp_sp)
22480b57cec5SDimitry Andric           wp_index = wp_sp->GetHardwareIndex();
22490b57cec5SDimitry Andric 
22500b57cec5SDimitry Andric         reason = "watchpoint";
22510b57cec5SDimitry Andric         StreamString ostr;
22520b57cec5SDimitry Andric         ostr.Printf("%" PRIu64 " %" PRIu32, wp_addr, wp_index);
22535ffd83dbSDimitry Andric         description = std::string(ostr.GetString());
22540b57cec5SDimitry Andric       } else if (key.compare("library") == 0) {
22559dba64beSDimitry Andric         auto error = LoadModules();
22569dba64beSDimitry Andric         if (error) {
22571fd87a68SDimitry Andric           Log *log(GetLog(GDBRLog::Process));
22589dba64beSDimitry Andric           LLDB_LOG_ERROR(log, std::move(error), "Failed to load modules: {0}");
22599dba64beSDimitry Andric         }
2260349cc55cSDimitry Andric       } else if (key.compare("fork") == 0 || key.compare("vfork") == 0) {
2261349cc55cSDimitry Andric         // fork includes child pid/tid in thread-id format
2262349cc55cSDimitry Andric         StringExtractorGDBRemote thread_id{value};
2263349cc55cSDimitry Andric         auto pid_tid = thread_id.GetPidTid(LLDB_INVALID_PROCESS_ID);
2264349cc55cSDimitry Andric         if (!pid_tid) {
22651fd87a68SDimitry Andric           Log *log(GetLog(GDBRLog::Process));
2266349cc55cSDimitry Andric           LLDB_LOG(log, "Invalid PID/TID to fork: {0}", value);
2267349cc55cSDimitry Andric           pid_tid = {{LLDB_INVALID_PROCESS_ID, LLDB_INVALID_THREAD_ID}};
2268349cc55cSDimitry Andric         }
2269349cc55cSDimitry Andric 
2270349cc55cSDimitry Andric         reason = key.str();
2271349cc55cSDimitry Andric         StreamString ostr;
2272349cc55cSDimitry Andric         ostr.Printf("%" PRIu64 " %" PRIu64, pid_tid->first, pid_tid->second);
2273349cc55cSDimitry Andric         description = std::string(ostr.GetString());
22740b57cec5SDimitry Andric       } else if (key.size() == 2 && ::isxdigit(key[0]) && ::isxdigit(key[1])) {
22750b57cec5SDimitry Andric         uint32_t reg = UINT32_MAX;
22760b57cec5SDimitry Andric         if (!key.getAsInteger(16, reg))
22775ffd83dbSDimitry Andric           expedited_register_map[reg] = std::string(std::move(value));
22780b57cec5SDimitry Andric       }
22790b57cec5SDimitry Andric     }
22800b57cec5SDimitry Andric 
2281fe6060f1SDimitry Andric     if (stop_pid != LLDB_INVALID_PROCESS_ID && stop_pid != pid) {
22821fd87a68SDimitry Andric       Log *log = GetLog(GDBRLog::Process);
2283fe6060f1SDimitry Andric       LLDB_LOG(log,
2284fe6060f1SDimitry Andric                "Received stop for incorrect PID = {0} (inferior PID = {1})",
2285fe6060f1SDimitry Andric                stop_pid, pid);
2286fe6060f1SDimitry Andric       return eStateInvalid;
2287fe6060f1SDimitry Andric     }
2288fe6060f1SDimitry Andric 
22890b57cec5SDimitry Andric     if (tid == LLDB_INVALID_THREAD_ID) {
22900b57cec5SDimitry Andric       // A thread id may be invalid if the response is old style 'S' packet
22910b57cec5SDimitry Andric       // which does not provide the
22920b57cec5SDimitry Andric       // thread information. So update the thread list and choose the first
22930b57cec5SDimitry Andric       // one.
22940b57cec5SDimitry Andric       UpdateThreadIDList();
22950b57cec5SDimitry Andric 
22960b57cec5SDimitry Andric       if (!m_thread_ids.empty()) {
22970b57cec5SDimitry Andric         tid = m_thread_ids.front();
22980b57cec5SDimitry Andric       }
22990b57cec5SDimitry Andric     }
23000b57cec5SDimitry Andric 
23010b57cec5SDimitry Andric     ThreadSP thread_sp = SetThreadStopInfo(
23020b57cec5SDimitry Andric         tid, expedited_register_map, signo, thread_name, reason, description,
23030b57cec5SDimitry Andric         exc_type, exc_data, thread_dispatch_qaddr, queue_vars_valid,
23040b57cec5SDimitry Andric         associated_with_dispatch_queue, dispatch_queue_t, queue_name,
23050b57cec5SDimitry Andric         queue_kind, queue_serial_number);
23060b57cec5SDimitry Andric 
23070b57cec5SDimitry Andric     return eStateStopped;
23080b57cec5SDimitry Andric   } break;
23090b57cec5SDimitry Andric 
23100b57cec5SDimitry Andric   case 'W':
23110b57cec5SDimitry Andric   case 'X':
23120b57cec5SDimitry Andric     // process exited
23130b57cec5SDimitry Andric     return eStateExited;
23140b57cec5SDimitry Andric 
23150b57cec5SDimitry Andric   default:
23160b57cec5SDimitry Andric     break;
23170b57cec5SDimitry Andric   }
23180b57cec5SDimitry Andric   return eStateInvalid;
23190b57cec5SDimitry Andric }
23200b57cec5SDimitry Andric 
23210b57cec5SDimitry Andric void ProcessGDBRemote::RefreshStateAfterStop() {
23220b57cec5SDimitry Andric   std::lock_guard<std::recursive_mutex> guard(m_thread_list_real.GetMutex());
23230b57cec5SDimitry Andric 
23240b57cec5SDimitry Andric   m_thread_ids.clear();
23250b57cec5SDimitry Andric   m_thread_pcs.clear();
2326480093f4SDimitry Andric 
23270b57cec5SDimitry Andric   // Set the thread stop info. It might have a "threads" key whose value is a
23280b57cec5SDimitry Andric   // list of all thread IDs in the current process, so m_thread_ids might get
23290b57cec5SDimitry Andric   // set.
23300b57cec5SDimitry Andric   // Check to see if SetThreadStopInfo() filled in m_thread_ids?
23310b57cec5SDimitry Andric   if (m_thread_ids.empty()) {
23320b57cec5SDimitry Andric       // No, we need to fetch the thread list manually
23330b57cec5SDimitry Andric       UpdateThreadIDList();
23340b57cec5SDimitry Andric   }
2335480093f4SDimitry Andric 
23360b57cec5SDimitry Andric   // We might set some stop info's so make sure the thread list is up to
23370b57cec5SDimitry Andric   // date before we do that or we might overwrite what was computed here.
23380b57cec5SDimitry Andric   UpdateThreadListIfNeeded();
23390b57cec5SDimitry Andric 
2340349cc55cSDimitry Andric   if (m_last_stop_packet)
2341349cc55cSDimitry Andric     SetThreadStopInfo(*m_last_stop_packet);
2342349cc55cSDimitry Andric   m_last_stop_packet.reset();
23430b57cec5SDimitry Andric 
23440b57cec5SDimitry Andric   // If we have queried for a default thread id
23450b57cec5SDimitry Andric   if (m_initial_tid != LLDB_INVALID_THREAD_ID) {
23460b57cec5SDimitry Andric     m_thread_list.SetSelectedThreadByID(m_initial_tid);
23470b57cec5SDimitry Andric     m_initial_tid = LLDB_INVALID_THREAD_ID;
23480b57cec5SDimitry Andric   }
23490b57cec5SDimitry Andric 
23500b57cec5SDimitry Andric   // Let all threads recover from stopping and do any clean up based on the
23510b57cec5SDimitry Andric   // previous thread state (if any).
23520b57cec5SDimitry Andric   m_thread_list_real.RefreshStateAfterStop();
23530b57cec5SDimitry Andric }
23540b57cec5SDimitry Andric 
23550b57cec5SDimitry Andric Status ProcessGDBRemote::DoHalt(bool &caused_stop) {
23560b57cec5SDimitry Andric   Status error;
23570b57cec5SDimitry Andric 
23580b57cec5SDimitry Andric   if (m_public_state.GetValue() == eStateAttaching) {
23590b57cec5SDimitry Andric     // We are being asked to halt during an attach. We need to just close our
23600b57cec5SDimitry Andric     // file handle and debugserver will go away, and we can be done...
23610b57cec5SDimitry Andric     m_gdb_comm.Disconnect();
23620b57cec5SDimitry Andric   } else
2363fe6060f1SDimitry Andric     caused_stop = m_gdb_comm.Interrupt(GetInterruptTimeout());
23640b57cec5SDimitry Andric   return error;
23650b57cec5SDimitry Andric }
23660b57cec5SDimitry Andric 
23670b57cec5SDimitry Andric Status ProcessGDBRemote::DoDetach(bool keep_stopped) {
23680b57cec5SDimitry Andric   Status error;
23691fd87a68SDimitry Andric   Log *log = GetLog(GDBRLog::Process);
23709dba64beSDimitry Andric   LLDB_LOGF(log, "ProcessGDBRemote::DoDetach(keep_stopped: %i)", keep_stopped);
23710b57cec5SDimitry Andric 
23720b57cec5SDimitry Andric   error = m_gdb_comm.Detach(keep_stopped);
23730b57cec5SDimitry Andric   if (log) {
23740b57cec5SDimitry Andric     if (error.Success())
23750b57cec5SDimitry Andric       log->PutCString(
23760b57cec5SDimitry Andric           "ProcessGDBRemote::DoDetach() detach packet sent successfully");
23770b57cec5SDimitry Andric     else
23789dba64beSDimitry Andric       LLDB_LOGF(log,
23799dba64beSDimitry Andric                 "ProcessGDBRemote::DoDetach() detach packet send failed: %s",
23800b57cec5SDimitry Andric                 error.AsCString() ? error.AsCString() : "<unknown error>");
23810b57cec5SDimitry Andric   }
23820b57cec5SDimitry Andric 
23830b57cec5SDimitry Andric   if (!error.Success())
23840b57cec5SDimitry Andric     return error;
23850b57cec5SDimitry Andric 
23860b57cec5SDimitry Andric   // Sleep for one second to let the process get all detached...
23870b57cec5SDimitry Andric   StopAsyncThread();
23880b57cec5SDimitry Andric 
23890b57cec5SDimitry Andric   SetPrivateState(eStateDetached);
23900b57cec5SDimitry Andric   ResumePrivateStateThread();
23910b57cec5SDimitry Andric 
23920b57cec5SDimitry Andric   // KillDebugserverProcess ();
23930b57cec5SDimitry Andric   return error;
23940b57cec5SDimitry Andric }
23950b57cec5SDimitry Andric 
23960b57cec5SDimitry Andric Status ProcessGDBRemote::DoDestroy() {
23970b57cec5SDimitry Andric   Status error;
23981fd87a68SDimitry Andric   Log *log = GetLog(GDBRLog::Process);
23999dba64beSDimitry Andric   LLDB_LOGF(log, "ProcessGDBRemote::DoDestroy()");
24000b57cec5SDimitry Andric 
24010b57cec5SDimitry Andric   // Interrupt if our inferior is running...
24020b57cec5SDimitry Andric   int exit_status = SIGABRT;
24030b57cec5SDimitry Andric   std::string exit_string;
24040b57cec5SDimitry Andric 
24050b57cec5SDimitry Andric   if (m_gdb_comm.IsConnected()) {
24060b57cec5SDimitry Andric     if (m_public_state.GetValue() != eStateAttaching) {
24070b57cec5SDimitry Andric       StringExtractorGDBRemote response;
24080b57cec5SDimitry Andric       GDBRemoteCommunication::ScopedTimeout(m_gdb_comm,
24090b57cec5SDimitry Andric                                             std::chrono::seconds(3));
24100b57cec5SDimitry Andric 
2411fe6060f1SDimitry Andric       if (m_gdb_comm.SendPacketAndWaitForResponse("k", response,
2412fe6060f1SDimitry Andric                                                   GetInterruptTimeout()) ==
24130b57cec5SDimitry Andric           GDBRemoteCommunication::PacketResult::Success) {
24140b57cec5SDimitry Andric         char packet_cmd = response.GetChar(0);
24150b57cec5SDimitry Andric 
24160b57cec5SDimitry Andric         if (packet_cmd == 'W' || packet_cmd == 'X') {
24170b57cec5SDimitry Andric #if defined(__APPLE__)
24180b57cec5SDimitry Andric           // For Native processes on Mac OS X, we launch through the Host
24190b57cec5SDimitry Andric           // Platform, then hand the process off to debugserver, which becomes
24200b57cec5SDimitry Andric           // the parent process through "PT_ATTACH".  Then when we go to kill
24210b57cec5SDimitry Andric           // the process on Mac OS X we call ptrace(PT_KILL) to kill it, then
24220b57cec5SDimitry Andric           // we call waitpid which returns with no error and the correct
24230b57cec5SDimitry Andric           // status.  But amusingly enough that doesn't seem to actually reap
24240b57cec5SDimitry Andric           // the process, but instead it is left around as a Zombie.  Probably
24250b57cec5SDimitry Andric           // the kernel is in the process of switching ownership back to lldb
24260b57cec5SDimitry Andric           // which was the original parent, and gets confused in the handoff.
24270b57cec5SDimitry Andric           // Anyway, so call waitpid here to finally reap it.
24280b57cec5SDimitry Andric           PlatformSP platform_sp(GetTarget().GetPlatform());
24290b57cec5SDimitry Andric           if (platform_sp && platform_sp->IsHost()) {
24300b57cec5SDimitry Andric             int status;
24310b57cec5SDimitry Andric             ::pid_t reap_pid;
24320b57cec5SDimitry Andric             reap_pid = waitpid(GetID(), &status, WNOHANG);
24339dba64beSDimitry Andric             LLDB_LOGF(log, "Reaped pid: %d, status: %d.\n", reap_pid, status);
24340b57cec5SDimitry Andric           }
24350b57cec5SDimitry Andric #endif
24360b57cec5SDimitry Andric           SetLastStopPacket(response);
24370b57cec5SDimitry Andric           ClearThreadIDList();
24380b57cec5SDimitry Andric           exit_status = response.GetHexU8();
24390b57cec5SDimitry Andric         } else {
24409dba64beSDimitry Andric           LLDB_LOGF(log,
24419dba64beSDimitry Andric                     "ProcessGDBRemote::DoDestroy - got unexpected response "
24420b57cec5SDimitry Andric                     "to k packet: %s",
24439dba64beSDimitry Andric                     response.GetStringRef().data());
24440b57cec5SDimitry Andric           exit_string.assign("got unexpected response to k packet: ");
24455ffd83dbSDimitry Andric           exit_string.append(std::string(response.GetStringRef()));
24460b57cec5SDimitry Andric         }
24470b57cec5SDimitry Andric       } else {
24489dba64beSDimitry Andric         LLDB_LOGF(log, "ProcessGDBRemote::DoDestroy - failed to send k packet");
24490b57cec5SDimitry Andric         exit_string.assign("failed to send the k packet");
24500b57cec5SDimitry Andric       }
24510b57cec5SDimitry Andric     } else {
24529dba64beSDimitry Andric       LLDB_LOGF(log,
24539dba64beSDimitry Andric                 "ProcessGDBRemote::DoDestroy - killed or interrupted while "
24540b57cec5SDimitry Andric                 "attaching");
24550b57cec5SDimitry Andric       exit_string.assign("killed or interrupted while attaching.");
24560b57cec5SDimitry Andric     }
24570b57cec5SDimitry Andric   } else {
24580b57cec5SDimitry Andric     // If we missed setting the exit status on the way out, do it here.
24590b57cec5SDimitry Andric     // NB set exit status can be called multiple times, the first one sets the
24600b57cec5SDimitry Andric     // status.
24610b57cec5SDimitry Andric     exit_string.assign("destroying when not connected to debugserver");
24620b57cec5SDimitry Andric   }
24630b57cec5SDimitry Andric 
24640b57cec5SDimitry Andric   SetExitStatus(exit_status, exit_string.c_str());
24650b57cec5SDimitry Andric 
24660b57cec5SDimitry Andric   StopAsyncThread();
24670b57cec5SDimitry Andric   KillDebugserverProcess();
24680b57cec5SDimitry Andric   return error;
24690b57cec5SDimitry Andric }
24700b57cec5SDimitry Andric 
24710b57cec5SDimitry Andric void ProcessGDBRemote::SetLastStopPacket(
24720b57cec5SDimitry Andric     const StringExtractorGDBRemote &response) {
24730b57cec5SDimitry Andric   const bool did_exec =
24740b57cec5SDimitry Andric       response.GetStringRef().find(";reason:exec;") != std::string::npos;
24750b57cec5SDimitry Andric   if (did_exec) {
24761fd87a68SDimitry Andric     Log *log = GetLog(GDBRLog::Process);
24779dba64beSDimitry Andric     LLDB_LOGF(log, "ProcessGDBRemote::SetLastStopPacket () - detected exec");
24780b57cec5SDimitry Andric 
24790b57cec5SDimitry Andric     m_thread_list_real.Clear();
24800b57cec5SDimitry Andric     m_thread_list.Clear();
24810b57cec5SDimitry Andric     BuildDynamicRegisterInfo(true);
24820b57cec5SDimitry Andric     m_gdb_comm.ResetDiscoverableSettings(did_exec);
24830b57cec5SDimitry Andric   }
24840b57cec5SDimitry Andric 
2485349cc55cSDimitry Andric   m_last_stop_packet = response;
24860b57cec5SDimitry Andric }
24870b57cec5SDimitry Andric 
24880b57cec5SDimitry Andric void ProcessGDBRemote::SetUnixSignals(const UnixSignalsSP &signals_sp) {
24890b57cec5SDimitry Andric   Process::SetUnixSignals(std::make_shared<GDBRemoteSignals>(signals_sp));
24900b57cec5SDimitry Andric }
24910b57cec5SDimitry Andric 
24920b57cec5SDimitry Andric // Process Queries
24930b57cec5SDimitry Andric 
24940b57cec5SDimitry Andric bool ProcessGDBRemote::IsAlive() {
24950b57cec5SDimitry Andric   return m_gdb_comm.IsConnected() && Process::IsAlive();
24960b57cec5SDimitry Andric }
24970b57cec5SDimitry Andric 
24980b57cec5SDimitry Andric addr_t ProcessGDBRemote::GetImageInfoAddress() {
24990b57cec5SDimitry Andric   // request the link map address via the $qShlibInfoAddr packet
25000b57cec5SDimitry Andric   lldb::addr_t addr = m_gdb_comm.GetShlibInfoAddr();
25010b57cec5SDimitry Andric 
25020b57cec5SDimitry Andric   // the loaded module list can also provides a link map address
25030b57cec5SDimitry Andric   if (addr == LLDB_INVALID_ADDRESS) {
25049dba64beSDimitry Andric     llvm::Expected<LoadedModuleInfoList> list = GetLoadedModuleList();
25059dba64beSDimitry Andric     if (!list) {
25061fd87a68SDimitry Andric       Log *log = GetLog(GDBRLog::Process);
2507e8d8bef9SDimitry Andric       LLDB_LOG_ERROR(log, list.takeError(), "Failed to read module list: {0}.");
25089dba64beSDimitry Andric     } else {
25099dba64beSDimitry Andric       addr = list->m_link_map;
25109dba64beSDimitry Andric     }
25110b57cec5SDimitry Andric   }
25120b57cec5SDimitry Andric 
25130b57cec5SDimitry Andric   return addr;
25140b57cec5SDimitry Andric }
25150b57cec5SDimitry Andric 
25160b57cec5SDimitry Andric void ProcessGDBRemote::WillPublicStop() {
25170b57cec5SDimitry Andric   // See if the GDB remote client supports the JSON threads info. If so, we
25180b57cec5SDimitry Andric   // gather stop info for all threads, expedited registers, expedited memory,
25190b57cec5SDimitry Andric   // runtime queue information (iOS and MacOSX only), and more. Expediting
25200b57cec5SDimitry Andric   // memory will help stack backtracing be much faster. Expediting registers
25210b57cec5SDimitry Andric   // will make sure we don't have to read the thread registers for GPRs.
25220b57cec5SDimitry Andric   m_jthreadsinfo_sp = m_gdb_comm.GetThreadsInfo();
25230b57cec5SDimitry Andric 
25240b57cec5SDimitry Andric   if (m_jthreadsinfo_sp) {
25250b57cec5SDimitry Andric     // Now set the stop info for each thread and also expedite any registers
25260b57cec5SDimitry Andric     // and memory that was in the jThreadsInfo response.
25270b57cec5SDimitry Andric     StructuredData::Array *thread_infos = m_jthreadsinfo_sp->GetAsArray();
25280b57cec5SDimitry Andric     if (thread_infos) {
25290b57cec5SDimitry Andric       const size_t n = thread_infos->GetSize();
25300b57cec5SDimitry Andric       for (size_t i = 0; i < n; ++i) {
25310b57cec5SDimitry Andric         StructuredData::Dictionary *thread_dict =
25320b57cec5SDimitry Andric             thread_infos->GetItemAtIndex(i)->GetAsDictionary();
25330b57cec5SDimitry Andric         if (thread_dict)
25340b57cec5SDimitry Andric           SetThreadStopInfo(thread_dict);
25350b57cec5SDimitry Andric       }
25360b57cec5SDimitry Andric     }
25370b57cec5SDimitry Andric   }
25380b57cec5SDimitry Andric }
25390b57cec5SDimitry Andric 
25400b57cec5SDimitry Andric // Process Memory
25410b57cec5SDimitry Andric size_t ProcessGDBRemote::DoReadMemory(addr_t addr, void *buf, size_t size,
25420b57cec5SDimitry Andric                                       Status &error) {
25430b57cec5SDimitry Andric   GetMaxMemorySize();
25440b57cec5SDimitry Andric   bool binary_memory_read = m_gdb_comm.GetxPacketSupported();
25450b57cec5SDimitry Andric   // M and m packets take 2 bytes for 1 byte of memory
25460b57cec5SDimitry Andric   size_t max_memory_size =
25470b57cec5SDimitry Andric       binary_memory_read ? m_max_memory_size : m_max_memory_size / 2;
25480b57cec5SDimitry Andric   if (size > max_memory_size) {
25490b57cec5SDimitry Andric     // Keep memory read sizes down to a sane limit. This function will be
25500b57cec5SDimitry Andric     // called multiple times in order to complete the task by
25510b57cec5SDimitry Andric     // lldb_private::Process so it is ok to do this.
25520b57cec5SDimitry Andric     size = max_memory_size;
25530b57cec5SDimitry Andric   }
25540b57cec5SDimitry Andric 
25550b57cec5SDimitry Andric   char packet[64];
25560b57cec5SDimitry Andric   int packet_len;
25570b57cec5SDimitry Andric   packet_len = ::snprintf(packet, sizeof(packet), "%c%" PRIx64 ",%" PRIx64,
25580b57cec5SDimitry Andric                           binary_memory_read ? 'x' : 'm', (uint64_t)addr,
25590b57cec5SDimitry Andric                           (uint64_t)size);
25600b57cec5SDimitry Andric   assert(packet_len + 1 < (int)sizeof(packet));
25610b57cec5SDimitry Andric   UNUSED_IF_ASSERT_DISABLED(packet_len);
25620b57cec5SDimitry Andric   StringExtractorGDBRemote response;
2563fe6060f1SDimitry Andric   if (m_gdb_comm.SendPacketAndWaitForResponse(packet, response,
2564fe6060f1SDimitry Andric                                               GetInterruptTimeout()) ==
25650b57cec5SDimitry Andric       GDBRemoteCommunication::PacketResult::Success) {
25660b57cec5SDimitry Andric     if (response.IsNormalResponse()) {
25670b57cec5SDimitry Andric       error.Clear();
25680b57cec5SDimitry Andric       if (binary_memory_read) {
25690b57cec5SDimitry Andric         // The lower level GDBRemoteCommunication packet receive layer has
25700b57cec5SDimitry Andric         // already de-quoted any 0x7d character escaping that was present in
25710b57cec5SDimitry Andric         // the packet
25720b57cec5SDimitry Andric 
25730b57cec5SDimitry Andric         size_t data_received_size = response.GetBytesLeft();
25740b57cec5SDimitry Andric         if (data_received_size > size) {
25750b57cec5SDimitry Andric           // Don't write past the end of BUF if the remote debug server gave us
25760b57cec5SDimitry Andric           // too much data for some reason.
25770b57cec5SDimitry Andric           data_received_size = size;
25780b57cec5SDimitry Andric         }
25790b57cec5SDimitry Andric         memcpy(buf, response.GetStringRef().data(), data_received_size);
25800b57cec5SDimitry Andric         return data_received_size;
25810b57cec5SDimitry Andric       } else {
25820b57cec5SDimitry Andric         return response.GetHexBytes(
25830b57cec5SDimitry Andric             llvm::MutableArrayRef<uint8_t>((uint8_t *)buf, size), '\xdd');
25840b57cec5SDimitry Andric       }
25850b57cec5SDimitry Andric     } else if (response.IsErrorResponse())
25860b57cec5SDimitry Andric       error.SetErrorStringWithFormat("memory read failed for 0x%" PRIx64, addr);
25870b57cec5SDimitry Andric     else if (response.IsUnsupportedResponse())
25880b57cec5SDimitry Andric       error.SetErrorStringWithFormat(
25890b57cec5SDimitry Andric           "GDB server does not support reading memory");
25900b57cec5SDimitry Andric     else
25910b57cec5SDimitry Andric       error.SetErrorStringWithFormat(
25920b57cec5SDimitry Andric           "unexpected response to GDB server memory read packet '%s': '%s'",
25939dba64beSDimitry Andric           packet, response.GetStringRef().data());
25940b57cec5SDimitry Andric   } else {
25950b57cec5SDimitry Andric     error.SetErrorStringWithFormat("failed to send packet: '%s'", packet);
25960b57cec5SDimitry Andric   }
25970b57cec5SDimitry Andric   return 0;
25980b57cec5SDimitry Andric }
25990b57cec5SDimitry Andric 
2600fe6060f1SDimitry Andric bool ProcessGDBRemote::SupportsMemoryTagging() {
2601fe6060f1SDimitry Andric   return m_gdb_comm.GetMemoryTaggingSupported();
2602fe6060f1SDimitry Andric }
2603fe6060f1SDimitry Andric 
2604fe6060f1SDimitry Andric llvm::Expected<std::vector<uint8_t>>
2605fe6060f1SDimitry Andric ProcessGDBRemote::DoReadMemoryTags(lldb::addr_t addr, size_t len,
2606fe6060f1SDimitry Andric                                    int32_t type) {
2607fe6060f1SDimitry Andric   // By this point ReadMemoryTags has validated that tagging is enabled
2608fe6060f1SDimitry Andric   // for this target/process/address.
2609fe6060f1SDimitry Andric   DataBufferSP buffer_sp = m_gdb_comm.ReadMemoryTags(addr, len, type);
2610fe6060f1SDimitry Andric   if (!buffer_sp) {
2611fe6060f1SDimitry Andric     return llvm::createStringError(llvm::inconvertibleErrorCode(),
2612fe6060f1SDimitry Andric                                    "Error reading memory tags from remote");
2613fe6060f1SDimitry Andric   }
2614fe6060f1SDimitry Andric 
2615fe6060f1SDimitry Andric   // Return the raw tag data
2616fe6060f1SDimitry Andric   llvm::ArrayRef<uint8_t> tag_data = buffer_sp->GetData();
2617fe6060f1SDimitry Andric   std::vector<uint8_t> got;
2618fe6060f1SDimitry Andric   got.reserve(tag_data.size());
2619fe6060f1SDimitry Andric   std::copy(tag_data.begin(), tag_data.end(), std::back_inserter(got));
2620fe6060f1SDimitry Andric   return got;
2621fe6060f1SDimitry Andric }
2622fe6060f1SDimitry Andric 
2623fe6060f1SDimitry Andric Status ProcessGDBRemote::DoWriteMemoryTags(lldb::addr_t addr, size_t len,
2624fe6060f1SDimitry Andric                                            int32_t type,
2625fe6060f1SDimitry Andric                                            const std::vector<uint8_t> &tags) {
2626fe6060f1SDimitry Andric   // By now WriteMemoryTags should have validated that tagging is enabled
2627fe6060f1SDimitry Andric   // for this target/process.
2628fe6060f1SDimitry Andric   return m_gdb_comm.WriteMemoryTags(addr, len, type, tags);
2629fe6060f1SDimitry Andric }
2630fe6060f1SDimitry Andric 
26310b57cec5SDimitry Andric Status ProcessGDBRemote::WriteObjectFile(
26320b57cec5SDimitry Andric     std::vector<ObjectFile::LoadableData> entries) {
26330b57cec5SDimitry Andric   Status error;
26340b57cec5SDimitry Andric   // Sort the entries by address because some writes, like those to flash
26350b57cec5SDimitry Andric   // memory, must happen in order of increasing address.
26360b57cec5SDimitry Andric   std::stable_sort(
26370b57cec5SDimitry Andric       std::begin(entries), std::end(entries),
26380b57cec5SDimitry Andric       [](const ObjectFile::LoadableData a, const ObjectFile::LoadableData b) {
26390b57cec5SDimitry Andric         return a.Dest < b.Dest;
26400b57cec5SDimitry Andric       });
26410b57cec5SDimitry Andric   m_allow_flash_writes = true;
26420b57cec5SDimitry Andric   error = Process::WriteObjectFile(entries);
26430b57cec5SDimitry Andric   if (error.Success())
26440b57cec5SDimitry Andric     error = FlashDone();
26450b57cec5SDimitry Andric   else
26460b57cec5SDimitry Andric     // Even though some of the writing failed, try to send a flash done if some
26470b57cec5SDimitry Andric     // of the writing succeeded so the flash state is reset to normal, but
26480b57cec5SDimitry Andric     // don't stomp on the error status that was set in the write failure since
26490b57cec5SDimitry Andric     // that's the one we want to report back.
26500b57cec5SDimitry Andric     FlashDone();
26510b57cec5SDimitry Andric   m_allow_flash_writes = false;
26520b57cec5SDimitry Andric   return error;
26530b57cec5SDimitry Andric }
26540b57cec5SDimitry Andric 
26550b57cec5SDimitry Andric bool ProcessGDBRemote::HasErased(FlashRange range) {
26560b57cec5SDimitry Andric   auto size = m_erased_flash_ranges.GetSize();
26570b57cec5SDimitry Andric   for (size_t i = 0; i < size; ++i)
26580b57cec5SDimitry Andric     if (m_erased_flash_ranges.GetEntryAtIndex(i)->Contains(range))
26590b57cec5SDimitry Andric       return true;
26600b57cec5SDimitry Andric   return false;
26610b57cec5SDimitry Andric }
26620b57cec5SDimitry Andric 
26630b57cec5SDimitry Andric Status ProcessGDBRemote::FlashErase(lldb::addr_t addr, size_t size) {
26640b57cec5SDimitry Andric   Status status;
26650b57cec5SDimitry Andric 
26660b57cec5SDimitry Andric   MemoryRegionInfo region;
26670b57cec5SDimitry Andric   status = GetMemoryRegionInfo(addr, region);
26680b57cec5SDimitry Andric   if (!status.Success())
26690b57cec5SDimitry Andric     return status;
26700b57cec5SDimitry Andric 
26710b57cec5SDimitry Andric   // The gdb spec doesn't say if erasures are allowed across multiple regions,
26720b57cec5SDimitry Andric   // but we'll disallow it to be safe and to keep the logic simple by worring
26730b57cec5SDimitry Andric   // about only one region's block size.  DoMemoryWrite is this function's
26740b57cec5SDimitry Andric   // primary user, and it can easily keep writes within a single memory region
26750b57cec5SDimitry Andric   if (addr + size > region.GetRange().GetRangeEnd()) {
26760b57cec5SDimitry Andric     status.SetErrorString("Unable to erase flash in multiple regions");
26770b57cec5SDimitry Andric     return status;
26780b57cec5SDimitry Andric   }
26790b57cec5SDimitry Andric 
26800b57cec5SDimitry Andric   uint64_t blocksize = region.GetBlocksize();
26810b57cec5SDimitry Andric   if (blocksize == 0) {
26820b57cec5SDimitry Andric     status.SetErrorString("Unable to erase flash because blocksize is 0");
26830b57cec5SDimitry Andric     return status;
26840b57cec5SDimitry Andric   }
26850b57cec5SDimitry Andric 
26860b57cec5SDimitry Andric   // Erasures can only be done on block boundary adresses, so round down addr
26870b57cec5SDimitry Andric   // and round up size
26880b57cec5SDimitry Andric   lldb::addr_t block_start_addr = addr - (addr % blocksize);
26890b57cec5SDimitry Andric   size += (addr - block_start_addr);
26900b57cec5SDimitry Andric   if ((size % blocksize) != 0)
26910b57cec5SDimitry Andric     size += (blocksize - size % blocksize);
26920b57cec5SDimitry Andric 
26930b57cec5SDimitry Andric   FlashRange range(block_start_addr, size);
26940b57cec5SDimitry Andric 
26950b57cec5SDimitry Andric   if (HasErased(range))
26960b57cec5SDimitry Andric     return status;
26970b57cec5SDimitry Andric 
26980b57cec5SDimitry Andric   // We haven't erased the entire range, but we may have erased part of it.
26990b57cec5SDimitry Andric   // (e.g., block A is already erased and range starts in A and ends in B). So,
27000b57cec5SDimitry Andric   // adjust range if necessary to exclude already erased blocks.
27010b57cec5SDimitry Andric   if (!m_erased_flash_ranges.IsEmpty()) {
27020b57cec5SDimitry Andric     // Assuming that writes and erasures are done in increasing addr order,
27030b57cec5SDimitry Andric     // because that is a requirement of the vFlashWrite command.  Therefore, we
27040b57cec5SDimitry Andric     // only need to look at the last range in the list for overlap.
27050b57cec5SDimitry Andric     const auto &last_range = *m_erased_flash_ranges.Back();
27060b57cec5SDimitry Andric     if (range.GetRangeBase() < last_range.GetRangeEnd()) {
27070b57cec5SDimitry Andric       auto overlap = last_range.GetRangeEnd() - range.GetRangeBase();
27080b57cec5SDimitry Andric       // overlap will be less than range.GetByteSize() or else HasErased()
27090b57cec5SDimitry Andric       // would have been true
27100b57cec5SDimitry Andric       range.SetByteSize(range.GetByteSize() - overlap);
27110b57cec5SDimitry Andric       range.SetRangeBase(range.GetRangeBase() + overlap);
27120b57cec5SDimitry Andric     }
27130b57cec5SDimitry Andric   }
27140b57cec5SDimitry Andric 
27150b57cec5SDimitry Andric   StreamString packet;
27160b57cec5SDimitry Andric   packet.Printf("vFlashErase:%" PRIx64 ",%" PRIx64, range.GetRangeBase(),
27170b57cec5SDimitry Andric                 (uint64_t)range.GetByteSize());
27180b57cec5SDimitry Andric 
27190b57cec5SDimitry Andric   StringExtractorGDBRemote response;
27200b57cec5SDimitry Andric   if (m_gdb_comm.SendPacketAndWaitForResponse(packet.GetString(), response,
2721fe6060f1SDimitry Andric                                               GetInterruptTimeout()) ==
27220b57cec5SDimitry Andric       GDBRemoteCommunication::PacketResult::Success) {
27230b57cec5SDimitry Andric     if (response.IsOKResponse()) {
27240b57cec5SDimitry Andric       m_erased_flash_ranges.Insert(range, true);
27250b57cec5SDimitry Andric     } else {
27260b57cec5SDimitry Andric       if (response.IsErrorResponse())
27270b57cec5SDimitry Andric         status.SetErrorStringWithFormat("flash erase failed for 0x%" PRIx64,
27280b57cec5SDimitry Andric                                         addr);
27290b57cec5SDimitry Andric       else if (response.IsUnsupportedResponse())
27300b57cec5SDimitry Andric         status.SetErrorStringWithFormat("GDB server does not support flashing");
27310b57cec5SDimitry Andric       else
27320b57cec5SDimitry Andric         status.SetErrorStringWithFormat(
27330b57cec5SDimitry Andric             "unexpected response to GDB server flash erase packet '%s': '%s'",
27349dba64beSDimitry Andric             packet.GetData(), response.GetStringRef().data());
27350b57cec5SDimitry Andric     }
27360b57cec5SDimitry Andric   } else {
27370b57cec5SDimitry Andric     status.SetErrorStringWithFormat("failed to send packet: '%s'",
27380b57cec5SDimitry Andric                                     packet.GetData());
27390b57cec5SDimitry Andric   }
27400b57cec5SDimitry Andric   return status;
27410b57cec5SDimitry Andric }
27420b57cec5SDimitry Andric 
27430b57cec5SDimitry Andric Status ProcessGDBRemote::FlashDone() {
27440b57cec5SDimitry Andric   Status status;
27450b57cec5SDimitry Andric   // If we haven't erased any blocks, then we must not have written anything
27460b57cec5SDimitry Andric   // either, so there is no need to actually send a vFlashDone command
27470b57cec5SDimitry Andric   if (m_erased_flash_ranges.IsEmpty())
27480b57cec5SDimitry Andric     return status;
27490b57cec5SDimitry Andric   StringExtractorGDBRemote response;
2750fe6060f1SDimitry Andric   if (m_gdb_comm.SendPacketAndWaitForResponse("vFlashDone", response,
2751fe6060f1SDimitry Andric                                               GetInterruptTimeout()) ==
27520b57cec5SDimitry Andric       GDBRemoteCommunication::PacketResult::Success) {
27530b57cec5SDimitry Andric     if (response.IsOKResponse()) {
27540b57cec5SDimitry Andric       m_erased_flash_ranges.Clear();
27550b57cec5SDimitry Andric     } else {
27560b57cec5SDimitry Andric       if (response.IsErrorResponse())
27570b57cec5SDimitry Andric         status.SetErrorStringWithFormat("flash done failed");
27580b57cec5SDimitry Andric       else if (response.IsUnsupportedResponse())
27590b57cec5SDimitry Andric         status.SetErrorStringWithFormat("GDB server does not support flashing");
27600b57cec5SDimitry Andric       else
27610b57cec5SDimitry Andric         status.SetErrorStringWithFormat(
27620b57cec5SDimitry Andric             "unexpected response to GDB server flash done packet: '%s'",
27639dba64beSDimitry Andric             response.GetStringRef().data());
27640b57cec5SDimitry Andric     }
27650b57cec5SDimitry Andric   } else {
27660b57cec5SDimitry Andric     status.SetErrorStringWithFormat("failed to send flash done packet");
27670b57cec5SDimitry Andric   }
27680b57cec5SDimitry Andric   return status;
27690b57cec5SDimitry Andric }
27700b57cec5SDimitry Andric 
27710b57cec5SDimitry Andric size_t ProcessGDBRemote::DoWriteMemory(addr_t addr, const void *buf,
27720b57cec5SDimitry Andric                                        size_t size, Status &error) {
27730b57cec5SDimitry Andric   GetMaxMemorySize();
27740b57cec5SDimitry Andric   // M and m packets take 2 bytes for 1 byte of memory
27750b57cec5SDimitry Andric   size_t max_memory_size = m_max_memory_size / 2;
27760b57cec5SDimitry Andric   if (size > max_memory_size) {
27770b57cec5SDimitry Andric     // Keep memory read sizes down to a sane limit. This function will be
27780b57cec5SDimitry Andric     // called multiple times in order to complete the task by
27790b57cec5SDimitry Andric     // lldb_private::Process so it is ok to do this.
27800b57cec5SDimitry Andric     size = max_memory_size;
27810b57cec5SDimitry Andric   }
27820b57cec5SDimitry Andric 
27830b57cec5SDimitry Andric   StreamGDBRemote packet;
27840b57cec5SDimitry Andric 
27850b57cec5SDimitry Andric   MemoryRegionInfo region;
27860b57cec5SDimitry Andric   Status region_status = GetMemoryRegionInfo(addr, region);
27870b57cec5SDimitry Andric 
27880b57cec5SDimitry Andric   bool is_flash =
27890b57cec5SDimitry Andric       region_status.Success() && region.GetFlash() == MemoryRegionInfo::eYes;
27900b57cec5SDimitry Andric 
27910b57cec5SDimitry Andric   if (is_flash) {
27920b57cec5SDimitry Andric     if (!m_allow_flash_writes) {
27930b57cec5SDimitry Andric       error.SetErrorString("Writing to flash memory is not allowed");
27940b57cec5SDimitry Andric       return 0;
27950b57cec5SDimitry Andric     }
27960b57cec5SDimitry Andric     // Keep the write within a flash memory region
27970b57cec5SDimitry Andric     if (addr + size > region.GetRange().GetRangeEnd())
27980b57cec5SDimitry Andric       size = region.GetRange().GetRangeEnd() - addr;
27990b57cec5SDimitry Andric     // Flash memory must be erased before it can be written
28000b57cec5SDimitry Andric     error = FlashErase(addr, size);
28010b57cec5SDimitry Andric     if (!error.Success())
28020b57cec5SDimitry Andric       return 0;
28030b57cec5SDimitry Andric     packet.Printf("vFlashWrite:%" PRIx64 ":", addr);
28040b57cec5SDimitry Andric     packet.PutEscapedBytes(buf, size);
28050b57cec5SDimitry Andric   } else {
28060b57cec5SDimitry Andric     packet.Printf("M%" PRIx64 ",%" PRIx64 ":", addr, (uint64_t)size);
28070b57cec5SDimitry Andric     packet.PutBytesAsRawHex8(buf, size, endian::InlHostByteOrder(),
28080b57cec5SDimitry Andric                              endian::InlHostByteOrder());
28090b57cec5SDimitry Andric   }
28100b57cec5SDimitry Andric   StringExtractorGDBRemote response;
28110b57cec5SDimitry Andric   if (m_gdb_comm.SendPacketAndWaitForResponse(packet.GetString(), response,
2812fe6060f1SDimitry Andric                                               GetInterruptTimeout()) ==
28130b57cec5SDimitry Andric       GDBRemoteCommunication::PacketResult::Success) {
28140b57cec5SDimitry Andric     if (response.IsOKResponse()) {
28150b57cec5SDimitry Andric       error.Clear();
28160b57cec5SDimitry Andric       return size;
28170b57cec5SDimitry Andric     } else if (response.IsErrorResponse())
28180b57cec5SDimitry Andric       error.SetErrorStringWithFormat("memory write failed for 0x%" PRIx64,
28190b57cec5SDimitry Andric                                      addr);
28200b57cec5SDimitry Andric     else if (response.IsUnsupportedResponse())
28210b57cec5SDimitry Andric       error.SetErrorStringWithFormat(
28220b57cec5SDimitry Andric           "GDB server does not support writing memory");
28230b57cec5SDimitry Andric     else
28240b57cec5SDimitry Andric       error.SetErrorStringWithFormat(
28250b57cec5SDimitry Andric           "unexpected response to GDB server memory write packet '%s': '%s'",
28269dba64beSDimitry Andric           packet.GetData(), response.GetStringRef().data());
28270b57cec5SDimitry Andric   } else {
28280b57cec5SDimitry Andric     error.SetErrorStringWithFormat("failed to send packet: '%s'",
28290b57cec5SDimitry Andric                                    packet.GetData());
28300b57cec5SDimitry Andric   }
28310b57cec5SDimitry Andric   return 0;
28320b57cec5SDimitry Andric }
28330b57cec5SDimitry Andric 
28340b57cec5SDimitry Andric lldb::addr_t ProcessGDBRemote::DoAllocateMemory(size_t size,
28350b57cec5SDimitry Andric                                                 uint32_t permissions,
28360b57cec5SDimitry Andric                                                 Status &error) {
2837*81ad6265SDimitry Andric   Log *log = GetLog(LLDBLog::Process | LLDBLog::Expressions);
28380b57cec5SDimitry Andric   addr_t allocated_addr = LLDB_INVALID_ADDRESS;
28390b57cec5SDimitry Andric 
28400b57cec5SDimitry Andric   if (m_gdb_comm.SupportsAllocDeallocMemory() != eLazyBoolNo) {
28410b57cec5SDimitry Andric     allocated_addr = m_gdb_comm.AllocateMemory(size, permissions);
28420b57cec5SDimitry Andric     if (allocated_addr != LLDB_INVALID_ADDRESS ||
28430b57cec5SDimitry Andric         m_gdb_comm.SupportsAllocDeallocMemory() == eLazyBoolYes)
28440b57cec5SDimitry Andric       return allocated_addr;
28450b57cec5SDimitry Andric   }
28460b57cec5SDimitry Andric 
28470b57cec5SDimitry Andric   if (m_gdb_comm.SupportsAllocDeallocMemory() == eLazyBoolNo) {
28480b57cec5SDimitry Andric     // Call mmap() to create memory in the inferior..
28490b57cec5SDimitry Andric     unsigned prot = 0;
28500b57cec5SDimitry Andric     if (permissions & lldb::ePermissionsReadable)
28510b57cec5SDimitry Andric       prot |= eMmapProtRead;
28520b57cec5SDimitry Andric     if (permissions & lldb::ePermissionsWritable)
28530b57cec5SDimitry Andric       prot |= eMmapProtWrite;
28540b57cec5SDimitry Andric     if (permissions & lldb::ePermissionsExecutable)
28550b57cec5SDimitry Andric       prot |= eMmapProtExec;
28560b57cec5SDimitry Andric 
28570b57cec5SDimitry Andric     if (InferiorCallMmap(this, allocated_addr, 0, size, prot,
28580b57cec5SDimitry Andric                          eMmapFlagsAnon | eMmapFlagsPrivate, -1, 0))
28590b57cec5SDimitry Andric       m_addr_to_mmap_size[allocated_addr] = size;
28600b57cec5SDimitry Andric     else {
28610b57cec5SDimitry Andric       allocated_addr = LLDB_INVALID_ADDRESS;
28629dba64beSDimitry Andric       LLDB_LOGF(log,
28639dba64beSDimitry Andric                 "ProcessGDBRemote::%s no direct stub support for memory "
28640b57cec5SDimitry Andric                 "allocation, and InferiorCallMmap also failed - is stub "
28650b57cec5SDimitry Andric                 "missing register context save/restore capability?",
28660b57cec5SDimitry Andric                 __FUNCTION__);
28670b57cec5SDimitry Andric     }
28680b57cec5SDimitry Andric   }
28690b57cec5SDimitry Andric 
28700b57cec5SDimitry Andric   if (allocated_addr == LLDB_INVALID_ADDRESS)
28710b57cec5SDimitry Andric     error.SetErrorStringWithFormat(
28720b57cec5SDimitry Andric         "unable to allocate %" PRIu64 " bytes of memory with permissions %s",
28730b57cec5SDimitry Andric         (uint64_t)size, GetPermissionsAsCString(permissions));
28740b57cec5SDimitry Andric   else
28750b57cec5SDimitry Andric     error.Clear();
28760b57cec5SDimitry Andric   return allocated_addr;
28770b57cec5SDimitry Andric }
28780b57cec5SDimitry Andric 
2879d56accc7SDimitry Andric Status ProcessGDBRemote::DoGetMemoryRegionInfo(addr_t load_addr,
28800b57cec5SDimitry Andric                                                MemoryRegionInfo &region_info) {
28810b57cec5SDimitry Andric 
28820b57cec5SDimitry Andric   Status error(m_gdb_comm.GetMemoryRegionInfo(load_addr, region_info));
28830b57cec5SDimitry Andric   return error;
28840b57cec5SDimitry Andric }
28850b57cec5SDimitry Andric 
28860b57cec5SDimitry Andric Status ProcessGDBRemote::GetWatchpointSupportInfo(uint32_t &num) {
28870b57cec5SDimitry Andric 
28880b57cec5SDimitry Andric   Status error(m_gdb_comm.GetWatchpointSupportInfo(num));
28890b57cec5SDimitry Andric   return error;
28900b57cec5SDimitry Andric }
28910b57cec5SDimitry Andric 
28920b57cec5SDimitry Andric Status ProcessGDBRemote::GetWatchpointSupportInfo(uint32_t &num, bool &after) {
28930b57cec5SDimitry Andric   Status error(m_gdb_comm.GetWatchpointSupportInfo(
28940b57cec5SDimitry Andric       num, after, GetTarget().GetArchitecture()));
28950b57cec5SDimitry Andric   return error;
28960b57cec5SDimitry Andric }
28970b57cec5SDimitry Andric 
28980b57cec5SDimitry Andric Status ProcessGDBRemote::DoDeallocateMemory(lldb::addr_t addr) {
28990b57cec5SDimitry Andric   Status error;
29000b57cec5SDimitry Andric   LazyBool supported = m_gdb_comm.SupportsAllocDeallocMemory();
29010b57cec5SDimitry Andric 
29020b57cec5SDimitry Andric   switch (supported) {
29030b57cec5SDimitry Andric   case eLazyBoolCalculate:
29040b57cec5SDimitry Andric     // We should never be deallocating memory without allocating memory first
29050b57cec5SDimitry Andric     // so we should never get eLazyBoolCalculate
29060b57cec5SDimitry Andric     error.SetErrorString(
29070b57cec5SDimitry Andric         "tried to deallocate memory without ever allocating memory");
29080b57cec5SDimitry Andric     break;
29090b57cec5SDimitry Andric 
29100b57cec5SDimitry Andric   case eLazyBoolYes:
29110b57cec5SDimitry Andric     if (!m_gdb_comm.DeallocateMemory(addr))
29120b57cec5SDimitry Andric       error.SetErrorStringWithFormat(
29130b57cec5SDimitry Andric           "unable to deallocate memory at 0x%" PRIx64, addr);
29140b57cec5SDimitry Andric     break;
29150b57cec5SDimitry Andric 
29160b57cec5SDimitry Andric   case eLazyBoolNo:
29170b57cec5SDimitry Andric     // Call munmap() to deallocate memory in the inferior..
29180b57cec5SDimitry Andric     {
29190b57cec5SDimitry Andric       MMapMap::iterator pos = m_addr_to_mmap_size.find(addr);
29200b57cec5SDimitry Andric       if (pos != m_addr_to_mmap_size.end() &&
29210b57cec5SDimitry Andric           InferiorCallMunmap(this, addr, pos->second))
29220b57cec5SDimitry Andric         m_addr_to_mmap_size.erase(pos);
29230b57cec5SDimitry Andric       else
29240b57cec5SDimitry Andric         error.SetErrorStringWithFormat(
29250b57cec5SDimitry Andric             "unable to deallocate memory at 0x%" PRIx64, addr);
29260b57cec5SDimitry Andric     }
29270b57cec5SDimitry Andric     break;
29280b57cec5SDimitry Andric   }
29290b57cec5SDimitry Andric 
29300b57cec5SDimitry Andric   return error;
29310b57cec5SDimitry Andric }
29320b57cec5SDimitry Andric 
29330b57cec5SDimitry Andric // Process STDIO
29340b57cec5SDimitry Andric size_t ProcessGDBRemote::PutSTDIN(const char *src, size_t src_len,
29350b57cec5SDimitry Andric                                   Status &error) {
29360b57cec5SDimitry Andric   if (m_stdio_communication.IsConnected()) {
29370b57cec5SDimitry Andric     ConnectionStatus status;
29380b57cec5SDimitry Andric     m_stdio_communication.Write(src, src_len, status, nullptr);
29390b57cec5SDimitry Andric   } else if (m_stdin_forward) {
29400b57cec5SDimitry Andric     m_gdb_comm.SendStdinNotification(src, src_len);
29410b57cec5SDimitry Andric   }
29420b57cec5SDimitry Andric   return 0;
29430b57cec5SDimitry Andric }
29440b57cec5SDimitry Andric 
29450b57cec5SDimitry Andric Status ProcessGDBRemote::EnableBreakpointSite(BreakpointSite *bp_site) {
29460b57cec5SDimitry Andric   Status error;
29470b57cec5SDimitry Andric   assert(bp_site != nullptr);
29480b57cec5SDimitry Andric 
29490b57cec5SDimitry Andric   // Get logging info
29501fd87a68SDimitry Andric   Log *log = GetLog(GDBRLog::Breakpoints);
29510b57cec5SDimitry Andric   user_id_t site_id = bp_site->GetID();
29520b57cec5SDimitry Andric 
29530b57cec5SDimitry Andric   // Get the breakpoint address
29540b57cec5SDimitry Andric   const addr_t addr = bp_site->GetLoadAddress();
29550b57cec5SDimitry Andric 
29560b57cec5SDimitry Andric   // Log that a breakpoint was requested
29579dba64beSDimitry Andric   LLDB_LOGF(log,
29589dba64beSDimitry Andric             "ProcessGDBRemote::EnableBreakpointSite (size_id = %" PRIu64
29590b57cec5SDimitry Andric             ") address = 0x%" PRIx64,
29600b57cec5SDimitry Andric             site_id, (uint64_t)addr);
29610b57cec5SDimitry Andric 
29620b57cec5SDimitry Andric   // Breakpoint already exists and is enabled
29630b57cec5SDimitry Andric   if (bp_site->IsEnabled()) {
29649dba64beSDimitry Andric     LLDB_LOGF(log,
29659dba64beSDimitry Andric               "ProcessGDBRemote::EnableBreakpointSite (size_id = %" PRIu64
29660b57cec5SDimitry Andric               ") address = 0x%" PRIx64 " -- SUCCESS (already enabled)",
29670b57cec5SDimitry Andric               site_id, (uint64_t)addr);
29680b57cec5SDimitry Andric     return error;
29690b57cec5SDimitry Andric   }
29700b57cec5SDimitry Andric 
29710b57cec5SDimitry Andric   // Get the software breakpoint trap opcode size
29720b57cec5SDimitry Andric   const size_t bp_op_size = GetSoftwareBreakpointTrapOpcode(bp_site);
29730b57cec5SDimitry Andric 
29740b57cec5SDimitry Andric   // SupportsGDBStoppointPacket() simply checks a boolean, indicating if this
29750b57cec5SDimitry Andric   // breakpoint type is supported by the remote stub. These are set to true by
29760b57cec5SDimitry Andric   // default, and later set to false only after we receive an unimplemented
29770b57cec5SDimitry Andric   // response when sending a breakpoint packet. This means initially that
29780b57cec5SDimitry Andric   // unless we were specifically instructed to use a hardware breakpoint, LLDB
29790b57cec5SDimitry Andric   // will attempt to set a software breakpoint. HardwareRequired() also queries
29800b57cec5SDimitry Andric   // a boolean variable which indicates if the user specifically asked for
29810b57cec5SDimitry Andric   // hardware breakpoints.  If true then we will skip over software
29820b57cec5SDimitry Andric   // breakpoints.
29830b57cec5SDimitry Andric   if (m_gdb_comm.SupportsGDBStoppointPacket(eBreakpointSoftware) &&
29840b57cec5SDimitry Andric       (!bp_site->HardwareRequired())) {
29850b57cec5SDimitry Andric     // Try to send off a software breakpoint packet ($Z0)
29860b57cec5SDimitry Andric     uint8_t error_no = m_gdb_comm.SendGDBStoppointTypePacket(
2987fe6060f1SDimitry Andric         eBreakpointSoftware, true, addr, bp_op_size, GetInterruptTimeout());
29880b57cec5SDimitry Andric     if (error_no == 0) {
29890b57cec5SDimitry Andric       // The breakpoint was placed successfully
29900b57cec5SDimitry Andric       bp_site->SetEnabled(true);
29910b57cec5SDimitry Andric       bp_site->SetType(BreakpointSite::eExternal);
29920b57cec5SDimitry Andric       return error;
29930b57cec5SDimitry Andric     }
29940b57cec5SDimitry Andric 
29950b57cec5SDimitry Andric     // SendGDBStoppointTypePacket() will return an error if it was unable to
29960b57cec5SDimitry Andric     // set this breakpoint. We need to differentiate between a error specific
29970b57cec5SDimitry Andric     // to placing this breakpoint or if we have learned that this breakpoint
29980b57cec5SDimitry Andric     // type is unsupported. To do this, we must test the support boolean for
29990b57cec5SDimitry Andric     // this breakpoint type to see if it now indicates that this breakpoint
30000b57cec5SDimitry Andric     // type is unsupported.  If they are still supported then we should return
30010b57cec5SDimitry Andric     // with the error code.  If they are now unsupported, then we would like to
30020b57cec5SDimitry Andric     // fall through and try another form of breakpoint.
30030b57cec5SDimitry Andric     if (m_gdb_comm.SupportsGDBStoppointPacket(eBreakpointSoftware)) {
30040b57cec5SDimitry Andric       if (error_no != UINT8_MAX)
30050b57cec5SDimitry Andric         error.SetErrorStringWithFormat(
30065ffd83dbSDimitry Andric             "error: %d sending the breakpoint request", error_no);
30070b57cec5SDimitry Andric       else
30080b57cec5SDimitry Andric         error.SetErrorString("error sending the breakpoint request");
30090b57cec5SDimitry Andric       return error;
30100b57cec5SDimitry Andric     }
30110b57cec5SDimitry Andric 
30120b57cec5SDimitry Andric     // We reach here when software breakpoints have been found to be
30130b57cec5SDimitry Andric     // unsupported. For future calls to set a breakpoint, we will not attempt
30140b57cec5SDimitry Andric     // to set a breakpoint with a type that is known not to be supported.
30159dba64beSDimitry Andric     LLDB_LOGF(log, "Software breakpoints are unsupported");
30160b57cec5SDimitry Andric 
30170b57cec5SDimitry Andric     // So we will fall through and try a hardware breakpoint
30180b57cec5SDimitry Andric   }
30190b57cec5SDimitry Andric 
30200b57cec5SDimitry Andric   // The process of setting a hardware breakpoint is much the same as above.
30210b57cec5SDimitry Andric   // We check the supported boolean for this breakpoint type, and if it is
30220b57cec5SDimitry Andric   // thought to be supported then we will try to set this breakpoint with a
30230b57cec5SDimitry Andric   // hardware breakpoint.
30240b57cec5SDimitry Andric   if (m_gdb_comm.SupportsGDBStoppointPacket(eBreakpointHardware)) {
30250b57cec5SDimitry Andric     // Try to send off a hardware breakpoint packet ($Z1)
30260b57cec5SDimitry Andric     uint8_t error_no = m_gdb_comm.SendGDBStoppointTypePacket(
3027fe6060f1SDimitry Andric         eBreakpointHardware, true, addr, bp_op_size, GetInterruptTimeout());
30280b57cec5SDimitry Andric     if (error_no == 0) {
30290b57cec5SDimitry Andric       // The breakpoint was placed successfully
30300b57cec5SDimitry Andric       bp_site->SetEnabled(true);
30310b57cec5SDimitry Andric       bp_site->SetType(BreakpointSite::eHardware);
30320b57cec5SDimitry Andric       return error;
30330b57cec5SDimitry Andric     }
30340b57cec5SDimitry Andric 
30350b57cec5SDimitry Andric     // Check if the error was something other then an unsupported breakpoint
30360b57cec5SDimitry Andric     // type
30370b57cec5SDimitry Andric     if (m_gdb_comm.SupportsGDBStoppointPacket(eBreakpointHardware)) {
30380b57cec5SDimitry Andric       // Unable to set this hardware breakpoint
30390b57cec5SDimitry Andric       if (error_no != UINT8_MAX)
30400b57cec5SDimitry Andric         error.SetErrorStringWithFormat(
30410b57cec5SDimitry Andric             "error: %d sending the hardware breakpoint request "
30420b57cec5SDimitry Andric             "(hardware breakpoint resources might be exhausted or unavailable)",
30430b57cec5SDimitry Andric             error_no);
30440b57cec5SDimitry Andric       else
30450b57cec5SDimitry Andric         error.SetErrorString("error sending the hardware breakpoint request "
30460b57cec5SDimitry Andric                              "(hardware breakpoint resources "
30470b57cec5SDimitry Andric                              "might be exhausted or unavailable)");
30480b57cec5SDimitry Andric       return error;
30490b57cec5SDimitry Andric     }
30500b57cec5SDimitry Andric 
30510b57cec5SDimitry Andric     // We will reach here when the stub gives an unsupported response to a
30520b57cec5SDimitry Andric     // hardware breakpoint
30539dba64beSDimitry Andric     LLDB_LOGF(log, "Hardware breakpoints are unsupported");
30540b57cec5SDimitry Andric 
30550b57cec5SDimitry Andric     // Finally we will falling through to a #trap style breakpoint
30560b57cec5SDimitry Andric   }
30570b57cec5SDimitry Andric 
30580b57cec5SDimitry Andric   // Don't fall through when hardware breakpoints were specifically requested
30590b57cec5SDimitry Andric   if (bp_site->HardwareRequired()) {
30600b57cec5SDimitry Andric     error.SetErrorString("hardware breakpoints are not supported");
30610b57cec5SDimitry Andric     return error;
30620b57cec5SDimitry Andric   }
30630b57cec5SDimitry Andric 
30640b57cec5SDimitry Andric   // As a last resort we want to place a manual breakpoint. An instruction is
30650b57cec5SDimitry Andric   // placed into the process memory using memory write packets.
30660b57cec5SDimitry Andric   return EnableSoftwareBreakpoint(bp_site);
30670b57cec5SDimitry Andric }
30680b57cec5SDimitry Andric 
30690b57cec5SDimitry Andric Status ProcessGDBRemote::DisableBreakpointSite(BreakpointSite *bp_site) {
30700b57cec5SDimitry Andric   Status error;
30710b57cec5SDimitry Andric   assert(bp_site != nullptr);
30720b57cec5SDimitry Andric   addr_t addr = bp_site->GetLoadAddress();
30730b57cec5SDimitry Andric   user_id_t site_id = bp_site->GetID();
30741fd87a68SDimitry Andric   Log *log = GetLog(GDBRLog::Breakpoints);
30759dba64beSDimitry Andric   LLDB_LOGF(log,
30769dba64beSDimitry Andric             "ProcessGDBRemote::DisableBreakpointSite (site_id = %" PRIu64
30770b57cec5SDimitry Andric             ") addr = 0x%8.8" PRIx64,
30780b57cec5SDimitry Andric             site_id, (uint64_t)addr);
30790b57cec5SDimitry Andric 
30800b57cec5SDimitry Andric   if (bp_site->IsEnabled()) {
30810b57cec5SDimitry Andric     const size_t bp_op_size = GetSoftwareBreakpointTrapOpcode(bp_site);
30820b57cec5SDimitry Andric 
30830b57cec5SDimitry Andric     BreakpointSite::Type bp_type = bp_site->GetType();
30840b57cec5SDimitry Andric     switch (bp_type) {
30850b57cec5SDimitry Andric     case BreakpointSite::eSoftware:
30860b57cec5SDimitry Andric       error = DisableSoftwareBreakpoint(bp_site);
30870b57cec5SDimitry Andric       break;
30880b57cec5SDimitry Andric 
30890b57cec5SDimitry Andric     case BreakpointSite::eHardware:
30900b57cec5SDimitry Andric       if (m_gdb_comm.SendGDBStoppointTypePacket(eBreakpointHardware, false,
3091fe6060f1SDimitry Andric                                                 addr, bp_op_size,
3092fe6060f1SDimitry Andric                                                 GetInterruptTimeout()))
30930b57cec5SDimitry Andric         error.SetErrorToGenericError();
30940b57cec5SDimitry Andric       break;
30950b57cec5SDimitry Andric 
30960b57cec5SDimitry Andric     case BreakpointSite::eExternal: {
3097e8d8bef9SDimitry Andric       if (m_gdb_comm.SendGDBStoppointTypePacket(eBreakpointSoftware, false,
3098fe6060f1SDimitry Andric                                                 addr, bp_op_size,
3099fe6060f1SDimitry Andric                                                 GetInterruptTimeout()))
31000b57cec5SDimitry Andric         error.SetErrorToGenericError();
31010b57cec5SDimitry Andric     } break;
31020b57cec5SDimitry Andric     }
31030b57cec5SDimitry Andric     if (error.Success())
31040b57cec5SDimitry Andric       bp_site->SetEnabled(false);
31050b57cec5SDimitry Andric   } else {
31069dba64beSDimitry Andric     LLDB_LOGF(log,
31079dba64beSDimitry Andric               "ProcessGDBRemote::DisableBreakpointSite (site_id = %" PRIu64
31080b57cec5SDimitry Andric               ") addr = 0x%8.8" PRIx64 " -- SUCCESS (already disabled)",
31090b57cec5SDimitry Andric               site_id, (uint64_t)addr);
31100b57cec5SDimitry Andric     return error;
31110b57cec5SDimitry Andric   }
31120b57cec5SDimitry Andric 
31130b57cec5SDimitry Andric   if (error.Success())
31140b57cec5SDimitry Andric     error.SetErrorToGenericError();
31150b57cec5SDimitry Andric   return error;
31160b57cec5SDimitry Andric }
31170b57cec5SDimitry Andric 
31180b57cec5SDimitry Andric // Pre-requisite: wp != NULL.
31190b57cec5SDimitry Andric static GDBStoppointType GetGDBStoppointType(Watchpoint *wp) {
31200b57cec5SDimitry Andric   assert(wp);
31210b57cec5SDimitry Andric   bool watch_read = wp->WatchpointRead();
31220b57cec5SDimitry Andric   bool watch_write = wp->WatchpointWrite();
31230b57cec5SDimitry Andric 
31240b57cec5SDimitry Andric   // watch_read and watch_write cannot both be false.
31250b57cec5SDimitry Andric   assert(watch_read || watch_write);
31260b57cec5SDimitry Andric   if (watch_read && watch_write)
31270b57cec5SDimitry Andric     return eWatchpointReadWrite;
31280b57cec5SDimitry Andric   else if (watch_read)
31290b57cec5SDimitry Andric     return eWatchpointRead;
31300b57cec5SDimitry Andric   else // Must be watch_write, then.
31310b57cec5SDimitry Andric     return eWatchpointWrite;
31320b57cec5SDimitry Andric }
31330b57cec5SDimitry Andric 
31340b57cec5SDimitry Andric Status ProcessGDBRemote::EnableWatchpoint(Watchpoint *wp, bool notify) {
31350b57cec5SDimitry Andric   Status error;
31360b57cec5SDimitry Andric   if (wp) {
31370b57cec5SDimitry Andric     user_id_t watchID = wp->GetID();
31380b57cec5SDimitry Andric     addr_t addr = wp->GetLoadAddress();
31391fd87a68SDimitry Andric     Log *log(GetLog(GDBRLog::Watchpoints));
31409dba64beSDimitry Andric     LLDB_LOGF(log, "ProcessGDBRemote::EnableWatchpoint(watchID = %" PRIu64 ")",
31410b57cec5SDimitry Andric               watchID);
31420b57cec5SDimitry Andric     if (wp->IsEnabled()) {
31439dba64beSDimitry Andric       LLDB_LOGF(log,
31449dba64beSDimitry Andric                 "ProcessGDBRemote::EnableWatchpoint(watchID = %" PRIu64
31450b57cec5SDimitry Andric                 ") addr = 0x%8.8" PRIx64 ": watchpoint already enabled.",
31460b57cec5SDimitry Andric                 watchID, (uint64_t)addr);
31470b57cec5SDimitry Andric       return error;
31480b57cec5SDimitry Andric     }
31490b57cec5SDimitry Andric 
31500b57cec5SDimitry Andric     GDBStoppointType type = GetGDBStoppointType(wp);
31510b57cec5SDimitry Andric     // Pass down an appropriate z/Z packet...
31520b57cec5SDimitry Andric     if (m_gdb_comm.SupportsGDBStoppointPacket(type)) {
31530b57cec5SDimitry Andric       if (m_gdb_comm.SendGDBStoppointTypePacket(type, true, addr,
3154fe6060f1SDimitry Andric                                                 wp->GetByteSize(),
3155fe6060f1SDimitry Andric                                                 GetInterruptTimeout()) == 0) {
31560b57cec5SDimitry Andric         wp->SetEnabled(true, notify);
31570b57cec5SDimitry Andric         return error;
31580b57cec5SDimitry Andric       } else
31590b57cec5SDimitry Andric         error.SetErrorString("sending gdb watchpoint packet failed");
31600b57cec5SDimitry Andric     } else
31610b57cec5SDimitry Andric       error.SetErrorString("watchpoints not supported");
31620b57cec5SDimitry Andric   } else {
31630b57cec5SDimitry Andric     error.SetErrorString("Watchpoint argument was NULL.");
31640b57cec5SDimitry Andric   }
31650b57cec5SDimitry Andric   if (error.Success())
31660b57cec5SDimitry Andric     error.SetErrorToGenericError();
31670b57cec5SDimitry Andric   return error;
31680b57cec5SDimitry Andric }
31690b57cec5SDimitry Andric 
31700b57cec5SDimitry Andric Status ProcessGDBRemote::DisableWatchpoint(Watchpoint *wp, bool notify) {
31710b57cec5SDimitry Andric   Status error;
31720b57cec5SDimitry Andric   if (wp) {
31730b57cec5SDimitry Andric     user_id_t watchID = wp->GetID();
31740b57cec5SDimitry Andric 
31751fd87a68SDimitry Andric     Log *log(GetLog(GDBRLog::Watchpoints));
31760b57cec5SDimitry Andric 
31770b57cec5SDimitry Andric     addr_t addr = wp->GetLoadAddress();
31780b57cec5SDimitry Andric 
31799dba64beSDimitry Andric     LLDB_LOGF(log,
31809dba64beSDimitry Andric               "ProcessGDBRemote::DisableWatchpoint (watchID = %" PRIu64
31810b57cec5SDimitry Andric               ") addr = 0x%8.8" PRIx64,
31820b57cec5SDimitry Andric               watchID, (uint64_t)addr);
31830b57cec5SDimitry Andric 
31840b57cec5SDimitry Andric     if (!wp->IsEnabled()) {
31859dba64beSDimitry Andric       LLDB_LOGF(log,
31869dba64beSDimitry Andric                 "ProcessGDBRemote::DisableWatchpoint (watchID = %" PRIu64
31870b57cec5SDimitry Andric                 ") addr = 0x%8.8" PRIx64 " -- SUCCESS (already disabled)",
31880b57cec5SDimitry Andric                 watchID, (uint64_t)addr);
31890b57cec5SDimitry Andric       // See also 'class WatchpointSentry' within StopInfo.cpp. This disabling
31900b57cec5SDimitry Andric       // attempt might come from the user-supplied actions, we'll route it in
31910b57cec5SDimitry Andric       // order for the watchpoint object to intelligently process this action.
31920b57cec5SDimitry Andric       wp->SetEnabled(false, notify);
31930b57cec5SDimitry Andric       return error;
31940b57cec5SDimitry Andric     }
31950b57cec5SDimitry Andric 
31960b57cec5SDimitry Andric     if (wp->IsHardware()) {
31970b57cec5SDimitry Andric       GDBStoppointType type = GetGDBStoppointType(wp);
31980b57cec5SDimitry Andric       // Pass down an appropriate z/Z packet...
31990b57cec5SDimitry Andric       if (m_gdb_comm.SendGDBStoppointTypePacket(type, false, addr,
3200fe6060f1SDimitry Andric                                                 wp->GetByteSize(),
3201fe6060f1SDimitry Andric                                                 GetInterruptTimeout()) == 0) {
32020b57cec5SDimitry Andric         wp->SetEnabled(false, notify);
32030b57cec5SDimitry Andric         return error;
32040b57cec5SDimitry Andric       } else
32050b57cec5SDimitry Andric         error.SetErrorString("sending gdb watchpoint packet failed");
32060b57cec5SDimitry Andric     }
32070b57cec5SDimitry Andric     // TODO: clear software watchpoints if we implement them
32080b57cec5SDimitry Andric   } else {
32090b57cec5SDimitry Andric     error.SetErrorString("Watchpoint argument was NULL.");
32100b57cec5SDimitry Andric   }
32110b57cec5SDimitry Andric   if (error.Success())
32120b57cec5SDimitry Andric     error.SetErrorToGenericError();
32130b57cec5SDimitry Andric   return error;
32140b57cec5SDimitry Andric }
32150b57cec5SDimitry Andric 
32160b57cec5SDimitry Andric void ProcessGDBRemote::Clear() {
32170b57cec5SDimitry Andric   m_thread_list_real.Clear();
32180b57cec5SDimitry Andric   m_thread_list.Clear();
32190b57cec5SDimitry Andric }
32200b57cec5SDimitry Andric 
32210b57cec5SDimitry Andric Status ProcessGDBRemote::DoSignal(int signo) {
32220b57cec5SDimitry Andric   Status error;
32231fd87a68SDimitry Andric   Log *log = GetLog(GDBRLog::Process);
32249dba64beSDimitry Andric   LLDB_LOGF(log, "ProcessGDBRemote::DoSignal (signal = %d)", signo);
32250b57cec5SDimitry Andric 
3226fe6060f1SDimitry Andric   if (!m_gdb_comm.SendAsyncSignal(signo, GetInterruptTimeout()))
32270b57cec5SDimitry Andric     error.SetErrorStringWithFormat("failed to send signal %i", signo);
32280b57cec5SDimitry Andric   return error;
32290b57cec5SDimitry Andric }
32300b57cec5SDimitry Andric 
32310b57cec5SDimitry Andric Status
32320b57cec5SDimitry Andric ProcessGDBRemote::EstablishConnectionIfNeeded(const ProcessInfo &process_info) {
32330b57cec5SDimitry Andric   // Make sure we aren't already connected?
32340b57cec5SDimitry Andric   if (m_gdb_comm.IsConnected())
32350b57cec5SDimitry Andric     return Status();
32360b57cec5SDimitry Andric 
32370b57cec5SDimitry Andric   PlatformSP platform_sp(GetTarget().GetPlatform());
32380b57cec5SDimitry Andric   if (platform_sp && !platform_sp->IsHost())
32390b57cec5SDimitry Andric     return Status("Lost debug server connection");
32400b57cec5SDimitry Andric 
32410b57cec5SDimitry Andric   auto error = LaunchAndConnectToDebugserver(process_info);
32420b57cec5SDimitry Andric   if (error.Fail()) {
32430b57cec5SDimitry Andric     const char *error_string = error.AsCString();
32440b57cec5SDimitry Andric     if (error_string == nullptr)
32450b57cec5SDimitry Andric       error_string = "unable to launch " DEBUGSERVER_BASENAME;
32460b57cec5SDimitry Andric   }
32470b57cec5SDimitry Andric   return error;
32480b57cec5SDimitry Andric }
32490b57cec5SDimitry Andric #if !defined(_WIN32)
32500b57cec5SDimitry Andric #define USE_SOCKETPAIR_FOR_LOCAL_CONNECTION 1
32510b57cec5SDimitry Andric #endif
32520b57cec5SDimitry Andric 
32530b57cec5SDimitry Andric #ifdef USE_SOCKETPAIR_FOR_LOCAL_CONNECTION
32540b57cec5SDimitry Andric static bool SetCloexecFlag(int fd) {
32550b57cec5SDimitry Andric #if defined(FD_CLOEXEC)
32560b57cec5SDimitry Andric   int flags = ::fcntl(fd, F_GETFD);
32570b57cec5SDimitry Andric   if (flags == -1)
32580b57cec5SDimitry Andric     return false;
32590b57cec5SDimitry Andric   return (::fcntl(fd, F_SETFD, flags | FD_CLOEXEC) == 0);
32600b57cec5SDimitry Andric #else
32610b57cec5SDimitry Andric   return false;
32620b57cec5SDimitry Andric #endif
32630b57cec5SDimitry Andric }
32640b57cec5SDimitry Andric #endif
32650b57cec5SDimitry Andric 
32660b57cec5SDimitry Andric Status ProcessGDBRemote::LaunchAndConnectToDebugserver(
32670b57cec5SDimitry Andric     const ProcessInfo &process_info) {
32680b57cec5SDimitry Andric   using namespace std::placeholders; // For _1, _2, etc.
32690b57cec5SDimitry Andric 
32700b57cec5SDimitry Andric   Status error;
32710b57cec5SDimitry Andric   if (m_debugserver_pid == LLDB_INVALID_PROCESS_ID) {
32720b57cec5SDimitry Andric     // If we locate debugserver, keep that located version around
32730b57cec5SDimitry Andric     static FileSpec g_debugserver_file_spec;
32740b57cec5SDimitry Andric 
32750b57cec5SDimitry Andric     ProcessLaunchInfo debugserver_launch_info;
32760b57cec5SDimitry Andric     // Make debugserver run in its own session so signals generated by special
32770b57cec5SDimitry Andric     // terminal key sequences (^C) don't affect debugserver.
32780b57cec5SDimitry Andric     debugserver_launch_info.SetLaunchInSeparateProcessGroup(true);
32790b57cec5SDimitry Andric 
32800b57cec5SDimitry Andric     const std::weak_ptr<ProcessGDBRemote> this_wp =
32810b57cec5SDimitry Andric         std::static_pointer_cast<ProcessGDBRemote>(shared_from_this());
32820b57cec5SDimitry Andric     debugserver_launch_info.SetMonitorProcessCallback(
3283*81ad6265SDimitry Andric         std::bind(MonitorDebugserverProcess, this_wp, _1, _2, _3));
32840b57cec5SDimitry Andric     debugserver_launch_info.SetUserID(process_info.GetUserID());
32850b57cec5SDimitry Andric 
32865ffd83dbSDimitry Andric #if defined(__APPLE__)
32875ffd83dbSDimitry Andric     // On macOS 11, we need to support x86_64 applications translated to
32885ffd83dbSDimitry Andric     // arm64. We check whether a binary is translated and spawn the correct
32895ffd83dbSDimitry Andric     // debugserver accordingly.
32905ffd83dbSDimitry Andric     int mib[] = { CTL_KERN, KERN_PROC, KERN_PROC_PID,
32915ffd83dbSDimitry Andric                   static_cast<int>(process_info.GetProcessID()) };
32925ffd83dbSDimitry Andric     struct kinfo_proc processInfo;
32935ffd83dbSDimitry Andric     size_t bufsize = sizeof(processInfo);
32945ffd83dbSDimitry Andric     if (sysctl(mib, (unsigned)(sizeof(mib)/sizeof(int)), &processInfo,
32955ffd83dbSDimitry Andric                &bufsize, NULL, 0) == 0 && bufsize > 0) {
32965ffd83dbSDimitry Andric       if (processInfo.kp_proc.p_flag & P_TRANSLATED) {
32975ffd83dbSDimitry Andric         FileSpec rosetta_debugserver("/Library/Apple/usr/libexec/oah/debugserver");
32985ffd83dbSDimitry Andric         debugserver_launch_info.SetExecutableFile(rosetta_debugserver, false);
32995ffd83dbSDimitry Andric       }
33005ffd83dbSDimitry Andric     }
33015ffd83dbSDimitry Andric #endif
33025ffd83dbSDimitry Andric 
33030b57cec5SDimitry Andric     int communication_fd = -1;
33040b57cec5SDimitry Andric #ifdef USE_SOCKETPAIR_FOR_LOCAL_CONNECTION
33050b57cec5SDimitry Andric     // Use a socketpair on non-Windows systems for security and performance
33060b57cec5SDimitry Andric     // reasons.
33070b57cec5SDimitry Andric     int sockets[2]; /* the pair of socket descriptors */
33080b57cec5SDimitry Andric     if (socketpair(AF_UNIX, SOCK_STREAM, 0, sockets) == -1) {
33090b57cec5SDimitry Andric       error.SetErrorToErrno();
33100b57cec5SDimitry Andric       return error;
33110b57cec5SDimitry Andric     }
33120b57cec5SDimitry Andric 
33130b57cec5SDimitry Andric     int our_socket = sockets[0];
33140b57cec5SDimitry Andric     int gdb_socket = sockets[1];
33159dba64beSDimitry Andric     auto cleanup_our = llvm::make_scope_exit([&]() { close(our_socket); });
33169dba64beSDimitry Andric     auto cleanup_gdb = llvm::make_scope_exit([&]() { close(gdb_socket); });
33170b57cec5SDimitry Andric 
33180b57cec5SDimitry Andric     // Don't let any child processes inherit our communication socket
33190b57cec5SDimitry Andric     SetCloexecFlag(our_socket);
33200b57cec5SDimitry Andric     communication_fd = gdb_socket;
33210b57cec5SDimitry Andric #endif
33220b57cec5SDimitry Andric 
33230b57cec5SDimitry Andric     error = m_gdb_comm.StartDebugserverProcess(
33240b57cec5SDimitry Andric         nullptr, GetTarget().GetPlatform().get(), debugserver_launch_info,
33250b57cec5SDimitry Andric         nullptr, nullptr, communication_fd);
33260b57cec5SDimitry Andric 
33270b57cec5SDimitry Andric     if (error.Success())
33280b57cec5SDimitry Andric       m_debugserver_pid = debugserver_launch_info.GetProcessID();
33290b57cec5SDimitry Andric     else
33300b57cec5SDimitry Andric       m_debugserver_pid = LLDB_INVALID_PROCESS_ID;
33310b57cec5SDimitry Andric 
33320b57cec5SDimitry Andric     if (m_debugserver_pid != LLDB_INVALID_PROCESS_ID) {
33330b57cec5SDimitry Andric #ifdef USE_SOCKETPAIR_FOR_LOCAL_CONNECTION
33340b57cec5SDimitry Andric       // Our process spawned correctly, we can now set our connection to use
33350b57cec5SDimitry Andric       // our end of the socket pair
33369dba64beSDimitry Andric       cleanup_our.release();
33375ffd83dbSDimitry Andric       m_gdb_comm.SetConnection(
33385ffd83dbSDimitry Andric           std::make_unique<ConnectionFileDescriptor>(our_socket, true));
33390b57cec5SDimitry Andric #endif
33400b57cec5SDimitry Andric       StartAsyncThread();
33410b57cec5SDimitry Andric     }
33420b57cec5SDimitry Andric 
33430b57cec5SDimitry Andric     if (error.Fail()) {
33441fd87a68SDimitry Andric       Log *log = GetLog(GDBRLog::Process);
33450b57cec5SDimitry Andric 
33469dba64beSDimitry Andric       LLDB_LOGF(log, "failed to start debugserver process: %s",
33470b57cec5SDimitry Andric                 error.AsCString());
33480b57cec5SDimitry Andric       return error;
33490b57cec5SDimitry Andric     }
33500b57cec5SDimitry Andric 
33510b57cec5SDimitry Andric     if (m_gdb_comm.IsConnected()) {
33520b57cec5SDimitry Andric       // Finish the connection process by doing the handshake without
33530b57cec5SDimitry Andric       // connecting (send NULL URL)
33540b57cec5SDimitry Andric       error = ConnectToDebugserver("");
33550b57cec5SDimitry Andric     } else {
33560b57cec5SDimitry Andric       error.SetErrorString("connection failed");
33570b57cec5SDimitry Andric     }
33580b57cec5SDimitry Andric   }
33590b57cec5SDimitry Andric   return error;
33600b57cec5SDimitry Andric }
33610b57cec5SDimitry Andric 
3362*81ad6265SDimitry Andric void ProcessGDBRemote::MonitorDebugserverProcess(
33630b57cec5SDimitry Andric     std::weak_ptr<ProcessGDBRemote> process_wp, lldb::pid_t debugserver_pid,
33640b57cec5SDimitry Andric     int signo,      // Zero for no signal
33650b57cec5SDimitry Andric     int exit_status // Exit value of process if signal is zero
33660b57cec5SDimitry Andric ) {
33670b57cec5SDimitry Andric   // "debugserver_pid" argument passed in is the process ID for debugserver
33680b57cec5SDimitry Andric   // that we are tracking...
33691fd87a68SDimitry Andric   Log *log = GetLog(GDBRLog::Process);
33700b57cec5SDimitry Andric 
33719dba64beSDimitry Andric   LLDB_LOGF(log,
33729dba64beSDimitry Andric             "ProcessGDBRemote::%s(process_wp, pid=%" PRIu64
33730b57cec5SDimitry Andric             ", signo=%i (0x%x), exit_status=%i)",
33740b57cec5SDimitry Andric             __FUNCTION__, debugserver_pid, signo, signo, exit_status);
33750b57cec5SDimitry Andric 
33760b57cec5SDimitry Andric   std::shared_ptr<ProcessGDBRemote> process_sp = process_wp.lock();
33779dba64beSDimitry Andric   LLDB_LOGF(log, "ProcessGDBRemote::%s(process = %p)", __FUNCTION__,
33780b57cec5SDimitry Andric             static_cast<void *>(process_sp.get()));
33790b57cec5SDimitry Andric   if (!process_sp || process_sp->m_debugserver_pid != debugserver_pid)
3380*81ad6265SDimitry Andric     return;
33810b57cec5SDimitry Andric 
33820b57cec5SDimitry Andric   // Sleep for a half a second to make sure our inferior process has time to
33830b57cec5SDimitry Andric   // set its exit status before we set it incorrectly when both the debugserver
33840b57cec5SDimitry Andric   // and the inferior process shut down.
33859dba64beSDimitry Andric   std::this_thread::sleep_for(std::chrono::milliseconds(500));
33869dba64beSDimitry Andric 
33870b57cec5SDimitry Andric   // If our process hasn't yet exited, debugserver might have died. If the
33880b57cec5SDimitry Andric   // process did exit, then we are reaping it.
33890b57cec5SDimitry Andric   const StateType state = process_sp->GetState();
33900b57cec5SDimitry Andric 
33910b57cec5SDimitry Andric   if (state != eStateInvalid && state != eStateUnloaded &&
33920b57cec5SDimitry Andric       state != eStateExited && state != eStateDetached) {
33930b57cec5SDimitry Andric     char error_str[1024];
33940b57cec5SDimitry Andric     if (signo) {
33950b57cec5SDimitry Andric       const char *signal_cstr =
33960b57cec5SDimitry Andric           process_sp->GetUnixSignals()->GetSignalAsCString(signo);
33970b57cec5SDimitry Andric       if (signal_cstr)
33980b57cec5SDimitry Andric         ::snprintf(error_str, sizeof(error_str),
33990b57cec5SDimitry Andric                    DEBUGSERVER_BASENAME " died with signal %s", signal_cstr);
34000b57cec5SDimitry Andric       else
34010b57cec5SDimitry Andric         ::snprintf(error_str, sizeof(error_str),
34020b57cec5SDimitry Andric                    DEBUGSERVER_BASENAME " died with signal %i", signo);
34030b57cec5SDimitry Andric     } else {
34040b57cec5SDimitry Andric       ::snprintf(error_str, sizeof(error_str),
34050b57cec5SDimitry Andric                  DEBUGSERVER_BASENAME " died with an exit status of 0x%8.8x",
34060b57cec5SDimitry Andric                  exit_status);
34070b57cec5SDimitry Andric     }
34080b57cec5SDimitry Andric 
34090b57cec5SDimitry Andric     process_sp->SetExitStatus(-1, error_str);
34100b57cec5SDimitry Andric   }
34110b57cec5SDimitry Andric   // Debugserver has exited we need to let our ProcessGDBRemote know that it no
34120b57cec5SDimitry Andric   // longer has a debugserver instance
34130b57cec5SDimitry Andric   process_sp->m_debugserver_pid = LLDB_INVALID_PROCESS_ID;
34140b57cec5SDimitry Andric }
34150b57cec5SDimitry Andric 
34160b57cec5SDimitry Andric void ProcessGDBRemote::KillDebugserverProcess() {
34170b57cec5SDimitry Andric   m_gdb_comm.Disconnect();
34180b57cec5SDimitry Andric   if (m_debugserver_pid != LLDB_INVALID_PROCESS_ID) {
34190b57cec5SDimitry Andric     Host::Kill(m_debugserver_pid, SIGINT);
34200b57cec5SDimitry Andric     m_debugserver_pid = LLDB_INVALID_PROCESS_ID;
34210b57cec5SDimitry Andric   }
34220b57cec5SDimitry Andric }
34230b57cec5SDimitry Andric 
34240b57cec5SDimitry Andric void ProcessGDBRemote::Initialize() {
34250b57cec5SDimitry Andric   static llvm::once_flag g_once_flag;
34260b57cec5SDimitry Andric 
34270b57cec5SDimitry Andric   llvm::call_once(g_once_flag, []() {
34280b57cec5SDimitry Andric     PluginManager::RegisterPlugin(GetPluginNameStatic(),
34290b57cec5SDimitry Andric                                   GetPluginDescriptionStatic(), CreateInstance,
34300b57cec5SDimitry Andric                                   DebuggerInitialize);
34310b57cec5SDimitry Andric   });
34320b57cec5SDimitry Andric }
34330b57cec5SDimitry Andric 
34340b57cec5SDimitry Andric void ProcessGDBRemote::DebuggerInitialize(Debugger &debugger) {
34350b57cec5SDimitry Andric   if (!PluginManager::GetSettingForProcessPlugin(
34360b57cec5SDimitry Andric           debugger, PluginProperties::GetSettingName())) {
34370b57cec5SDimitry Andric     const bool is_global_setting = true;
34380b57cec5SDimitry Andric     PluginManager::CreateSettingForProcessPlugin(
3439349cc55cSDimitry Andric         debugger, GetGlobalPluginProperties().GetValueProperties(),
34400b57cec5SDimitry Andric         ConstString("Properties for the gdb-remote process plug-in."),
34410b57cec5SDimitry Andric         is_global_setting);
34420b57cec5SDimitry Andric   }
34430b57cec5SDimitry Andric }
34440b57cec5SDimitry Andric 
34450b57cec5SDimitry Andric bool ProcessGDBRemote::StartAsyncThread() {
34461fd87a68SDimitry Andric   Log *log = GetLog(GDBRLog::Process);
34470b57cec5SDimitry Andric 
34489dba64beSDimitry Andric   LLDB_LOGF(log, "ProcessGDBRemote::%s ()", __FUNCTION__);
34490b57cec5SDimitry Andric 
34500b57cec5SDimitry Andric   std::lock_guard<std::recursive_mutex> guard(m_async_thread_state_mutex);
34510b57cec5SDimitry Andric   if (!m_async_thread.IsJoinable()) {
34520b57cec5SDimitry Andric     // Create a thread that watches our internal state and controls which
34530b57cec5SDimitry Andric     // events make it to clients (into the DCProcess event queue).
34540b57cec5SDimitry Andric 
3455*81ad6265SDimitry Andric     llvm::Expected<HostThread> async_thread =
3456*81ad6265SDimitry Andric         ThreadLauncher::LaunchThread("<lldb.process.gdb-remote.async>", [this] {
3457*81ad6265SDimitry Andric           return ProcessGDBRemote::AsyncThread();
3458*81ad6265SDimitry Andric         });
34590b57cec5SDimitry Andric     if (!async_thread) {
3460*81ad6265SDimitry Andric       LLDB_LOG_ERROR(GetLog(LLDBLog::Host), async_thread.takeError(),
3461480093f4SDimitry Andric                      "failed to launch host thread: {}");
34620b57cec5SDimitry Andric       return false;
34630b57cec5SDimitry Andric     }
34640b57cec5SDimitry Andric     m_async_thread = *async_thread;
34659dba64beSDimitry Andric   } else
34669dba64beSDimitry Andric     LLDB_LOGF(log,
34679dba64beSDimitry Andric               "ProcessGDBRemote::%s () - Called when Async thread was "
34680b57cec5SDimitry Andric               "already running.",
34690b57cec5SDimitry Andric               __FUNCTION__);
34700b57cec5SDimitry Andric 
34710b57cec5SDimitry Andric   return m_async_thread.IsJoinable();
34720b57cec5SDimitry Andric }
34730b57cec5SDimitry Andric 
34740b57cec5SDimitry Andric void ProcessGDBRemote::StopAsyncThread() {
34751fd87a68SDimitry Andric   Log *log = GetLog(GDBRLog::Process);
34760b57cec5SDimitry Andric 
34779dba64beSDimitry Andric   LLDB_LOGF(log, "ProcessGDBRemote::%s ()", __FUNCTION__);
34780b57cec5SDimitry Andric 
34790b57cec5SDimitry Andric   std::lock_guard<std::recursive_mutex> guard(m_async_thread_state_mutex);
34800b57cec5SDimitry Andric   if (m_async_thread.IsJoinable()) {
34810b57cec5SDimitry Andric     m_async_broadcaster.BroadcastEvent(eBroadcastBitAsyncThreadShouldExit);
34820b57cec5SDimitry Andric 
34830b57cec5SDimitry Andric     //  This will shut down the async thread.
34840b57cec5SDimitry Andric     m_gdb_comm.Disconnect(); // Disconnect from the debug server.
34850b57cec5SDimitry Andric 
34860b57cec5SDimitry Andric     // Stop the stdio thread
34870b57cec5SDimitry Andric     m_async_thread.Join(nullptr);
34880b57cec5SDimitry Andric     m_async_thread.Reset();
34899dba64beSDimitry Andric   } else
34909dba64beSDimitry Andric     LLDB_LOGF(
34919dba64beSDimitry Andric         log,
34920b57cec5SDimitry Andric         "ProcessGDBRemote::%s () - Called when Async thread was not running.",
34930b57cec5SDimitry Andric         __FUNCTION__);
34940b57cec5SDimitry Andric }
34950b57cec5SDimitry Andric 
3496*81ad6265SDimitry Andric thread_result_t ProcessGDBRemote::AsyncThread() {
34971fd87a68SDimitry Andric   Log *log = GetLog(GDBRLog::Process);
3498*81ad6265SDimitry Andric   LLDB_LOGF(log, "ProcessGDBRemote::%s(pid = %" PRIu64 ") thread starting...",
3499*81ad6265SDimitry Andric             __FUNCTION__, GetID());
35000b57cec5SDimitry Andric 
35010b57cec5SDimitry Andric   EventSP event_sp;
3502fe6060f1SDimitry Andric 
3503fe6060f1SDimitry Andric   // We need to ignore any packets that come in after we have
3504fe6060f1SDimitry Andric   // have decided the process has exited.  There are some
3505fe6060f1SDimitry Andric   // situations, for instance when we try to interrupt a running
3506fe6060f1SDimitry Andric   // process and the interrupt fails, where another packet might
3507fe6060f1SDimitry Andric   // get delivered after we've decided to give up on the process.
3508fe6060f1SDimitry Andric   // But once we've decided we are done with the process we will
3509fe6060f1SDimitry Andric   // not be in a state to do anything useful with new packets.
3510fe6060f1SDimitry Andric   // So it is safer to simply ignore any remaining packets by
3511fe6060f1SDimitry Andric   // explicitly checking for eStateExited before reentering the
3512fe6060f1SDimitry Andric   // fetch loop.
3513fe6060f1SDimitry Andric 
35140b57cec5SDimitry Andric   bool done = false;
3515*81ad6265SDimitry Andric   while (!done && GetPrivateState() != eStateExited) {
35169dba64beSDimitry Andric     LLDB_LOGF(log,
3517*81ad6265SDimitry Andric               "ProcessGDBRemote::%s(pid = %" PRIu64
35180b57cec5SDimitry Andric               ") listener.WaitForEvent (NULL, event_sp)...",
3519*81ad6265SDimitry Andric               __FUNCTION__, GetID());
3520fe6060f1SDimitry Andric 
3521*81ad6265SDimitry Andric     if (m_async_listener_sp->GetEvent(event_sp, llvm::None)) {
35220b57cec5SDimitry Andric       const uint32_t event_type = event_sp->GetType();
3523*81ad6265SDimitry Andric       if (event_sp->BroadcasterIs(&m_async_broadcaster)) {
35249dba64beSDimitry Andric         LLDB_LOGF(log,
3525*81ad6265SDimitry Andric                   "ProcessGDBRemote::%s(pid = %" PRIu64
35260b57cec5SDimitry Andric                   ") Got an event of type: %d...",
3527*81ad6265SDimitry Andric                   __FUNCTION__, GetID(), event_type);
35280b57cec5SDimitry Andric 
35290b57cec5SDimitry Andric         switch (event_type) {
35300b57cec5SDimitry Andric         case eBroadcastBitAsyncContinue: {
35310b57cec5SDimitry Andric           const EventDataBytes *continue_packet =
35320b57cec5SDimitry Andric               EventDataBytes::GetEventDataFromEvent(event_sp.get());
35330b57cec5SDimitry Andric 
35340b57cec5SDimitry Andric           if (continue_packet) {
35350b57cec5SDimitry Andric             const char *continue_cstr =
35360b57cec5SDimitry Andric                 (const char *)continue_packet->GetBytes();
35370b57cec5SDimitry Andric             const size_t continue_cstr_len = continue_packet->GetByteSize();
35389dba64beSDimitry Andric             LLDB_LOGF(log,
3539*81ad6265SDimitry Andric                       "ProcessGDBRemote::%s(pid = %" PRIu64
35400b57cec5SDimitry Andric                       ") got eBroadcastBitAsyncContinue: %s",
3541*81ad6265SDimitry Andric                       __FUNCTION__, GetID(), continue_cstr);
35420b57cec5SDimitry Andric 
35430b57cec5SDimitry Andric             if (::strstr(continue_cstr, "vAttach") == nullptr)
3544*81ad6265SDimitry Andric               SetPrivateState(eStateRunning);
35450b57cec5SDimitry Andric             StringExtractorGDBRemote response;
35460b57cec5SDimitry Andric 
35470b57cec5SDimitry Andric             StateType stop_state =
3548*81ad6265SDimitry Andric                 GetGDBRemote().SendContinuePacketAndWaitForResponse(
3549*81ad6265SDimitry Andric                     *this, *GetUnixSignals(),
35500b57cec5SDimitry Andric                     llvm::StringRef(continue_cstr, continue_cstr_len),
3551*81ad6265SDimitry Andric                     GetInterruptTimeout(), response);
35520b57cec5SDimitry Andric 
35530b57cec5SDimitry Andric             // We need to immediately clear the thread ID list so we are sure
35540b57cec5SDimitry Andric             // to get a valid list of threads. The thread ID list might be
35550b57cec5SDimitry Andric             // contained within the "response", or the stop reply packet that
35560b57cec5SDimitry Andric             // caused the stop. So clear it now before we give the stop reply
35570b57cec5SDimitry Andric             // packet to the process using the
3558*81ad6265SDimitry Andric             // SetLastStopPacket()...
3559*81ad6265SDimitry Andric             ClearThreadIDList();
35600b57cec5SDimitry Andric 
35610b57cec5SDimitry Andric             switch (stop_state) {
35620b57cec5SDimitry Andric             case eStateStopped:
35630b57cec5SDimitry Andric             case eStateCrashed:
35640b57cec5SDimitry Andric             case eStateSuspended:
3565*81ad6265SDimitry Andric               SetLastStopPacket(response);
3566*81ad6265SDimitry Andric               SetPrivateState(stop_state);
35670b57cec5SDimitry Andric               break;
35680b57cec5SDimitry Andric 
35690b57cec5SDimitry Andric             case eStateExited: {
3570*81ad6265SDimitry Andric               SetLastStopPacket(response);
3571*81ad6265SDimitry Andric               ClearThreadIDList();
35720b57cec5SDimitry Andric               response.SetFilePos(1);
35730b57cec5SDimitry Andric 
35740b57cec5SDimitry Andric               int exit_status = response.GetHexU8();
35750b57cec5SDimitry Andric               std::string desc_string;
3576349cc55cSDimitry Andric               if (response.GetBytesLeft() > 0 && response.GetChar('-') == ';') {
35770b57cec5SDimitry Andric                 llvm::StringRef desc_str;
35780b57cec5SDimitry Andric                 llvm::StringRef desc_token;
35790b57cec5SDimitry Andric                 while (response.GetNameColonValue(desc_token, desc_str)) {
35800b57cec5SDimitry Andric                   if (desc_token != "description")
35810b57cec5SDimitry Andric                     continue;
35820b57cec5SDimitry Andric                   StringExtractor extractor(desc_str);
35830b57cec5SDimitry Andric                   extractor.GetHexByteString(desc_string);
35840b57cec5SDimitry Andric                 }
35850b57cec5SDimitry Andric               }
3586*81ad6265SDimitry Andric               SetExitStatus(exit_status, desc_string.c_str());
35870b57cec5SDimitry Andric               done = true;
35880b57cec5SDimitry Andric               break;
35890b57cec5SDimitry Andric             }
35900b57cec5SDimitry Andric             case eStateInvalid: {
35910b57cec5SDimitry Andric               // Check to see if we were trying to attach and if we got back
35920b57cec5SDimitry Andric               // the "E87" error code from debugserver -- this indicates that
35930b57cec5SDimitry Andric               // the process is not debuggable.  Return a slightly more
35940b57cec5SDimitry Andric               // helpful error message about why the attach failed.
35950b57cec5SDimitry Andric               if (::strstr(continue_cstr, "vAttach") != nullptr &&
35960b57cec5SDimitry Andric                   response.GetError() == 0x87) {
3597*81ad6265SDimitry Andric                 SetExitStatus(-1, "cannot attach to process due to "
35980b57cec5SDimitry Andric                                   "System Integrity Protection");
35990b57cec5SDimitry Andric               } else if (::strstr(continue_cstr, "vAttach") != nullptr &&
36000b57cec5SDimitry Andric                          response.GetStatus().Fail()) {
3601*81ad6265SDimitry Andric                 SetExitStatus(-1, response.GetStatus().AsCString());
36020b57cec5SDimitry Andric               } else {
3603*81ad6265SDimitry Andric                 SetExitStatus(-1, "lost connection");
36040b57cec5SDimitry Andric               }
3605fe6060f1SDimitry Andric               done = true;
36060b57cec5SDimitry Andric               break;
36070b57cec5SDimitry Andric             }
36080b57cec5SDimitry Andric 
36090b57cec5SDimitry Andric             default:
3610*81ad6265SDimitry Andric               SetPrivateState(stop_state);
36110b57cec5SDimitry Andric               break;
36120b57cec5SDimitry Andric             }   // switch(stop_state)
36130b57cec5SDimitry Andric           }     // if (continue_packet)
36145ffd83dbSDimitry Andric         }       // case eBroadcastBitAsyncContinue
36150b57cec5SDimitry Andric         break;
36160b57cec5SDimitry Andric 
36170b57cec5SDimitry Andric         case eBroadcastBitAsyncThreadShouldExit:
36189dba64beSDimitry Andric           LLDB_LOGF(log,
3619*81ad6265SDimitry Andric                     "ProcessGDBRemote::%s(pid = %" PRIu64
36200b57cec5SDimitry Andric                     ") got eBroadcastBitAsyncThreadShouldExit...",
3621*81ad6265SDimitry Andric                     __FUNCTION__, GetID());
36220b57cec5SDimitry Andric           done = true;
36230b57cec5SDimitry Andric           break;
36240b57cec5SDimitry Andric 
36250b57cec5SDimitry Andric         default:
36269dba64beSDimitry Andric           LLDB_LOGF(log,
3627*81ad6265SDimitry Andric                     "ProcessGDBRemote::%s(pid = %" PRIu64
36280b57cec5SDimitry Andric                     ") got unknown event 0x%8.8x",
3629*81ad6265SDimitry Andric                     __FUNCTION__, GetID(), event_type);
36300b57cec5SDimitry Andric           done = true;
36310b57cec5SDimitry Andric           break;
36320b57cec5SDimitry Andric         }
3633*81ad6265SDimitry Andric       } else if (event_sp->BroadcasterIs(&m_gdb_comm)) {
36340b57cec5SDimitry Andric         switch (event_type) {
36350b57cec5SDimitry Andric         case Communication::eBroadcastBitReadThreadDidExit:
3636*81ad6265SDimitry Andric           SetExitStatus(-1, "lost connection");
36370b57cec5SDimitry Andric           done = true;
36380b57cec5SDimitry Andric           break;
36390b57cec5SDimitry Andric 
36400b57cec5SDimitry Andric         default:
36419dba64beSDimitry Andric           LLDB_LOGF(log,
3642*81ad6265SDimitry Andric                     "ProcessGDBRemote::%s(pid = %" PRIu64
36430b57cec5SDimitry Andric                     ") got unknown event 0x%8.8x",
3644*81ad6265SDimitry Andric                     __FUNCTION__, GetID(), event_type);
36450b57cec5SDimitry Andric           done = true;
36460b57cec5SDimitry Andric           break;
36470b57cec5SDimitry Andric         }
36480b57cec5SDimitry Andric       }
36490b57cec5SDimitry Andric     } else {
36509dba64beSDimitry Andric       LLDB_LOGF(log,
3651*81ad6265SDimitry Andric                 "ProcessGDBRemote::%s(pid = %" PRIu64
36520b57cec5SDimitry Andric                 ") listener.WaitForEvent (NULL, event_sp) => false",
3653*81ad6265SDimitry Andric                 __FUNCTION__, GetID());
36540b57cec5SDimitry Andric       done = true;
36550b57cec5SDimitry Andric     }
36560b57cec5SDimitry Andric   }
36570b57cec5SDimitry Andric 
3658*81ad6265SDimitry Andric   LLDB_LOGF(log, "ProcessGDBRemote::%s(pid = %" PRIu64 ") thread exiting...",
3659*81ad6265SDimitry Andric             __FUNCTION__, GetID());
36600b57cec5SDimitry Andric 
36610b57cec5SDimitry Andric   return {};
36620b57cec5SDimitry Andric }
36630b57cec5SDimitry Andric 
36640b57cec5SDimitry Andric // uint32_t
36650b57cec5SDimitry Andric // ProcessGDBRemote::ListProcessesMatchingName (const char *name, StringList
36660b57cec5SDimitry Andric // &matches, std::vector<lldb::pid_t> &pids)
36670b57cec5SDimitry Andric //{
36680b57cec5SDimitry Andric //    // If we are planning to launch the debugserver remotely, then we need to
36690b57cec5SDimitry Andric //    fire up a debugserver
36700b57cec5SDimitry Andric //    // process and ask it for the list of processes. But if we are local, we
36710b57cec5SDimitry Andric //    can let the Host do it.
36720b57cec5SDimitry Andric //    if (m_local_debugserver)
36730b57cec5SDimitry Andric //    {
36740b57cec5SDimitry Andric //        return Host::ListProcessesMatchingName (name, matches, pids);
36750b57cec5SDimitry Andric //    }
36760b57cec5SDimitry Andric //    else
36770b57cec5SDimitry Andric //    {
36780b57cec5SDimitry Andric //        // FIXME: Implement talking to the remote debugserver.
36790b57cec5SDimitry Andric //        return 0;
36800b57cec5SDimitry Andric //    }
36810b57cec5SDimitry Andric //
36820b57cec5SDimitry Andric //}
36830b57cec5SDimitry Andric //
36840b57cec5SDimitry Andric bool ProcessGDBRemote::NewThreadNotifyBreakpointHit(
36850b57cec5SDimitry Andric     void *baton, StoppointCallbackContext *context, lldb::user_id_t break_id,
36860b57cec5SDimitry Andric     lldb::user_id_t break_loc_id) {
36870b57cec5SDimitry Andric   // I don't think I have to do anything here, just make sure I notice the new
36880b57cec5SDimitry Andric   // thread when it starts to
36890b57cec5SDimitry Andric   // run so I can stop it if that's what I want to do.
3690*81ad6265SDimitry Andric   Log *log = GetLog(LLDBLog::Step);
36919dba64beSDimitry Andric   LLDB_LOGF(log, "Hit New Thread Notification breakpoint.");
36920b57cec5SDimitry Andric   return false;
36930b57cec5SDimitry Andric }
36940b57cec5SDimitry Andric 
36950b57cec5SDimitry Andric Status ProcessGDBRemote::UpdateAutomaticSignalFiltering() {
36961fd87a68SDimitry Andric   Log *log = GetLog(GDBRLog::Process);
36970b57cec5SDimitry Andric   LLDB_LOG(log, "Check if need to update ignored signals");
36980b57cec5SDimitry Andric 
36990b57cec5SDimitry Andric   // QPassSignals package is not supported by the server, there is no way we
37000b57cec5SDimitry Andric   // can ignore any signals on server side.
37010b57cec5SDimitry Andric   if (!m_gdb_comm.GetQPassSignalsSupported())
37020b57cec5SDimitry Andric     return Status();
37030b57cec5SDimitry Andric 
37040b57cec5SDimitry Andric   // No signals, nothing to send.
37050b57cec5SDimitry Andric   if (m_unix_signals_sp == nullptr)
37060b57cec5SDimitry Andric     return Status();
37070b57cec5SDimitry Andric 
37080b57cec5SDimitry Andric   // Signals' version hasn't changed, no need to send anything.
37090b57cec5SDimitry Andric   uint64_t new_signals_version = m_unix_signals_sp->GetVersion();
37100b57cec5SDimitry Andric   if (new_signals_version == m_last_signals_version) {
37110b57cec5SDimitry Andric     LLDB_LOG(log, "Signals' version hasn't changed. version={0}",
37120b57cec5SDimitry Andric              m_last_signals_version);
37130b57cec5SDimitry Andric     return Status();
37140b57cec5SDimitry Andric   }
37150b57cec5SDimitry Andric 
37160b57cec5SDimitry Andric   auto signals_to_ignore =
37170b57cec5SDimitry Andric       m_unix_signals_sp->GetFilteredSignals(false, false, false);
37180b57cec5SDimitry Andric   Status error = m_gdb_comm.SendSignalsToIgnore(signals_to_ignore);
37190b57cec5SDimitry Andric 
37200b57cec5SDimitry Andric   LLDB_LOG(log,
37210b57cec5SDimitry Andric            "Signals' version changed. old version={0}, new version={1}, "
37220b57cec5SDimitry Andric            "signals ignored={2}, update result={3}",
37230b57cec5SDimitry Andric            m_last_signals_version, new_signals_version,
37240b57cec5SDimitry Andric            signals_to_ignore.size(), error);
37250b57cec5SDimitry Andric 
37260b57cec5SDimitry Andric   if (error.Success())
37270b57cec5SDimitry Andric     m_last_signals_version = new_signals_version;
37280b57cec5SDimitry Andric 
37290b57cec5SDimitry Andric   return error;
37300b57cec5SDimitry Andric }
37310b57cec5SDimitry Andric 
37320b57cec5SDimitry Andric bool ProcessGDBRemote::StartNoticingNewThreads() {
3733*81ad6265SDimitry Andric   Log *log = GetLog(LLDBLog::Step);
37340b57cec5SDimitry Andric   if (m_thread_create_bp_sp) {
37350b57cec5SDimitry Andric     if (log && log->GetVerbose())
37369dba64beSDimitry Andric       LLDB_LOGF(log, "Enabled noticing new thread breakpoint.");
37370b57cec5SDimitry Andric     m_thread_create_bp_sp->SetEnabled(true);
37380b57cec5SDimitry Andric   } else {
37390b57cec5SDimitry Andric     PlatformSP platform_sp(GetTarget().GetPlatform());
37400b57cec5SDimitry Andric     if (platform_sp) {
37410b57cec5SDimitry Andric       m_thread_create_bp_sp =
37420b57cec5SDimitry Andric           platform_sp->SetThreadCreationBreakpoint(GetTarget());
37430b57cec5SDimitry Andric       if (m_thread_create_bp_sp) {
37440b57cec5SDimitry Andric         if (log && log->GetVerbose())
37459dba64beSDimitry Andric           LLDB_LOGF(
37469dba64beSDimitry Andric               log, "Successfully created new thread notification breakpoint %i",
37470b57cec5SDimitry Andric               m_thread_create_bp_sp->GetID());
37480b57cec5SDimitry Andric         m_thread_create_bp_sp->SetCallback(
37490b57cec5SDimitry Andric             ProcessGDBRemote::NewThreadNotifyBreakpointHit, this, true);
37500b57cec5SDimitry Andric       } else {
37519dba64beSDimitry Andric         LLDB_LOGF(log, "Failed to create new thread notification breakpoint.");
37520b57cec5SDimitry Andric       }
37530b57cec5SDimitry Andric     }
37540b57cec5SDimitry Andric   }
37550b57cec5SDimitry Andric   return m_thread_create_bp_sp.get() != nullptr;
37560b57cec5SDimitry Andric }
37570b57cec5SDimitry Andric 
37580b57cec5SDimitry Andric bool ProcessGDBRemote::StopNoticingNewThreads() {
3759*81ad6265SDimitry Andric   Log *log = GetLog(LLDBLog::Step);
37600b57cec5SDimitry Andric   if (log && log->GetVerbose())
37619dba64beSDimitry Andric     LLDB_LOGF(log, "Disabling new thread notification breakpoint.");
37620b57cec5SDimitry Andric 
37630b57cec5SDimitry Andric   if (m_thread_create_bp_sp)
37640b57cec5SDimitry Andric     m_thread_create_bp_sp->SetEnabled(false);
37650b57cec5SDimitry Andric 
37660b57cec5SDimitry Andric   return true;
37670b57cec5SDimitry Andric }
37680b57cec5SDimitry Andric 
37690b57cec5SDimitry Andric DynamicLoader *ProcessGDBRemote::GetDynamicLoader() {
37700b57cec5SDimitry Andric   if (m_dyld_up.get() == nullptr)
3771349cc55cSDimitry Andric     m_dyld_up.reset(DynamicLoader::FindPlugin(this, ""));
37720b57cec5SDimitry Andric   return m_dyld_up.get();
37730b57cec5SDimitry Andric }
37740b57cec5SDimitry Andric 
37750b57cec5SDimitry Andric Status ProcessGDBRemote::SendEventData(const char *data) {
37760b57cec5SDimitry Andric   int return_value;
37770b57cec5SDimitry Andric   bool was_supported;
37780b57cec5SDimitry Andric 
37790b57cec5SDimitry Andric   Status error;
37800b57cec5SDimitry Andric 
37810b57cec5SDimitry Andric   return_value = m_gdb_comm.SendLaunchEventDataPacket(data, &was_supported);
37820b57cec5SDimitry Andric   if (return_value != 0) {
37830b57cec5SDimitry Andric     if (!was_supported)
37840b57cec5SDimitry Andric       error.SetErrorString("Sending events is not supported for this process.");
37850b57cec5SDimitry Andric     else
37860b57cec5SDimitry Andric       error.SetErrorStringWithFormat("Error sending event data: %d.",
37870b57cec5SDimitry Andric                                      return_value);
37880b57cec5SDimitry Andric   }
37890b57cec5SDimitry Andric   return error;
37900b57cec5SDimitry Andric }
37910b57cec5SDimitry Andric 
37920b57cec5SDimitry Andric DataExtractor ProcessGDBRemote::GetAuxvData() {
37930b57cec5SDimitry Andric   DataBufferSP buf;
37940b57cec5SDimitry Andric   if (m_gdb_comm.GetQXferAuxvReadSupported()) {
3795349cc55cSDimitry Andric     llvm::Expected<std::string> response = m_gdb_comm.ReadExtFeature("auxv", "");
3796349cc55cSDimitry Andric     if (response)
3797349cc55cSDimitry Andric       buf = std::make_shared<DataBufferHeap>(response->c_str(),
3798349cc55cSDimitry Andric                                              response->length());
3799349cc55cSDimitry Andric     else
38001fd87a68SDimitry Andric       LLDB_LOG_ERROR(GetLog(GDBRLog::Process), response.takeError(), "{0}");
38010b57cec5SDimitry Andric   }
38020b57cec5SDimitry Andric   return DataExtractor(buf, GetByteOrder(), GetAddressByteSize());
38030b57cec5SDimitry Andric }
38040b57cec5SDimitry Andric 
38050b57cec5SDimitry Andric StructuredData::ObjectSP
38060b57cec5SDimitry Andric ProcessGDBRemote::GetExtendedInfoForThread(lldb::tid_t tid) {
38070b57cec5SDimitry Andric   StructuredData::ObjectSP object_sp;
38080b57cec5SDimitry Andric 
38090b57cec5SDimitry Andric   if (m_gdb_comm.GetThreadExtendedInfoSupported()) {
38100b57cec5SDimitry Andric     StructuredData::ObjectSP args_dict(new StructuredData::Dictionary());
38110b57cec5SDimitry Andric     SystemRuntime *runtime = GetSystemRuntime();
38120b57cec5SDimitry Andric     if (runtime) {
38130b57cec5SDimitry Andric       runtime->AddThreadExtendedInfoPacketHints(args_dict);
38140b57cec5SDimitry Andric     }
38150b57cec5SDimitry Andric     args_dict->GetAsDictionary()->AddIntegerItem("thread", tid);
38160b57cec5SDimitry Andric 
38170b57cec5SDimitry Andric     StreamString packet;
38180b57cec5SDimitry Andric     packet << "jThreadExtendedInfo:";
38190b57cec5SDimitry Andric     args_dict->Dump(packet, false);
38200b57cec5SDimitry Andric 
38210b57cec5SDimitry Andric     // FIXME the final character of a JSON dictionary, '}', is the escape
38220b57cec5SDimitry Andric     // character in gdb-remote binary mode.  lldb currently doesn't escape
38230b57cec5SDimitry Andric     // these characters in its packet output -- so we add the quoted version of
38240b57cec5SDimitry Andric     // the } character here manually in case we talk to a debugserver which un-
38250b57cec5SDimitry Andric     // escapes the characters at packet read time.
38260b57cec5SDimitry Andric     packet << (char)(0x7d ^ 0x20);
38270b57cec5SDimitry Andric 
38280b57cec5SDimitry Andric     StringExtractorGDBRemote response;
38290b57cec5SDimitry Andric     response.SetResponseValidatorToJSON();
3830fe6060f1SDimitry Andric     if (m_gdb_comm.SendPacketAndWaitForResponse(packet.GetString(), response) ==
38310b57cec5SDimitry Andric         GDBRemoteCommunication::PacketResult::Success) {
38320b57cec5SDimitry Andric       StringExtractorGDBRemote::ResponseType response_type =
38330b57cec5SDimitry Andric           response.GetResponseType();
38340b57cec5SDimitry Andric       if (response_type == StringExtractorGDBRemote::eResponse) {
38350b57cec5SDimitry Andric         if (!response.Empty()) {
38365ffd83dbSDimitry Andric           object_sp =
38375ffd83dbSDimitry Andric               StructuredData::ParseJSON(std::string(response.GetStringRef()));
38380b57cec5SDimitry Andric         }
38390b57cec5SDimitry Andric       }
38400b57cec5SDimitry Andric     }
38410b57cec5SDimitry Andric   }
38420b57cec5SDimitry Andric   return object_sp;
38430b57cec5SDimitry Andric }
38440b57cec5SDimitry Andric 
38450b57cec5SDimitry Andric StructuredData::ObjectSP ProcessGDBRemote::GetLoadedDynamicLibrariesInfos(
38460b57cec5SDimitry Andric     lldb::addr_t image_list_address, lldb::addr_t image_count) {
38470b57cec5SDimitry Andric 
38480b57cec5SDimitry Andric   StructuredData::ObjectSP args_dict(new StructuredData::Dictionary());
38490b57cec5SDimitry Andric   args_dict->GetAsDictionary()->AddIntegerItem("image_list_address",
38500b57cec5SDimitry Andric                                                image_list_address);
38510b57cec5SDimitry Andric   args_dict->GetAsDictionary()->AddIntegerItem("image_count", image_count);
38520b57cec5SDimitry Andric 
38530b57cec5SDimitry Andric   return GetLoadedDynamicLibrariesInfos_sender(args_dict);
38540b57cec5SDimitry Andric }
38550b57cec5SDimitry Andric 
38560b57cec5SDimitry Andric StructuredData::ObjectSP ProcessGDBRemote::GetLoadedDynamicLibrariesInfos() {
38570b57cec5SDimitry Andric   StructuredData::ObjectSP args_dict(new StructuredData::Dictionary());
38580b57cec5SDimitry Andric 
38590b57cec5SDimitry Andric   args_dict->GetAsDictionary()->AddBooleanItem("fetch_all_solibs", true);
38600b57cec5SDimitry Andric 
38610b57cec5SDimitry Andric   return GetLoadedDynamicLibrariesInfos_sender(args_dict);
38620b57cec5SDimitry Andric }
38630b57cec5SDimitry Andric 
38640b57cec5SDimitry Andric StructuredData::ObjectSP ProcessGDBRemote::GetLoadedDynamicLibrariesInfos(
38650b57cec5SDimitry Andric     const std::vector<lldb::addr_t> &load_addresses) {
38660b57cec5SDimitry Andric   StructuredData::ObjectSP args_dict(new StructuredData::Dictionary());
38670b57cec5SDimitry Andric   StructuredData::ArraySP addresses(new StructuredData::Array);
38680b57cec5SDimitry Andric 
38690b57cec5SDimitry Andric   for (auto addr : load_addresses) {
38700b57cec5SDimitry Andric     StructuredData::ObjectSP addr_sp(new StructuredData::Integer(addr));
38710b57cec5SDimitry Andric     addresses->AddItem(addr_sp);
38720b57cec5SDimitry Andric   }
38730b57cec5SDimitry Andric 
38740b57cec5SDimitry Andric   args_dict->GetAsDictionary()->AddItem("solib_addresses", addresses);
38750b57cec5SDimitry Andric 
38760b57cec5SDimitry Andric   return GetLoadedDynamicLibrariesInfos_sender(args_dict);
38770b57cec5SDimitry Andric }
38780b57cec5SDimitry Andric 
38790b57cec5SDimitry Andric StructuredData::ObjectSP
38800b57cec5SDimitry Andric ProcessGDBRemote::GetLoadedDynamicLibrariesInfos_sender(
38810b57cec5SDimitry Andric     StructuredData::ObjectSP args_dict) {
38820b57cec5SDimitry Andric   StructuredData::ObjectSP object_sp;
38830b57cec5SDimitry Andric 
38840b57cec5SDimitry Andric   if (m_gdb_comm.GetLoadedDynamicLibrariesInfosSupported()) {
38850b57cec5SDimitry Andric     // Scope for the scoped timeout object
38860b57cec5SDimitry Andric     GDBRemoteCommunication::ScopedTimeout timeout(m_gdb_comm,
38870b57cec5SDimitry Andric                                                   std::chrono::seconds(10));
38880b57cec5SDimitry Andric 
38890b57cec5SDimitry Andric     StreamString packet;
38900b57cec5SDimitry Andric     packet << "jGetLoadedDynamicLibrariesInfos:";
38910b57cec5SDimitry Andric     args_dict->Dump(packet, false);
38920b57cec5SDimitry Andric 
38930b57cec5SDimitry Andric     // FIXME the final character of a JSON dictionary, '}', is the escape
38940b57cec5SDimitry Andric     // character in gdb-remote binary mode.  lldb currently doesn't escape
38950b57cec5SDimitry Andric     // these characters in its packet output -- so we add the quoted version of
38960b57cec5SDimitry Andric     // the } character here manually in case we talk to a debugserver which un-
38970b57cec5SDimitry Andric     // escapes the characters at packet read time.
38980b57cec5SDimitry Andric     packet << (char)(0x7d ^ 0x20);
38990b57cec5SDimitry Andric 
39000b57cec5SDimitry Andric     StringExtractorGDBRemote response;
39010b57cec5SDimitry Andric     response.SetResponseValidatorToJSON();
3902fe6060f1SDimitry Andric     if (m_gdb_comm.SendPacketAndWaitForResponse(packet.GetString(), response) ==
39030b57cec5SDimitry Andric         GDBRemoteCommunication::PacketResult::Success) {
39040b57cec5SDimitry Andric       StringExtractorGDBRemote::ResponseType response_type =
39050b57cec5SDimitry Andric           response.GetResponseType();
39060b57cec5SDimitry Andric       if (response_type == StringExtractorGDBRemote::eResponse) {
39070b57cec5SDimitry Andric         if (!response.Empty()) {
39085ffd83dbSDimitry Andric           object_sp =
39095ffd83dbSDimitry Andric               StructuredData::ParseJSON(std::string(response.GetStringRef()));
39100b57cec5SDimitry Andric         }
39110b57cec5SDimitry Andric       }
39120b57cec5SDimitry Andric     }
39130b57cec5SDimitry Andric   }
39140b57cec5SDimitry Andric   return object_sp;
39150b57cec5SDimitry Andric }
39160b57cec5SDimitry Andric 
39170b57cec5SDimitry Andric StructuredData::ObjectSP ProcessGDBRemote::GetSharedCacheInfo() {
39180b57cec5SDimitry Andric   StructuredData::ObjectSP object_sp;
39190b57cec5SDimitry Andric   StructuredData::ObjectSP args_dict(new StructuredData::Dictionary());
39200b57cec5SDimitry Andric 
39210b57cec5SDimitry Andric   if (m_gdb_comm.GetSharedCacheInfoSupported()) {
39220b57cec5SDimitry Andric     StreamString packet;
39230b57cec5SDimitry Andric     packet << "jGetSharedCacheInfo:";
39240b57cec5SDimitry Andric     args_dict->Dump(packet, false);
39250b57cec5SDimitry Andric 
39260b57cec5SDimitry Andric     // FIXME the final character of a JSON dictionary, '}', is the escape
39270b57cec5SDimitry Andric     // character in gdb-remote binary mode.  lldb currently doesn't escape
39280b57cec5SDimitry Andric     // these characters in its packet output -- so we add the quoted version of
39290b57cec5SDimitry Andric     // the } character here manually in case we talk to a debugserver which un-
39300b57cec5SDimitry Andric     // escapes the characters at packet read time.
39310b57cec5SDimitry Andric     packet << (char)(0x7d ^ 0x20);
39320b57cec5SDimitry Andric 
39330b57cec5SDimitry Andric     StringExtractorGDBRemote response;
39340b57cec5SDimitry Andric     response.SetResponseValidatorToJSON();
3935fe6060f1SDimitry Andric     if (m_gdb_comm.SendPacketAndWaitForResponse(packet.GetString(), response) ==
39360b57cec5SDimitry Andric         GDBRemoteCommunication::PacketResult::Success) {
39370b57cec5SDimitry Andric       StringExtractorGDBRemote::ResponseType response_type =
39380b57cec5SDimitry Andric           response.GetResponseType();
39390b57cec5SDimitry Andric       if (response_type == StringExtractorGDBRemote::eResponse) {
39400b57cec5SDimitry Andric         if (!response.Empty()) {
39415ffd83dbSDimitry Andric           object_sp =
39425ffd83dbSDimitry Andric               StructuredData::ParseJSON(std::string(response.GetStringRef()));
39430b57cec5SDimitry Andric         }
39440b57cec5SDimitry Andric       }
39450b57cec5SDimitry Andric     }
39460b57cec5SDimitry Andric   }
39470b57cec5SDimitry Andric   return object_sp;
39480b57cec5SDimitry Andric }
39490b57cec5SDimitry Andric 
39500b57cec5SDimitry Andric Status ProcessGDBRemote::ConfigureStructuredData(
39510b57cec5SDimitry Andric     ConstString type_name, const StructuredData::ObjectSP &config_sp) {
39520b57cec5SDimitry Andric   return m_gdb_comm.ConfigureRemoteStructuredData(type_name, config_sp);
39530b57cec5SDimitry Andric }
39540b57cec5SDimitry Andric 
39550b57cec5SDimitry Andric // Establish the largest memory read/write payloads we should use. If the
39560b57cec5SDimitry Andric // remote stub has a max packet size, stay under that size.
39570b57cec5SDimitry Andric //
39580b57cec5SDimitry Andric // If the remote stub's max packet size is crazy large, use a reasonable
39590b57cec5SDimitry Andric // largeish default.
39600b57cec5SDimitry Andric //
39610b57cec5SDimitry Andric // If the remote stub doesn't advertise a max packet size, use a conservative
39620b57cec5SDimitry Andric // default.
39630b57cec5SDimitry Andric 
39640b57cec5SDimitry Andric void ProcessGDBRemote::GetMaxMemorySize() {
39650b57cec5SDimitry Andric   const uint64_t reasonable_largeish_default = 128 * 1024;
39660b57cec5SDimitry Andric   const uint64_t conservative_default = 512;
39670b57cec5SDimitry Andric 
39680b57cec5SDimitry Andric   if (m_max_memory_size == 0) {
39690b57cec5SDimitry Andric     uint64_t stub_max_size = m_gdb_comm.GetRemoteMaxPacketSize();
39700b57cec5SDimitry Andric     if (stub_max_size != UINT64_MAX && stub_max_size != 0) {
39710b57cec5SDimitry Andric       // Save the stub's claimed maximum packet size
39720b57cec5SDimitry Andric       m_remote_stub_max_memory_size = stub_max_size;
39730b57cec5SDimitry Andric 
39740b57cec5SDimitry Andric       // Even if the stub says it can support ginormous packets, don't exceed
39750b57cec5SDimitry Andric       // our reasonable largeish default packet size.
39760b57cec5SDimitry Andric       if (stub_max_size > reasonable_largeish_default) {
39770b57cec5SDimitry Andric         stub_max_size = reasonable_largeish_default;
39780b57cec5SDimitry Andric       }
39790b57cec5SDimitry Andric 
39800b57cec5SDimitry Andric       // Memory packet have other overheads too like Maddr,size:#NN Instead of
39810b57cec5SDimitry Andric       // calculating the bytes taken by size and addr every time, we take a
39820b57cec5SDimitry Andric       // maximum guess here.
39830b57cec5SDimitry Andric       if (stub_max_size > 70)
39840b57cec5SDimitry Andric         stub_max_size -= 32 + 32 + 6;
39850b57cec5SDimitry Andric       else {
39860b57cec5SDimitry Andric         // In unlikely scenario that max packet size is less then 70, we will
39870b57cec5SDimitry Andric         // hope that data being written is small enough to fit.
39881fd87a68SDimitry Andric         Log *log(GetLog(GDBRLog::Comm | GDBRLog::Memory));
39890b57cec5SDimitry Andric         if (log)
39900b57cec5SDimitry Andric           log->Warning("Packet size is too small. "
39910b57cec5SDimitry Andric                        "LLDB may face problems while writing memory");
39920b57cec5SDimitry Andric       }
39930b57cec5SDimitry Andric 
39940b57cec5SDimitry Andric       m_max_memory_size = stub_max_size;
39950b57cec5SDimitry Andric     } else {
39960b57cec5SDimitry Andric       m_max_memory_size = conservative_default;
39970b57cec5SDimitry Andric     }
39980b57cec5SDimitry Andric   }
39990b57cec5SDimitry Andric }
40000b57cec5SDimitry Andric 
40010b57cec5SDimitry Andric void ProcessGDBRemote::SetUserSpecifiedMaxMemoryTransferSize(
40020b57cec5SDimitry Andric     uint64_t user_specified_max) {
40030b57cec5SDimitry Andric   if (user_specified_max != 0) {
40040b57cec5SDimitry Andric     GetMaxMemorySize();
40050b57cec5SDimitry Andric 
40060b57cec5SDimitry Andric     if (m_remote_stub_max_memory_size != 0) {
40070b57cec5SDimitry Andric       if (m_remote_stub_max_memory_size < user_specified_max) {
40080b57cec5SDimitry Andric         m_max_memory_size = m_remote_stub_max_memory_size; // user specified a
40090b57cec5SDimitry Andric                                                            // packet size too
40100b57cec5SDimitry Andric                                                            // big, go as big
40110b57cec5SDimitry Andric         // as the remote stub says we can go.
40120b57cec5SDimitry Andric       } else {
40130b57cec5SDimitry Andric         m_max_memory_size = user_specified_max; // user's packet size is good
40140b57cec5SDimitry Andric       }
40150b57cec5SDimitry Andric     } else {
40160b57cec5SDimitry Andric       m_max_memory_size =
40170b57cec5SDimitry Andric           user_specified_max; // user's packet size is probably fine
40180b57cec5SDimitry Andric     }
40190b57cec5SDimitry Andric   }
40200b57cec5SDimitry Andric }
40210b57cec5SDimitry Andric 
40220b57cec5SDimitry Andric bool ProcessGDBRemote::GetModuleSpec(const FileSpec &module_file_spec,
40230b57cec5SDimitry Andric                                      const ArchSpec &arch,
40240b57cec5SDimitry Andric                                      ModuleSpec &module_spec) {
4025*81ad6265SDimitry Andric   Log *log = GetLog(LLDBLog::Platform);
40260b57cec5SDimitry Andric 
40270b57cec5SDimitry Andric   const ModuleCacheKey key(module_file_spec.GetPath(),
40280b57cec5SDimitry Andric                            arch.GetTriple().getTriple());
40290b57cec5SDimitry Andric   auto cached = m_cached_module_specs.find(key);
40300b57cec5SDimitry Andric   if (cached != m_cached_module_specs.end()) {
40310b57cec5SDimitry Andric     module_spec = cached->second;
40320b57cec5SDimitry Andric     return bool(module_spec);
40330b57cec5SDimitry Andric   }
40340b57cec5SDimitry Andric 
40350b57cec5SDimitry Andric   if (!m_gdb_comm.GetModuleInfo(module_file_spec, arch, module_spec)) {
40369dba64beSDimitry Andric     LLDB_LOGF(log, "ProcessGDBRemote::%s - failed to get module info for %s:%s",
40370b57cec5SDimitry Andric               __FUNCTION__, module_file_spec.GetPath().c_str(),
40380b57cec5SDimitry Andric               arch.GetTriple().getTriple().c_str());
40390b57cec5SDimitry Andric     return false;
40400b57cec5SDimitry Andric   }
40410b57cec5SDimitry Andric 
40420b57cec5SDimitry Andric   if (log) {
40430b57cec5SDimitry Andric     StreamString stream;
40440b57cec5SDimitry Andric     module_spec.Dump(stream);
40459dba64beSDimitry Andric     LLDB_LOGF(log, "ProcessGDBRemote::%s - got module info for (%s:%s) : %s",
40460b57cec5SDimitry Andric               __FUNCTION__, module_file_spec.GetPath().c_str(),
40470b57cec5SDimitry Andric               arch.GetTriple().getTriple().c_str(), stream.GetData());
40480b57cec5SDimitry Andric   }
40490b57cec5SDimitry Andric 
40500b57cec5SDimitry Andric   m_cached_module_specs[key] = module_spec;
40510b57cec5SDimitry Andric   return true;
40520b57cec5SDimitry Andric }
40530b57cec5SDimitry Andric 
40540b57cec5SDimitry Andric void ProcessGDBRemote::PrefetchModuleSpecs(
40550b57cec5SDimitry Andric     llvm::ArrayRef<FileSpec> module_file_specs, const llvm::Triple &triple) {
40560b57cec5SDimitry Andric   auto module_specs = m_gdb_comm.GetModulesInfo(module_file_specs, triple);
40570b57cec5SDimitry Andric   if (module_specs) {
40580b57cec5SDimitry Andric     for (const FileSpec &spec : module_file_specs)
40590b57cec5SDimitry Andric       m_cached_module_specs[ModuleCacheKey(spec.GetPath(),
40600b57cec5SDimitry Andric                                            triple.getTriple())] = ModuleSpec();
40610b57cec5SDimitry Andric     for (const ModuleSpec &spec : *module_specs)
40620b57cec5SDimitry Andric       m_cached_module_specs[ModuleCacheKey(spec.GetFileSpec().GetPath(),
40630b57cec5SDimitry Andric                                            triple.getTriple())] = spec;
40640b57cec5SDimitry Andric   }
40650b57cec5SDimitry Andric }
40660b57cec5SDimitry Andric 
40670b57cec5SDimitry Andric llvm::VersionTuple ProcessGDBRemote::GetHostOSVersion() {
40680b57cec5SDimitry Andric   return m_gdb_comm.GetOSVersion();
40690b57cec5SDimitry Andric }
40700b57cec5SDimitry Andric 
40719dba64beSDimitry Andric llvm::VersionTuple ProcessGDBRemote::GetHostMacCatalystVersion() {
40729dba64beSDimitry Andric   return m_gdb_comm.GetMacCatalystVersion();
40739dba64beSDimitry Andric }
40749dba64beSDimitry Andric 
40750b57cec5SDimitry Andric namespace {
40760b57cec5SDimitry Andric 
40770b57cec5SDimitry Andric typedef std::vector<std::string> stringVec;
40780b57cec5SDimitry Andric 
40790b57cec5SDimitry Andric typedef std::vector<struct GdbServerRegisterInfo> GDBServerRegisterVec;
40800b57cec5SDimitry Andric struct RegisterSetInfo {
40810b57cec5SDimitry Andric   ConstString name;
40820b57cec5SDimitry Andric };
40830b57cec5SDimitry Andric 
40840b57cec5SDimitry Andric typedef std::map<uint32_t, RegisterSetInfo> RegisterSetMap;
40850b57cec5SDimitry Andric 
40860b57cec5SDimitry Andric struct GdbServerTargetInfo {
40870b57cec5SDimitry Andric   std::string arch;
40880b57cec5SDimitry Andric   std::string osabi;
40890b57cec5SDimitry Andric   stringVec includes;
40900b57cec5SDimitry Andric   RegisterSetMap reg_set_map;
40910b57cec5SDimitry Andric };
40920b57cec5SDimitry Andric 
40930b57cec5SDimitry Andric bool ParseRegisters(XMLNode feature_node, GdbServerTargetInfo &target_info,
4094349cc55cSDimitry Andric                     std::vector<DynamicRegisterInfo::Register> &registers) {
40950b57cec5SDimitry Andric   if (!feature_node)
40960b57cec5SDimitry Andric     return false;
40970b57cec5SDimitry Andric 
40980b57cec5SDimitry Andric   feature_node.ForEachChildElementWithName(
4099349cc55cSDimitry Andric       "reg", [&target_info, &registers](const XMLNode &reg_node) -> bool {
41000b57cec5SDimitry Andric         std::string gdb_group;
41010b57cec5SDimitry Andric         std::string gdb_type;
4102349cc55cSDimitry Andric         DynamicRegisterInfo::Register reg_info;
41030b57cec5SDimitry Andric         bool encoding_set = false;
41040b57cec5SDimitry Andric         bool format_set = false;
41050b57cec5SDimitry Andric 
4106349cc55cSDimitry Andric         // FIXME: we're silently ignoring invalid data here
41070b57cec5SDimitry Andric         reg_node.ForEachAttribute([&target_info, &gdb_group, &gdb_type,
4108349cc55cSDimitry Andric                                    &encoding_set, &format_set, &reg_info](
41090b57cec5SDimitry Andric                                       const llvm::StringRef &name,
41100b57cec5SDimitry Andric                                       const llvm::StringRef &value) -> bool {
41110b57cec5SDimitry Andric           if (name == "name") {
4112349cc55cSDimitry Andric             reg_info.name.SetString(value);
41130b57cec5SDimitry Andric           } else if (name == "bitsize") {
4114349cc55cSDimitry Andric             if (llvm::to_integer(value, reg_info.byte_size))
41150b57cec5SDimitry Andric               reg_info.byte_size =
4116349cc55cSDimitry Andric                   llvm::divideCeil(reg_info.byte_size, CHAR_BIT);
41170b57cec5SDimitry Andric           } else if (name == "type") {
41180b57cec5SDimitry Andric             gdb_type = value.str();
41190b57cec5SDimitry Andric           } else if (name == "group") {
41200b57cec5SDimitry Andric             gdb_group = value.str();
41210b57cec5SDimitry Andric           } else if (name == "regnum") {
4122349cc55cSDimitry Andric             llvm::to_integer(value, reg_info.regnum_remote);
41230b57cec5SDimitry Andric           } else if (name == "offset") {
4124349cc55cSDimitry Andric             llvm::to_integer(value, reg_info.byte_offset);
41250b57cec5SDimitry Andric           } else if (name == "altname") {
4126349cc55cSDimitry Andric             reg_info.alt_name.SetString(value);
41270b57cec5SDimitry Andric           } else if (name == "encoding") {
41280b57cec5SDimitry Andric             encoding_set = true;
41290b57cec5SDimitry Andric             reg_info.encoding = Args::StringToEncoding(value, eEncodingUint);
41300b57cec5SDimitry Andric           } else if (name == "format") {
41310b57cec5SDimitry Andric             format_set = true;
4132349cc55cSDimitry Andric             if (!OptionArgParser::ToFormat(value.data(), reg_info.format,
4133349cc55cSDimitry Andric                                            nullptr)
41340b57cec5SDimitry Andric                      .Success())
4135349cc55cSDimitry Andric               reg_info.format =
4136349cc55cSDimitry Andric                   llvm::StringSwitch<lldb::Format>(value)
4137349cc55cSDimitry Andric                       .Case("vector-sint8", eFormatVectorOfSInt8)
4138349cc55cSDimitry Andric                       .Case("vector-uint8", eFormatVectorOfUInt8)
4139349cc55cSDimitry Andric                       .Case("vector-sint16", eFormatVectorOfSInt16)
4140349cc55cSDimitry Andric                       .Case("vector-uint16", eFormatVectorOfUInt16)
4141349cc55cSDimitry Andric                       .Case("vector-sint32", eFormatVectorOfSInt32)
4142349cc55cSDimitry Andric                       .Case("vector-uint32", eFormatVectorOfUInt32)
4143349cc55cSDimitry Andric                       .Case("vector-float32", eFormatVectorOfFloat32)
4144349cc55cSDimitry Andric                       .Case("vector-uint64", eFormatVectorOfUInt64)
4145349cc55cSDimitry Andric                       .Case("vector-uint128", eFormatVectorOfUInt128)
4146349cc55cSDimitry Andric                       .Default(eFormatInvalid);
41470b57cec5SDimitry Andric           } else if (name == "group_id") {
4148349cc55cSDimitry Andric             uint32_t set_id = UINT32_MAX;
4149349cc55cSDimitry Andric             llvm::to_integer(value, set_id);
41500b57cec5SDimitry Andric             RegisterSetMap::const_iterator pos =
41510b57cec5SDimitry Andric                 target_info.reg_set_map.find(set_id);
41520b57cec5SDimitry Andric             if (pos != target_info.reg_set_map.end())
4153349cc55cSDimitry Andric               reg_info.set_name = pos->second.name;
41540b57cec5SDimitry Andric           } else if (name == "gcc_regnum" || name == "ehframe_regnum") {
4155349cc55cSDimitry Andric             llvm::to_integer(value, reg_info.regnum_ehframe);
41560b57cec5SDimitry Andric           } else if (name == "dwarf_regnum") {
4157349cc55cSDimitry Andric             llvm::to_integer(value, reg_info.regnum_dwarf);
41580b57cec5SDimitry Andric           } else if (name == "generic") {
4159349cc55cSDimitry Andric             reg_info.regnum_generic = Args::StringToGenericRegister(value);
41600b57cec5SDimitry Andric           } else if (name == "value_regnums") {
4161349cc55cSDimitry Andric             SplitCommaSeparatedRegisterNumberString(value, reg_info.value_regs,
4162349cc55cSDimitry Andric                                                     0);
41630b57cec5SDimitry Andric           } else if (name == "invalidate_regnums") {
4164349cc55cSDimitry Andric             SplitCommaSeparatedRegisterNumberString(
4165349cc55cSDimitry Andric                 value, reg_info.invalidate_regs, 0);
41660b57cec5SDimitry Andric           } else {
41671fd87a68SDimitry Andric             Log *log(GetLog(GDBRLog::Process));
4168349cc55cSDimitry Andric             LLDB_LOGF(log,
4169349cc55cSDimitry Andric                       "ProcessGDBRemote::%s unhandled reg attribute %s = %s",
4170349cc55cSDimitry Andric                       __FUNCTION__, name.data(), value.data());
41710b57cec5SDimitry Andric           }
41720b57cec5SDimitry Andric           return true; // Keep iterating through all attributes
41730b57cec5SDimitry Andric         });
41740b57cec5SDimitry Andric 
41750b57cec5SDimitry Andric         if (!gdb_type.empty() && !(encoding_set || format_set)) {
41765ffd83dbSDimitry Andric           if (llvm::StringRef(gdb_type).startswith("int")) {
41770b57cec5SDimitry Andric             reg_info.format = eFormatHex;
41780b57cec5SDimitry Andric             reg_info.encoding = eEncodingUint;
41790b57cec5SDimitry Andric           } else if (gdb_type == "data_ptr" || gdb_type == "code_ptr") {
41800b57cec5SDimitry Andric             reg_info.format = eFormatAddressInfo;
41810b57cec5SDimitry Andric             reg_info.encoding = eEncodingUint;
4182349cc55cSDimitry Andric           } else if (gdb_type == "float") {
41830b57cec5SDimitry Andric             reg_info.format = eFormatFloat;
41840b57cec5SDimitry Andric             reg_info.encoding = eEncodingIEEE754;
4185349cc55cSDimitry Andric           } else if (gdb_type == "aarch64v" ||
4186349cc55cSDimitry Andric                      llvm::StringRef(gdb_type).startswith("vec") ||
4187349cc55cSDimitry Andric                      gdb_type == "i387_ext" || gdb_type == "uint128") {
4188349cc55cSDimitry Andric             // lldb doesn't handle 128-bit uints correctly (for ymm*h), so treat
4189349cc55cSDimitry Andric             // them as vector (similarly to xmm/ymm)
4190349cc55cSDimitry Andric             reg_info.format = eFormatVectorOfUInt8;
4191349cc55cSDimitry Andric             reg_info.encoding = eEncodingVector;
41920b57cec5SDimitry Andric           }
41930b57cec5SDimitry Andric         }
41940b57cec5SDimitry Andric 
41950b57cec5SDimitry Andric         // Only update the register set name if we didn't get a "reg_set"
41960b57cec5SDimitry Andric         // attribute. "set_name" will be empty if we didn't have a "reg_set"
41970b57cec5SDimitry Andric         // attribute.
4198349cc55cSDimitry Andric         if (!reg_info.set_name) {
41990b57cec5SDimitry Andric           if (!gdb_group.empty()) {
4200349cc55cSDimitry Andric             reg_info.set_name.SetCString(gdb_group.c_str());
42010b57cec5SDimitry Andric           } else {
42020b57cec5SDimitry Andric             // If no register group name provided anywhere,
42030b57cec5SDimitry Andric             // we'll create a 'general' register set
4204349cc55cSDimitry Andric             reg_info.set_name.SetCString("general");
42050b57cec5SDimitry Andric           }
42060b57cec5SDimitry Andric         }
42070b57cec5SDimitry Andric 
4208349cc55cSDimitry Andric         if (reg_info.byte_size == 0) {
42091fd87a68SDimitry Andric           Log *log(GetLog(GDBRLog::Process));
4210349cc55cSDimitry Andric           LLDB_LOGF(log,
4211349cc55cSDimitry Andric                     "ProcessGDBRemote::%s Skipping zero bitsize register %s",
4212349cc55cSDimitry Andric                     __FUNCTION__, reg_info.name.AsCString());
4213349cc55cSDimitry Andric         } else
4214349cc55cSDimitry Andric           registers.push_back(reg_info);
42150b57cec5SDimitry Andric 
42160b57cec5SDimitry Andric         return true; // Keep iterating through all "reg" elements
42170b57cec5SDimitry Andric       });
42180b57cec5SDimitry Andric   return true;
42190b57cec5SDimitry Andric }
42200b57cec5SDimitry Andric 
42210b57cec5SDimitry Andric } // namespace
42220b57cec5SDimitry Andric 
42230b57cec5SDimitry Andric // This method fetches a register description feature xml file from
42240b57cec5SDimitry Andric // the remote stub and adds registers/register groupsets/architecture
42250b57cec5SDimitry Andric // information to the current process.  It will call itself recursively
42260b57cec5SDimitry Andric // for nested register definition files.  It returns true if it was able
42270b57cec5SDimitry Andric // to fetch and parse an xml file.
42289dba64beSDimitry Andric bool ProcessGDBRemote::GetGDBServerRegisterInfoXMLAndProcess(
4229349cc55cSDimitry Andric     ArchSpec &arch_to_use, std::string xml_filename,
4230349cc55cSDimitry Andric     std::vector<DynamicRegisterInfo::Register> &registers) {
42310b57cec5SDimitry Andric   // request the target xml file
4232349cc55cSDimitry Andric   llvm::Expected<std::string> raw = m_gdb_comm.ReadExtFeature("features", xml_filename);
4233349cc55cSDimitry Andric   if (errorToBool(raw.takeError()))
42340b57cec5SDimitry Andric     return false;
42350b57cec5SDimitry Andric 
42360b57cec5SDimitry Andric   XMLDocument xml_document;
42370b57cec5SDimitry Andric 
4238349cc55cSDimitry Andric   if (xml_document.ParseMemory(raw->c_str(), raw->size(),
4239349cc55cSDimitry Andric                                xml_filename.c_str())) {
42400b57cec5SDimitry Andric     GdbServerTargetInfo target_info;
42410b57cec5SDimitry Andric     std::vector<XMLNode> feature_nodes;
42420b57cec5SDimitry Andric 
42430b57cec5SDimitry Andric     // The top level feature XML file will start with a <target> tag.
42440b57cec5SDimitry Andric     XMLNode target_node = xml_document.GetRootElement("target");
42450b57cec5SDimitry Andric     if (target_node) {
42460b57cec5SDimitry Andric       target_node.ForEachChildElement([&target_info, &feature_nodes](
42470b57cec5SDimitry Andric                                           const XMLNode &node) -> bool {
42480b57cec5SDimitry Andric         llvm::StringRef name = node.GetName();
42490b57cec5SDimitry Andric         if (name == "architecture") {
42500b57cec5SDimitry Andric           node.GetElementText(target_info.arch);
42510b57cec5SDimitry Andric         } else if (name == "osabi") {
42520b57cec5SDimitry Andric           node.GetElementText(target_info.osabi);
42530b57cec5SDimitry Andric         } else if (name == "xi:include" || name == "include") {
425404eeddc0SDimitry Andric           std::string href = node.GetAttributeValue("href");
42550b57cec5SDimitry Andric           if (!href.empty())
425604eeddc0SDimitry Andric             target_info.includes.push_back(href);
42570b57cec5SDimitry Andric         } else if (name == "feature") {
42580b57cec5SDimitry Andric           feature_nodes.push_back(node);
42590b57cec5SDimitry Andric         } else if (name == "groups") {
42600b57cec5SDimitry Andric           node.ForEachChildElementWithName(
42610b57cec5SDimitry Andric               "group", [&target_info](const XMLNode &node) -> bool {
42620b57cec5SDimitry Andric                 uint32_t set_id = UINT32_MAX;
42630b57cec5SDimitry Andric                 RegisterSetInfo set_info;
42640b57cec5SDimitry Andric 
42650b57cec5SDimitry Andric                 node.ForEachAttribute(
42660b57cec5SDimitry Andric                     [&set_id, &set_info](const llvm::StringRef &name,
42670b57cec5SDimitry Andric                                          const llvm::StringRef &value) -> bool {
4268349cc55cSDimitry Andric                       // FIXME: we're silently ignoring invalid data here
42690b57cec5SDimitry Andric                       if (name == "id")
4270349cc55cSDimitry Andric                         llvm::to_integer(value, set_id);
42710b57cec5SDimitry Andric                       if (name == "name")
42720b57cec5SDimitry Andric                         set_info.name = ConstString(value);
42730b57cec5SDimitry Andric                       return true; // Keep iterating through all attributes
42740b57cec5SDimitry Andric                     });
42750b57cec5SDimitry Andric 
42760b57cec5SDimitry Andric                 if (set_id != UINT32_MAX)
42770b57cec5SDimitry Andric                   target_info.reg_set_map[set_id] = set_info;
42780b57cec5SDimitry Andric                 return true; // Keep iterating through all "group" elements
42790b57cec5SDimitry Andric               });
42800b57cec5SDimitry Andric         }
42810b57cec5SDimitry Andric         return true; // Keep iterating through all children of the target_node
42820b57cec5SDimitry Andric       });
42830b57cec5SDimitry Andric     } else {
42840b57cec5SDimitry Andric       // In an included XML feature file, we're already "inside" the <target>
42850b57cec5SDimitry Andric       // tag of the initial XML file; this included file will likely only have
42860b57cec5SDimitry Andric       // a <feature> tag.  Need to check for any more included files in this
42870b57cec5SDimitry Andric       // <feature> element.
42880b57cec5SDimitry Andric       XMLNode feature_node = xml_document.GetRootElement("feature");
42890b57cec5SDimitry Andric       if (feature_node) {
42900b57cec5SDimitry Andric         feature_nodes.push_back(feature_node);
42910b57cec5SDimitry Andric         feature_node.ForEachChildElement([&target_info](
42920b57cec5SDimitry Andric                                         const XMLNode &node) -> bool {
42930b57cec5SDimitry Andric           llvm::StringRef name = node.GetName();
42940b57cec5SDimitry Andric           if (name == "xi:include" || name == "include") {
429504eeddc0SDimitry Andric             std::string href = node.GetAttributeValue("href");
42960b57cec5SDimitry Andric             if (!href.empty())
429704eeddc0SDimitry Andric               target_info.includes.push_back(href);
42980b57cec5SDimitry Andric             }
42990b57cec5SDimitry Andric             return true;
43000b57cec5SDimitry Andric           });
43010b57cec5SDimitry Andric       }
43020b57cec5SDimitry Andric     }
43030b57cec5SDimitry Andric 
4304349cc55cSDimitry Andric     // gdbserver does not implement the LLDB packets used to determine host
4305349cc55cSDimitry Andric     // or process architecture.  If that is the case, attempt to use
4306349cc55cSDimitry Andric     // the <architecture/> field from target.xml, e.g.:
4307349cc55cSDimitry Andric     //
43080b57cec5SDimitry Andric     //   <architecture>i386:x86-64</architecture> (seen from VMWare ESXi)
4309349cc55cSDimitry Andric     //   <architecture>arm</architecture> (seen from Segger JLink on unspecified
4310349cc55cSDimitry Andric     //   arm board)
43110b57cec5SDimitry Andric     if (!arch_to_use.IsValid() && !target_info.arch.empty()) {
43120b57cec5SDimitry Andric       // We don't have any information about vendor or OS.
4313349cc55cSDimitry Andric       arch_to_use.SetTriple(llvm::StringSwitch<std::string>(target_info.arch)
4314349cc55cSDimitry Andric                                 .Case("i386:x86-64", "x86_64")
4315349cc55cSDimitry Andric                                 .Default(target_info.arch) +
4316349cc55cSDimitry Andric                             "--");
43170b57cec5SDimitry Andric 
4318349cc55cSDimitry Andric       if (arch_to_use.IsValid())
43190b57cec5SDimitry Andric         GetTarget().MergeArchitecture(arch_to_use);
43200b57cec5SDimitry Andric     }
43210b57cec5SDimitry Andric 
43220b57cec5SDimitry Andric     if (arch_to_use.IsValid()) {
43230b57cec5SDimitry Andric       for (auto &feature_node : feature_nodes) {
4324349cc55cSDimitry Andric         ParseRegisters(feature_node, target_info,
4325349cc55cSDimitry Andric                        registers);
43260b57cec5SDimitry Andric       }
43270b57cec5SDimitry Andric 
43280b57cec5SDimitry Andric       for (const auto &include : target_info.includes) {
4329e8d8bef9SDimitry Andric         GetGDBServerRegisterInfoXMLAndProcess(arch_to_use, include,
4330349cc55cSDimitry Andric                                               registers);
43310b57cec5SDimitry Andric       }
43320b57cec5SDimitry Andric     }
43330b57cec5SDimitry Andric   } else {
43340b57cec5SDimitry Andric     return false;
43350b57cec5SDimitry Andric   }
43360b57cec5SDimitry Andric   return true;
43370b57cec5SDimitry Andric }
43380b57cec5SDimitry Andric 
4339349cc55cSDimitry Andric void ProcessGDBRemote::AddRemoteRegisters(
4340349cc55cSDimitry Andric     std::vector<DynamicRegisterInfo::Register> &registers,
4341349cc55cSDimitry Andric     const ArchSpec &arch_to_use) {
4342349cc55cSDimitry Andric   std::map<uint32_t, uint32_t> remote_to_local_map;
4343349cc55cSDimitry Andric   uint32_t remote_regnum = 0;
4344349cc55cSDimitry Andric   for (auto it : llvm::enumerate(registers)) {
4345349cc55cSDimitry Andric     DynamicRegisterInfo::Register &remote_reg_info = it.value();
4346349cc55cSDimitry Andric 
4347349cc55cSDimitry Andric     // Assign successive remote regnums if missing.
4348349cc55cSDimitry Andric     if (remote_reg_info.regnum_remote == LLDB_INVALID_REGNUM)
4349349cc55cSDimitry Andric       remote_reg_info.regnum_remote = remote_regnum;
4350349cc55cSDimitry Andric 
4351349cc55cSDimitry Andric     // Create a mapping from remote to local regnos.
4352349cc55cSDimitry Andric     remote_to_local_map[remote_reg_info.regnum_remote] = it.index();
4353349cc55cSDimitry Andric 
4354349cc55cSDimitry Andric     remote_regnum = remote_reg_info.regnum_remote + 1;
4355349cc55cSDimitry Andric   }
4356349cc55cSDimitry Andric 
4357349cc55cSDimitry Andric   for (DynamicRegisterInfo::Register &remote_reg_info : registers) {
4358349cc55cSDimitry Andric     auto proc_to_lldb = [&remote_to_local_map](uint32_t process_regnum) {
4359349cc55cSDimitry Andric       auto lldb_regit = remote_to_local_map.find(process_regnum);
4360349cc55cSDimitry Andric       return lldb_regit != remote_to_local_map.end() ? lldb_regit->second
4361349cc55cSDimitry Andric                                                      : LLDB_INVALID_REGNUM;
4362349cc55cSDimitry Andric     };
4363349cc55cSDimitry Andric 
4364349cc55cSDimitry Andric     llvm::transform(remote_reg_info.value_regs,
4365349cc55cSDimitry Andric                     remote_reg_info.value_regs.begin(), proc_to_lldb);
4366349cc55cSDimitry Andric     llvm::transform(remote_reg_info.invalidate_regs,
4367349cc55cSDimitry Andric                     remote_reg_info.invalidate_regs.begin(), proc_to_lldb);
4368349cc55cSDimitry Andric   }
4369349cc55cSDimitry Andric 
4370349cc55cSDimitry Andric   // Don't use Process::GetABI, this code gets called from DidAttach, and
4371349cc55cSDimitry Andric   // in that context we haven't set the Target's architecture yet, so the
4372349cc55cSDimitry Andric   // ABI is also potentially incorrect.
4373349cc55cSDimitry Andric   if (ABISP abi_sp = ABI::FindPlugin(shared_from_this(), arch_to_use))
4374349cc55cSDimitry Andric     abi_sp->AugmentRegisterInfo(registers);
4375349cc55cSDimitry Andric 
4376349cc55cSDimitry Andric   m_register_info_sp->SetRegisterInfo(std::move(registers), arch_to_use);
4377349cc55cSDimitry Andric }
4378349cc55cSDimitry Andric 
43790b57cec5SDimitry Andric // query the target of gdb-remote for extended target information returns
43800b57cec5SDimitry Andric // true on success (got register definitions), false on failure (did not).
43810b57cec5SDimitry Andric bool ProcessGDBRemote::GetGDBServerRegisterInfo(ArchSpec &arch_to_use) {
43820b57cec5SDimitry Andric   // Make sure LLDB has an XML parser it can use first
43830b57cec5SDimitry Andric   if (!XMLDocument::XMLEnabled())
43840b57cec5SDimitry Andric     return false;
43850b57cec5SDimitry Andric 
43860b57cec5SDimitry Andric   // check that we have extended feature read support
43870b57cec5SDimitry Andric   if (!m_gdb_comm.GetQXferFeaturesReadSupported())
43880b57cec5SDimitry Andric     return false;
43890b57cec5SDimitry Andric 
4390349cc55cSDimitry Andric   std::vector<DynamicRegisterInfo::Register> registers;
4391e8d8bef9SDimitry Andric   if (GetGDBServerRegisterInfoXMLAndProcess(arch_to_use, "target.xml",
4392349cc55cSDimitry Andric                                             registers))
4393349cc55cSDimitry Andric     AddRemoteRegisters(registers, arch_to_use);
43940b57cec5SDimitry Andric 
4395e8d8bef9SDimitry Andric   return m_register_info_sp->GetNumRegisters() > 0;
43960b57cec5SDimitry Andric }
43970b57cec5SDimitry Andric 
43989dba64beSDimitry Andric llvm::Expected<LoadedModuleInfoList> ProcessGDBRemote::GetLoadedModuleList() {
43990b57cec5SDimitry Andric   // Make sure LLDB has an XML parser it can use first
44000b57cec5SDimitry Andric   if (!XMLDocument::XMLEnabled())
44019dba64beSDimitry Andric     return llvm::createStringError(llvm::inconvertibleErrorCode(),
44029dba64beSDimitry Andric                                    "XML parsing not available");
44030b57cec5SDimitry Andric 
4404*81ad6265SDimitry Andric   Log *log = GetLog(LLDBLog::Process);
44059dba64beSDimitry Andric   LLDB_LOGF(log, "ProcessGDBRemote::%s", __FUNCTION__);
44060b57cec5SDimitry Andric 
44079dba64beSDimitry Andric   LoadedModuleInfoList list;
44080b57cec5SDimitry Andric   GDBRemoteCommunicationClient &comm = m_gdb_comm;
4409349cc55cSDimitry Andric   bool can_use_svr4 = GetGlobalPluginProperties().GetUseSVR4();
44100b57cec5SDimitry Andric 
44110b57cec5SDimitry Andric   // check that we have extended feature read support
44120b57cec5SDimitry Andric   if (can_use_svr4 && comm.GetQXferLibrariesSVR4ReadSupported()) {
44130b57cec5SDimitry Andric     // request the loaded library list
4414349cc55cSDimitry Andric     llvm::Expected<std::string> raw = comm.ReadExtFeature("libraries-svr4", "");
4415349cc55cSDimitry Andric     if (!raw)
4416349cc55cSDimitry Andric       return raw.takeError();
44170b57cec5SDimitry Andric 
44180b57cec5SDimitry Andric     // parse the xml file in memory
4419349cc55cSDimitry Andric     LLDB_LOGF(log, "parsing: %s", raw->c_str());
44200b57cec5SDimitry Andric     XMLDocument doc;
44210b57cec5SDimitry Andric 
4422349cc55cSDimitry Andric     if (!doc.ParseMemory(raw->c_str(), raw->size(), "noname.xml"))
44239dba64beSDimitry Andric       return llvm::createStringError(llvm::inconvertibleErrorCode(),
44249dba64beSDimitry Andric                                      "Error reading noname.xml");
44250b57cec5SDimitry Andric 
44260b57cec5SDimitry Andric     XMLNode root_element = doc.GetRootElement("library-list-svr4");
44270b57cec5SDimitry Andric     if (!root_element)
44289dba64beSDimitry Andric       return llvm::createStringError(
44299dba64beSDimitry Andric           llvm::inconvertibleErrorCode(),
44309dba64beSDimitry Andric           "Error finding library-list-svr4 xml element");
44310b57cec5SDimitry Andric 
44320b57cec5SDimitry Andric     // main link map structure
443304eeddc0SDimitry Andric     std::string main_lm = root_element.GetAttributeValue("main-lm");
4434349cc55cSDimitry Andric     // FIXME: we're silently ignoring invalid data here
4435349cc55cSDimitry Andric     if (!main_lm.empty())
4436349cc55cSDimitry Andric       llvm::to_integer(main_lm, list.m_link_map);
44370b57cec5SDimitry Andric 
44380b57cec5SDimitry Andric     root_element.ForEachChildElementWithName(
44390b57cec5SDimitry Andric         "library", [log, &list](const XMLNode &library) -> bool {
44400b57cec5SDimitry Andric           LoadedModuleInfoList::LoadedModuleInfo module;
44410b57cec5SDimitry Andric 
4442349cc55cSDimitry Andric           // FIXME: we're silently ignoring invalid data here
44430b57cec5SDimitry Andric           library.ForEachAttribute(
44440b57cec5SDimitry Andric               [&module](const llvm::StringRef &name,
44450b57cec5SDimitry Andric                         const llvm::StringRef &value) -> bool {
4446349cc55cSDimitry Andric                 uint64_t uint_value = LLDB_INVALID_ADDRESS;
44470b57cec5SDimitry Andric                 if (name == "name")
44480b57cec5SDimitry Andric                   module.set_name(value.str());
44490b57cec5SDimitry Andric                 else if (name == "lm") {
44500b57cec5SDimitry Andric                   // the address of the link_map struct.
4451349cc55cSDimitry Andric                   llvm::to_integer(value, uint_value);
4452349cc55cSDimitry Andric                   module.set_link_map(uint_value);
44530b57cec5SDimitry Andric                 } else if (name == "l_addr") {
44540b57cec5SDimitry Andric                   // the displacement as read from the field 'l_addr' of the
44550b57cec5SDimitry Andric                   // link_map struct.
4456349cc55cSDimitry Andric                   llvm::to_integer(value, uint_value);
4457349cc55cSDimitry Andric                   module.set_base(uint_value);
44580b57cec5SDimitry Andric                   // base address is always a displacement, not an absolute
44590b57cec5SDimitry Andric                   // value.
44600b57cec5SDimitry Andric                   module.set_base_is_offset(true);
44610b57cec5SDimitry Andric                 } else if (name == "l_ld") {
44625ffd83dbSDimitry Andric                   // the memory address of the libraries PT_DYNAMIC section.
4463349cc55cSDimitry Andric                   llvm::to_integer(value, uint_value);
4464349cc55cSDimitry Andric                   module.set_dynamic(uint_value);
44650b57cec5SDimitry Andric                 }
44660b57cec5SDimitry Andric 
44670b57cec5SDimitry Andric                 return true; // Keep iterating over all properties of "library"
44680b57cec5SDimitry Andric               });
44690b57cec5SDimitry Andric 
44700b57cec5SDimitry Andric           if (log) {
44710b57cec5SDimitry Andric             std::string name;
44720b57cec5SDimitry Andric             lldb::addr_t lm = 0, base = 0, ld = 0;
44730b57cec5SDimitry Andric             bool base_is_offset;
44740b57cec5SDimitry Andric 
44750b57cec5SDimitry Andric             module.get_name(name);
44760b57cec5SDimitry Andric             module.get_link_map(lm);
44770b57cec5SDimitry Andric             module.get_base(base);
44780b57cec5SDimitry Andric             module.get_base_is_offset(base_is_offset);
44790b57cec5SDimitry Andric             module.get_dynamic(ld);
44800b57cec5SDimitry Andric 
44819dba64beSDimitry Andric             LLDB_LOGF(log,
44829dba64beSDimitry Andric                       "found (link_map:0x%08" PRIx64 ", base:0x%08" PRIx64
44830b57cec5SDimitry Andric                       "[%s], ld:0x%08" PRIx64 ", name:'%s')",
44840b57cec5SDimitry Andric                       lm, base, (base_is_offset ? "offset" : "absolute"), ld,
44850b57cec5SDimitry Andric                       name.c_str());
44860b57cec5SDimitry Andric           }
44870b57cec5SDimitry Andric 
44880b57cec5SDimitry Andric           list.add(module);
44890b57cec5SDimitry Andric           return true; // Keep iterating over all "library" elements in the root
44900b57cec5SDimitry Andric                        // node
44910b57cec5SDimitry Andric         });
44920b57cec5SDimitry Andric 
44930b57cec5SDimitry Andric     if (log)
44949dba64beSDimitry Andric       LLDB_LOGF(log, "found %" PRId32 " modules in total",
44950b57cec5SDimitry Andric                 (int)list.m_list.size());
44969dba64beSDimitry Andric     return list;
44970b57cec5SDimitry Andric   } else if (comm.GetQXferLibrariesReadSupported()) {
44980b57cec5SDimitry Andric     // request the loaded library list
4499349cc55cSDimitry Andric     llvm::Expected<std::string> raw = comm.ReadExtFeature("libraries", "");
45000b57cec5SDimitry Andric 
4501349cc55cSDimitry Andric     if (!raw)
4502349cc55cSDimitry Andric       return raw.takeError();
45030b57cec5SDimitry Andric 
4504349cc55cSDimitry Andric     LLDB_LOGF(log, "parsing: %s", raw->c_str());
45050b57cec5SDimitry Andric     XMLDocument doc;
45060b57cec5SDimitry Andric 
4507349cc55cSDimitry Andric     if (!doc.ParseMemory(raw->c_str(), raw->size(), "noname.xml"))
45089dba64beSDimitry Andric       return llvm::createStringError(llvm::inconvertibleErrorCode(),
45099dba64beSDimitry Andric                                      "Error reading noname.xml");
45100b57cec5SDimitry Andric 
45110b57cec5SDimitry Andric     XMLNode root_element = doc.GetRootElement("library-list");
45120b57cec5SDimitry Andric     if (!root_element)
45139dba64beSDimitry Andric       return llvm::createStringError(llvm::inconvertibleErrorCode(),
45149dba64beSDimitry Andric                                      "Error finding library-list xml element");
45150b57cec5SDimitry Andric 
4516349cc55cSDimitry Andric     // FIXME: we're silently ignoring invalid data here
45170b57cec5SDimitry Andric     root_element.ForEachChildElementWithName(
45180b57cec5SDimitry Andric         "library", [log, &list](const XMLNode &library) -> bool {
45190b57cec5SDimitry Andric           LoadedModuleInfoList::LoadedModuleInfo module;
45200b57cec5SDimitry Andric 
452104eeddc0SDimitry Andric           std::string name = library.GetAttributeValue("name");
452204eeddc0SDimitry Andric           module.set_name(name);
45230b57cec5SDimitry Andric 
45240b57cec5SDimitry Andric           // The base address of a given library will be the address of its
45250b57cec5SDimitry Andric           // first section. Most remotes send only one section for Windows
45260b57cec5SDimitry Andric           // targets for example.
45270b57cec5SDimitry Andric           const XMLNode &section =
45280b57cec5SDimitry Andric               library.FindFirstChildElementWithName("section");
452904eeddc0SDimitry Andric           std::string address = section.GetAttributeValue("address");
4530349cc55cSDimitry Andric           uint64_t address_value = LLDB_INVALID_ADDRESS;
4531349cc55cSDimitry Andric           llvm::to_integer(address, address_value);
4532349cc55cSDimitry Andric           module.set_base(address_value);
45330b57cec5SDimitry Andric           // These addresses are absolute values.
45340b57cec5SDimitry Andric           module.set_base_is_offset(false);
45350b57cec5SDimitry Andric 
45360b57cec5SDimitry Andric           if (log) {
45370b57cec5SDimitry Andric             std::string name;
45380b57cec5SDimitry Andric             lldb::addr_t base = 0;
45390b57cec5SDimitry Andric             bool base_is_offset;
45400b57cec5SDimitry Andric             module.get_name(name);
45410b57cec5SDimitry Andric             module.get_base(base);
45420b57cec5SDimitry Andric             module.get_base_is_offset(base_is_offset);
45430b57cec5SDimitry Andric 
45449dba64beSDimitry Andric             LLDB_LOGF(log, "found (base:0x%08" PRIx64 "[%s], name:'%s')", base,
45450b57cec5SDimitry Andric                       (base_is_offset ? "offset" : "absolute"), name.c_str());
45460b57cec5SDimitry Andric           }
45470b57cec5SDimitry Andric 
45480b57cec5SDimitry Andric           list.add(module);
45490b57cec5SDimitry Andric           return true; // Keep iterating over all "library" elements in the root
45500b57cec5SDimitry Andric                        // node
45510b57cec5SDimitry Andric         });
45520b57cec5SDimitry Andric 
45530b57cec5SDimitry Andric     if (log)
45549dba64beSDimitry Andric       LLDB_LOGF(log, "found %" PRId32 " modules in total",
45550b57cec5SDimitry Andric                 (int)list.m_list.size());
45569dba64beSDimitry Andric     return list;
45570b57cec5SDimitry Andric   } else {
45589dba64beSDimitry Andric     return llvm::createStringError(llvm::inconvertibleErrorCode(),
45599dba64beSDimitry Andric                                    "Remote libraries not supported");
45600b57cec5SDimitry Andric   }
45610b57cec5SDimitry Andric }
45620b57cec5SDimitry Andric 
45630b57cec5SDimitry Andric lldb::ModuleSP ProcessGDBRemote::LoadModuleAtAddress(const FileSpec &file,
45640b57cec5SDimitry Andric                                                      lldb::addr_t link_map,
45650b57cec5SDimitry Andric                                                      lldb::addr_t base_addr,
45660b57cec5SDimitry Andric                                                      bool value_is_offset) {
45670b57cec5SDimitry Andric   DynamicLoader *loader = GetDynamicLoader();
45680b57cec5SDimitry Andric   if (!loader)
45690b57cec5SDimitry Andric     return nullptr;
45700b57cec5SDimitry Andric 
45710b57cec5SDimitry Andric   return loader->LoadModuleAtAddress(file, link_map, base_addr,
45720b57cec5SDimitry Andric                                      value_is_offset);
45730b57cec5SDimitry Andric }
45740b57cec5SDimitry Andric 
45759dba64beSDimitry Andric llvm::Error ProcessGDBRemote::LoadModules() {
45760b57cec5SDimitry Andric   using lldb_private::process_gdb_remote::ProcessGDBRemote;
45770b57cec5SDimitry Andric 
45780b57cec5SDimitry Andric   // request a list of loaded libraries from GDBServer
45799dba64beSDimitry Andric   llvm::Expected<LoadedModuleInfoList> module_list = GetLoadedModuleList();
45809dba64beSDimitry Andric   if (!module_list)
45819dba64beSDimitry Andric     return module_list.takeError();
45820b57cec5SDimitry Andric 
45830b57cec5SDimitry Andric   // get a list of all the modules
45840b57cec5SDimitry Andric   ModuleList new_modules;
45850b57cec5SDimitry Andric 
45869dba64beSDimitry Andric   for (LoadedModuleInfoList::LoadedModuleInfo &modInfo : module_list->m_list) {
45870b57cec5SDimitry Andric     std::string mod_name;
45880b57cec5SDimitry Andric     lldb::addr_t mod_base;
45890b57cec5SDimitry Andric     lldb::addr_t link_map;
45900b57cec5SDimitry Andric     bool mod_base_is_offset;
45910b57cec5SDimitry Andric 
45920b57cec5SDimitry Andric     bool valid = true;
45930b57cec5SDimitry Andric     valid &= modInfo.get_name(mod_name);
45940b57cec5SDimitry Andric     valid &= modInfo.get_base(mod_base);
45950b57cec5SDimitry Andric     valid &= modInfo.get_base_is_offset(mod_base_is_offset);
45960b57cec5SDimitry Andric     if (!valid)
45970b57cec5SDimitry Andric       continue;
45980b57cec5SDimitry Andric 
45990b57cec5SDimitry Andric     if (!modInfo.get_link_map(link_map))
46000b57cec5SDimitry Andric       link_map = LLDB_INVALID_ADDRESS;
46010b57cec5SDimitry Andric 
46020b57cec5SDimitry Andric     FileSpec file(mod_name);
46030b57cec5SDimitry Andric     FileSystem::Instance().Resolve(file);
46040b57cec5SDimitry Andric     lldb::ModuleSP module_sp =
46050b57cec5SDimitry Andric         LoadModuleAtAddress(file, link_map, mod_base, mod_base_is_offset);
46060b57cec5SDimitry Andric 
46070b57cec5SDimitry Andric     if (module_sp.get())
46080b57cec5SDimitry Andric       new_modules.Append(module_sp);
46090b57cec5SDimitry Andric   }
46100b57cec5SDimitry Andric 
46110b57cec5SDimitry Andric   if (new_modules.GetSize() > 0) {
46120b57cec5SDimitry Andric     ModuleList removed_modules;
46130b57cec5SDimitry Andric     Target &target = GetTarget();
46140b57cec5SDimitry Andric     ModuleList &loaded_modules = m_process->GetTarget().GetImages();
46150b57cec5SDimitry Andric 
46160b57cec5SDimitry Andric     for (size_t i = 0; i < loaded_modules.GetSize(); ++i) {
46170b57cec5SDimitry Andric       const lldb::ModuleSP loaded_module = loaded_modules.GetModuleAtIndex(i);
46180b57cec5SDimitry Andric 
46190b57cec5SDimitry Andric       bool found = false;
46200b57cec5SDimitry Andric       for (size_t j = 0; j < new_modules.GetSize(); ++j) {
46210b57cec5SDimitry Andric         if (new_modules.GetModuleAtIndex(j).get() == loaded_module.get())
46220b57cec5SDimitry Andric           found = true;
46230b57cec5SDimitry Andric       }
46240b57cec5SDimitry Andric 
46250b57cec5SDimitry Andric       // The main executable will never be included in libraries-svr4, don't
46260b57cec5SDimitry Andric       // remove it
46270b57cec5SDimitry Andric       if (!found &&
46280b57cec5SDimitry Andric           loaded_module.get() != target.GetExecutableModulePointer()) {
46290b57cec5SDimitry Andric         removed_modules.Append(loaded_module);
46300b57cec5SDimitry Andric       }
46310b57cec5SDimitry Andric     }
46320b57cec5SDimitry Andric 
46330b57cec5SDimitry Andric     loaded_modules.Remove(removed_modules);
46340b57cec5SDimitry Andric     m_process->GetTarget().ModulesDidUnload(removed_modules, false);
46350b57cec5SDimitry Andric 
46360b57cec5SDimitry Andric     new_modules.ForEach([&target](const lldb::ModuleSP module_sp) -> bool {
46370b57cec5SDimitry Andric       lldb_private::ObjectFile *obj = module_sp->GetObjectFile();
46380b57cec5SDimitry Andric       if (!obj)
46390b57cec5SDimitry Andric         return true;
46400b57cec5SDimitry Andric 
46410b57cec5SDimitry Andric       if (obj->GetType() != ObjectFile::Type::eTypeExecutable)
46420b57cec5SDimitry Andric         return true;
46430b57cec5SDimitry Andric 
46440b57cec5SDimitry Andric       lldb::ModuleSP module_copy_sp = module_sp;
46450b57cec5SDimitry Andric       target.SetExecutableModule(module_copy_sp, eLoadDependentsNo);
46460b57cec5SDimitry Andric       return false;
46470b57cec5SDimitry Andric     });
46480b57cec5SDimitry Andric 
46490b57cec5SDimitry Andric     loaded_modules.AppendIfNeeded(new_modules);
46500b57cec5SDimitry Andric     m_process->GetTarget().ModulesDidLoad(new_modules);
46510b57cec5SDimitry Andric   }
46520b57cec5SDimitry Andric 
46539dba64beSDimitry Andric   return llvm::ErrorSuccess();
46540b57cec5SDimitry Andric }
46550b57cec5SDimitry Andric 
46560b57cec5SDimitry Andric Status ProcessGDBRemote::GetFileLoadAddress(const FileSpec &file,
46570b57cec5SDimitry Andric                                             bool &is_loaded,
46580b57cec5SDimitry Andric                                             lldb::addr_t &load_addr) {
46590b57cec5SDimitry Andric   is_loaded = false;
46600b57cec5SDimitry Andric   load_addr = LLDB_INVALID_ADDRESS;
46610b57cec5SDimitry Andric 
46620b57cec5SDimitry Andric   std::string file_path = file.GetPath(false);
46630b57cec5SDimitry Andric   if (file_path.empty())
46640b57cec5SDimitry Andric     return Status("Empty file name specified");
46650b57cec5SDimitry Andric 
46660b57cec5SDimitry Andric   StreamString packet;
46670b57cec5SDimitry Andric   packet.PutCString("qFileLoadAddress:");
46680b57cec5SDimitry Andric   packet.PutStringAsRawHex8(file_path);
46690b57cec5SDimitry Andric 
46700b57cec5SDimitry Andric   StringExtractorGDBRemote response;
4671fe6060f1SDimitry Andric   if (m_gdb_comm.SendPacketAndWaitForResponse(packet.GetString(), response) !=
46720b57cec5SDimitry Andric       GDBRemoteCommunication::PacketResult::Success)
46730b57cec5SDimitry Andric     return Status("Sending qFileLoadAddress packet failed");
46740b57cec5SDimitry Andric 
46750b57cec5SDimitry Andric   if (response.IsErrorResponse()) {
46760b57cec5SDimitry Andric     if (response.GetError() == 1) {
46770b57cec5SDimitry Andric       // The file is not loaded into the inferior
46780b57cec5SDimitry Andric       is_loaded = false;
46790b57cec5SDimitry Andric       load_addr = LLDB_INVALID_ADDRESS;
46800b57cec5SDimitry Andric       return Status();
46810b57cec5SDimitry Andric     }
46820b57cec5SDimitry Andric 
46830b57cec5SDimitry Andric     return Status(
46840b57cec5SDimitry Andric         "Fetching file load address from remote server returned an error");
46850b57cec5SDimitry Andric   }
46860b57cec5SDimitry Andric 
46870b57cec5SDimitry Andric   if (response.IsNormalResponse()) {
46880b57cec5SDimitry Andric     is_loaded = true;
46890b57cec5SDimitry Andric     load_addr = response.GetHexMaxU64(false, LLDB_INVALID_ADDRESS);
46900b57cec5SDimitry Andric     return Status();
46910b57cec5SDimitry Andric   }
46920b57cec5SDimitry Andric 
46930b57cec5SDimitry Andric   return Status(
46940b57cec5SDimitry Andric       "Unknown error happened during sending the load address packet");
46950b57cec5SDimitry Andric }
46960b57cec5SDimitry Andric 
46970b57cec5SDimitry Andric void ProcessGDBRemote::ModulesDidLoad(ModuleList &module_list) {
46980b57cec5SDimitry Andric   // We must call the lldb_private::Process::ModulesDidLoad () first before we
46990b57cec5SDimitry Andric   // do anything
47000b57cec5SDimitry Andric   Process::ModulesDidLoad(module_list);
47010b57cec5SDimitry Andric 
47020b57cec5SDimitry Andric   // After loading shared libraries, we can ask our remote GDB server if it
47030b57cec5SDimitry Andric   // needs any symbols.
47040b57cec5SDimitry Andric   m_gdb_comm.ServeSymbolLookups(this);
47050b57cec5SDimitry Andric }
47060b57cec5SDimitry Andric 
47070b57cec5SDimitry Andric void ProcessGDBRemote::HandleAsyncStdout(llvm::StringRef out) {
47080b57cec5SDimitry Andric   AppendSTDOUT(out.data(), out.size());
47090b57cec5SDimitry Andric }
47100b57cec5SDimitry Andric 
47110b57cec5SDimitry Andric static const char *end_delimiter = "--end--;";
47120b57cec5SDimitry Andric static const int end_delimiter_len = 8;
47130b57cec5SDimitry Andric 
47140b57cec5SDimitry Andric void ProcessGDBRemote::HandleAsyncMisc(llvm::StringRef data) {
47150b57cec5SDimitry Andric   std::string input = data.str(); // '1' to move beyond 'A'
47160b57cec5SDimitry Andric   if (m_partial_profile_data.length() > 0) {
47170b57cec5SDimitry Andric     m_partial_profile_data.append(input);
47180b57cec5SDimitry Andric     input = m_partial_profile_data;
47190b57cec5SDimitry Andric     m_partial_profile_data.clear();
47200b57cec5SDimitry Andric   }
47210b57cec5SDimitry Andric 
47220b57cec5SDimitry Andric   size_t found, pos = 0, len = input.length();
47230b57cec5SDimitry Andric   while ((found = input.find(end_delimiter, pos)) != std::string::npos) {
47240b57cec5SDimitry Andric     StringExtractorGDBRemote profileDataExtractor(
47250b57cec5SDimitry Andric         input.substr(pos, found).c_str());
47260b57cec5SDimitry Andric     std::string profile_data =
47270b57cec5SDimitry Andric         HarmonizeThreadIdsForProfileData(profileDataExtractor);
47280b57cec5SDimitry Andric     BroadcastAsyncProfileData(profile_data);
47290b57cec5SDimitry Andric 
47300b57cec5SDimitry Andric     pos = found + end_delimiter_len;
47310b57cec5SDimitry Andric   }
47320b57cec5SDimitry Andric 
47330b57cec5SDimitry Andric   if (pos < len) {
47340b57cec5SDimitry Andric     // Last incomplete chunk.
47350b57cec5SDimitry Andric     m_partial_profile_data = input.substr(pos);
47360b57cec5SDimitry Andric   }
47370b57cec5SDimitry Andric }
47380b57cec5SDimitry Andric 
47390b57cec5SDimitry Andric std::string ProcessGDBRemote::HarmonizeThreadIdsForProfileData(
47400b57cec5SDimitry Andric     StringExtractorGDBRemote &profileDataExtractor) {
47410b57cec5SDimitry Andric   std::map<uint64_t, uint32_t> new_thread_id_to_used_usec_map;
47420b57cec5SDimitry Andric   std::string output;
47430b57cec5SDimitry Andric   llvm::raw_string_ostream output_stream(output);
47440b57cec5SDimitry Andric   llvm::StringRef name, value;
47450b57cec5SDimitry Andric 
47460b57cec5SDimitry Andric   // Going to assuming thread_used_usec comes first, else bail out.
47470b57cec5SDimitry Andric   while (profileDataExtractor.GetNameColonValue(name, value)) {
47480b57cec5SDimitry Andric     if (name.compare("thread_used_id") == 0) {
47490b57cec5SDimitry Andric       StringExtractor threadIDHexExtractor(value);
47500b57cec5SDimitry Andric       uint64_t thread_id = threadIDHexExtractor.GetHexMaxU64(false, 0);
47510b57cec5SDimitry Andric 
47520b57cec5SDimitry Andric       bool has_used_usec = false;
47530b57cec5SDimitry Andric       uint32_t curr_used_usec = 0;
47540b57cec5SDimitry Andric       llvm::StringRef usec_name, usec_value;
47550b57cec5SDimitry Andric       uint32_t input_file_pos = profileDataExtractor.GetFilePos();
47560b57cec5SDimitry Andric       if (profileDataExtractor.GetNameColonValue(usec_name, usec_value)) {
47570b57cec5SDimitry Andric         if (usec_name.equals("thread_used_usec")) {
47580b57cec5SDimitry Andric           has_used_usec = true;
47590b57cec5SDimitry Andric           usec_value.getAsInteger(0, curr_used_usec);
47600b57cec5SDimitry Andric         } else {
47610b57cec5SDimitry Andric           // We didn't find what we want, it is probably an older version. Bail
47620b57cec5SDimitry Andric           // out.
47630b57cec5SDimitry Andric           profileDataExtractor.SetFilePos(input_file_pos);
47640b57cec5SDimitry Andric         }
47650b57cec5SDimitry Andric       }
47660b57cec5SDimitry Andric 
47670b57cec5SDimitry Andric       if (has_used_usec) {
47680b57cec5SDimitry Andric         uint32_t prev_used_usec = 0;
47690b57cec5SDimitry Andric         std::map<uint64_t, uint32_t>::iterator iterator =
47700b57cec5SDimitry Andric             m_thread_id_to_used_usec_map.find(thread_id);
47710b57cec5SDimitry Andric         if (iterator != m_thread_id_to_used_usec_map.end()) {
47720b57cec5SDimitry Andric           prev_used_usec = m_thread_id_to_used_usec_map[thread_id];
47730b57cec5SDimitry Andric         }
47740b57cec5SDimitry Andric 
47750b57cec5SDimitry Andric         uint32_t real_used_usec = curr_used_usec - prev_used_usec;
47760b57cec5SDimitry Andric         // A good first time record is one that runs for at least 0.25 sec
47770b57cec5SDimitry Andric         bool good_first_time =
47780b57cec5SDimitry Andric             (prev_used_usec == 0) && (real_used_usec > 250000);
47790b57cec5SDimitry Andric         bool good_subsequent_time =
47800b57cec5SDimitry Andric             (prev_used_usec > 0) &&
47810b57cec5SDimitry Andric             ((real_used_usec > 0) || (HasAssignedIndexIDToThread(thread_id)));
47820b57cec5SDimitry Andric 
47830b57cec5SDimitry Andric         if (good_first_time || good_subsequent_time) {
47840b57cec5SDimitry Andric           // We try to avoid doing too many index id reservation, resulting in
47850b57cec5SDimitry Andric           // fast increase of index ids.
47860b57cec5SDimitry Andric 
47870b57cec5SDimitry Andric           output_stream << name << ":";
47880b57cec5SDimitry Andric           int32_t index_id = AssignIndexIDToThread(thread_id);
47890b57cec5SDimitry Andric           output_stream << index_id << ";";
47900b57cec5SDimitry Andric 
47910b57cec5SDimitry Andric           output_stream << usec_name << ":" << usec_value << ";";
47920b57cec5SDimitry Andric         } else {
47930b57cec5SDimitry Andric           // Skip past 'thread_used_name'.
47940b57cec5SDimitry Andric           llvm::StringRef local_name, local_value;
47950b57cec5SDimitry Andric           profileDataExtractor.GetNameColonValue(local_name, local_value);
47960b57cec5SDimitry Andric         }
47970b57cec5SDimitry Andric 
47980b57cec5SDimitry Andric         // Store current time as previous time so that they can be compared
47990b57cec5SDimitry Andric         // later.
48000b57cec5SDimitry Andric         new_thread_id_to_used_usec_map[thread_id] = curr_used_usec;
48010b57cec5SDimitry Andric       } else {
48020b57cec5SDimitry Andric         // Bail out and use old string.
48030b57cec5SDimitry Andric         output_stream << name << ":" << value << ";";
48040b57cec5SDimitry Andric       }
48050b57cec5SDimitry Andric     } else {
48060b57cec5SDimitry Andric       output_stream << name << ":" << value << ";";
48070b57cec5SDimitry Andric     }
48080b57cec5SDimitry Andric   }
48090b57cec5SDimitry Andric   output_stream << end_delimiter;
48100b57cec5SDimitry Andric   m_thread_id_to_used_usec_map = new_thread_id_to_used_usec_map;
48110b57cec5SDimitry Andric 
48120b57cec5SDimitry Andric   return output_stream.str();
48130b57cec5SDimitry Andric }
48140b57cec5SDimitry Andric 
48150b57cec5SDimitry Andric void ProcessGDBRemote::HandleStopReply() {
48160b57cec5SDimitry Andric   if (GetStopID() != 0)
48170b57cec5SDimitry Andric     return;
48180b57cec5SDimitry Andric 
48190b57cec5SDimitry Andric   if (GetID() == LLDB_INVALID_PROCESS_ID) {
48200b57cec5SDimitry Andric     lldb::pid_t pid = m_gdb_comm.GetCurrentProcessID();
48210b57cec5SDimitry Andric     if (pid != LLDB_INVALID_PROCESS_ID)
48220b57cec5SDimitry Andric       SetID(pid);
48230b57cec5SDimitry Andric   }
48240b57cec5SDimitry Andric   BuildDynamicRegisterInfo(true);
48250b57cec5SDimitry Andric }
48260b57cec5SDimitry Andric 
4827349cc55cSDimitry Andric llvm::Expected<bool> ProcessGDBRemote::SaveCore(llvm::StringRef outfile) {
4828349cc55cSDimitry Andric   if (!m_gdb_comm.GetSaveCoreSupported())
4829349cc55cSDimitry Andric     return false;
4830349cc55cSDimitry Andric 
4831349cc55cSDimitry Andric   StreamString packet;
4832349cc55cSDimitry Andric   packet.PutCString("qSaveCore;path-hint:");
4833349cc55cSDimitry Andric   packet.PutStringAsRawHex8(outfile);
4834349cc55cSDimitry Andric 
4835349cc55cSDimitry Andric   StringExtractorGDBRemote response;
4836349cc55cSDimitry Andric   if (m_gdb_comm.SendPacketAndWaitForResponse(packet.GetString(), response) ==
4837349cc55cSDimitry Andric       GDBRemoteCommunication::PacketResult::Success) {
4838349cc55cSDimitry Andric     // TODO: grab error message from the packet?  StringExtractor seems to
4839349cc55cSDimitry Andric     // be missing a method for that
4840349cc55cSDimitry Andric     if (response.IsErrorResponse())
4841349cc55cSDimitry Andric       return llvm::createStringError(
4842349cc55cSDimitry Andric           llvm::inconvertibleErrorCode(),
4843349cc55cSDimitry Andric           llvm::formatv("qSaveCore returned an error"));
4844349cc55cSDimitry Andric 
4845349cc55cSDimitry Andric     std::string path;
4846349cc55cSDimitry Andric 
4847349cc55cSDimitry Andric     // process the response
4848349cc55cSDimitry Andric     for (auto x : llvm::split(response.GetStringRef(), ';')) {
4849349cc55cSDimitry Andric       if (x.consume_front("core-path:"))
4850349cc55cSDimitry Andric         StringExtractor(x).GetHexByteString(path);
4851349cc55cSDimitry Andric     }
4852349cc55cSDimitry Andric 
4853349cc55cSDimitry Andric     // verify that we've gotten what we need
4854349cc55cSDimitry Andric     if (path.empty())
4855349cc55cSDimitry Andric       return llvm::createStringError(llvm::inconvertibleErrorCode(),
4856349cc55cSDimitry Andric                                      "qSaveCore returned no core path");
4857349cc55cSDimitry Andric 
4858349cc55cSDimitry Andric     // now transfer the core file
4859349cc55cSDimitry Andric     FileSpec remote_core{llvm::StringRef(path)};
4860349cc55cSDimitry Andric     Platform &platform = *GetTarget().GetPlatform();
4861349cc55cSDimitry Andric     Status error = platform.GetFile(remote_core, FileSpec(outfile));
4862349cc55cSDimitry Andric 
4863349cc55cSDimitry Andric     if (platform.IsRemote()) {
4864349cc55cSDimitry Andric       // NB: we unlink the file on error too
4865349cc55cSDimitry Andric       platform.Unlink(remote_core);
4866349cc55cSDimitry Andric       if (error.Fail())
4867349cc55cSDimitry Andric         return error.ToError();
4868349cc55cSDimitry Andric     }
4869349cc55cSDimitry Andric 
4870349cc55cSDimitry Andric     return true;
4871349cc55cSDimitry Andric   }
4872349cc55cSDimitry Andric 
4873349cc55cSDimitry Andric   return llvm::createStringError(llvm::inconvertibleErrorCode(),
4874349cc55cSDimitry Andric                                  "Unable to send qSaveCore");
4875349cc55cSDimitry Andric }
4876349cc55cSDimitry Andric 
48770b57cec5SDimitry Andric static const char *const s_async_json_packet_prefix = "JSON-async:";
48780b57cec5SDimitry Andric 
48790b57cec5SDimitry Andric static StructuredData::ObjectSP
48800b57cec5SDimitry Andric ParseStructuredDataPacket(llvm::StringRef packet) {
48811fd87a68SDimitry Andric   Log *log = GetLog(GDBRLog::Process);
48820b57cec5SDimitry Andric 
48830b57cec5SDimitry Andric   if (!packet.consume_front(s_async_json_packet_prefix)) {
48840b57cec5SDimitry Andric     if (log) {
48859dba64beSDimitry Andric       LLDB_LOGF(
48869dba64beSDimitry Andric           log,
48870b57cec5SDimitry Andric           "GDBRemoteCommunicationClientBase::%s() received $J packet "
48880b57cec5SDimitry Andric           "but was not a StructuredData packet: packet starts with "
48890b57cec5SDimitry Andric           "%s",
48900b57cec5SDimitry Andric           __FUNCTION__,
48910b57cec5SDimitry Andric           packet.slice(0, strlen(s_async_json_packet_prefix)).str().c_str());
48920b57cec5SDimitry Andric     }
48930b57cec5SDimitry Andric     return StructuredData::ObjectSP();
48940b57cec5SDimitry Andric   }
48950b57cec5SDimitry Andric 
48960b57cec5SDimitry Andric   // This is an asynchronous JSON packet, destined for a StructuredDataPlugin.
48975ffd83dbSDimitry Andric   StructuredData::ObjectSP json_sp =
48985ffd83dbSDimitry Andric       StructuredData::ParseJSON(std::string(packet));
48990b57cec5SDimitry Andric   if (log) {
49000b57cec5SDimitry Andric     if (json_sp) {
49010b57cec5SDimitry Andric       StreamString json_str;
49029dba64beSDimitry Andric       json_sp->Dump(json_str, true);
49030b57cec5SDimitry Andric       json_str.Flush();
49049dba64beSDimitry Andric       LLDB_LOGF(log,
49059dba64beSDimitry Andric                 "ProcessGDBRemote::%s() "
49060b57cec5SDimitry Andric                 "received Async StructuredData packet: %s",
49070b57cec5SDimitry Andric                 __FUNCTION__, json_str.GetData());
49080b57cec5SDimitry Andric     } else {
49099dba64beSDimitry Andric       LLDB_LOGF(log,
49109dba64beSDimitry Andric                 "ProcessGDBRemote::%s"
49110b57cec5SDimitry Andric                 "() received StructuredData packet:"
49120b57cec5SDimitry Andric                 " parse failure",
49130b57cec5SDimitry Andric                 __FUNCTION__);
49140b57cec5SDimitry Andric     }
49150b57cec5SDimitry Andric   }
49160b57cec5SDimitry Andric   return json_sp;
49170b57cec5SDimitry Andric }
49180b57cec5SDimitry Andric 
49190b57cec5SDimitry Andric void ProcessGDBRemote::HandleAsyncStructuredDataPacket(llvm::StringRef data) {
49200b57cec5SDimitry Andric   auto structured_data_sp = ParseStructuredDataPacket(data);
49210b57cec5SDimitry Andric   if (structured_data_sp)
49220b57cec5SDimitry Andric     RouteAsyncStructuredData(structured_data_sp);
49230b57cec5SDimitry Andric }
49240b57cec5SDimitry Andric 
49250b57cec5SDimitry Andric class CommandObjectProcessGDBRemoteSpeedTest : public CommandObjectParsed {
49260b57cec5SDimitry Andric public:
49270b57cec5SDimitry Andric   CommandObjectProcessGDBRemoteSpeedTest(CommandInterpreter &interpreter)
49280b57cec5SDimitry Andric       : CommandObjectParsed(interpreter, "process plugin packet speed-test",
49290b57cec5SDimitry Andric                             "Tests packet speeds of various sizes to determine "
49300b57cec5SDimitry Andric                             "the performance characteristics of the GDB remote "
49310b57cec5SDimitry Andric                             "connection. ",
49320b57cec5SDimitry Andric                             nullptr),
49330b57cec5SDimitry Andric         m_option_group(),
49340b57cec5SDimitry Andric         m_num_packets(LLDB_OPT_SET_1, false, "count", 'c', 0, eArgTypeCount,
49350b57cec5SDimitry Andric                       "The number of packets to send of each varying size "
49360b57cec5SDimitry Andric                       "(default is 1000).",
49370b57cec5SDimitry Andric                       1000),
49380b57cec5SDimitry Andric         m_max_send(LLDB_OPT_SET_1, false, "max-send", 's', 0, eArgTypeCount,
49390b57cec5SDimitry Andric                    "The maximum number of bytes to send in a packet. Sizes "
49400b57cec5SDimitry Andric                    "increase in powers of 2 while the size is less than or "
49410b57cec5SDimitry Andric                    "equal to this option value. (default 1024).",
49420b57cec5SDimitry Andric                    1024),
49430b57cec5SDimitry Andric         m_max_recv(LLDB_OPT_SET_1, false, "max-receive", 'r', 0, eArgTypeCount,
49440b57cec5SDimitry Andric                    "The maximum number of bytes to receive in a packet. Sizes "
49450b57cec5SDimitry Andric                    "increase in powers of 2 while the size is less than or "
49460b57cec5SDimitry Andric                    "equal to this option value. (default 1024).",
49470b57cec5SDimitry Andric                    1024),
49480b57cec5SDimitry Andric         m_json(LLDB_OPT_SET_1, false, "json", 'j',
49490b57cec5SDimitry Andric                "Print the output as JSON data for easy parsing.", false, true) {
49500b57cec5SDimitry Andric     m_option_group.Append(&m_num_packets, LLDB_OPT_SET_ALL, LLDB_OPT_SET_1);
49510b57cec5SDimitry Andric     m_option_group.Append(&m_max_send, LLDB_OPT_SET_ALL, LLDB_OPT_SET_1);
49520b57cec5SDimitry Andric     m_option_group.Append(&m_max_recv, LLDB_OPT_SET_ALL, LLDB_OPT_SET_1);
49530b57cec5SDimitry Andric     m_option_group.Append(&m_json, LLDB_OPT_SET_ALL, LLDB_OPT_SET_1);
49540b57cec5SDimitry Andric     m_option_group.Finalize();
49550b57cec5SDimitry Andric   }
49560b57cec5SDimitry Andric 
4957fe6060f1SDimitry Andric   ~CommandObjectProcessGDBRemoteSpeedTest() override = default;
49580b57cec5SDimitry Andric 
49590b57cec5SDimitry Andric   Options *GetOptions() override { return &m_option_group; }
49600b57cec5SDimitry Andric 
49610b57cec5SDimitry Andric   bool DoExecute(Args &command, CommandReturnObject &result) override {
49620b57cec5SDimitry Andric     const size_t argc = command.GetArgumentCount();
49630b57cec5SDimitry Andric     if (argc == 0) {
49640b57cec5SDimitry Andric       ProcessGDBRemote *process =
49650b57cec5SDimitry Andric           (ProcessGDBRemote *)m_interpreter.GetExecutionContext()
49660b57cec5SDimitry Andric               .GetProcessPtr();
49670b57cec5SDimitry Andric       if (process) {
49680b57cec5SDimitry Andric         StreamSP output_stream_sp(
49690b57cec5SDimitry Andric             m_interpreter.GetDebugger().GetAsyncOutputStream());
49700b57cec5SDimitry Andric         result.SetImmediateOutputStream(output_stream_sp);
49710b57cec5SDimitry Andric 
49720b57cec5SDimitry Andric         const uint32_t num_packets =
49730b57cec5SDimitry Andric             (uint32_t)m_num_packets.GetOptionValue().GetCurrentValue();
49740b57cec5SDimitry Andric         const uint64_t max_send = m_max_send.GetOptionValue().GetCurrentValue();
49750b57cec5SDimitry Andric         const uint64_t max_recv = m_max_recv.GetOptionValue().GetCurrentValue();
49760b57cec5SDimitry Andric         const bool json = m_json.GetOptionValue().GetCurrentValue();
49770b57cec5SDimitry Andric         const uint64_t k_recv_amount =
49780b57cec5SDimitry Andric             4 * 1024 * 1024; // Receive amount in bytes
49790b57cec5SDimitry Andric         process->GetGDBRemote().TestPacketSpeed(
49800b57cec5SDimitry Andric             num_packets, max_send, max_recv, k_recv_amount, json,
49810b57cec5SDimitry Andric             output_stream_sp ? *output_stream_sp : result.GetOutputStream());
49820b57cec5SDimitry Andric         result.SetStatus(eReturnStatusSuccessFinishResult);
49830b57cec5SDimitry Andric         return true;
49840b57cec5SDimitry Andric       }
49850b57cec5SDimitry Andric     } else {
49860b57cec5SDimitry Andric       result.AppendErrorWithFormat("'%s' takes no arguments",
49870b57cec5SDimitry Andric                                    m_cmd_name.c_str());
49880b57cec5SDimitry Andric     }
49890b57cec5SDimitry Andric     result.SetStatus(eReturnStatusFailed);
49900b57cec5SDimitry Andric     return false;
49910b57cec5SDimitry Andric   }
49920b57cec5SDimitry Andric 
49930b57cec5SDimitry Andric protected:
49940b57cec5SDimitry Andric   OptionGroupOptions m_option_group;
49950b57cec5SDimitry Andric   OptionGroupUInt64 m_num_packets;
49960b57cec5SDimitry Andric   OptionGroupUInt64 m_max_send;
49970b57cec5SDimitry Andric   OptionGroupUInt64 m_max_recv;
49980b57cec5SDimitry Andric   OptionGroupBoolean m_json;
49990b57cec5SDimitry Andric };
50000b57cec5SDimitry Andric 
50010b57cec5SDimitry Andric class CommandObjectProcessGDBRemotePacketHistory : public CommandObjectParsed {
50020b57cec5SDimitry Andric private:
50030b57cec5SDimitry Andric public:
50040b57cec5SDimitry Andric   CommandObjectProcessGDBRemotePacketHistory(CommandInterpreter &interpreter)
50050b57cec5SDimitry Andric       : CommandObjectParsed(interpreter, "process plugin packet history",
50060b57cec5SDimitry Andric                             "Dumps the packet history buffer. ", nullptr) {}
50070b57cec5SDimitry Andric 
5008fe6060f1SDimitry Andric   ~CommandObjectProcessGDBRemotePacketHistory() override = default;
50090b57cec5SDimitry Andric 
50100b57cec5SDimitry Andric   bool DoExecute(Args &command, CommandReturnObject &result) override {
50110b57cec5SDimitry Andric     ProcessGDBRemote *process =
5012*81ad6265SDimitry Andric         (ProcessGDBRemote *)m_interpreter.GetExecutionContext().GetProcessPtr();
50130b57cec5SDimitry Andric     if (process) {
50140b57cec5SDimitry Andric       process->GetGDBRemote().DumpHistory(result.GetOutputStream());
50150b57cec5SDimitry Andric       result.SetStatus(eReturnStatusSuccessFinishResult);
50160b57cec5SDimitry Andric       return true;
50170b57cec5SDimitry Andric     }
50180b57cec5SDimitry Andric     result.SetStatus(eReturnStatusFailed);
50190b57cec5SDimitry Andric     return false;
50200b57cec5SDimitry Andric   }
50210b57cec5SDimitry Andric };
50220b57cec5SDimitry Andric 
50230b57cec5SDimitry Andric class CommandObjectProcessGDBRemotePacketXferSize : public CommandObjectParsed {
50240b57cec5SDimitry Andric private:
50250b57cec5SDimitry Andric public:
50260b57cec5SDimitry Andric   CommandObjectProcessGDBRemotePacketXferSize(CommandInterpreter &interpreter)
50270b57cec5SDimitry Andric       : CommandObjectParsed(
50280b57cec5SDimitry Andric             interpreter, "process plugin packet xfer-size",
50290b57cec5SDimitry Andric             "Maximum size that lldb will try to read/write one one chunk.",
5030*81ad6265SDimitry Andric             nullptr) {
5031*81ad6265SDimitry Andric     CommandArgumentData max_arg{eArgTypeUnsignedInteger, eArgRepeatPlain};
5032*81ad6265SDimitry Andric     m_arguments.push_back({max_arg});
5033*81ad6265SDimitry Andric   }
50340b57cec5SDimitry Andric 
5035fe6060f1SDimitry Andric   ~CommandObjectProcessGDBRemotePacketXferSize() override = default;
50360b57cec5SDimitry Andric 
50370b57cec5SDimitry Andric   bool DoExecute(Args &command, CommandReturnObject &result) override {
50380b57cec5SDimitry Andric     const size_t argc = command.GetArgumentCount();
50390b57cec5SDimitry Andric     if (argc == 0) {
50400b57cec5SDimitry Andric       result.AppendErrorWithFormat("'%s' takes an argument to specify the max "
50410b57cec5SDimitry Andric                                    "amount to be transferred when "
50420b57cec5SDimitry Andric                                    "reading/writing",
50430b57cec5SDimitry Andric                                    m_cmd_name.c_str());
50440b57cec5SDimitry Andric       return false;
50450b57cec5SDimitry Andric     }
50460b57cec5SDimitry Andric 
50470b57cec5SDimitry Andric     ProcessGDBRemote *process =
50480b57cec5SDimitry Andric         (ProcessGDBRemote *)m_interpreter.GetExecutionContext().GetProcessPtr();
50490b57cec5SDimitry Andric     if (process) {
50500b57cec5SDimitry Andric       const char *packet_size = command.GetArgumentAtIndex(0);
50510b57cec5SDimitry Andric       errno = 0;
50520b57cec5SDimitry Andric       uint64_t user_specified_max = strtoul(packet_size, nullptr, 10);
50530b57cec5SDimitry Andric       if (errno == 0 && user_specified_max != 0) {
50540b57cec5SDimitry Andric         process->SetUserSpecifiedMaxMemoryTransferSize(user_specified_max);
50550b57cec5SDimitry Andric         result.SetStatus(eReturnStatusSuccessFinishResult);
50560b57cec5SDimitry Andric         return true;
50570b57cec5SDimitry Andric       }
50580b57cec5SDimitry Andric     }
50590b57cec5SDimitry Andric     result.SetStatus(eReturnStatusFailed);
50600b57cec5SDimitry Andric     return false;
50610b57cec5SDimitry Andric   }
50620b57cec5SDimitry Andric };
50630b57cec5SDimitry Andric 
50640b57cec5SDimitry Andric class CommandObjectProcessGDBRemotePacketSend : public CommandObjectParsed {
50650b57cec5SDimitry Andric private:
50660b57cec5SDimitry Andric public:
50670b57cec5SDimitry Andric   CommandObjectProcessGDBRemotePacketSend(CommandInterpreter &interpreter)
50680b57cec5SDimitry Andric       : CommandObjectParsed(interpreter, "process plugin packet send",
50690b57cec5SDimitry Andric                             "Send a custom packet through the GDB remote "
50700b57cec5SDimitry Andric                             "protocol and print the answer. "
50710b57cec5SDimitry Andric                             "The packet header and footer will automatically "
50720b57cec5SDimitry Andric                             "be added to the packet prior to sending and "
50730b57cec5SDimitry Andric                             "stripped from the result.",
5074*81ad6265SDimitry Andric                             nullptr) {
5075*81ad6265SDimitry Andric     CommandArgumentData packet_arg{eArgTypeNone, eArgRepeatStar};
5076*81ad6265SDimitry Andric     m_arguments.push_back({packet_arg});
5077*81ad6265SDimitry Andric   }
50780b57cec5SDimitry Andric 
5079fe6060f1SDimitry Andric   ~CommandObjectProcessGDBRemotePacketSend() override = default;
50800b57cec5SDimitry Andric 
50810b57cec5SDimitry Andric   bool DoExecute(Args &command, CommandReturnObject &result) override {
50820b57cec5SDimitry Andric     const size_t argc = command.GetArgumentCount();
50830b57cec5SDimitry Andric     if (argc == 0) {
50840b57cec5SDimitry Andric       result.AppendErrorWithFormat(
50850b57cec5SDimitry Andric           "'%s' takes a one or more packet content arguments",
50860b57cec5SDimitry Andric           m_cmd_name.c_str());
50870b57cec5SDimitry Andric       return false;
50880b57cec5SDimitry Andric     }
50890b57cec5SDimitry Andric 
50900b57cec5SDimitry Andric     ProcessGDBRemote *process =
50910b57cec5SDimitry Andric         (ProcessGDBRemote *)m_interpreter.GetExecutionContext().GetProcessPtr();
50920b57cec5SDimitry Andric     if (process) {
50930b57cec5SDimitry Andric       for (size_t i = 0; i < argc; ++i) {
50940b57cec5SDimitry Andric         const char *packet_cstr = command.GetArgumentAtIndex(0);
50950b57cec5SDimitry Andric         StringExtractorGDBRemote response;
50960b57cec5SDimitry Andric         process->GetGDBRemote().SendPacketAndWaitForResponse(
5097fe6060f1SDimitry Andric             packet_cstr, response, process->GetInterruptTimeout());
50980b57cec5SDimitry Andric         result.SetStatus(eReturnStatusSuccessFinishResult);
50990b57cec5SDimitry Andric         Stream &output_strm = result.GetOutputStream();
51000b57cec5SDimitry Andric         output_strm.Printf("  packet: %s\n", packet_cstr);
51015ffd83dbSDimitry Andric         std::string response_str = std::string(response.GetStringRef());
51020b57cec5SDimitry Andric 
51030b57cec5SDimitry Andric         if (strstr(packet_cstr, "qGetProfileData") != nullptr) {
51040b57cec5SDimitry Andric           response_str = process->HarmonizeThreadIdsForProfileData(response);
51050b57cec5SDimitry Andric         }
51060b57cec5SDimitry Andric 
51070b57cec5SDimitry Andric         if (response_str.empty())
51080b57cec5SDimitry Andric           output_strm.PutCString("response: \nerror: UNIMPLEMENTED\n");
51090b57cec5SDimitry Andric         else
51109dba64beSDimitry Andric           output_strm.Printf("response: %s\n", response.GetStringRef().data());
51110b57cec5SDimitry Andric       }
51120b57cec5SDimitry Andric     }
51130b57cec5SDimitry Andric     return true;
51140b57cec5SDimitry Andric   }
51150b57cec5SDimitry Andric };
51160b57cec5SDimitry Andric 
51170b57cec5SDimitry Andric class CommandObjectProcessGDBRemotePacketMonitor : public CommandObjectRaw {
51180b57cec5SDimitry Andric private:
51190b57cec5SDimitry Andric public:
51200b57cec5SDimitry Andric   CommandObjectProcessGDBRemotePacketMonitor(CommandInterpreter &interpreter)
51210b57cec5SDimitry Andric       : CommandObjectRaw(interpreter, "process plugin packet monitor",
51220b57cec5SDimitry Andric                          "Send a qRcmd packet through the GDB remote protocol "
51230b57cec5SDimitry Andric                          "and print the response."
51240b57cec5SDimitry Andric                          "The argument passed to this command will be hex "
51250b57cec5SDimitry Andric                          "encoded into a valid 'qRcmd' packet, sent and the "
51260b57cec5SDimitry Andric                          "response will be printed.") {}
51270b57cec5SDimitry Andric 
5128fe6060f1SDimitry Andric   ~CommandObjectProcessGDBRemotePacketMonitor() override = default;
51290b57cec5SDimitry Andric 
51300b57cec5SDimitry Andric   bool DoExecute(llvm::StringRef command,
51310b57cec5SDimitry Andric                  CommandReturnObject &result) override {
51320b57cec5SDimitry Andric     if (command.empty()) {
51330b57cec5SDimitry Andric       result.AppendErrorWithFormat("'%s' takes a command string argument",
51340b57cec5SDimitry Andric                                    m_cmd_name.c_str());
51350b57cec5SDimitry Andric       return false;
51360b57cec5SDimitry Andric     }
51370b57cec5SDimitry Andric 
51380b57cec5SDimitry Andric     ProcessGDBRemote *process =
51390b57cec5SDimitry Andric         (ProcessGDBRemote *)m_interpreter.GetExecutionContext().GetProcessPtr();
51400b57cec5SDimitry Andric     if (process) {
51410b57cec5SDimitry Andric       StreamString packet;
51420b57cec5SDimitry Andric       packet.PutCString("qRcmd,");
51430b57cec5SDimitry Andric       packet.PutBytesAsRawHex8(command.data(), command.size());
51440b57cec5SDimitry Andric 
51450b57cec5SDimitry Andric       StringExtractorGDBRemote response;
51460b57cec5SDimitry Andric       Stream &output_strm = result.GetOutputStream();
51470b57cec5SDimitry Andric       process->GetGDBRemote().SendPacketAndReceiveResponseWithOutputSupport(
5148fe6060f1SDimitry Andric           packet.GetString(), response, process->GetInterruptTimeout(),
51490b57cec5SDimitry Andric           [&output_strm](llvm::StringRef output) { output_strm << output; });
51500b57cec5SDimitry Andric       result.SetStatus(eReturnStatusSuccessFinishResult);
51510b57cec5SDimitry Andric       output_strm.Printf("  packet: %s\n", packet.GetData());
51525ffd83dbSDimitry Andric       const std::string &response_str = std::string(response.GetStringRef());
51530b57cec5SDimitry Andric 
51540b57cec5SDimitry Andric       if (response_str.empty())
51550b57cec5SDimitry Andric         output_strm.PutCString("response: \nerror: UNIMPLEMENTED\n");
51560b57cec5SDimitry Andric       else
51579dba64beSDimitry Andric         output_strm.Printf("response: %s\n", response.GetStringRef().data());
51580b57cec5SDimitry Andric     }
51590b57cec5SDimitry Andric     return true;
51600b57cec5SDimitry Andric   }
51610b57cec5SDimitry Andric };
51620b57cec5SDimitry Andric 
51630b57cec5SDimitry Andric class CommandObjectProcessGDBRemotePacket : public CommandObjectMultiword {
51640b57cec5SDimitry Andric private:
51650b57cec5SDimitry Andric public:
51660b57cec5SDimitry Andric   CommandObjectProcessGDBRemotePacket(CommandInterpreter &interpreter)
51670b57cec5SDimitry Andric       : CommandObjectMultiword(interpreter, "process plugin packet",
51680b57cec5SDimitry Andric                                "Commands that deal with GDB remote packets.",
51690b57cec5SDimitry Andric                                nullptr) {
51700b57cec5SDimitry Andric     LoadSubCommand(
51710b57cec5SDimitry Andric         "history",
51720b57cec5SDimitry Andric         CommandObjectSP(
51730b57cec5SDimitry Andric             new CommandObjectProcessGDBRemotePacketHistory(interpreter)));
51740b57cec5SDimitry Andric     LoadSubCommand(
51750b57cec5SDimitry Andric         "send", CommandObjectSP(
51760b57cec5SDimitry Andric                     new CommandObjectProcessGDBRemotePacketSend(interpreter)));
51770b57cec5SDimitry Andric     LoadSubCommand(
51780b57cec5SDimitry Andric         "monitor",
51790b57cec5SDimitry Andric         CommandObjectSP(
51800b57cec5SDimitry Andric             new CommandObjectProcessGDBRemotePacketMonitor(interpreter)));
51810b57cec5SDimitry Andric     LoadSubCommand(
51820b57cec5SDimitry Andric         "xfer-size",
51830b57cec5SDimitry Andric         CommandObjectSP(
51840b57cec5SDimitry Andric             new CommandObjectProcessGDBRemotePacketXferSize(interpreter)));
51850b57cec5SDimitry Andric     LoadSubCommand("speed-test",
51860b57cec5SDimitry Andric                    CommandObjectSP(new CommandObjectProcessGDBRemoteSpeedTest(
51870b57cec5SDimitry Andric                        interpreter)));
51880b57cec5SDimitry Andric   }
51890b57cec5SDimitry Andric 
5190fe6060f1SDimitry Andric   ~CommandObjectProcessGDBRemotePacket() override = default;
51910b57cec5SDimitry Andric };
51920b57cec5SDimitry Andric 
51930b57cec5SDimitry Andric class CommandObjectMultiwordProcessGDBRemote : public CommandObjectMultiword {
51940b57cec5SDimitry Andric public:
51950b57cec5SDimitry Andric   CommandObjectMultiwordProcessGDBRemote(CommandInterpreter &interpreter)
51960b57cec5SDimitry Andric       : CommandObjectMultiword(
51970b57cec5SDimitry Andric             interpreter, "process plugin",
51980b57cec5SDimitry Andric             "Commands for operating on a ProcessGDBRemote process.",
51990b57cec5SDimitry Andric             "process plugin <subcommand> [<subcommand-options>]") {
52000b57cec5SDimitry Andric     LoadSubCommand(
52010b57cec5SDimitry Andric         "packet",
52020b57cec5SDimitry Andric         CommandObjectSP(new CommandObjectProcessGDBRemotePacket(interpreter)));
52030b57cec5SDimitry Andric   }
52040b57cec5SDimitry Andric 
5205fe6060f1SDimitry Andric   ~CommandObjectMultiwordProcessGDBRemote() override = default;
52060b57cec5SDimitry Andric };
52070b57cec5SDimitry Andric 
52080b57cec5SDimitry Andric CommandObject *ProcessGDBRemote::GetPluginCommandObject() {
52090b57cec5SDimitry Andric   if (!m_command_sp)
52100b57cec5SDimitry Andric     m_command_sp = std::make_shared<CommandObjectMultiwordProcessGDBRemote>(
52110b57cec5SDimitry Andric         GetTarget().GetDebugger().GetCommandInterpreter());
52120b57cec5SDimitry Andric   return m_command_sp.get();
52130b57cec5SDimitry Andric }
5214349cc55cSDimitry Andric 
5215349cc55cSDimitry Andric void ProcessGDBRemote::DidForkSwitchSoftwareBreakpoints(bool enable) {
5216349cc55cSDimitry Andric   GetBreakpointSiteList().ForEach([this, enable](BreakpointSite *bp_site) {
5217349cc55cSDimitry Andric     if (bp_site->IsEnabled() &&
5218349cc55cSDimitry Andric         (bp_site->GetType() == BreakpointSite::eSoftware ||
5219349cc55cSDimitry Andric          bp_site->GetType() == BreakpointSite::eExternal)) {
5220349cc55cSDimitry Andric       m_gdb_comm.SendGDBStoppointTypePacket(
5221349cc55cSDimitry Andric           eBreakpointSoftware, enable, bp_site->GetLoadAddress(),
5222349cc55cSDimitry Andric           GetSoftwareBreakpointTrapOpcode(bp_site), GetInterruptTimeout());
5223349cc55cSDimitry Andric     }
5224349cc55cSDimitry Andric   });
5225349cc55cSDimitry Andric }
5226349cc55cSDimitry Andric 
5227349cc55cSDimitry Andric void ProcessGDBRemote::DidForkSwitchHardwareTraps(bool enable) {
5228349cc55cSDimitry Andric   if (m_gdb_comm.SupportsGDBStoppointPacket(eBreakpointHardware)) {
5229349cc55cSDimitry Andric     GetBreakpointSiteList().ForEach([this, enable](BreakpointSite *bp_site) {
5230349cc55cSDimitry Andric       if (bp_site->IsEnabled() &&
5231349cc55cSDimitry Andric           bp_site->GetType() == BreakpointSite::eHardware) {
5232349cc55cSDimitry Andric         m_gdb_comm.SendGDBStoppointTypePacket(
5233349cc55cSDimitry Andric             eBreakpointHardware, enable, bp_site->GetLoadAddress(),
5234349cc55cSDimitry Andric             GetSoftwareBreakpointTrapOpcode(bp_site), GetInterruptTimeout());
5235349cc55cSDimitry Andric       }
5236349cc55cSDimitry Andric     });
5237349cc55cSDimitry Andric   }
5238349cc55cSDimitry Andric 
5239349cc55cSDimitry Andric   WatchpointList &wps = GetTarget().GetWatchpointList();
5240349cc55cSDimitry Andric   size_t wp_count = wps.GetSize();
5241349cc55cSDimitry Andric   for (size_t i = 0; i < wp_count; ++i) {
5242349cc55cSDimitry Andric     WatchpointSP wp = wps.GetByIndex(i);
5243349cc55cSDimitry Andric     if (wp->IsEnabled()) {
5244349cc55cSDimitry Andric       GDBStoppointType type = GetGDBStoppointType(wp.get());
5245349cc55cSDimitry Andric       m_gdb_comm.SendGDBStoppointTypePacket(type, enable, wp->GetLoadAddress(),
5246349cc55cSDimitry Andric                                             wp->GetByteSize(),
5247349cc55cSDimitry Andric                                             GetInterruptTimeout());
5248349cc55cSDimitry Andric     }
5249349cc55cSDimitry Andric   }
5250349cc55cSDimitry Andric }
5251349cc55cSDimitry Andric 
5252349cc55cSDimitry Andric void ProcessGDBRemote::DidFork(lldb::pid_t child_pid, lldb::tid_t child_tid) {
52531fd87a68SDimitry Andric   Log *log = GetLog(GDBRLog::Process);
5254349cc55cSDimitry Andric 
5255349cc55cSDimitry Andric   lldb::pid_t parent_pid = m_gdb_comm.GetCurrentProcessID();
5256349cc55cSDimitry Andric   // Any valid TID will suffice, thread-relevant actions will set a proper TID
5257349cc55cSDimitry Andric   // anyway.
5258349cc55cSDimitry Andric   lldb::tid_t parent_tid = m_thread_ids.front();
5259349cc55cSDimitry Andric 
5260349cc55cSDimitry Andric   lldb::pid_t follow_pid, detach_pid;
5261349cc55cSDimitry Andric   lldb::tid_t follow_tid, detach_tid;
5262349cc55cSDimitry Andric 
5263349cc55cSDimitry Andric   switch (GetFollowForkMode()) {
5264349cc55cSDimitry Andric   case eFollowParent:
5265349cc55cSDimitry Andric     follow_pid = parent_pid;
5266349cc55cSDimitry Andric     follow_tid = parent_tid;
5267349cc55cSDimitry Andric     detach_pid = child_pid;
5268349cc55cSDimitry Andric     detach_tid = child_tid;
5269349cc55cSDimitry Andric     break;
5270349cc55cSDimitry Andric   case eFollowChild:
5271349cc55cSDimitry Andric     follow_pid = child_pid;
5272349cc55cSDimitry Andric     follow_tid = child_tid;
5273349cc55cSDimitry Andric     detach_pid = parent_pid;
5274349cc55cSDimitry Andric     detach_tid = parent_tid;
5275349cc55cSDimitry Andric     break;
5276349cc55cSDimitry Andric   }
5277349cc55cSDimitry Andric 
5278349cc55cSDimitry Andric   // Switch to the process that is going to be detached.
5279349cc55cSDimitry Andric   if (!m_gdb_comm.SetCurrentThread(detach_tid, detach_pid)) {
5280349cc55cSDimitry Andric     LLDB_LOG(log, "ProcessGDBRemote::DidFork() unable to set pid/tid");
5281349cc55cSDimitry Andric     return;
5282349cc55cSDimitry Andric   }
5283349cc55cSDimitry Andric 
5284349cc55cSDimitry Andric   // Disable all software breakpoints in the forked process.
5285349cc55cSDimitry Andric   if (m_gdb_comm.SupportsGDBStoppointPacket(eBreakpointSoftware))
5286349cc55cSDimitry Andric     DidForkSwitchSoftwareBreakpoints(false);
5287349cc55cSDimitry Andric 
5288349cc55cSDimitry Andric   // Remove hardware breakpoints / watchpoints from parent process if we're
5289349cc55cSDimitry Andric   // following child.
5290349cc55cSDimitry Andric   if (GetFollowForkMode() == eFollowChild)
5291349cc55cSDimitry Andric     DidForkSwitchHardwareTraps(false);
5292349cc55cSDimitry Andric 
5293349cc55cSDimitry Andric   // Switch to the process that is going to be followed
5294349cc55cSDimitry Andric   if (!m_gdb_comm.SetCurrentThread(follow_tid, follow_pid) ||
5295349cc55cSDimitry Andric       !m_gdb_comm.SetCurrentThreadForRun(follow_tid, follow_pid)) {
5296349cc55cSDimitry Andric     LLDB_LOG(log, "ProcessGDBRemote::DidFork() unable to reset pid/tid");
5297349cc55cSDimitry Andric     return;
5298349cc55cSDimitry Andric   }
5299349cc55cSDimitry Andric 
5300349cc55cSDimitry Andric   LLDB_LOG(log, "Detaching process {0}", detach_pid);
5301349cc55cSDimitry Andric   Status error = m_gdb_comm.Detach(false, detach_pid);
5302349cc55cSDimitry Andric   if (error.Fail()) {
5303349cc55cSDimitry Andric     LLDB_LOG(log, "ProcessGDBRemote::DidFork() detach packet send failed: {0}",
5304349cc55cSDimitry Andric              error.AsCString() ? error.AsCString() : "<unknown error>");
5305349cc55cSDimitry Andric     return;
5306349cc55cSDimitry Andric   }
5307349cc55cSDimitry Andric 
5308349cc55cSDimitry Andric   // Hardware breakpoints/watchpoints are not inherited implicitly,
5309349cc55cSDimitry Andric   // so we need to readd them if we're following child.
5310349cc55cSDimitry Andric   if (GetFollowForkMode() == eFollowChild)
5311349cc55cSDimitry Andric     DidForkSwitchHardwareTraps(true);
5312349cc55cSDimitry Andric }
5313349cc55cSDimitry Andric 
5314349cc55cSDimitry Andric void ProcessGDBRemote::DidVFork(lldb::pid_t child_pid, lldb::tid_t child_tid) {
53151fd87a68SDimitry Andric   Log *log = GetLog(GDBRLog::Process);
5316349cc55cSDimitry Andric 
5317349cc55cSDimitry Andric   assert(!m_vfork_in_progress);
5318349cc55cSDimitry Andric   m_vfork_in_progress = true;
5319349cc55cSDimitry Andric 
5320349cc55cSDimitry Andric   // Disable all software breakpoints for the duration of vfork.
5321349cc55cSDimitry Andric   if (m_gdb_comm.SupportsGDBStoppointPacket(eBreakpointSoftware))
5322349cc55cSDimitry Andric     DidForkSwitchSoftwareBreakpoints(false);
5323349cc55cSDimitry Andric 
5324349cc55cSDimitry Andric   lldb::pid_t detach_pid;
5325349cc55cSDimitry Andric   lldb::tid_t detach_tid;
5326349cc55cSDimitry Andric 
5327349cc55cSDimitry Andric   switch (GetFollowForkMode()) {
5328349cc55cSDimitry Andric   case eFollowParent:
5329349cc55cSDimitry Andric     detach_pid = child_pid;
5330349cc55cSDimitry Andric     detach_tid = child_tid;
5331349cc55cSDimitry Andric     break;
5332349cc55cSDimitry Andric   case eFollowChild:
5333349cc55cSDimitry Andric     detach_pid = m_gdb_comm.GetCurrentProcessID();
5334349cc55cSDimitry Andric     // Any valid TID will suffice, thread-relevant actions will set a proper TID
5335349cc55cSDimitry Andric     // anyway.
5336349cc55cSDimitry Andric     detach_tid = m_thread_ids.front();
5337349cc55cSDimitry Andric 
5338349cc55cSDimitry Andric     // Switch to the parent process before detaching it.
5339349cc55cSDimitry Andric     if (!m_gdb_comm.SetCurrentThread(detach_tid, detach_pid)) {
5340349cc55cSDimitry Andric       LLDB_LOG(log, "ProcessGDBRemote::DidFork() unable to set pid/tid");
5341349cc55cSDimitry Andric       return;
5342349cc55cSDimitry Andric     }
5343349cc55cSDimitry Andric 
5344349cc55cSDimitry Andric     // Remove hardware breakpoints / watchpoints from the parent process.
5345349cc55cSDimitry Andric     DidForkSwitchHardwareTraps(false);
5346349cc55cSDimitry Andric 
5347349cc55cSDimitry Andric     // Switch to the child process.
5348349cc55cSDimitry Andric     if (!m_gdb_comm.SetCurrentThread(child_tid, child_pid) ||
5349349cc55cSDimitry Andric         !m_gdb_comm.SetCurrentThreadForRun(child_tid, child_pid)) {
5350349cc55cSDimitry Andric       LLDB_LOG(log, "ProcessGDBRemote::DidFork() unable to reset pid/tid");
5351349cc55cSDimitry Andric       return;
5352349cc55cSDimitry Andric     }
5353349cc55cSDimitry Andric     break;
5354349cc55cSDimitry Andric   }
5355349cc55cSDimitry Andric 
5356349cc55cSDimitry Andric   LLDB_LOG(log, "Detaching process {0}", detach_pid);
5357349cc55cSDimitry Andric   Status error = m_gdb_comm.Detach(false, detach_pid);
5358349cc55cSDimitry Andric   if (error.Fail()) {
5359349cc55cSDimitry Andric       LLDB_LOG(log,
5360349cc55cSDimitry Andric                "ProcessGDBRemote::DidFork() detach packet send failed: {0}",
5361349cc55cSDimitry Andric                 error.AsCString() ? error.AsCString() : "<unknown error>");
5362349cc55cSDimitry Andric       return;
5363349cc55cSDimitry Andric   }
5364349cc55cSDimitry Andric }
5365349cc55cSDimitry Andric 
5366349cc55cSDimitry Andric void ProcessGDBRemote::DidVForkDone() {
5367349cc55cSDimitry Andric   assert(m_vfork_in_progress);
5368349cc55cSDimitry Andric   m_vfork_in_progress = false;
5369349cc55cSDimitry Andric 
5370349cc55cSDimitry Andric   // Reenable all software breakpoints that were enabled before vfork.
5371349cc55cSDimitry Andric   if (m_gdb_comm.SupportsGDBStoppointPacket(eBreakpointSoftware))
5372349cc55cSDimitry Andric     DidForkSwitchSoftwareBreakpoints(true);
5373349cc55cSDimitry Andric }
5374349cc55cSDimitry Andric 
5375349cc55cSDimitry Andric void ProcessGDBRemote::DidExec() {
5376349cc55cSDimitry Andric   // If we are following children, vfork is finished by exec (rather than
5377349cc55cSDimitry Andric   // vforkdone that is submitted for parent).
5378349cc55cSDimitry Andric   if (GetFollowForkMode() == eFollowChild)
5379349cc55cSDimitry Andric     m_vfork_in_progress = false;
5380349cc55cSDimitry Andric   Process::DidExec();
5381349cc55cSDimitry Andric }
5382