xref: /freebsd-src/contrib/llvm-project/lldb/source/Plugins/Process/gdb-remote/ProcessGDBRemote.cpp (revision 4824e7fd18a1223177218d4aec1b3c6c5c4a444e)
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 <algorithm>
270b57cec5SDimitry Andric #include <csignal>
280b57cec5SDimitry Andric #include <map>
290b57cec5SDimitry Andric #include <memory>
300b57cec5SDimitry Andric #include <mutex>
310b57cec5SDimitry Andric #include <sstream>
320b57cec5SDimitry Andric 
330b57cec5SDimitry Andric #include "lldb/Breakpoint/Watchpoint.h"
340b57cec5SDimitry Andric #include "lldb/Core/Debugger.h"
350b57cec5SDimitry Andric #include "lldb/Core/Module.h"
360b57cec5SDimitry Andric #include "lldb/Core/ModuleSpec.h"
370b57cec5SDimitry Andric #include "lldb/Core/PluginManager.h"
380b57cec5SDimitry Andric #include "lldb/Core/StreamFile.h"
390b57cec5SDimitry Andric #include "lldb/Core/Value.h"
400b57cec5SDimitry Andric #include "lldb/DataFormatters/FormatManager.h"
410b57cec5SDimitry Andric #include "lldb/Host/ConnectionFileDescriptor.h"
420b57cec5SDimitry Andric #include "lldb/Host/FileSystem.h"
430b57cec5SDimitry Andric #include "lldb/Host/HostThread.h"
440b57cec5SDimitry Andric #include "lldb/Host/PosixApi.h"
450b57cec5SDimitry Andric #include "lldb/Host/PseudoTerminal.h"
460b57cec5SDimitry Andric #include "lldb/Host/ThreadLauncher.h"
470b57cec5SDimitry Andric #include "lldb/Host/XML.h"
480b57cec5SDimitry Andric #include "lldb/Interpreter/CommandInterpreter.h"
490b57cec5SDimitry Andric #include "lldb/Interpreter/CommandObject.h"
500b57cec5SDimitry Andric #include "lldb/Interpreter/CommandObjectMultiword.h"
510b57cec5SDimitry Andric #include "lldb/Interpreter/CommandReturnObject.h"
520b57cec5SDimitry Andric #include "lldb/Interpreter/OptionArgParser.h"
530b57cec5SDimitry Andric #include "lldb/Interpreter/OptionGroupBoolean.h"
540b57cec5SDimitry Andric #include "lldb/Interpreter/OptionGroupUInt64.h"
550b57cec5SDimitry Andric #include "lldb/Interpreter/OptionValueProperties.h"
560b57cec5SDimitry Andric #include "lldb/Interpreter/Options.h"
570b57cec5SDimitry Andric #include "lldb/Interpreter/Property.h"
580b57cec5SDimitry Andric #include "lldb/Symbol/LocateSymbolFile.h"
590b57cec5SDimitry Andric #include "lldb/Symbol/ObjectFile.h"
600b57cec5SDimitry Andric #include "lldb/Target/ABI.h"
610b57cec5SDimitry Andric #include "lldb/Target/DynamicLoader.h"
620b57cec5SDimitry Andric #include "lldb/Target/MemoryRegionInfo.h"
630b57cec5SDimitry Andric #include "lldb/Target/SystemRuntime.h"
640b57cec5SDimitry Andric #include "lldb/Target/Target.h"
650b57cec5SDimitry Andric #include "lldb/Target/TargetList.h"
660b57cec5SDimitry Andric #include "lldb/Target/ThreadPlanCallFunction.h"
670b57cec5SDimitry Andric #include "lldb/Utility/Args.h"
680b57cec5SDimitry Andric #include "lldb/Utility/FileSpec.h"
690b57cec5SDimitry Andric #include "lldb/Utility/Reproducer.h"
700b57cec5SDimitry Andric #include "lldb/Utility/State.h"
710b57cec5SDimitry Andric #include "lldb/Utility/StreamString.h"
720b57cec5SDimitry Andric #include "lldb/Utility/Timer.h"
730b57cec5SDimitry Andric 
740b57cec5SDimitry Andric #include "GDBRemoteRegisterContext.h"
75580012d6SDimitry Andric #ifdef LLDB_ENABLE_ALL
760b57cec5SDimitry Andric #include "Plugins/Platform/MacOSX/PlatformRemoteiOS.h"
77580012d6SDimitry Andric #endif // LLDB_ENABLE_ALL
780b57cec5SDimitry Andric #include "Plugins/Process/Utility/GDBRemoteSignals.h"
790b57cec5SDimitry Andric #include "Plugins/Process/Utility/InferiorCallPOSIX.h"
800b57cec5SDimitry Andric #include "Plugins/Process/Utility/StopInfoMachException.h"
810b57cec5SDimitry Andric #include "ProcessGDBRemote.h"
820b57cec5SDimitry Andric #include "ProcessGDBRemoteLog.h"
830b57cec5SDimitry Andric #include "ThreadGDBRemote.h"
840b57cec5SDimitry Andric #include "lldb/Host/Host.h"
850b57cec5SDimitry Andric #include "lldb/Utility/StringExtractorGDBRemote.h"
860b57cec5SDimitry Andric 
879dba64beSDimitry Andric #include "llvm/ADT/ScopeExit.h"
880b57cec5SDimitry Andric #include "llvm/ADT/StringSwitch.h"
890b57cec5SDimitry Andric #include "llvm/Support/Threading.h"
900b57cec5SDimitry Andric #include "llvm/Support/raw_ostream.h"
910b57cec5SDimitry Andric 
920b57cec5SDimitry Andric #define DEBUGSERVER_BASENAME "debugserver"
930b57cec5SDimitry Andric using namespace lldb;
940b57cec5SDimitry Andric using namespace lldb_private;
950b57cec5SDimitry Andric using namespace lldb_private::process_gdb_remote;
960b57cec5SDimitry Andric 
975ffd83dbSDimitry Andric LLDB_PLUGIN_DEFINE(ProcessGDBRemote)
985ffd83dbSDimitry Andric 
990b57cec5SDimitry Andric namespace lldb {
1000b57cec5SDimitry Andric // Provide a function that can easily dump the packet history if we know a
1010b57cec5SDimitry Andric // ProcessGDBRemote * value (which we can get from logs or from debugging). We
1020b57cec5SDimitry Andric // need the function in the lldb namespace so it makes it into the final
1030b57cec5SDimitry Andric // executable since the LLDB shared library only exports stuff in the lldb
1040b57cec5SDimitry Andric // namespace. This allows you to attach with a debugger and call this function
1050b57cec5SDimitry Andric // and get the packet history dumped to a file.
1060b57cec5SDimitry Andric void DumpProcessGDBRemotePacketHistory(void *p, const char *path) {
1079dba64beSDimitry Andric   auto file = FileSystem::Instance().Open(
108349cc55cSDimitry Andric       FileSpec(path), File::eOpenOptionWriteOnly | File::eOpenOptionCanCreate);
1099dba64beSDimitry Andric   if (!file) {
1109dba64beSDimitry Andric     llvm::consumeError(file.takeError());
1119dba64beSDimitry Andric     return;
1129dba64beSDimitry Andric   }
1139dba64beSDimitry Andric   StreamFile stream(std::move(file.get()));
1149dba64beSDimitry Andric   ((ProcessGDBRemote *)p)->GetGDBRemote().DumpHistory(stream);
1150b57cec5SDimitry Andric }
1160b57cec5SDimitry Andric } // namespace lldb
1170b57cec5SDimitry Andric 
1180b57cec5SDimitry Andric namespace {
1190b57cec5SDimitry Andric 
1209dba64beSDimitry Andric #define LLDB_PROPERTIES_processgdbremote
1219dba64beSDimitry Andric #include "ProcessGDBRemoteProperties.inc"
1220b57cec5SDimitry Andric 
1230b57cec5SDimitry Andric enum {
1249dba64beSDimitry Andric #define LLDB_PROPERTIES_processgdbremote
1259dba64beSDimitry Andric #include "ProcessGDBRemotePropertiesEnum.inc"
1260b57cec5SDimitry Andric };
1270b57cec5SDimitry Andric 
1280b57cec5SDimitry Andric class PluginProperties : public Properties {
1290b57cec5SDimitry Andric public:
1300b57cec5SDimitry Andric   static ConstString GetSettingName() {
131349cc55cSDimitry Andric     return ConstString(ProcessGDBRemote::GetPluginNameStatic());
1320b57cec5SDimitry Andric   }
1330b57cec5SDimitry Andric 
1340b57cec5SDimitry Andric   PluginProperties() : Properties() {
1350b57cec5SDimitry Andric     m_collection_sp = std::make_shared<OptionValueProperties>(GetSettingName());
1369dba64beSDimitry Andric     m_collection_sp->Initialize(g_processgdbremote_properties);
1370b57cec5SDimitry Andric   }
1380b57cec5SDimitry Andric 
139fe6060f1SDimitry Andric   ~PluginProperties() override = default;
1400b57cec5SDimitry Andric 
1410b57cec5SDimitry Andric   uint64_t GetPacketTimeout() {
1420b57cec5SDimitry Andric     const uint32_t idx = ePropertyPacketTimeout;
1430b57cec5SDimitry Andric     return m_collection_sp->GetPropertyAtIndexAsUInt64(
1449dba64beSDimitry Andric         nullptr, idx, g_processgdbremote_properties[idx].default_uint_value);
1450b57cec5SDimitry Andric   }
1460b57cec5SDimitry Andric 
1470b57cec5SDimitry Andric   bool SetPacketTimeout(uint64_t timeout) {
1480b57cec5SDimitry Andric     const uint32_t idx = ePropertyPacketTimeout;
1490b57cec5SDimitry Andric     return m_collection_sp->SetPropertyAtIndexAsUInt64(nullptr, idx, timeout);
1500b57cec5SDimitry Andric   }
1510b57cec5SDimitry Andric 
1520b57cec5SDimitry Andric   FileSpec GetTargetDefinitionFile() const {
1530b57cec5SDimitry Andric     const uint32_t idx = ePropertyTargetDefinitionFile;
1540b57cec5SDimitry Andric     return m_collection_sp->GetPropertyAtIndexAsFileSpec(nullptr, idx);
1550b57cec5SDimitry Andric   }
1560b57cec5SDimitry Andric 
1570b57cec5SDimitry Andric   bool GetUseSVR4() const {
1580b57cec5SDimitry Andric     const uint32_t idx = ePropertyUseSVR4;
1590b57cec5SDimitry Andric     return m_collection_sp->GetPropertyAtIndexAsBoolean(
1609dba64beSDimitry Andric         nullptr, idx,
1619dba64beSDimitry Andric         g_processgdbremote_properties[idx].default_uint_value != 0);
1620b57cec5SDimitry Andric   }
163480093f4SDimitry Andric 
164480093f4SDimitry Andric   bool GetUseGPacketForReading() const {
165480093f4SDimitry Andric     const uint32_t idx = ePropertyUseGPacketForReading;
166480093f4SDimitry Andric     return m_collection_sp->GetPropertyAtIndexAsBoolean(nullptr, idx, true);
167480093f4SDimitry Andric   }
1680b57cec5SDimitry Andric };
1690b57cec5SDimitry Andric 
170349cc55cSDimitry Andric static PluginProperties &GetGlobalPluginProperties() {
171349cc55cSDimitry Andric   static PluginProperties g_settings;
172349cc55cSDimitry Andric   return g_settings;
1730b57cec5SDimitry Andric }
1740b57cec5SDimitry Andric 
1750b57cec5SDimitry Andric } // namespace
1760b57cec5SDimitry Andric 
1770b57cec5SDimitry Andric // TODO Randomly assigning a port is unsafe.  We should get an unused
1780b57cec5SDimitry Andric // ephemeral port from the kernel and make sure we reserve it before passing it
1790b57cec5SDimitry Andric // to debugserver.
1800b57cec5SDimitry Andric 
1810b57cec5SDimitry Andric #if defined(__APPLE__)
1820b57cec5SDimitry Andric #define LOW_PORT (IPPORT_RESERVED)
1830b57cec5SDimitry Andric #define HIGH_PORT (IPPORT_HIFIRSTAUTO)
1840b57cec5SDimitry Andric #else
1850b57cec5SDimitry Andric #define LOW_PORT (1024u)
1860b57cec5SDimitry Andric #define HIGH_PORT (49151u)
1870b57cec5SDimitry Andric #endif
1880b57cec5SDimitry Andric 
189349cc55cSDimitry Andric llvm::StringRef ProcessGDBRemote::GetPluginDescriptionStatic() {
1900b57cec5SDimitry Andric   return "GDB Remote protocol based debugging plug-in.";
1910b57cec5SDimitry Andric }
1920b57cec5SDimitry Andric 
1930b57cec5SDimitry Andric void ProcessGDBRemote::Terminate() {
1940b57cec5SDimitry Andric   PluginManager::UnregisterPlugin(ProcessGDBRemote::CreateInstance);
1950b57cec5SDimitry Andric }
1960b57cec5SDimitry Andric 
1970b57cec5SDimitry Andric lldb::ProcessSP
1980b57cec5SDimitry Andric ProcessGDBRemote::CreateInstance(lldb::TargetSP target_sp,
1990b57cec5SDimitry Andric                                  ListenerSP listener_sp,
200e8d8bef9SDimitry Andric                                  const FileSpec *crash_file_path,
201e8d8bef9SDimitry Andric                                  bool can_connect) {
2020b57cec5SDimitry Andric   lldb::ProcessSP process_sp;
2030b57cec5SDimitry Andric   if (crash_file_path == nullptr)
2040b57cec5SDimitry Andric     process_sp = std::make_shared<ProcessGDBRemote>(target_sp, listener_sp);
2050b57cec5SDimitry Andric   return process_sp;
2060b57cec5SDimitry Andric }
2070b57cec5SDimitry Andric 
208fe6060f1SDimitry Andric std::chrono::seconds ProcessGDBRemote::GetPacketTimeout() {
209349cc55cSDimitry Andric   return std::chrono::seconds(GetGlobalPluginProperties().GetPacketTimeout());
210fe6060f1SDimitry Andric }
211fe6060f1SDimitry Andric 
2120b57cec5SDimitry Andric bool ProcessGDBRemote::CanDebug(lldb::TargetSP target_sp,
2130b57cec5SDimitry Andric                                 bool plugin_specified_by_name) {
2140b57cec5SDimitry Andric   if (plugin_specified_by_name)
2150b57cec5SDimitry Andric     return true;
2160b57cec5SDimitry Andric 
2170b57cec5SDimitry Andric   // For now we are just making sure the file exists for a given module
2180b57cec5SDimitry Andric   Module *exe_module = target_sp->GetExecutableModulePointer();
2190b57cec5SDimitry Andric   if (exe_module) {
2200b57cec5SDimitry Andric     ObjectFile *exe_objfile = exe_module->GetObjectFile();
2210b57cec5SDimitry Andric     // We can't debug core files...
2220b57cec5SDimitry Andric     switch (exe_objfile->GetType()) {
2230b57cec5SDimitry Andric     case ObjectFile::eTypeInvalid:
2240b57cec5SDimitry Andric     case ObjectFile::eTypeCoreFile:
2250b57cec5SDimitry Andric     case ObjectFile::eTypeDebugInfo:
2260b57cec5SDimitry Andric     case ObjectFile::eTypeObjectFile:
2270b57cec5SDimitry Andric     case ObjectFile::eTypeSharedLibrary:
2280b57cec5SDimitry Andric     case ObjectFile::eTypeStubLibrary:
2290b57cec5SDimitry Andric     case ObjectFile::eTypeJIT:
2300b57cec5SDimitry Andric       return false;
2310b57cec5SDimitry Andric     case ObjectFile::eTypeExecutable:
2320b57cec5SDimitry Andric     case ObjectFile::eTypeDynamicLinker:
2330b57cec5SDimitry Andric     case ObjectFile::eTypeUnknown:
2340b57cec5SDimitry Andric       break;
2350b57cec5SDimitry Andric     }
2360b57cec5SDimitry Andric     return FileSystem::Instance().Exists(exe_module->GetFileSpec());
2370b57cec5SDimitry Andric   }
2380b57cec5SDimitry Andric   // However, if there is no executable module, we return true since we might
2390b57cec5SDimitry Andric   // be preparing to attach.
2400b57cec5SDimitry Andric   return true;
2410b57cec5SDimitry Andric }
2420b57cec5SDimitry Andric 
2430b57cec5SDimitry Andric // ProcessGDBRemote constructor
2440b57cec5SDimitry Andric ProcessGDBRemote::ProcessGDBRemote(lldb::TargetSP target_sp,
2450b57cec5SDimitry Andric                                    ListenerSP listener_sp)
2460b57cec5SDimitry Andric     : Process(target_sp, listener_sp),
247349cc55cSDimitry Andric       m_debugserver_pid(LLDB_INVALID_PROCESS_ID), m_register_info_sp(nullptr),
2480b57cec5SDimitry Andric       m_async_broadcaster(nullptr, "lldb.process.gdb-remote.async-broadcaster"),
2490b57cec5SDimitry Andric       m_async_listener_sp(
2500b57cec5SDimitry Andric           Listener::MakeListener("lldb.process.gdb-remote.async-listener")),
2510b57cec5SDimitry Andric       m_async_thread_state_mutex(), m_thread_ids(), m_thread_pcs(),
2520b57cec5SDimitry Andric       m_jstopinfo_sp(), m_jthreadsinfo_sp(), m_continue_c_tids(),
2530b57cec5SDimitry Andric       m_continue_C_tids(), m_continue_s_tids(), m_continue_S_tids(),
2540b57cec5SDimitry Andric       m_max_memory_size(0), m_remote_stub_max_memory_size(0),
2550b57cec5SDimitry Andric       m_addr_to_mmap_size(), m_thread_create_bp_sp(),
2560b57cec5SDimitry Andric       m_waiting_for_attach(false), m_destroy_tried_resuming(false),
2570b57cec5SDimitry Andric       m_command_sp(), m_breakpoint_pc_offset(0),
2580b57cec5SDimitry Andric       m_initial_tid(LLDB_INVALID_THREAD_ID), m_replay_mode(false),
259349cc55cSDimitry Andric       m_allow_flash_writes(false), m_erased_flash_ranges(),
260349cc55cSDimitry Andric       m_vfork_in_progress(false) {
2610b57cec5SDimitry Andric   m_async_broadcaster.SetEventName(eBroadcastBitAsyncThreadShouldExit,
2620b57cec5SDimitry Andric                                    "async thread should exit");
2630b57cec5SDimitry Andric   m_async_broadcaster.SetEventName(eBroadcastBitAsyncContinue,
2640b57cec5SDimitry Andric                                    "async thread continue");
2650b57cec5SDimitry Andric   m_async_broadcaster.SetEventName(eBroadcastBitAsyncThreadDidExit,
2660b57cec5SDimitry Andric                                    "async thread did exit");
2670b57cec5SDimitry Andric 
2680b57cec5SDimitry Andric   if (repro::Generator *g = repro::Reproducer::Instance().GetGenerator()) {
269480093f4SDimitry Andric     repro::GDBRemoteProvider &provider =
270480093f4SDimitry Andric         g->GetOrCreate<repro::GDBRemoteProvider>();
271480093f4SDimitry Andric     m_gdb_comm.SetPacketRecorder(provider.GetNewPacketRecorder());
2720b57cec5SDimitry Andric   }
2730b57cec5SDimitry Andric 
2740b57cec5SDimitry Andric   Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_ASYNC));
2750b57cec5SDimitry Andric 
2760b57cec5SDimitry Andric   const uint32_t async_event_mask =
2770b57cec5SDimitry Andric       eBroadcastBitAsyncContinue | eBroadcastBitAsyncThreadShouldExit;
2780b57cec5SDimitry Andric 
2790b57cec5SDimitry Andric   if (m_async_listener_sp->StartListeningForEvents(
2800b57cec5SDimitry Andric           &m_async_broadcaster, async_event_mask) != async_event_mask) {
2819dba64beSDimitry Andric     LLDB_LOGF(log,
2829dba64beSDimitry Andric               "ProcessGDBRemote::%s failed to listen for "
2830b57cec5SDimitry Andric               "m_async_broadcaster events",
2840b57cec5SDimitry Andric               __FUNCTION__);
2850b57cec5SDimitry Andric   }
2860b57cec5SDimitry Andric 
287*4824e7fdSDimitry Andric   const uint32_t gdb_event_mask = Communication::eBroadcastBitReadThreadDidExit;
2880b57cec5SDimitry Andric   if (m_async_listener_sp->StartListeningForEvents(
2890b57cec5SDimitry Andric           &m_gdb_comm, gdb_event_mask) != gdb_event_mask) {
2909dba64beSDimitry Andric     LLDB_LOGF(log,
2919dba64beSDimitry Andric               "ProcessGDBRemote::%s failed to listen for m_gdb_comm events",
2920b57cec5SDimitry Andric               __FUNCTION__);
2930b57cec5SDimitry Andric   }
2940b57cec5SDimitry Andric 
2950b57cec5SDimitry Andric   const uint64_t timeout_seconds =
296349cc55cSDimitry Andric       GetGlobalPluginProperties().GetPacketTimeout();
2970b57cec5SDimitry Andric   if (timeout_seconds > 0)
2980b57cec5SDimitry Andric     m_gdb_comm.SetPacketTimeout(std::chrono::seconds(timeout_seconds));
299480093f4SDimitry Andric 
300480093f4SDimitry Andric   m_use_g_packet_for_reading =
301349cc55cSDimitry Andric       GetGlobalPluginProperties().GetUseGPacketForReading();
3020b57cec5SDimitry Andric }
3030b57cec5SDimitry Andric 
3040b57cec5SDimitry Andric // Destructor
3050b57cec5SDimitry Andric ProcessGDBRemote::~ProcessGDBRemote() {
3060b57cec5SDimitry Andric   //  m_mach_process.UnregisterNotificationCallbacks (this);
3070b57cec5SDimitry Andric   Clear();
3080b57cec5SDimitry Andric   // We need to call finalize on the process before destroying ourselves to
3090b57cec5SDimitry Andric   // make sure all of the broadcaster cleanup goes as planned. If we destruct
3100b57cec5SDimitry Andric   // this class, then Process::~Process() might have problems trying to fully
3110b57cec5SDimitry Andric   // destroy the broadcaster.
3120b57cec5SDimitry Andric   Finalize();
3130b57cec5SDimitry Andric 
3140b57cec5SDimitry Andric   // The general Finalize is going to try to destroy the process and that
3150b57cec5SDimitry Andric   // SHOULD shut down the async thread.  However, if we don't kill it it will
3160b57cec5SDimitry Andric   // get stranded and its connection will go away so when it wakes up it will
3170b57cec5SDimitry Andric   // crash.  So kill it for sure here.
3180b57cec5SDimitry Andric   StopAsyncThread();
3190b57cec5SDimitry Andric   KillDebugserverProcess();
3200b57cec5SDimitry Andric }
3210b57cec5SDimitry Andric 
3220b57cec5SDimitry Andric bool ProcessGDBRemote::ParsePythonTargetDefinition(
3230b57cec5SDimitry Andric     const FileSpec &target_definition_fspec) {
3240b57cec5SDimitry Andric   ScriptInterpreter *interpreter =
3250b57cec5SDimitry Andric       GetTarget().GetDebugger().GetScriptInterpreter();
3260b57cec5SDimitry Andric   Status error;
3270b57cec5SDimitry Andric   StructuredData::ObjectSP module_object_sp(
3280b57cec5SDimitry Andric       interpreter->LoadPluginModule(target_definition_fspec, error));
3290b57cec5SDimitry Andric   if (module_object_sp) {
3300b57cec5SDimitry Andric     StructuredData::DictionarySP target_definition_sp(
3310b57cec5SDimitry Andric         interpreter->GetDynamicSettings(module_object_sp, &GetTarget(),
3320b57cec5SDimitry Andric                                         "gdb-server-target-definition", error));
3330b57cec5SDimitry Andric 
3340b57cec5SDimitry Andric     if (target_definition_sp) {
3350b57cec5SDimitry Andric       StructuredData::ObjectSP target_object(
3360b57cec5SDimitry Andric           target_definition_sp->GetValueForKey("host-info"));
3370b57cec5SDimitry Andric       if (target_object) {
3380b57cec5SDimitry Andric         if (auto host_info_dict = target_object->GetAsDictionary()) {
3390b57cec5SDimitry Andric           StructuredData::ObjectSP triple_value =
3400b57cec5SDimitry Andric               host_info_dict->GetValueForKey("triple");
3410b57cec5SDimitry Andric           if (auto triple_string_value = triple_value->GetAsString()) {
3425ffd83dbSDimitry Andric             std::string triple_string =
3435ffd83dbSDimitry Andric                 std::string(triple_string_value->GetValue());
3440b57cec5SDimitry Andric             ArchSpec host_arch(triple_string.c_str());
3450b57cec5SDimitry Andric             if (!host_arch.IsCompatibleMatch(GetTarget().GetArchitecture())) {
3460b57cec5SDimitry Andric               GetTarget().SetArchitecture(host_arch);
3470b57cec5SDimitry Andric             }
3480b57cec5SDimitry Andric           }
3490b57cec5SDimitry Andric         }
3500b57cec5SDimitry Andric       }
3510b57cec5SDimitry Andric       m_breakpoint_pc_offset = 0;
3520b57cec5SDimitry Andric       StructuredData::ObjectSP breakpoint_pc_offset_value =
3530b57cec5SDimitry Andric           target_definition_sp->GetValueForKey("breakpoint-pc-offset");
3540b57cec5SDimitry Andric       if (breakpoint_pc_offset_value) {
3550b57cec5SDimitry Andric         if (auto breakpoint_pc_int_value =
3560b57cec5SDimitry Andric                 breakpoint_pc_offset_value->GetAsInteger())
3570b57cec5SDimitry Andric           m_breakpoint_pc_offset = breakpoint_pc_int_value->GetValue();
3580b57cec5SDimitry Andric       }
3590b57cec5SDimitry Andric 
360e8d8bef9SDimitry Andric       if (m_register_info_sp->SetRegisterInfo(
361e8d8bef9SDimitry Andric               *target_definition_sp, GetTarget().GetArchitecture()) > 0) {
3620b57cec5SDimitry Andric         return true;
3630b57cec5SDimitry Andric       }
3640b57cec5SDimitry Andric     }
3650b57cec5SDimitry Andric   }
3660b57cec5SDimitry Andric   return false;
3670b57cec5SDimitry Andric }
3680b57cec5SDimitry Andric 
3690b57cec5SDimitry Andric static size_t SplitCommaSeparatedRegisterNumberString(
370349cc55cSDimitry Andric     const llvm::StringRef &comma_separated_register_numbers,
3710b57cec5SDimitry Andric     std::vector<uint32_t> &regnums, int base) {
3720b57cec5SDimitry Andric   regnums.clear();
373349cc55cSDimitry Andric   for (llvm::StringRef x : llvm::split(comma_separated_register_numbers, ',')) {
374349cc55cSDimitry Andric     uint32_t reg;
375349cc55cSDimitry Andric     if (llvm::to_integer(x, reg, base))
3760b57cec5SDimitry Andric       regnums.push_back(reg);
3770b57cec5SDimitry Andric   }
3780b57cec5SDimitry Andric   return regnums.size();
3790b57cec5SDimitry Andric }
3800b57cec5SDimitry Andric 
3810b57cec5SDimitry Andric void ProcessGDBRemote::BuildDynamicRegisterInfo(bool force) {
382e8d8bef9SDimitry Andric   if (!force && m_register_info_sp)
3830b57cec5SDimitry Andric     return;
3840b57cec5SDimitry Andric 
385e8d8bef9SDimitry Andric   m_register_info_sp = std::make_shared<GDBRemoteDynamicRegisterInfo>();
3860b57cec5SDimitry Andric 
3870b57cec5SDimitry Andric   // Check if qHostInfo specified a specific packet timeout for this
3880b57cec5SDimitry Andric   // connection. If so then lets update our setting so the user knows what the
3890b57cec5SDimitry Andric   // timeout is and can see it.
3900b57cec5SDimitry Andric   const auto host_packet_timeout = m_gdb_comm.GetHostDefaultPacketTimeout();
3910b57cec5SDimitry Andric   if (host_packet_timeout > std::chrono::seconds(0)) {
392349cc55cSDimitry Andric     GetGlobalPluginProperties().SetPacketTimeout(host_packet_timeout.count());
3930b57cec5SDimitry Andric   }
3940b57cec5SDimitry Andric 
3950b57cec5SDimitry Andric   // Register info search order:
3960b57cec5SDimitry Andric   //     1 - Use the target definition python file if one is specified.
3970b57cec5SDimitry Andric   //     2 - If the target definition doesn't have any of the info from the
3980b57cec5SDimitry Andric   //     target.xml (registers) then proceed to read the target.xml.
3990b57cec5SDimitry Andric   //     3 - Fall back on the qRegisterInfo packets.
4000b57cec5SDimitry Andric 
4010b57cec5SDimitry Andric   FileSpec target_definition_fspec =
402349cc55cSDimitry Andric       GetGlobalPluginProperties().GetTargetDefinitionFile();
4030b57cec5SDimitry Andric   if (!FileSystem::Instance().Exists(target_definition_fspec)) {
4040b57cec5SDimitry Andric     // If the filename doesn't exist, it may be a ~ not having been expanded -
4050b57cec5SDimitry Andric     // try to resolve it.
4060b57cec5SDimitry Andric     FileSystem::Instance().Resolve(target_definition_fspec);
4070b57cec5SDimitry Andric   }
4080b57cec5SDimitry Andric   if (target_definition_fspec) {
4090b57cec5SDimitry Andric     // See if we can get register definitions from a python file
4100b57cec5SDimitry Andric     if (ParsePythonTargetDefinition(target_definition_fspec)) {
4110b57cec5SDimitry Andric       return;
4120b57cec5SDimitry Andric     } else {
4130b57cec5SDimitry Andric       StreamSP stream_sp = GetTarget().GetDebugger().GetAsyncOutputStream();
4140b57cec5SDimitry Andric       stream_sp->Printf("ERROR: target description file %s failed to parse.\n",
4150b57cec5SDimitry Andric                         target_definition_fspec.GetPath().c_str());
4160b57cec5SDimitry Andric     }
4170b57cec5SDimitry Andric   }
4180b57cec5SDimitry Andric 
4190b57cec5SDimitry Andric   const ArchSpec &target_arch = GetTarget().GetArchitecture();
4200b57cec5SDimitry Andric   const ArchSpec &remote_host_arch = m_gdb_comm.GetHostArchitecture();
4210b57cec5SDimitry Andric   const ArchSpec &remote_process_arch = m_gdb_comm.GetProcessArchitecture();
4220b57cec5SDimitry Andric 
4230b57cec5SDimitry Andric   // Use the process' architecture instead of the host arch, if available
4240b57cec5SDimitry Andric   ArchSpec arch_to_use;
4250b57cec5SDimitry Andric   if (remote_process_arch.IsValid())
4260b57cec5SDimitry Andric     arch_to_use = remote_process_arch;
4270b57cec5SDimitry Andric   else
4280b57cec5SDimitry Andric     arch_to_use = remote_host_arch;
4290b57cec5SDimitry Andric 
4300b57cec5SDimitry Andric   if (!arch_to_use.IsValid())
4310b57cec5SDimitry Andric     arch_to_use = target_arch;
4320b57cec5SDimitry Andric 
4330b57cec5SDimitry Andric   if (GetGDBServerRegisterInfo(arch_to_use))
4340b57cec5SDimitry Andric     return;
4350b57cec5SDimitry Andric 
4360b57cec5SDimitry Andric   char packet[128];
437349cc55cSDimitry Andric   std::vector<DynamicRegisterInfo::Register> registers;
4380b57cec5SDimitry Andric   uint32_t reg_num = 0;
4390b57cec5SDimitry Andric   for (StringExtractorGDBRemote::ResponseType response_type =
4400b57cec5SDimitry Andric            StringExtractorGDBRemote::eResponse;
4410b57cec5SDimitry Andric        response_type == StringExtractorGDBRemote::eResponse; ++reg_num) {
4420b57cec5SDimitry Andric     const int packet_len =
4430b57cec5SDimitry Andric         ::snprintf(packet, sizeof(packet), "qRegisterInfo%x", reg_num);
4440b57cec5SDimitry Andric     assert(packet_len < (int)sizeof(packet));
4450b57cec5SDimitry Andric     UNUSED_IF_ASSERT_DISABLED(packet_len);
4460b57cec5SDimitry Andric     StringExtractorGDBRemote response;
447fe6060f1SDimitry Andric     if (m_gdb_comm.SendPacketAndWaitForResponse(packet, response) ==
4480b57cec5SDimitry Andric         GDBRemoteCommunication::PacketResult::Success) {
4490b57cec5SDimitry Andric       response_type = response.GetResponseType();
4500b57cec5SDimitry Andric       if (response_type == StringExtractorGDBRemote::eResponse) {
4510b57cec5SDimitry Andric         llvm::StringRef name;
4520b57cec5SDimitry Andric         llvm::StringRef value;
453349cc55cSDimitry Andric         DynamicRegisterInfo::Register reg_info;
4540b57cec5SDimitry Andric 
4550b57cec5SDimitry Andric         while (response.GetNameColonValue(name, value)) {
4560b57cec5SDimitry Andric           if (name.equals("name")) {
457349cc55cSDimitry Andric             reg_info.name.SetString(value);
4580b57cec5SDimitry Andric           } else if (name.equals("alt-name")) {
459349cc55cSDimitry Andric             reg_info.alt_name.SetString(value);
4600b57cec5SDimitry Andric           } else if (name.equals("bitsize")) {
461349cc55cSDimitry Andric             if (!value.getAsInteger(0, reg_info.byte_size))
4620b57cec5SDimitry Andric               reg_info.byte_size /= CHAR_BIT;
4630b57cec5SDimitry Andric           } else if (name.equals("offset")) {
464349cc55cSDimitry Andric             value.getAsInteger(0, reg_info.byte_offset);
4650b57cec5SDimitry Andric           } else if (name.equals("encoding")) {
4660b57cec5SDimitry Andric             const Encoding encoding = Args::StringToEncoding(value);
4670b57cec5SDimitry Andric             if (encoding != eEncodingInvalid)
4680b57cec5SDimitry Andric               reg_info.encoding = encoding;
4690b57cec5SDimitry Andric           } else if (name.equals("format")) {
470349cc55cSDimitry Andric             if (!OptionArgParser::ToFormat(value.str().c_str(), reg_info.format, nullptr)
4710b57cec5SDimitry Andric                     .Success())
4720b57cec5SDimitry Andric               reg_info.format =
4730b57cec5SDimitry Andric                   llvm::StringSwitch<Format>(value)
4740b57cec5SDimitry Andric                       .Case("binary", eFormatBinary)
4750b57cec5SDimitry Andric                       .Case("decimal", eFormatDecimal)
4760b57cec5SDimitry Andric                       .Case("hex", eFormatHex)
4770b57cec5SDimitry Andric                       .Case("float", eFormatFloat)
4780b57cec5SDimitry Andric                       .Case("vector-sint8", eFormatVectorOfSInt8)
4790b57cec5SDimitry Andric                       .Case("vector-uint8", eFormatVectorOfUInt8)
4800b57cec5SDimitry Andric                       .Case("vector-sint16", eFormatVectorOfSInt16)
4810b57cec5SDimitry Andric                       .Case("vector-uint16", eFormatVectorOfUInt16)
4820b57cec5SDimitry Andric                       .Case("vector-sint32", eFormatVectorOfSInt32)
4830b57cec5SDimitry Andric                       .Case("vector-uint32", eFormatVectorOfUInt32)
4840b57cec5SDimitry Andric                       .Case("vector-float32", eFormatVectorOfFloat32)
4850b57cec5SDimitry Andric                       .Case("vector-uint64", eFormatVectorOfUInt64)
4860b57cec5SDimitry Andric                       .Case("vector-uint128", eFormatVectorOfUInt128)
4870b57cec5SDimitry Andric                       .Default(eFormatInvalid);
4880b57cec5SDimitry Andric           } else if (name.equals("set")) {
489349cc55cSDimitry Andric             reg_info.set_name.SetString(value);
4900b57cec5SDimitry Andric           } else if (name.equals("gcc") || name.equals("ehframe")) {
491349cc55cSDimitry Andric             value.getAsInteger(0, reg_info.regnum_ehframe);
4920b57cec5SDimitry Andric           } else if (name.equals("dwarf")) {
493349cc55cSDimitry Andric             value.getAsInteger(0, reg_info.regnum_dwarf);
4940b57cec5SDimitry Andric           } else if (name.equals("generic")) {
495349cc55cSDimitry Andric             reg_info.regnum_generic = Args::StringToGenericRegister(value);
4960b57cec5SDimitry Andric           } else if (name.equals("container-regs")) {
497349cc55cSDimitry Andric             SplitCommaSeparatedRegisterNumberString(value, reg_info.value_regs, 16);
4980b57cec5SDimitry Andric           } else if (name.equals("invalidate-regs")) {
499349cc55cSDimitry Andric             SplitCommaSeparatedRegisterNumberString(value, reg_info.invalidate_regs, 16);
5000b57cec5SDimitry Andric           }
5010b57cec5SDimitry Andric         }
5020b57cec5SDimitry Andric 
5030b57cec5SDimitry Andric         assert(reg_info.byte_size != 0);
504349cc55cSDimitry Andric         registers.push_back(reg_info);
5050b57cec5SDimitry Andric       } else {
5060b57cec5SDimitry Andric         break; // ensure exit before reg_num is incremented
5070b57cec5SDimitry Andric       }
5080b57cec5SDimitry Andric     } else {
5090b57cec5SDimitry Andric       break;
5100b57cec5SDimitry Andric     }
5110b57cec5SDimitry Andric   }
5120b57cec5SDimitry Andric 
513349cc55cSDimitry Andric   AddRemoteRegisters(registers, arch_to_use);
5140b57cec5SDimitry Andric }
5150b57cec5SDimitry Andric 
5160b57cec5SDimitry Andric Status ProcessGDBRemote::WillLaunch(lldb_private::Module *module) {
5170b57cec5SDimitry Andric   return WillLaunchOrAttach();
5180b57cec5SDimitry Andric }
5190b57cec5SDimitry Andric 
5200b57cec5SDimitry Andric Status ProcessGDBRemote::WillAttachToProcessWithID(lldb::pid_t pid) {
5210b57cec5SDimitry Andric   return WillLaunchOrAttach();
5220b57cec5SDimitry Andric }
5230b57cec5SDimitry Andric 
5240b57cec5SDimitry Andric Status ProcessGDBRemote::WillAttachToProcessWithName(const char *process_name,
5250b57cec5SDimitry Andric                                                      bool wait_for_launch) {
5260b57cec5SDimitry Andric   return WillLaunchOrAttach();
5270b57cec5SDimitry Andric }
5280b57cec5SDimitry Andric 
5295ffd83dbSDimitry Andric Status ProcessGDBRemote::DoConnectRemote(llvm::StringRef remote_url) {
5300b57cec5SDimitry Andric   Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
5310b57cec5SDimitry Andric   Status error(WillLaunchOrAttach());
5320b57cec5SDimitry Andric 
5330b57cec5SDimitry Andric   if (error.Fail())
5340b57cec5SDimitry Andric     return error;
5350b57cec5SDimitry Andric 
5365ffd83dbSDimitry Andric   if (repro::Reproducer::Instance().IsReplaying())
5375ffd83dbSDimitry Andric     error = ConnectToReplayServer();
5385ffd83dbSDimitry Andric   else
5390b57cec5SDimitry Andric     error = ConnectToDebugserver(remote_url);
5400b57cec5SDimitry Andric 
5410b57cec5SDimitry Andric   if (error.Fail())
5420b57cec5SDimitry Andric     return error;
5430b57cec5SDimitry Andric   StartAsyncThread();
5440b57cec5SDimitry Andric 
5450b57cec5SDimitry Andric   lldb::pid_t pid = m_gdb_comm.GetCurrentProcessID();
5460b57cec5SDimitry Andric   if (pid == LLDB_INVALID_PROCESS_ID) {
5470b57cec5SDimitry Andric     // We don't have a valid process ID, so note that we are connected and
5480b57cec5SDimitry Andric     // could now request to launch or attach, or get remote process listings...
5490b57cec5SDimitry Andric     SetPrivateState(eStateConnected);
5500b57cec5SDimitry Andric   } else {
5510b57cec5SDimitry Andric     // We have a valid process
5520b57cec5SDimitry Andric     SetID(pid);
5530b57cec5SDimitry Andric     GetThreadList();
5540b57cec5SDimitry Andric     StringExtractorGDBRemote response;
5550b57cec5SDimitry Andric     if (m_gdb_comm.GetStopReply(response)) {
5560b57cec5SDimitry Andric       SetLastStopPacket(response);
5570b57cec5SDimitry Andric 
5580b57cec5SDimitry Andric       Target &target = GetTarget();
5590b57cec5SDimitry Andric       if (!target.GetArchitecture().IsValid()) {
5600b57cec5SDimitry Andric         if (m_gdb_comm.GetProcessArchitecture().IsValid()) {
5610b57cec5SDimitry Andric           target.SetArchitecture(m_gdb_comm.GetProcessArchitecture());
5620b57cec5SDimitry Andric         } else {
5630b57cec5SDimitry Andric           if (m_gdb_comm.GetHostArchitecture().IsValid()) {
5640b57cec5SDimitry Andric             target.SetArchitecture(m_gdb_comm.GetHostArchitecture());
5650b57cec5SDimitry Andric           }
5660b57cec5SDimitry Andric         }
5670b57cec5SDimitry Andric       }
5680b57cec5SDimitry Andric 
5690b57cec5SDimitry Andric       const StateType state = SetThreadStopInfo(response);
5700b57cec5SDimitry Andric       if (state != eStateInvalid) {
5710b57cec5SDimitry Andric         SetPrivateState(state);
5720b57cec5SDimitry Andric       } else
5730b57cec5SDimitry Andric         error.SetErrorStringWithFormat(
5740b57cec5SDimitry Andric             "Process %" PRIu64 " was reported after connecting to "
5750b57cec5SDimitry Andric             "'%s', but state was not stopped: %s",
5760b57cec5SDimitry Andric             pid, remote_url.str().c_str(), StateAsCString(state));
5770b57cec5SDimitry Andric     } else
5780b57cec5SDimitry Andric       error.SetErrorStringWithFormat("Process %" PRIu64
5790b57cec5SDimitry Andric                                      " was reported after connecting to '%s', "
5800b57cec5SDimitry Andric                                      "but no stop reply packet was received",
5810b57cec5SDimitry Andric                                      pid, remote_url.str().c_str());
5820b57cec5SDimitry Andric   }
5830b57cec5SDimitry Andric 
5849dba64beSDimitry Andric   LLDB_LOGF(log,
5859dba64beSDimitry Andric             "ProcessGDBRemote::%s pid %" PRIu64
5860b57cec5SDimitry Andric             ": normalizing target architecture initial triple: %s "
5870b57cec5SDimitry Andric             "(GetTarget().GetArchitecture().IsValid() %s, "
5880b57cec5SDimitry Andric             "m_gdb_comm.GetHostArchitecture().IsValid(): %s)",
5890b57cec5SDimitry Andric             __FUNCTION__, GetID(),
5900b57cec5SDimitry Andric             GetTarget().GetArchitecture().GetTriple().getTriple().c_str(),
5910b57cec5SDimitry Andric             GetTarget().GetArchitecture().IsValid() ? "true" : "false",
5920b57cec5SDimitry Andric             m_gdb_comm.GetHostArchitecture().IsValid() ? "true" : "false");
5930b57cec5SDimitry Andric 
5940b57cec5SDimitry Andric   if (error.Success() && !GetTarget().GetArchitecture().IsValid() &&
5950b57cec5SDimitry Andric       m_gdb_comm.GetHostArchitecture().IsValid()) {
5960b57cec5SDimitry Andric     // Prefer the *process'* architecture over that of the *host*, if
5970b57cec5SDimitry Andric     // available.
5980b57cec5SDimitry Andric     if (m_gdb_comm.GetProcessArchitecture().IsValid())
5990b57cec5SDimitry Andric       GetTarget().SetArchitecture(m_gdb_comm.GetProcessArchitecture());
6000b57cec5SDimitry Andric     else
6010b57cec5SDimitry Andric       GetTarget().SetArchitecture(m_gdb_comm.GetHostArchitecture());
6020b57cec5SDimitry Andric   }
6030b57cec5SDimitry Andric 
6049dba64beSDimitry Andric   LLDB_LOGF(log,
6059dba64beSDimitry Andric             "ProcessGDBRemote::%s pid %" PRIu64
6060b57cec5SDimitry Andric             ": normalized target architecture triple: %s",
6070b57cec5SDimitry Andric             __FUNCTION__, GetID(),
6080b57cec5SDimitry Andric             GetTarget().GetArchitecture().GetTriple().getTriple().c_str());
6090b57cec5SDimitry Andric 
6100b57cec5SDimitry Andric   return error;
6110b57cec5SDimitry Andric }
6120b57cec5SDimitry Andric 
6130b57cec5SDimitry Andric Status ProcessGDBRemote::WillLaunchOrAttach() {
6140b57cec5SDimitry Andric   Status error;
6150b57cec5SDimitry Andric   m_stdio_communication.Clear();
6160b57cec5SDimitry Andric   return error;
6170b57cec5SDimitry Andric }
6180b57cec5SDimitry Andric 
6190b57cec5SDimitry Andric // Process Control
6200b57cec5SDimitry Andric Status ProcessGDBRemote::DoLaunch(lldb_private::Module *exe_module,
6210b57cec5SDimitry Andric                                   ProcessLaunchInfo &launch_info) {
6220b57cec5SDimitry Andric   Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
6230b57cec5SDimitry Andric   Status error;
6240b57cec5SDimitry Andric 
6259dba64beSDimitry Andric   LLDB_LOGF(log, "ProcessGDBRemote::%s() entered", __FUNCTION__);
6260b57cec5SDimitry Andric 
6270b57cec5SDimitry Andric   uint32_t launch_flags = launch_info.GetFlags().Get();
6280b57cec5SDimitry Andric   FileSpec stdin_file_spec{};
6290b57cec5SDimitry Andric   FileSpec stdout_file_spec{};
6300b57cec5SDimitry Andric   FileSpec stderr_file_spec{};
6310b57cec5SDimitry Andric   FileSpec working_dir = launch_info.GetWorkingDirectory();
6320b57cec5SDimitry Andric 
6330b57cec5SDimitry Andric   const FileAction *file_action;
6340b57cec5SDimitry Andric   file_action = launch_info.GetFileActionForFD(STDIN_FILENO);
6350b57cec5SDimitry Andric   if (file_action) {
6360b57cec5SDimitry Andric     if (file_action->GetAction() == FileAction::eFileActionOpen)
6370b57cec5SDimitry Andric       stdin_file_spec = file_action->GetFileSpec();
6380b57cec5SDimitry Andric   }
6390b57cec5SDimitry Andric   file_action = launch_info.GetFileActionForFD(STDOUT_FILENO);
6400b57cec5SDimitry Andric   if (file_action) {
6410b57cec5SDimitry Andric     if (file_action->GetAction() == FileAction::eFileActionOpen)
6420b57cec5SDimitry Andric       stdout_file_spec = file_action->GetFileSpec();
6430b57cec5SDimitry Andric   }
6440b57cec5SDimitry Andric   file_action = launch_info.GetFileActionForFD(STDERR_FILENO);
6450b57cec5SDimitry Andric   if (file_action) {
6460b57cec5SDimitry Andric     if (file_action->GetAction() == FileAction::eFileActionOpen)
6470b57cec5SDimitry Andric       stderr_file_spec = file_action->GetFileSpec();
6480b57cec5SDimitry Andric   }
6490b57cec5SDimitry Andric 
6500b57cec5SDimitry Andric   if (log) {
6510b57cec5SDimitry Andric     if (stdin_file_spec || stdout_file_spec || stderr_file_spec)
6529dba64beSDimitry Andric       LLDB_LOGF(log,
6539dba64beSDimitry Andric                 "ProcessGDBRemote::%s provided with STDIO paths via "
6540b57cec5SDimitry Andric                 "launch_info: stdin=%s, stdout=%s, stderr=%s",
6550b57cec5SDimitry Andric                 __FUNCTION__,
6560b57cec5SDimitry Andric                 stdin_file_spec ? stdin_file_spec.GetCString() : "<null>",
6570b57cec5SDimitry Andric                 stdout_file_spec ? stdout_file_spec.GetCString() : "<null>",
6580b57cec5SDimitry Andric                 stderr_file_spec ? stderr_file_spec.GetCString() : "<null>");
6590b57cec5SDimitry Andric     else
6609dba64beSDimitry Andric       LLDB_LOGF(log,
6619dba64beSDimitry Andric                 "ProcessGDBRemote::%s no STDIO paths given via launch_info",
6620b57cec5SDimitry Andric                 __FUNCTION__);
6630b57cec5SDimitry Andric   }
6640b57cec5SDimitry Andric 
6650b57cec5SDimitry Andric   const bool disable_stdio = (launch_flags & eLaunchFlagDisableSTDIO) != 0;
6660b57cec5SDimitry Andric   if (stdin_file_spec || disable_stdio) {
6670b57cec5SDimitry Andric     // the inferior will be reading stdin from the specified file or stdio is
6680b57cec5SDimitry Andric     // completely disabled
6690b57cec5SDimitry Andric     m_stdin_forward = false;
6700b57cec5SDimitry Andric   } else {
6710b57cec5SDimitry Andric     m_stdin_forward = true;
6720b57cec5SDimitry Andric   }
6730b57cec5SDimitry Andric 
6740b57cec5SDimitry Andric   //  ::LogSetBitMask (GDBR_LOG_DEFAULT);
6750b57cec5SDimitry Andric   //  ::LogSetOptions (LLDB_LOG_OPTION_THREADSAFE |
6760b57cec5SDimitry Andric   //  LLDB_LOG_OPTION_PREPEND_TIMESTAMP |
6770b57cec5SDimitry Andric   //  LLDB_LOG_OPTION_PREPEND_PROC_AND_THREAD);
6780b57cec5SDimitry Andric   //  ::LogSetLogFile ("/dev/stdout");
6790b57cec5SDimitry Andric 
6800b57cec5SDimitry Andric   error = EstablishConnectionIfNeeded(launch_info);
6810b57cec5SDimitry Andric   if (error.Success()) {
6820b57cec5SDimitry Andric     PseudoTerminal pty;
6830b57cec5SDimitry Andric     const bool disable_stdio = (launch_flags & eLaunchFlagDisableSTDIO) != 0;
6840b57cec5SDimitry Andric 
6850b57cec5SDimitry Andric     PlatformSP platform_sp(GetTarget().GetPlatform());
6860b57cec5SDimitry Andric     if (disable_stdio) {
6870b57cec5SDimitry Andric       // set to /dev/null unless redirected to a file above
6880b57cec5SDimitry Andric       if (!stdin_file_spec)
6890b57cec5SDimitry Andric         stdin_file_spec.SetFile(FileSystem::DEV_NULL,
6900b57cec5SDimitry Andric                                 FileSpec::Style::native);
6910b57cec5SDimitry Andric       if (!stdout_file_spec)
6920b57cec5SDimitry Andric         stdout_file_spec.SetFile(FileSystem::DEV_NULL,
6930b57cec5SDimitry Andric                                  FileSpec::Style::native);
6940b57cec5SDimitry Andric       if (!stderr_file_spec)
6950b57cec5SDimitry Andric         stderr_file_spec.SetFile(FileSystem::DEV_NULL,
6960b57cec5SDimitry Andric                                  FileSpec::Style::native);
6970b57cec5SDimitry Andric     } else if (platform_sp && platform_sp->IsHost()) {
6980b57cec5SDimitry Andric       // If the debugserver is local and we aren't disabling STDIO, lets use
6990b57cec5SDimitry Andric       // a pseudo terminal to instead of relying on the 'O' packets for stdio
7000b57cec5SDimitry Andric       // since 'O' packets can really slow down debugging if the inferior
7010b57cec5SDimitry Andric       // does a lot of output.
7020b57cec5SDimitry Andric       if ((!stdin_file_spec || !stdout_file_spec || !stderr_file_spec) &&
703e8d8bef9SDimitry Andric           !errorToBool(pty.OpenFirstAvailablePrimary(O_RDWR | O_NOCTTY))) {
704e8d8bef9SDimitry Andric         FileSpec secondary_name(pty.GetSecondaryName());
7050b57cec5SDimitry Andric 
7060b57cec5SDimitry Andric         if (!stdin_file_spec)
7075ffd83dbSDimitry Andric           stdin_file_spec = secondary_name;
7080b57cec5SDimitry Andric 
7090b57cec5SDimitry Andric         if (!stdout_file_spec)
7105ffd83dbSDimitry Andric           stdout_file_spec = secondary_name;
7110b57cec5SDimitry Andric 
7120b57cec5SDimitry Andric         if (!stderr_file_spec)
7135ffd83dbSDimitry Andric           stderr_file_spec = secondary_name;
7140b57cec5SDimitry Andric       }
7159dba64beSDimitry Andric       LLDB_LOGF(
7169dba64beSDimitry Andric           log,
7170b57cec5SDimitry Andric           "ProcessGDBRemote::%s adjusted STDIO paths for local platform "
7185ffd83dbSDimitry Andric           "(IsHost() is true) using secondary: stdin=%s, stdout=%s, "
7195ffd83dbSDimitry Andric           "stderr=%s",
7200b57cec5SDimitry Andric           __FUNCTION__,
7210b57cec5SDimitry Andric           stdin_file_spec ? stdin_file_spec.GetCString() : "<null>",
7220b57cec5SDimitry Andric           stdout_file_spec ? stdout_file_spec.GetCString() : "<null>",
7230b57cec5SDimitry Andric           stderr_file_spec ? stderr_file_spec.GetCString() : "<null>");
7240b57cec5SDimitry Andric     }
7250b57cec5SDimitry Andric 
7269dba64beSDimitry Andric     LLDB_LOGF(log,
7279dba64beSDimitry Andric               "ProcessGDBRemote::%s final STDIO paths after all "
7280b57cec5SDimitry Andric               "adjustments: stdin=%s, stdout=%s, stderr=%s",
7290b57cec5SDimitry Andric               __FUNCTION__,
7300b57cec5SDimitry Andric               stdin_file_spec ? stdin_file_spec.GetCString() : "<null>",
7310b57cec5SDimitry Andric               stdout_file_spec ? stdout_file_spec.GetCString() : "<null>",
7329dba64beSDimitry Andric               stderr_file_spec ? stderr_file_spec.GetCString() : "<null>");
7330b57cec5SDimitry Andric 
7340b57cec5SDimitry Andric     if (stdin_file_spec)
7350b57cec5SDimitry Andric       m_gdb_comm.SetSTDIN(stdin_file_spec);
7360b57cec5SDimitry Andric     if (stdout_file_spec)
7370b57cec5SDimitry Andric       m_gdb_comm.SetSTDOUT(stdout_file_spec);
7380b57cec5SDimitry Andric     if (stderr_file_spec)
7390b57cec5SDimitry Andric       m_gdb_comm.SetSTDERR(stderr_file_spec);
7400b57cec5SDimitry Andric 
7410b57cec5SDimitry Andric     m_gdb_comm.SetDisableASLR(launch_flags & eLaunchFlagDisableASLR);
7420b57cec5SDimitry Andric     m_gdb_comm.SetDetachOnError(launch_flags & eLaunchFlagDetachOnError);
7430b57cec5SDimitry Andric 
7440b57cec5SDimitry Andric     m_gdb_comm.SendLaunchArchPacket(
7450b57cec5SDimitry Andric         GetTarget().GetArchitecture().GetArchitectureName());
7460b57cec5SDimitry Andric 
7470b57cec5SDimitry Andric     const char *launch_event_data = launch_info.GetLaunchEventData();
7480b57cec5SDimitry Andric     if (launch_event_data != nullptr && *launch_event_data != '\0')
7490b57cec5SDimitry Andric       m_gdb_comm.SendLaunchEventDataPacket(launch_event_data);
7500b57cec5SDimitry Andric 
7510b57cec5SDimitry Andric     if (working_dir) {
7520b57cec5SDimitry Andric       m_gdb_comm.SetWorkingDir(working_dir);
7530b57cec5SDimitry Andric     }
7540b57cec5SDimitry Andric 
7550b57cec5SDimitry Andric     // Send the environment and the program + arguments after we connect
7560b57cec5SDimitry Andric     m_gdb_comm.SendEnvironment(launch_info.GetEnvironment());
7570b57cec5SDimitry Andric 
7580b57cec5SDimitry Andric     {
7590b57cec5SDimitry Andric       // Scope for the scoped timeout object
7600b57cec5SDimitry Andric       GDBRemoteCommunication::ScopedTimeout timeout(m_gdb_comm,
7610b57cec5SDimitry Andric                                                     std::chrono::seconds(10));
7620b57cec5SDimitry Andric 
7630b57cec5SDimitry Andric       int arg_packet_err = m_gdb_comm.SendArgumentsPacket(launch_info);
7640b57cec5SDimitry Andric       if (arg_packet_err == 0) {
7650b57cec5SDimitry Andric         std::string error_str;
7660b57cec5SDimitry Andric         if (m_gdb_comm.GetLaunchSuccess(error_str)) {
7670b57cec5SDimitry Andric           SetID(m_gdb_comm.GetCurrentProcessID());
7680b57cec5SDimitry Andric         } else {
7690b57cec5SDimitry Andric           error.SetErrorString(error_str.c_str());
7700b57cec5SDimitry Andric         }
7710b57cec5SDimitry Andric       } else {
7720b57cec5SDimitry Andric         error.SetErrorStringWithFormat("'A' packet returned an error: %i",
7730b57cec5SDimitry Andric                                        arg_packet_err);
7740b57cec5SDimitry Andric       }
7750b57cec5SDimitry Andric     }
7760b57cec5SDimitry Andric 
7770b57cec5SDimitry Andric     if (GetID() == LLDB_INVALID_PROCESS_ID) {
7789dba64beSDimitry Andric       LLDB_LOGF(log, "failed to connect to debugserver: %s",
7790b57cec5SDimitry Andric                 error.AsCString());
7800b57cec5SDimitry Andric       KillDebugserverProcess();
7810b57cec5SDimitry Andric       return error;
7820b57cec5SDimitry Andric     }
7830b57cec5SDimitry Andric 
7840b57cec5SDimitry Andric     StringExtractorGDBRemote response;
7850b57cec5SDimitry Andric     if (m_gdb_comm.GetStopReply(response)) {
7860b57cec5SDimitry Andric       SetLastStopPacket(response);
7870b57cec5SDimitry Andric 
7880b57cec5SDimitry Andric       const ArchSpec &process_arch = m_gdb_comm.GetProcessArchitecture();
7890b57cec5SDimitry Andric 
7900b57cec5SDimitry Andric       if (process_arch.IsValid()) {
7910b57cec5SDimitry Andric         GetTarget().MergeArchitecture(process_arch);
7920b57cec5SDimitry Andric       } else {
7930b57cec5SDimitry Andric         const ArchSpec &host_arch = m_gdb_comm.GetHostArchitecture();
7940b57cec5SDimitry Andric         if (host_arch.IsValid())
7950b57cec5SDimitry Andric           GetTarget().MergeArchitecture(host_arch);
7960b57cec5SDimitry Andric       }
7970b57cec5SDimitry Andric 
7980b57cec5SDimitry Andric       SetPrivateState(SetThreadStopInfo(response));
7990b57cec5SDimitry Andric 
8000b57cec5SDimitry Andric       if (!disable_stdio) {
8015ffd83dbSDimitry Andric         if (pty.GetPrimaryFileDescriptor() != PseudoTerminal::invalid_fd)
8025ffd83dbSDimitry Andric           SetSTDIOFileDescriptor(pty.ReleasePrimaryFileDescriptor());
8030b57cec5SDimitry Andric       }
8040b57cec5SDimitry Andric     }
8050b57cec5SDimitry Andric   } else {
8069dba64beSDimitry Andric     LLDB_LOGF(log, "failed to connect to debugserver: %s", error.AsCString());
8070b57cec5SDimitry Andric   }
8080b57cec5SDimitry Andric   return error;
8090b57cec5SDimitry Andric }
8100b57cec5SDimitry Andric 
8110b57cec5SDimitry Andric Status ProcessGDBRemote::ConnectToDebugserver(llvm::StringRef connect_url) {
8120b57cec5SDimitry Andric   Status error;
8130b57cec5SDimitry Andric   // Only connect if we have a valid connect URL
8140b57cec5SDimitry Andric   Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
8150b57cec5SDimitry Andric 
8160b57cec5SDimitry Andric   if (!connect_url.empty()) {
8179dba64beSDimitry Andric     LLDB_LOGF(log, "ProcessGDBRemote::%s Connecting to %s", __FUNCTION__,
8180b57cec5SDimitry Andric               connect_url.str().c_str());
8190b57cec5SDimitry Andric     std::unique_ptr<ConnectionFileDescriptor> conn_up(
8200b57cec5SDimitry Andric         new ConnectionFileDescriptor());
8210b57cec5SDimitry Andric     if (conn_up) {
8220b57cec5SDimitry Andric       const uint32_t max_retry_count = 50;
8230b57cec5SDimitry Andric       uint32_t retry_count = 0;
8240b57cec5SDimitry Andric       while (!m_gdb_comm.IsConnected()) {
8250b57cec5SDimitry Andric         if (conn_up->Connect(connect_url, &error) == eConnectionStatusSuccess) {
8265ffd83dbSDimitry Andric           m_gdb_comm.SetConnection(std::move(conn_up));
8270b57cec5SDimitry Andric           break;
8280b57cec5SDimitry Andric         }
8290b57cec5SDimitry Andric 
8300b57cec5SDimitry Andric         retry_count++;
8310b57cec5SDimitry Andric 
8320b57cec5SDimitry Andric         if (retry_count >= max_retry_count)
8330b57cec5SDimitry Andric           break;
8340b57cec5SDimitry Andric 
8359dba64beSDimitry Andric         std::this_thread::sleep_for(std::chrono::milliseconds(100));
8360b57cec5SDimitry Andric       }
8370b57cec5SDimitry Andric     }
8380b57cec5SDimitry Andric   }
8390b57cec5SDimitry Andric 
8400b57cec5SDimitry Andric   if (!m_gdb_comm.IsConnected()) {
8410b57cec5SDimitry Andric     if (error.Success())
8420b57cec5SDimitry Andric       error.SetErrorString("not connected to remote gdb server");
8430b57cec5SDimitry Andric     return error;
8440b57cec5SDimitry Andric   }
8450b57cec5SDimitry Andric 
8460b57cec5SDimitry Andric   // We always seem to be able to open a connection to a local port so we need
8470b57cec5SDimitry Andric   // to make sure we can then send data to it. If we can't then we aren't
8480b57cec5SDimitry Andric   // actually connected to anything, so try and do the handshake with the
8490b57cec5SDimitry Andric   // remote GDB server and make sure that goes alright.
8500b57cec5SDimitry Andric   if (!m_gdb_comm.HandshakeWithServer(&error)) {
8510b57cec5SDimitry Andric     m_gdb_comm.Disconnect();
8520b57cec5SDimitry Andric     if (error.Success())
8530b57cec5SDimitry Andric       error.SetErrorString("not connected to remote gdb server");
8540b57cec5SDimitry Andric     return error;
8550b57cec5SDimitry Andric   }
8560b57cec5SDimitry Andric 
8570b57cec5SDimitry Andric   m_gdb_comm.GetEchoSupported();
8580b57cec5SDimitry Andric   m_gdb_comm.GetThreadSuffixSupported();
8590b57cec5SDimitry Andric   m_gdb_comm.GetListThreadsInStopReplySupported();
8600b57cec5SDimitry Andric   m_gdb_comm.GetHostInfo();
8610b57cec5SDimitry Andric   m_gdb_comm.GetVContSupported('c');
8620b57cec5SDimitry Andric   m_gdb_comm.GetVAttachOrWaitSupported();
8630b57cec5SDimitry Andric   m_gdb_comm.EnableErrorStringInPacket();
8640b57cec5SDimitry Andric 
8650b57cec5SDimitry Andric   size_t num_cmds = GetExtraStartupCommands().GetArgumentCount();
8660b57cec5SDimitry Andric   for (size_t idx = 0; idx < num_cmds; idx++) {
8670b57cec5SDimitry Andric     StringExtractorGDBRemote response;
8680b57cec5SDimitry Andric     m_gdb_comm.SendPacketAndWaitForResponse(
869fe6060f1SDimitry Andric         GetExtraStartupCommands().GetArgumentAtIndex(idx), response);
8700b57cec5SDimitry Andric   }
8710b57cec5SDimitry Andric   return error;
8720b57cec5SDimitry Andric }
8730b57cec5SDimitry Andric 
8740b57cec5SDimitry Andric void ProcessGDBRemote::DidLaunchOrAttach(ArchSpec &process_arch) {
8750b57cec5SDimitry Andric   Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
8760b57cec5SDimitry Andric   BuildDynamicRegisterInfo(false);
8770b57cec5SDimitry Andric 
8785ffd83dbSDimitry Andric   // See if the GDB server supports qHostInfo or qProcessInfo packets. Prefer
8795ffd83dbSDimitry Andric   // qProcessInfo as it will be more specific to our process.
8800b57cec5SDimitry Andric 
8810b57cec5SDimitry Andric   const ArchSpec &remote_process_arch = m_gdb_comm.GetProcessArchitecture();
8820b57cec5SDimitry Andric   if (remote_process_arch.IsValid()) {
8830b57cec5SDimitry Andric     process_arch = remote_process_arch;
8845ffd83dbSDimitry Andric     LLDB_LOG(log, "gdb-remote had process architecture, using {0} {1}",
8855ffd83dbSDimitry Andric              process_arch.GetArchitectureName(),
8865ffd83dbSDimitry Andric              process_arch.GetTriple().getTriple());
8870b57cec5SDimitry Andric   } else {
8880b57cec5SDimitry Andric     process_arch = m_gdb_comm.GetHostArchitecture();
8895ffd83dbSDimitry Andric     LLDB_LOG(log,
8905ffd83dbSDimitry Andric              "gdb-remote did not have process architecture, using gdb-remote "
8915ffd83dbSDimitry Andric              "host architecture {0} {1}",
8925ffd83dbSDimitry Andric              process_arch.GetArchitectureName(),
8935ffd83dbSDimitry Andric              process_arch.GetTriple().getTriple());
8940b57cec5SDimitry Andric   }
8950b57cec5SDimitry Andric 
896fe6060f1SDimitry Andric   if (int addresssable_bits = m_gdb_comm.GetAddressingBits()) {
897fe6060f1SDimitry Andric     lldb::addr_t address_mask = ~((1ULL << addresssable_bits) - 1);
898fe6060f1SDimitry Andric     SetCodeAddressMask(address_mask);
899fe6060f1SDimitry Andric     SetDataAddressMask(address_mask);
900fe6060f1SDimitry Andric   }
901fe6060f1SDimitry Andric 
9020b57cec5SDimitry Andric   if (process_arch.IsValid()) {
9030b57cec5SDimitry Andric     const ArchSpec &target_arch = GetTarget().GetArchitecture();
9040b57cec5SDimitry Andric     if (target_arch.IsValid()) {
9055ffd83dbSDimitry Andric       LLDB_LOG(log, "analyzing target arch, currently {0} {1}",
9065ffd83dbSDimitry Andric                target_arch.GetArchitectureName(),
9075ffd83dbSDimitry Andric                target_arch.GetTriple().getTriple());
9080b57cec5SDimitry Andric 
9090b57cec5SDimitry Andric       // If the remote host is ARM and we have apple as the vendor, then
9100b57cec5SDimitry Andric       // ARM executables and shared libraries can have mixed ARM
9110b57cec5SDimitry Andric       // architectures.
9120b57cec5SDimitry Andric       // You can have an armv6 executable, and if the host is armv7, then the
9130b57cec5SDimitry Andric       // system will load the best possible architecture for all shared
9140b57cec5SDimitry Andric       // libraries it has, so we really need to take the remote host
9150b57cec5SDimitry Andric       // architecture as our defacto architecture in this case.
9160b57cec5SDimitry Andric 
9170b57cec5SDimitry Andric       if ((process_arch.GetMachine() == llvm::Triple::arm ||
9180b57cec5SDimitry Andric            process_arch.GetMachine() == llvm::Triple::thumb) &&
9190b57cec5SDimitry Andric           process_arch.GetTriple().getVendor() == llvm::Triple::Apple) {
9200b57cec5SDimitry Andric         GetTarget().SetArchitecture(process_arch);
9215ffd83dbSDimitry Andric         LLDB_LOG(log,
9225ffd83dbSDimitry Andric                  "remote process is ARM/Apple, "
9235ffd83dbSDimitry Andric                  "setting target arch to {0} {1}",
9245ffd83dbSDimitry Andric                  process_arch.GetArchitectureName(),
9255ffd83dbSDimitry Andric                  process_arch.GetTriple().getTriple());
9260b57cec5SDimitry Andric       } else {
9270b57cec5SDimitry Andric         // Fill in what is missing in the triple
9280b57cec5SDimitry Andric         const llvm::Triple &remote_triple = process_arch.GetTriple();
9290b57cec5SDimitry Andric         llvm::Triple new_target_triple = target_arch.GetTriple();
9300b57cec5SDimitry Andric         if (new_target_triple.getVendorName().size() == 0) {
9310b57cec5SDimitry Andric           new_target_triple.setVendor(remote_triple.getVendor());
9320b57cec5SDimitry Andric 
9330b57cec5SDimitry Andric           if (new_target_triple.getOSName().size() == 0) {
9340b57cec5SDimitry Andric             new_target_triple.setOS(remote_triple.getOS());
9350b57cec5SDimitry Andric 
9360b57cec5SDimitry Andric             if (new_target_triple.getEnvironmentName().size() == 0)
9375ffd83dbSDimitry Andric               new_target_triple.setEnvironment(remote_triple.getEnvironment());
9380b57cec5SDimitry Andric           }
9390b57cec5SDimitry Andric 
9400b57cec5SDimitry Andric           ArchSpec new_target_arch = target_arch;
9410b57cec5SDimitry Andric           new_target_arch.SetTriple(new_target_triple);
9420b57cec5SDimitry Andric           GetTarget().SetArchitecture(new_target_arch);
9430b57cec5SDimitry Andric         }
9440b57cec5SDimitry Andric       }
9450b57cec5SDimitry Andric 
9465ffd83dbSDimitry Andric       LLDB_LOG(log,
9475ffd83dbSDimitry Andric                "final target arch after adjustments for remote architecture: "
9485ffd83dbSDimitry Andric                "{0} {1}",
9495ffd83dbSDimitry Andric                target_arch.GetArchitectureName(),
9505ffd83dbSDimitry Andric                target_arch.GetTriple().getTriple());
9510b57cec5SDimitry Andric     } else {
9520b57cec5SDimitry Andric       // The target doesn't have a valid architecture yet, set it from the
9530b57cec5SDimitry Andric       // architecture we got from the remote GDB server
9540b57cec5SDimitry Andric       GetTarget().SetArchitecture(process_arch);
9550b57cec5SDimitry Andric     }
9560b57cec5SDimitry Andric   }
9570b57cec5SDimitry Andric 
9585ffd83dbSDimitry Andric   MaybeLoadExecutableModule();
9595ffd83dbSDimitry Andric 
9600b57cec5SDimitry Andric   // Find out which StructuredDataPlugins are supported by the debug monitor.
9610b57cec5SDimitry Andric   // These plugins transmit data over async $J packets.
9625ffd83dbSDimitry Andric   if (StructuredData::Array *supported_packets =
9635ffd83dbSDimitry Andric           m_gdb_comm.GetSupportedStructuredDataPlugins())
9645ffd83dbSDimitry Andric     MapSupportedStructuredDataPlugins(*supported_packets);
965349cc55cSDimitry Andric 
966349cc55cSDimitry Andric   // If connected to LLDB ("native-signals+"), use signal defs for
967349cc55cSDimitry Andric   // the remote platform.  If connected to GDB, just use the standard set.
968349cc55cSDimitry Andric   if (!m_gdb_comm.UsesNativeSignals()) {
969349cc55cSDimitry Andric     SetUnixSignals(std::make_shared<GDBRemoteSignals>());
970349cc55cSDimitry Andric   } else {
971349cc55cSDimitry Andric     PlatformSP platform_sp = GetTarget().GetPlatform();
972349cc55cSDimitry Andric     if (platform_sp && platform_sp->IsConnected())
973349cc55cSDimitry Andric       SetUnixSignals(platform_sp->GetUnixSignals());
974349cc55cSDimitry Andric     else
975349cc55cSDimitry Andric       SetUnixSignals(UnixSignals::Create(GetTarget().GetArchitecture()));
976349cc55cSDimitry Andric   }
9775ffd83dbSDimitry Andric }
9785ffd83dbSDimitry Andric 
9795ffd83dbSDimitry Andric void ProcessGDBRemote::MaybeLoadExecutableModule() {
9805ffd83dbSDimitry Andric   ModuleSP module_sp = GetTarget().GetExecutableModule();
9815ffd83dbSDimitry Andric   if (!module_sp)
9825ffd83dbSDimitry Andric     return;
9835ffd83dbSDimitry Andric 
9845ffd83dbSDimitry Andric   llvm::Optional<QOffsets> offsets = m_gdb_comm.GetQOffsets();
9855ffd83dbSDimitry Andric   if (!offsets)
9865ffd83dbSDimitry Andric     return;
9875ffd83dbSDimitry Andric 
9885ffd83dbSDimitry Andric   bool is_uniform =
9895ffd83dbSDimitry Andric       size_t(llvm::count(offsets->offsets, offsets->offsets[0])) ==
9905ffd83dbSDimitry Andric       offsets->offsets.size();
9915ffd83dbSDimitry Andric   if (!is_uniform)
9925ffd83dbSDimitry Andric     return; // TODO: Handle non-uniform responses.
9935ffd83dbSDimitry Andric 
9945ffd83dbSDimitry Andric   bool changed = false;
9955ffd83dbSDimitry Andric   module_sp->SetLoadAddress(GetTarget(), offsets->offsets[0],
9965ffd83dbSDimitry Andric                             /*value_is_offset=*/true, changed);
9975ffd83dbSDimitry Andric   if (changed) {
9985ffd83dbSDimitry Andric     ModuleList list;
9995ffd83dbSDimitry Andric     list.Append(module_sp);
10005ffd83dbSDimitry Andric     m_process->GetTarget().ModulesDidLoad(list);
10010b57cec5SDimitry Andric   }
10020b57cec5SDimitry Andric }
10030b57cec5SDimitry Andric 
10040b57cec5SDimitry Andric void ProcessGDBRemote::DidLaunch() {
10050b57cec5SDimitry Andric   ArchSpec process_arch;
10060b57cec5SDimitry Andric   DidLaunchOrAttach(process_arch);
10070b57cec5SDimitry Andric }
10080b57cec5SDimitry Andric 
10090b57cec5SDimitry Andric Status ProcessGDBRemote::DoAttachToProcessWithID(
10100b57cec5SDimitry Andric     lldb::pid_t attach_pid, const ProcessAttachInfo &attach_info) {
10110b57cec5SDimitry Andric   Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
10120b57cec5SDimitry Andric   Status error;
10130b57cec5SDimitry Andric 
10149dba64beSDimitry Andric   LLDB_LOGF(log, "ProcessGDBRemote::%s()", __FUNCTION__);
10150b57cec5SDimitry Andric 
10160b57cec5SDimitry Andric   // Clear out and clean up from any current state
10170b57cec5SDimitry Andric   Clear();
10180b57cec5SDimitry Andric   if (attach_pid != LLDB_INVALID_PROCESS_ID) {
10190b57cec5SDimitry Andric     error = EstablishConnectionIfNeeded(attach_info);
10200b57cec5SDimitry Andric     if (error.Success()) {
10210b57cec5SDimitry Andric       m_gdb_comm.SetDetachOnError(attach_info.GetDetachOnError());
10220b57cec5SDimitry Andric 
10230b57cec5SDimitry Andric       char packet[64];
10240b57cec5SDimitry Andric       const int packet_len =
10250b57cec5SDimitry Andric           ::snprintf(packet, sizeof(packet), "vAttach;%" PRIx64, attach_pid);
10260b57cec5SDimitry Andric       SetID(attach_pid);
10270b57cec5SDimitry Andric       m_async_broadcaster.BroadcastEvent(
10280b57cec5SDimitry Andric           eBroadcastBitAsyncContinue, new EventDataBytes(packet, packet_len));
10290b57cec5SDimitry Andric     } else
10300b57cec5SDimitry Andric       SetExitStatus(-1, error.AsCString());
10310b57cec5SDimitry Andric   }
10320b57cec5SDimitry Andric 
10330b57cec5SDimitry Andric   return error;
10340b57cec5SDimitry Andric }
10350b57cec5SDimitry Andric 
10360b57cec5SDimitry Andric Status ProcessGDBRemote::DoAttachToProcessWithName(
10370b57cec5SDimitry Andric     const char *process_name, const ProcessAttachInfo &attach_info) {
10380b57cec5SDimitry Andric   Status error;
10390b57cec5SDimitry Andric   // Clear out and clean up from any current state
10400b57cec5SDimitry Andric   Clear();
10410b57cec5SDimitry Andric 
10420b57cec5SDimitry Andric   if (process_name && process_name[0]) {
10430b57cec5SDimitry Andric     error = EstablishConnectionIfNeeded(attach_info);
10440b57cec5SDimitry Andric     if (error.Success()) {
10450b57cec5SDimitry Andric       StreamString packet;
10460b57cec5SDimitry Andric 
10470b57cec5SDimitry Andric       m_gdb_comm.SetDetachOnError(attach_info.GetDetachOnError());
10480b57cec5SDimitry Andric 
10490b57cec5SDimitry Andric       if (attach_info.GetWaitForLaunch()) {
10500b57cec5SDimitry Andric         if (!m_gdb_comm.GetVAttachOrWaitSupported()) {
10510b57cec5SDimitry Andric           packet.PutCString("vAttachWait");
10520b57cec5SDimitry Andric         } else {
10530b57cec5SDimitry Andric           if (attach_info.GetIgnoreExisting())
10540b57cec5SDimitry Andric             packet.PutCString("vAttachWait");
10550b57cec5SDimitry Andric           else
10560b57cec5SDimitry Andric             packet.PutCString("vAttachOrWait");
10570b57cec5SDimitry Andric         }
10580b57cec5SDimitry Andric       } else
10590b57cec5SDimitry Andric         packet.PutCString("vAttachName");
10600b57cec5SDimitry Andric       packet.PutChar(';');
10610b57cec5SDimitry Andric       packet.PutBytesAsRawHex8(process_name, strlen(process_name),
10620b57cec5SDimitry Andric                                endian::InlHostByteOrder(),
10630b57cec5SDimitry Andric                                endian::InlHostByteOrder());
10640b57cec5SDimitry Andric 
10650b57cec5SDimitry Andric       m_async_broadcaster.BroadcastEvent(
10660b57cec5SDimitry Andric           eBroadcastBitAsyncContinue,
10670b57cec5SDimitry Andric           new EventDataBytes(packet.GetString().data(), packet.GetSize()));
10680b57cec5SDimitry Andric 
10690b57cec5SDimitry Andric     } else
10700b57cec5SDimitry Andric       SetExitStatus(-1, error.AsCString());
10710b57cec5SDimitry Andric   }
10720b57cec5SDimitry Andric   return error;
10730b57cec5SDimitry Andric }
10740b57cec5SDimitry Andric 
1075fe6060f1SDimitry Andric llvm::Expected<TraceSupportedResponse> ProcessGDBRemote::TraceSupported() {
1076fe6060f1SDimitry Andric   return m_gdb_comm.SendTraceSupported(GetInterruptTimeout());
10770b57cec5SDimitry Andric }
10780b57cec5SDimitry Andric 
1079fe6060f1SDimitry Andric llvm::Error ProcessGDBRemote::TraceStop(const TraceStopRequest &request) {
1080fe6060f1SDimitry Andric   return m_gdb_comm.SendTraceStop(request, GetInterruptTimeout());
10810b57cec5SDimitry Andric }
10820b57cec5SDimitry Andric 
1083fe6060f1SDimitry Andric llvm::Error ProcessGDBRemote::TraceStart(const llvm::json::Value &request) {
1084fe6060f1SDimitry Andric   return m_gdb_comm.SendTraceStart(request, GetInterruptTimeout());
10850b57cec5SDimitry Andric }
10860b57cec5SDimitry Andric 
1087fe6060f1SDimitry Andric llvm::Expected<std::string>
1088fe6060f1SDimitry Andric ProcessGDBRemote::TraceGetState(llvm::StringRef type) {
1089fe6060f1SDimitry Andric   return m_gdb_comm.SendTraceGetState(type, GetInterruptTimeout());
10900b57cec5SDimitry Andric }
10910b57cec5SDimitry Andric 
1092fe6060f1SDimitry Andric llvm::Expected<std::vector<uint8_t>>
1093fe6060f1SDimitry Andric ProcessGDBRemote::TraceGetBinaryData(const TraceGetBinaryDataRequest &request) {
1094fe6060f1SDimitry Andric   return m_gdb_comm.SendTraceGetBinaryData(request, GetInterruptTimeout());
1095e8d8bef9SDimitry Andric }
1096e8d8bef9SDimitry Andric 
10970b57cec5SDimitry Andric void ProcessGDBRemote::DidExit() {
10980b57cec5SDimitry Andric   // When we exit, disconnect from the GDB server communications
10990b57cec5SDimitry Andric   m_gdb_comm.Disconnect();
11000b57cec5SDimitry Andric }
11010b57cec5SDimitry Andric 
11020b57cec5SDimitry Andric void ProcessGDBRemote::DidAttach(ArchSpec &process_arch) {
11030b57cec5SDimitry Andric   // If you can figure out what the architecture is, fill it in here.
11040b57cec5SDimitry Andric   process_arch.Clear();
11050b57cec5SDimitry Andric   DidLaunchOrAttach(process_arch);
11060b57cec5SDimitry Andric }
11070b57cec5SDimitry Andric 
11080b57cec5SDimitry Andric Status ProcessGDBRemote::WillResume() {
11090b57cec5SDimitry Andric   m_continue_c_tids.clear();
11100b57cec5SDimitry Andric   m_continue_C_tids.clear();
11110b57cec5SDimitry Andric   m_continue_s_tids.clear();
11120b57cec5SDimitry Andric   m_continue_S_tids.clear();
11130b57cec5SDimitry Andric   m_jstopinfo_sp.reset();
11140b57cec5SDimitry Andric   m_jthreadsinfo_sp.reset();
11150b57cec5SDimitry Andric   return Status();
11160b57cec5SDimitry Andric }
11170b57cec5SDimitry Andric 
11180b57cec5SDimitry Andric Status ProcessGDBRemote::DoResume() {
11190b57cec5SDimitry Andric   Status error;
11200b57cec5SDimitry Andric   Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
11219dba64beSDimitry Andric   LLDB_LOGF(log, "ProcessGDBRemote::Resume()");
11220b57cec5SDimitry Andric 
11230b57cec5SDimitry Andric   ListenerSP listener_sp(
11240b57cec5SDimitry Andric       Listener::MakeListener("gdb-remote.resume-packet-sent"));
11250b57cec5SDimitry Andric   if (listener_sp->StartListeningForEvents(
11260b57cec5SDimitry Andric           &m_gdb_comm, GDBRemoteCommunication::eBroadcastBitRunPacketSent)) {
11270b57cec5SDimitry Andric     listener_sp->StartListeningForEvents(
11280b57cec5SDimitry Andric         &m_async_broadcaster,
11290b57cec5SDimitry Andric         ProcessGDBRemote::eBroadcastBitAsyncThreadDidExit);
11300b57cec5SDimitry Andric 
11310b57cec5SDimitry Andric     const size_t num_threads = GetThreadList().GetSize();
11320b57cec5SDimitry Andric 
11330b57cec5SDimitry Andric     StreamString continue_packet;
11340b57cec5SDimitry Andric     bool continue_packet_error = false;
11350b57cec5SDimitry Andric     if (m_gdb_comm.HasAnyVContSupport()) {
1136349cc55cSDimitry Andric       if (m_continue_c_tids.size() == num_threads ||
11370b57cec5SDimitry Andric           (m_continue_c_tids.empty() && m_continue_C_tids.empty() &&
1138349cc55cSDimitry Andric            m_continue_s_tids.empty() && m_continue_S_tids.empty())) {
11390b57cec5SDimitry Andric         // All threads are continuing, just send a "c" packet
11400b57cec5SDimitry Andric         continue_packet.PutCString("c");
11410b57cec5SDimitry Andric       } else {
11420b57cec5SDimitry Andric         continue_packet.PutCString("vCont");
11430b57cec5SDimitry Andric 
11440b57cec5SDimitry Andric         if (!m_continue_c_tids.empty()) {
11450b57cec5SDimitry Andric           if (m_gdb_comm.GetVContSupported('c')) {
11460b57cec5SDimitry Andric             for (tid_collection::const_iterator
11470b57cec5SDimitry Andric                      t_pos = m_continue_c_tids.begin(),
11480b57cec5SDimitry Andric                      t_end = m_continue_c_tids.end();
11490b57cec5SDimitry Andric                  t_pos != t_end; ++t_pos)
11500b57cec5SDimitry Andric               continue_packet.Printf(";c:%4.4" PRIx64, *t_pos);
11510b57cec5SDimitry Andric           } else
11520b57cec5SDimitry Andric             continue_packet_error = true;
11530b57cec5SDimitry Andric         }
11540b57cec5SDimitry Andric 
11550b57cec5SDimitry Andric         if (!continue_packet_error && !m_continue_C_tids.empty()) {
11560b57cec5SDimitry Andric           if (m_gdb_comm.GetVContSupported('C')) {
11570b57cec5SDimitry Andric             for (tid_sig_collection::const_iterator
11580b57cec5SDimitry Andric                      s_pos = m_continue_C_tids.begin(),
11590b57cec5SDimitry Andric                      s_end = m_continue_C_tids.end();
11600b57cec5SDimitry Andric                  s_pos != s_end; ++s_pos)
11610b57cec5SDimitry Andric               continue_packet.Printf(";C%2.2x:%4.4" PRIx64, s_pos->second,
11620b57cec5SDimitry Andric                                      s_pos->first);
11630b57cec5SDimitry Andric           } else
11640b57cec5SDimitry Andric             continue_packet_error = true;
11650b57cec5SDimitry Andric         }
11660b57cec5SDimitry Andric 
11670b57cec5SDimitry Andric         if (!continue_packet_error && !m_continue_s_tids.empty()) {
11680b57cec5SDimitry Andric           if (m_gdb_comm.GetVContSupported('s')) {
11690b57cec5SDimitry Andric             for (tid_collection::const_iterator
11700b57cec5SDimitry Andric                      t_pos = m_continue_s_tids.begin(),
11710b57cec5SDimitry Andric                      t_end = m_continue_s_tids.end();
11720b57cec5SDimitry Andric                  t_pos != t_end; ++t_pos)
11730b57cec5SDimitry Andric               continue_packet.Printf(";s:%4.4" PRIx64, *t_pos);
11740b57cec5SDimitry Andric           } else
11750b57cec5SDimitry Andric             continue_packet_error = true;
11760b57cec5SDimitry Andric         }
11770b57cec5SDimitry Andric 
11780b57cec5SDimitry Andric         if (!continue_packet_error && !m_continue_S_tids.empty()) {
11790b57cec5SDimitry Andric           if (m_gdb_comm.GetVContSupported('S')) {
11800b57cec5SDimitry Andric             for (tid_sig_collection::const_iterator
11810b57cec5SDimitry Andric                      s_pos = m_continue_S_tids.begin(),
11820b57cec5SDimitry Andric                      s_end = m_continue_S_tids.end();
11830b57cec5SDimitry Andric                  s_pos != s_end; ++s_pos)
11840b57cec5SDimitry Andric               continue_packet.Printf(";S%2.2x:%4.4" PRIx64, s_pos->second,
11850b57cec5SDimitry Andric                                      s_pos->first);
11860b57cec5SDimitry Andric           } else
11870b57cec5SDimitry Andric             continue_packet_error = true;
11880b57cec5SDimitry Andric         }
11890b57cec5SDimitry Andric 
11900b57cec5SDimitry Andric         if (continue_packet_error)
11910b57cec5SDimitry Andric           continue_packet.Clear();
11920b57cec5SDimitry Andric       }
11930b57cec5SDimitry Andric     } else
11940b57cec5SDimitry Andric       continue_packet_error = true;
11950b57cec5SDimitry Andric 
11960b57cec5SDimitry Andric     if (continue_packet_error) {
11970b57cec5SDimitry Andric       // Either no vCont support, or we tried to use part of the vCont packet
11980b57cec5SDimitry Andric       // that wasn't supported by the remote GDB server. We need to try and
11990b57cec5SDimitry Andric       // make a simple packet that can do our continue
12000b57cec5SDimitry Andric       const size_t num_continue_c_tids = m_continue_c_tids.size();
12010b57cec5SDimitry Andric       const size_t num_continue_C_tids = m_continue_C_tids.size();
12020b57cec5SDimitry Andric       const size_t num_continue_s_tids = m_continue_s_tids.size();
12030b57cec5SDimitry Andric       const size_t num_continue_S_tids = m_continue_S_tids.size();
12040b57cec5SDimitry Andric       if (num_continue_c_tids > 0) {
12050b57cec5SDimitry Andric         if (num_continue_c_tids == num_threads) {
12060b57cec5SDimitry Andric           // All threads are resuming...
12070b57cec5SDimitry Andric           m_gdb_comm.SetCurrentThreadForRun(-1);
12080b57cec5SDimitry Andric           continue_packet.PutChar('c');
12090b57cec5SDimitry Andric           continue_packet_error = false;
12100b57cec5SDimitry Andric         } else if (num_continue_c_tids == 1 && num_continue_C_tids == 0 &&
12110b57cec5SDimitry Andric                    num_continue_s_tids == 0 && num_continue_S_tids == 0) {
12120b57cec5SDimitry Andric           // Only one thread is continuing
12130b57cec5SDimitry Andric           m_gdb_comm.SetCurrentThreadForRun(m_continue_c_tids.front());
12140b57cec5SDimitry Andric           continue_packet.PutChar('c');
12150b57cec5SDimitry Andric           continue_packet_error = false;
12160b57cec5SDimitry Andric         }
12170b57cec5SDimitry Andric       }
12180b57cec5SDimitry Andric 
12190b57cec5SDimitry Andric       if (continue_packet_error && num_continue_C_tids > 0) {
12200b57cec5SDimitry Andric         if ((num_continue_C_tids + num_continue_c_tids) == num_threads &&
12210b57cec5SDimitry Andric             num_continue_C_tids > 0 && num_continue_s_tids == 0 &&
12220b57cec5SDimitry Andric             num_continue_S_tids == 0) {
12230b57cec5SDimitry Andric           const int continue_signo = m_continue_C_tids.front().second;
12240b57cec5SDimitry Andric           // Only one thread is continuing
12250b57cec5SDimitry Andric           if (num_continue_C_tids > 1) {
12260b57cec5SDimitry Andric             // More that one thread with a signal, yet we don't have vCont
12270b57cec5SDimitry Andric             // support and we are being asked to resume each thread with a
12280b57cec5SDimitry Andric             // signal, we need to make sure they are all the same signal, or we
12290b57cec5SDimitry Andric             // can't issue the continue accurately with the current support...
12300b57cec5SDimitry Andric             if (num_continue_C_tids > 1) {
12310b57cec5SDimitry Andric               continue_packet_error = false;
12320b57cec5SDimitry Andric               for (size_t i = 1; i < m_continue_C_tids.size(); ++i) {
12330b57cec5SDimitry Andric                 if (m_continue_C_tids[i].second != continue_signo)
12340b57cec5SDimitry Andric                   continue_packet_error = true;
12350b57cec5SDimitry Andric               }
12360b57cec5SDimitry Andric             }
12370b57cec5SDimitry Andric             if (!continue_packet_error)
12380b57cec5SDimitry Andric               m_gdb_comm.SetCurrentThreadForRun(-1);
12390b57cec5SDimitry Andric           } else {
12400b57cec5SDimitry Andric             // Set the continue thread ID
12410b57cec5SDimitry Andric             continue_packet_error = false;
12420b57cec5SDimitry Andric             m_gdb_comm.SetCurrentThreadForRun(m_continue_C_tids.front().first);
12430b57cec5SDimitry Andric           }
12440b57cec5SDimitry Andric           if (!continue_packet_error) {
12450b57cec5SDimitry Andric             // Add threads continuing with the same signo...
12460b57cec5SDimitry Andric             continue_packet.Printf("C%2.2x", continue_signo);
12470b57cec5SDimitry Andric           }
12480b57cec5SDimitry Andric         }
12490b57cec5SDimitry Andric       }
12500b57cec5SDimitry Andric 
12510b57cec5SDimitry Andric       if (continue_packet_error && num_continue_s_tids > 0) {
12520b57cec5SDimitry Andric         if (num_continue_s_tids == num_threads) {
12530b57cec5SDimitry Andric           // All threads are resuming...
12540b57cec5SDimitry Andric           m_gdb_comm.SetCurrentThreadForRun(-1);
12550b57cec5SDimitry Andric 
12560b57cec5SDimitry Andric           continue_packet.PutChar('s');
12570b57cec5SDimitry Andric 
12580b57cec5SDimitry Andric           continue_packet_error = false;
12590b57cec5SDimitry Andric         } else if (num_continue_c_tids == 0 && num_continue_C_tids == 0 &&
12600b57cec5SDimitry Andric                    num_continue_s_tids == 1 && num_continue_S_tids == 0) {
12610b57cec5SDimitry Andric           // Only one thread is stepping
12620b57cec5SDimitry Andric           m_gdb_comm.SetCurrentThreadForRun(m_continue_s_tids.front());
12630b57cec5SDimitry Andric           continue_packet.PutChar('s');
12640b57cec5SDimitry Andric           continue_packet_error = false;
12650b57cec5SDimitry Andric         }
12660b57cec5SDimitry Andric       }
12670b57cec5SDimitry Andric 
12680b57cec5SDimitry Andric       if (!continue_packet_error && num_continue_S_tids > 0) {
12690b57cec5SDimitry Andric         if (num_continue_S_tids == num_threads) {
12700b57cec5SDimitry Andric           const int step_signo = m_continue_S_tids.front().second;
12710b57cec5SDimitry Andric           // Are all threads trying to step with the same signal?
12720b57cec5SDimitry Andric           continue_packet_error = false;
12730b57cec5SDimitry Andric           if (num_continue_S_tids > 1) {
12740b57cec5SDimitry Andric             for (size_t i = 1; i < num_threads; ++i) {
12750b57cec5SDimitry Andric               if (m_continue_S_tids[i].second != step_signo)
12760b57cec5SDimitry Andric                 continue_packet_error = true;
12770b57cec5SDimitry Andric             }
12780b57cec5SDimitry Andric           }
12790b57cec5SDimitry Andric           if (!continue_packet_error) {
12800b57cec5SDimitry Andric             // Add threads stepping with the same signo...
12810b57cec5SDimitry Andric             m_gdb_comm.SetCurrentThreadForRun(-1);
12820b57cec5SDimitry Andric             continue_packet.Printf("S%2.2x", step_signo);
12830b57cec5SDimitry Andric           }
12840b57cec5SDimitry Andric         } else if (num_continue_c_tids == 0 && num_continue_C_tids == 0 &&
12850b57cec5SDimitry Andric                    num_continue_s_tids == 0 && num_continue_S_tids == 1) {
12860b57cec5SDimitry Andric           // Only one thread is stepping with signal
12870b57cec5SDimitry Andric           m_gdb_comm.SetCurrentThreadForRun(m_continue_S_tids.front().first);
12880b57cec5SDimitry Andric           continue_packet.Printf("S%2.2x", m_continue_S_tids.front().second);
12890b57cec5SDimitry Andric           continue_packet_error = false;
12900b57cec5SDimitry Andric         }
12910b57cec5SDimitry Andric       }
12920b57cec5SDimitry Andric     }
12930b57cec5SDimitry Andric 
12940b57cec5SDimitry Andric     if (continue_packet_error) {
12950b57cec5SDimitry Andric       error.SetErrorString("can't make continue packet for this resume");
12960b57cec5SDimitry Andric     } else {
12970b57cec5SDimitry Andric       EventSP event_sp;
12980b57cec5SDimitry Andric       if (!m_async_thread.IsJoinable()) {
12990b57cec5SDimitry Andric         error.SetErrorString("Trying to resume but the async thread is dead.");
13009dba64beSDimitry Andric         LLDB_LOGF(log, "ProcessGDBRemote::DoResume: Trying to resume but the "
13010b57cec5SDimitry Andric                        "async thread is dead.");
13020b57cec5SDimitry Andric         return error;
13030b57cec5SDimitry Andric       }
13040b57cec5SDimitry Andric 
13050b57cec5SDimitry Andric       m_async_broadcaster.BroadcastEvent(
13060b57cec5SDimitry Andric           eBroadcastBitAsyncContinue,
13070b57cec5SDimitry Andric           new EventDataBytes(continue_packet.GetString().data(),
13080b57cec5SDimitry Andric                              continue_packet.GetSize()));
13090b57cec5SDimitry Andric 
13100b57cec5SDimitry Andric       if (!listener_sp->GetEvent(event_sp, std::chrono::seconds(5))) {
13110b57cec5SDimitry Andric         error.SetErrorString("Resume timed out.");
13129dba64beSDimitry Andric         LLDB_LOGF(log, "ProcessGDBRemote::DoResume: Resume timed out.");
13130b57cec5SDimitry Andric       } else if (event_sp->BroadcasterIs(&m_async_broadcaster)) {
13140b57cec5SDimitry Andric         error.SetErrorString("Broadcast continue, but the async thread was "
13150b57cec5SDimitry Andric                              "killed before we got an ack back.");
13169dba64beSDimitry Andric         LLDB_LOGF(log,
13179dba64beSDimitry Andric                   "ProcessGDBRemote::DoResume: Broadcast continue, but the "
13180b57cec5SDimitry Andric                   "async thread was killed before we got an ack back.");
13190b57cec5SDimitry Andric         return error;
13200b57cec5SDimitry Andric       }
13210b57cec5SDimitry Andric     }
13220b57cec5SDimitry Andric   }
13230b57cec5SDimitry Andric 
13240b57cec5SDimitry Andric   return error;
13250b57cec5SDimitry Andric }
13260b57cec5SDimitry Andric 
13270b57cec5SDimitry Andric void ProcessGDBRemote::ClearThreadIDList() {
13280b57cec5SDimitry Andric   std::lock_guard<std::recursive_mutex> guard(m_thread_list_real.GetMutex());
13290b57cec5SDimitry Andric   m_thread_ids.clear();
13300b57cec5SDimitry Andric   m_thread_pcs.clear();
13310b57cec5SDimitry Andric }
13320b57cec5SDimitry Andric 
1333fe6060f1SDimitry Andric size_t ProcessGDBRemote::UpdateThreadIDsFromStopReplyThreadsValue(
1334fe6060f1SDimitry Andric     llvm::StringRef value) {
13350b57cec5SDimitry Andric   m_thread_ids.clear();
1336fe6060f1SDimitry Andric   lldb::pid_t pid = m_gdb_comm.GetCurrentProcessID();
1337fe6060f1SDimitry Andric   StringExtractorGDBRemote thread_ids{value};
1338fe6060f1SDimitry Andric 
1339fe6060f1SDimitry Andric   do {
1340fe6060f1SDimitry Andric     auto pid_tid = thread_ids.GetPidTid(pid);
1341fe6060f1SDimitry Andric     if (pid_tid && pid_tid->first == pid) {
1342fe6060f1SDimitry Andric       lldb::tid_t tid = pid_tid->second;
1343fe6060f1SDimitry Andric       if (tid != LLDB_INVALID_THREAD_ID &&
1344fe6060f1SDimitry Andric           tid != StringExtractorGDBRemote::AllProcesses)
13450b57cec5SDimitry Andric         m_thread_ids.push_back(tid);
13460b57cec5SDimitry Andric     }
1347fe6060f1SDimitry Andric   } while (thread_ids.GetChar() == ',');
1348fe6060f1SDimitry Andric 
13490b57cec5SDimitry Andric   return m_thread_ids.size();
13500b57cec5SDimitry Andric }
13510b57cec5SDimitry Andric 
1352349cc55cSDimitry Andric size_t ProcessGDBRemote::UpdateThreadPCsFromStopReplyThreadsValue(
1353349cc55cSDimitry Andric     llvm::StringRef value) {
13540b57cec5SDimitry Andric   m_thread_pcs.clear();
1355349cc55cSDimitry Andric   for (llvm::StringRef x : llvm::split(value, ',')) {
13560b57cec5SDimitry Andric     lldb::addr_t pc;
1357349cc55cSDimitry Andric     if (llvm::to_integer(x, pc, 16))
13580b57cec5SDimitry Andric       m_thread_pcs.push_back(pc);
13590b57cec5SDimitry Andric   }
13600b57cec5SDimitry Andric   return m_thread_pcs.size();
13610b57cec5SDimitry Andric }
13620b57cec5SDimitry Andric 
13630b57cec5SDimitry Andric bool ProcessGDBRemote::UpdateThreadIDList() {
13640b57cec5SDimitry Andric   std::lock_guard<std::recursive_mutex> guard(m_thread_list_real.GetMutex());
13650b57cec5SDimitry Andric 
13660b57cec5SDimitry Andric   if (m_jthreadsinfo_sp) {
13670b57cec5SDimitry Andric     // If we have the JSON threads info, we can get the thread list from that
13680b57cec5SDimitry Andric     StructuredData::Array *thread_infos = m_jthreadsinfo_sp->GetAsArray();
13690b57cec5SDimitry Andric     if (thread_infos && thread_infos->GetSize() > 0) {
13700b57cec5SDimitry Andric       m_thread_ids.clear();
13710b57cec5SDimitry Andric       m_thread_pcs.clear();
13720b57cec5SDimitry Andric       thread_infos->ForEach([this](StructuredData::Object *object) -> bool {
13730b57cec5SDimitry Andric         StructuredData::Dictionary *thread_dict = object->GetAsDictionary();
13740b57cec5SDimitry Andric         if (thread_dict) {
13750b57cec5SDimitry Andric           // Set the thread stop info from the JSON dictionary
13760b57cec5SDimitry Andric           SetThreadStopInfo(thread_dict);
13770b57cec5SDimitry Andric           lldb::tid_t tid = LLDB_INVALID_THREAD_ID;
13780b57cec5SDimitry Andric           if (thread_dict->GetValueForKeyAsInteger<lldb::tid_t>("tid", tid))
13790b57cec5SDimitry Andric             m_thread_ids.push_back(tid);
13800b57cec5SDimitry Andric         }
13810b57cec5SDimitry Andric         return true; // Keep iterating through all thread_info objects
13820b57cec5SDimitry Andric       });
13830b57cec5SDimitry Andric     }
13840b57cec5SDimitry Andric     if (!m_thread_ids.empty())
13850b57cec5SDimitry Andric       return true;
13860b57cec5SDimitry Andric   } else {
13870b57cec5SDimitry Andric     // See if we can get the thread IDs from the current stop reply packets
13880b57cec5SDimitry Andric     // that might contain a "threads" key/value pair
13890b57cec5SDimitry Andric 
1390349cc55cSDimitry Andric     if (m_last_stop_packet) {
13910b57cec5SDimitry Andric       // Get the thread stop info
1392349cc55cSDimitry Andric       StringExtractorGDBRemote &stop_info = *m_last_stop_packet;
1393349cc55cSDimitry Andric       const std::string &stop_info_str = std::string(stop_info.GetStringRef());
13940b57cec5SDimitry Andric 
13950b57cec5SDimitry Andric       m_thread_pcs.clear();
13960b57cec5SDimitry Andric       const size_t thread_pcs_pos = stop_info_str.find(";thread-pcs:");
13970b57cec5SDimitry Andric       if (thread_pcs_pos != std::string::npos) {
13980b57cec5SDimitry Andric         const size_t start = thread_pcs_pos + strlen(";thread-pcs:");
13990b57cec5SDimitry Andric         const size_t end = stop_info_str.find(';', start);
14000b57cec5SDimitry Andric         if (end != std::string::npos) {
14010b57cec5SDimitry Andric           std::string value = stop_info_str.substr(start, end - start);
14020b57cec5SDimitry Andric           UpdateThreadPCsFromStopReplyThreadsValue(value);
14030b57cec5SDimitry Andric         }
14040b57cec5SDimitry Andric       }
14050b57cec5SDimitry Andric 
14060b57cec5SDimitry Andric       const size_t threads_pos = stop_info_str.find(";threads:");
14070b57cec5SDimitry Andric       if (threads_pos != std::string::npos) {
14080b57cec5SDimitry Andric         const size_t start = threads_pos + strlen(";threads:");
14090b57cec5SDimitry Andric         const size_t end = stop_info_str.find(';', start);
14100b57cec5SDimitry Andric         if (end != std::string::npos) {
14110b57cec5SDimitry Andric           std::string value = stop_info_str.substr(start, end - start);
14120b57cec5SDimitry Andric           if (UpdateThreadIDsFromStopReplyThreadsValue(value))
14130b57cec5SDimitry Andric             return true;
14140b57cec5SDimitry Andric         }
14150b57cec5SDimitry Andric       }
14160b57cec5SDimitry Andric     }
14170b57cec5SDimitry Andric   }
14180b57cec5SDimitry Andric 
14190b57cec5SDimitry Andric   bool sequence_mutex_unavailable = false;
14200b57cec5SDimitry Andric   m_gdb_comm.GetCurrentThreadIDs(m_thread_ids, sequence_mutex_unavailable);
14210b57cec5SDimitry Andric   if (sequence_mutex_unavailable) {
14220b57cec5SDimitry Andric     return false; // We just didn't get the list
14230b57cec5SDimitry Andric   }
14240b57cec5SDimitry Andric   return true;
14250b57cec5SDimitry Andric }
14260b57cec5SDimitry Andric 
1427e8d8bef9SDimitry Andric bool ProcessGDBRemote::DoUpdateThreadList(ThreadList &old_thread_list,
14280b57cec5SDimitry Andric                                           ThreadList &new_thread_list) {
14290b57cec5SDimitry Andric   // locker will keep a mutex locked until it goes out of scope
14300b57cec5SDimitry Andric   Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_THREAD));
14310b57cec5SDimitry Andric   LLDB_LOGV(log, "pid = {0}", GetID());
14320b57cec5SDimitry Andric 
14330b57cec5SDimitry Andric   size_t num_thread_ids = m_thread_ids.size();
14340b57cec5SDimitry Andric   // The "m_thread_ids" thread ID list should always be updated after each stop
14350b57cec5SDimitry Andric   // reply packet, but in case it isn't, update it here.
14360b57cec5SDimitry Andric   if (num_thread_ids == 0) {
14370b57cec5SDimitry Andric     if (!UpdateThreadIDList())
14380b57cec5SDimitry Andric       return false;
14390b57cec5SDimitry Andric     num_thread_ids = m_thread_ids.size();
14400b57cec5SDimitry Andric   }
14410b57cec5SDimitry Andric 
14420b57cec5SDimitry Andric   ThreadList old_thread_list_copy(old_thread_list);
14430b57cec5SDimitry Andric   if (num_thread_ids > 0) {
14440b57cec5SDimitry Andric     for (size_t i = 0; i < num_thread_ids; ++i) {
14450b57cec5SDimitry Andric       tid_t tid = m_thread_ids[i];
14460b57cec5SDimitry Andric       ThreadSP thread_sp(
14470b57cec5SDimitry Andric           old_thread_list_copy.RemoveThreadByProtocolID(tid, false));
14480b57cec5SDimitry Andric       if (!thread_sp) {
14490b57cec5SDimitry Andric         thread_sp = std::make_shared<ThreadGDBRemote>(*this, tid);
14500b57cec5SDimitry Andric         LLDB_LOGV(log, "Making new thread: {0} for thread ID: {1:x}.",
14510b57cec5SDimitry Andric                   thread_sp.get(), thread_sp->GetID());
14520b57cec5SDimitry Andric       } else {
14530b57cec5SDimitry Andric         LLDB_LOGV(log, "Found old thread: {0} for thread ID: {1:x}.",
14540b57cec5SDimitry Andric                   thread_sp.get(), thread_sp->GetID());
14550b57cec5SDimitry Andric       }
14560b57cec5SDimitry Andric 
14570b57cec5SDimitry Andric       SetThreadPc(thread_sp, i);
14580b57cec5SDimitry Andric       new_thread_list.AddThreadSortedByIndexID(thread_sp);
14590b57cec5SDimitry Andric     }
14600b57cec5SDimitry Andric   }
14610b57cec5SDimitry Andric 
14620b57cec5SDimitry Andric   // Whatever that is left in old_thread_list_copy are not present in
14630b57cec5SDimitry Andric   // new_thread_list. Remove non-existent threads from internal id table.
14640b57cec5SDimitry Andric   size_t old_num_thread_ids = old_thread_list_copy.GetSize(false);
14650b57cec5SDimitry Andric   for (size_t i = 0; i < old_num_thread_ids; i++) {
14660b57cec5SDimitry Andric     ThreadSP old_thread_sp(old_thread_list_copy.GetThreadAtIndex(i, false));
14670b57cec5SDimitry Andric     if (old_thread_sp) {
14680b57cec5SDimitry Andric       lldb::tid_t old_thread_id = old_thread_sp->GetProtocolID();
14690b57cec5SDimitry Andric       m_thread_id_to_index_id_map.erase(old_thread_id);
14700b57cec5SDimitry Andric     }
14710b57cec5SDimitry Andric   }
14720b57cec5SDimitry Andric 
14730b57cec5SDimitry Andric   return true;
14740b57cec5SDimitry Andric }
14750b57cec5SDimitry Andric 
14760b57cec5SDimitry Andric void ProcessGDBRemote::SetThreadPc(const ThreadSP &thread_sp, uint64_t index) {
14770b57cec5SDimitry Andric   if (m_thread_ids.size() == m_thread_pcs.size() && thread_sp.get() &&
14780b57cec5SDimitry Andric       GetByteOrder() != eByteOrderInvalid) {
14790b57cec5SDimitry Andric     ThreadGDBRemote *gdb_thread =
14800b57cec5SDimitry Andric         static_cast<ThreadGDBRemote *>(thread_sp.get());
14810b57cec5SDimitry Andric     RegisterContextSP reg_ctx_sp(thread_sp->GetRegisterContext());
14820b57cec5SDimitry Andric     if (reg_ctx_sp) {
14830b57cec5SDimitry Andric       uint32_t pc_regnum = reg_ctx_sp->ConvertRegisterKindToRegisterNumber(
14840b57cec5SDimitry Andric           eRegisterKindGeneric, LLDB_REGNUM_GENERIC_PC);
14850b57cec5SDimitry Andric       if (pc_regnum != LLDB_INVALID_REGNUM) {
14860b57cec5SDimitry Andric         gdb_thread->PrivateSetRegisterValue(pc_regnum, m_thread_pcs[index]);
14870b57cec5SDimitry Andric       }
14880b57cec5SDimitry Andric     }
14890b57cec5SDimitry Andric   }
14900b57cec5SDimitry Andric }
14910b57cec5SDimitry Andric 
14920b57cec5SDimitry Andric bool ProcessGDBRemote::GetThreadStopInfoFromJSON(
14930b57cec5SDimitry Andric     ThreadGDBRemote *thread, const StructuredData::ObjectSP &thread_infos_sp) {
14940b57cec5SDimitry Andric   // See if we got thread stop infos for all threads via the "jThreadsInfo"
14950b57cec5SDimitry Andric   // packet
14960b57cec5SDimitry Andric   if (thread_infos_sp) {
14970b57cec5SDimitry Andric     StructuredData::Array *thread_infos = thread_infos_sp->GetAsArray();
14980b57cec5SDimitry Andric     if (thread_infos) {
14990b57cec5SDimitry Andric       lldb::tid_t tid;
15000b57cec5SDimitry Andric       const size_t n = thread_infos->GetSize();
15010b57cec5SDimitry Andric       for (size_t i = 0; i < n; ++i) {
15020b57cec5SDimitry Andric         StructuredData::Dictionary *thread_dict =
15030b57cec5SDimitry Andric             thread_infos->GetItemAtIndex(i)->GetAsDictionary();
15040b57cec5SDimitry Andric         if (thread_dict) {
15050b57cec5SDimitry Andric           if (thread_dict->GetValueForKeyAsInteger<lldb::tid_t>(
15060b57cec5SDimitry Andric                   "tid", tid, LLDB_INVALID_THREAD_ID)) {
15070b57cec5SDimitry Andric             if (tid == thread->GetID())
15080b57cec5SDimitry Andric               return (bool)SetThreadStopInfo(thread_dict);
15090b57cec5SDimitry Andric           }
15100b57cec5SDimitry Andric         }
15110b57cec5SDimitry Andric       }
15120b57cec5SDimitry Andric     }
15130b57cec5SDimitry Andric   }
15140b57cec5SDimitry Andric   return false;
15150b57cec5SDimitry Andric }
15160b57cec5SDimitry Andric 
15170b57cec5SDimitry Andric bool ProcessGDBRemote::CalculateThreadStopInfo(ThreadGDBRemote *thread) {
15180b57cec5SDimitry Andric   // See if we got thread stop infos for all threads via the "jThreadsInfo"
15190b57cec5SDimitry Andric   // packet
15200b57cec5SDimitry Andric   if (GetThreadStopInfoFromJSON(thread, m_jthreadsinfo_sp))
15210b57cec5SDimitry Andric     return true;
15220b57cec5SDimitry Andric 
15230b57cec5SDimitry Andric   // See if we got thread stop info for any threads valid stop info reasons
15240b57cec5SDimitry Andric   // threads via the "jstopinfo" packet stop reply packet key/value pair?
15250b57cec5SDimitry Andric   if (m_jstopinfo_sp) {
15260b57cec5SDimitry Andric     // If we have "jstopinfo" then we have stop descriptions for all threads
15270b57cec5SDimitry Andric     // that have stop reasons, and if there is no entry for a thread, then it
15280b57cec5SDimitry Andric     // has no stop reason.
15290b57cec5SDimitry Andric     thread->GetRegisterContext()->InvalidateIfNeeded(true);
15300b57cec5SDimitry Andric     if (!GetThreadStopInfoFromJSON(thread, m_jstopinfo_sp)) {
15310b57cec5SDimitry Andric       thread->SetStopInfo(StopInfoSP());
15320b57cec5SDimitry Andric     }
15330b57cec5SDimitry Andric     return true;
15340b57cec5SDimitry Andric   }
15350b57cec5SDimitry Andric 
15360b57cec5SDimitry Andric   // Fall back to using the qThreadStopInfo packet
15370b57cec5SDimitry Andric   StringExtractorGDBRemote stop_packet;
15380b57cec5SDimitry Andric   if (GetGDBRemote().GetThreadStopInfo(thread->GetProtocolID(), stop_packet))
15390b57cec5SDimitry Andric     return SetThreadStopInfo(stop_packet) == eStateStopped;
15400b57cec5SDimitry Andric   return false;
15410b57cec5SDimitry Andric }
15420b57cec5SDimitry Andric 
15430b57cec5SDimitry Andric ThreadSP ProcessGDBRemote::SetThreadStopInfo(
15440b57cec5SDimitry Andric     lldb::tid_t tid, ExpeditedRegisterMap &expedited_register_map,
15450b57cec5SDimitry Andric     uint8_t signo, const std::string &thread_name, const std::string &reason,
15460b57cec5SDimitry Andric     const std::string &description, uint32_t exc_type,
15470b57cec5SDimitry Andric     const std::vector<addr_t> &exc_data, addr_t thread_dispatch_qaddr,
15480b57cec5SDimitry Andric     bool queue_vars_valid, // Set to true if queue_name, queue_kind and
15490b57cec5SDimitry Andric                            // queue_serial are valid
15500b57cec5SDimitry Andric     LazyBool associated_with_dispatch_queue, addr_t dispatch_queue_t,
15510b57cec5SDimitry Andric     std::string &queue_name, QueueKind queue_kind, uint64_t queue_serial) {
15520b57cec5SDimitry Andric   ThreadSP thread_sp;
15530b57cec5SDimitry Andric   if (tid != LLDB_INVALID_THREAD_ID) {
15540b57cec5SDimitry Andric     // Scope for "locker" below
15550b57cec5SDimitry Andric     {
15560b57cec5SDimitry Andric       // m_thread_list_real does have its own mutex, but we need to hold onto
15570b57cec5SDimitry Andric       // the mutex between the call to m_thread_list_real.FindThreadByID(...)
15580b57cec5SDimitry Andric       // and the m_thread_list_real.AddThread(...) so it doesn't change on us
15590b57cec5SDimitry Andric       std::lock_guard<std::recursive_mutex> guard(
15600b57cec5SDimitry Andric           m_thread_list_real.GetMutex());
15610b57cec5SDimitry Andric       thread_sp = m_thread_list_real.FindThreadByProtocolID(tid, false);
15620b57cec5SDimitry Andric 
15630b57cec5SDimitry Andric       if (!thread_sp) {
15640b57cec5SDimitry Andric         // Create the thread if we need to
15650b57cec5SDimitry Andric         thread_sp = std::make_shared<ThreadGDBRemote>(*this, tid);
15660b57cec5SDimitry Andric         m_thread_list_real.AddThread(thread_sp);
15670b57cec5SDimitry Andric       }
15680b57cec5SDimitry Andric     }
15690b57cec5SDimitry Andric 
15700b57cec5SDimitry Andric     if (thread_sp) {
15710b57cec5SDimitry Andric       ThreadGDBRemote *gdb_thread =
15720b57cec5SDimitry Andric           static_cast<ThreadGDBRemote *>(thread_sp.get());
1573fe6060f1SDimitry Andric       RegisterContextSP gdb_reg_ctx_sp(gdb_thread->GetRegisterContext());
1574fe6060f1SDimitry Andric 
1575fe6060f1SDimitry Andric       gdb_reg_ctx_sp->InvalidateIfNeeded(true);
15760b57cec5SDimitry Andric 
15770b57cec5SDimitry Andric       auto iter = std::find(m_thread_ids.begin(), m_thread_ids.end(), tid);
15780b57cec5SDimitry Andric       if (iter != m_thread_ids.end()) {
15790b57cec5SDimitry Andric         SetThreadPc(thread_sp, iter - m_thread_ids.begin());
15800b57cec5SDimitry Andric       }
15810b57cec5SDimitry Andric 
15820b57cec5SDimitry Andric       for (const auto &pair : expedited_register_map) {
15839dba64beSDimitry Andric         StringExtractor reg_value_extractor(pair.second);
15840b57cec5SDimitry Andric         DataBufferSP buffer_sp(new DataBufferHeap(
15850b57cec5SDimitry Andric             reg_value_extractor.GetStringRef().size() / 2, 0));
15860b57cec5SDimitry Andric         reg_value_extractor.GetHexBytes(buffer_sp->GetData(), '\xcc');
1587fe6060f1SDimitry Andric         uint32_t lldb_regnum =
1588fe6060f1SDimitry Andric             gdb_reg_ctx_sp->ConvertRegisterKindToRegisterNumber(
1589fe6060f1SDimitry Andric                 eRegisterKindProcessPlugin, pair.first);
1590fe6060f1SDimitry Andric         gdb_thread->PrivateSetRegisterValue(lldb_regnum, buffer_sp->GetData());
15910b57cec5SDimitry Andric       }
15920b57cec5SDimitry Andric 
1593e8d8bef9SDimitry Andric       // AArch64 SVE specific code below calls AArch64SVEReconfigure to update
1594e8d8bef9SDimitry Andric       // SVE register sizes and offsets if value of VG register has changed
1595e8d8bef9SDimitry Andric       // since last stop.
1596e8d8bef9SDimitry Andric       const ArchSpec &arch = GetTarget().GetArchitecture();
1597e8d8bef9SDimitry Andric       if (arch.IsValid() && arch.GetTriple().isAArch64()) {
1598e8d8bef9SDimitry Andric         GDBRemoteRegisterContext *reg_ctx_sp =
1599e8d8bef9SDimitry Andric             static_cast<GDBRemoteRegisterContext *>(
1600e8d8bef9SDimitry Andric                 gdb_thread->GetRegisterContext().get());
1601e8d8bef9SDimitry Andric 
1602e8d8bef9SDimitry Andric         if (reg_ctx_sp)
1603e8d8bef9SDimitry Andric           reg_ctx_sp->AArch64SVEReconfigure();
1604e8d8bef9SDimitry Andric       }
1605e8d8bef9SDimitry Andric 
16060b57cec5SDimitry Andric       thread_sp->SetName(thread_name.empty() ? nullptr : thread_name.c_str());
16070b57cec5SDimitry Andric 
16080b57cec5SDimitry Andric       gdb_thread->SetThreadDispatchQAddr(thread_dispatch_qaddr);
16090b57cec5SDimitry Andric       // Check if the GDB server was able to provide the queue name, kind and
16100b57cec5SDimitry Andric       // serial number
16110b57cec5SDimitry Andric       if (queue_vars_valid)
16120b57cec5SDimitry Andric         gdb_thread->SetQueueInfo(std::move(queue_name), queue_kind,
16130b57cec5SDimitry Andric                                  queue_serial, dispatch_queue_t,
16140b57cec5SDimitry Andric                                  associated_with_dispatch_queue);
16150b57cec5SDimitry Andric       else
16160b57cec5SDimitry Andric         gdb_thread->ClearQueueInfo();
16170b57cec5SDimitry Andric 
16180b57cec5SDimitry Andric       gdb_thread->SetAssociatedWithLibdispatchQueue(
16190b57cec5SDimitry Andric           associated_with_dispatch_queue);
16200b57cec5SDimitry Andric 
16210b57cec5SDimitry Andric       if (dispatch_queue_t != LLDB_INVALID_ADDRESS)
16220b57cec5SDimitry Andric         gdb_thread->SetQueueLibdispatchQueueAddress(dispatch_queue_t);
16230b57cec5SDimitry Andric 
16240b57cec5SDimitry Andric       // Make sure we update our thread stop reason just once
16250b57cec5SDimitry Andric       if (!thread_sp->StopInfoIsUpToDate()) {
16260b57cec5SDimitry Andric         thread_sp->SetStopInfo(StopInfoSP());
16270b57cec5SDimitry Andric         // If there's a memory thread backed by this thread, we need to use it
16280b57cec5SDimitry Andric         // to calculate StopInfo.
16290b57cec5SDimitry Andric         if (ThreadSP memory_thread_sp =
16300b57cec5SDimitry Andric                 m_thread_list.GetBackingThread(thread_sp))
16310b57cec5SDimitry Andric           thread_sp = memory_thread_sp;
16320b57cec5SDimitry Andric 
16330b57cec5SDimitry Andric         if (exc_type != 0) {
16340b57cec5SDimitry Andric           const size_t exc_data_size = exc_data.size();
16350b57cec5SDimitry Andric 
16360b57cec5SDimitry Andric           thread_sp->SetStopInfo(
16370b57cec5SDimitry Andric               StopInfoMachException::CreateStopReasonWithMachException(
16380b57cec5SDimitry Andric                   *thread_sp, exc_type, exc_data_size,
16390b57cec5SDimitry Andric                   exc_data_size >= 1 ? exc_data[0] : 0,
16400b57cec5SDimitry Andric                   exc_data_size >= 2 ? exc_data[1] : 0,
16410b57cec5SDimitry Andric                   exc_data_size >= 3 ? exc_data[2] : 0));
16420b57cec5SDimitry Andric         } else {
16430b57cec5SDimitry Andric           bool handled = false;
16440b57cec5SDimitry Andric           bool did_exec = false;
16450b57cec5SDimitry Andric           if (!reason.empty()) {
16460b57cec5SDimitry Andric             if (reason == "trace") {
16470b57cec5SDimitry Andric               addr_t pc = thread_sp->GetRegisterContext()->GetPC();
16480b57cec5SDimitry Andric               lldb::BreakpointSiteSP bp_site_sp = thread_sp->GetProcess()
16490b57cec5SDimitry Andric                                                       ->GetBreakpointSiteList()
16500b57cec5SDimitry Andric                                                       .FindByAddress(pc);
16510b57cec5SDimitry Andric 
16520b57cec5SDimitry Andric               // If the current pc is a breakpoint site then the StopInfo
16530b57cec5SDimitry Andric               // should be set to Breakpoint Otherwise, it will be set to
16540b57cec5SDimitry Andric               // Trace.
1655fe6060f1SDimitry Andric               if (bp_site_sp && bp_site_sp->ValidForThisThread(*thread_sp)) {
16560b57cec5SDimitry Andric                 thread_sp->SetStopInfo(
16570b57cec5SDimitry Andric                     StopInfo::CreateStopReasonWithBreakpointSiteID(
16580b57cec5SDimitry Andric                         *thread_sp, bp_site_sp->GetID()));
16590b57cec5SDimitry Andric               } else
16600b57cec5SDimitry Andric                 thread_sp->SetStopInfo(
16610b57cec5SDimitry Andric                     StopInfo::CreateStopReasonToTrace(*thread_sp));
16620b57cec5SDimitry Andric               handled = true;
16630b57cec5SDimitry Andric             } else if (reason == "breakpoint") {
16640b57cec5SDimitry Andric               addr_t pc = thread_sp->GetRegisterContext()->GetPC();
16650b57cec5SDimitry Andric               lldb::BreakpointSiteSP bp_site_sp = thread_sp->GetProcess()
16660b57cec5SDimitry Andric                                                       ->GetBreakpointSiteList()
16670b57cec5SDimitry Andric                                                       .FindByAddress(pc);
16680b57cec5SDimitry Andric               if (bp_site_sp) {
16690b57cec5SDimitry Andric                 // If the breakpoint is for this thread, then we'll report the
16700b57cec5SDimitry Andric                 // hit, but if it is for another thread, we can just report no
16710b57cec5SDimitry Andric                 // reason.  We don't need to worry about stepping over the
16720b57cec5SDimitry Andric                 // breakpoint here, that will be taken care of when the thread
16730b57cec5SDimitry Andric                 // resumes and notices that there's a breakpoint under the pc.
16740b57cec5SDimitry Andric                 handled = true;
1675fe6060f1SDimitry Andric                 if (bp_site_sp->ValidForThisThread(*thread_sp)) {
16760b57cec5SDimitry Andric                   thread_sp->SetStopInfo(
16770b57cec5SDimitry Andric                       StopInfo::CreateStopReasonWithBreakpointSiteID(
16780b57cec5SDimitry Andric                           *thread_sp, bp_site_sp->GetID()));
16790b57cec5SDimitry Andric                 } else {
16800b57cec5SDimitry Andric                   StopInfoSP invalid_stop_info_sp;
16810b57cec5SDimitry Andric                   thread_sp->SetStopInfo(invalid_stop_info_sp);
16820b57cec5SDimitry Andric                 }
16830b57cec5SDimitry Andric               }
16840b57cec5SDimitry Andric             } else if (reason == "trap") {
16850b57cec5SDimitry Andric               // Let the trap just use the standard signal stop reason below...
16860b57cec5SDimitry Andric             } else if (reason == "watchpoint") {
16870b57cec5SDimitry Andric               StringExtractor desc_extractor(description.c_str());
16880b57cec5SDimitry Andric               addr_t wp_addr = desc_extractor.GetU64(LLDB_INVALID_ADDRESS);
16890b57cec5SDimitry Andric               uint32_t wp_index = desc_extractor.GetU32(LLDB_INVALID_INDEX32);
16900b57cec5SDimitry Andric               addr_t wp_hit_addr = desc_extractor.GetU64(LLDB_INVALID_ADDRESS);
16910b57cec5SDimitry Andric               watch_id_t watch_id = LLDB_INVALID_WATCH_ID;
16920b57cec5SDimitry Andric               if (wp_addr != LLDB_INVALID_ADDRESS) {
16930b57cec5SDimitry Andric                 WatchpointSP wp_sp;
16940b57cec5SDimitry Andric                 ArchSpec::Core core = GetTarget().GetArchitecture().GetCore();
16950b57cec5SDimitry Andric                 if ((core >= ArchSpec::kCore_mips_first &&
16960b57cec5SDimitry Andric                      core <= ArchSpec::kCore_mips_last) ||
16970b57cec5SDimitry Andric                     (core >= ArchSpec::eCore_arm_generic &&
16980b57cec5SDimitry Andric                      core <= ArchSpec::eCore_arm_aarch64))
16990b57cec5SDimitry Andric                   wp_sp = GetTarget().GetWatchpointList().FindByAddress(
17000b57cec5SDimitry Andric                       wp_hit_addr);
17010b57cec5SDimitry Andric                 if (!wp_sp)
17020b57cec5SDimitry Andric                   wp_sp =
17030b57cec5SDimitry Andric                       GetTarget().GetWatchpointList().FindByAddress(wp_addr);
17040b57cec5SDimitry Andric                 if (wp_sp) {
17050b57cec5SDimitry Andric                   wp_sp->SetHardwareIndex(wp_index);
17060b57cec5SDimitry Andric                   watch_id = wp_sp->GetID();
17070b57cec5SDimitry Andric                 }
17080b57cec5SDimitry Andric               }
17090b57cec5SDimitry Andric               if (watch_id == LLDB_INVALID_WATCH_ID) {
17100b57cec5SDimitry Andric                 Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(
17110b57cec5SDimitry Andric                     GDBR_LOG_WATCHPOINTS));
17129dba64beSDimitry Andric                 LLDB_LOGF(log, "failed to find watchpoint");
17130b57cec5SDimitry Andric               }
17140b57cec5SDimitry Andric               thread_sp->SetStopInfo(StopInfo::CreateStopReasonWithWatchpointID(
17150b57cec5SDimitry Andric                   *thread_sp, watch_id, wp_hit_addr));
17160b57cec5SDimitry Andric               handled = true;
17170b57cec5SDimitry Andric             } else if (reason == "exception") {
17180b57cec5SDimitry Andric               thread_sp->SetStopInfo(StopInfo::CreateStopReasonWithException(
17190b57cec5SDimitry Andric                   *thread_sp, description.c_str()));
17200b57cec5SDimitry Andric               handled = true;
17210b57cec5SDimitry Andric             } else if (reason == "exec") {
17220b57cec5SDimitry Andric               did_exec = true;
17230b57cec5SDimitry Andric               thread_sp->SetStopInfo(
17240b57cec5SDimitry Andric                   StopInfo::CreateStopReasonWithExec(*thread_sp));
17250b57cec5SDimitry Andric               handled = true;
1726fe6060f1SDimitry Andric             } else if (reason == "processor trace") {
1727fe6060f1SDimitry Andric               thread_sp->SetStopInfo(StopInfo::CreateStopReasonProcessorTrace(
1728fe6060f1SDimitry Andric                   *thread_sp, description.c_str()));
1729349cc55cSDimitry Andric             } else if (reason == "fork") {
1730349cc55cSDimitry Andric               StringExtractor desc_extractor(description.c_str());
1731349cc55cSDimitry Andric               lldb::pid_t child_pid = desc_extractor.GetU64(
1732349cc55cSDimitry Andric                   LLDB_INVALID_PROCESS_ID);
1733349cc55cSDimitry Andric               lldb::tid_t child_tid = desc_extractor.GetU64(
1734349cc55cSDimitry Andric                   LLDB_INVALID_THREAD_ID);
1735349cc55cSDimitry Andric               thread_sp->SetStopInfo(StopInfo::CreateStopReasonFork(
1736349cc55cSDimitry Andric                   *thread_sp, child_pid, child_tid));
1737349cc55cSDimitry Andric               handled = true;
1738349cc55cSDimitry Andric             } else if (reason == "vfork") {
1739349cc55cSDimitry Andric               StringExtractor desc_extractor(description.c_str());
1740349cc55cSDimitry Andric               lldb::pid_t child_pid = desc_extractor.GetU64(
1741349cc55cSDimitry Andric                   LLDB_INVALID_PROCESS_ID);
1742349cc55cSDimitry Andric               lldb::tid_t child_tid = desc_extractor.GetU64(
1743349cc55cSDimitry Andric                   LLDB_INVALID_THREAD_ID);
1744349cc55cSDimitry Andric               thread_sp->SetStopInfo(StopInfo::CreateStopReasonVFork(
1745349cc55cSDimitry Andric                   *thread_sp, child_pid, child_tid));
1746349cc55cSDimitry Andric               handled = true;
1747349cc55cSDimitry Andric             } else if (reason == "vforkdone") {
1748349cc55cSDimitry Andric               thread_sp->SetStopInfo(
1749349cc55cSDimitry Andric                   StopInfo::CreateStopReasonVForkDone(*thread_sp));
1750349cc55cSDimitry Andric               handled = true;
17510b57cec5SDimitry Andric             }
17520b57cec5SDimitry Andric           } else if (!signo) {
17530b57cec5SDimitry Andric             addr_t pc = thread_sp->GetRegisterContext()->GetPC();
17540b57cec5SDimitry Andric             lldb::BreakpointSiteSP bp_site_sp =
17550b57cec5SDimitry Andric                 thread_sp->GetProcess()->GetBreakpointSiteList().FindByAddress(
17560b57cec5SDimitry Andric                     pc);
17570b57cec5SDimitry Andric 
17580b57cec5SDimitry Andric             // If the current pc is a breakpoint site then the StopInfo should
17590b57cec5SDimitry Andric             // be set to Breakpoint even though the remote stub did not set it
17600b57cec5SDimitry Andric             // as such. This can happen when the thread is involuntarily
17610b57cec5SDimitry Andric             // interrupted (e.g. due to stops on other threads) just as it is
17620b57cec5SDimitry Andric             // about to execute the breakpoint instruction.
1763fe6060f1SDimitry Andric             if (bp_site_sp && bp_site_sp->ValidForThisThread(*thread_sp)) {
17640b57cec5SDimitry Andric               thread_sp->SetStopInfo(
17650b57cec5SDimitry Andric                   StopInfo::CreateStopReasonWithBreakpointSiteID(
17660b57cec5SDimitry Andric                       *thread_sp, bp_site_sp->GetID()));
17670b57cec5SDimitry Andric               handled = true;
17680b57cec5SDimitry Andric             }
17690b57cec5SDimitry Andric           }
17700b57cec5SDimitry Andric 
17710b57cec5SDimitry Andric           if (!handled && signo && !did_exec) {
17720b57cec5SDimitry Andric             if (signo == SIGTRAP) {
17730b57cec5SDimitry Andric               // Currently we are going to assume SIGTRAP means we are either
17740b57cec5SDimitry Andric               // hitting a breakpoint or hardware single stepping.
17750b57cec5SDimitry Andric               handled = true;
17760b57cec5SDimitry Andric               addr_t pc = thread_sp->GetRegisterContext()->GetPC() +
17770b57cec5SDimitry Andric                           m_breakpoint_pc_offset;
17780b57cec5SDimitry Andric               lldb::BreakpointSiteSP bp_site_sp = thread_sp->GetProcess()
17790b57cec5SDimitry Andric                                                       ->GetBreakpointSiteList()
17800b57cec5SDimitry Andric                                                       .FindByAddress(pc);
17810b57cec5SDimitry Andric 
17820b57cec5SDimitry Andric               if (bp_site_sp) {
17830b57cec5SDimitry Andric                 // If the breakpoint is for this thread, then we'll report the
17840b57cec5SDimitry Andric                 // hit, but if it is for another thread, we can just report no
17850b57cec5SDimitry Andric                 // reason.  We don't need to worry about stepping over the
17860b57cec5SDimitry Andric                 // breakpoint here, that will be taken care of when the thread
17870b57cec5SDimitry Andric                 // resumes and notices that there's a breakpoint under the pc.
1788fe6060f1SDimitry Andric                 if (bp_site_sp->ValidForThisThread(*thread_sp)) {
17890b57cec5SDimitry Andric                   if (m_breakpoint_pc_offset != 0)
17900b57cec5SDimitry Andric                     thread_sp->GetRegisterContext()->SetPC(pc);
17910b57cec5SDimitry Andric                   thread_sp->SetStopInfo(
17920b57cec5SDimitry Andric                       StopInfo::CreateStopReasonWithBreakpointSiteID(
17930b57cec5SDimitry Andric                           *thread_sp, bp_site_sp->GetID()));
17940b57cec5SDimitry Andric                 } else {
17950b57cec5SDimitry Andric                   StopInfoSP invalid_stop_info_sp;
17960b57cec5SDimitry Andric                   thread_sp->SetStopInfo(invalid_stop_info_sp);
17970b57cec5SDimitry Andric                 }
17980b57cec5SDimitry Andric               } else {
17990b57cec5SDimitry Andric                 // If we were stepping then assume the stop was the result of
18000b57cec5SDimitry Andric                 // the trace.  If we were not stepping then report the SIGTRAP.
18010b57cec5SDimitry Andric                 // FIXME: We are still missing the case where we single step
18020b57cec5SDimitry Andric                 // over a trap instruction.
18030b57cec5SDimitry Andric                 if (thread_sp->GetTemporaryResumeState() == eStateStepping)
18040b57cec5SDimitry Andric                   thread_sp->SetStopInfo(
18050b57cec5SDimitry Andric                       StopInfo::CreateStopReasonToTrace(*thread_sp));
18060b57cec5SDimitry Andric                 else
18070b57cec5SDimitry Andric                   thread_sp->SetStopInfo(StopInfo::CreateStopReasonWithSignal(
18080b57cec5SDimitry Andric                       *thread_sp, signo, description.c_str()));
18090b57cec5SDimitry Andric               }
18100b57cec5SDimitry Andric             }
18110b57cec5SDimitry Andric             if (!handled)
18120b57cec5SDimitry Andric               thread_sp->SetStopInfo(StopInfo::CreateStopReasonWithSignal(
18130b57cec5SDimitry Andric                   *thread_sp, signo, description.c_str()));
18140b57cec5SDimitry Andric           }
18150b57cec5SDimitry Andric 
18160b57cec5SDimitry Andric           if (!description.empty()) {
18170b57cec5SDimitry Andric             lldb::StopInfoSP stop_info_sp(thread_sp->GetStopInfo());
18180b57cec5SDimitry Andric             if (stop_info_sp) {
18190b57cec5SDimitry Andric               const char *stop_info_desc = stop_info_sp->GetDescription();
18200b57cec5SDimitry Andric               if (!stop_info_desc || !stop_info_desc[0])
18210b57cec5SDimitry Andric                 stop_info_sp->SetDescription(description.c_str());
18220b57cec5SDimitry Andric             } else {
18230b57cec5SDimitry Andric               thread_sp->SetStopInfo(StopInfo::CreateStopReasonWithException(
18240b57cec5SDimitry Andric                   *thread_sp, description.c_str()));
18250b57cec5SDimitry Andric             }
18260b57cec5SDimitry Andric           }
18270b57cec5SDimitry Andric         }
18280b57cec5SDimitry Andric       }
18290b57cec5SDimitry Andric     }
18300b57cec5SDimitry Andric   }
18310b57cec5SDimitry Andric   return thread_sp;
18320b57cec5SDimitry Andric }
18330b57cec5SDimitry Andric 
18340b57cec5SDimitry Andric lldb::ThreadSP
18350b57cec5SDimitry Andric ProcessGDBRemote::SetThreadStopInfo(StructuredData::Dictionary *thread_dict) {
18360b57cec5SDimitry Andric   static ConstString g_key_tid("tid");
18370b57cec5SDimitry Andric   static ConstString g_key_name("name");
18380b57cec5SDimitry Andric   static ConstString g_key_reason("reason");
18390b57cec5SDimitry Andric   static ConstString g_key_metype("metype");
18400b57cec5SDimitry Andric   static ConstString g_key_medata("medata");
18410b57cec5SDimitry Andric   static ConstString g_key_qaddr("qaddr");
18420b57cec5SDimitry Andric   static ConstString g_key_dispatch_queue_t("dispatch_queue_t");
18430b57cec5SDimitry Andric   static ConstString g_key_associated_with_dispatch_queue(
18440b57cec5SDimitry Andric       "associated_with_dispatch_queue");
18450b57cec5SDimitry Andric   static ConstString g_key_queue_name("qname");
18460b57cec5SDimitry Andric   static ConstString g_key_queue_kind("qkind");
18470b57cec5SDimitry Andric   static ConstString g_key_queue_serial_number("qserialnum");
18480b57cec5SDimitry Andric   static ConstString g_key_registers("registers");
18490b57cec5SDimitry Andric   static ConstString g_key_memory("memory");
18500b57cec5SDimitry Andric   static ConstString g_key_address("address");
18510b57cec5SDimitry Andric   static ConstString g_key_bytes("bytes");
18520b57cec5SDimitry Andric   static ConstString g_key_description("description");
18530b57cec5SDimitry Andric   static ConstString g_key_signal("signal");
18540b57cec5SDimitry Andric 
18550b57cec5SDimitry Andric   // Stop with signal and thread info
18560b57cec5SDimitry Andric   lldb::tid_t tid = LLDB_INVALID_THREAD_ID;
18570b57cec5SDimitry Andric   uint8_t signo = 0;
18580b57cec5SDimitry Andric   std::string value;
18590b57cec5SDimitry Andric   std::string thread_name;
18600b57cec5SDimitry Andric   std::string reason;
18610b57cec5SDimitry Andric   std::string description;
18620b57cec5SDimitry Andric   uint32_t exc_type = 0;
18630b57cec5SDimitry Andric   std::vector<addr_t> exc_data;
18640b57cec5SDimitry Andric   addr_t thread_dispatch_qaddr = LLDB_INVALID_ADDRESS;
18650b57cec5SDimitry Andric   ExpeditedRegisterMap expedited_register_map;
18660b57cec5SDimitry Andric   bool queue_vars_valid = false;
18670b57cec5SDimitry Andric   addr_t dispatch_queue_t = LLDB_INVALID_ADDRESS;
18680b57cec5SDimitry Andric   LazyBool associated_with_dispatch_queue = eLazyBoolCalculate;
18690b57cec5SDimitry Andric   std::string queue_name;
18700b57cec5SDimitry Andric   QueueKind queue_kind = eQueueKindUnknown;
18710b57cec5SDimitry Andric   uint64_t queue_serial_number = 0;
18720b57cec5SDimitry Andric   // Iterate through all of the thread dictionary key/value pairs from the
18730b57cec5SDimitry Andric   // structured data dictionary
18740b57cec5SDimitry Andric 
1875349cc55cSDimitry Andric   // FIXME: we're silently ignoring invalid data here
18760b57cec5SDimitry Andric   thread_dict->ForEach([this, &tid, &expedited_register_map, &thread_name,
18770b57cec5SDimitry Andric                         &signo, &reason, &description, &exc_type, &exc_data,
18780b57cec5SDimitry Andric                         &thread_dispatch_qaddr, &queue_vars_valid,
18790b57cec5SDimitry Andric                         &associated_with_dispatch_queue, &dispatch_queue_t,
18800b57cec5SDimitry Andric                         &queue_name, &queue_kind, &queue_serial_number](
18810b57cec5SDimitry Andric                            ConstString key,
18820b57cec5SDimitry Andric                            StructuredData::Object *object) -> bool {
18830b57cec5SDimitry Andric     if (key == g_key_tid) {
18840b57cec5SDimitry Andric       // thread in big endian hex
18850b57cec5SDimitry Andric       tid = object->GetIntegerValue(LLDB_INVALID_THREAD_ID);
18860b57cec5SDimitry Andric     } else if (key == g_key_metype) {
18870b57cec5SDimitry Andric       // exception type in big endian hex
18880b57cec5SDimitry Andric       exc_type = object->GetIntegerValue(0);
18890b57cec5SDimitry Andric     } else if (key == g_key_medata) {
18900b57cec5SDimitry Andric       // exception data in big endian hex
18910b57cec5SDimitry Andric       StructuredData::Array *array = object->GetAsArray();
18920b57cec5SDimitry Andric       if (array) {
18930b57cec5SDimitry Andric         array->ForEach([&exc_data](StructuredData::Object *object) -> bool {
18940b57cec5SDimitry Andric           exc_data.push_back(object->GetIntegerValue());
18950b57cec5SDimitry Andric           return true; // Keep iterating through all array items
18960b57cec5SDimitry Andric         });
18970b57cec5SDimitry Andric       }
18980b57cec5SDimitry Andric     } else if (key == g_key_name) {
18995ffd83dbSDimitry Andric       thread_name = std::string(object->GetStringValue());
19000b57cec5SDimitry Andric     } else if (key == g_key_qaddr) {
19010b57cec5SDimitry Andric       thread_dispatch_qaddr = object->GetIntegerValue(LLDB_INVALID_ADDRESS);
19020b57cec5SDimitry Andric     } else if (key == g_key_queue_name) {
19030b57cec5SDimitry Andric       queue_vars_valid = true;
19045ffd83dbSDimitry Andric       queue_name = std::string(object->GetStringValue());
19050b57cec5SDimitry Andric     } else if (key == g_key_queue_kind) {
19065ffd83dbSDimitry Andric       std::string queue_kind_str = std::string(object->GetStringValue());
19070b57cec5SDimitry Andric       if (queue_kind_str == "serial") {
19080b57cec5SDimitry Andric         queue_vars_valid = true;
19090b57cec5SDimitry Andric         queue_kind = eQueueKindSerial;
19100b57cec5SDimitry Andric       } else if (queue_kind_str == "concurrent") {
19110b57cec5SDimitry Andric         queue_vars_valid = true;
19120b57cec5SDimitry Andric         queue_kind = eQueueKindConcurrent;
19130b57cec5SDimitry Andric       }
19140b57cec5SDimitry Andric     } else if (key == g_key_queue_serial_number) {
19150b57cec5SDimitry Andric       queue_serial_number = object->GetIntegerValue(0);
19160b57cec5SDimitry Andric       if (queue_serial_number != 0)
19170b57cec5SDimitry Andric         queue_vars_valid = true;
19180b57cec5SDimitry Andric     } else if (key == g_key_dispatch_queue_t) {
19190b57cec5SDimitry Andric       dispatch_queue_t = object->GetIntegerValue(0);
19200b57cec5SDimitry Andric       if (dispatch_queue_t != 0 && dispatch_queue_t != LLDB_INVALID_ADDRESS)
19210b57cec5SDimitry Andric         queue_vars_valid = true;
19220b57cec5SDimitry Andric     } else if (key == g_key_associated_with_dispatch_queue) {
19230b57cec5SDimitry Andric       queue_vars_valid = true;
19240b57cec5SDimitry Andric       bool associated = object->GetBooleanValue();
19250b57cec5SDimitry Andric       if (associated)
19260b57cec5SDimitry Andric         associated_with_dispatch_queue = eLazyBoolYes;
19270b57cec5SDimitry Andric       else
19280b57cec5SDimitry Andric         associated_with_dispatch_queue = eLazyBoolNo;
19290b57cec5SDimitry Andric     } else if (key == g_key_reason) {
19305ffd83dbSDimitry Andric       reason = std::string(object->GetStringValue());
19310b57cec5SDimitry Andric     } else if (key == g_key_description) {
19325ffd83dbSDimitry Andric       description = std::string(object->GetStringValue());
19330b57cec5SDimitry Andric     } else if (key == g_key_registers) {
19340b57cec5SDimitry Andric       StructuredData::Dictionary *registers_dict = object->GetAsDictionary();
19350b57cec5SDimitry Andric 
19360b57cec5SDimitry Andric       if (registers_dict) {
19370b57cec5SDimitry Andric         registers_dict->ForEach(
19380b57cec5SDimitry Andric             [&expedited_register_map](ConstString key,
19390b57cec5SDimitry Andric                                       StructuredData::Object *object) -> bool {
1940349cc55cSDimitry Andric               uint32_t reg;
1941349cc55cSDimitry Andric               if (llvm::to_integer(key.AsCString(), reg))
19425ffd83dbSDimitry Andric                 expedited_register_map[reg] =
19435ffd83dbSDimitry Andric                     std::string(object->GetStringValue());
19440b57cec5SDimitry Andric               return true; // Keep iterating through all array items
19450b57cec5SDimitry Andric             });
19460b57cec5SDimitry Andric       }
19470b57cec5SDimitry Andric     } else if (key == g_key_memory) {
19480b57cec5SDimitry Andric       StructuredData::Array *array = object->GetAsArray();
19490b57cec5SDimitry Andric       if (array) {
19500b57cec5SDimitry Andric         array->ForEach([this](StructuredData::Object *object) -> bool {
19510b57cec5SDimitry Andric           StructuredData::Dictionary *mem_cache_dict =
19520b57cec5SDimitry Andric               object->GetAsDictionary();
19530b57cec5SDimitry Andric           if (mem_cache_dict) {
19540b57cec5SDimitry Andric             lldb::addr_t mem_cache_addr = LLDB_INVALID_ADDRESS;
19550b57cec5SDimitry Andric             if (mem_cache_dict->GetValueForKeyAsInteger<lldb::addr_t>(
19560b57cec5SDimitry Andric                     "address", mem_cache_addr)) {
19570b57cec5SDimitry Andric               if (mem_cache_addr != LLDB_INVALID_ADDRESS) {
19580b57cec5SDimitry Andric                 llvm::StringRef str;
19590b57cec5SDimitry Andric                 if (mem_cache_dict->GetValueForKeyAsString("bytes", str)) {
19600b57cec5SDimitry Andric                   StringExtractor bytes(str);
19610b57cec5SDimitry Andric                   bytes.SetFilePos(0);
19620b57cec5SDimitry Andric 
19630b57cec5SDimitry Andric                   const size_t byte_size = bytes.GetStringRef().size() / 2;
19640b57cec5SDimitry Andric                   DataBufferSP data_buffer_sp(new DataBufferHeap(byte_size, 0));
19650b57cec5SDimitry Andric                   const size_t bytes_copied =
19660b57cec5SDimitry Andric                       bytes.GetHexBytes(data_buffer_sp->GetData(), 0);
19670b57cec5SDimitry Andric                   if (bytes_copied == byte_size)
19680b57cec5SDimitry Andric                     m_memory_cache.AddL1CacheData(mem_cache_addr,
19690b57cec5SDimitry Andric                                                   data_buffer_sp);
19700b57cec5SDimitry Andric                 }
19710b57cec5SDimitry Andric               }
19720b57cec5SDimitry Andric             }
19730b57cec5SDimitry Andric           }
19740b57cec5SDimitry Andric           return true; // Keep iterating through all array items
19750b57cec5SDimitry Andric         });
19760b57cec5SDimitry Andric       }
19770b57cec5SDimitry Andric 
19780b57cec5SDimitry Andric     } else if (key == g_key_signal)
19790b57cec5SDimitry Andric       signo = object->GetIntegerValue(LLDB_INVALID_SIGNAL_NUMBER);
19800b57cec5SDimitry Andric     return true; // Keep iterating through all dictionary key/value pairs
19810b57cec5SDimitry Andric   });
19820b57cec5SDimitry Andric 
19830b57cec5SDimitry Andric   return SetThreadStopInfo(tid, expedited_register_map, signo, thread_name,
19840b57cec5SDimitry Andric                            reason, description, exc_type, exc_data,
19850b57cec5SDimitry Andric                            thread_dispatch_qaddr, queue_vars_valid,
19860b57cec5SDimitry Andric                            associated_with_dispatch_queue, dispatch_queue_t,
19870b57cec5SDimitry Andric                            queue_name, queue_kind, queue_serial_number);
19880b57cec5SDimitry Andric }
19890b57cec5SDimitry Andric 
19900b57cec5SDimitry Andric StateType ProcessGDBRemote::SetThreadStopInfo(StringExtractor &stop_packet) {
1991fe6060f1SDimitry Andric   lldb::pid_t pid = m_gdb_comm.GetCurrentProcessID();
19920b57cec5SDimitry Andric   stop_packet.SetFilePos(0);
19930b57cec5SDimitry Andric   const char stop_type = stop_packet.GetChar();
19940b57cec5SDimitry Andric   switch (stop_type) {
19950b57cec5SDimitry Andric   case 'T':
19960b57cec5SDimitry Andric   case 'S': {
19970b57cec5SDimitry Andric     // This is a bit of a hack, but is is required. If we did exec, we need to
19980b57cec5SDimitry Andric     // clear our thread lists and also know to rebuild our dynamic register
19990b57cec5SDimitry Andric     // info before we lookup and threads and populate the expedited register
20000b57cec5SDimitry Andric     // values so we need to know this right away so we can cleanup and update
20010b57cec5SDimitry Andric     // our registers.
20020b57cec5SDimitry Andric     const uint32_t stop_id = GetStopID();
20030b57cec5SDimitry Andric     if (stop_id == 0) {
20040b57cec5SDimitry Andric       // Our first stop, make sure we have a process ID, and also make sure we
20050b57cec5SDimitry Andric       // know about our registers
2006fe6060f1SDimitry Andric       if (GetID() == LLDB_INVALID_PROCESS_ID && pid != LLDB_INVALID_PROCESS_ID)
20070b57cec5SDimitry Andric         SetID(pid);
20080b57cec5SDimitry Andric       BuildDynamicRegisterInfo(true);
20090b57cec5SDimitry Andric     }
20100b57cec5SDimitry Andric     // Stop with signal and thread info
2011fe6060f1SDimitry Andric     lldb::pid_t stop_pid = LLDB_INVALID_PROCESS_ID;
20120b57cec5SDimitry Andric     lldb::tid_t tid = LLDB_INVALID_THREAD_ID;
20130b57cec5SDimitry Andric     const uint8_t signo = stop_packet.GetHexU8();
20140b57cec5SDimitry Andric     llvm::StringRef key;
20150b57cec5SDimitry Andric     llvm::StringRef value;
20160b57cec5SDimitry Andric     std::string thread_name;
20170b57cec5SDimitry Andric     std::string reason;
20180b57cec5SDimitry Andric     std::string description;
20190b57cec5SDimitry Andric     uint32_t exc_type = 0;
20200b57cec5SDimitry Andric     std::vector<addr_t> exc_data;
20210b57cec5SDimitry Andric     addr_t thread_dispatch_qaddr = LLDB_INVALID_ADDRESS;
20220b57cec5SDimitry Andric     bool queue_vars_valid =
20230b57cec5SDimitry Andric         false; // says if locals below that start with "queue_" are valid
20240b57cec5SDimitry Andric     addr_t dispatch_queue_t = LLDB_INVALID_ADDRESS;
20250b57cec5SDimitry Andric     LazyBool associated_with_dispatch_queue = eLazyBoolCalculate;
20260b57cec5SDimitry Andric     std::string queue_name;
20270b57cec5SDimitry Andric     QueueKind queue_kind = eQueueKindUnknown;
20280b57cec5SDimitry Andric     uint64_t queue_serial_number = 0;
20290b57cec5SDimitry Andric     ExpeditedRegisterMap expedited_register_map;
20300b57cec5SDimitry Andric     while (stop_packet.GetNameColonValue(key, value)) {
20310b57cec5SDimitry Andric       if (key.compare("metype") == 0) {
20320b57cec5SDimitry Andric         // exception type in big endian hex
20330b57cec5SDimitry Andric         value.getAsInteger(16, exc_type);
20340b57cec5SDimitry Andric       } else if (key.compare("medata") == 0) {
20350b57cec5SDimitry Andric         // exception data in big endian hex
20360b57cec5SDimitry Andric         uint64_t x;
20370b57cec5SDimitry Andric         value.getAsInteger(16, x);
20380b57cec5SDimitry Andric         exc_data.push_back(x);
20390b57cec5SDimitry Andric       } else if (key.compare("thread") == 0) {
2040fe6060f1SDimitry Andric         // thread-id
2041fe6060f1SDimitry Andric         StringExtractorGDBRemote thread_id{value};
2042fe6060f1SDimitry Andric         auto pid_tid = thread_id.GetPidTid(pid);
2043fe6060f1SDimitry Andric         if (pid_tid) {
2044fe6060f1SDimitry Andric           stop_pid = pid_tid->first;
2045fe6060f1SDimitry Andric           tid = pid_tid->second;
2046fe6060f1SDimitry Andric         } else
20470b57cec5SDimitry Andric           tid = LLDB_INVALID_THREAD_ID;
20480b57cec5SDimitry Andric       } else if (key.compare("threads") == 0) {
20490b57cec5SDimitry Andric         std::lock_guard<std::recursive_mutex> guard(
20500b57cec5SDimitry Andric             m_thread_list_real.GetMutex());
2051fe6060f1SDimitry Andric         UpdateThreadIDsFromStopReplyThreadsValue(value);
20520b57cec5SDimitry Andric       } else if (key.compare("thread-pcs") == 0) {
20530b57cec5SDimitry Andric         m_thread_pcs.clear();
20540b57cec5SDimitry Andric         // A comma separated list of all threads in the current
20550b57cec5SDimitry Andric         // process that includes the thread for this stop reply packet
20560b57cec5SDimitry Andric         lldb::addr_t pc;
20570b57cec5SDimitry Andric         while (!value.empty()) {
20580b57cec5SDimitry Andric           llvm::StringRef pc_str;
20590b57cec5SDimitry Andric           std::tie(pc_str, value) = value.split(',');
20600b57cec5SDimitry Andric           if (pc_str.getAsInteger(16, pc))
20610b57cec5SDimitry Andric             pc = LLDB_INVALID_ADDRESS;
20620b57cec5SDimitry Andric           m_thread_pcs.push_back(pc);
20630b57cec5SDimitry Andric         }
20640b57cec5SDimitry Andric       } else if (key.compare("jstopinfo") == 0) {
20650b57cec5SDimitry Andric         StringExtractor json_extractor(value);
20660b57cec5SDimitry Andric         std::string json;
20670b57cec5SDimitry Andric         // Now convert the HEX bytes into a string value
20680b57cec5SDimitry Andric         json_extractor.GetHexByteString(json);
20690b57cec5SDimitry Andric 
20700b57cec5SDimitry Andric         // This JSON contains thread IDs and thread stop info for all threads.
20710b57cec5SDimitry Andric         // It doesn't contain expedited registers, memory or queue info.
20720b57cec5SDimitry Andric         m_jstopinfo_sp = StructuredData::ParseJSON(json);
20730b57cec5SDimitry Andric       } else if (key.compare("hexname") == 0) {
20740b57cec5SDimitry Andric         StringExtractor name_extractor(value);
20750b57cec5SDimitry Andric         std::string name;
20760b57cec5SDimitry Andric         // Now convert the HEX bytes into a string value
20770b57cec5SDimitry Andric         name_extractor.GetHexByteString(thread_name);
20780b57cec5SDimitry Andric       } else if (key.compare("name") == 0) {
20795ffd83dbSDimitry Andric         thread_name = std::string(value);
20800b57cec5SDimitry Andric       } else if (key.compare("qaddr") == 0) {
20810b57cec5SDimitry Andric         value.getAsInteger(16, thread_dispatch_qaddr);
20820b57cec5SDimitry Andric       } else if (key.compare("dispatch_queue_t") == 0) {
20830b57cec5SDimitry Andric         queue_vars_valid = true;
20840b57cec5SDimitry Andric         value.getAsInteger(16, dispatch_queue_t);
20850b57cec5SDimitry Andric       } else if (key.compare("qname") == 0) {
20860b57cec5SDimitry Andric         queue_vars_valid = true;
20870b57cec5SDimitry Andric         StringExtractor name_extractor(value);
20880b57cec5SDimitry Andric         // Now convert the HEX bytes into a string value
20890b57cec5SDimitry Andric         name_extractor.GetHexByteString(queue_name);
20900b57cec5SDimitry Andric       } else if (key.compare("qkind") == 0) {
20910b57cec5SDimitry Andric         queue_kind = llvm::StringSwitch<QueueKind>(value)
20920b57cec5SDimitry Andric                          .Case("serial", eQueueKindSerial)
20930b57cec5SDimitry Andric                          .Case("concurrent", eQueueKindConcurrent)
20940b57cec5SDimitry Andric                          .Default(eQueueKindUnknown);
20950b57cec5SDimitry Andric         queue_vars_valid = queue_kind != eQueueKindUnknown;
20960b57cec5SDimitry Andric       } else if (key.compare("qserialnum") == 0) {
20970b57cec5SDimitry Andric         if (!value.getAsInteger(0, queue_serial_number))
20980b57cec5SDimitry Andric           queue_vars_valid = true;
20990b57cec5SDimitry Andric       } else if (key.compare("reason") == 0) {
21005ffd83dbSDimitry Andric         reason = std::string(value);
21010b57cec5SDimitry Andric       } else if (key.compare("description") == 0) {
21020b57cec5SDimitry Andric         StringExtractor desc_extractor(value);
21030b57cec5SDimitry Andric         // Now convert the HEX bytes into a string value
21040b57cec5SDimitry Andric         desc_extractor.GetHexByteString(description);
21050b57cec5SDimitry Andric       } else if (key.compare("memory") == 0) {
21060b57cec5SDimitry Andric         // Expedited memory. GDB servers can choose to send back expedited
21070b57cec5SDimitry Andric         // memory that can populate the L1 memory cache in the process so that
21080b57cec5SDimitry Andric         // things like the frame pointer backchain can be expedited. This will
21090b57cec5SDimitry Andric         // help stack backtracing be more efficient by not having to send as
21100b57cec5SDimitry Andric         // many memory read requests down the remote GDB server.
21110b57cec5SDimitry Andric 
21120b57cec5SDimitry Andric         // Key/value pair format: memory:<addr>=<bytes>;
21130b57cec5SDimitry Andric         // <addr> is a number whose base will be interpreted by the prefix:
21140b57cec5SDimitry Andric         //      "0x[0-9a-fA-F]+" for hex
21150b57cec5SDimitry Andric         //      "0[0-7]+" for octal
21160b57cec5SDimitry Andric         //      "[1-9]+" for decimal
21170b57cec5SDimitry Andric         // <bytes> is native endian ASCII hex bytes just like the register
21180b57cec5SDimitry Andric         // values
21190b57cec5SDimitry Andric         llvm::StringRef addr_str, bytes_str;
21200b57cec5SDimitry Andric         std::tie(addr_str, bytes_str) = value.split('=');
21210b57cec5SDimitry Andric         if (!addr_str.empty() && !bytes_str.empty()) {
21220b57cec5SDimitry Andric           lldb::addr_t mem_cache_addr = LLDB_INVALID_ADDRESS;
21230b57cec5SDimitry Andric           if (!addr_str.getAsInteger(0, mem_cache_addr)) {
21240b57cec5SDimitry Andric             StringExtractor bytes(bytes_str);
21250b57cec5SDimitry Andric             const size_t byte_size = bytes.GetBytesLeft() / 2;
21260b57cec5SDimitry Andric             DataBufferSP data_buffer_sp(new DataBufferHeap(byte_size, 0));
21270b57cec5SDimitry Andric             const size_t bytes_copied =
21280b57cec5SDimitry Andric                 bytes.GetHexBytes(data_buffer_sp->GetData(), 0);
21290b57cec5SDimitry Andric             if (bytes_copied == byte_size)
21300b57cec5SDimitry Andric               m_memory_cache.AddL1CacheData(mem_cache_addr, data_buffer_sp);
21310b57cec5SDimitry Andric           }
21320b57cec5SDimitry Andric         }
21330b57cec5SDimitry Andric       } else if (key.compare("watch") == 0 || key.compare("rwatch") == 0 ||
21340b57cec5SDimitry Andric                  key.compare("awatch") == 0) {
21350b57cec5SDimitry Andric         // Support standard GDB remote stop reply packet 'TAAwatch:addr'
21360b57cec5SDimitry Andric         lldb::addr_t wp_addr = LLDB_INVALID_ADDRESS;
21370b57cec5SDimitry Andric         value.getAsInteger(16, wp_addr);
21380b57cec5SDimitry Andric 
21390b57cec5SDimitry Andric         WatchpointSP wp_sp =
21400b57cec5SDimitry Andric             GetTarget().GetWatchpointList().FindByAddress(wp_addr);
21410b57cec5SDimitry Andric         uint32_t wp_index = LLDB_INVALID_INDEX32;
21420b57cec5SDimitry Andric 
21430b57cec5SDimitry Andric         if (wp_sp)
21440b57cec5SDimitry Andric           wp_index = wp_sp->GetHardwareIndex();
21450b57cec5SDimitry Andric 
21460b57cec5SDimitry Andric         reason = "watchpoint";
21470b57cec5SDimitry Andric         StreamString ostr;
21480b57cec5SDimitry Andric         ostr.Printf("%" PRIu64 " %" PRIu32, wp_addr, wp_index);
21495ffd83dbSDimitry Andric         description = std::string(ostr.GetString());
21500b57cec5SDimitry Andric       } else if (key.compare("library") == 0) {
21519dba64beSDimitry Andric         auto error = LoadModules();
21529dba64beSDimitry Andric         if (error) {
21539dba64beSDimitry Andric           Log *log(
21549dba64beSDimitry Andric               ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
21559dba64beSDimitry Andric           LLDB_LOG_ERROR(log, std::move(error), "Failed to load modules: {0}");
21569dba64beSDimitry Andric         }
2157349cc55cSDimitry Andric       } else if (key.compare("fork") == 0 || key.compare("vfork") == 0) {
2158349cc55cSDimitry Andric         // fork includes child pid/tid in thread-id format
2159349cc55cSDimitry Andric         StringExtractorGDBRemote thread_id{value};
2160349cc55cSDimitry Andric         auto pid_tid = thread_id.GetPidTid(LLDB_INVALID_PROCESS_ID);
2161349cc55cSDimitry Andric         if (!pid_tid) {
2162349cc55cSDimitry Andric           Log *log(
2163349cc55cSDimitry Andric               ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
2164349cc55cSDimitry Andric           LLDB_LOG(log, "Invalid PID/TID to fork: {0}", value);
2165349cc55cSDimitry Andric           pid_tid = {{LLDB_INVALID_PROCESS_ID, LLDB_INVALID_THREAD_ID}};
2166349cc55cSDimitry Andric         }
2167349cc55cSDimitry Andric 
2168349cc55cSDimitry Andric         reason = key.str();
2169349cc55cSDimitry Andric         StreamString ostr;
2170349cc55cSDimitry Andric         ostr.Printf("%" PRIu64 " %" PRIu64, pid_tid->first, pid_tid->second);
2171349cc55cSDimitry Andric         description = std::string(ostr.GetString());
21720b57cec5SDimitry Andric       } else if (key.size() == 2 && ::isxdigit(key[0]) && ::isxdigit(key[1])) {
21730b57cec5SDimitry Andric         uint32_t reg = UINT32_MAX;
21740b57cec5SDimitry Andric         if (!key.getAsInteger(16, reg))
21755ffd83dbSDimitry Andric           expedited_register_map[reg] = std::string(std::move(value));
21760b57cec5SDimitry Andric       }
21770b57cec5SDimitry Andric     }
21780b57cec5SDimitry Andric 
2179fe6060f1SDimitry Andric     if (stop_pid != LLDB_INVALID_PROCESS_ID && stop_pid != pid) {
2180fe6060f1SDimitry Andric       Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
2181fe6060f1SDimitry Andric       LLDB_LOG(log,
2182fe6060f1SDimitry Andric                "Received stop for incorrect PID = {0} (inferior PID = {1})",
2183fe6060f1SDimitry Andric                stop_pid, pid);
2184fe6060f1SDimitry Andric       return eStateInvalid;
2185fe6060f1SDimitry Andric     }
2186fe6060f1SDimitry Andric 
21870b57cec5SDimitry Andric     if (tid == LLDB_INVALID_THREAD_ID) {
21880b57cec5SDimitry Andric       // A thread id may be invalid if the response is old style 'S' packet
21890b57cec5SDimitry Andric       // which does not provide the
21900b57cec5SDimitry Andric       // thread information. So update the thread list and choose the first
21910b57cec5SDimitry Andric       // one.
21920b57cec5SDimitry Andric       UpdateThreadIDList();
21930b57cec5SDimitry Andric 
21940b57cec5SDimitry Andric       if (!m_thread_ids.empty()) {
21950b57cec5SDimitry Andric         tid = m_thread_ids.front();
21960b57cec5SDimitry Andric       }
21970b57cec5SDimitry Andric     }
21980b57cec5SDimitry Andric 
21990b57cec5SDimitry Andric     ThreadSP thread_sp = SetThreadStopInfo(
22000b57cec5SDimitry Andric         tid, expedited_register_map, signo, thread_name, reason, description,
22010b57cec5SDimitry Andric         exc_type, exc_data, thread_dispatch_qaddr, queue_vars_valid,
22020b57cec5SDimitry Andric         associated_with_dispatch_queue, dispatch_queue_t, queue_name,
22030b57cec5SDimitry Andric         queue_kind, queue_serial_number);
22040b57cec5SDimitry Andric 
22050b57cec5SDimitry Andric     return eStateStopped;
22060b57cec5SDimitry Andric   } break;
22070b57cec5SDimitry Andric 
22080b57cec5SDimitry Andric   case 'W':
22090b57cec5SDimitry Andric   case 'X':
22100b57cec5SDimitry Andric     // process exited
22110b57cec5SDimitry Andric     return eStateExited;
22120b57cec5SDimitry Andric 
22130b57cec5SDimitry Andric   default:
22140b57cec5SDimitry Andric     break;
22150b57cec5SDimitry Andric   }
22160b57cec5SDimitry Andric   return eStateInvalid;
22170b57cec5SDimitry Andric }
22180b57cec5SDimitry Andric 
22190b57cec5SDimitry Andric void ProcessGDBRemote::RefreshStateAfterStop() {
22200b57cec5SDimitry Andric   std::lock_guard<std::recursive_mutex> guard(m_thread_list_real.GetMutex());
22210b57cec5SDimitry Andric 
22220b57cec5SDimitry Andric   m_thread_ids.clear();
22230b57cec5SDimitry Andric   m_thread_pcs.clear();
2224480093f4SDimitry Andric 
22250b57cec5SDimitry Andric   // Set the thread stop info. It might have a "threads" key whose value is a
22260b57cec5SDimitry Andric   // list of all thread IDs in the current process, so m_thread_ids might get
22270b57cec5SDimitry Andric   // set.
22280b57cec5SDimitry Andric   // Check to see if SetThreadStopInfo() filled in m_thread_ids?
22290b57cec5SDimitry Andric   if (m_thread_ids.empty()) {
22300b57cec5SDimitry Andric       // No, we need to fetch the thread list manually
22310b57cec5SDimitry Andric       UpdateThreadIDList();
22320b57cec5SDimitry Andric   }
2233480093f4SDimitry Andric 
22340b57cec5SDimitry Andric   // We might set some stop info's so make sure the thread list is up to
22350b57cec5SDimitry Andric   // date before we do that or we might overwrite what was computed here.
22360b57cec5SDimitry Andric   UpdateThreadListIfNeeded();
22370b57cec5SDimitry Andric 
2238349cc55cSDimitry Andric   if (m_last_stop_packet)
2239349cc55cSDimitry Andric     SetThreadStopInfo(*m_last_stop_packet);
2240349cc55cSDimitry Andric   m_last_stop_packet.reset();
22410b57cec5SDimitry Andric 
22420b57cec5SDimitry Andric   // If we have queried for a default thread id
22430b57cec5SDimitry Andric   if (m_initial_tid != LLDB_INVALID_THREAD_ID) {
22440b57cec5SDimitry Andric     m_thread_list.SetSelectedThreadByID(m_initial_tid);
22450b57cec5SDimitry Andric     m_initial_tid = LLDB_INVALID_THREAD_ID;
22460b57cec5SDimitry Andric   }
22470b57cec5SDimitry Andric 
22480b57cec5SDimitry Andric   // Let all threads recover from stopping and do any clean up based on the
22490b57cec5SDimitry Andric   // previous thread state (if any).
22500b57cec5SDimitry Andric   m_thread_list_real.RefreshStateAfterStop();
22510b57cec5SDimitry Andric }
22520b57cec5SDimitry Andric 
22530b57cec5SDimitry Andric Status ProcessGDBRemote::DoHalt(bool &caused_stop) {
22540b57cec5SDimitry Andric   Status error;
22550b57cec5SDimitry Andric 
22560b57cec5SDimitry Andric   if (m_public_state.GetValue() == eStateAttaching) {
22570b57cec5SDimitry Andric     // We are being asked to halt during an attach. We need to just close our
22580b57cec5SDimitry Andric     // file handle and debugserver will go away, and we can be done...
22590b57cec5SDimitry Andric     m_gdb_comm.Disconnect();
22600b57cec5SDimitry Andric   } else
2261fe6060f1SDimitry Andric     caused_stop = m_gdb_comm.Interrupt(GetInterruptTimeout());
22620b57cec5SDimitry Andric   return error;
22630b57cec5SDimitry Andric }
22640b57cec5SDimitry Andric 
22650b57cec5SDimitry Andric Status ProcessGDBRemote::DoDetach(bool keep_stopped) {
22660b57cec5SDimitry Andric   Status error;
22670b57cec5SDimitry Andric   Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
22689dba64beSDimitry Andric   LLDB_LOGF(log, "ProcessGDBRemote::DoDetach(keep_stopped: %i)", keep_stopped);
22690b57cec5SDimitry Andric 
22700b57cec5SDimitry Andric   error = m_gdb_comm.Detach(keep_stopped);
22710b57cec5SDimitry Andric   if (log) {
22720b57cec5SDimitry Andric     if (error.Success())
22730b57cec5SDimitry Andric       log->PutCString(
22740b57cec5SDimitry Andric           "ProcessGDBRemote::DoDetach() detach packet sent successfully");
22750b57cec5SDimitry Andric     else
22769dba64beSDimitry Andric       LLDB_LOGF(log,
22779dba64beSDimitry Andric                 "ProcessGDBRemote::DoDetach() detach packet send failed: %s",
22780b57cec5SDimitry Andric                 error.AsCString() ? error.AsCString() : "<unknown error>");
22790b57cec5SDimitry Andric   }
22800b57cec5SDimitry Andric 
22810b57cec5SDimitry Andric   if (!error.Success())
22820b57cec5SDimitry Andric     return error;
22830b57cec5SDimitry Andric 
22840b57cec5SDimitry Andric   // Sleep for one second to let the process get all detached...
22850b57cec5SDimitry Andric   StopAsyncThread();
22860b57cec5SDimitry Andric 
22870b57cec5SDimitry Andric   SetPrivateState(eStateDetached);
22880b57cec5SDimitry Andric   ResumePrivateStateThread();
22890b57cec5SDimitry Andric 
22900b57cec5SDimitry Andric   // KillDebugserverProcess ();
22910b57cec5SDimitry Andric   return error;
22920b57cec5SDimitry Andric }
22930b57cec5SDimitry Andric 
22940b57cec5SDimitry Andric Status ProcessGDBRemote::DoDestroy() {
22950b57cec5SDimitry Andric   Status error;
22960b57cec5SDimitry Andric   Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
22979dba64beSDimitry Andric   LLDB_LOGF(log, "ProcessGDBRemote::DoDestroy()");
22980b57cec5SDimitry Andric 
2299580012d6SDimitry Andric #ifdef LLDB_ENABLE_ALL // XXX Currently no iOS target support on FreeBSD
23000b57cec5SDimitry Andric   // There is a bug in older iOS debugservers where they don't shut down the
23010b57cec5SDimitry Andric   // process they are debugging properly.  If the process is sitting at a
23020b57cec5SDimitry Andric   // breakpoint or an exception, this can cause problems with restarting.  So
23030b57cec5SDimitry Andric   // we check to see if any of our threads are stopped at a breakpoint, and if
23040b57cec5SDimitry Andric   // so we remove all the breakpoints, resume the process, and THEN destroy it
23050b57cec5SDimitry Andric   // again.
23060b57cec5SDimitry Andric   //
23070b57cec5SDimitry Andric   // Note, we don't have a good way to test the version of debugserver, but I
23080b57cec5SDimitry Andric   // happen to know that the set of all the iOS debugservers which don't
23090b57cec5SDimitry Andric   // support GetThreadSuffixSupported() and that of the debugservers with this
23100b57cec5SDimitry Andric   // bug are equal.  There really should be a better way to test this!
23110b57cec5SDimitry Andric   //
23120b57cec5SDimitry Andric   // We also use m_destroy_tried_resuming to make sure we only do this once, if
23130b57cec5SDimitry Andric   // we resume and then halt and get called here to destroy again and we're
23140b57cec5SDimitry Andric   // still at a breakpoint or exception, then we should just do the straight-
23150b57cec5SDimitry Andric   // forward kill.
23160b57cec5SDimitry Andric   //
23170b57cec5SDimitry Andric   // And of course, if we weren't able to stop the process by the time we get
23180b57cec5SDimitry Andric   // here, it isn't necessary (or helpful) to do any of this.
23190b57cec5SDimitry Andric 
23200b57cec5SDimitry Andric   if (!m_gdb_comm.GetThreadSuffixSupported() &&
23210b57cec5SDimitry Andric       m_public_state.GetValue() != eStateRunning) {
23220b57cec5SDimitry Andric     PlatformSP platform_sp = GetTarget().GetPlatform();
23230b57cec5SDimitry Andric 
23240b57cec5SDimitry Andric     if (platform_sp && platform_sp->GetName() &&
2325349cc55cSDimitry Andric         platform_sp->GetName().GetStringRef() ==
2326349cc55cSDimitry Andric             PlatformRemoteiOS::GetPluginNameStatic()) {
23270b57cec5SDimitry Andric       if (m_destroy_tried_resuming) {
23280b57cec5SDimitry Andric         if (log)
23290b57cec5SDimitry Andric           log->PutCString("ProcessGDBRemote::DoDestroy() - Tried resuming to "
23300b57cec5SDimitry Andric                           "destroy once already, not doing it again.");
23310b57cec5SDimitry Andric       } else {
23320b57cec5SDimitry Andric         // At present, the plans are discarded and the breakpoints disabled
23330b57cec5SDimitry Andric         // Process::Destroy, but we really need it to happen here and it
23340b57cec5SDimitry Andric         // doesn't matter if we do it twice.
23350b57cec5SDimitry Andric         m_thread_list.DiscardThreadPlans();
23360b57cec5SDimitry Andric         DisableAllBreakpointSites();
23370b57cec5SDimitry Andric 
23380b57cec5SDimitry Andric         bool stop_looks_like_crash = false;
23390b57cec5SDimitry Andric         ThreadList &threads = GetThreadList();
23400b57cec5SDimitry Andric 
23410b57cec5SDimitry Andric         {
23420b57cec5SDimitry Andric           std::lock_guard<std::recursive_mutex> guard(threads.GetMutex());
23430b57cec5SDimitry Andric 
23440b57cec5SDimitry Andric           size_t num_threads = threads.GetSize();
23450b57cec5SDimitry Andric           for (size_t i = 0; i < num_threads; i++) {
23460b57cec5SDimitry Andric             ThreadSP thread_sp = threads.GetThreadAtIndex(i);
23470b57cec5SDimitry Andric             StopInfoSP stop_info_sp = thread_sp->GetPrivateStopInfo();
23480b57cec5SDimitry Andric             StopReason reason = eStopReasonInvalid;
23490b57cec5SDimitry Andric             if (stop_info_sp)
23500b57cec5SDimitry Andric               reason = stop_info_sp->GetStopReason();
23510b57cec5SDimitry Andric             if (reason == eStopReasonBreakpoint ||
23520b57cec5SDimitry Andric                 reason == eStopReasonException) {
23539dba64beSDimitry Andric               LLDB_LOGF(log,
23540b57cec5SDimitry Andric                         "ProcessGDBRemote::DoDestroy() - thread: 0x%4.4" PRIx64
23550b57cec5SDimitry Andric                         " stopped with reason: %s.",
23569dba64beSDimitry Andric                         thread_sp->GetProtocolID(),
23579dba64beSDimitry Andric                         stop_info_sp->GetDescription());
23580b57cec5SDimitry Andric               stop_looks_like_crash = true;
23590b57cec5SDimitry Andric               break;
23600b57cec5SDimitry Andric             }
23610b57cec5SDimitry Andric           }
23620b57cec5SDimitry Andric         }
23630b57cec5SDimitry Andric 
23640b57cec5SDimitry Andric         if (stop_looks_like_crash) {
23650b57cec5SDimitry Andric           if (log)
23660b57cec5SDimitry Andric             log->PutCString("ProcessGDBRemote::DoDestroy() - Stopped at a "
23670b57cec5SDimitry Andric                             "breakpoint, continue and then kill.");
23680b57cec5SDimitry Andric           m_destroy_tried_resuming = true;
23690b57cec5SDimitry Andric 
23700b57cec5SDimitry Andric           // If we are going to run again before killing, it would be good to
23710b57cec5SDimitry Andric           // suspend all the threads before resuming so they won't get into
23720b57cec5SDimitry Andric           // more trouble.  Sadly, for the threads stopped with the breakpoint
23730b57cec5SDimitry Andric           // or exception, the exception doesn't get cleared if it is
23740b57cec5SDimitry Andric           // suspended, so we do have to run the risk of letting those threads
23750b57cec5SDimitry Andric           // proceed a bit.
23760b57cec5SDimitry Andric 
23770b57cec5SDimitry Andric           {
23780b57cec5SDimitry Andric             std::lock_guard<std::recursive_mutex> guard(threads.GetMutex());
23790b57cec5SDimitry Andric 
23800b57cec5SDimitry Andric             size_t num_threads = threads.GetSize();
23810b57cec5SDimitry Andric             for (size_t i = 0; i < num_threads; i++) {
23820b57cec5SDimitry Andric               ThreadSP thread_sp = threads.GetThreadAtIndex(i);
23830b57cec5SDimitry Andric               StopInfoSP stop_info_sp = thread_sp->GetPrivateStopInfo();
23840b57cec5SDimitry Andric               StopReason reason = eStopReasonInvalid;
23850b57cec5SDimitry Andric               if (stop_info_sp)
23860b57cec5SDimitry Andric                 reason = stop_info_sp->GetStopReason();
23870b57cec5SDimitry Andric               if (reason != eStopReasonBreakpoint &&
23880b57cec5SDimitry Andric                   reason != eStopReasonException) {
23899dba64beSDimitry Andric                 LLDB_LOGF(log,
23909dba64beSDimitry Andric                           "ProcessGDBRemote::DoDestroy() - Suspending "
23910b57cec5SDimitry Andric                           "thread: 0x%4.4" PRIx64 " before running.",
23920b57cec5SDimitry Andric                           thread_sp->GetProtocolID());
23930b57cec5SDimitry Andric                 thread_sp->SetResumeState(eStateSuspended);
23940b57cec5SDimitry Andric               }
23950b57cec5SDimitry Andric             }
23960b57cec5SDimitry Andric           }
23970b57cec5SDimitry Andric           Resume();
23980b57cec5SDimitry Andric           return Destroy(false);
23990b57cec5SDimitry Andric         }
24000b57cec5SDimitry Andric       }
24010b57cec5SDimitry Andric     }
24020b57cec5SDimitry Andric   }
2403580012d6SDimitry Andric #endif // LLDB_ENABLE_ALL
24040b57cec5SDimitry Andric 
24050b57cec5SDimitry Andric   // Interrupt if our inferior is running...
24060b57cec5SDimitry Andric   int exit_status = SIGABRT;
24070b57cec5SDimitry Andric   std::string exit_string;
24080b57cec5SDimitry Andric 
24090b57cec5SDimitry Andric   if (m_gdb_comm.IsConnected()) {
24100b57cec5SDimitry Andric     if (m_public_state.GetValue() != eStateAttaching) {
24110b57cec5SDimitry Andric       StringExtractorGDBRemote response;
24120b57cec5SDimitry Andric       GDBRemoteCommunication::ScopedTimeout(m_gdb_comm,
24130b57cec5SDimitry Andric                                             std::chrono::seconds(3));
24140b57cec5SDimitry Andric 
2415fe6060f1SDimitry Andric       if (m_gdb_comm.SendPacketAndWaitForResponse("k", response,
2416fe6060f1SDimitry Andric                                                   GetInterruptTimeout()) ==
24170b57cec5SDimitry Andric           GDBRemoteCommunication::PacketResult::Success) {
24180b57cec5SDimitry Andric         char packet_cmd = response.GetChar(0);
24190b57cec5SDimitry Andric 
24200b57cec5SDimitry Andric         if (packet_cmd == 'W' || packet_cmd == 'X') {
24210b57cec5SDimitry Andric #if defined(__APPLE__)
24220b57cec5SDimitry Andric           // For Native processes on Mac OS X, we launch through the Host
24230b57cec5SDimitry Andric           // Platform, then hand the process off to debugserver, which becomes
24240b57cec5SDimitry Andric           // the parent process through "PT_ATTACH".  Then when we go to kill
24250b57cec5SDimitry Andric           // the process on Mac OS X we call ptrace(PT_KILL) to kill it, then
24260b57cec5SDimitry Andric           // we call waitpid which returns with no error and the correct
24270b57cec5SDimitry Andric           // status.  But amusingly enough that doesn't seem to actually reap
24280b57cec5SDimitry Andric           // the process, but instead it is left around as a Zombie.  Probably
24290b57cec5SDimitry Andric           // the kernel is in the process of switching ownership back to lldb
24300b57cec5SDimitry Andric           // which was the original parent, and gets confused in the handoff.
24310b57cec5SDimitry Andric           // Anyway, so call waitpid here to finally reap it.
24320b57cec5SDimitry Andric           PlatformSP platform_sp(GetTarget().GetPlatform());
24330b57cec5SDimitry Andric           if (platform_sp && platform_sp->IsHost()) {
24340b57cec5SDimitry Andric             int status;
24350b57cec5SDimitry Andric             ::pid_t reap_pid;
24360b57cec5SDimitry Andric             reap_pid = waitpid(GetID(), &status, WNOHANG);
24379dba64beSDimitry Andric             LLDB_LOGF(log, "Reaped pid: %d, status: %d.\n", reap_pid, status);
24380b57cec5SDimitry Andric           }
24390b57cec5SDimitry Andric #endif
24400b57cec5SDimitry Andric           SetLastStopPacket(response);
24410b57cec5SDimitry Andric           ClearThreadIDList();
24420b57cec5SDimitry Andric           exit_status = response.GetHexU8();
24430b57cec5SDimitry Andric         } else {
24449dba64beSDimitry Andric           LLDB_LOGF(log,
24459dba64beSDimitry Andric                     "ProcessGDBRemote::DoDestroy - got unexpected response "
24460b57cec5SDimitry Andric                     "to k packet: %s",
24479dba64beSDimitry Andric                     response.GetStringRef().data());
24480b57cec5SDimitry Andric           exit_string.assign("got unexpected response to k packet: ");
24495ffd83dbSDimitry Andric           exit_string.append(std::string(response.GetStringRef()));
24500b57cec5SDimitry Andric         }
24510b57cec5SDimitry Andric       } else {
24529dba64beSDimitry Andric         LLDB_LOGF(log, "ProcessGDBRemote::DoDestroy - failed to send k packet");
24530b57cec5SDimitry Andric         exit_string.assign("failed to send the k packet");
24540b57cec5SDimitry Andric       }
24550b57cec5SDimitry Andric     } else {
24569dba64beSDimitry Andric       LLDB_LOGF(log,
24579dba64beSDimitry Andric                 "ProcessGDBRemote::DoDestroy - killed or interrupted while "
24580b57cec5SDimitry Andric                 "attaching");
24590b57cec5SDimitry Andric       exit_string.assign("killed or interrupted while attaching.");
24600b57cec5SDimitry Andric     }
24610b57cec5SDimitry Andric   } else {
24620b57cec5SDimitry Andric     // If we missed setting the exit status on the way out, do it here.
24630b57cec5SDimitry Andric     // NB set exit status can be called multiple times, the first one sets the
24640b57cec5SDimitry Andric     // status.
24650b57cec5SDimitry Andric     exit_string.assign("destroying when not connected to debugserver");
24660b57cec5SDimitry Andric   }
24670b57cec5SDimitry Andric 
24680b57cec5SDimitry Andric   SetExitStatus(exit_status, exit_string.c_str());
24690b57cec5SDimitry Andric 
24700b57cec5SDimitry Andric   StopAsyncThread();
24710b57cec5SDimitry Andric   KillDebugserverProcess();
24720b57cec5SDimitry Andric   return error;
24730b57cec5SDimitry Andric }
24740b57cec5SDimitry Andric 
24750b57cec5SDimitry Andric void ProcessGDBRemote::SetLastStopPacket(
24760b57cec5SDimitry Andric     const StringExtractorGDBRemote &response) {
24770b57cec5SDimitry Andric   const bool did_exec =
24780b57cec5SDimitry Andric       response.GetStringRef().find(";reason:exec;") != std::string::npos;
24790b57cec5SDimitry Andric   if (did_exec) {
24800b57cec5SDimitry Andric     Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
24819dba64beSDimitry Andric     LLDB_LOGF(log, "ProcessGDBRemote::SetLastStopPacket () - detected exec");
24820b57cec5SDimitry Andric 
24830b57cec5SDimitry Andric     m_thread_list_real.Clear();
24840b57cec5SDimitry Andric     m_thread_list.Clear();
24850b57cec5SDimitry Andric     BuildDynamicRegisterInfo(true);
24860b57cec5SDimitry Andric     m_gdb_comm.ResetDiscoverableSettings(did_exec);
24870b57cec5SDimitry Andric   }
24880b57cec5SDimitry Andric 
2489349cc55cSDimitry Andric   m_last_stop_packet = response;
24900b57cec5SDimitry Andric }
24910b57cec5SDimitry Andric 
24920b57cec5SDimitry Andric void ProcessGDBRemote::SetUnixSignals(const UnixSignalsSP &signals_sp) {
24930b57cec5SDimitry Andric   Process::SetUnixSignals(std::make_shared<GDBRemoteSignals>(signals_sp));
24940b57cec5SDimitry Andric }
24950b57cec5SDimitry Andric 
24960b57cec5SDimitry Andric // Process Queries
24970b57cec5SDimitry Andric 
24980b57cec5SDimitry Andric bool ProcessGDBRemote::IsAlive() {
24990b57cec5SDimitry Andric   return m_gdb_comm.IsConnected() && Process::IsAlive();
25000b57cec5SDimitry Andric }
25010b57cec5SDimitry Andric 
25020b57cec5SDimitry Andric addr_t ProcessGDBRemote::GetImageInfoAddress() {
25030b57cec5SDimitry Andric   // request the link map address via the $qShlibInfoAddr packet
25040b57cec5SDimitry Andric   lldb::addr_t addr = m_gdb_comm.GetShlibInfoAddr();
25050b57cec5SDimitry Andric 
25060b57cec5SDimitry Andric   // the loaded module list can also provides a link map address
25070b57cec5SDimitry Andric   if (addr == LLDB_INVALID_ADDRESS) {
25089dba64beSDimitry Andric     llvm::Expected<LoadedModuleInfoList> list = GetLoadedModuleList();
25099dba64beSDimitry Andric     if (!list) {
25109dba64beSDimitry Andric       Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
2511e8d8bef9SDimitry Andric       LLDB_LOG_ERROR(log, list.takeError(), "Failed to read module list: {0}.");
25129dba64beSDimitry Andric     } else {
25139dba64beSDimitry Andric       addr = list->m_link_map;
25149dba64beSDimitry Andric     }
25150b57cec5SDimitry Andric   }
25160b57cec5SDimitry Andric 
25170b57cec5SDimitry Andric   return addr;
25180b57cec5SDimitry Andric }
25190b57cec5SDimitry Andric 
25200b57cec5SDimitry Andric void ProcessGDBRemote::WillPublicStop() {
25210b57cec5SDimitry Andric   // See if the GDB remote client supports the JSON threads info. If so, we
25220b57cec5SDimitry Andric   // gather stop info for all threads, expedited registers, expedited memory,
25230b57cec5SDimitry Andric   // runtime queue information (iOS and MacOSX only), and more. Expediting
25240b57cec5SDimitry Andric   // memory will help stack backtracing be much faster. Expediting registers
25250b57cec5SDimitry Andric   // will make sure we don't have to read the thread registers for GPRs.
25260b57cec5SDimitry Andric   m_jthreadsinfo_sp = m_gdb_comm.GetThreadsInfo();
25270b57cec5SDimitry Andric 
25280b57cec5SDimitry Andric   if (m_jthreadsinfo_sp) {
25290b57cec5SDimitry Andric     // Now set the stop info for each thread and also expedite any registers
25300b57cec5SDimitry Andric     // and memory that was in the jThreadsInfo response.
25310b57cec5SDimitry Andric     StructuredData::Array *thread_infos = m_jthreadsinfo_sp->GetAsArray();
25320b57cec5SDimitry Andric     if (thread_infos) {
25330b57cec5SDimitry Andric       const size_t n = thread_infos->GetSize();
25340b57cec5SDimitry Andric       for (size_t i = 0; i < n; ++i) {
25350b57cec5SDimitry Andric         StructuredData::Dictionary *thread_dict =
25360b57cec5SDimitry Andric             thread_infos->GetItemAtIndex(i)->GetAsDictionary();
25370b57cec5SDimitry Andric         if (thread_dict)
25380b57cec5SDimitry Andric           SetThreadStopInfo(thread_dict);
25390b57cec5SDimitry Andric       }
25400b57cec5SDimitry Andric     }
25410b57cec5SDimitry Andric   }
25420b57cec5SDimitry Andric }
25430b57cec5SDimitry Andric 
25440b57cec5SDimitry Andric // Process Memory
25450b57cec5SDimitry Andric size_t ProcessGDBRemote::DoReadMemory(addr_t addr, void *buf, size_t size,
25460b57cec5SDimitry Andric                                       Status &error) {
25470b57cec5SDimitry Andric   GetMaxMemorySize();
25480b57cec5SDimitry Andric   bool binary_memory_read = m_gdb_comm.GetxPacketSupported();
25490b57cec5SDimitry Andric   // M and m packets take 2 bytes for 1 byte of memory
25500b57cec5SDimitry Andric   size_t max_memory_size =
25510b57cec5SDimitry Andric       binary_memory_read ? m_max_memory_size : m_max_memory_size / 2;
25520b57cec5SDimitry Andric   if (size > max_memory_size) {
25530b57cec5SDimitry Andric     // Keep memory read sizes down to a sane limit. This function will be
25540b57cec5SDimitry Andric     // called multiple times in order to complete the task by
25550b57cec5SDimitry Andric     // lldb_private::Process so it is ok to do this.
25560b57cec5SDimitry Andric     size = max_memory_size;
25570b57cec5SDimitry Andric   }
25580b57cec5SDimitry Andric 
25590b57cec5SDimitry Andric   char packet[64];
25600b57cec5SDimitry Andric   int packet_len;
25610b57cec5SDimitry Andric   packet_len = ::snprintf(packet, sizeof(packet), "%c%" PRIx64 ",%" PRIx64,
25620b57cec5SDimitry Andric                           binary_memory_read ? 'x' : 'm', (uint64_t)addr,
25630b57cec5SDimitry Andric                           (uint64_t)size);
25640b57cec5SDimitry Andric   assert(packet_len + 1 < (int)sizeof(packet));
25650b57cec5SDimitry Andric   UNUSED_IF_ASSERT_DISABLED(packet_len);
25660b57cec5SDimitry Andric   StringExtractorGDBRemote response;
2567fe6060f1SDimitry Andric   if (m_gdb_comm.SendPacketAndWaitForResponse(packet, response,
2568fe6060f1SDimitry Andric                                               GetInterruptTimeout()) ==
25690b57cec5SDimitry Andric       GDBRemoteCommunication::PacketResult::Success) {
25700b57cec5SDimitry Andric     if (response.IsNormalResponse()) {
25710b57cec5SDimitry Andric       error.Clear();
25720b57cec5SDimitry Andric       if (binary_memory_read) {
25730b57cec5SDimitry Andric         // The lower level GDBRemoteCommunication packet receive layer has
25740b57cec5SDimitry Andric         // already de-quoted any 0x7d character escaping that was present in
25750b57cec5SDimitry Andric         // the packet
25760b57cec5SDimitry Andric 
25770b57cec5SDimitry Andric         size_t data_received_size = response.GetBytesLeft();
25780b57cec5SDimitry Andric         if (data_received_size > size) {
25790b57cec5SDimitry Andric           // Don't write past the end of BUF if the remote debug server gave us
25800b57cec5SDimitry Andric           // too much data for some reason.
25810b57cec5SDimitry Andric           data_received_size = size;
25820b57cec5SDimitry Andric         }
25830b57cec5SDimitry Andric         memcpy(buf, response.GetStringRef().data(), data_received_size);
25840b57cec5SDimitry Andric         return data_received_size;
25850b57cec5SDimitry Andric       } else {
25860b57cec5SDimitry Andric         return response.GetHexBytes(
25870b57cec5SDimitry Andric             llvm::MutableArrayRef<uint8_t>((uint8_t *)buf, size), '\xdd');
25880b57cec5SDimitry Andric       }
25890b57cec5SDimitry Andric     } else if (response.IsErrorResponse())
25900b57cec5SDimitry Andric       error.SetErrorStringWithFormat("memory read failed for 0x%" PRIx64, addr);
25910b57cec5SDimitry Andric     else if (response.IsUnsupportedResponse())
25920b57cec5SDimitry Andric       error.SetErrorStringWithFormat(
25930b57cec5SDimitry Andric           "GDB server does not support reading memory");
25940b57cec5SDimitry Andric     else
25950b57cec5SDimitry Andric       error.SetErrorStringWithFormat(
25960b57cec5SDimitry Andric           "unexpected response to GDB server memory read packet '%s': '%s'",
25979dba64beSDimitry Andric           packet, response.GetStringRef().data());
25980b57cec5SDimitry Andric   } else {
25990b57cec5SDimitry Andric     error.SetErrorStringWithFormat("failed to send packet: '%s'", packet);
26000b57cec5SDimitry Andric   }
26010b57cec5SDimitry Andric   return 0;
26020b57cec5SDimitry Andric }
26030b57cec5SDimitry Andric 
2604fe6060f1SDimitry Andric bool ProcessGDBRemote::SupportsMemoryTagging() {
2605fe6060f1SDimitry Andric   return m_gdb_comm.GetMemoryTaggingSupported();
2606fe6060f1SDimitry Andric }
2607fe6060f1SDimitry Andric 
2608fe6060f1SDimitry Andric llvm::Expected<std::vector<uint8_t>>
2609fe6060f1SDimitry Andric ProcessGDBRemote::DoReadMemoryTags(lldb::addr_t addr, size_t len,
2610fe6060f1SDimitry Andric                                    int32_t type) {
2611fe6060f1SDimitry Andric   // By this point ReadMemoryTags has validated that tagging is enabled
2612fe6060f1SDimitry Andric   // for this target/process/address.
2613fe6060f1SDimitry Andric   DataBufferSP buffer_sp = m_gdb_comm.ReadMemoryTags(addr, len, type);
2614fe6060f1SDimitry Andric   if (!buffer_sp) {
2615fe6060f1SDimitry Andric     return llvm::createStringError(llvm::inconvertibleErrorCode(),
2616fe6060f1SDimitry Andric                                    "Error reading memory tags from remote");
2617fe6060f1SDimitry Andric   }
2618fe6060f1SDimitry Andric 
2619fe6060f1SDimitry Andric   // Return the raw tag data
2620fe6060f1SDimitry Andric   llvm::ArrayRef<uint8_t> tag_data = buffer_sp->GetData();
2621fe6060f1SDimitry Andric   std::vector<uint8_t> got;
2622fe6060f1SDimitry Andric   got.reserve(tag_data.size());
2623fe6060f1SDimitry Andric   std::copy(tag_data.begin(), tag_data.end(), std::back_inserter(got));
2624fe6060f1SDimitry Andric   return got;
2625fe6060f1SDimitry Andric }
2626fe6060f1SDimitry Andric 
2627fe6060f1SDimitry Andric Status ProcessGDBRemote::DoWriteMemoryTags(lldb::addr_t addr, size_t len,
2628fe6060f1SDimitry Andric                                            int32_t type,
2629fe6060f1SDimitry Andric                                            const std::vector<uint8_t> &tags) {
2630fe6060f1SDimitry Andric   // By now WriteMemoryTags should have validated that tagging is enabled
2631fe6060f1SDimitry Andric   // for this target/process.
2632fe6060f1SDimitry Andric   return m_gdb_comm.WriteMemoryTags(addr, len, type, tags);
2633fe6060f1SDimitry Andric }
2634fe6060f1SDimitry Andric 
26350b57cec5SDimitry Andric Status ProcessGDBRemote::WriteObjectFile(
26360b57cec5SDimitry Andric     std::vector<ObjectFile::LoadableData> entries) {
26370b57cec5SDimitry Andric   Status error;
26380b57cec5SDimitry Andric   // Sort the entries by address because some writes, like those to flash
26390b57cec5SDimitry Andric   // memory, must happen in order of increasing address.
26400b57cec5SDimitry Andric   std::stable_sort(
26410b57cec5SDimitry Andric       std::begin(entries), std::end(entries),
26420b57cec5SDimitry Andric       [](const ObjectFile::LoadableData a, const ObjectFile::LoadableData b) {
26430b57cec5SDimitry Andric         return a.Dest < b.Dest;
26440b57cec5SDimitry Andric       });
26450b57cec5SDimitry Andric   m_allow_flash_writes = true;
26460b57cec5SDimitry Andric   error = Process::WriteObjectFile(entries);
26470b57cec5SDimitry Andric   if (error.Success())
26480b57cec5SDimitry Andric     error = FlashDone();
26490b57cec5SDimitry Andric   else
26500b57cec5SDimitry Andric     // Even though some of the writing failed, try to send a flash done if some
26510b57cec5SDimitry Andric     // of the writing succeeded so the flash state is reset to normal, but
26520b57cec5SDimitry Andric     // don't stomp on the error status that was set in the write failure since
26530b57cec5SDimitry Andric     // that's the one we want to report back.
26540b57cec5SDimitry Andric     FlashDone();
26550b57cec5SDimitry Andric   m_allow_flash_writes = false;
26560b57cec5SDimitry Andric   return error;
26570b57cec5SDimitry Andric }
26580b57cec5SDimitry Andric 
26590b57cec5SDimitry Andric bool ProcessGDBRemote::HasErased(FlashRange range) {
26600b57cec5SDimitry Andric   auto size = m_erased_flash_ranges.GetSize();
26610b57cec5SDimitry Andric   for (size_t i = 0; i < size; ++i)
26620b57cec5SDimitry Andric     if (m_erased_flash_ranges.GetEntryAtIndex(i)->Contains(range))
26630b57cec5SDimitry Andric       return true;
26640b57cec5SDimitry Andric   return false;
26650b57cec5SDimitry Andric }
26660b57cec5SDimitry Andric 
26670b57cec5SDimitry Andric Status ProcessGDBRemote::FlashErase(lldb::addr_t addr, size_t size) {
26680b57cec5SDimitry Andric   Status status;
26690b57cec5SDimitry Andric 
26700b57cec5SDimitry Andric   MemoryRegionInfo region;
26710b57cec5SDimitry Andric   status = GetMemoryRegionInfo(addr, region);
26720b57cec5SDimitry Andric   if (!status.Success())
26730b57cec5SDimitry Andric     return status;
26740b57cec5SDimitry Andric 
26750b57cec5SDimitry Andric   // The gdb spec doesn't say if erasures are allowed across multiple regions,
26760b57cec5SDimitry Andric   // but we'll disallow it to be safe and to keep the logic simple by worring
26770b57cec5SDimitry Andric   // about only one region's block size.  DoMemoryWrite is this function's
26780b57cec5SDimitry Andric   // primary user, and it can easily keep writes within a single memory region
26790b57cec5SDimitry Andric   if (addr + size > region.GetRange().GetRangeEnd()) {
26800b57cec5SDimitry Andric     status.SetErrorString("Unable to erase flash in multiple regions");
26810b57cec5SDimitry Andric     return status;
26820b57cec5SDimitry Andric   }
26830b57cec5SDimitry Andric 
26840b57cec5SDimitry Andric   uint64_t blocksize = region.GetBlocksize();
26850b57cec5SDimitry Andric   if (blocksize == 0) {
26860b57cec5SDimitry Andric     status.SetErrorString("Unable to erase flash because blocksize is 0");
26870b57cec5SDimitry Andric     return status;
26880b57cec5SDimitry Andric   }
26890b57cec5SDimitry Andric 
26900b57cec5SDimitry Andric   // Erasures can only be done on block boundary adresses, so round down addr
26910b57cec5SDimitry Andric   // and round up size
26920b57cec5SDimitry Andric   lldb::addr_t block_start_addr = addr - (addr % blocksize);
26930b57cec5SDimitry Andric   size += (addr - block_start_addr);
26940b57cec5SDimitry Andric   if ((size % blocksize) != 0)
26950b57cec5SDimitry Andric     size += (blocksize - size % blocksize);
26960b57cec5SDimitry Andric 
26970b57cec5SDimitry Andric   FlashRange range(block_start_addr, size);
26980b57cec5SDimitry Andric 
26990b57cec5SDimitry Andric   if (HasErased(range))
27000b57cec5SDimitry Andric     return status;
27010b57cec5SDimitry Andric 
27020b57cec5SDimitry Andric   // We haven't erased the entire range, but we may have erased part of it.
27030b57cec5SDimitry Andric   // (e.g., block A is already erased and range starts in A and ends in B). So,
27040b57cec5SDimitry Andric   // adjust range if necessary to exclude already erased blocks.
27050b57cec5SDimitry Andric   if (!m_erased_flash_ranges.IsEmpty()) {
27060b57cec5SDimitry Andric     // Assuming that writes and erasures are done in increasing addr order,
27070b57cec5SDimitry Andric     // because that is a requirement of the vFlashWrite command.  Therefore, we
27080b57cec5SDimitry Andric     // only need to look at the last range in the list for overlap.
27090b57cec5SDimitry Andric     const auto &last_range = *m_erased_flash_ranges.Back();
27100b57cec5SDimitry Andric     if (range.GetRangeBase() < last_range.GetRangeEnd()) {
27110b57cec5SDimitry Andric       auto overlap = last_range.GetRangeEnd() - range.GetRangeBase();
27120b57cec5SDimitry Andric       // overlap will be less than range.GetByteSize() or else HasErased()
27130b57cec5SDimitry Andric       // would have been true
27140b57cec5SDimitry Andric       range.SetByteSize(range.GetByteSize() - overlap);
27150b57cec5SDimitry Andric       range.SetRangeBase(range.GetRangeBase() + overlap);
27160b57cec5SDimitry Andric     }
27170b57cec5SDimitry Andric   }
27180b57cec5SDimitry Andric 
27190b57cec5SDimitry Andric   StreamString packet;
27200b57cec5SDimitry Andric   packet.Printf("vFlashErase:%" PRIx64 ",%" PRIx64, range.GetRangeBase(),
27210b57cec5SDimitry Andric                 (uint64_t)range.GetByteSize());
27220b57cec5SDimitry Andric 
27230b57cec5SDimitry Andric   StringExtractorGDBRemote response;
27240b57cec5SDimitry Andric   if (m_gdb_comm.SendPacketAndWaitForResponse(packet.GetString(), response,
2725fe6060f1SDimitry Andric                                               GetInterruptTimeout()) ==
27260b57cec5SDimitry Andric       GDBRemoteCommunication::PacketResult::Success) {
27270b57cec5SDimitry Andric     if (response.IsOKResponse()) {
27280b57cec5SDimitry Andric       m_erased_flash_ranges.Insert(range, true);
27290b57cec5SDimitry Andric     } else {
27300b57cec5SDimitry Andric       if (response.IsErrorResponse())
27310b57cec5SDimitry Andric         status.SetErrorStringWithFormat("flash erase failed for 0x%" PRIx64,
27320b57cec5SDimitry Andric                                         addr);
27330b57cec5SDimitry Andric       else if (response.IsUnsupportedResponse())
27340b57cec5SDimitry Andric         status.SetErrorStringWithFormat("GDB server does not support flashing");
27350b57cec5SDimitry Andric       else
27360b57cec5SDimitry Andric         status.SetErrorStringWithFormat(
27370b57cec5SDimitry Andric             "unexpected response to GDB server flash erase packet '%s': '%s'",
27389dba64beSDimitry Andric             packet.GetData(), response.GetStringRef().data());
27390b57cec5SDimitry Andric     }
27400b57cec5SDimitry Andric   } else {
27410b57cec5SDimitry Andric     status.SetErrorStringWithFormat("failed to send packet: '%s'",
27420b57cec5SDimitry Andric                                     packet.GetData());
27430b57cec5SDimitry Andric   }
27440b57cec5SDimitry Andric   return status;
27450b57cec5SDimitry Andric }
27460b57cec5SDimitry Andric 
27470b57cec5SDimitry Andric Status ProcessGDBRemote::FlashDone() {
27480b57cec5SDimitry Andric   Status status;
27490b57cec5SDimitry Andric   // If we haven't erased any blocks, then we must not have written anything
27500b57cec5SDimitry Andric   // either, so there is no need to actually send a vFlashDone command
27510b57cec5SDimitry Andric   if (m_erased_flash_ranges.IsEmpty())
27520b57cec5SDimitry Andric     return status;
27530b57cec5SDimitry Andric   StringExtractorGDBRemote response;
2754fe6060f1SDimitry Andric   if (m_gdb_comm.SendPacketAndWaitForResponse("vFlashDone", response,
2755fe6060f1SDimitry Andric                                               GetInterruptTimeout()) ==
27560b57cec5SDimitry Andric       GDBRemoteCommunication::PacketResult::Success) {
27570b57cec5SDimitry Andric     if (response.IsOKResponse()) {
27580b57cec5SDimitry Andric       m_erased_flash_ranges.Clear();
27590b57cec5SDimitry Andric     } else {
27600b57cec5SDimitry Andric       if (response.IsErrorResponse())
27610b57cec5SDimitry Andric         status.SetErrorStringWithFormat("flash done failed");
27620b57cec5SDimitry Andric       else if (response.IsUnsupportedResponse())
27630b57cec5SDimitry Andric         status.SetErrorStringWithFormat("GDB server does not support flashing");
27640b57cec5SDimitry Andric       else
27650b57cec5SDimitry Andric         status.SetErrorStringWithFormat(
27660b57cec5SDimitry Andric             "unexpected response to GDB server flash done packet: '%s'",
27679dba64beSDimitry Andric             response.GetStringRef().data());
27680b57cec5SDimitry Andric     }
27690b57cec5SDimitry Andric   } else {
27700b57cec5SDimitry Andric     status.SetErrorStringWithFormat("failed to send flash done packet");
27710b57cec5SDimitry Andric   }
27720b57cec5SDimitry Andric   return status;
27730b57cec5SDimitry Andric }
27740b57cec5SDimitry Andric 
27750b57cec5SDimitry Andric size_t ProcessGDBRemote::DoWriteMemory(addr_t addr, const void *buf,
27760b57cec5SDimitry Andric                                        size_t size, Status &error) {
27770b57cec5SDimitry Andric   GetMaxMemorySize();
27780b57cec5SDimitry Andric   // M and m packets take 2 bytes for 1 byte of memory
27790b57cec5SDimitry Andric   size_t max_memory_size = m_max_memory_size / 2;
27800b57cec5SDimitry Andric   if (size > max_memory_size) {
27810b57cec5SDimitry Andric     // Keep memory read sizes down to a sane limit. This function will be
27820b57cec5SDimitry Andric     // called multiple times in order to complete the task by
27830b57cec5SDimitry Andric     // lldb_private::Process so it is ok to do this.
27840b57cec5SDimitry Andric     size = max_memory_size;
27850b57cec5SDimitry Andric   }
27860b57cec5SDimitry Andric 
27870b57cec5SDimitry Andric   StreamGDBRemote packet;
27880b57cec5SDimitry Andric 
27890b57cec5SDimitry Andric   MemoryRegionInfo region;
27900b57cec5SDimitry Andric   Status region_status = GetMemoryRegionInfo(addr, region);
27910b57cec5SDimitry Andric 
27920b57cec5SDimitry Andric   bool is_flash =
27930b57cec5SDimitry Andric       region_status.Success() && region.GetFlash() == MemoryRegionInfo::eYes;
27940b57cec5SDimitry Andric 
27950b57cec5SDimitry Andric   if (is_flash) {
27960b57cec5SDimitry Andric     if (!m_allow_flash_writes) {
27970b57cec5SDimitry Andric       error.SetErrorString("Writing to flash memory is not allowed");
27980b57cec5SDimitry Andric       return 0;
27990b57cec5SDimitry Andric     }
28000b57cec5SDimitry Andric     // Keep the write within a flash memory region
28010b57cec5SDimitry Andric     if (addr + size > region.GetRange().GetRangeEnd())
28020b57cec5SDimitry Andric       size = region.GetRange().GetRangeEnd() - addr;
28030b57cec5SDimitry Andric     // Flash memory must be erased before it can be written
28040b57cec5SDimitry Andric     error = FlashErase(addr, size);
28050b57cec5SDimitry Andric     if (!error.Success())
28060b57cec5SDimitry Andric       return 0;
28070b57cec5SDimitry Andric     packet.Printf("vFlashWrite:%" PRIx64 ":", addr);
28080b57cec5SDimitry Andric     packet.PutEscapedBytes(buf, size);
28090b57cec5SDimitry Andric   } else {
28100b57cec5SDimitry Andric     packet.Printf("M%" PRIx64 ",%" PRIx64 ":", addr, (uint64_t)size);
28110b57cec5SDimitry Andric     packet.PutBytesAsRawHex8(buf, size, endian::InlHostByteOrder(),
28120b57cec5SDimitry Andric                              endian::InlHostByteOrder());
28130b57cec5SDimitry Andric   }
28140b57cec5SDimitry Andric   StringExtractorGDBRemote response;
28150b57cec5SDimitry Andric   if (m_gdb_comm.SendPacketAndWaitForResponse(packet.GetString(), response,
2816fe6060f1SDimitry Andric                                               GetInterruptTimeout()) ==
28170b57cec5SDimitry Andric       GDBRemoteCommunication::PacketResult::Success) {
28180b57cec5SDimitry Andric     if (response.IsOKResponse()) {
28190b57cec5SDimitry Andric       error.Clear();
28200b57cec5SDimitry Andric       return size;
28210b57cec5SDimitry Andric     } else if (response.IsErrorResponse())
28220b57cec5SDimitry Andric       error.SetErrorStringWithFormat("memory write failed for 0x%" PRIx64,
28230b57cec5SDimitry Andric                                      addr);
28240b57cec5SDimitry Andric     else if (response.IsUnsupportedResponse())
28250b57cec5SDimitry Andric       error.SetErrorStringWithFormat(
28260b57cec5SDimitry Andric           "GDB server does not support writing memory");
28270b57cec5SDimitry Andric     else
28280b57cec5SDimitry Andric       error.SetErrorStringWithFormat(
28290b57cec5SDimitry Andric           "unexpected response to GDB server memory write packet '%s': '%s'",
28309dba64beSDimitry Andric           packet.GetData(), response.GetStringRef().data());
28310b57cec5SDimitry Andric   } else {
28320b57cec5SDimitry Andric     error.SetErrorStringWithFormat("failed to send packet: '%s'",
28330b57cec5SDimitry Andric                                    packet.GetData());
28340b57cec5SDimitry Andric   }
28350b57cec5SDimitry Andric   return 0;
28360b57cec5SDimitry Andric }
28370b57cec5SDimitry Andric 
28380b57cec5SDimitry Andric lldb::addr_t ProcessGDBRemote::DoAllocateMemory(size_t size,
28390b57cec5SDimitry Andric                                                 uint32_t permissions,
28400b57cec5SDimitry Andric                                                 Status &error) {
28410b57cec5SDimitry Andric   Log *log(
28420b57cec5SDimitry Andric       GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS | LIBLLDB_LOG_EXPRESSIONS));
28430b57cec5SDimitry Andric   addr_t allocated_addr = LLDB_INVALID_ADDRESS;
28440b57cec5SDimitry Andric 
28450b57cec5SDimitry Andric   if (m_gdb_comm.SupportsAllocDeallocMemory() != eLazyBoolNo) {
28460b57cec5SDimitry Andric     allocated_addr = m_gdb_comm.AllocateMemory(size, permissions);
28470b57cec5SDimitry Andric     if (allocated_addr != LLDB_INVALID_ADDRESS ||
28480b57cec5SDimitry Andric         m_gdb_comm.SupportsAllocDeallocMemory() == eLazyBoolYes)
28490b57cec5SDimitry Andric       return allocated_addr;
28500b57cec5SDimitry Andric   }
28510b57cec5SDimitry Andric 
28520b57cec5SDimitry Andric   if (m_gdb_comm.SupportsAllocDeallocMemory() == eLazyBoolNo) {
28530b57cec5SDimitry Andric     // Call mmap() to create memory in the inferior..
28540b57cec5SDimitry Andric     unsigned prot = 0;
28550b57cec5SDimitry Andric     if (permissions & lldb::ePermissionsReadable)
28560b57cec5SDimitry Andric       prot |= eMmapProtRead;
28570b57cec5SDimitry Andric     if (permissions & lldb::ePermissionsWritable)
28580b57cec5SDimitry Andric       prot |= eMmapProtWrite;
28590b57cec5SDimitry Andric     if (permissions & lldb::ePermissionsExecutable)
28600b57cec5SDimitry Andric       prot |= eMmapProtExec;
28610b57cec5SDimitry Andric 
28620b57cec5SDimitry Andric     if (InferiorCallMmap(this, allocated_addr, 0, size, prot,
28630b57cec5SDimitry Andric                          eMmapFlagsAnon | eMmapFlagsPrivate, -1, 0))
28640b57cec5SDimitry Andric       m_addr_to_mmap_size[allocated_addr] = size;
28650b57cec5SDimitry Andric     else {
28660b57cec5SDimitry Andric       allocated_addr = LLDB_INVALID_ADDRESS;
28679dba64beSDimitry Andric       LLDB_LOGF(log,
28689dba64beSDimitry Andric                 "ProcessGDBRemote::%s no direct stub support for memory "
28690b57cec5SDimitry Andric                 "allocation, and InferiorCallMmap also failed - is stub "
28700b57cec5SDimitry Andric                 "missing register context save/restore capability?",
28710b57cec5SDimitry Andric                 __FUNCTION__);
28720b57cec5SDimitry Andric     }
28730b57cec5SDimitry Andric   }
28740b57cec5SDimitry Andric 
28750b57cec5SDimitry Andric   if (allocated_addr == LLDB_INVALID_ADDRESS)
28760b57cec5SDimitry Andric     error.SetErrorStringWithFormat(
28770b57cec5SDimitry Andric         "unable to allocate %" PRIu64 " bytes of memory with permissions %s",
28780b57cec5SDimitry Andric         (uint64_t)size, GetPermissionsAsCString(permissions));
28790b57cec5SDimitry Andric   else
28800b57cec5SDimitry Andric     error.Clear();
28810b57cec5SDimitry Andric   return allocated_addr;
28820b57cec5SDimitry Andric }
28830b57cec5SDimitry Andric 
2884*4824e7fdSDimitry Andric Status ProcessGDBRemote::GetMemoryRegionInfo(addr_t load_addr,
28850b57cec5SDimitry Andric                                              MemoryRegionInfo &region_info) {
28860b57cec5SDimitry Andric 
28870b57cec5SDimitry Andric   Status error(m_gdb_comm.GetMemoryRegionInfo(load_addr, region_info));
28880b57cec5SDimitry Andric   return error;
28890b57cec5SDimitry Andric }
28900b57cec5SDimitry Andric 
28910b57cec5SDimitry Andric Status ProcessGDBRemote::GetWatchpointSupportInfo(uint32_t &num) {
28920b57cec5SDimitry Andric 
28930b57cec5SDimitry Andric   Status error(m_gdb_comm.GetWatchpointSupportInfo(num));
28940b57cec5SDimitry Andric   return error;
28950b57cec5SDimitry Andric }
28960b57cec5SDimitry Andric 
28970b57cec5SDimitry Andric Status ProcessGDBRemote::GetWatchpointSupportInfo(uint32_t &num, bool &after) {
28980b57cec5SDimitry Andric   Status error(m_gdb_comm.GetWatchpointSupportInfo(
28990b57cec5SDimitry Andric       num, after, GetTarget().GetArchitecture()));
29000b57cec5SDimitry Andric   return error;
29010b57cec5SDimitry Andric }
29020b57cec5SDimitry Andric 
29030b57cec5SDimitry Andric Status ProcessGDBRemote::DoDeallocateMemory(lldb::addr_t addr) {
29040b57cec5SDimitry Andric   Status error;
29050b57cec5SDimitry Andric   LazyBool supported = m_gdb_comm.SupportsAllocDeallocMemory();
29060b57cec5SDimitry Andric 
29070b57cec5SDimitry Andric   switch (supported) {
29080b57cec5SDimitry Andric   case eLazyBoolCalculate:
29090b57cec5SDimitry Andric     // We should never be deallocating memory without allocating memory first
29100b57cec5SDimitry Andric     // so we should never get eLazyBoolCalculate
29110b57cec5SDimitry Andric     error.SetErrorString(
29120b57cec5SDimitry Andric         "tried to deallocate memory without ever allocating memory");
29130b57cec5SDimitry Andric     break;
29140b57cec5SDimitry Andric 
29150b57cec5SDimitry Andric   case eLazyBoolYes:
29160b57cec5SDimitry Andric     if (!m_gdb_comm.DeallocateMemory(addr))
29170b57cec5SDimitry Andric       error.SetErrorStringWithFormat(
29180b57cec5SDimitry Andric           "unable to deallocate memory at 0x%" PRIx64, addr);
29190b57cec5SDimitry Andric     break;
29200b57cec5SDimitry Andric 
29210b57cec5SDimitry Andric   case eLazyBoolNo:
29220b57cec5SDimitry Andric     // Call munmap() to deallocate memory in the inferior..
29230b57cec5SDimitry Andric     {
29240b57cec5SDimitry Andric       MMapMap::iterator pos = m_addr_to_mmap_size.find(addr);
29250b57cec5SDimitry Andric       if (pos != m_addr_to_mmap_size.end() &&
29260b57cec5SDimitry Andric           InferiorCallMunmap(this, addr, pos->second))
29270b57cec5SDimitry Andric         m_addr_to_mmap_size.erase(pos);
29280b57cec5SDimitry Andric       else
29290b57cec5SDimitry Andric         error.SetErrorStringWithFormat(
29300b57cec5SDimitry Andric             "unable to deallocate memory at 0x%" PRIx64, addr);
29310b57cec5SDimitry Andric     }
29320b57cec5SDimitry Andric     break;
29330b57cec5SDimitry Andric   }
29340b57cec5SDimitry Andric 
29350b57cec5SDimitry Andric   return error;
29360b57cec5SDimitry Andric }
29370b57cec5SDimitry Andric 
29380b57cec5SDimitry Andric // Process STDIO
29390b57cec5SDimitry Andric size_t ProcessGDBRemote::PutSTDIN(const char *src, size_t src_len,
29400b57cec5SDimitry Andric                                   Status &error) {
29410b57cec5SDimitry Andric   if (m_stdio_communication.IsConnected()) {
29420b57cec5SDimitry Andric     ConnectionStatus status;
29430b57cec5SDimitry Andric     m_stdio_communication.Write(src, src_len, status, nullptr);
29440b57cec5SDimitry Andric   } else if (m_stdin_forward) {
29450b57cec5SDimitry Andric     m_gdb_comm.SendStdinNotification(src, src_len);
29460b57cec5SDimitry Andric   }
29470b57cec5SDimitry Andric   return 0;
29480b57cec5SDimitry Andric }
29490b57cec5SDimitry Andric 
29500b57cec5SDimitry Andric Status ProcessGDBRemote::EnableBreakpointSite(BreakpointSite *bp_site) {
29510b57cec5SDimitry Andric   Status error;
29520b57cec5SDimitry Andric   assert(bp_site != nullptr);
29530b57cec5SDimitry Andric 
29540b57cec5SDimitry Andric   // Get logging info
29550b57cec5SDimitry Andric   Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_BREAKPOINTS));
29560b57cec5SDimitry Andric   user_id_t site_id = bp_site->GetID();
29570b57cec5SDimitry Andric 
29580b57cec5SDimitry Andric   // Get the breakpoint address
29590b57cec5SDimitry Andric   const addr_t addr = bp_site->GetLoadAddress();
29600b57cec5SDimitry Andric 
29610b57cec5SDimitry Andric   // Log that a breakpoint was requested
29629dba64beSDimitry Andric   LLDB_LOGF(log,
29639dba64beSDimitry Andric             "ProcessGDBRemote::EnableBreakpointSite (size_id = %" PRIu64
29640b57cec5SDimitry Andric             ") address = 0x%" PRIx64,
29650b57cec5SDimitry Andric             site_id, (uint64_t)addr);
29660b57cec5SDimitry Andric 
29670b57cec5SDimitry Andric   // Breakpoint already exists and is enabled
29680b57cec5SDimitry Andric   if (bp_site->IsEnabled()) {
29699dba64beSDimitry Andric     LLDB_LOGF(log,
29709dba64beSDimitry Andric               "ProcessGDBRemote::EnableBreakpointSite (size_id = %" PRIu64
29710b57cec5SDimitry Andric               ") address = 0x%" PRIx64 " -- SUCCESS (already enabled)",
29720b57cec5SDimitry Andric               site_id, (uint64_t)addr);
29730b57cec5SDimitry Andric     return error;
29740b57cec5SDimitry Andric   }
29750b57cec5SDimitry Andric 
29760b57cec5SDimitry Andric   // Get the software breakpoint trap opcode size
29770b57cec5SDimitry Andric   const size_t bp_op_size = GetSoftwareBreakpointTrapOpcode(bp_site);
29780b57cec5SDimitry Andric 
29790b57cec5SDimitry Andric   // SupportsGDBStoppointPacket() simply checks a boolean, indicating if this
29800b57cec5SDimitry Andric   // breakpoint type is supported by the remote stub. These are set to true by
29810b57cec5SDimitry Andric   // default, and later set to false only after we receive an unimplemented
29820b57cec5SDimitry Andric   // response when sending a breakpoint packet. This means initially that
29830b57cec5SDimitry Andric   // unless we were specifically instructed to use a hardware breakpoint, LLDB
29840b57cec5SDimitry Andric   // will attempt to set a software breakpoint. HardwareRequired() also queries
29850b57cec5SDimitry Andric   // a boolean variable which indicates if the user specifically asked for
29860b57cec5SDimitry Andric   // hardware breakpoints.  If true then we will skip over software
29870b57cec5SDimitry Andric   // breakpoints.
29880b57cec5SDimitry Andric   if (m_gdb_comm.SupportsGDBStoppointPacket(eBreakpointSoftware) &&
29890b57cec5SDimitry Andric       (!bp_site->HardwareRequired())) {
29900b57cec5SDimitry Andric     // Try to send off a software breakpoint packet ($Z0)
29910b57cec5SDimitry Andric     uint8_t error_no = m_gdb_comm.SendGDBStoppointTypePacket(
2992fe6060f1SDimitry Andric         eBreakpointSoftware, true, addr, bp_op_size, GetInterruptTimeout());
29930b57cec5SDimitry Andric     if (error_no == 0) {
29940b57cec5SDimitry Andric       // The breakpoint was placed successfully
29950b57cec5SDimitry Andric       bp_site->SetEnabled(true);
29960b57cec5SDimitry Andric       bp_site->SetType(BreakpointSite::eExternal);
29970b57cec5SDimitry Andric       return error;
29980b57cec5SDimitry Andric     }
29990b57cec5SDimitry Andric 
30000b57cec5SDimitry Andric     // SendGDBStoppointTypePacket() will return an error if it was unable to
30010b57cec5SDimitry Andric     // set this breakpoint. We need to differentiate between a error specific
30020b57cec5SDimitry Andric     // to placing this breakpoint or if we have learned that this breakpoint
30030b57cec5SDimitry Andric     // type is unsupported. To do this, we must test the support boolean for
30040b57cec5SDimitry Andric     // this breakpoint type to see if it now indicates that this breakpoint
30050b57cec5SDimitry Andric     // type is unsupported.  If they are still supported then we should return
30060b57cec5SDimitry Andric     // with the error code.  If they are now unsupported, then we would like to
30070b57cec5SDimitry Andric     // fall through and try another form of breakpoint.
30080b57cec5SDimitry Andric     if (m_gdb_comm.SupportsGDBStoppointPacket(eBreakpointSoftware)) {
30090b57cec5SDimitry Andric       if (error_no != UINT8_MAX)
30100b57cec5SDimitry Andric         error.SetErrorStringWithFormat(
30115ffd83dbSDimitry Andric             "error: %d sending the breakpoint request", error_no);
30120b57cec5SDimitry Andric       else
30130b57cec5SDimitry Andric         error.SetErrorString("error sending the breakpoint request");
30140b57cec5SDimitry Andric       return error;
30150b57cec5SDimitry Andric     }
30160b57cec5SDimitry Andric 
30170b57cec5SDimitry Andric     // We reach here when software breakpoints have been found to be
30180b57cec5SDimitry Andric     // unsupported. For future calls to set a breakpoint, we will not attempt
30190b57cec5SDimitry Andric     // to set a breakpoint with a type that is known not to be supported.
30209dba64beSDimitry Andric     LLDB_LOGF(log, "Software breakpoints are unsupported");
30210b57cec5SDimitry Andric 
30220b57cec5SDimitry Andric     // So we will fall through and try a hardware breakpoint
30230b57cec5SDimitry Andric   }
30240b57cec5SDimitry Andric 
30250b57cec5SDimitry Andric   // The process of setting a hardware breakpoint is much the same as above.
30260b57cec5SDimitry Andric   // We check the supported boolean for this breakpoint type, and if it is
30270b57cec5SDimitry Andric   // thought to be supported then we will try to set this breakpoint with a
30280b57cec5SDimitry Andric   // hardware breakpoint.
30290b57cec5SDimitry Andric   if (m_gdb_comm.SupportsGDBStoppointPacket(eBreakpointHardware)) {
30300b57cec5SDimitry Andric     // Try to send off a hardware breakpoint packet ($Z1)
30310b57cec5SDimitry Andric     uint8_t error_no = m_gdb_comm.SendGDBStoppointTypePacket(
3032fe6060f1SDimitry Andric         eBreakpointHardware, true, addr, bp_op_size, GetInterruptTimeout());
30330b57cec5SDimitry Andric     if (error_no == 0) {
30340b57cec5SDimitry Andric       // The breakpoint was placed successfully
30350b57cec5SDimitry Andric       bp_site->SetEnabled(true);
30360b57cec5SDimitry Andric       bp_site->SetType(BreakpointSite::eHardware);
30370b57cec5SDimitry Andric       return error;
30380b57cec5SDimitry Andric     }
30390b57cec5SDimitry Andric 
30400b57cec5SDimitry Andric     // Check if the error was something other then an unsupported breakpoint
30410b57cec5SDimitry Andric     // type
30420b57cec5SDimitry Andric     if (m_gdb_comm.SupportsGDBStoppointPacket(eBreakpointHardware)) {
30430b57cec5SDimitry Andric       // Unable to set this hardware breakpoint
30440b57cec5SDimitry Andric       if (error_no != UINT8_MAX)
30450b57cec5SDimitry Andric         error.SetErrorStringWithFormat(
30460b57cec5SDimitry Andric             "error: %d sending the hardware breakpoint request "
30470b57cec5SDimitry Andric             "(hardware breakpoint resources might be exhausted or unavailable)",
30480b57cec5SDimitry Andric             error_no);
30490b57cec5SDimitry Andric       else
30500b57cec5SDimitry Andric         error.SetErrorString("error sending the hardware breakpoint request "
30510b57cec5SDimitry Andric                              "(hardware breakpoint resources "
30520b57cec5SDimitry Andric                              "might be exhausted or unavailable)");
30530b57cec5SDimitry Andric       return error;
30540b57cec5SDimitry Andric     }
30550b57cec5SDimitry Andric 
30560b57cec5SDimitry Andric     // We will reach here when the stub gives an unsupported response to a
30570b57cec5SDimitry Andric     // hardware breakpoint
30589dba64beSDimitry Andric     LLDB_LOGF(log, "Hardware breakpoints are unsupported");
30590b57cec5SDimitry Andric 
30600b57cec5SDimitry Andric     // Finally we will falling through to a #trap style breakpoint
30610b57cec5SDimitry Andric   }
30620b57cec5SDimitry Andric 
30630b57cec5SDimitry Andric   // Don't fall through when hardware breakpoints were specifically requested
30640b57cec5SDimitry Andric   if (bp_site->HardwareRequired()) {
30650b57cec5SDimitry Andric     error.SetErrorString("hardware breakpoints are not supported");
30660b57cec5SDimitry Andric     return error;
30670b57cec5SDimitry Andric   }
30680b57cec5SDimitry Andric 
30690b57cec5SDimitry Andric   // As a last resort we want to place a manual breakpoint. An instruction is
30700b57cec5SDimitry Andric   // placed into the process memory using memory write packets.
30710b57cec5SDimitry Andric   return EnableSoftwareBreakpoint(bp_site);
30720b57cec5SDimitry Andric }
30730b57cec5SDimitry Andric 
30740b57cec5SDimitry Andric Status ProcessGDBRemote::DisableBreakpointSite(BreakpointSite *bp_site) {
30750b57cec5SDimitry Andric   Status error;
30760b57cec5SDimitry Andric   assert(bp_site != nullptr);
30770b57cec5SDimitry Andric   addr_t addr = bp_site->GetLoadAddress();
30780b57cec5SDimitry Andric   user_id_t site_id = bp_site->GetID();
30790b57cec5SDimitry Andric   Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_BREAKPOINTS));
30809dba64beSDimitry Andric   LLDB_LOGF(log,
30819dba64beSDimitry Andric             "ProcessGDBRemote::DisableBreakpointSite (site_id = %" PRIu64
30820b57cec5SDimitry Andric             ") addr = 0x%8.8" PRIx64,
30830b57cec5SDimitry Andric             site_id, (uint64_t)addr);
30840b57cec5SDimitry Andric 
30850b57cec5SDimitry Andric   if (bp_site->IsEnabled()) {
30860b57cec5SDimitry Andric     const size_t bp_op_size = GetSoftwareBreakpointTrapOpcode(bp_site);
30870b57cec5SDimitry Andric 
30880b57cec5SDimitry Andric     BreakpointSite::Type bp_type = bp_site->GetType();
30890b57cec5SDimitry Andric     switch (bp_type) {
30900b57cec5SDimitry Andric     case BreakpointSite::eSoftware:
30910b57cec5SDimitry Andric       error = DisableSoftwareBreakpoint(bp_site);
30920b57cec5SDimitry Andric       break;
30930b57cec5SDimitry Andric 
30940b57cec5SDimitry Andric     case BreakpointSite::eHardware:
30950b57cec5SDimitry Andric       if (m_gdb_comm.SendGDBStoppointTypePacket(eBreakpointHardware, false,
3096fe6060f1SDimitry Andric                                                 addr, bp_op_size,
3097fe6060f1SDimitry Andric                                                 GetInterruptTimeout()))
30980b57cec5SDimitry Andric         error.SetErrorToGenericError();
30990b57cec5SDimitry Andric       break;
31000b57cec5SDimitry Andric 
31010b57cec5SDimitry Andric     case BreakpointSite::eExternal: {
3102e8d8bef9SDimitry Andric       if (m_gdb_comm.SendGDBStoppointTypePacket(eBreakpointSoftware, false,
3103fe6060f1SDimitry Andric                                                 addr, bp_op_size,
3104fe6060f1SDimitry Andric                                                 GetInterruptTimeout()))
31050b57cec5SDimitry Andric         error.SetErrorToGenericError();
31060b57cec5SDimitry Andric     } break;
31070b57cec5SDimitry Andric     }
31080b57cec5SDimitry Andric     if (error.Success())
31090b57cec5SDimitry Andric       bp_site->SetEnabled(false);
31100b57cec5SDimitry Andric   } else {
31119dba64beSDimitry Andric     LLDB_LOGF(log,
31129dba64beSDimitry Andric               "ProcessGDBRemote::DisableBreakpointSite (site_id = %" PRIu64
31130b57cec5SDimitry Andric               ") addr = 0x%8.8" PRIx64 " -- SUCCESS (already disabled)",
31140b57cec5SDimitry Andric               site_id, (uint64_t)addr);
31150b57cec5SDimitry Andric     return error;
31160b57cec5SDimitry Andric   }
31170b57cec5SDimitry Andric 
31180b57cec5SDimitry Andric   if (error.Success())
31190b57cec5SDimitry Andric     error.SetErrorToGenericError();
31200b57cec5SDimitry Andric   return error;
31210b57cec5SDimitry Andric }
31220b57cec5SDimitry Andric 
31230b57cec5SDimitry Andric // Pre-requisite: wp != NULL.
31240b57cec5SDimitry Andric static GDBStoppointType GetGDBStoppointType(Watchpoint *wp) {
31250b57cec5SDimitry Andric   assert(wp);
31260b57cec5SDimitry Andric   bool watch_read = wp->WatchpointRead();
31270b57cec5SDimitry Andric   bool watch_write = wp->WatchpointWrite();
31280b57cec5SDimitry Andric 
31290b57cec5SDimitry Andric   // watch_read and watch_write cannot both be false.
31300b57cec5SDimitry Andric   assert(watch_read || watch_write);
31310b57cec5SDimitry Andric   if (watch_read && watch_write)
31320b57cec5SDimitry Andric     return eWatchpointReadWrite;
31330b57cec5SDimitry Andric   else if (watch_read)
31340b57cec5SDimitry Andric     return eWatchpointRead;
31350b57cec5SDimitry Andric   else // Must be watch_write, then.
31360b57cec5SDimitry Andric     return eWatchpointWrite;
31370b57cec5SDimitry Andric }
31380b57cec5SDimitry Andric 
31390b57cec5SDimitry Andric Status ProcessGDBRemote::EnableWatchpoint(Watchpoint *wp, bool notify) {
31400b57cec5SDimitry Andric   Status error;
31410b57cec5SDimitry Andric   if (wp) {
31420b57cec5SDimitry Andric     user_id_t watchID = wp->GetID();
31430b57cec5SDimitry Andric     addr_t addr = wp->GetLoadAddress();
31440b57cec5SDimitry Andric     Log *log(
31450b57cec5SDimitry Andric         ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_WATCHPOINTS));
31469dba64beSDimitry Andric     LLDB_LOGF(log, "ProcessGDBRemote::EnableWatchpoint(watchID = %" PRIu64 ")",
31470b57cec5SDimitry Andric               watchID);
31480b57cec5SDimitry Andric     if (wp->IsEnabled()) {
31499dba64beSDimitry Andric       LLDB_LOGF(log,
31509dba64beSDimitry Andric                 "ProcessGDBRemote::EnableWatchpoint(watchID = %" PRIu64
31510b57cec5SDimitry Andric                 ") addr = 0x%8.8" PRIx64 ": watchpoint already enabled.",
31520b57cec5SDimitry Andric                 watchID, (uint64_t)addr);
31530b57cec5SDimitry Andric       return error;
31540b57cec5SDimitry Andric     }
31550b57cec5SDimitry Andric 
31560b57cec5SDimitry Andric     GDBStoppointType type = GetGDBStoppointType(wp);
31570b57cec5SDimitry Andric     // Pass down an appropriate z/Z packet...
31580b57cec5SDimitry Andric     if (m_gdb_comm.SupportsGDBStoppointPacket(type)) {
31590b57cec5SDimitry Andric       if (m_gdb_comm.SendGDBStoppointTypePacket(type, true, addr,
3160fe6060f1SDimitry Andric                                                 wp->GetByteSize(),
3161fe6060f1SDimitry Andric                                                 GetInterruptTimeout()) == 0) {
31620b57cec5SDimitry Andric         wp->SetEnabled(true, notify);
31630b57cec5SDimitry Andric         return error;
31640b57cec5SDimitry Andric       } else
31650b57cec5SDimitry Andric         error.SetErrorString("sending gdb watchpoint packet failed");
31660b57cec5SDimitry Andric     } else
31670b57cec5SDimitry Andric       error.SetErrorString("watchpoints not supported");
31680b57cec5SDimitry Andric   } else {
31690b57cec5SDimitry Andric     error.SetErrorString("Watchpoint argument was NULL.");
31700b57cec5SDimitry Andric   }
31710b57cec5SDimitry Andric   if (error.Success())
31720b57cec5SDimitry Andric     error.SetErrorToGenericError();
31730b57cec5SDimitry Andric   return error;
31740b57cec5SDimitry Andric }
31750b57cec5SDimitry Andric 
31760b57cec5SDimitry Andric Status ProcessGDBRemote::DisableWatchpoint(Watchpoint *wp, bool notify) {
31770b57cec5SDimitry Andric   Status error;
31780b57cec5SDimitry Andric   if (wp) {
31790b57cec5SDimitry Andric     user_id_t watchID = wp->GetID();
31800b57cec5SDimitry Andric 
31810b57cec5SDimitry Andric     Log *log(
31820b57cec5SDimitry Andric         ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_WATCHPOINTS));
31830b57cec5SDimitry Andric 
31840b57cec5SDimitry Andric     addr_t addr = wp->GetLoadAddress();
31850b57cec5SDimitry Andric 
31869dba64beSDimitry Andric     LLDB_LOGF(log,
31879dba64beSDimitry Andric               "ProcessGDBRemote::DisableWatchpoint (watchID = %" PRIu64
31880b57cec5SDimitry Andric               ") addr = 0x%8.8" PRIx64,
31890b57cec5SDimitry Andric               watchID, (uint64_t)addr);
31900b57cec5SDimitry Andric 
31910b57cec5SDimitry Andric     if (!wp->IsEnabled()) {
31929dba64beSDimitry Andric       LLDB_LOGF(log,
31939dba64beSDimitry Andric                 "ProcessGDBRemote::DisableWatchpoint (watchID = %" PRIu64
31940b57cec5SDimitry Andric                 ") addr = 0x%8.8" PRIx64 " -- SUCCESS (already disabled)",
31950b57cec5SDimitry Andric                 watchID, (uint64_t)addr);
31960b57cec5SDimitry Andric       // See also 'class WatchpointSentry' within StopInfo.cpp. This disabling
31970b57cec5SDimitry Andric       // attempt might come from the user-supplied actions, we'll route it in
31980b57cec5SDimitry Andric       // order for the watchpoint object to intelligently process this action.
31990b57cec5SDimitry Andric       wp->SetEnabled(false, notify);
32000b57cec5SDimitry Andric       return error;
32010b57cec5SDimitry Andric     }
32020b57cec5SDimitry Andric 
32030b57cec5SDimitry Andric     if (wp->IsHardware()) {
32040b57cec5SDimitry Andric       GDBStoppointType type = GetGDBStoppointType(wp);
32050b57cec5SDimitry Andric       // Pass down an appropriate z/Z packet...
32060b57cec5SDimitry Andric       if (m_gdb_comm.SendGDBStoppointTypePacket(type, false, addr,
3207fe6060f1SDimitry Andric                                                 wp->GetByteSize(),
3208fe6060f1SDimitry Andric                                                 GetInterruptTimeout()) == 0) {
32090b57cec5SDimitry Andric         wp->SetEnabled(false, notify);
32100b57cec5SDimitry Andric         return error;
32110b57cec5SDimitry Andric       } else
32120b57cec5SDimitry Andric         error.SetErrorString("sending gdb watchpoint packet failed");
32130b57cec5SDimitry Andric     }
32140b57cec5SDimitry Andric     // TODO: clear software watchpoints if we implement them
32150b57cec5SDimitry Andric   } else {
32160b57cec5SDimitry Andric     error.SetErrorString("Watchpoint argument was NULL.");
32170b57cec5SDimitry Andric   }
32180b57cec5SDimitry Andric   if (error.Success())
32190b57cec5SDimitry Andric     error.SetErrorToGenericError();
32200b57cec5SDimitry Andric   return error;
32210b57cec5SDimitry Andric }
32220b57cec5SDimitry Andric 
32230b57cec5SDimitry Andric void ProcessGDBRemote::Clear() {
32240b57cec5SDimitry Andric   m_thread_list_real.Clear();
32250b57cec5SDimitry Andric   m_thread_list.Clear();
32260b57cec5SDimitry Andric }
32270b57cec5SDimitry Andric 
32280b57cec5SDimitry Andric Status ProcessGDBRemote::DoSignal(int signo) {
32290b57cec5SDimitry Andric   Status error;
32300b57cec5SDimitry Andric   Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
32319dba64beSDimitry Andric   LLDB_LOGF(log, "ProcessGDBRemote::DoSignal (signal = %d)", signo);
32320b57cec5SDimitry Andric 
3233fe6060f1SDimitry Andric   if (!m_gdb_comm.SendAsyncSignal(signo, GetInterruptTimeout()))
32340b57cec5SDimitry Andric     error.SetErrorStringWithFormat("failed to send signal %i", signo);
32350b57cec5SDimitry Andric   return error;
32360b57cec5SDimitry Andric }
32370b57cec5SDimitry Andric 
32385ffd83dbSDimitry Andric Status ProcessGDBRemote::ConnectToReplayServer() {
32395ffd83dbSDimitry Andric   Status status = m_gdb_replay_server.Connect(m_gdb_comm);
32405ffd83dbSDimitry Andric   if (status.Fail())
32415ffd83dbSDimitry Andric     return status;
32420b57cec5SDimitry Andric 
3243480093f4SDimitry Andric   // Enable replay mode.
3244480093f4SDimitry Andric   m_replay_mode = true;
3245480093f4SDimitry Andric 
32460b57cec5SDimitry Andric   // Start server thread.
32470b57cec5SDimitry Andric   m_gdb_replay_server.StartAsyncThread();
32480b57cec5SDimitry Andric 
32490b57cec5SDimitry Andric   // Start client thread.
32500b57cec5SDimitry Andric   StartAsyncThread();
32510b57cec5SDimitry Andric 
32520b57cec5SDimitry Andric   // Do the usual setup.
32530b57cec5SDimitry Andric   return ConnectToDebugserver("");
32540b57cec5SDimitry Andric }
32550b57cec5SDimitry Andric 
32560b57cec5SDimitry Andric Status
32570b57cec5SDimitry Andric ProcessGDBRemote::EstablishConnectionIfNeeded(const ProcessInfo &process_info) {
32580b57cec5SDimitry Andric   // Make sure we aren't already connected?
32590b57cec5SDimitry Andric   if (m_gdb_comm.IsConnected())
32600b57cec5SDimitry Andric     return Status();
32610b57cec5SDimitry Andric 
32620b57cec5SDimitry Andric   PlatformSP platform_sp(GetTarget().GetPlatform());
32630b57cec5SDimitry Andric   if (platform_sp && !platform_sp->IsHost())
32640b57cec5SDimitry Andric     return Status("Lost debug server connection");
32650b57cec5SDimitry Andric 
32665ffd83dbSDimitry Andric   if (repro::Reproducer::Instance().IsReplaying())
32675ffd83dbSDimitry Andric     return ConnectToReplayServer();
32680b57cec5SDimitry Andric 
32690b57cec5SDimitry Andric   auto error = LaunchAndConnectToDebugserver(process_info);
32700b57cec5SDimitry Andric   if (error.Fail()) {
32710b57cec5SDimitry Andric     const char *error_string = error.AsCString();
32720b57cec5SDimitry Andric     if (error_string == nullptr)
32730b57cec5SDimitry Andric       error_string = "unable to launch " DEBUGSERVER_BASENAME;
32740b57cec5SDimitry Andric   }
32750b57cec5SDimitry Andric   return error;
32760b57cec5SDimitry Andric }
32770b57cec5SDimitry Andric #if !defined(_WIN32)
32780b57cec5SDimitry Andric #define USE_SOCKETPAIR_FOR_LOCAL_CONNECTION 1
32790b57cec5SDimitry Andric #endif
32800b57cec5SDimitry Andric 
32810b57cec5SDimitry Andric #ifdef USE_SOCKETPAIR_FOR_LOCAL_CONNECTION
32820b57cec5SDimitry Andric static bool SetCloexecFlag(int fd) {
32830b57cec5SDimitry Andric #if defined(FD_CLOEXEC)
32840b57cec5SDimitry Andric   int flags = ::fcntl(fd, F_GETFD);
32850b57cec5SDimitry Andric   if (flags == -1)
32860b57cec5SDimitry Andric     return false;
32870b57cec5SDimitry Andric   return (::fcntl(fd, F_SETFD, flags | FD_CLOEXEC) == 0);
32880b57cec5SDimitry Andric #else
32890b57cec5SDimitry Andric   return false;
32900b57cec5SDimitry Andric #endif
32910b57cec5SDimitry Andric }
32920b57cec5SDimitry Andric #endif
32930b57cec5SDimitry Andric 
32940b57cec5SDimitry Andric Status ProcessGDBRemote::LaunchAndConnectToDebugserver(
32950b57cec5SDimitry Andric     const ProcessInfo &process_info) {
32960b57cec5SDimitry Andric   using namespace std::placeholders; // For _1, _2, etc.
32970b57cec5SDimitry Andric 
32980b57cec5SDimitry Andric   Status error;
32990b57cec5SDimitry Andric   if (m_debugserver_pid == LLDB_INVALID_PROCESS_ID) {
33000b57cec5SDimitry Andric     // If we locate debugserver, keep that located version around
33010b57cec5SDimitry Andric     static FileSpec g_debugserver_file_spec;
33020b57cec5SDimitry Andric 
33030b57cec5SDimitry Andric     ProcessLaunchInfo debugserver_launch_info;
33040b57cec5SDimitry Andric     // Make debugserver run in its own session so signals generated by special
33050b57cec5SDimitry Andric     // terminal key sequences (^C) don't affect debugserver.
33060b57cec5SDimitry Andric     debugserver_launch_info.SetLaunchInSeparateProcessGroup(true);
33070b57cec5SDimitry Andric 
33080b57cec5SDimitry Andric     const std::weak_ptr<ProcessGDBRemote> this_wp =
33090b57cec5SDimitry Andric         std::static_pointer_cast<ProcessGDBRemote>(shared_from_this());
33100b57cec5SDimitry Andric     debugserver_launch_info.SetMonitorProcessCallback(
33110b57cec5SDimitry Andric         std::bind(MonitorDebugserverProcess, this_wp, _1, _2, _3, _4), false);
33120b57cec5SDimitry Andric     debugserver_launch_info.SetUserID(process_info.GetUserID());
33130b57cec5SDimitry Andric 
33145ffd83dbSDimitry Andric #if defined(__APPLE__)
33155ffd83dbSDimitry Andric     // On macOS 11, we need to support x86_64 applications translated to
33165ffd83dbSDimitry Andric     // arm64. We check whether a binary is translated and spawn the correct
33175ffd83dbSDimitry Andric     // debugserver accordingly.
33185ffd83dbSDimitry Andric     int mib[] = { CTL_KERN, KERN_PROC, KERN_PROC_PID,
33195ffd83dbSDimitry Andric                   static_cast<int>(process_info.GetProcessID()) };
33205ffd83dbSDimitry Andric     struct kinfo_proc processInfo;
33215ffd83dbSDimitry Andric     size_t bufsize = sizeof(processInfo);
33225ffd83dbSDimitry Andric     if (sysctl(mib, (unsigned)(sizeof(mib)/sizeof(int)), &processInfo,
33235ffd83dbSDimitry Andric                &bufsize, NULL, 0) == 0 && bufsize > 0) {
33245ffd83dbSDimitry Andric       if (processInfo.kp_proc.p_flag & P_TRANSLATED) {
33255ffd83dbSDimitry Andric         FileSpec rosetta_debugserver("/Library/Apple/usr/libexec/oah/debugserver");
33265ffd83dbSDimitry Andric         debugserver_launch_info.SetExecutableFile(rosetta_debugserver, false);
33275ffd83dbSDimitry Andric       }
33285ffd83dbSDimitry Andric     }
33295ffd83dbSDimitry Andric #endif
33305ffd83dbSDimitry Andric 
33310b57cec5SDimitry Andric     int communication_fd = -1;
33320b57cec5SDimitry Andric #ifdef USE_SOCKETPAIR_FOR_LOCAL_CONNECTION
33330b57cec5SDimitry Andric     // Use a socketpair on non-Windows systems for security and performance
33340b57cec5SDimitry Andric     // reasons.
33350b57cec5SDimitry Andric     int sockets[2]; /* the pair of socket descriptors */
33360b57cec5SDimitry Andric     if (socketpair(AF_UNIX, SOCK_STREAM, 0, sockets) == -1) {
33370b57cec5SDimitry Andric       error.SetErrorToErrno();
33380b57cec5SDimitry Andric       return error;
33390b57cec5SDimitry Andric     }
33400b57cec5SDimitry Andric 
33410b57cec5SDimitry Andric     int our_socket = sockets[0];
33420b57cec5SDimitry Andric     int gdb_socket = sockets[1];
33439dba64beSDimitry Andric     auto cleanup_our = llvm::make_scope_exit([&]() { close(our_socket); });
33449dba64beSDimitry Andric     auto cleanup_gdb = llvm::make_scope_exit([&]() { close(gdb_socket); });
33450b57cec5SDimitry Andric 
33460b57cec5SDimitry Andric     // Don't let any child processes inherit our communication socket
33470b57cec5SDimitry Andric     SetCloexecFlag(our_socket);
33480b57cec5SDimitry Andric     communication_fd = gdb_socket;
33490b57cec5SDimitry Andric #endif
33500b57cec5SDimitry Andric 
33510b57cec5SDimitry Andric     error = m_gdb_comm.StartDebugserverProcess(
33520b57cec5SDimitry Andric         nullptr, GetTarget().GetPlatform().get(), debugserver_launch_info,
33530b57cec5SDimitry Andric         nullptr, nullptr, communication_fd);
33540b57cec5SDimitry Andric 
33550b57cec5SDimitry Andric     if (error.Success())
33560b57cec5SDimitry Andric       m_debugserver_pid = debugserver_launch_info.GetProcessID();
33570b57cec5SDimitry Andric     else
33580b57cec5SDimitry Andric       m_debugserver_pid = LLDB_INVALID_PROCESS_ID;
33590b57cec5SDimitry Andric 
33600b57cec5SDimitry Andric     if (m_debugserver_pid != LLDB_INVALID_PROCESS_ID) {
33610b57cec5SDimitry Andric #ifdef USE_SOCKETPAIR_FOR_LOCAL_CONNECTION
33620b57cec5SDimitry Andric       // Our process spawned correctly, we can now set our connection to use
33630b57cec5SDimitry Andric       // our end of the socket pair
33649dba64beSDimitry Andric       cleanup_our.release();
33655ffd83dbSDimitry Andric       m_gdb_comm.SetConnection(
33665ffd83dbSDimitry Andric           std::make_unique<ConnectionFileDescriptor>(our_socket, true));
33670b57cec5SDimitry Andric #endif
33680b57cec5SDimitry Andric       StartAsyncThread();
33690b57cec5SDimitry Andric     }
33700b57cec5SDimitry Andric 
33710b57cec5SDimitry Andric     if (error.Fail()) {
33720b57cec5SDimitry Andric       Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
33730b57cec5SDimitry Andric 
33749dba64beSDimitry Andric       LLDB_LOGF(log, "failed to start debugserver process: %s",
33750b57cec5SDimitry Andric                 error.AsCString());
33760b57cec5SDimitry Andric       return error;
33770b57cec5SDimitry Andric     }
33780b57cec5SDimitry Andric 
33790b57cec5SDimitry Andric     if (m_gdb_comm.IsConnected()) {
33800b57cec5SDimitry Andric       // Finish the connection process by doing the handshake without
33810b57cec5SDimitry Andric       // connecting (send NULL URL)
33820b57cec5SDimitry Andric       error = ConnectToDebugserver("");
33830b57cec5SDimitry Andric     } else {
33840b57cec5SDimitry Andric       error.SetErrorString("connection failed");
33850b57cec5SDimitry Andric     }
33860b57cec5SDimitry Andric   }
33870b57cec5SDimitry Andric   return error;
33880b57cec5SDimitry Andric }
33890b57cec5SDimitry Andric 
33900b57cec5SDimitry Andric bool ProcessGDBRemote::MonitorDebugserverProcess(
33910b57cec5SDimitry Andric     std::weak_ptr<ProcessGDBRemote> process_wp, lldb::pid_t debugserver_pid,
33920b57cec5SDimitry Andric     bool exited,    // True if the process did exit
33930b57cec5SDimitry Andric     int signo,      // Zero for no signal
33940b57cec5SDimitry Andric     int exit_status // Exit value of process if signal is zero
33950b57cec5SDimitry Andric ) {
33960b57cec5SDimitry Andric   // "debugserver_pid" argument passed in is the process ID for debugserver
33970b57cec5SDimitry Andric   // that we are tracking...
33980b57cec5SDimitry Andric   Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
33990b57cec5SDimitry Andric   const bool handled = true;
34000b57cec5SDimitry Andric 
34019dba64beSDimitry Andric   LLDB_LOGF(log,
34029dba64beSDimitry Andric             "ProcessGDBRemote::%s(process_wp, pid=%" PRIu64
34030b57cec5SDimitry Andric             ", signo=%i (0x%x), exit_status=%i)",
34040b57cec5SDimitry Andric             __FUNCTION__, debugserver_pid, signo, signo, exit_status);
34050b57cec5SDimitry Andric 
34060b57cec5SDimitry Andric   std::shared_ptr<ProcessGDBRemote> process_sp = process_wp.lock();
34079dba64beSDimitry Andric   LLDB_LOGF(log, "ProcessGDBRemote::%s(process = %p)", __FUNCTION__,
34080b57cec5SDimitry Andric             static_cast<void *>(process_sp.get()));
34090b57cec5SDimitry Andric   if (!process_sp || process_sp->m_debugserver_pid != debugserver_pid)
34100b57cec5SDimitry Andric     return handled;
34110b57cec5SDimitry Andric 
34120b57cec5SDimitry Andric   // Sleep for a half a second to make sure our inferior process has time to
34130b57cec5SDimitry Andric   // set its exit status before we set it incorrectly when both the debugserver
34140b57cec5SDimitry Andric   // and the inferior process shut down.
34159dba64beSDimitry Andric   std::this_thread::sleep_for(std::chrono::milliseconds(500));
34169dba64beSDimitry Andric 
34170b57cec5SDimitry Andric   // If our process hasn't yet exited, debugserver might have died. If the
34180b57cec5SDimitry Andric   // process did exit, then we are reaping it.
34190b57cec5SDimitry Andric   const StateType state = process_sp->GetState();
34200b57cec5SDimitry Andric 
34210b57cec5SDimitry Andric   if (state != eStateInvalid && state != eStateUnloaded &&
34220b57cec5SDimitry Andric       state != eStateExited && state != eStateDetached) {
34230b57cec5SDimitry Andric     char error_str[1024];
34240b57cec5SDimitry Andric     if (signo) {
34250b57cec5SDimitry Andric       const char *signal_cstr =
34260b57cec5SDimitry Andric           process_sp->GetUnixSignals()->GetSignalAsCString(signo);
34270b57cec5SDimitry Andric       if (signal_cstr)
34280b57cec5SDimitry Andric         ::snprintf(error_str, sizeof(error_str),
34290b57cec5SDimitry Andric                    DEBUGSERVER_BASENAME " died with signal %s", signal_cstr);
34300b57cec5SDimitry Andric       else
34310b57cec5SDimitry Andric         ::snprintf(error_str, sizeof(error_str),
34320b57cec5SDimitry Andric                    DEBUGSERVER_BASENAME " died with signal %i", signo);
34330b57cec5SDimitry Andric     } else {
34340b57cec5SDimitry Andric       ::snprintf(error_str, sizeof(error_str),
34350b57cec5SDimitry Andric                  DEBUGSERVER_BASENAME " died with an exit status of 0x%8.8x",
34360b57cec5SDimitry Andric                  exit_status);
34370b57cec5SDimitry Andric     }
34380b57cec5SDimitry Andric 
34390b57cec5SDimitry Andric     process_sp->SetExitStatus(-1, error_str);
34400b57cec5SDimitry Andric   }
34410b57cec5SDimitry Andric   // Debugserver has exited we need to let our ProcessGDBRemote know that it no
34420b57cec5SDimitry Andric   // longer has a debugserver instance
34430b57cec5SDimitry Andric   process_sp->m_debugserver_pid = LLDB_INVALID_PROCESS_ID;
34440b57cec5SDimitry Andric   return handled;
34450b57cec5SDimitry Andric }
34460b57cec5SDimitry Andric 
34470b57cec5SDimitry Andric void ProcessGDBRemote::KillDebugserverProcess() {
34480b57cec5SDimitry Andric   m_gdb_comm.Disconnect();
34490b57cec5SDimitry Andric   if (m_debugserver_pid != LLDB_INVALID_PROCESS_ID) {
34500b57cec5SDimitry Andric     Host::Kill(m_debugserver_pid, SIGINT);
34510b57cec5SDimitry Andric     m_debugserver_pid = LLDB_INVALID_PROCESS_ID;
34520b57cec5SDimitry Andric   }
34530b57cec5SDimitry Andric }
34540b57cec5SDimitry Andric 
34550b57cec5SDimitry Andric void ProcessGDBRemote::Initialize() {
34560b57cec5SDimitry Andric   static llvm::once_flag g_once_flag;
34570b57cec5SDimitry Andric 
34580b57cec5SDimitry Andric   llvm::call_once(g_once_flag, []() {
34590b57cec5SDimitry Andric     PluginManager::RegisterPlugin(GetPluginNameStatic(),
34600b57cec5SDimitry Andric                                   GetPluginDescriptionStatic(), CreateInstance,
34610b57cec5SDimitry Andric                                   DebuggerInitialize);
34620b57cec5SDimitry Andric   });
34630b57cec5SDimitry Andric }
34640b57cec5SDimitry Andric 
34650b57cec5SDimitry Andric void ProcessGDBRemote::DebuggerInitialize(Debugger &debugger) {
34660b57cec5SDimitry Andric   if (!PluginManager::GetSettingForProcessPlugin(
34670b57cec5SDimitry Andric           debugger, PluginProperties::GetSettingName())) {
34680b57cec5SDimitry Andric     const bool is_global_setting = true;
34690b57cec5SDimitry Andric     PluginManager::CreateSettingForProcessPlugin(
3470349cc55cSDimitry Andric         debugger, GetGlobalPluginProperties().GetValueProperties(),
34710b57cec5SDimitry Andric         ConstString("Properties for the gdb-remote process plug-in."),
34720b57cec5SDimitry Andric         is_global_setting);
34730b57cec5SDimitry Andric   }
34740b57cec5SDimitry Andric }
34750b57cec5SDimitry Andric 
34760b57cec5SDimitry Andric bool ProcessGDBRemote::StartAsyncThread() {
34770b57cec5SDimitry Andric   Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
34780b57cec5SDimitry Andric 
34799dba64beSDimitry Andric   LLDB_LOGF(log, "ProcessGDBRemote::%s ()", __FUNCTION__);
34800b57cec5SDimitry Andric 
34810b57cec5SDimitry Andric   std::lock_guard<std::recursive_mutex> guard(m_async_thread_state_mutex);
34820b57cec5SDimitry Andric   if (!m_async_thread.IsJoinable()) {
34830b57cec5SDimitry Andric     // Create a thread that watches our internal state and controls which
34840b57cec5SDimitry Andric     // events make it to clients (into the DCProcess event queue).
34850b57cec5SDimitry Andric 
34860b57cec5SDimitry Andric     llvm::Expected<HostThread> async_thread = ThreadLauncher::LaunchThread(
34870b57cec5SDimitry Andric         "<lldb.process.gdb-remote.async>", ProcessGDBRemote::AsyncThread, this);
34880b57cec5SDimitry Andric     if (!async_thread) {
3489480093f4SDimitry Andric       LLDB_LOG_ERROR(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_HOST),
3490480093f4SDimitry Andric                      async_thread.takeError(),
3491480093f4SDimitry Andric                      "failed to launch host thread: {}");
34920b57cec5SDimitry Andric       return false;
34930b57cec5SDimitry Andric     }
34940b57cec5SDimitry Andric     m_async_thread = *async_thread;
34959dba64beSDimitry Andric   } else
34969dba64beSDimitry Andric     LLDB_LOGF(log,
34979dba64beSDimitry Andric               "ProcessGDBRemote::%s () - Called when Async thread was "
34980b57cec5SDimitry Andric               "already running.",
34990b57cec5SDimitry Andric               __FUNCTION__);
35000b57cec5SDimitry Andric 
35010b57cec5SDimitry Andric   return m_async_thread.IsJoinable();
35020b57cec5SDimitry Andric }
35030b57cec5SDimitry Andric 
35040b57cec5SDimitry Andric void ProcessGDBRemote::StopAsyncThread() {
35050b57cec5SDimitry Andric   Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
35060b57cec5SDimitry Andric 
35079dba64beSDimitry Andric   LLDB_LOGF(log, "ProcessGDBRemote::%s ()", __FUNCTION__);
35080b57cec5SDimitry Andric 
35090b57cec5SDimitry Andric   std::lock_guard<std::recursive_mutex> guard(m_async_thread_state_mutex);
35100b57cec5SDimitry Andric   if (m_async_thread.IsJoinable()) {
35110b57cec5SDimitry Andric     m_async_broadcaster.BroadcastEvent(eBroadcastBitAsyncThreadShouldExit);
35120b57cec5SDimitry Andric 
35130b57cec5SDimitry Andric     //  This will shut down the async thread.
35140b57cec5SDimitry Andric     m_gdb_comm.Disconnect(); // Disconnect from the debug server.
35150b57cec5SDimitry Andric 
35160b57cec5SDimitry Andric     // Stop the stdio thread
35170b57cec5SDimitry Andric     m_async_thread.Join(nullptr);
35180b57cec5SDimitry Andric     m_async_thread.Reset();
35199dba64beSDimitry Andric   } else
35209dba64beSDimitry Andric     LLDB_LOGF(
35219dba64beSDimitry Andric         log,
35220b57cec5SDimitry Andric         "ProcessGDBRemote::%s () - Called when Async thread was not running.",
35230b57cec5SDimitry Andric         __FUNCTION__);
35240b57cec5SDimitry Andric }
35250b57cec5SDimitry Andric 
35260b57cec5SDimitry Andric thread_result_t ProcessGDBRemote::AsyncThread(void *arg) {
35270b57cec5SDimitry Andric   ProcessGDBRemote *process = (ProcessGDBRemote *)arg;
35280b57cec5SDimitry Andric 
35290b57cec5SDimitry Andric   Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
35309dba64beSDimitry Andric   LLDB_LOGF(log,
35319dba64beSDimitry Andric             "ProcessGDBRemote::%s (arg = %p, pid = %" PRIu64
35320b57cec5SDimitry Andric             ") thread starting...",
35330b57cec5SDimitry Andric             __FUNCTION__, arg, process->GetID());
35340b57cec5SDimitry Andric 
35350b57cec5SDimitry Andric   EventSP event_sp;
3536fe6060f1SDimitry Andric 
3537fe6060f1SDimitry Andric   // We need to ignore any packets that come in after we have
3538fe6060f1SDimitry Andric   // have decided the process has exited.  There are some
3539fe6060f1SDimitry Andric   // situations, for instance when we try to interrupt a running
3540fe6060f1SDimitry Andric   // process and the interrupt fails, where another packet might
3541fe6060f1SDimitry Andric   // get delivered after we've decided to give up on the process.
3542fe6060f1SDimitry Andric   // But once we've decided we are done with the process we will
3543fe6060f1SDimitry Andric   // not be in a state to do anything useful with new packets.
3544fe6060f1SDimitry Andric   // So it is safer to simply ignore any remaining packets by
3545fe6060f1SDimitry Andric   // explicitly checking for eStateExited before reentering the
3546fe6060f1SDimitry Andric   // fetch loop.
3547fe6060f1SDimitry Andric 
35480b57cec5SDimitry Andric   bool done = false;
3549fe6060f1SDimitry Andric   while (!done && process->GetPrivateState() != eStateExited) {
35509dba64beSDimitry Andric     LLDB_LOGF(log,
35519dba64beSDimitry Andric               "ProcessGDBRemote::%s (arg = %p, pid = %" PRIu64
35520b57cec5SDimitry Andric               ") listener.WaitForEvent (NULL, event_sp)...",
35530b57cec5SDimitry Andric               __FUNCTION__, arg, process->GetID());
3554fe6060f1SDimitry Andric 
35550b57cec5SDimitry Andric     if (process->m_async_listener_sp->GetEvent(event_sp, llvm::None)) {
35560b57cec5SDimitry Andric       const uint32_t event_type = event_sp->GetType();
35570b57cec5SDimitry Andric       if (event_sp->BroadcasterIs(&process->m_async_broadcaster)) {
35589dba64beSDimitry Andric         LLDB_LOGF(log,
35599dba64beSDimitry Andric                   "ProcessGDBRemote::%s (arg = %p, pid = %" PRIu64
35600b57cec5SDimitry Andric                   ") Got an event of type: %d...",
35610b57cec5SDimitry Andric                   __FUNCTION__, arg, process->GetID(), event_type);
35620b57cec5SDimitry Andric 
35630b57cec5SDimitry Andric         switch (event_type) {
35640b57cec5SDimitry Andric         case eBroadcastBitAsyncContinue: {
35650b57cec5SDimitry Andric           const EventDataBytes *continue_packet =
35660b57cec5SDimitry Andric               EventDataBytes::GetEventDataFromEvent(event_sp.get());
35670b57cec5SDimitry Andric 
35680b57cec5SDimitry Andric           if (continue_packet) {
35690b57cec5SDimitry Andric             const char *continue_cstr =
35700b57cec5SDimitry Andric                 (const char *)continue_packet->GetBytes();
35710b57cec5SDimitry Andric             const size_t continue_cstr_len = continue_packet->GetByteSize();
35729dba64beSDimitry Andric             LLDB_LOGF(log,
35739dba64beSDimitry Andric                       "ProcessGDBRemote::%s (arg = %p, pid = %" PRIu64
35740b57cec5SDimitry Andric                       ") got eBroadcastBitAsyncContinue: %s",
35750b57cec5SDimitry Andric                       __FUNCTION__, arg, process->GetID(), continue_cstr);
35760b57cec5SDimitry Andric 
35770b57cec5SDimitry Andric             if (::strstr(continue_cstr, "vAttach") == nullptr)
35780b57cec5SDimitry Andric               process->SetPrivateState(eStateRunning);
35790b57cec5SDimitry Andric             StringExtractorGDBRemote response;
35800b57cec5SDimitry Andric 
35810b57cec5SDimitry Andric             StateType stop_state =
35820b57cec5SDimitry Andric                 process->GetGDBRemote().SendContinuePacketAndWaitForResponse(
35830b57cec5SDimitry Andric                     *process, *process->GetUnixSignals(),
35840b57cec5SDimitry Andric                     llvm::StringRef(continue_cstr, continue_cstr_len),
3585349cc55cSDimitry Andric                     process->GetInterruptTimeout(), response);
35860b57cec5SDimitry Andric 
35870b57cec5SDimitry Andric             // We need to immediately clear the thread ID list so we are sure
35880b57cec5SDimitry Andric             // to get a valid list of threads. The thread ID list might be
35890b57cec5SDimitry Andric             // contained within the "response", or the stop reply packet that
35900b57cec5SDimitry Andric             // caused the stop. So clear it now before we give the stop reply
35910b57cec5SDimitry Andric             // packet to the process using the
35920b57cec5SDimitry Andric             // process->SetLastStopPacket()...
35930b57cec5SDimitry Andric             process->ClearThreadIDList();
35940b57cec5SDimitry Andric 
35950b57cec5SDimitry Andric             switch (stop_state) {
35960b57cec5SDimitry Andric             case eStateStopped:
35970b57cec5SDimitry Andric             case eStateCrashed:
35980b57cec5SDimitry Andric             case eStateSuspended:
35990b57cec5SDimitry Andric               process->SetLastStopPacket(response);
36000b57cec5SDimitry Andric               process->SetPrivateState(stop_state);
36010b57cec5SDimitry Andric               break;
36020b57cec5SDimitry Andric 
36030b57cec5SDimitry Andric             case eStateExited: {
36040b57cec5SDimitry Andric               process->SetLastStopPacket(response);
36050b57cec5SDimitry Andric               process->ClearThreadIDList();
36060b57cec5SDimitry Andric               response.SetFilePos(1);
36070b57cec5SDimitry Andric 
36080b57cec5SDimitry Andric               int exit_status = response.GetHexU8();
36090b57cec5SDimitry Andric               std::string desc_string;
3610349cc55cSDimitry Andric               if (response.GetBytesLeft() > 0 && response.GetChar('-') == ';') {
36110b57cec5SDimitry Andric                 llvm::StringRef desc_str;
36120b57cec5SDimitry Andric                 llvm::StringRef desc_token;
36130b57cec5SDimitry Andric                 while (response.GetNameColonValue(desc_token, desc_str)) {
36140b57cec5SDimitry Andric                   if (desc_token != "description")
36150b57cec5SDimitry Andric                     continue;
36160b57cec5SDimitry Andric                   StringExtractor extractor(desc_str);
36170b57cec5SDimitry Andric                   extractor.GetHexByteString(desc_string);
36180b57cec5SDimitry Andric                 }
36190b57cec5SDimitry Andric               }
36200b57cec5SDimitry Andric               process->SetExitStatus(exit_status, desc_string.c_str());
36210b57cec5SDimitry Andric               done = true;
36220b57cec5SDimitry Andric               break;
36230b57cec5SDimitry Andric             }
36240b57cec5SDimitry Andric             case eStateInvalid: {
36250b57cec5SDimitry Andric               // Check to see if we were trying to attach and if we got back
36260b57cec5SDimitry Andric               // the "E87" error code from debugserver -- this indicates that
36270b57cec5SDimitry Andric               // the process is not debuggable.  Return a slightly more
36280b57cec5SDimitry Andric               // helpful error message about why the attach failed.
36290b57cec5SDimitry Andric               if (::strstr(continue_cstr, "vAttach") != nullptr &&
36300b57cec5SDimitry Andric                   response.GetError() == 0x87) {
36310b57cec5SDimitry Andric                 process->SetExitStatus(-1, "cannot attach to process due to "
36320b57cec5SDimitry Andric                                            "System Integrity Protection");
36330b57cec5SDimitry Andric               } else if (::strstr(continue_cstr, "vAttach") != nullptr &&
36340b57cec5SDimitry Andric                          response.GetStatus().Fail()) {
36350b57cec5SDimitry Andric                 process->SetExitStatus(-1, response.GetStatus().AsCString());
36360b57cec5SDimitry Andric               } else {
36370b57cec5SDimitry Andric                 process->SetExitStatus(-1, "lost connection");
36380b57cec5SDimitry Andric               }
3639fe6060f1SDimitry Andric               done = true;
36400b57cec5SDimitry Andric               break;
36410b57cec5SDimitry Andric             }
36420b57cec5SDimitry Andric 
36430b57cec5SDimitry Andric             default:
36440b57cec5SDimitry Andric               process->SetPrivateState(stop_state);
36450b57cec5SDimitry Andric               break;
36460b57cec5SDimitry Andric             }   // switch(stop_state)
36470b57cec5SDimitry Andric           }     // if (continue_packet)
36485ffd83dbSDimitry Andric         }       // case eBroadcastBitAsyncContinue
36490b57cec5SDimitry Andric         break;
36500b57cec5SDimitry Andric 
36510b57cec5SDimitry Andric         case eBroadcastBitAsyncThreadShouldExit:
36529dba64beSDimitry Andric           LLDB_LOGF(log,
36539dba64beSDimitry Andric                     "ProcessGDBRemote::%s (arg = %p, pid = %" PRIu64
36540b57cec5SDimitry Andric                     ") got eBroadcastBitAsyncThreadShouldExit...",
36550b57cec5SDimitry Andric                     __FUNCTION__, arg, process->GetID());
36560b57cec5SDimitry Andric           done = true;
36570b57cec5SDimitry Andric           break;
36580b57cec5SDimitry Andric 
36590b57cec5SDimitry Andric         default:
36609dba64beSDimitry Andric           LLDB_LOGF(log,
36619dba64beSDimitry Andric                     "ProcessGDBRemote::%s (arg = %p, pid = %" PRIu64
36620b57cec5SDimitry Andric                     ") got unknown event 0x%8.8x",
36630b57cec5SDimitry Andric                     __FUNCTION__, arg, process->GetID(), event_type);
36640b57cec5SDimitry Andric           done = true;
36650b57cec5SDimitry Andric           break;
36660b57cec5SDimitry Andric         }
36670b57cec5SDimitry Andric       } else if (event_sp->BroadcasterIs(&process->m_gdb_comm)) {
36680b57cec5SDimitry Andric         switch (event_type) {
36690b57cec5SDimitry Andric         case Communication::eBroadcastBitReadThreadDidExit:
36700b57cec5SDimitry Andric           process->SetExitStatus(-1, "lost connection");
36710b57cec5SDimitry Andric           done = true;
36720b57cec5SDimitry Andric           break;
36730b57cec5SDimitry Andric 
36740b57cec5SDimitry Andric         default:
36759dba64beSDimitry Andric           LLDB_LOGF(log,
36769dba64beSDimitry Andric                     "ProcessGDBRemote::%s (arg = %p, pid = %" PRIu64
36770b57cec5SDimitry Andric                     ") got unknown event 0x%8.8x",
36780b57cec5SDimitry Andric                     __FUNCTION__, arg, process->GetID(), event_type);
36790b57cec5SDimitry Andric           done = true;
36800b57cec5SDimitry Andric           break;
36810b57cec5SDimitry Andric         }
36820b57cec5SDimitry Andric       }
36830b57cec5SDimitry Andric     } else {
36849dba64beSDimitry Andric       LLDB_LOGF(log,
36859dba64beSDimitry Andric                 "ProcessGDBRemote::%s (arg = %p, pid = %" PRIu64
36860b57cec5SDimitry Andric                 ") listener.WaitForEvent (NULL, event_sp) => false",
36870b57cec5SDimitry Andric                 __FUNCTION__, arg, process->GetID());
36880b57cec5SDimitry Andric       done = true;
36890b57cec5SDimitry Andric     }
36900b57cec5SDimitry Andric   }
36910b57cec5SDimitry Andric 
36929dba64beSDimitry Andric   LLDB_LOGF(log,
36939dba64beSDimitry Andric             "ProcessGDBRemote::%s (arg = %p, pid = %" PRIu64
36940b57cec5SDimitry Andric             ") thread exiting...",
36950b57cec5SDimitry Andric             __FUNCTION__, arg, process->GetID());
36960b57cec5SDimitry Andric 
36970b57cec5SDimitry Andric   return {};
36980b57cec5SDimitry Andric }
36990b57cec5SDimitry Andric 
37000b57cec5SDimitry Andric // uint32_t
37010b57cec5SDimitry Andric // ProcessGDBRemote::ListProcessesMatchingName (const char *name, StringList
37020b57cec5SDimitry Andric // &matches, std::vector<lldb::pid_t> &pids)
37030b57cec5SDimitry Andric //{
37040b57cec5SDimitry Andric //    // If we are planning to launch the debugserver remotely, then we need to
37050b57cec5SDimitry Andric //    fire up a debugserver
37060b57cec5SDimitry Andric //    // process and ask it for the list of processes. But if we are local, we
37070b57cec5SDimitry Andric //    can let the Host do it.
37080b57cec5SDimitry Andric //    if (m_local_debugserver)
37090b57cec5SDimitry Andric //    {
37100b57cec5SDimitry Andric //        return Host::ListProcessesMatchingName (name, matches, pids);
37110b57cec5SDimitry Andric //    }
37120b57cec5SDimitry Andric //    else
37130b57cec5SDimitry Andric //    {
37140b57cec5SDimitry Andric //        // FIXME: Implement talking to the remote debugserver.
37150b57cec5SDimitry Andric //        return 0;
37160b57cec5SDimitry Andric //    }
37170b57cec5SDimitry Andric //
37180b57cec5SDimitry Andric //}
37190b57cec5SDimitry Andric //
37200b57cec5SDimitry Andric bool ProcessGDBRemote::NewThreadNotifyBreakpointHit(
37210b57cec5SDimitry Andric     void *baton, StoppointCallbackContext *context, lldb::user_id_t break_id,
37220b57cec5SDimitry Andric     lldb::user_id_t break_loc_id) {
37230b57cec5SDimitry Andric   // I don't think I have to do anything here, just make sure I notice the new
37240b57cec5SDimitry Andric   // thread when it starts to
37250b57cec5SDimitry Andric   // run so I can stop it if that's what I want to do.
37260b57cec5SDimitry Andric   Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_STEP));
37279dba64beSDimitry Andric   LLDB_LOGF(log, "Hit New Thread Notification breakpoint.");
37280b57cec5SDimitry Andric   return false;
37290b57cec5SDimitry Andric }
37300b57cec5SDimitry Andric 
37310b57cec5SDimitry Andric Status ProcessGDBRemote::UpdateAutomaticSignalFiltering() {
37320b57cec5SDimitry Andric   Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
37330b57cec5SDimitry Andric   LLDB_LOG(log, "Check if need to update ignored signals");
37340b57cec5SDimitry Andric 
37350b57cec5SDimitry Andric   // QPassSignals package is not supported by the server, there is no way we
37360b57cec5SDimitry Andric   // can ignore any signals on server side.
37370b57cec5SDimitry Andric   if (!m_gdb_comm.GetQPassSignalsSupported())
37380b57cec5SDimitry Andric     return Status();
37390b57cec5SDimitry Andric 
37400b57cec5SDimitry Andric   // No signals, nothing to send.
37410b57cec5SDimitry Andric   if (m_unix_signals_sp == nullptr)
37420b57cec5SDimitry Andric     return Status();
37430b57cec5SDimitry Andric 
37440b57cec5SDimitry Andric   // Signals' version hasn't changed, no need to send anything.
37450b57cec5SDimitry Andric   uint64_t new_signals_version = m_unix_signals_sp->GetVersion();
37460b57cec5SDimitry Andric   if (new_signals_version == m_last_signals_version) {
37470b57cec5SDimitry Andric     LLDB_LOG(log, "Signals' version hasn't changed. version={0}",
37480b57cec5SDimitry Andric              m_last_signals_version);
37490b57cec5SDimitry Andric     return Status();
37500b57cec5SDimitry Andric   }
37510b57cec5SDimitry Andric 
37520b57cec5SDimitry Andric   auto signals_to_ignore =
37530b57cec5SDimitry Andric       m_unix_signals_sp->GetFilteredSignals(false, false, false);
37540b57cec5SDimitry Andric   Status error = m_gdb_comm.SendSignalsToIgnore(signals_to_ignore);
37550b57cec5SDimitry Andric 
37560b57cec5SDimitry Andric   LLDB_LOG(log,
37570b57cec5SDimitry Andric            "Signals' version changed. old version={0}, new version={1}, "
37580b57cec5SDimitry Andric            "signals ignored={2}, update result={3}",
37590b57cec5SDimitry Andric            m_last_signals_version, new_signals_version,
37600b57cec5SDimitry Andric            signals_to_ignore.size(), error);
37610b57cec5SDimitry Andric 
37620b57cec5SDimitry Andric   if (error.Success())
37630b57cec5SDimitry Andric     m_last_signals_version = new_signals_version;
37640b57cec5SDimitry Andric 
37650b57cec5SDimitry Andric   return error;
37660b57cec5SDimitry Andric }
37670b57cec5SDimitry Andric 
37680b57cec5SDimitry Andric bool ProcessGDBRemote::StartNoticingNewThreads() {
37690b57cec5SDimitry Andric   Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_STEP));
37700b57cec5SDimitry Andric   if (m_thread_create_bp_sp) {
37710b57cec5SDimitry Andric     if (log && log->GetVerbose())
37729dba64beSDimitry Andric       LLDB_LOGF(log, "Enabled noticing new thread breakpoint.");
37730b57cec5SDimitry Andric     m_thread_create_bp_sp->SetEnabled(true);
37740b57cec5SDimitry Andric   } else {
37750b57cec5SDimitry Andric     PlatformSP platform_sp(GetTarget().GetPlatform());
37760b57cec5SDimitry Andric     if (platform_sp) {
37770b57cec5SDimitry Andric       m_thread_create_bp_sp =
37780b57cec5SDimitry Andric           platform_sp->SetThreadCreationBreakpoint(GetTarget());
37790b57cec5SDimitry Andric       if (m_thread_create_bp_sp) {
37800b57cec5SDimitry Andric         if (log && log->GetVerbose())
37819dba64beSDimitry Andric           LLDB_LOGF(
37829dba64beSDimitry Andric               log, "Successfully created new thread notification breakpoint %i",
37830b57cec5SDimitry Andric               m_thread_create_bp_sp->GetID());
37840b57cec5SDimitry Andric         m_thread_create_bp_sp->SetCallback(
37850b57cec5SDimitry Andric             ProcessGDBRemote::NewThreadNotifyBreakpointHit, this, true);
37860b57cec5SDimitry Andric       } else {
37879dba64beSDimitry Andric         LLDB_LOGF(log, "Failed to create new thread notification breakpoint.");
37880b57cec5SDimitry Andric       }
37890b57cec5SDimitry Andric     }
37900b57cec5SDimitry Andric   }
37910b57cec5SDimitry Andric   return m_thread_create_bp_sp.get() != nullptr;
37920b57cec5SDimitry Andric }
37930b57cec5SDimitry Andric 
37940b57cec5SDimitry Andric bool ProcessGDBRemote::StopNoticingNewThreads() {
37950b57cec5SDimitry Andric   Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_STEP));
37960b57cec5SDimitry Andric   if (log && log->GetVerbose())
37979dba64beSDimitry Andric     LLDB_LOGF(log, "Disabling new thread notification breakpoint.");
37980b57cec5SDimitry Andric 
37990b57cec5SDimitry Andric   if (m_thread_create_bp_sp)
38000b57cec5SDimitry Andric     m_thread_create_bp_sp->SetEnabled(false);
38010b57cec5SDimitry Andric 
38020b57cec5SDimitry Andric   return true;
38030b57cec5SDimitry Andric }
38040b57cec5SDimitry Andric 
38050b57cec5SDimitry Andric DynamicLoader *ProcessGDBRemote::GetDynamicLoader() {
38060b57cec5SDimitry Andric   if (m_dyld_up.get() == nullptr)
3807349cc55cSDimitry Andric     m_dyld_up.reset(DynamicLoader::FindPlugin(this, ""));
38080b57cec5SDimitry Andric   return m_dyld_up.get();
38090b57cec5SDimitry Andric }
38100b57cec5SDimitry Andric 
38110b57cec5SDimitry Andric Status ProcessGDBRemote::SendEventData(const char *data) {
38120b57cec5SDimitry Andric   int return_value;
38130b57cec5SDimitry Andric   bool was_supported;
38140b57cec5SDimitry Andric 
38150b57cec5SDimitry Andric   Status error;
38160b57cec5SDimitry Andric 
38170b57cec5SDimitry Andric   return_value = m_gdb_comm.SendLaunchEventDataPacket(data, &was_supported);
38180b57cec5SDimitry Andric   if (return_value != 0) {
38190b57cec5SDimitry Andric     if (!was_supported)
38200b57cec5SDimitry Andric       error.SetErrorString("Sending events is not supported for this process.");
38210b57cec5SDimitry Andric     else
38220b57cec5SDimitry Andric       error.SetErrorStringWithFormat("Error sending event data: %d.",
38230b57cec5SDimitry Andric                                      return_value);
38240b57cec5SDimitry Andric   }
38250b57cec5SDimitry Andric   return error;
38260b57cec5SDimitry Andric }
38270b57cec5SDimitry Andric 
38280b57cec5SDimitry Andric DataExtractor ProcessGDBRemote::GetAuxvData() {
38290b57cec5SDimitry Andric   DataBufferSP buf;
38300b57cec5SDimitry Andric   if (m_gdb_comm.GetQXferAuxvReadSupported()) {
3831349cc55cSDimitry Andric     llvm::Expected<std::string> response = m_gdb_comm.ReadExtFeature("auxv", "");
3832349cc55cSDimitry Andric     if (response)
3833349cc55cSDimitry Andric       buf = std::make_shared<DataBufferHeap>(response->c_str(),
3834349cc55cSDimitry Andric                                              response->length());
3835349cc55cSDimitry Andric     else
3836349cc55cSDimitry Andric       LLDB_LOG_ERROR(
3837349cc55cSDimitry Andric           ProcessGDBRemoteLog::GetLogIfAnyCategoryIsSet(GDBR_LOG_PROCESS),
3838349cc55cSDimitry Andric           response.takeError(), "{0}");
38390b57cec5SDimitry Andric   }
38400b57cec5SDimitry Andric   return DataExtractor(buf, GetByteOrder(), GetAddressByteSize());
38410b57cec5SDimitry Andric }
38420b57cec5SDimitry Andric 
38430b57cec5SDimitry Andric StructuredData::ObjectSP
38440b57cec5SDimitry Andric ProcessGDBRemote::GetExtendedInfoForThread(lldb::tid_t tid) {
38450b57cec5SDimitry Andric   StructuredData::ObjectSP object_sp;
38460b57cec5SDimitry Andric 
38470b57cec5SDimitry Andric   if (m_gdb_comm.GetThreadExtendedInfoSupported()) {
38480b57cec5SDimitry Andric     StructuredData::ObjectSP args_dict(new StructuredData::Dictionary());
38490b57cec5SDimitry Andric     SystemRuntime *runtime = GetSystemRuntime();
38500b57cec5SDimitry Andric     if (runtime) {
38510b57cec5SDimitry Andric       runtime->AddThreadExtendedInfoPacketHints(args_dict);
38520b57cec5SDimitry Andric     }
38530b57cec5SDimitry Andric     args_dict->GetAsDictionary()->AddIntegerItem("thread", tid);
38540b57cec5SDimitry Andric 
38550b57cec5SDimitry Andric     StreamString packet;
38560b57cec5SDimitry Andric     packet << "jThreadExtendedInfo:";
38570b57cec5SDimitry Andric     args_dict->Dump(packet, false);
38580b57cec5SDimitry Andric 
38590b57cec5SDimitry Andric     // FIXME the final character of a JSON dictionary, '}', is the escape
38600b57cec5SDimitry Andric     // character in gdb-remote binary mode.  lldb currently doesn't escape
38610b57cec5SDimitry Andric     // these characters in its packet output -- so we add the quoted version of
38620b57cec5SDimitry Andric     // the } character here manually in case we talk to a debugserver which un-
38630b57cec5SDimitry Andric     // escapes the characters at packet read time.
38640b57cec5SDimitry Andric     packet << (char)(0x7d ^ 0x20);
38650b57cec5SDimitry Andric 
38660b57cec5SDimitry Andric     StringExtractorGDBRemote response;
38670b57cec5SDimitry Andric     response.SetResponseValidatorToJSON();
3868fe6060f1SDimitry Andric     if (m_gdb_comm.SendPacketAndWaitForResponse(packet.GetString(), response) ==
38690b57cec5SDimitry Andric         GDBRemoteCommunication::PacketResult::Success) {
38700b57cec5SDimitry Andric       StringExtractorGDBRemote::ResponseType response_type =
38710b57cec5SDimitry Andric           response.GetResponseType();
38720b57cec5SDimitry Andric       if (response_type == StringExtractorGDBRemote::eResponse) {
38730b57cec5SDimitry Andric         if (!response.Empty()) {
38745ffd83dbSDimitry Andric           object_sp =
38755ffd83dbSDimitry Andric               StructuredData::ParseJSON(std::string(response.GetStringRef()));
38760b57cec5SDimitry Andric         }
38770b57cec5SDimitry Andric       }
38780b57cec5SDimitry Andric     }
38790b57cec5SDimitry Andric   }
38800b57cec5SDimitry Andric   return object_sp;
38810b57cec5SDimitry Andric }
38820b57cec5SDimitry Andric 
38830b57cec5SDimitry Andric StructuredData::ObjectSP ProcessGDBRemote::GetLoadedDynamicLibrariesInfos(
38840b57cec5SDimitry Andric     lldb::addr_t image_list_address, lldb::addr_t image_count) {
38850b57cec5SDimitry Andric 
38860b57cec5SDimitry Andric   StructuredData::ObjectSP args_dict(new StructuredData::Dictionary());
38870b57cec5SDimitry Andric   args_dict->GetAsDictionary()->AddIntegerItem("image_list_address",
38880b57cec5SDimitry Andric                                                image_list_address);
38890b57cec5SDimitry Andric   args_dict->GetAsDictionary()->AddIntegerItem("image_count", image_count);
38900b57cec5SDimitry Andric 
38910b57cec5SDimitry Andric   return GetLoadedDynamicLibrariesInfos_sender(args_dict);
38920b57cec5SDimitry Andric }
38930b57cec5SDimitry Andric 
38940b57cec5SDimitry Andric StructuredData::ObjectSP ProcessGDBRemote::GetLoadedDynamicLibrariesInfos() {
38950b57cec5SDimitry Andric   StructuredData::ObjectSP args_dict(new StructuredData::Dictionary());
38960b57cec5SDimitry Andric 
38970b57cec5SDimitry Andric   args_dict->GetAsDictionary()->AddBooleanItem("fetch_all_solibs", true);
38980b57cec5SDimitry Andric 
38990b57cec5SDimitry Andric   return GetLoadedDynamicLibrariesInfos_sender(args_dict);
39000b57cec5SDimitry Andric }
39010b57cec5SDimitry Andric 
39020b57cec5SDimitry Andric StructuredData::ObjectSP ProcessGDBRemote::GetLoadedDynamicLibrariesInfos(
39030b57cec5SDimitry Andric     const std::vector<lldb::addr_t> &load_addresses) {
39040b57cec5SDimitry Andric   StructuredData::ObjectSP args_dict(new StructuredData::Dictionary());
39050b57cec5SDimitry Andric   StructuredData::ArraySP addresses(new StructuredData::Array);
39060b57cec5SDimitry Andric 
39070b57cec5SDimitry Andric   for (auto addr : load_addresses) {
39080b57cec5SDimitry Andric     StructuredData::ObjectSP addr_sp(new StructuredData::Integer(addr));
39090b57cec5SDimitry Andric     addresses->AddItem(addr_sp);
39100b57cec5SDimitry Andric   }
39110b57cec5SDimitry Andric 
39120b57cec5SDimitry Andric   args_dict->GetAsDictionary()->AddItem("solib_addresses", addresses);
39130b57cec5SDimitry Andric 
39140b57cec5SDimitry Andric   return GetLoadedDynamicLibrariesInfos_sender(args_dict);
39150b57cec5SDimitry Andric }
39160b57cec5SDimitry Andric 
39170b57cec5SDimitry Andric StructuredData::ObjectSP
39180b57cec5SDimitry Andric ProcessGDBRemote::GetLoadedDynamicLibrariesInfos_sender(
39190b57cec5SDimitry Andric     StructuredData::ObjectSP args_dict) {
39200b57cec5SDimitry Andric   StructuredData::ObjectSP object_sp;
39210b57cec5SDimitry Andric 
39220b57cec5SDimitry Andric   if (m_gdb_comm.GetLoadedDynamicLibrariesInfosSupported()) {
39230b57cec5SDimitry Andric     // Scope for the scoped timeout object
39240b57cec5SDimitry Andric     GDBRemoteCommunication::ScopedTimeout timeout(m_gdb_comm,
39250b57cec5SDimitry Andric                                                   std::chrono::seconds(10));
39260b57cec5SDimitry Andric 
39270b57cec5SDimitry Andric     StreamString packet;
39280b57cec5SDimitry Andric     packet << "jGetLoadedDynamicLibrariesInfos:";
39290b57cec5SDimitry Andric     args_dict->Dump(packet, false);
39300b57cec5SDimitry Andric 
39310b57cec5SDimitry Andric     // FIXME the final character of a JSON dictionary, '}', is the escape
39320b57cec5SDimitry Andric     // character in gdb-remote binary mode.  lldb currently doesn't escape
39330b57cec5SDimitry Andric     // these characters in its packet output -- so we add the quoted version of
39340b57cec5SDimitry Andric     // the } character here manually in case we talk to a debugserver which un-
39350b57cec5SDimitry Andric     // escapes the characters at packet read time.
39360b57cec5SDimitry Andric     packet << (char)(0x7d ^ 0x20);
39370b57cec5SDimitry Andric 
39380b57cec5SDimitry Andric     StringExtractorGDBRemote response;
39390b57cec5SDimitry Andric     response.SetResponseValidatorToJSON();
3940fe6060f1SDimitry Andric     if (m_gdb_comm.SendPacketAndWaitForResponse(packet.GetString(), response) ==
39410b57cec5SDimitry Andric         GDBRemoteCommunication::PacketResult::Success) {
39420b57cec5SDimitry Andric       StringExtractorGDBRemote::ResponseType response_type =
39430b57cec5SDimitry Andric           response.GetResponseType();
39440b57cec5SDimitry Andric       if (response_type == StringExtractorGDBRemote::eResponse) {
39450b57cec5SDimitry Andric         if (!response.Empty()) {
39465ffd83dbSDimitry Andric           object_sp =
39475ffd83dbSDimitry Andric               StructuredData::ParseJSON(std::string(response.GetStringRef()));
39480b57cec5SDimitry Andric         }
39490b57cec5SDimitry Andric       }
39500b57cec5SDimitry Andric     }
39510b57cec5SDimitry Andric   }
39520b57cec5SDimitry Andric   return object_sp;
39530b57cec5SDimitry Andric }
39540b57cec5SDimitry Andric 
39550b57cec5SDimitry Andric StructuredData::ObjectSP ProcessGDBRemote::GetSharedCacheInfo() {
39560b57cec5SDimitry Andric   StructuredData::ObjectSP object_sp;
39570b57cec5SDimitry Andric   StructuredData::ObjectSP args_dict(new StructuredData::Dictionary());
39580b57cec5SDimitry Andric 
39590b57cec5SDimitry Andric   if (m_gdb_comm.GetSharedCacheInfoSupported()) {
39600b57cec5SDimitry Andric     StreamString packet;
39610b57cec5SDimitry Andric     packet << "jGetSharedCacheInfo:";
39620b57cec5SDimitry Andric     args_dict->Dump(packet, false);
39630b57cec5SDimitry Andric 
39640b57cec5SDimitry Andric     // FIXME the final character of a JSON dictionary, '}', is the escape
39650b57cec5SDimitry Andric     // character in gdb-remote binary mode.  lldb currently doesn't escape
39660b57cec5SDimitry Andric     // these characters in its packet output -- so we add the quoted version of
39670b57cec5SDimitry Andric     // the } character here manually in case we talk to a debugserver which un-
39680b57cec5SDimitry Andric     // escapes the characters at packet read time.
39690b57cec5SDimitry Andric     packet << (char)(0x7d ^ 0x20);
39700b57cec5SDimitry Andric 
39710b57cec5SDimitry Andric     StringExtractorGDBRemote response;
39720b57cec5SDimitry Andric     response.SetResponseValidatorToJSON();
3973fe6060f1SDimitry Andric     if (m_gdb_comm.SendPacketAndWaitForResponse(packet.GetString(), response) ==
39740b57cec5SDimitry Andric         GDBRemoteCommunication::PacketResult::Success) {
39750b57cec5SDimitry Andric       StringExtractorGDBRemote::ResponseType response_type =
39760b57cec5SDimitry Andric           response.GetResponseType();
39770b57cec5SDimitry Andric       if (response_type == StringExtractorGDBRemote::eResponse) {
39780b57cec5SDimitry Andric         if (!response.Empty()) {
39795ffd83dbSDimitry Andric           object_sp =
39805ffd83dbSDimitry Andric               StructuredData::ParseJSON(std::string(response.GetStringRef()));
39810b57cec5SDimitry Andric         }
39820b57cec5SDimitry Andric       }
39830b57cec5SDimitry Andric     }
39840b57cec5SDimitry Andric   }
39850b57cec5SDimitry Andric   return object_sp;
39860b57cec5SDimitry Andric }
39870b57cec5SDimitry Andric 
39880b57cec5SDimitry Andric Status ProcessGDBRemote::ConfigureStructuredData(
39890b57cec5SDimitry Andric     ConstString type_name, const StructuredData::ObjectSP &config_sp) {
39900b57cec5SDimitry Andric   return m_gdb_comm.ConfigureRemoteStructuredData(type_name, config_sp);
39910b57cec5SDimitry Andric }
39920b57cec5SDimitry Andric 
39930b57cec5SDimitry Andric // Establish the largest memory read/write payloads we should use. If the
39940b57cec5SDimitry Andric // remote stub has a max packet size, stay under that size.
39950b57cec5SDimitry Andric //
39960b57cec5SDimitry Andric // If the remote stub's max packet size is crazy large, use a reasonable
39970b57cec5SDimitry Andric // largeish default.
39980b57cec5SDimitry Andric //
39990b57cec5SDimitry Andric // If the remote stub doesn't advertise a max packet size, use a conservative
40000b57cec5SDimitry Andric // default.
40010b57cec5SDimitry Andric 
40020b57cec5SDimitry Andric void ProcessGDBRemote::GetMaxMemorySize() {
40030b57cec5SDimitry Andric   const uint64_t reasonable_largeish_default = 128 * 1024;
40040b57cec5SDimitry Andric   const uint64_t conservative_default = 512;
40050b57cec5SDimitry Andric 
40060b57cec5SDimitry Andric   if (m_max_memory_size == 0) {
40070b57cec5SDimitry Andric     uint64_t stub_max_size = m_gdb_comm.GetRemoteMaxPacketSize();
40080b57cec5SDimitry Andric     if (stub_max_size != UINT64_MAX && stub_max_size != 0) {
40090b57cec5SDimitry Andric       // Save the stub's claimed maximum packet size
40100b57cec5SDimitry Andric       m_remote_stub_max_memory_size = stub_max_size;
40110b57cec5SDimitry Andric 
40120b57cec5SDimitry Andric       // Even if the stub says it can support ginormous packets, don't exceed
40130b57cec5SDimitry Andric       // our reasonable largeish default packet size.
40140b57cec5SDimitry Andric       if (stub_max_size > reasonable_largeish_default) {
40150b57cec5SDimitry Andric         stub_max_size = reasonable_largeish_default;
40160b57cec5SDimitry Andric       }
40170b57cec5SDimitry Andric 
40180b57cec5SDimitry Andric       // Memory packet have other overheads too like Maddr,size:#NN Instead of
40190b57cec5SDimitry Andric       // calculating the bytes taken by size and addr every time, we take a
40200b57cec5SDimitry Andric       // maximum guess here.
40210b57cec5SDimitry Andric       if (stub_max_size > 70)
40220b57cec5SDimitry Andric         stub_max_size -= 32 + 32 + 6;
40230b57cec5SDimitry Andric       else {
40240b57cec5SDimitry Andric         // In unlikely scenario that max packet size is less then 70, we will
40250b57cec5SDimitry Andric         // hope that data being written is small enough to fit.
40260b57cec5SDimitry Andric         Log *log(ProcessGDBRemoteLog::GetLogIfAnyCategoryIsSet(
40270b57cec5SDimitry Andric             GDBR_LOG_COMM | GDBR_LOG_MEMORY));
40280b57cec5SDimitry Andric         if (log)
40290b57cec5SDimitry Andric           log->Warning("Packet size is too small. "
40300b57cec5SDimitry Andric                        "LLDB may face problems while writing memory");
40310b57cec5SDimitry Andric       }
40320b57cec5SDimitry Andric 
40330b57cec5SDimitry Andric       m_max_memory_size = stub_max_size;
40340b57cec5SDimitry Andric     } else {
40350b57cec5SDimitry Andric       m_max_memory_size = conservative_default;
40360b57cec5SDimitry Andric     }
40370b57cec5SDimitry Andric   }
40380b57cec5SDimitry Andric }
40390b57cec5SDimitry Andric 
40400b57cec5SDimitry Andric void ProcessGDBRemote::SetUserSpecifiedMaxMemoryTransferSize(
40410b57cec5SDimitry Andric     uint64_t user_specified_max) {
40420b57cec5SDimitry Andric   if (user_specified_max != 0) {
40430b57cec5SDimitry Andric     GetMaxMemorySize();
40440b57cec5SDimitry Andric 
40450b57cec5SDimitry Andric     if (m_remote_stub_max_memory_size != 0) {
40460b57cec5SDimitry Andric       if (m_remote_stub_max_memory_size < user_specified_max) {
40470b57cec5SDimitry Andric         m_max_memory_size = m_remote_stub_max_memory_size; // user specified a
40480b57cec5SDimitry Andric                                                            // packet size too
40490b57cec5SDimitry Andric                                                            // big, go as big
40500b57cec5SDimitry Andric         // as the remote stub says we can go.
40510b57cec5SDimitry Andric       } else {
40520b57cec5SDimitry Andric         m_max_memory_size = user_specified_max; // user's packet size is good
40530b57cec5SDimitry Andric       }
40540b57cec5SDimitry Andric     } else {
40550b57cec5SDimitry Andric       m_max_memory_size =
40560b57cec5SDimitry Andric           user_specified_max; // user's packet size is probably fine
40570b57cec5SDimitry Andric     }
40580b57cec5SDimitry Andric   }
40590b57cec5SDimitry Andric }
40600b57cec5SDimitry Andric 
40610b57cec5SDimitry Andric bool ProcessGDBRemote::GetModuleSpec(const FileSpec &module_file_spec,
40620b57cec5SDimitry Andric                                      const ArchSpec &arch,
40630b57cec5SDimitry Andric                                      ModuleSpec &module_spec) {
40640b57cec5SDimitry Andric   Log *log = GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PLATFORM);
40650b57cec5SDimitry Andric 
40660b57cec5SDimitry Andric   const ModuleCacheKey key(module_file_spec.GetPath(),
40670b57cec5SDimitry Andric                            arch.GetTriple().getTriple());
40680b57cec5SDimitry Andric   auto cached = m_cached_module_specs.find(key);
40690b57cec5SDimitry Andric   if (cached != m_cached_module_specs.end()) {
40700b57cec5SDimitry Andric     module_spec = cached->second;
40710b57cec5SDimitry Andric     return bool(module_spec);
40720b57cec5SDimitry Andric   }
40730b57cec5SDimitry Andric 
40740b57cec5SDimitry Andric   if (!m_gdb_comm.GetModuleInfo(module_file_spec, arch, module_spec)) {
40759dba64beSDimitry Andric     LLDB_LOGF(log, "ProcessGDBRemote::%s - failed to get module info for %s:%s",
40760b57cec5SDimitry Andric               __FUNCTION__, module_file_spec.GetPath().c_str(),
40770b57cec5SDimitry Andric               arch.GetTriple().getTriple().c_str());
40780b57cec5SDimitry Andric     return false;
40790b57cec5SDimitry Andric   }
40800b57cec5SDimitry Andric 
40810b57cec5SDimitry Andric   if (log) {
40820b57cec5SDimitry Andric     StreamString stream;
40830b57cec5SDimitry Andric     module_spec.Dump(stream);
40849dba64beSDimitry Andric     LLDB_LOGF(log, "ProcessGDBRemote::%s - got module info for (%s:%s) : %s",
40850b57cec5SDimitry Andric               __FUNCTION__, module_file_spec.GetPath().c_str(),
40860b57cec5SDimitry Andric               arch.GetTriple().getTriple().c_str(), stream.GetData());
40870b57cec5SDimitry Andric   }
40880b57cec5SDimitry Andric 
40890b57cec5SDimitry Andric   m_cached_module_specs[key] = module_spec;
40900b57cec5SDimitry Andric   return true;
40910b57cec5SDimitry Andric }
40920b57cec5SDimitry Andric 
40930b57cec5SDimitry Andric void ProcessGDBRemote::PrefetchModuleSpecs(
40940b57cec5SDimitry Andric     llvm::ArrayRef<FileSpec> module_file_specs, const llvm::Triple &triple) {
40950b57cec5SDimitry Andric   auto module_specs = m_gdb_comm.GetModulesInfo(module_file_specs, triple);
40960b57cec5SDimitry Andric   if (module_specs) {
40970b57cec5SDimitry Andric     for (const FileSpec &spec : module_file_specs)
40980b57cec5SDimitry Andric       m_cached_module_specs[ModuleCacheKey(spec.GetPath(),
40990b57cec5SDimitry Andric                                            triple.getTriple())] = ModuleSpec();
41000b57cec5SDimitry Andric     for (const ModuleSpec &spec : *module_specs)
41010b57cec5SDimitry Andric       m_cached_module_specs[ModuleCacheKey(spec.GetFileSpec().GetPath(),
41020b57cec5SDimitry Andric                                            triple.getTriple())] = spec;
41030b57cec5SDimitry Andric   }
41040b57cec5SDimitry Andric }
41050b57cec5SDimitry Andric 
41060b57cec5SDimitry Andric llvm::VersionTuple ProcessGDBRemote::GetHostOSVersion() {
41070b57cec5SDimitry Andric   return m_gdb_comm.GetOSVersion();
41080b57cec5SDimitry Andric }
41090b57cec5SDimitry Andric 
41109dba64beSDimitry Andric llvm::VersionTuple ProcessGDBRemote::GetHostMacCatalystVersion() {
41119dba64beSDimitry Andric   return m_gdb_comm.GetMacCatalystVersion();
41129dba64beSDimitry Andric }
41139dba64beSDimitry Andric 
41140b57cec5SDimitry Andric namespace {
41150b57cec5SDimitry Andric 
41160b57cec5SDimitry Andric typedef std::vector<std::string> stringVec;
41170b57cec5SDimitry Andric 
41180b57cec5SDimitry Andric typedef std::vector<struct GdbServerRegisterInfo> GDBServerRegisterVec;
41190b57cec5SDimitry Andric struct RegisterSetInfo {
41200b57cec5SDimitry Andric   ConstString name;
41210b57cec5SDimitry Andric };
41220b57cec5SDimitry Andric 
41230b57cec5SDimitry Andric typedef std::map<uint32_t, RegisterSetInfo> RegisterSetMap;
41240b57cec5SDimitry Andric 
41250b57cec5SDimitry Andric struct GdbServerTargetInfo {
41260b57cec5SDimitry Andric   std::string arch;
41270b57cec5SDimitry Andric   std::string osabi;
41280b57cec5SDimitry Andric   stringVec includes;
41290b57cec5SDimitry Andric   RegisterSetMap reg_set_map;
41300b57cec5SDimitry Andric };
41310b57cec5SDimitry Andric 
41320b57cec5SDimitry Andric bool ParseRegisters(XMLNode feature_node, GdbServerTargetInfo &target_info,
4133349cc55cSDimitry Andric                     std::vector<DynamicRegisterInfo::Register> &registers) {
41340b57cec5SDimitry Andric   if (!feature_node)
41350b57cec5SDimitry Andric     return false;
41360b57cec5SDimitry Andric 
41370b57cec5SDimitry Andric   feature_node.ForEachChildElementWithName(
4138349cc55cSDimitry Andric       "reg", [&target_info, &registers](const XMLNode &reg_node) -> bool {
41390b57cec5SDimitry Andric         std::string gdb_group;
41400b57cec5SDimitry Andric         std::string gdb_type;
4141349cc55cSDimitry Andric         DynamicRegisterInfo::Register reg_info;
41420b57cec5SDimitry Andric         bool encoding_set = false;
41430b57cec5SDimitry Andric         bool format_set = false;
41440b57cec5SDimitry Andric 
4145349cc55cSDimitry Andric         // FIXME: we're silently ignoring invalid data here
41460b57cec5SDimitry Andric         reg_node.ForEachAttribute([&target_info, &gdb_group, &gdb_type,
4147349cc55cSDimitry Andric                                    &encoding_set, &format_set, &reg_info](
41480b57cec5SDimitry Andric                                       const llvm::StringRef &name,
41490b57cec5SDimitry Andric                                       const llvm::StringRef &value) -> bool {
41500b57cec5SDimitry Andric           if (name == "name") {
4151349cc55cSDimitry Andric             reg_info.name.SetString(value);
41520b57cec5SDimitry Andric           } else if (name == "bitsize") {
4153349cc55cSDimitry Andric             if (llvm::to_integer(value, reg_info.byte_size))
41540b57cec5SDimitry Andric               reg_info.byte_size =
4155349cc55cSDimitry Andric                   llvm::divideCeil(reg_info.byte_size, CHAR_BIT);
41560b57cec5SDimitry Andric           } else if (name == "type") {
41570b57cec5SDimitry Andric             gdb_type = value.str();
41580b57cec5SDimitry Andric           } else if (name == "group") {
41590b57cec5SDimitry Andric             gdb_group = value.str();
41600b57cec5SDimitry Andric           } else if (name == "regnum") {
4161349cc55cSDimitry Andric             llvm::to_integer(value, reg_info.regnum_remote);
41620b57cec5SDimitry Andric           } else if (name == "offset") {
4163349cc55cSDimitry Andric             llvm::to_integer(value, reg_info.byte_offset);
41640b57cec5SDimitry Andric           } else if (name == "altname") {
4165349cc55cSDimitry Andric             reg_info.alt_name.SetString(value);
41660b57cec5SDimitry Andric           } else if (name == "encoding") {
41670b57cec5SDimitry Andric             encoding_set = true;
41680b57cec5SDimitry Andric             reg_info.encoding = Args::StringToEncoding(value, eEncodingUint);
41690b57cec5SDimitry Andric           } else if (name == "format") {
41700b57cec5SDimitry Andric             format_set = true;
4171349cc55cSDimitry Andric             if (!OptionArgParser::ToFormat(value.data(), reg_info.format,
4172349cc55cSDimitry Andric                                            nullptr)
41730b57cec5SDimitry Andric                      .Success())
4174349cc55cSDimitry Andric               reg_info.format =
4175349cc55cSDimitry Andric                   llvm::StringSwitch<lldb::Format>(value)
4176349cc55cSDimitry Andric                       .Case("vector-sint8", eFormatVectorOfSInt8)
4177349cc55cSDimitry Andric                       .Case("vector-uint8", eFormatVectorOfUInt8)
4178349cc55cSDimitry Andric                       .Case("vector-sint16", eFormatVectorOfSInt16)
4179349cc55cSDimitry Andric                       .Case("vector-uint16", eFormatVectorOfUInt16)
4180349cc55cSDimitry Andric                       .Case("vector-sint32", eFormatVectorOfSInt32)
4181349cc55cSDimitry Andric                       .Case("vector-uint32", eFormatVectorOfUInt32)
4182349cc55cSDimitry Andric                       .Case("vector-float32", eFormatVectorOfFloat32)
4183349cc55cSDimitry Andric                       .Case("vector-uint64", eFormatVectorOfUInt64)
4184349cc55cSDimitry Andric                       .Case("vector-uint128", eFormatVectorOfUInt128)
4185349cc55cSDimitry Andric                       .Default(eFormatInvalid);
41860b57cec5SDimitry Andric           } else if (name == "group_id") {
4187349cc55cSDimitry Andric             uint32_t set_id = UINT32_MAX;
4188349cc55cSDimitry Andric             llvm::to_integer(value, set_id);
41890b57cec5SDimitry Andric             RegisterSetMap::const_iterator pos =
41900b57cec5SDimitry Andric                 target_info.reg_set_map.find(set_id);
41910b57cec5SDimitry Andric             if (pos != target_info.reg_set_map.end())
4192349cc55cSDimitry Andric               reg_info.set_name = pos->second.name;
41930b57cec5SDimitry Andric           } else if (name == "gcc_regnum" || name == "ehframe_regnum") {
4194349cc55cSDimitry Andric             llvm::to_integer(value, reg_info.regnum_ehframe);
41950b57cec5SDimitry Andric           } else if (name == "dwarf_regnum") {
4196349cc55cSDimitry Andric             llvm::to_integer(value, reg_info.regnum_dwarf);
41970b57cec5SDimitry Andric           } else if (name == "generic") {
4198349cc55cSDimitry Andric             reg_info.regnum_generic = Args::StringToGenericRegister(value);
41990b57cec5SDimitry Andric           } else if (name == "value_regnums") {
4200349cc55cSDimitry Andric             SplitCommaSeparatedRegisterNumberString(value, reg_info.value_regs,
4201349cc55cSDimitry Andric                                                     0);
42020b57cec5SDimitry Andric           } else if (name == "invalidate_regnums") {
4203349cc55cSDimitry Andric             SplitCommaSeparatedRegisterNumberString(
4204349cc55cSDimitry Andric                 value, reg_info.invalidate_regs, 0);
42050b57cec5SDimitry Andric           } else {
4206349cc55cSDimitry Andric             Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(
4207349cc55cSDimitry Andric                 GDBR_LOG_PROCESS));
4208349cc55cSDimitry Andric             LLDB_LOGF(log,
4209349cc55cSDimitry Andric                       "ProcessGDBRemote::%s unhandled reg attribute %s = %s",
4210349cc55cSDimitry Andric                       __FUNCTION__, name.data(), value.data());
42110b57cec5SDimitry Andric           }
42120b57cec5SDimitry Andric           return true; // Keep iterating through all attributes
42130b57cec5SDimitry Andric         });
42140b57cec5SDimitry Andric 
42150b57cec5SDimitry Andric         if (!gdb_type.empty() && !(encoding_set || format_set)) {
42165ffd83dbSDimitry Andric           if (llvm::StringRef(gdb_type).startswith("int")) {
42170b57cec5SDimitry Andric             reg_info.format = eFormatHex;
42180b57cec5SDimitry Andric             reg_info.encoding = eEncodingUint;
42190b57cec5SDimitry Andric           } else if (gdb_type == "data_ptr" || gdb_type == "code_ptr") {
42200b57cec5SDimitry Andric             reg_info.format = eFormatAddressInfo;
42210b57cec5SDimitry Andric             reg_info.encoding = eEncodingUint;
4222349cc55cSDimitry Andric           } else if (gdb_type == "float") {
42230b57cec5SDimitry Andric             reg_info.format = eFormatFloat;
42240b57cec5SDimitry Andric             reg_info.encoding = eEncodingIEEE754;
4225349cc55cSDimitry Andric           } else if (gdb_type == "aarch64v" ||
4226349cc55cSDimitry Andric                      llvm::StringRef(gdb_type).startswith("vec") ||
4227349cc55cSDimitry Andric                      gdb_type == "i387_ext" || gdb_type == "uint128") {
4228349cc55cSDimitry Andric             // lldb doesn't handle 128-bit uints correctly (for ymm*h), so treat
4229349cc55cSDimitry Andric             // them as vector (similarly to xmm/ymm)
4230349cc55cSDimitry Andric             reg_info.format = eFormatVectorOfUInt8;
4231349cc55cSDimitry Andric             reg_info.encoding = eEncodingVector;
42320b57cec5SDimitry Andric           }
42330b57cec5SDimitry Andric         }
42340b57cec5SDimitry Andric 
42350b57cec5SDimitry Andric         // Only update the register set name if we didn't get a "reg_set"
42360b57cec5SDimitry Andric         // attribute. "set_name" will be empty if we didn't have a "reg_set"
42370b57cec5SDimitry Andric         // attribute.
4238349cc55cSDimitry Andric         if (!reg_info.set_name) {
42390b57cec5SDimitry Andric           if (!gdb_group.empty()) {
4240349cc55cSDimitry Andric             reg_info.set_name.SetCString(gdb_group.c_str());
42410b57cec5SDimitry Andric           } else {
42420b57cec5SDimitry Andric             // If no register group name provided anywhere,
42430b57cec5SDimitry Andric             // we'll create a 'general' register set
4244349cc55cSDimitry Andric             reg_info.set_name.SetCString("general");
42450b57cec5SDimitry Andric           }
42460b57cec5SDimitry Andric         }
42470b57cec5SDimitry Andric 
4248349cc55cSDimitry Andric         if (reg_info.byte_size == 0) {
4249349cc55cSDimitry Andric           Log *log(
4250349cc55cSDimitry Andric               ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
4251349cc55cSDimitry Andric           LLDB_LOGF(log,
4252349cc55cSDimitry Andric                     "ProcessGDBRemote::%s Skipping zero bitsize register %s",
4253349cc55cSDimitry Andric                     __FUNCTION__, reg_info.name.AsCString());
4254349cc55cSDimitry Andric         } else
4255349cc55cSDimitry Andric           registers.push_back(reg_info);
42560b57cec5SDimitry Andric 
42570b57cec5SDimitry Andric         return true; // Keep iterating through all "reg" elements
42580b57cec5SDimitry Andric       });
42590b57cec5SDimitry Andric   return true;
42600b57cec5SDimitry Andric }
42610b57cec5SDimitry Andric 
42620b57cec5SDimitry Andric } // namespace
42630b57cec5SDimitry Andric 
42640b57cec5SDimitry Andric // This method fetches a register description feature xml file from
42650b57cec5SDimitry Andric // the remote stub and adds registers/register groupsets/architecture
42660b57cec5SDimitry Andric // information to the current process.  It will call itself recursively
42670b57cec5SDimitry Andric // for nested register definition files.  It returns true if it was able
42680b57cec5SDimitry Andric // to fetch and parse an xml file.
42699dba64beSDimitry Andric bool ProcessGDBRemote::GetGDBServerRegisterInfoXMLAndProcess(
4270349cc55cSDimitry Andric     ArchSpec &arch_to_use, std::string xml_filename,
4271349cc55cSDimitry Andric     std::vector<DynamicRegisterInfo::Register> &registers) {
42720b57cec5SDimitry Andric   // request the target xml file
4273349cc55cSDimitry Andric   llvm::Expected<std::string> raw = m_gdb_comm.ReadExtFeature("features", xml_filename);
4274349cc55cSDimitry Andric   if (errorToBool(raw.takeError()))
42750b57cec5SDimitry Andric     return false;
42760b57cec5SDimitry Andric 
42770b57cec5SDimitry Andric   XMLDocument xml_document;
42780b57cec5SDimitry Andric 
4279349cc55cSDimitry Andric   if (xml_document.ParseMemory(raw->c_str(), raw->size(),
4280349cc55cSDimitry Andric                                xml_filename.c_str())) {
42810b57cec5SDimitry Andric     GdbServerTargetInfo target_info;
42820b57cec5SDimitry Andric     std::vector<XMLNode> feature_nodes;
42830b57cec5SDimitry Andric 
42840b57cec5SDimitry Andric     // The top level feature XML file will start with a <target> tag.
42850b57cec5SDimitry Andric     XMLNode target_node = xml_document.GetRootElement("target");
42860b57cec5SDimitry Andric     if (target_node) {
42870b57cec5SDimitry Andric       target_node.ForEachChildElement([&target_info, &feature_nodes](
42880b57cec5SDimitry Andric                                           const XMLNode &node) -> bool {
42890b57cec5SDimitry Andric         llvm::StringRef name = node.GetName();
42900b57cec5SDimitry Andric         if (name == "architecture") {
42910b57cec5SDimitry Andric           node.GetElementText(target_info.arch);
42920b57cec5SDimitry Andric         } else if (name == "osabi") {
42930b57cec5SDimitry Andric           node.GetElementText(target_info.osabi);
42940b57cec5SDimitry Andric         } else if (name == "xi:include" || name == "include") {
42950b57cec5SDimitry Andric           llvm::StringRef href = node.GetAttributeValue("href");
42960b57cec5SDimitry Andric           if (!href.empty())
42970b57cec5SDimitry Andric             target_info.includes.push_back(href.str());
42980b57cec5SDimitry Andric         } else if (name == "feature") {
42990b57cec5SDimitry Andric           feature_nodes.push_back(node);
43000b57cec5SDimitry Andric         } else if (name == "groups") {
43010b57cec5SDimitry Andric           node.ForEachChildElementWithName(
43020b57cec5SDimitry Andric               "group", [&target_info](const XMLNode &node) -> bool {
43030b57cec5SDimitry Andric                 uint32_t set_id = UINT32_MAX;
43040b57cec5SDimitry Andric                 RegisterSetInfo set_info;
43050b57cec5SDimitry Andric 
43060b57cec5SDimitry Andric                 node.ForEachAttribute(
43070b57cec5SDimitry Andric                     [&set_id, &set_info](const llvm::StringRef &name,
43080b57cec5SDimitry Andric                                          const llvm::StringRef &value) -> bool {
4309349cc55cSDimitry Andric                       // FIXME: we're silently ignoring invalid data here
43100b57cec5SDimitry Andric                       if (name == "id")
4311349cc55cSDimitry Andric                         llvm::to_integer(value, set_id);
43120b57cec5SDimitry Andric                       if (name == "name")
43130b57cec5SDimitry Andric                         set_info.name = ConstString(value);
43140b57cec5SDimitry Andric                       return true; // Keep iterating through all attributes
43150b57cec5SDimitry Andric                     });
43160b57cec5SDimitry Andric 
43170b57cec5SDimitry Andric                 if (set_id != UINT32_MAX)
43180b57cec5SDimitry Andric                   target_info.reg_set_map[set_id] = set_info;
43190b57cec5SDimitry Andric                 return true; // Keep iterating through all "group" elements
43200b57cec5SDimitry Andric               });
43210b57cec5SDimitry Andric         }
43220b57cec5SDimitry Andric         return true; // Keep iterating through all children of the target_node
43230b57cec5SDimitry Andric       });
43240b57cec5SDimitry Andric     } else {
43250b57cec5SDimitry Andric       // In an included XML feature file, we're already "inside" the <target>
43260b57cec5SDimitry Andric       // tag of the initial XML file; this included file will likely only have
43270b57cec5SDimitry Andric       // a <feature> tag.  Need to check for any more included files in this
43280b57cec5SDimitry Andric       // <feature> element.
43290b57cec5SDimitry Andric       XMLNode feature_node = xml_document.GetRootElement("feature");
43300b57cec5SDimitry Andric       if (feature_node) {
43310b57cec5SDimitry Andric         feature_nodes.push_back(feature_node);
43320b57cec5SDimitry Andric         feature_node.ForEachChildElement([&target_info](
43330b57cec5SDimitry Andric                                         const XMLNode &node) -> bool {
43340b57cec5SDimitry Andric           llvm::StringRef name = node.GetName();
43350b57cec5SDimitry Andric           if (name == "xi:include" || name == "include") {
43360b57cec5SDimitry Andric             llvm::StringRef href = node.GetAttributeValue("href");
43370b57cec5SDimitry Andric             if (!href.empty())
43380b57cec5SDimitry Andric               target_info.includes.push_back(href.str());
43390b57cec5SDimitry Andric             }
43400b57cec5SDimitry Andric             return true;
43410b57cec5SDimitry Andric           });
43420b57cec5SDimitry Andric       }
43430b57cec5SDimitry Andric     }
43440b57cec5SDimitry Andric 
4345349cc55cSDimitry Andric     // gdbserver does not implement the LLDB packets used to determine host
4346349cc55cSDimitry Andric     // or process architecture.  If that is the case, attempt to use
4347349cc55cSDimitry Andric     // the <architecture/> field from target.xml, e.g.:
4348349cc55cSDimitry Andric     //
43490b57cec5SDimitry Andric     //   <architecture>i386:x86-64</architecture> (seen from VMWare ESXi)
4350349cc55cSDimitry Andric     //   <architecture>arm</architecture> (seen from Segger JLink on unspecified
4351349cc55cSDimitry Andric     //   arm board)
43520b57cec5SDimitry Andric     if (!arch_to_use.IsValid() && !target_info.arch.empty()) {
43530b57cec5SDimitry Andric       // We don't have any information about vendor or OS.
4354349cc55cSDimitry Andric       arch_to_use.SetTriple(llvm::StringSwitch<std::string>(target_info.arch)
4355349cc55cSDimitry Andric                                 .Case("i386:x86-64", "x86_64")
4356349cc55cSDimitry Andric                                 .Default(target_info.arch) +
4357349cc55cSDimitry Andric                             "--");
43580b57cec5SDimitry Andric 
4359349cc55cSDimitry Andric       if (arch_to_use.IsValid())
43600b57cec5SDimitry Andric         GetTarget().MergeArchitecture(arch_to_use);
43610b57cec5SDimitry Andric     }
43620b57cec5SDimitry Andric 
43630b57cec5SDimitry Andric     if (arch_to_use.IsValid()) {
43640b57cec5SDimitry Andric       for (auto &feature_node : feature_nodes) {
4365349cc55cSDimitry Andric         ParseRegisters(feature_node, target_info,
4366349cc55cSDimitry Andric                        registers);
43670b57cec5SDimitry Andric       }
43680b57cec5SDimitry Andric 
43690b57cec5SDimitry Andric       for (const auto &include : target_info.includes) {
4370e8d8bef9SDimitry Andric         GetGDBServerRegisterInfoXMLAndProcess(arch_to_use, include,
4371349cc55cSDimitry Andric                                               registers);
43720b57cec5SDimitry Andric       }
43730b57cec5SDimitry Andric     }
43740b57cec5SDimitry Andric   } else {
43750b57cec5SDimitry Andric     return false;
43760b57cec5SDimitry Andric   }
43770b57cec5SDimitry Andric   return true;
43780b57cec5SDimitry Andric }
43790b57cec5SDimitry Andric 
4380349cc55cSDimitry Andric void ProcessGDBRemote::AddRemoteRegisters(
4381349cc55cSDimitry Andric     std::vector<DynamicRegisterInfo::Register> &registers,
4382349cc55cSDimitry Andric     const ArchSpec &arch_to_use) {
4383349cc55cSDimitry Andric   std::map<uint32_t, uint32_t> remote_to_local_map;
4384349cc55cSDimitry Andric   uint32_t remote_regnum = 0;
4385349cc55cSDimitry Andric   for (auto it : llvm::enumerate(registers)) {
4386349cc55cSDimitry Andric     DynamicRegisterInfo::Register &remote_reg_info = it.value();
4387349cc55cSDimitry Andric 
4388349cc55cSDimitry Andric     // Assign successive remote regnums if missing.
4389349cc55cSDimitry Andric     if (remote_reg_info.regnum_remote == LLDB_INVALID_REGNUM)
4390349cc55cSDimitry Andric       remote_reg_info.regnum_remote = remote_regnum;
4391349cc55cSDimitry Andric 
4392349cc55cSDimitry Andric     // Create a mapping from remote to local regnos.
4393349cc55cSDimitry Andric     remote_to_local_map[remote_reg_info.regnum_remote] = it.index();
4394349cc55cSDimitry Andric 
4395349cc55cSDimitry Andric     remote_regnum = remote_reg_info.regnum_remote + 1;
4396349cc55cSDimitry Andric   }
4397349cc55cSDimitry Andric 
4398349cc55cSDimitry Andric   for (DynamicRegisterInfo::Register &remote_reg_info : registers) {
4399349cc55cSDimitry Andric     auto proc_to_lldb = [&remote_to_local_map](uint32_t process_regnum) {
4400349cc55cSDimitry Andric       auto lldb_regit = remote_to_local_map.find(process_regnum);
4401349cc55cSDimitry Andric       return lldb_regit != remote_to_local_map.end() ? lldb_regit->second
4402349cc55cSDimitry Andric                                                      : LLDB_INVALID_REGNUM;
4403349cc55cSDimitry Andric     };
4404349cc55cSDimitry Andric 
4405349cc55cSDimitry Andric     llvm::transform(remote_reg_info.value_regs,
4406349cc55cSDimitry Andric                     remote_reg_info.value_regs.begin(), proc_to_lldb);
4407349cc55cSDimitry Andric     llvm::transform(remote_reg_info.invalidate_regs,
4408349cc55cSDimitry Andric                     remote_reg_info.invalidate_regs.begin(), proc_to_lldb);
4409349cc55cSDimitry Andric   }
4410349cc55cSDimitry Andric 
4411349cc55cSDimitry Andric   // Don't use Process::GetABI, this code gets called from DidAttach, and
4412349cc55cSDimitry Andric   // in that context we haven't set the Target's architecture yet, so the
4413349cc55cSDimitry Andric   // ABI is also potentially incorrect.
4414349cc55cSDimitry Andric   if (ABISP abi_sp = ABI::FindPlugin(shared_from_this(), arch_to_use))
4415349cc55cSDimitry Andric     abi_sp->AugmentRegisterInfo(registers);
4416349cc55cSDimitry Andric 
4417349cc55cSDimitry Andric   m_register_info_sp->SetRegisterInfo(std::move(registers), arch_to_use);
4418349cc55cSDimitry Andric }
4419349cc55cSDimitry Andric 
44200b57cec5SDimitry Andric // query the target of gdb-remote for extended target information returns
44210b57cec5SDimitry Andric // true on success (got register definitions), false on failure (did not).
44220b57cec5SDimitry Andric bool ProcessGDBRemote::GetGDBServerRegisterInfo(ArchSpec &arch_to_use) {
44230b57cec5SDimitry Andric   // Make sure LLDB has an XML parser it can use first
44240b57cec5SDimitry Andric   if (!XMLDocument::XMLEnabled())
44250b57cec5SDimitry Andric     return false;
44260b57cec5SDimitry Andric 
44270b57cec5SDimitry Andric   // check that we have extended feature read support
44280b57cec5SDimitry Andric   if (!m_gdb_comm.GetQXferFeaturesReadSupported())
44290b57cec5SDimitry Andric     return false;
44300b57cec5SDimitry Andric 
4431349cc55cSDimitry Andric   std::vector<DynamicRegisterInfo::Register> registers;
4432e8d8bef9SDimitry Andric   if (GetGDBServerRegisterInfoXMLAndProcess(arch_to_use, "target.xml",
4433349cc55cSDimitry Andric                                             registers))
4434349cc55cSDimitry Andric     AddRemoteRegisters(registers, arch_to_use);
44350b57cec5SDimitry Andric 
4436e8d8bef9SDimitry Andric   return m_register_info_sp->GetNumRegisters() > 0;
44370b57cec5SDimitry Andric }
44380b57cec5SDimitry Andric 
44399dba64beSDimitry Andric llvm::Expected<LoadedModuleInfoList> ProcessGDBRemote::GetLoadedModuleList() {
44400b57cec5SDimitry Andric   // Make sure LLDB has an XML parser it can use first
44410b57cec5SDimitry Andric   if (!XMLDocument::XMLEnabled())
44429dba64beSDimitry Andric     return llvm::createStringError(llvm::inconvertibleErrorCode(),
44439dba64beSDimitry Andric                                    "XML parsing not available");
44440b57cec5SDimitry Andric 
44450b57cec5SDimitry Andric   Log *log = GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS);
44469dba64beSDimitry Andric   LLDB_LOGF(log, "ProcessGDBRemote::%s", __FUNCTION__);
44470b57cec5SDimitry Andric 
44489dba64beSDimitry Andric   LoadedModuleInfoList list;
44490b57cec5SDimitry Andric   GDBRemoteCommunicationClient &comm = m_gdb_comm;
4450349cc55cSDimitry Andric   bool can_use_svr4 = GetGlobalPluginProperties().GetUseSVR4();
44510b57cec5SDimitry Andric 
44520b57cec5SDimitry Andric   // check that we have extended feature read support
44530b57cec5SDimitry Andric   if (can_use_svr4 && comm.GetQXferLibrariesSVR4ReadSupported()) {
44540b57cec5SDimitry Andric     // request the loaded library list
4455349cc55cSDimitry Andric     llvm::Expected<std::string> raw = comm.ReadExtFeature("libraries-svr4", "");
4456349cc55cSDimitry Andric     if (!raw)
4457349cc55cSDimitry Andric       return raw.takeError();
44580b57cec5SDimitry Andric 
44590b57cec5SDimitry Andric     // parse the xml file in memory
4460349cc55cSDimitry Andric     LLDB_LOGF(log, "parsing: %s", raw->c_str());
44610b57cec5SDimitry Andric     XMLDocument doc;
44620b57cec5SDimitry Andric 
4463349cc55cSDimitry Andric     if (!doc.ParseMemory(raw->c_str(), raw->size(), "noname.xml"))
44649dba64beSDimitry Andric       return llvm::createStringError(llvm::inconvertibleErrorCode(),
44659dba64beSDimitry Andric                                      "Error reading noname.xml");
44660b57cec5SDimitry Andric 
44670b57cec5SDimitry Andric     XMLNode root_element = doc.GetRootElement("library-list-svr4");
44680b57cec5SDimitry Andric     if (!root_element)
44699dba64beSDimitry Andric       return llvm::createStringError(
44709dba64beSDimitry Andric           llvm::inconvertibleErrorCode(),
44719dba64beSDimitry Andric           "Error finding library-list-svr4 xml element");
44720b57cec5SDimitry Andric 
44730b57cec5SDimitry Andric     // main link map structure
44740b57cec5SDimitry Andric     llvm::StringRef main_lm = root_element.GetAttributeValue("main-lm");
4475349cc55cSDimitry Andric     // FIXME: we're silently ignoring invalid data here
4476349cc55cSDimitry Andric     if (!main_lm.empty())
4477349cc55cSDimitry Andric       llvm::to_integer(main_lm, list.m_link_map);
44780b57cec5SDimitry Andric 
44790b57cec5SDimitry Andric     root_element.ForEachChildElementWithName(
44800b57cec5SDimitry Andric         "library", [log, &list](const XMLNode &library) -> bool {
44810b57cec5SDimitry Andric           LoadedModuleInfoList::LoadedModuleInfo module;
44820b57cec5SDimitry Andric 
4483349cc55cSDimitry Andric           // FIXME: we're silently ignoring invalid data here
44840b57cec5SDimitry Andric           library.ForEachAttribute(
44850b57cec5SDimitry Andric               [&module](const llvm::StringRef &name,
44860b57cec5SDimitry Andric                         const llvm::StringRef &value) -> bool {
4487349cc55cSDimitry Andric                 uint64_t uint_value = LLDB_INVALID_ADDRESS;
44880b57cec5SDimitry Andric                 if (name == "name")
44890b57cec5SDimitry Andric                   module.set_name(value.str());
44900b57cec5SDimitry Andric                 else if (name == "lm") {
44910b57cec5SDimitry Andric                   // the address of the link_map struct.
4492349cc55cSDimitry Andric                   llvm::to_integer(value, uint_value);
4493349cc55cSDimitry Andric                   module.set_link_map(uint_value);
44940b57cec5SDimitry Andric                 } else if (name == "l_addr") {
44950b57cec5SDimitry Andric                   // the displacement as read from the field 'l_addr' of the
44960b57cec5SDimitry Andric                   // link_map struct.
4497349cc55cSDimitry Andric                   llvm::to_integer(value, uint_value);
4498349cc55cSDimitry Andric                   module.set_base(uint_value);
44990b57cec5SDimitry Andric                   // base address is always a displacement, not an absolute
45000b57cec5SDimitry Andric                   // value.
45010b57cec5SDimitry Andric                   module.set_base_is_offset(true);
45020b57cec5SDimitry Andric                 } else if (name == "l_ld") {
45035ffd83dbSDimitry Andric                   // the memory address of the libraries PT_DYNAMIC section.
4504349cc55cSDimitry Andric                   llvm::to_integer(value, uint_value);
4505349cc55cSDimitry Andric                   module.set_dynamic(uint_value);
45060b57cec5SDimitry Andric                 }
45070b57cec5SDimitry Andric 
45080b57cec5SDimitry Andric                 return true; // Keep iterating over all properties of "library"
45090b57cec5SDimitry Andric               });
45100b57cec5SDimitry Andric 
45110b57cec5SDimitry Andric           if (log) {
45120b57cec5SDimitry Andric             std::string name;
45130b57cec5SDimitry Andric             lldb::addr_t lm = 0, base = 0, ld = 0;
45140b57cec5SDimitry Andric             bool base_is_offset;
45150b57cec5SDimitry Andric 
45160b57cec5SDimitry Andric             module.get_name(name);
45170b57cec5SDimitry Andric             module.get_link_map(lm);
45180b57cec5SDimitry Andric             module.get_base(base);
45190b57cec5SDimitry Andric             module.get_base_is_offset(base_is_offset);
45200b57cec5SDimitry Andric             module.get_dynamic(ld);
45210b57cec5SDimitry Andric 
45229dba64beSDimitry Andric             LLDB_LOGF(log,
45239dba64beSDimitry Andric                       "found (link_map:0x%08" PRIx64 ", base:0x%08" PRIx64
45240b57cec5SDimitry Andric                       "[%s], ld:0x%08" PRIx64 ", name:'%s')",
45250b57cec5SDimitry Andric                       lm, base, (base_is_offset ? "offset" : "absolute"), ld,
45260b57cec5SDimitry Andric                       name.c_str());
45270b57cec5SDimitry Andric           }
45280b57cec5SDimitry Andric 
45290b57cec5SDimitry Andric           list.add(module);
45300b57cec5SDimitry Andric           return true; // Keep iterating over all "library" elements in the root
45310b57cec5SDimitry Andric                        // node
45320b57cec5SDimitry Andric         });
45330b57cec5SDimitry Andric 
45340b57cec5SDimitry Andric     if (log)
45359dba64beSDimitry Andric       LLDB_LOGF(log, "found %" PRId32 " modules in total",
45360b57cec5SDimitry Andric                 (int)list.m_list.size());
45379dba64beSDimitry Andric     return list;
45380b57cec5SDimitry Andric   } else if (comm.GetQXferLibrariesReadSupported()) {
45390b57cec5SDimitry Andric     // request the loaded library list
4540349cc55cSDimitry Andric     llvm::Expected<std::string> raw = comm.ReadExtFeature("libraries", "");
45410b57cec5SDimitry Andric 
4542349cc55cSDimitry Andric     if (!raw)
4543349cc55cSDimitry Andric       return raw.takeError();
45440b57cec5SDimitry Andric 
4545349cc55cSDimitry Andric     LLDB_LOGF(log, "parsing: %s", raw->c_str());
45460b57cec5SDimitry Andric     XMLDocument doc;
45470b57cec5SDimitry Andric 
4548349cc55cSDimitry Andric     if (!doc.ParseMemory(raw->c_str(), raw->size(), "noname.xml"))
45499dba64beSDimitry Andric       return llvm::createStringError(llvm::inconvertibleErrorCode(),
45509dba64beSDimitry Andric                                      "Error reading noname.xml");
45510b57cec5SDimitry Andric 
45520b57cec5SDimitry Andric     XMLNode root_element = doc.GetRootElement("library-list");
45530b57cec5SDimitry Andric     if (!root_element)
45549dba64beSDimitry Andric       return llvm::createStringError(llvm::inconvertibleErrorCode(),
45559dba64beSDimitry Andric                                      "Error finding library-list xml element");
45560b57cec5SDimitry Andric 
4557349cc55cSDimitry Andric     // FIXME: we're silently ignoring invalid data here
45580b57cec5SDimitry Andric     root_element.ForEachChildElementWithName(
45590b57cec5SDimitry Andric         "library", [log, &list](const XMLNode &library) -> bool {
45600b57cec5SDimitry Andric           LoadedModuleInfoList::LoadedModuleInfo module;
45610b57cec5SDimitry Andric 
45620b57cec5SDimitry Andric           llvm::StringRef name = library.GetAttributeValue("name");
45630b57cec5SDimitry Andric           module.set_name(name.str());
45640b57cec5SDimitry Andric 
45650b57cec5SDimitry Andric           // The base address of a given library will be the address of its
45660b57cec5SDimitry Andric           // first section. Most remotes send only one section for Windows
45670b57cec5SDimitry Andric           // targets for example.
45680b57cec5SDimitry Andric           const XMLNode &section =
45690b57cec5SDimitry Andric               library.FindFirstChildElementWithName("section");
45700b57cec5SDimitry Andric           llvm::StringRef address = section.GetAttributeValue("address");
4571349cc55cSDimitry Andric           uint64_t address_value = LLDB_INVALID_ADDRESS;
4572349cc55cSDimitry Andric           llvm::to_integer(address, address_value);
4573349cc55cSDimitry Andric           module.set_base(address_value);
45740b57cec5SDimitry Andric           // These addresses are absolute values.
45750b57cec5SDimitry Andric           module.set_base_is_offset(false);
45760b57cec5SDimitry Andric 
45770b57cec5SDimitry Andric           if (log) {
45780b57cec5SDimitry Andric             std::string name;
45790b57cec5SDimitry Andric             lldb::addr_t base = 0;
45800b57cec5SDimitry Andric             bool base_is_offset;
45810b57cec5SDimitry Andric             module.get_name(name);
45820b57cec5SDimitry Andric             module.get_base(base);
45830b57cec5SDimitry Andric             module.get_base_is_offset(base_is_offset);
45840b57cec5SDimitry Andric 
45859dba64beSDimitry Andric             LLDB_LOGF(log, "found (base:0x%08" PRIx64 "[%s], name:'%s')", base,
45860b57cec5SDimitry Andric                       (base_is_offset ? "offset" : "absolute"), name.c_str());
45870b57cec5SDimitry Andric           }
45880b57cec5SDimitry Andric 
45890b57cec5SDimitry Andric           list.add(module);
45900b57cec5SDimitry Andric           return true; // Keep iterating over all "library" elements in the root
45910b57cec5SDimitry Andric                        // node
45920b57cec5SDimitry Andric         });
45930b57cec5SDimitry Andric 
45940b57cec5SDimitry Andric     if (log)
45959dba64beSDimitry Andric       LLDB_LOGF(log, "found %" PRId32 " modules in total",
45960b57cec5SDimitry Andric                 (int)list.m_list.size());
45979dba64beSDimitry Andric     return list;
45980b57cec5SDimitry Andric   } else {
45999dba64beSDimitry Andric     return llvm::createStringError(llvm::inconvertibleErrorCode(),
46009dba64beSDimitry Andric                                    "Remote libraries not supported");
46010b57cec5SDimitry Andric   }
46020b57cec5SDimitry Andric }
46030b57cec5SDimitry Andric 
46040b57cec5SDimitry Andric lldb::ModuleSP ProcessGDBRemote::LoadModuleAtAddress(const FileSpec &file,
46050b57cec5SDimitry Andric                                                      lldb::addr_t link_map,
46060b57cec5SDimitry Andric                                                      lldb::addr_t base_addr,
46070b57cec5SDimitry Andric                                                      bool value_is_offset) {
46080b57cec5SDimitry Andric   DynamicLoader *loader = GetDynamicLoader();
46090b57cec5SDimitry Andric   if (!loader)
46100b57cec5SDimitry Andric     return nullptr;
46110b57cec5SDimitry Andric 
46120b57cec5SDimitry Andric   return loader->LoadModuleAtAddress(file, link_map, base_addr,
46130b57cec5SDimitry Andric                                      value_is_offset);
46140b57cec5SDimitry Andric }
46150b57cec5SDimitry Andric 
46169dba64beSDimitry Andric llvm::Error ProcessGDBRemote::LoadModules() {
46170b57cec5SDimitry Andric   using lldb_private::process_gdb_remote::ProcessGDBRemote;
46180b57cec5SDimitry Andric 
46190b57cec5SDimitry Andric   // request a list of loaded libraries from GDBServer
46209dba64beSDimitry Andric   llvm::Expected<LoadedModuleInfoList> module_list = GetLoadedModuleList();
46219dba64beSDimitry Andric   if (!module_list)
46229dba64beSDimitry Andric     return module_list.takeError();
46230b57cec5SDimitry Andric 
46240b57cec5SDimitry Andric   // get a list of all the modules
46250b57cec5SDimitry Andric   ModuleList new_modules;
46260b57cec5SDimitry Andric 
46279dba64beSDimitry Andric   for (LoadedModuleInfoList::LoadedModuleInfo &modInfo : module_list->m_list) {
46280b57cec5SDimitry Andric     std::string mod_name;
46290b57cec5SDimitry Andric     lldb::addr_t mod_base;
46300b57cec5SDimitry Andric     lldb::addr_t link_map;
46310b57cec5SDimitry Andric     bool mod_base_is_offset;
46320b57cec5SDimitry Andric 
46330b57cec5SDimitry Andric     bool valid = true;
46340b57cec5SDimitry Andric     valid &= modInfo.get_name(mod_name);
46350b57cec5SDimitry Andric     valid &= modInfo.get_base(mod_base);
46360b57cec5SDimitry Andric     valid &= modInfo.get_base_is_offset(mod_base_is_offset);
46370b57cec5SDimitry Andric     if (!valid)
46380b57cec5SDimitry Andric       continue;
46390b57cec5SDimitry Andric 
46400b57cec5SDimitry Andric     if (!modInfo.get_link_map(link_map))
46410b57cec5SDimitry Andric       link_map = LLDB_INVALID_ADDRESS;
46420b57cec5SDimitry Andric 
46430b57cec5SDimitry Andric     FileSpec file(mod_name);
46440b57cec5SDimitry Andric     FileSystem::Instance().Resolve(file);
46450b57cec5SDimitry Andric     lldb::ModuleSP module_sp =
46460b57cec5SDimitry Andric         LoadModuleAtAddress(file, link_map, mod_base, mod_base_is_offset);
46470b57cec5SDimitry Andric 
46480b57cec5SDimitry Andric     if (module_sp.get())
46490b57cec5SDimitry Andric       new_modules.Append(module_sp);
46500b57cec5SDimitry Andric   }
46510b57cec5SDimitry Andric 
46520b57cec5SDimitry Andric   if (new_modules.GetSize() > 0) {
46530b57cec5SDimitry Andric     ModuleList removed_modules;
46540b57cec5SDimitry Andric     Target &target = GetTarget();
46550b57cec5SDimitry Andric     ModuleList &loaded_modules = m_process->GetTarget().GetImages();
46560b57cec5SDimitry Andric 
46570b57cec5SDimitry Andric     for (size_t i = 0; i < loaded_modules.GetSize(); ++i) {
46580b57cec5SDimitry Andric       const lldb::ModuleSP loaded_module = loaded_modules.GetModuleAtIndex(i);
46590b57cec5SDimitry Andric 
46600b57cec5SDimitry Andric       bool found = false;
46610b57cec5SDimitry Andric       for (size_t j = 0; j < new_modules.GetSize(); ++j) {
46620b57cec5SDimitry Andric         if (new_modules.GetModuleAtIndex(j).get() == loaded_module.get())
46630b57cec5SDimitry Andric           found = true;
46640b57cec5SDimitry Andric       }
46650b57cec5SDimitry Andric 
46660b57cec5SDimitry Andric       // The main executable will never be included in libraries-svr4, don't
46670b57cec5SDimitry Andric       // remove it
46680b57cec5SDimitry Andric       if (!found &&
46690b57cec5SDimitry Andric           loaded_module.get() != target.GetExecutableModulePointer()) {
46700b57cec5SDimitry Andric         removed_modules.Append(loaded_module);
46710b57cec5SDimitry Andric       }
46720b57cec5SDimitry Andric     }
46730b57cec5SDimitry Andric 
46740b57cec5SDimitry Andric     loaded_modules.Remove(removed_modules);
46750b57cec5SDimitry Andric     m_process->GetTarget().ModulesDidUnload(removed_modules, false);
46760b57cec5SDimitry Andric 
46770b57cec5SDimitry Andric     new_modules.ForEach([&target](const lldb::ModuleSP module_sp) -> bool {
46780b57cec5SDimitry Andric       lldb_private::ObjectFile *obj = module_sp->GetObjectFile();
46790b57cec5SDimitry Andric       if (!obj)
46800b57cec5SDimitry Andric         return true;
46810b57cec5SDimitry Andric 
46820b57cec5SDimitry Andric       if (obj->GetType() != ObjectFile::Type::eTypeExecutable)
46830b57cec5SDimitry Andric         return true;
46840b57cec5SDimitry Andric 
46850b57cec5SDimitry Andric       lldb::ModuleSP module_copy_sp = module_sp;
46860b57cec5SDimitry Andric       target.SetExecutableModule(module_copy_sp, eLoadDependentsNo);
46870b57cec5SDimitry Andric       return false;
46880b57cec5SDimitry Andric     });
46890b57cec5SDimitry Andric 
46900b57cec5SDimitry Andric     loaded_modules.AppendIfNeeded(new_modules);
46910b57cec5SDimitry Andric     m_process->GetTarget().ModulesDidLoad(new_modules);
46920b57cec5SDimitry Andric   }
46930b57cec5SDimitry Andric 
46949dba64beSDimitry Andric   return llvm::ErrorSuccess();
46950b57cec5SDimitry Andric }
46960b57cec5SDimitry Andric 
46970b57cec5SDimitry Andric Status ProcessGDBRemote::GetFileLoadAddress(const FileSpec &file,
46980b57cec5SDimitry Andric                                             bool &is_loaded,
46990b57cec5SDimitry Andric                                             lldb::addr_t &load_addr) {
47000b57cec5SDimitry Andric   is_loaded = false;
47010b57cec5SDimitry Andric   load_addr = LLDB_INVALID_ADDRESS;
47020b57cec5SDimitry Andric 
47030b57cec5SDimitry Andric   std::string file_path = file.GetPath(false);
47040b57cec5SDimitry Andric   if (file_path.empty())
47050b57cec5SDimitry Andric     return Status("Empty file name specified");
47060b57cec5SDimitry Andric 
47070b57cec5SDimitry Andric   StreamString packet;
47080b57cec5SDimitry Andric   packet.PutCString("qFileLoadAddress:");
47090b57cec5SDimitry Andric   packet.PutStringAsRawHex8(file_path);
47100b57cec5SDimitry Andric 
47110b57cec5SDimitry Andric   StringExtractorGDBRemote response;
4712fe6060f1SDimitry Andric   if (m_gdb_comm.SendPacketAndWaitForResponse(packet.GetString(), response) !=
47130b57cec5SDimitry Andric       GDBRemoteCommunication::PacketResult::Success)
47140b57cec5SDimitry Andric     return Status("Sending qFileLoadAddress packet failed");
47150b57cec5SDimitry Andric 
47160b57cec5SDimitry Andric   if (response.IsErrorResponse()) {
47170b57cec5SDimitry Andric     if (response.GetError() == 1) {
47180b57cec5SDimitry Andric       // The file is not loaded into the inferior
47190b57cec5SDimitry Andric       is_loaded = false;
47200b57cec5SDimitry Andric       load_addr = LLDB_INVALID_ADDRESS;
47210b57cec5SDimitry Andric       return Status();
47220b57cec5SDimitry Andric     }
47230b57cec5SDimitry Andric 
47240b57cec5SDimitry Andric     return Status(
47250b57cec5SDimitry Andric         "Fetching file load address from remote server returned an error");
47260b57cec5SDimitry Andric   }
47270b57cec5SDimitry Andric 
47280b57cec5SDimitry Andric   if (response.IsNormalResponse()) {
47290b57cec5SDimitry Andric     is_loaded = true;
47300b57cec5SDimitry Andric     load_addr = response.GetHexMaxU64(false, LLDB_INVALID_ADDRESS);
47310b57cec5SDimitry Andric     return Status();
47320b57cec5SDimitry Andric   }
47330b57cec5SDimitry Andric 
47340b57cec5SDimitry Andric   return Status(
47350b57cec5SDimitry Andric       "Unknown error happened during sending the load address packet");
47360b57cec5SDimitry Andric }
47370b57cec5SDimitry Andric 
47380b57cec5SDimitry Andric void ProcessGDBRemote::ModulesDidLoad(ModuleList &module_list) {
47390b57cec5SDimitry Andric   // We must call the lldb_private::Process::ModulesDidLoad () first before we
47400b57cec5SDimitry Andric   // do anything
47410b57cec5SDimitry Andric   Process::ModulesDidLoad(module_list);
47420b57cec5SDimitry Andric 
47430b57cec5SDimitry Andric   // After loading shared libraries, we can ask our remote GDB server if it
47440b57cec5SDimitry Andric   // needs any symbols.
47450b57cec5SDimitry Andric   m_gdb_comm.ServeSymbolLookups(this);
47460b57cec5SDimitry Andric }
47470b57cec5SDimitry Andric 
47480b57cec5SDimitry Andric void ProcessGDBRemote::HandleAsyncStdout(llvm::StringRef out) {
47490b57cec5SDimitry Andric   AppendSTDOUT(out.data(), out.size());
47500b57cec5SDimitry Andric }
47510b57cec5SDimitry Andric 
47520b57cec5SDimitry Andric static const char *end_delimiter = "--end--;";
47530b57cec5SDimitry Andric static const int end_delimiter_len = 8;
47540b57cec5SDimitry Andric 
47550b57cec5SDimitry Andric void ProcessGDBRemote::HandleAsyncMisc(llvm::StringRef data) {
47560b57cec5SDimitry Andric   std::string input = data.str(); // '1' to move beyond 'A'
47570b57cec5SDimitry Andric   if (m_partial_profile_data.length() > 0) {
47580b57cec5SDimitry Andric     m_partial_profile_data.append(input);
47590b57cec5SDimitry Andric     input = m_partial_profile_data;
47600b57cec5SDimitry Andric     m_partial_profile_data.clear();
47610b57cec5SDimitry Andric   }
47620b57cec5SDimitry Andric 
47630b57cec5SDimitry Andric   size_t found, pos = 0, len = input.length();
47640b57cec5SDimitry Andric   while ((found = input.find(end_delimiter, pos)) != std::string::npos) {
47650b57cec5SDimitry Andric     StringExtractorGDBRemote profileDataExtractor(
47660b57cec5SDimitry Andric         input.substr(pos, found).c_str());
47670b57cec5SDimitry Andric     std::string profile_data =
47680b57cec5SDimitry Andric         HarmonizeThreadIdsForProfileData(profileDataExtractor);
47690b57cec5SDimitry Andric     BroadcastAsyncProfileData(profile_data);
47700b57cec5SDimitry Andric 
47710b57cec5SDimitry Andric     pos = found + end_delimiter_len;
47720b57cec5SDimitry Andric   }
47730b57cec5SDimitry Andric 
47740b57cec5SDimitry Andric   if (pos < len) {
47750b57cec5SDimitry Andric     // Last incomplete chunk.
47760b57cec5SDimitry Andric     m_partial_profile_data = input.substr(pos);
47770b57cec5SDimitry Andric   }
47780b57cec5SDimitry Andric }
47790b57cec5SDimitry Andric 
47800b57cec5SDimitry Andric std::string ProcessGDBRemote::HarmonizeThreadIdsForProfileData(
47810b57cec5SDimitry Andric     StringExtractorGDBRemote &profileDataExtractor) {
47820b57cec5SDimitry Andric   std::map<uint64_t, uint32_t> new_thread_id_to_used_usec_map;
47830b57cec5SDimitry Andric   std::string output;
47840b57cec5SDimitry Andric   llvm::raw_string_ostream output_stream(output);
47850b57cec5SDimitry Andric   llvm::StringRef name, value;
47860b57cec5SDimitry Andric 
47870b57cec5SDimitry Andric   // Going to assuming thread_used_usec comes first, else bail out.
47880b57cec5SDimitry Andric   while (profileDataExtractor.GetNameColonValue(name, value)) {
47890b57cec5SDimitry Andric     if (name.compare("thread_used_id") == 0) {
47900b57cec5SDimitry Andric       StringExtractor threadIDHexExtractor(value);
47910b57cec5SDimitry Andric       uint64_t thread_id = threadIDHexExtractor.GetHexMaxU64(false, 0);
47920b57cec5SDimitry Andric 
47930b57cec5SDimitry Andric       bool has_used_usec = false;
47940b57cec5SDimitry Andric       uint32_t curr_used_usec = 0;
47950b57cec5SDimitry Andric       llvm::StringRef usec_name, usec_value;
47960b57cec5SDimitry Andric       uint32_t input_file_pos = profileDataExtractor.GetFilePos();
47970b57cec5SDimitry Andric       if (profileDataExtractor.GetNameColonValue(usec_name, usec_value)) {
47980b57cec5SDimitry Andric         if (usec_name.equals("thread_used_usec")) {
47990b57cec5SDimitry Andric           has_used_usec = true;
48000b57cec5SDimitry Andric           usec_value.getAsInteger(0, curr_used_usec);
48010b57cec5SDimitry Andric         } else {
48020b57cec5SDimitry Andric           // We didn't find what we want, it is probably an older version. Bail
48030b57cec5SDimitry Andric           // out.
48040b57cec5SDimitry Andric           profileDataExtractor.SetFilePos(input_file_pos);
48050b57cec5SDimitry Andric         }
48060b57cec5SDimitry Andric       }
48070b57cec5SDimitry Andric 
48080b57cec5SDimitry Andric       if (has_used_usec) {
48090b57cec5SDimitry Andric         uint32_t prev_used_usec = 0;
48100b57cec5SDimitry Andric         std::map<uint64_t, uint32_t>::iterator iterator =
48110b57cec5SDimitry Andric             m_thread_id_to_used_usec_map.find(thread_id);
48120b57cec5SDimitry Andric         if (iterator != m_thread_id_to_used_usec_map.end()) {
48130b57cec5SDimitry Andric           prev_used_usec = m_thread_id_to_used_usec_map[thread_id];
48140b57cec5SDimitry Andric         }
48150b57cec5SDimitry Andric 
48160b57cec5SDimitry Andric         uint32_t real_used_usec = curr_used_usec - prev_used_usec;
48170b57cec5SDimitry Andric         // A good first time record is one that runs for at least 0.25 sec
48180b57cec5SDimitry Andric         bool good_first_time =
48190b57cec5SDimitry Andric             (prev_used_usec == 0) && (real_used_usec > 250000);
48200b57cec5SDimitry Andric         bool good_subsequent_time =
48210b57cec5SDimitry Andric             (prev_used_usec > 0) &&
48220b57cec5SDimitry Andric             ((real_used_usec > 0) || (HasAssignedIndexIDToThread(thread_id)));
48230b57cec5SDimitry Andric 
48240b57cec5SDimitry Andric         if (good_first_time || good_subsequent_time) {
48250b57cec5SDimitry Andric           // We try to avoid doing too many index id reservation, resulting in
48260b57cec5SDimitry Andric           // fast increase of index ids.
48270b57cec5SDimitry Andric 
48280b57cec5SDimitry Andric           output_stream << name << ":";
48290b57cec5SDimitry Andric           int32_t index_id = AssignIndexIDToThread(thread_id);
48300b57cec5SDimitry Andric           output_stream << index_id << ";";
48310b57cec5SDimitry Andric 
48320b57cec5SDimitry Andric           output_stream << usec_name << ":" << usec_value << ";";
48330b57cec5SDimitry Andric         } else {
48340b57cec5SDimitry Andric           // Skip past 'thread_used_name'.
48350b57cec5SDimitry Andric           llvm::StringRef local_name, local_value;
48360b57cec5SDimitry Andric           profileDataExtractor.GetNameColonValue(local_name, local_value);
48370b57cec5SDimitry Andric         }
48380b57cec5SDimitry Andric 
48390b57cec5SDimitry Andric         // Store current time as previous time so that they can be compared
48400b57cec5SDimitry Andric         // later.
48410b57cec5SDimitry Andric         new_thread_id_to_used_usec_map[thread_id] = curr_used_usec;
48420b57cec5SDimitry Andric       } else {
48430b57cec5SDimitry Andric         // Bail out and use old string.
48440b57cec5SDimitry Andric         output_stream << name << ":" << value << ";";
48450b57cec5SDimitry Andric       }
48460b57cec5SDimitry Andric     } else {
48470b57cec5SDimitry Andric       output_stream << name << ":" << value << ";";
48480b57cec5SDimitry Andric     }
48490b57cec5SDimitry Andric   }
48500b57cec5SDimitry Andric   output_stream << end_delimiter;
48510b57cec5SDimitry Andric   m_thread_id_to_used_usec_map = new_thread_id_to_used_usec_map;
48520b57cec5SDimitry Andric 
48530b57cec5SDimitry Andric   return output_stream.str();
48540b57cec5SDimitry Andric }
48550b57cec5SDimitry Andric 
48560b57cec5SDimitry Andric void ProcessGDBRemote::HandleStopReply() {
48570b57cec5SDimitry Andric   if (GetStopID() != 0)
48580b57cec5SDimitry Andric     return;
48590b57cec5SDimitry Andric 
48600b57cec5SDimitry Andric   if (GetID() == LLDB_INVALID_PROCESS_ID) {
48610b57cec5SDimitry Andric     lldb::pid_t pid = m_gdb_comm.GetCurrentProcessID();
48620b57cec5SDimitry Andric     if (pid != LLDB_INVALID_PROCESS_ID)
48630b57cec5SDimitry Andric       SetID(pid);
48640b57cec5SDimitry Andric   }
48650b57cec5SDimitry Andric   BuildDynamicRegisterInfo(true);
48660b57cec5SDimitry Andric }
48670b57cec5SDimitry Andric 
4868349cc55cSDimitry Andric llvm::Expected<bool> ProcessGDBRemote::SaveCore(llvm::StringRef outfile) {
4869349cc55cSDimitry Andric   if (!m_gdb_comm.GetSaveCoreSupported())
4870349cc55cSDimitry Andric     return false;
4871349cc55cSDimitry Andric 
4872349cc55cSDimitry Andric   StreamString packet;
4873349cc55cSDimitry Andric   packet.PutCString("qSaveCore;path-hint:");
4874349cc55cSDimitry Andric   packet.PutStringAsRawHex8(outfile);
4875349cc55cSDimitry Andric 
4876349cc55cSDimitry Andric   StringExtractorGDBRemote response;
4877349cc55cSDimitry Andric   if (m_gdb_comm.SendPacketAndWaitForResponse(packet.GetString(), response) ==
4878349cc55cSDimitry Andric       GDBRemoteCommunication::PacketResult::Success) {
4879349cc55cSDimitry Andric     // TODO: grab error message from the packet?  StringExtractor seems to
4880349cc55cSDimitry Andric     // be missing a method for that
4881349cc55cSDimitry Andric     if (response.IsErrorResponse())
4882349cc55cSDimitry Andric       return llvm::createStringError(
4883349cc55cSDimitry Andric           llvm::inconvertibleErrorCode(),
4884349cc55cSDimitry Andric           llvm::formatv("qSaveCore returned an error"));
4885349cc55cSDimitry Andric 
4886349cc55cSDimitry Andric     std::string path;
4887349cc55cSDimitry Andric 
4888349cc55cSDimitry Andric     // process the response
4889349cc55cSDimitry Andric     for (auto x : llvm::split(response.GetStringRef(), ';')) {
4890349cc55cSDimitry Andric       if (x.consume_front("core-path:"))
4891349cc55cSDimitry Andric         StringExtractor(x).GetHexByteString(path);
4892349cc55cSDimitry Andric     }
4893349cc55cSDimitry Andric 
4894349cc55cSDimitry Andric     // verify that we've gotten what we need
4895349cc55cSDimitry Andric     if (path.empty())
4896349cc55cSDimitry Andric       return llvm::createStringError(llvm::inconvertibleErrorCode(),
4897349cc55cSDimitry Andric                                      "qSaveCore returned no core path");
4898349cc55cSDimitry Andric 
4899349cc55cSDimitry Andric     // now transfer the core file
4900349cc55cSDimitry Andric     FileSpec remote_core{llvm::StringRef(path)};
4901349cc55cSDimitry Andric     Platform &platform = *GetTarget().GetPlatform();
4902349cc55cSDimitry Andric     Status error = platform.GetFile(remote_core, FileSpec(outfile));
4903349cc55cSDimitry Andric 
4904349cc55cSDimitry Andric     if (platform.IsRemote()) {
4905349cc55cSDimitry Andric       // NB: we unlink the file on error too
4906349cc55cSDimitry Andric       platform.Unlink(remote_core);
4907349cc55cSDimitry Andric       if (error.Fail())
4908349cc55cSDimitry Andric         return error.ToError();
4909349cc55cSDimitry Andric     }
4910349cc55cSDimitry Andric 
4911349cc55cSDimitry Andric     return true;
4912349cc55cSDimitry Andric   }
4913349cc55cSDimitry Andric 
4914349cc55cSDimitry Andric   return llvm::createStringError(llvm::inconvertibleErrorCode(),
4915349cc55cSDimitry Andric                                  "Unable to send qSaveCore");
4916349cc55cSDimitry Andric }
4917349cc55cSDimitry Andric 
49180b57cec5SDimitry Andric static const char *const s_async_json_packet_prefix = "JSON-async:";
49190b57cec5SDimitry Andric 
49200b57cec5SDimitry Andric static StructuredData::ObjectSP
49210b57cec5SDimitry Andric ParseStructuredDataPacket(llvm::StringRef packet) {
49220b57cec5SDimitry Andric   Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
49230b57cec5SDimitry Andric 
49240b57cec5SDimitry Andric   if (!packet.consume_front(s_async_json_packet_prefix)) {
49250b57cec5SDimitry Andric     if (log) {
49269dba64beSDimitry Andric       LLDB_LOGF(
49279dba64beSDimitry Andric           log,
49280b57cec5SDimitry Andric           "GDBRemoteCommunicationClientBase::%s() received $J packet "
49290b57cec5SDimitry Andric           "but was not a StructuredData packet: packet starts with "
49300b57cec5SDimitry Andric           "%s",
49310b57cec5SDimitry Andric           __FUNCTION__,
49320b57cec5SDimitry Andric           packet.slice(0, strlen(s_async_json_packet_prefix)).str().c_str());
49330b57cec5SDimitry Andric     }
49340b57cec5SDimitry Andric     return StructuredData::ObjectSP();
49350b57cec5SDimitry Andric   }
49360b57cec5SDimitry Andric 
49370b57cec5SDimitry Andric   // This is an asynchronous JSON packet, destined for a StructuredDataPlugin.
49385ffd83dbSDimitry Andric   StructuredData::ObjectSP json_sp =
49395ffd83dbSDimitry Andric       StructuredData::ParseJSON(std::string(packet));
49400b57cec5SDimitry Andric   if (log) {
49410b57cec5SDimitry Andric     if (json_sp) {
49420b57cec5SDimitry Andric       StreamString json_str;
49439dba64beSDimitry Andric       json_sp->Dump(json_str, true);
49440b57cec5SDimitry Andric       json_str.Flush();
49459dba64beSDimitry Andric       LLDB_LOGF(log,
49469dba64beSDimitry Andric                 "ProcessGDBRemote::%s() "
49470b57cec5SDimitry Andric                 "received Async StructuredData packet: %s",
49480b57cec5SDimitry Andric                 __FUNCTION__, json_str.GetData());
49490b57cec5SDimitry Andric     } else {
49509dba64beSDimitry Andric       LLDB_LOGF(log,
49519dba64beSDimitry Andric                 "ProcessGDBRemote::%s"
49520b57cec5SDimitry Andric                 "() received StructuredData packet:"
49530b57cec5SDimitry Andric                 " parse failure",
49540b57cec5SDimitry Andric                 __FUNCTION__);
49550b57cec5SDimitry Andric     }
49560b57cec5SDimitry Andric   }
49570b57cec5SDimitry Andric   return json_sp;
49580b57cec5SDimitry Andric }
49590b57cec5SDimitry Andric 
49600b57cec5SDimitry Andric void ProcessGDBRemote::HandleAsyncStructuredDataPacket(llvm::StringRef data) {
49610b57cec5SDimitry Andric   auto structured_data_sp = ParseStructuredDataPacket(data);
49620b57cec5SDimitry Andric   if (structured_data_sp)
49630b57cec5SDimitry Andric     RouteAsyncStructuredData(structured_data_sp);
49640b57cec5SDimitry Andric }
49650b57cec5SDimitry Andric 
49660b57cec5SDimitry Andric class CommandObjectProcessGDBRemoteSpeedTest : public CommandObjectParsed {
49670b57cec5SDimitry Andric public:
49680b57cec5SDimitry Andric   CommandObjectProcessGDBRemoteSpeedTest(CommandInterpreter &interpreter)
49690b57cec5SDimitry Andric       : CommandObjectParsed(interpreter, "process plugin packet speed-test",
49700b57cec5SDimitry Andric                             "Tests packet speeds of various sizes to determine "
49710b57cec5SDimitry Andric                             "the performance characteristics of the GDB remote "
49720b57cec5SDimitry Andric                             "connection. ",
49730b57cec5SDimitry Andric                             nullptr),
49740b57cec5SDimitry Andric         m_option_group(),
49750b57cec5SDimitry Andric         m_num_packets(LLDB_OPT_SET_1, false, "count", 'c', 0, eArgTypeCount,
49760b57cec5SDimitry Andric                       "The number of packets to send of each varying size "
49770b57cec5SDimitry Andric                       "(default is 1000).",
49780b57cec5SDimitry Andric                       1000),
49790b57cec5SDimitry Andric         m_max_send(LLDB_OPT_SET_1, false, "max-send", 's', 0, eArgTypeCount,
49800b57cec5SDimitry Andric                    "The maximum number of bytes to send in a packet. Sizes "
49810b57cec5SDimitry Andric                    "increase in powers of 2 while the size is less than or "
49820b57cec5SDimitry Andric                    "equal to this option value. (default 1024).",
49830b57cec5SDimitry Andric                    1024),
49840b57cec5SDimitry Andric         m_max_recv(LLDB_OPT_SET_1, false, "max-receive", 'r', 0, eArgTypeCount,
49850b57cec5SDimitry Andric                    "The maximum number of bytes to receive in a packet. Sizes "
49860b57cec5SDimitry Andric                    "increase in powers of 2 while the size is less than or "
49870b57cec5SDimitry Andric                    "equal to this option value. (default 1024).",
49880b57cec5SDimitry Andric                    1024),
49890b57cec5SDimitry Andric         m_json(LLDB_OPT_SET_1, false, "json", 'j',
49900b57cec5SDimitry Andric                "Print the output as JSON data for easy parsing.", false, true) {
49910b57cec5SDimitry Andric     m_option_group.Append(&m_num_packets, LLDB_OPT_SET_ALL, LLDB_OPT_SET_1);
49920b57cec5SDimitry Andric     m_option_group.Append(&m_max_send, LLDB_OPT_SET_ALL, LLDB_OPT_SET_1);
49930b57cec5SDimitry Andric     m_option_group.Append(&m_max_recv, LLDB_OPT_SET_ALL, LLDB_OPT_SET_1);
49940b57cec5SDimitry Andric     m_option_group.Append(&m_json, LLDB_OPT_SET_ALL, LLDB_OPT_SET_1);
49950b57cec5SDimitry Andric     m_option_group.Finalize();
49960b57cec5SDimitry Andric   }
49970b57cec5SDimitry Andric 
4998fe6060f1SDimitry Andric   ~CommandObjectProcessGDBRemoteSpeedTest() override = default;
49990b57cec5SDimitry Andric 
50000b57cec5SDimitry Andric   Options *GetOptions() override { return &m_option_group; }
50010b57cec5SDimitry Andric 
50020b57cec5SDimitry Andric   bool DoExecute(Args &command, CommandReturnObject &result) override {
50030b57cec5SDimitry Andric     const size_t argc = command.GetArgumentCount();
50040b57cec5SDimitry Andric     if (argc == 0) {
50050b57cec5SDimitry Andric       ProcessGDBRemote *process =
50060b57cec5SDimitry Andric           (ProcessGDBRemote *)m_interpreter.GetExecutionContext()
50070b57cec5SDimitry Andric               .GetProcessPtr();
50080b57cec5SDimitry Andric       if (process) {
50090b57cec5SDimitry Andric         StreamSP output_stream_sp(
50100b57cec5SDimitry Andric             m_interpreter.GetDebugger().GetAsyncOutputStream());
50110b57cec5SDimitry Andric         result.SetImmediateOutputStream(output_stream_sp);
50120b57cec5SDimitry Andric 
50130b57cec5SDimitry Andric         const uint32_t num_packets =
50140b57cec5SDimitry Andric             (uint32_t)m_num_packets.GetOptionValue().GetCurrentValue();
50150b57cec5SDimitry Andric         const uint64_t max_send = m_max_send.GetOptionValue().GetCurrentValue();
50160b57cec5SDimitry Andric         const uint64_t max_recv = m_max_recv.GetOptionValue().GetCurrentValue();
50170b57cec5SDimitry Andric         const bool json = m_json.GetOptionValue().GetCurrentValue();
50180b57cec5SDimitry Andric         const uint64_t k_recv_amount =
50190b57cec5SDimitry Andric             4 * 1024 * 1024; // Receive amount in bytes
50200b57cec5SDimitry Andric         process->GetGDBRemote().TestPacketSpeed(
50210b57cec5SDimitry Andric             num_packets, max_send, max_recv, k_recv_amount, json,
50220b57cec5SDimitry Andric             output_stream_sp ? *output_stream_sp : result.GetOutputStream());
50230b57cec5SDimitry Andric         result.SetStatus(eReturnStatusSuccessFinishResult);
50240b57cec5SDimitry Andric         return true;
50250b57cec5SDimitry Andric       }
50260b57cec5SDimitry Andric     } else {
50270b57cec5SDimitry Andric       result.AppendErrorWithFormat("'%s' takes no arguments",
50280b57cec5SDimitry Andric                                    m_cmd_name.c_str());
50290b57cec5SDimitry Andric     }
50300b57cec5SDimitry Andric     result.SetStatus(eReturnStatusFailed);
50310b57cec5SDimitry Andric     return false;
50320b57cec5SDimitry Andric   }
50330b57cec5SDimitry Andric 
50340b57cec5SDimitry Andric protected:
50350b57cec5SDimitry Andric   OptionGroupOptions m_option_group;
50360b57cec5SDimitry Andric   OptionGroupUInt64 m_num_packets;
50370b57cec5SDimitry Andric   OptionGroupUInt64 m_max_send;
50380b57cec5SDimitry Andric   OptionGroupUInt64 m_max_recv;
50390b57cec5SDimitry Andric   OptionGroupBoolean m_json;
50400b57cec5SDimitry Andric };
50410b57cec5SDimitry Andric 
50420b57cec5SDimitry Andric class CommandObjectProcessGDBRemotePacketHistory : public CommandObjectParsed {
50430b57cec5SDimitry Andric private:
50440b57cec5SDimitry Andric public:
50450b57cec5SDimitry Andric   CommandObjectProcessGDBRemotePacketHistory(CommandInterpreter &interpreter)
50460b57cec5SDimitry Andric       : CommandObjectParsed(interpreter, "process plugin packet history",
50470b57cec5SDimitry Andric                             "Dumps the packet history buffer. ", nullptr) {}
50480b57cec5SDimitry Andric 
5049fe6060f1SDimitry Andric   ~CommandObjectProcessGDBRemotePacketHistory() override = default;
50500b57cec5SDimitry Andric 
50510b57cec5SDimitry Andric   bool DoExecute(Args &command, CommandReturnObject &result) override {
50520b57cec5SDimitry Andric     const size_t argc = command.GetArgumentCount();
50530b57cec5SDimitry Andric     if (argc == 0) {
50540b57cec5SDimitry Andric       ProcessGDBRemote *process =
50550b57cec5SDimitry Andric           (ProcessGDBRemote *)m_interpreter.GetExecutionContext()
50560b57cec5SDimitry Andric               .GetProcessPtr();
50570b57cec5SDimitry Andric       if (process) {
50580b57cec5SDimitry Andric         process->GetGDBRemote().DumpHistory(result.GetOutputStream());
50590b57cec5SDimitry Andric         result.SetStatus(eReturnStatusSuccessFinishResult);
50600b57cec5SDimitry Andric         return true;
50610b57cec5SDimitry Andric       }
50620b57cec5SDimitry Andric     } else {
50630b57cec5SDimitry Andric       result.AppendErrorWithFormat("'%s' takes no arguments",
50640b57cec5SDimitry Andric                                    m_cmd_name.c_str());
50650b57cec5SDimitry Andric     }
50660b57cec5SDimitry Andric     result.SetStatus(eReturnStatusFailed);
50670b57cec5SDimitry Andric     return false;
50680b57cec5SDimitry Andric   }
50690b57cec5SDimitry Andric };
50700b57cec5SDimitry Andric 
50710b57cec5SDimitry Andric class CommandObjectProcessGDBRemotePacketXferSize : public CommandObjectParsed {
50720b57cec5SDimitry Andric private:
50730b57cec5SDimitry Andric public:
50740b57cec5SDimitry Andric   CommandObjectProcessGDBRemotePacketXferSize(CommandInterpreter &interpreter)
50750b57cec5SDimitry Andric       : CommandObjectParsed(
50760b57cec5SDimitry Andric             interpreter, "process plugin packet xfer-size",
50770b57cec5SDimitry Andric             "Maximum size that lldb will try to read/write one one chunk.",
50780b57cec5SDimitry Andric             nullptr) {}
50790b57cec5SDimitry Andric 
5080fe6060f1SDimitry Andric   ~CommandObjectProcessGDBRemotePacketXferSize() override = default;
50810b57cec5SDimitry Andric 
50820b57cec5SDimitry Andric   bool DoExecute(Args &command, CommandReturnObject &result) override {
50830b57cec5SDimitry Andric     const size_t argc = command.GetArgumentCount();
50840b57cec5SDimitry Andric     if (argc == 0) {
50850b57cec5SDimitry Andric       result.AppendErrorWithFormat("'%s' takes an argument to specify the max "
50860b57cec5SDimitry Andric                                    "amount to be transferred when "
50870b57cec5SDimitry Andric                                    "reading/writing",
50880b57cec5SDimitry Andric                                    m_cmd_name.c_str());
50890b57cec5SDimitry Andric       return false;
50900b57cec5SDimitry Andric     }
50910b57cec5SDimitry Andric 
50920b57cec5SDimitry Andric     ProcessGDBRemote *process =
50930b57cec5SDimitry Andric         (ProcessGDBRemote *)m_interpreter.GetExecutionContext().GetProcessPtr();
50940b57cec5SDimitry Andric     if (process) {
50950b57cec5SDimitry Andric       const char *packet_size = command.GetArgumentAtIndex(0);
50960b57cec5SDimitry Andric       errno = 0;
50970b57cec5SDimitry Andric       uint64_t user_specified_max = strtoul(packet_size, nullptr, 10);
50980b57cec5SDimitry Andric       if (errno == 0 && user_specified_max != 0) {
50990b57cec5SDimitry Andric         process->SetUserSpecifiedMaxMemoryTransferSize(user_specified_max);
51000b57cec5SDimitry Andric         result.SetStatus(eReturnStatusSuccessFinishResult);
51010b57cec5SDimitry Andric         return true;
51020b57cec5SDimitry Andric       }
51030b57cec5SDimitry Andric     }
51040b57cec5SDimitry Andric     result.SetStatus(eReturnStatusFailed);
51050b57cec5SDimitry Andric     return false;
51060b57cec5SDimitry Andric   }
51070b57cec5SDimitry Andric };
51080b57cec5SDimitry Andric 
51090b57cec5SDimitry Andric class CommandObjectProcessGDBRemotePacketSend : public CommandObjectParsed {
51100b57cec5SDimitry Andric private:
51110b57cec5SDimitry Andric public:
51120b57cec5SDimitry Andric   CommandObjectProcessGDBRemotePacketSend(CommandInterpreter &interpreter)
51130b57cec5SDimitry Andric       : CommandObjectParsed(interpreter, "process plugin packet send",
51140b57cec5SDimitry Andric                             "Send a custom packet through the GDB remote "
51150b57cec5SDimitry Andric                             "protocol and print the answer. "
51160b57cec5SDimitry Andric                             "The packet header and footer will automatically "
51170b57cec5SDimitry Andric                             "be added to the packet prior to sending and "
51180b57cec5SDimitry Andric                             "stripped from the result.",
51190b57cec5SDimitry Andric                             nullptr) {}
51200b57cec5SDimitry Andric 
5121fe6060f1SDimitry Andric   ~CommandObjectProcessGDBRemotePacketSend() override = default;
51220b57cec5SDimitry Andric 
51230b57cec5SDimitry Andric   bool DoExecute(Args &command, CommandReturnObject &result) override {
51240b57cec5SDimitry Andric     const size_t argc = command.GetArgumentCount();
51250b57cec5SDimitry Andric     if (argc == 0) {
51260b57cec5SDimitry Andric       result.AppendErrorWithFormat(
51270b57cec5SDimitry Andric           "'%s' takes a one or more packet content arguments",
51280b57cec5SDimitry Andric           m_cmd_name.c_str());
51290b57cec5SDimitry Andric       return false;
51300b57cec5SDimitry Andric     }
51310b57cec5SDimitry Andric 
51320b57cec5SDimitry Andric     ProcessGDBRemote *process =
51330b57cec5SDimitry Andric         (ProcessGDBRemote *)m_interpreter.GetExecutionContext().GetProcessPtr();
51340b57cec5SDimitry Andric     if (process) {
51350b57cec5SDimitry Andric       for (size_t i = 0; i < argc; ++i) {
51360b57cec5SDimitry Andric         const char *packet_cstr = command.GetArgumentAtIndex(0);
51370b57cec5SDimitry Andric         StringExtractorGDBRemote response;
51380b57cec5SDimitry Andric         process->GetGDBRemote().SendPacketAndWaitForResponse(
5139fe6060f1SDimitry Andric             packet_cstr, response, process->GetInterruptTimeout());
51400b57cec5SDimitry Andric         result.SetStatus(eReturnStatusSuccessFinishResult);
51410b57cec5SDimitry Andric         Stream &output_strm = result.GetOutputStream();
51420b57cec5SDimitry Andric         output_strm.Printf("  packet: %s\n", packet_cstr);
51435ffd83dbSDimitry Andric         std::string response_str = std::string(response.GetStringRef());
51440b57cec5SDimitry Andric 
51450b57cec5SDimitry Andric         if (strstr(packet_cstr, "qGetProfileData") != nullptr) {
51460b57cec5SDimitry Andric           response_str = process->HarmonizeThreadIdsForProfileData(response);
51470b57cec5SDimitry Andric         }
51480b57cec5SDimitry Andric 
51490b57cec5SDimitry Andric         if (response_str.empty())
51500b57cec5SDimitry Andric           output_strm.PutCString("response: \nerror: UNIMPLEMENTED\n");
51510b57cec5SDimitry Andric         else
51529dba64beSDimitry Andric           output_strm.Printf("response: %s\n", response.GetStringRef().data());
51530b57cec5SDimitry Andric       }
51540b57cec5SDimitry Andric     }
51550b57cec5SDimitry Andric     return true;
51560b57cec5SDimitry Andric   }
51570b57cec5SDimitry Andric };
51580b57cec5SDimitry Andric 
51590b57cec5SDimitry Andric class CommandObjectProcessGDBRemotePacketMonitor : public CommandObjectRaw {
51600b57cec5SDimitry Andric private:
51610b57cec5SDimitry Andric public:
51620b57cec5SDimitry Andric   CommandObjectProcessGDBRemotePacketMonitor(CommandInterpreter &interpreter)
51630b57cec5SDimitry Andric       : CommandObjectRaw(interpreter, "process plugin packet monitor",
51640b57cec5SDimitry Andric                          "Send a qRcmd packet through the GDB remote protocol "
51650b57cec5SDimitry Andric                          "and print the response."
51660b57cec5SDimitry Andric                          "The argument passed to this command will be hex "
51670b57cec5SDimitry Andric                          "encoded into a valid 'qRcmd' packet, sent and the "
51680b57cec5SDimitry Andric                          "response will be printed.") {}
51690b57cec5SDimitry Andric 
5170fe6060f1SDimitry Andric   ~CommandObjectProcessGDBRemotePacketMonitor() override = default;
51710b57cec5SDimitry Andric 
51720b57cec5SDimitry Andric   bool DoExecute(llvm::StringRef command,
51730b57cec5SDimitry Andric                  CommandReturnObject &result) override {
51740b57cec5SDimitry Andric     if (command.empty()) {
51750b57cec5SDimitry Andric       result.AppendErrorWithFormat("'%s' takes a command string argument",
51760b57cec5SDimitry Andric                                    m_cmd_name.c_str());
51770b57cec5SDimitry Andric       return false;
51780b57cec5SDimitry Andric     }
51790b57cec5SDimitry Andric 
51800b57cec5SDimitry Andric     ProcessGDBRemote *process =
51810b57cec5SDimitry Andric         (ProcessGDBRemote *)m_interpreter.GetExecutionContext().GetProcessPtr();
51820b57cec5SDimitry Andric     if (process) {
51830b57cec5SDimitry Andric       StreamString packet;
51840b57cec5SDimitry Andric       packet.PutCString("qRcmd,");
51850b57cec5SDimitry Andric       packet.PutBytesAsRawHex8(command.data(), command.size());
51860b57cec5SDimitry Andric 
51870b57cec5SDimitry Andric       StringExtractorGDBRemote response;
51880b57cec5SDimitry Andric       Stream &output_strm = result.GetOutputStream();
51890b57cec5SDimitry Andric       process->GetGDBRemote().SendPacketAndReceiveResponseWithOutputSupport(
5190fe6060f1SDimitry Andric           packet.GetString(), response, process->GetInterruptTimeout(),
51910b57cec5SDimitry Andric           [&output_strm](llvm::StringRef output) { output_strm << output; });
51920b57cec5SDimitry Andric       result.SetStatus(eReturnStatusSuccessFinishResult);
51930b57cec5SDimitry Andric       output_strm.Printf("  packet: %s\n", packet.GetData());
51945ffd83dbSDimitry Andric       const std::string &response_str = std::string(response.GetStringRef());
51950b57cec5SDimitry Andric 
51960b57cec5SDimitry Andric       if (response_str.empty())
51970b57cec5SDimitry Andric         output_strm.PutCString("response: \nerror: UNIMPLEMENTED\n");
51980b57cec5SDimitry Andric       else
51999dba64beSDimitry Andric         output_strm.Printf("response: %s\n", response.GetStringRef().data());
52000b57cec5SDimitry Andric     }
52010b57cec5SDimitry Andric     return true;
52020b57cec5SDimitry Andric   }
52030b57cec5SDimitry Andric };
52040b57cec5SDimitry Andric 
52050b57cec5SDimitry Andric class CommandObjectProcessGDBRemotePacket : public CommandObjectMultiword {
52060b57cec5SDimitry Andric private:
52070b57cec5SDimitry Andric public:
52080b57cec5SDimitry Andric   CommandObjectProcessGDBRemotePacket(CommandInterpreter &interpreter)
52090b57cec5SDimitry Andric       : CommandObjectMultiword(interpreter, "process plugin packet",
52100b57cec5SDimitry Andric                                "Commands that deal with GDB remote packets.",
52110b57cec5SDimitry Andric                                nullptr) {
52120b57cec5SDimitry Andric     LoadSubCommand(
52130b57cec5SDimitry Andric         "history",
52140b57cec5SDimitry Andric         CommandObjectSP(
52150b57cec5SDimitry Andric             new CommandObjectProcessGDBRemotePacketHistory(interpreter)));
52160b57cec5SDimitry Andric     LoadSubCommand(
52170b57cec5SDimitry Andric         "send", CommandObjectSP(
52180b57cec5SDimitry Andric                     new CommandObjectProcessGDBRemotePacketSend(interpreter)));
52190b57cec5SDimitry Andric     LoadSubCommand(
52200b57cec5SDimitry Andric         "monitor",
52210b57cec5SDimitry Andric         CommandObjectSP(
52220b57cec5SDimitry Andric             new CommandObjectProcessGDBRemotePacketMonitor(interpreter)));
52230b57cec5SDimitry Andric     LoadSubCommand(
52240b57cec5SDimitry Andric         "xfer-size",
52250b57cec5SDimitry Andric         CommandObjectSP(
52260b57cec5SDimitry Andric             new CommandObjectProcessGDBRemotePacketXferSize(interpreter)));
52270b57cec5SDimitry Andric     LoadSubCommand("speed-test",
52280b57cec5SDimitry Andric                    CommandObjectSP(new CommandObjectProcessGDBRemoteSpeedTest(
52290b57cec5SDimitry Andric                        interpreter)));
52300b57cec5SDimitry Andric   }
52310b57cec5SDimitry Andric 
5232fe6060f1SDimitry Andric   ~CommandObjectProcessGDBRemotePacket() override = default;
52330b57cec5SDimitry Andric };
52340b57cec5SDimitry Andric 
52350b57cec5SDimitry Andric class CommandObjectMultiwordProcessGDBRemote : public CommandObjectMultiword {
52360b57cec5SDimitry Andric public:
52370b57cec5SDimitry Andric   CommandObjectMultiwordProcessGDBRemote(CommandInterpreter &interpreter)
52380b57cec5SDimitry Andric       : CommandObjectMultiword(
52390b57cec5SDimitry Andric             interpreter, "process plugin",
52400b57cec5SDimitry Andric             "Commands for operating on a ProcessGDBRemote process.",
52410b57cec5SDimitry Andric             "process plugin <subcommand> [<subcommand-options>]") {
52420b57cec5SDimitry Andric     LoadSubCommand(
52430b57cec5SDimitry Andric         "packet",
52440b57cec5SDimitry Andric         CommandObjectSP(new CommandObjectProcessGDBRemotePacket(interpreter)));
52450b57cec5SDimitry Andric   }
52460b57cec5SDimitry Andric 
5247fe6060f1SDimitry Andric   ~CommandObjectMultiwordProcessGDBRemote() override = default;
52480b57cec5SDimitry Andric };
52490b57cec5SDimitry Andric 
52500b57cec5SDimitry Andric CommandObject *ProcessGDBRemote::GetPluginCommandObject() {
52510b57cec5SDimitry Andric   if (!m_command_sp)
52520b57cec5SDimitry Andric     m_command_sp = std::make_shared<CommandObjectMultiwordProcessGDBRemote>(
52530b57cec5SDimitry Andric         GetTarget().GetDebugger().GetCommandInterpreter());
52540b57cec5SDimitry Andric   return m_command_sp.get();
52550b57cec5SDimitry Andric }
5256349cc55cSDimitry Andric 
5257349cc55cSDimitry Andric void ProcessGDBRemote::DidForkSwitchSoftwareBreakpoints(bool enable) {
5258349cc55cSDimitry Andric   GetBreakpointSiteList().ForEach([this, enable](BreakpointSite *bp_site) {
5259349cc55cSDimitry Andric     if (bp_site->IsEnabled() &&
5260349cc55cSDimitry Andric         (bp_site->GetType() == BreakpointSite::eSoftware ||
5261349cc55cSDimitry Andric          bp_site->GetType() == BreakpointSite::eExternal)) {
5262349cc55cSDimitry Andric       m_gdb_comm.SendGDBStoppointTypePacket(
5263349cc55cSDimitry Andric           eBreakpointSoftware, enable, bp_site->GetLoadAddress(),
5264349cc55cSDimitry Andric           GetSoftwareBreakpointTrapOpcode(bp_site), GetInterruptTimeout());
5265349cc55cSDimitry Andric     }
5266349cc55cSDimitry Andric   });
5267349cc55cSDimitry Andric }
5268349cc55cSDimitry Andric 
5269349cc55cSDimitry Andric void ProcessGDBRemote::DidForkSwitchHardwareTraps(bool enable) {
5270349cc55cSDimitry Andric   if (m_gdb_comm.SupportsGDBStoppointPacket(eBreakpointHardware)) {
5271349cc55cSDimitry Andric     GetBreakpointSiteList().ForEach([this, enable](BreakpointSite *bp_site) {
5272349cc55cSDimitry Andric       if (bp_site->IsEnabled() &&
5273349cc55cSDimitry Andric           bp_site->GetType() == BreakpointSite::eHardware) {
5274349cc55cSDimitry Andric         m_gdb_comm.SendGDBStoppointTypePacket(
5275349cc55cSDimitry Andric             eBreakpointHardware, enable, bp_site->GetLoadAddress(),
5276349cc55cSDimitry Andric             GetSoftwareBreakpointTrapOpcode(bp_site), GetInterruptTimeout());
5277349cc55cSDimitry Andric       }
5278349cc55cSDimitry Andric     });
5279349cc55cSDimitry Andric   }
5280349cc55cSDimitry Andric 
5281349cc55cSDimitry Andric   WatchpointList &wps = GetTarget().GetWatchpointList();
5282349cc55cSDimitry Andric   size_t wp_count = wps.GetSize();
5283349cc55cSDimitry Andric   for (size_t i = 0; i < wp_count; ++i) {
5284349cc55cSDimitry Andric     WatchpointSP wp = wps.GetByIndex(i);
5285349cc55cSDimitry Andric     if (wp->IsEnabled()) {
5286349cc55cSDimitry Andric       GDBStoppointType type = GetGDBStoppointType(wp.get());
5287349cc55cSDimitry Andric       m_gdb_comm.SendGDBStoppointTypePacket(type, enable, wp->GetLoadAddress(),
5288349cc55cSDimitry Andric                                             wp->GetByteSize(),
5289349cc55cSDimitry Andric                                             GetInterruptTimeout());
5290349cc55cSDimitry Andric     }
5291349cc55cSDimitry Andric   }
5292349cc55cSDimitry Andric }
5293349cc55cSDimitry Andric 
5294349cc55cSDimitry Andric void ProcessGDBRemote::DidFork(lldb::pid_t child_pid, lldb::tid_t child_tid) {
5295349cc55cSDimitry Andric   Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
5296349cc55cSDimitry Andric 
5297349cc55cSDimitry Andric   lldb::pid_t parent_pid = m_gdb_comm.GetCurrentProcessID();
5298349cc55cSDimitry Andric   // Any valid TID will suffice, thread-relevant actions will set a proper TID
5299349cc55cSDimitry Andric   // anyway.
5300349cc55cSDimitry Andric   lldb::tid_t parent_tid = m_thread_ids.front();
5301349cc55cSDimitry Andric 
5302349cc55cSDimitry Andric   lldb::pid_t follow_pid, detach_pid;
5303349cc55cSDimitry Andric   lldb::tid_t follow_tid, detach_tid;
5304349cc55cSDimitry Andric 
5305349cc55cSDimitry Andric   switch (GetFollowForkMode()) {
5306349cc55cSDimitry Andric   case eFollowParent:
5307349cc55cSDimitry Andric     follow_pid = parent_pid;
5308349cc55cSDimitry Andric     follow_tid = parent_tid;
5309349cc55cSDimitry Andric     detach_pid = child_pid;
5310349cc55cSDimitry Andric     detach_tid = child_tid;
5311349cc55cSDimitry Andric     break;
5312349cc55cSDimitry Andric   case eFollowChild:
5313349cc55cSDimitry Andric     follow_pid = child_pid;
5314349cc55cSDimitry Andric     follow_tid = child_tid;
5315349cc55cSDimitry Andric     detach_pid = parent_pid;
5316349cc55cSDimitry Andric     detach_tid = parent_tid;
5317349cc55cSDimitry Andric     break;
5318349cc55cSDimitry Andric   }
5319349cc55cSDimitry Andric 
5320349cc55cSDimitry Andric   // Switch to the process that is going to be detached.
5321349cc55cSDimitry Andric   if (!m_gdb_comm.SetCurrentThread(detach_tid, detach_pid)) {
5322349cc55cSDimitry Andric     LLDB_LOG(log, "ProcessGDBRemote::DidFork() unable to set pid/tid");
5323349cc55cSDimitry Andric     return;
5324349cc55cSDimitry Andric   }
5325349cc55cSDimitry Andric 
5326349cc55cSDimitry Andric   // Disable all software breakpoints in the forked process.
5327349cc55cSDimitry Andric   if (m_gdb_comm.SupportsGDBStoppointPacket(eBreakpointSoftware))
5328349cc55cSDimitry Andric     DidForkSwitchSoftwareBreakpoints(false);
5329349cc55cSDimitry Andric 
5330349cc55cSDimitry Andric   // Remove hardware breakpoints / watchpoints from parent process if we're
5331349cc55cSDimitry Andric   // following child.
5332349cc55cSDimitry Andric   if (GetFollowForkMode() == eFollowChild)
5333349cc55cSDimitry Andric     DidForkSwitchHardwareTraps(false);
5334349cc55cSDimitry Andric 
5335349cc55cSDimitry Andric   // Switch to the process that is going to be followed
5336349cc55cSDimitry Andric   if (!m_gdb_comm.SetCurrentThread(follow_tid, follow_pid) ||
5337349cc55cSDimitry Andric       !m_gdb_comm.SetCurrentThreadForRun(follow_tid, follow_pid)) {
5338349cc55cSDimitry Andric     LLDB_LOG(log, "ProcessGDBRemote::DidFork() unable to reset pid/tid");
5339349cc55cSDimitry Andric     return;
5340349cc55cSDimitry Andric   }
5341349cc55cSDimitry Andric 
5342349cc55cSDimitry Andric   LLDB_LOG(log, "Detaching process {0}", detach_pid);
5343349cc55cSDimitry Andric   Status error = m_gdb_comm.Detach(false, detach_pid);
5344349cc55cSDimitry Andric   if (error.Fail()) {
5345349cc55cSDimitry Andric     LLDB_LOG(log, "ProcessGDBRemote::DidFork() detach packet send failed: {0}",
5346349cc55cSDimitry Andric              error.AsCString() ? error.AsCString() : "<unknown error>");
5347349cc55cSDimitry Andric     return;
5348349cc55cSDimitry Andric   }
5349349cc55cSDimitry Andric 
5350349cc55cSDimitry Andric   // Hardware breakpoints/watchpoints are not inherited implicitly,
5351349cc55cSDimitry Andric   // so we need to readd them if we're following child.
5352349cc55cSDimitry Andric   if (GetFollowForkMode() == eFollowChild)
5353349cc55cSDimitry Andric     DidForkSwitchHardwareTraps(true);
5354349cc55cSDimitry Andric }
5355349cc55cSDimitry Andric 
5356349cc55cSDimitry Andric void ProcessGDBRemote::DidVFork(lldb::pid_t child_pid, lldb::tid_t child_tid) {
5357349cc55cSDimitry Andric   Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
5358349cc55cSDimitry Andric 
5359349cc55cSDimitry Andric   assert(!m_vfork_in_progress);
5360349cc55cSDimitry Andric   m_vfork_in_progress = true;
5361349cc55cSDimitry Andric 
5362349cc55cSDimitry Andric   // Disable all software breakpoints for the duration of vfork.
5363349cc55cSDimitry Andric   if (m_gdb_comm.SupportsGDBStoppointPacket(eBreakpointSoftware))
5364349cc55cSDimitry Andric     DidForkSwitchSoftwareBreakpoints(false);
5365349cc55cSDimitry Andric 
5366349cc55cSDimitry Andric   lldb::pid_t detach_pid;
5367349cc55cSDimitry Andric   lldb::tid_t detach_tid;
5368349cc55cSDimitry Andric 
5369349cc55cSDimitry Andric   switch (GetFollowForkMode()) {
5370349cc55cSDimitry Andric   case eFollowParent:
5371349cc55cSDimitry Andric     detach_pid = child_pid;
5372349cc55cSDimitry Andric     detach_tid = child_tid;
5373349cc55cSDimitry Andric     break;
5374349cc55cSDimitry Andric   case eFollowChild:
5375349cc55cSDimitry Andric     detach_pid = m_gdb_comm.GetCurrentProcessID();
5376349cc55cSDimitry Andric     // Any valid TID will suffice, thread-relevant actions will set a proper TID
5377349cc55cSDimitry Andric     // anyway.
5378349cc55cSDimitry Andric     detach_tid = m_thread_ids.front();
5379349cc55cSDimitry Andric 
5380349cc55cSDimitry Andric     // Switch to the parent process before detaching it.
5381349cc55cSDimitry Andric     if (!m_gdb_comm.SetCurrentThread(detach_tid, detach_pid)) {
5382349cc55cSDimitry Andric       LLDB_LOG(log, "ProcessGDBRemote::DidFork() unable to set pid/tid");
5383349cc55cSDimitry Andric       return;
5384349cc55cSDimitry Andric     }
5385349cc55cSDimitry Andric 
5386349cc55cSDimitry Andric     // Remove hardware breakpoints / watchpoints from the parent process.
5387349cc55cSDimitry Andric     DidForkSwitchHardwareTraps(false);
5388349cc55cSDimitry Andric 
5389349cc55cSDimitry Andric     // Switch to the child process.
5390349cc55cSDimitry Andric     if (!m_gdb_comm.SetCurrentThread(child_tid, child_pid) ||
5391349cc55cSDimitry Andric         !m_gdb_comm.SetCurrentThreadForRun(child_tid, child_pid)) {
5392349cc55cSDimitry Andric       LLDB_LOG(log, "ProcessGDBRemote::DidFork() unable to reset pid/tid");
5393349cc55cSDimitry Andric       return;
5394349cc55cSDimitry Andric     }
5395349cc55cSDimitry Andric     break;
5396349cc55cSDimitry Andric   }
5397349cc55cSDimitry Andric 
5398349cc55cSDimitry Andric   LLDB_LOG(log, "Detaching process {0}", detach_pid);
5399349cc55cSDimitry Andric   Status error = m_gdb_comm.Detach(false, detach_pid);
5400349cc55cSDimitry Andric   if (error.Fail()) {
5401349cc55cSDimitry Andric       LLDB_LOG(log,
5402349cc55cSDimitry Andric                "ProcessGDBRemote::DidFork() detach packet send failed: {0}",
5403349cc55cSDimitry Andric                 error.AsCString() ? error.AsCString() : "<unknown error>");
5404349cc55cSDimitry Andric       return;
5405349cc55cSDimitry Andric   }
5406349cc55cSDimitry Andric }
5407349cc55cSDimitry Andric 
5408349cc55cSDimitry Andric void ProcessGDBRemote::DidVForkDone() {
5409349cc55cSDimitry Andric   assert(m_vfork_in_progress);
5410349cc55cSDimitry Andric   m_vfork_in_progress = false;
5411349cc55cSDimitry Andric 
5412349cc55cSDimitry Andric   // Reenable all software breakpoints that were enabled before vfork.
5413349cc55cSDimitry Andric   if (m_gdb_comm.SupportsGDBStoppointPacket(eBreakpointSoftware))
5414349cc55cSDimitry Andric     DidForkSwitchSoftwareBreakpoints(true);
5415349cc55cSDimitry Andric }
5416349cc55cSDimitry Andric 
5417349cc55cSDimitry Andric void ProcessGDBRemote::DidExec() {
5418349cc55cSDimitry Andric   // If we are following children, vfork is finished by exec (rather than
5419349cc55cSDimitry Andric   // vforkdone that is submitted for parent).
5420349cc55cSDimitry Andric   if (GetFollowForkMode() == eFollowChild)
5421349cc55cSDimitry Andric     m_vfork_in_progress = false;
5422349cc55cSDimitry Andric   Process::DidExec();
5423349cc55cSDimitry Andric }
5424