xref: /freebsd-src/contrib/llvm-project/lldb/source/Plugins/Process/gdb-remote/ProcessGDBRemote.cpp (revision 580012d60438215d86a9e6b2a8038de964867163)
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 
110b57cec5SDimitry Andric #include <errno.h>
120b57cec5SDimitry Andric #include <stdlib.h>
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
230b57cec5SDimitry Andric #include <sys/types.h>
240b57cec5SDimitry Andric #include <time.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/StringConvert.h"
470b57cec5SDimitry Andric #include "lldb/Host/ThreadLauncher.h"
480b57cec5SDimitry Andric #include "lldb/Host/XML.h"
490b57cec5SDimitry Andric #include "lldb/Interpreter/CommandInterpreter.h"
500b57cec5SDimitry Andric #include "lldb/Interpreter/CommandObject.h"
510b57cec5SDimitry Andric #include "lldb/Interpreter/CommandObjectMultiword.h"
520b57cec5SDimitry Andric #include "lldb/Interpreter/CommandReturnObject.h"
530b57cec5SDimitry Andric #include "lldb/Interpreter/OptionArgParser.h"
540b57cec5SDimitry Andric #include "lldb/Interpreter/OptionGroupBoolean.h"
550b57cec5SDimitry Andric #include "lldb/Interpreter/OptionGroupUInt64.h"
560b57cec5SDimitry Andric #include "lldb/Interpreter/OptionValueProperties.h"
570b57cec5SDimitry Andric #include "lldb/Interpreter/Options.h"
580b57cec5SDimitry Andric #include "lldb/Interpreter/Property.h"
590b57cec5SDimitry Andric #include "lldb/Symbol/LocateSymbolFile.h"
600b57cec5SDimitry Andric #include "lldb/Symbol/ObjectFile.h"
610b57cec5SDimitry Andric #include "lldb/Target/ABI.h"
620b57cec5SDimitry Andric #include "lldb/Target/DynamicLoader.h"
630b57cec5SDimitry Andric #include "lldb/Target/MemoryRegionInfo.h"
640b57cec5SDimitry Andric #include "lldb/Target/SystemRuntime.h"
650b57cec5SDimitry Andric #include "lldb/Target/Target.h"
660b57cec5SDimitry Andric #include "lldb/Target/TargetList.h"
670b57cec5SDimitry Andric #include "lldb/Target/ThreadPlanCallFunction.h"
680b57cec5SDimitry Andric #include "lldb/Utility/Args.h"
690b57cec5SDimitry Andric #include "lldb/Utility/FileSpec.h"
700b57cec5SDimitry Andric #include "lldb/Utility/Reproducer.h"
710b57cec5SDimitry Andric #include "lldb/Utility/State.h"
720b57cec5SDimitry Andric #include "lldb/Utility/StreamString.h"
730b57cec5SDimitry Andric #include "lldb/Utility/Timer.h"
740b57cec5SDimitry Andric 
750b57cec5SDimitry Andric #include "GDBRemoteRegisterContext.h"
76*580012d6SDimitry Andric #ifdef LLDB_ENABLE_ALL
770b57cec5SDimitry Andric #include "Plugins/Platform/MacOSX/PlatformRemoteiOS.h"
78*580012d6SDimitry Andric #endif // LLDB_ENABLE_ALL
790b57cec5SDimitry Andric #include "Plugins/Process/Utility/GDBRemoteSignals.h"
800b57cec5SDimitry Andric #include "Plugins/Process/Utility/InferiorCallPOSIX.h"
810b57cec5SDimitry Andric #include "Plugins/Process/Utility/StopInfoMachException.h"
820b57cec5SDimitry Andric #include "ProcessGDBRemote.h"
830b57cec5SDimitry Andric #include "ProcessGDBRemoteLog.h"
840b57cec5SDimitry Andric #include "ThreadGDBRemote.h"
850b57cec5SDimitry Andric #include "lldb/Host/Host.h"
860b57cec5SDimitry Andric #include "lldb/Utility/StringExtractorGDBRemote.h"
870b57cec5SDimitry Andric 
889dba64beSDimitry Andric #include "llvm/ADT/ScopeExit.h"
890b57cec5SDimitry Andric #include "llvm/ADT/StringSwitch.h"
900b57cec5SDimitry Andric #include "llvm/Support/Threading.h"
910b57cec5SDimitry Andric #include "llvm/Support/raw_ostream.h"
920b57cec5SDimitry Andric 
930b57cec5SDimitry Andric #define DEBUGSERVER_BASENAME "debugserver"
940b57cec5SDimitry Andric using namespace lldb;
950b57cec5SDimitry Andric using namespace lldb_private;
960b57cec5SDimitry Andric using namespace lldb_private::process_gdb_remote;
970b57cec5SDimitry Andric 
985ffd83dbSDimitry Andric LLDB_PLUGIN_DEFINE(ProcessGDBRemote)
995ffd83dbSDimitry Andric 
1000b57cec5SDimitry Andric namespace lldb {
1010b57cec5SDimitry Andric // Provide a function that can easily dump the packet history if we know a
1020b57cec5SDimitry Andric // ProcessGDBRemote * value (which we can get from logs or from debugging). We
1030b57cec5SDimitry Andric // need the function in the lldb namespace so it makes it into the final
1040b57cec5SDimitry Andric // executable since the LLDB shared library only exports stuff in the lldb
1050b57cec5SDimitry Andric // namespace. This allows you to attach with a debugger and call this function
1060b57cec5SDimitry Andric // and get the packet history dumped to a file.
1070b57cec5SDimitry Andric void DumpProcessGDBRemotePacketHistory(void *p, const char *path) {
1089dba64beSDimitry Andric   auto file = FileSystem::Instance().Open(
1099dba64beSDimitry Andric       FileSpec(path), File::eOpenOptionWrite | File::eOpenOptionCanCreate);
1109dba64beSDimitry Andric   if (!file) {
1119dba64beSDimitry Andric     llvm::consumeError(file.takeError());
1129dba64beSDimitry Andric     return;
1139dba64beSDimitry Andric   }
1149dba64beSDimitry Andric   StreamFile stream(std::move(file.get()));
1159dba64beSDimitry Andric   ((ProcessGDBRemote *)p)->GetGDBRemote().DumpHistory(stream);
1160b57cec5SDimitry Andric }
1170b57cec5SDimitry Andric } // namespace lldb
1180b57cec5SDimitry Andric 
1190b57cec5SDimitry Andric namespace {
1200b57cec5SDimitry Andric 
1219dba64beSDimitry Andric #define LLDB_PROPERTIES_processgdbremote
1229dba64beSDimitry Andric #include "ProcessGDBRemoteProperties.inc"
1230b57cec5SDimitry Andric 
1240b57cec5SDimitry Andric enum {
1259dba64beSDimitry Andric #define LLDB_PROPERTIES_processgdbremote
1269dba64beSDimitry Andric #include "ProcessGDBRemotePropertiesEnum.inc"
1270b57cec5SDimitry Andric };
1280b57cec5SDimitry Andric 
1290b57cec5SDimitry Andric class PluginProperties : public Properties {
1300b57cec5SDimitry Andric public:
1310b57cec5SDimitry Andric   static ConstString GetSettingName() {
1320b57cec5SDimitry Andric     return ProcessGDBRemote::GetPluginNameStatic();
1330b57cec5SDimitry Andric   }
1340b57cec5SDimitry Andric 
1350b57cec5SDimitry Andric   PluginProperties() : Properties() {
1360b57cec5SDimitry Andric     m_collection_sp = std::make_shared<OptionValueProperties>(GetSettingName());
1379dba64beSDimitry Andric     m_collection_sp->Initialize(g_processgdbremote_properties);
1380b57cec5SDimitry Andric   }
1390b57cec5SDimitry Andric 
1400b57cec5SDimitry Andric   ~PluginProperties() override {}
1410b57cec5SDimitry Andric 
1420b57cec5SDimitry Andric   uint64_t GetPacketTimeout() {
1430b57cec5SDimitry Andric     const uint32_t idx = ePropertyPacketTimeout;
1440b57cec5SDimitry Andric     return m_collection_sp->GetPropertyAtIndexAsUInt64(
1459dba64beSDimitry Andric         nullptr, idx, g_processgdbremote_properties[idx].default_uint_value);
1460b57cec5SDimitry Andric   }
1470b57cec5SDimitry Andric 
1480b57cec5SDimitry Andric   bool SetPacketTimeout(uint64_t timeout) {
1490b57cec5SDimitry Andric     const uint32_t idx = ePropertyPacketTimeout;
1500b57cec5SDimitry Andric     return m_collection_sp->SetPropertyAtIndexAsUInt64(nullptr, idx, timeout);
1510b57cec5SDimitry Andric   }
1520b57cec5SDimitry Andric 
1530b57cec5SDimitry Andric   FileSpec GetTargetDefinitionFile() const {
1540b57cec5SDimitry Andric     const uint32_t idx = ePropertyTargetDefinitionFile;
1550b57cec5SDimitry Andric     return m_collection_sp->GetPropertyAtIndexAsFileSpec(nullptr, idx);
1560b57cec5SDimitry Andric   }
1570b57cec5SDimitry Andric 
1580b57cec5SDimitry Andric   bool GetUseSVR4() const {
1590b57cec5SDimitry Andric     const uint32_t idx = ePropertyUseSVR4;
1600b57cec5SDimitry Andric     return m_collection_sp->GetPropertyAtIndexAsBoolean(
1619dba64beSDimitry Andric         nullptr, idx,
1629dba64beSDimitry Andric         g_processgdbremote_properties[idx].default_uint_value != 0);
1630b57cec5SDimitry Andric   }
164480093f4SDimitry Andric 
165480093f4SDimitry Andric   bool GetUseGPacketForReading() const {
166480093f4SDimitry Andric     const uint32_t idx = ePropertyUseGPacketForReading;
167480093f4SDimitry Andric     return m_collection_sp->GetPropertyAtIndexAsBoolean(nullptr, idx, true);
168480093f4SDimitry Andric   }
1690b57cec5SDimitry Andric };
1700b57cec5SDimitry Andric 
1710b57cec5SDimitry Andric typedef std::shared_ptr<PluginProperties> ProcessKDPPropertiesSP;
1720b57cec5SDimitry Andric 
1730b57cec5SDimitry Andric static const ProcessKDPPropertiesSP &GetGlobalPluginProperties() {
1740b57cec5SDimitry Andric   static ProcessKDPPropertiesSP g_settings_sp;
1750b57cec5SDimitry Andric   if (!g_settings_sp)
1760b57cec5SDimitry Andric     g_settings_sp = std::make_shared<PluginProperties>();
1770b57cec5SDimitry Andric   return g_settings_sp;
1780b57cec5SDimitry Andric }
1790b57cec5SDimitry Andric 
1800b57cec5SDimitry Andric } // namespace
1810b57cec5SDimitry Andric 
1820b57cec5SDimitry Andric // TODO Randomly assigning a port is unsafe.  We should get an unused
1830b57cec5SDimitry Andric // ephemeral port from the kernel and make sure we reserve it before passing it
1840b57cec5SDimitry Andric // to debugserver.
1850b57cec5SDimitry Andric 
1860b57cec5SDimitry Andric #if defined(__APPLE__)
1870b57cec5SDimitry Andric #define LOW_PORT (IPPORT_RESERVED)
1880b57cec5SDimitry Andric #define HIGH_PORT (IPPORT_HIFIRSTAUTO)
1890b57cec5SDimitry Andric #else
1900b57cec5SDimitry Andric #define LOW_PORT (1024u)
1910b57cec5SDimitry Andric #define HIGH_PORT (49151u)
1920b57cec5SDimitry Andric #endif
1930b57cec5SDimitry Andric 
1940b57cec5SDimitry Andric ConstString ProcessGDBRemote::GetPluginNameStatic() {
1950b57cec5SDimitry Andric   static ConstString g_name("gdb-remote");
1960b57cec5SDimitry Andric   return g_name;
1970b57cec5SDimitry Andric }
1980b57cec5SDimitry Andric 
1990b57cec5SDimitry Andric const char *ProcessGDBRemote::GetPluginDescriptionStatic() {
2000b57cec5SDimitry Andric   return "GDB Remote protocol based debugging plug-in.";
2010b57cec5SDimitry Andric }
2020b57cec5SDimitry Andric 
2030b57cec5SDimitry Andric void ProcessGDBRemote::Terminate() {
2040b57cec5SDimitry Andric   PluginManager::UnregisterPlugin(ProcessGDBRemote::CreateInstance);
2050b57cec5SDimitry Andric }
2060b57cec5SDimitry Andric 
2070b57cec5SDimitry Andric lldb::ProcessSP
2080b57cec5SDimitry Andric ProcessGDBRemote::CreateInstance(lldb::TargetSP target_sp,
2090b57cec5SDimitry Andric                                  ListenerSP listener_sp,
2100b57cec5SDimitry Andric                                  const FileSpec *crash_file_path) {
2110b57cec5SDimitry Andric   lldb::ProcessSP process_sp;
2120b57cec5SDimitry Andric   if (crash_file_path == nullptr)
2130b57cec5SDimitry Andric     process_sp = std::make_shared<ProcessGDBRemote>(target_sp, listener_sp);
2140b57cec5SDimitry Andric   return process_sp;
2150b57cec5SDimitry Andric }
2160b57cec5SDimitry Andric 
2170b57cec5SDimitry Andric bool ProcessGDBRemote::CanDebug(lldb::TargetSP target_sp,
2180b57cec5SDimitry Andric                                 bool plugin_specified_by_name) {
2190b57cec5SDimitry Andric   if (plugin_specified_by_name)
2200b57cec5SDimitry Andric     return true;
2210b57cec5SDimitry Andric 
2220b57cec5SDimitry Andric   // For now we are just making sure the file exists for a given module
2230b57cec5SDimitry Andric   Module *exe_module = target_sp->GetExecutableModulePointer();
2240b57cec5SDimitry Andric   if (exe_module) {
2250b57cec5SDimitry Andric     ObjectFile *exe_objfile = exe_module->GetObjectFile();
2260b57cec5SDimitry Andric     // We can't debug core files...
2270b57cec5SDimitry Andric     switch (exe_objfile->GetType()) {
2280b57cec5SDimitry Andric     case ObjectFile::eTypeInvalid:
2290b57cec5SDimitry Andric     case ObjectFile::eTypeCoreFile:
2300b57cec5SDimitry Andric     case ObjectFile::eTypeDebugInfo:
2310b57cec5SDimitry Andric     case ObjectFile::eTypeObjectFile:
2320b57cec5SDimitry Andric     case ObjectFile::eTypeSharedLibrary:
2330b57cec5SDimitry Andric     case ObjectFile::eTypeStubLibrary:
2340b57cec5SDimitry Andric     case ObjectFile::eTypeJIT:
2350b57cec5SDimitry Andric       return false;
2360b57cec5SDimitry Andric     case ObjectFile::eTypeExecutable:
2370b57cec5SDimitry Andric     case ObjectFile::eTypeDynamicLinker:
2380b57cec5SDimitry Andric     case ObjectFile::eTypeUnknown:
2390b57cec5SDimitry Andric       break;
2400b57cec5SDimitry Andric     }
2410b57cec5SDimitry Andric     return FileSystem::Instance().Exists(exe_module->GetFileSpec());
2420b57cec5SDimitry Andric   }
2430b57cec5SDimitry Andric   // However, if there is no executable module, we return true since we might
2440b57cec5SDimitry Andric   // be preparing to attach.
2450b57cec5SDimitry Andric   return true;
2460b57cec5SDimitry Andric }
2470b57cec5SDimitry Andric 
2480b57cec5SDimitry Andric // ProcessGDBRemote constructor
2490b57cec5SDimitry Andric ProcessGDBRemote::ProcessGDBRemote(lldb::TargetSP target_sp,
2500b57cec5SDimitry Andric                                    ListenerSP listener_sp)
2510b57cec5SDimitry Andric     : Process(target_sp, listener_sp),
2520b57cec5SDimitry Andric       m_debugserver_pid(LLDB_INVALID_PROCESS_ID), m_last_stop_packet_mutex(),
2530b57cec5SDimitry Andric       m_register_info(),
2540b57cec5SDimitry Andric       m_async_broadcaster(nullptr, "lldb.process.gdb-remote.async-broadcaster"),
2550b57cec5SDimitry Andric       m_async_listener_sp(
2560b57cec5SDimitry Andric           Listener::MakeListener("lldb.process.gdb-remote.async-listener")),
2570b57cec5SDimitry Andric       m_async_thread_state_mutex(), m_thread_ids(), m_thread_pcs(),
2580b57cec5SDimitry Andric       m_jstopinfo_sp(), m_jthreadsinfo_sp(), m_continue_c_tids(),
2590b57cec5SDimitry Andric       m_continue_C_tids(), m_continue_s_tids(), m_continue_S_tids(),
2600b57cec5SDimitry Andric       m_max_memory_size(0), m_remote_stub_max_memory_size(0),
2610b57cec5SDimitry Andric       m_addr_to_mmap_size(), m_thread_create_bp_sp(),
2620b57cec5SDimitry Andric       m_waiting_for_attach(false), m_destroy_tried_resuming(false),
2630b57cec5SDimitry Andric       m_command_sp(), m_breakpoint_pc_offset(0),
2640b57cec5SDimitry Andric       m_initial_tid(LLDB_INVALID_THREAD_ID), m_replay_mode(false),
2650b57cec5SDimitry Andric       m_allow_flash_writes(false), m_erased_flash_ranges() {
2660b57cec5SDimitry Andric   m_async_broadcaster.SetEventName(eBroadcastBitAsyncThreadShouldExit,
2670b57cec5SDimitry Andric                                    "async thread should exit");
2680b57cec5SDimitry Andric   m_async_broadcaster.SetEventName(eBroadcastBitAsyncContinue,
2690b57cec5SDimitry Andric                                    "async thread continue");
2700b57cec5SDimitry Andric   m_async_broadcaster.SetEventName(eBroadcastBitAsyncThreadDidExit,
2710b57cec5SDimitry Andric                                    "async thread did exit");
2720b57cec5SDimitry Andric 
2730b57cec5SDimitry Andric   if (repro::Generator *g = repro::Reproducer::Instance().GetGenerator()) {
274480093f4SDimitry Andric     repro::GDBRemoteProvider &provider =
275480093f4SDimitry Andric         g->GetOrCreate<repro::GDBRemoteProvider>();
276480093f4SDimitry Andric     m_gdb_comm.SetPacketRecorder(provider.GetNewPacketRecorder());
2770b57cec5SDimitry Andric   }
2780b57cec5SDimitry Andric 
2790b57cec5SDimitry Andric   Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_ASYNC));
2800b57cec5SDimitry Andric 
2810b57cec5SDimitry Andric   const uint32_t async_event_mask =
2820b57cec5SDimitry Andric       eBroadcastBitAsyncContinue | eBroadcastBitAsyncThreadShouldExit;
2830b57cec5SDimitry Andric 
2840b57cec5SDimitry Andric   if (m_async_listener_sp->StartListeningForEvents(
2850b57cec5SDimitry Andric           &m_async_broadcaster, async_event_mask) != async_event_mask) {
2869dba64beSDimitry Andric     LLDB_LOGF(log,
2879dba64beSDimitry Andric               "ProcessGDBRemote::%s failed to listen for "
2880b57cec5SDimitry Andric               "m_async_broadcaster events",
2890b57cec5SDimitry Andric               __FUNCTION__);
2900b57cec5SDimitry Andric   }
2910b57cec5SDimitry Andric 
2920b57cec5SDimitry Andric   const uint32_t gdb_event_mask =
2930b57cec5SDimitry Andric       Communication::eBroadcastBitReadThreadDidExit |
2940b57cec5SDimitry Andric       GDBRemoteCommunication::eBroadcastBitGdbReadThreadGotNotify;
2950b57cec5SDimitry Andric   if (m_async_listener_sp->StartListeningForEvents(
2960b57cec5SDimitry Andric           &m_gdb_comm, gdb_event_mask) != gdb_event_mask) {
2979dba64beSDimitry Andric     LLDB_LOGF(log,
2989dba64beSDimitry Andric               "ProcessGDBRemote::%s failed to listen for m_gdb_comm events",
2990b57cec5SDimitry Andric               __FUNCTION__);
3000b57cec5SDimitry Andric   }
3010b57cec5SDimitry Andric 
3020b57cec5SDimitry Andric   const uint64_t timeout_seconds =
3030b57cec5SDimitry Andric       GetGlobalPluginProperties()->GetPacketTimeout();
3040b57cec5SDimitry Andric   if (timeout_seconds > 0)
3050b57cec5SDimitry Andric     m_gdb_comm.SetPacketTimeout(std::chrono::seconds(timeout_seconds));
306480093f4SDimitry Andric 
307480093f4SDimitry Andric   m_use_g_packet_for_reading =
308480093f4SDimitry Andric       GetGlobalPluginProperties()->GetUseGPacketForReading();
3090b57cec5SDimitry Andric }
3100b57cec5SDimitry Andric 
3110b57cec5SDimitry Andric // Destructor
3120b57cec5SDimitry Andric ProcessGDBRemote::~ProcessGDBRemote() {
3130b57cec5SDimitry Andric   //  m_mach_process.UnregisterNotificationCallbacks (this);
3140b57cec5SDimitry Andric   Clear();
3150b57cec5SDimitry Andric   // We need to call finalize on the process before destroying ourselves to
3160b57cec5SDimitry Andric   // make sure all of the broadcaster cleanup goes as planned. If we destruct
3170b57cec5SDimitry Andric   // this class, then Process::~Process() might have problems trying to fully
3180b57cec5SDimitry Andric   // destroy the broadcaster.
3190b57cec5SDimitry Andric   Finalize();
3200b57cec5SDimitry Andric 
3210b57cec5SDimitry Andric   // The general Finalize is going to try to destroy the process and that
3220b57cec5SDimitry Andric   // SHOULD shut down the async thread.  However, if we don't kill it it will
3230b57cec5SDimitry Andric   // get stranded and its connection will go away so when it wakes up it will
3240b57cec5SDimitry Andric   // crash.  So kill it for sure here.
3250b57cec5SDimitry Andric   StopAsyncThread();
3260b57cec5SDimitry Andric   KillDebugserverProcess();
3270b57cec5SDimitry Andric }
3280b57cec5SDimitry Andric 
3290b57cec5SDimitry Andric // PluginInterface
3300b57cec5SDimitry Andric ConstString ProcessGDBRemote::GetPluginName() { return GetPluginNameStatic(); }
3310b57cec5SDimitry Andric 
3320b57cec5SDimitry Andric uint32_t ProcessGDBRemote::GetPluginVersion() { return 1; }
3330b57cec5SDimitry Andric 
3340b57cec5SDimitry Andric bool ProcessGDBRemote::ParsePythonTargetDefinition(
3350b57cec5SDimitry Andric     const FileSpec &target_definition_fspec) {
3360b57cec5SDimitry Andric   ScriptInterpreter *interpreter =
3370b57cec5SDimitry Andric       GetTarget().GetDebugger().GetScriptInterpreter();
3380b57cec5SDimitry Andric   Status error;
3390b57cec5SDimitry Andric   StructuredData::ObjectSP module_object_sp(
3400b57cec5SDimitry Andric       interpreter->LoadPluginModule(target_definition_fspec, error));
3410b57cec5SDimitry Andric   if (module_object_sp) {
3420b57cec5SDimitry Andric     StructuredData::DictionarySP target_definition_sp(
3430b57cec5SDimitry Andric         interpreter->GetDynamicSettings(module_object_sp, &GetTarget(),
3440b57cec5SDimitry Andric                                         "gdb-server-target-definition", error));
3450b57cec5SDimitry Andric 
3460b57cec5SDimitry Andric     if (target_definition_sp) {
3470b57cec5SDimitry Andric       StructuredData::ObjectSP target_object(
3480b57cec5SDimitry Andric           target_definition_sp->GetValueForKey("host-info"));
3490b57cec5SDimitry Andric       if (target_object) {
3500b57cec5SDimitry Andric         if (auto host_info_dict = target_object->GetAsDictionary()) {
3510b57cec5SDimitry Andric           StructuredData::ObjectSP triple_value =
3520b57cec5SDimitry Andric               host_info_dict->GetValueForKey("triple");
3530b57cec5SDimitry Andric           if (auto triple_string_value = triple_value->GetAsString()) {
3545ffd83dbSDimitry Andric             std::string triple_string =
3555ffd83dbSDimitry Andric                 std::string(triple_string_value->GetValue());
3560b57cec5SDimitry Andric             ArchSpec host_arch(triple_string.c_str());
3570b57cec5SDimitry Andric             if (!host_arch.IsCompatibleMatch(GetTarget().GetArchitecture())) {
3580b57cec5SDimitry Andric               GetTarget().SetArchitecture(host_arch);
3590b57cec5SDimitry Andric             }
3600b57cec5SDimitry Andric           }
3610b57cec5SDimitry Andric         }
3620b57cec5SDimitry Andric       }
3630b57cec5SDimitry Andric       m_breakpoint_pc_offset = 0;
3640b57cec5SDimitry Andric       StructuredData::ObjectSP breakpoint_pc_offset_value =
3650b57cec5SDimitry Andric           target_definition_sp->GetValueForKey("breakpoint-pc-offset");
3660b57cec5SDimitry Andric       if (breakpoint_pc_offset_value) {
3670b57cec5SDimitry Andric         if (auto breakpoint_pc_int_value =
3680b57cec5SDimitry Andric                 breakpoint_pc_offset_value->GetAsInteger())
3690b57cec5SDimitry Andric           m_breakpoint_pc_offset = breakpoint_pc_int_value->GetValue();
3700b57cec5SDimitry Andric       }
3710b57cec5SDimitry Andric 
3720b57cec5SDimitry Andric       if (m_register_info.SetRegisterInfo(*target_definition_sp,
3730b57cec5SDimitry Andric                                           GetTarget().GetArchitecture()) > 0) {
3740b57cec5SDimitry Andric         return true;
3750b57cec5SDimitry Andric       }
3760b57cec5SDimitry Andric     }
3770b57cec5SDimitry Andric   }
3780b57cec5SDimitry Andric   return false;
3790b57cec5SDimitry Andric }
3800b57cec5SDimitry Andric 
3810b57cec5SDimitry Andric static size_t SplitCommaSeparatedRegisterNumberString(
3820b57cec5SDimitry Andric     const llvm::StringRef &comma_separated_regiter_numbers,
3830b57cec5SDimitry Andric     std::vector<uint32_t> &regnums, int base) {
3840b57cec5SDimitry Andric   regnums.clear();
3850b57cec5SDimitry Andric   std::pair<llvm::StringRef, llvm::StringRef> value_pair;
3860b57cec5SDimitry Andric   value_pair.second = comma_separated_regiter_numbers;
3870b57cec5SDimitry Andric   do {
3880b57cec5SDimitry Andric     value_pair = value_pair.second.split(',');
3890b57cec5SDimitry Andric     if (!value_pair.first.empty()) {
3900b57cec5SDimitry Andric       uint32_t reg = StringConvert::ToUInt32(value_pair.first.str().c_str(),
3910b57cec5SDimitry Andric                                              LLDB_INVALID_REGNUM, base);
3920b57cec5SDimitry Andric       if (reg != LLDB_INVALID_REGNUM)
3930b57cec5SDimitry Andric         regnums.push_back(reg);
3940b57cec5SDimitry Andric     }
3950b57cec5SDimitry Andric   } while (!value_pair.second.empty());
3960b57cec5SDimitry Andric   return regnums.size();
3970b57cec5SDimitry Andric }
3980b57cec5SDimitry Andric 
3990b57cec5SDimitry Andric void ProcessGDBRemote::BuildDynamicRegisterInfo(bool force) {
4000b57cec5SDimitry Andric   if (!force && m_register_info.GetNumRegisters() > 0)
4010b57cec5SDimitry Andric     return;
4020b57cec5SDimitry Andric 
4030b57cec5SDimitry Andric   m_register_info.Clear();
4040b57cec5SDimitry Andric 
4050b57cec5SDimitry Andric   // Check if qHostInfo specified a specific packet timeout for this
4060b57cec5SDimitry Andric   // connection. If so then lets update our setting so the user knows what the
4070b57cec5SDimitry Andric   // timeout is and can see it.
4080b57cec5SDimitry Andric   const auto host_packet_timeout = m_gdb_comm.GetHostDefaultPacketTimeout();
4090b57cec5SDimitry Andric   if (host_packet_timeout > std::chrono::seconds(0)) {
4100b57cec5SDimitry Andric     GetGlobalPluginProperties()->SetPacketTimeout(host_packet_timeout.count());
4110b57cec5SDimitry Andric   }
4120b57cec5SDimitry Andric 
4130b57cec5SDimitry Andric   // Register info search order:
4140b57cec5SDimitry Andric   //     1 - Use the target definition python file if one is specified.
4150b57cec5SDimitry Andric   //     2 - If the target definition doesn't have any of the info from the
4160b57cec5SDimitry Andric   //     target.xml (registers) then proceed to read the target.xml.
4170b57cec5SDimitry Andric   //     3 - Fall back on the qRegisterInfo packets.
4180b57cec5SDimitry Andric 
4190b57cec5SDimitry Andric   FileSpec target_definition_fspec =
4200b57cec5SDimitry Andric       GetGlobalPluginProperties()->GetTargetDefinitionFile();
4210b57cec5SDimitry Andric   if (!FileSystem::Instance().Exists(target_definition_fspec)) {
4220b57cec5SDimitry Andric     // If the filename doesn't exist, it may be a ~ not having been expanded -
4230b57cec5SDimitry Andric     // try to resolve it.
4240b57cec5SDimitry Andric     FileSystem::Instance().Resolve(target_definition_fspec);
4250b57cec5SDimitry Andric   }
4260b57cec5SDimitry Andric   if (target_definition_fspec) {
4270b57cec5SDimitry Andric     // See if we can get register definitions from a python file
4280b57cec5SDimitry Andric     if (ParsePythonTargetDefinition(target_definition_fspec)) {
4290b57cec5SDimitry Andric       return;
4300b57cec5SDimitry Andric     } else {
4310b57cec5SDimitry Andric       StreamSP stream_sp = GetTarget().GetDebugger().GetAsyncOutputStream();
4320b57cec5SDimitry Andric       stream_sp->Printf("ERROR: target description file %s failed to parse.\n",
4330b57cec5SDimitry Andric                         target_definition_fspec.GetPath().c_str());
4340b57cec5SDimitry Andric     }
4350b57cec5SDimitry Andric   }
4360b57cec5SDimitry Andric 
4370b57cec5SDimitry Andric   const ArchSpec &target_arch = GetTarget().GetArchitecture();
4380b57cec5SDimitry Andric   const ArchSpec &remote_host_arch = m_gdb_comm.GetHostArchitecture();
4390b57cec5SDimitry Andric   const ArchSpec &remote_process_arch = m_gdb_comm.GetProcessArchitecture();
4400b57cec5SDimitry Andric 
4410b57cec5SDimitry Andric   // Use the process' architecture instead of the host arch, if available
4420b57cec5SDimitry Andric   ArchSpec arch_to_use;
4430b57cec5SDimitry Andric   if (remote_process_arch.IsValid())
4440b57cec5SDimitry Andric     arch_to_use = remote_process_arch;
4450b57cec5SDimitry Andric   else
4460b57cec5SDimitry Andric     arch_to_use = remote_host_arch;
4470b57cec5SDimitry Andric 
4480b57cec5SDimitry Andric   if (!arch_to_use.IsValid())
4490b57cec5SDimitry Andric     arch_to_use = target_arch;
4500b57cec5SDimitry Andric 
4510b57cec5SDimitry Andric   if (GetGDBServerRegisterInfo(arch_to_use))
4520b57cec5SDimitry Andric     return;
4530b57cec5SDimitry Andric 
4540b57cec5SDimitry Andric   char packet[128];
4550b57cec5SDimitry Andric   uint32_t reg_offset = 0;
4560b57cec5SDimitry Andric   uint32_t reg_num = 0;
4570b57cec5SDimitry Andric   for (StringExtractorGDBRemote::ResponseType response_type =
4580b57cec5SDimitry Andric            StringExtractorGDBRemote::eResponse;
4590b57cec5SDimitry Andric        response_type == StringExtractorGDBRemote::eResponse; ++reg_num) {
4600b57cec5SDimitry Andric     const int packet_len =
4610b57cec5SDimitry Andric         ::snprintf(packet, sizeof(packet), "qRegisterInfo%x", reg_num);
4620b57cec5SDimitry Andric     assert(packet_len < (int)sizeof(packet));
4630b57cec5SDimitry Andric     UNUSED_IF_ASSERT_DISABLED(packet_len);
4640b57cec5SDimitry Andric     StringExtractorGDBRemote response;
4650b57cec5SDimitry Andric     if (m_gdb_comm.SendPacketAndWaitForResponse(packet, response, false) ==
4660b57cec5SDimitry Andric         GDBRemoteCommunication::PacketResult::Success) {
4670b57cec5SDimitry Andric       response_type = response.GetResponseType();
4680b57cec5SDimitry Andric       if (response_type == StringExtractorGDBRemote::eResponse) {
4690b57cec5SDimitry Andric         llvm::StringRef name;
4700b57cec5SDimitry Andric         llvm::StringRef value;
4710b57cec5SDimitry Andric         ConstString reg_name;
4720b57cec5SDimitry Andric         ConstString alt_name;
4730b57cec5SDimitry Andric         ConstString set_name;
4740b57cec5SDimitry Andric         std::vector<uint32_t> value_regs;
4750b57cec5SDimitry Andric         std::vector<uint32_t> invalidate_regs;
4760b57cec5SDimitry Andric         std::vector<uint8_t> dwarf_opcode_bytes;
4770b57cec5SDimitry Andric         RegisterInfo reg_info = {
4780b57cec5SDimitry Andric             nullptr,       // Name
4790b57cec5SDimitry Andric             nullptr,       // Alt name
4800b57cec5SDimitry Andric             0,             // byte size
4810b57cec5SDimitry Andric             reg_offset,    // offset
4820b57cec5SDimitry Andric             eEncodingUint, // encoding
4830b57cec5SDimitry Andric             eFormatHex,    // format
4840b57cec5SDimitry Andric             {
4850b57cec5SDimitry Andric                 LLDB_INVALID_REGNUM, // eh_frame reg num
4860b57cec5SDimitry Andric                 LLDB_INVALID_REGNUM, // DWARF reg num
4870b57cec5SDimitry Andric                 LLDB_INVALID_REGNUM, // generic reg num
4880b57cec5SDimitry Andric                 reg_num,             // process plugin reg num
4890b57cec5SDimitry Andric                 reg_num              // native register number
4900b57cec5SDimitry Andric             },
4910b57cec5SDimitry Andric             nullptr,
4920b57cec5SDimitry Andric             nullptr,
4930b57cec5SDimitry Andric             nullptr, // Dwarf expression opcode bytes pointer
4940b57cec5SDimitry Andric             0        // Dwarf expression opcode bytes length
4950b57cec5SDimitry Andric         };
4960b57cec5SDimitry Andric 
4970b57cec5SDimitry Andric         while (response.GetNameColonValue(name, value)) {
4980b57cec5SDimitry Andric           if (name.equals("name")) {
4990b57cec5SDimitry Andric             reg_name.SetString(value);
5000b57cec5SDimitry Andric           } else if (name.equals("alt-name")) {
5010b57cec5SDimitry Andric             alt_name.SetString(value);
5020b57cec5SDimitry Andric           } else if (name.equals("bitsize")) {
5030b57cec5SDimitry Andric             value.getAsInteger(0, reg_info.byte_size);
5040b57cec5SDimitry Andric             reg_info.byte_size /= CHAR_BIT;
5050b57cec5SDimitry Andric           } else if (name.equals("offset")) {
5060b57cec5SDimitry Andric             if (value.getAsInteger(0, reg_offset))
5070b57cec5SDimitry Andric               reg_offset = UINT32_MAX;
5080b57cec5SDimitry Andric           } else if (name.equals("encoding")) {
5090b57cec5SDimitry Andric             const Encoding encoding = Args::StringToEncoding(value);
5100b57cec5SDimitry Andric             if (encoding != eEncodingInvalid)
5110b57cec5SDimitry Andric               reg_info.encoding = encoding;
5120b57cec5SDimitry Andric           } else if (name.equals("format")) {
5130b57cec5SDimitry Andric             Format format = eFormatInvalid;
5140b57cec5SDimitry Andric             if (OptionArgParser::ToFormat(value.str().c_str(), format, nullptr)
5150b57cec5SDimitry Andric                     .Success())
5160b57cec5SDimitry Andric               reg_info.format = format;
5170b57cec5SDimitry Andric             else {
5180b57cec5SDimitry Andric               reg_info.format =
5190b57cec5SDimitry Andric                   llvm::StringSwitch<Format>(value)
5200b57cec5SDimitry Andric                       .Case("binary", eFormatBinary)
5210b57cec5SDimitry Andric                       .Case("decimal", eFormatDecimal)
5220b57cec5SDimitry Andric                       .Case("hex", eFormatHex)
5230b57cec5SDimitry Andric                       .Case("float", eFormatFloat)
5240b57cec5SDimitry Andric                       .Case("vector-sint8", eFormatVectorOfSInt8)
5250b57cec5SDimitry Andric                       .Case("vector-uint8", eFormatVectorOfUInt8)
5260b57cec5SDimitry Andric                       .Case("vector-sint16", eFormatVectorOfSInt16)
5270b57cec5SDimitry Andric                       .Case("vector-uint16", eFormatVectorOfUInt16)
5280b57cec5SDimitry Andric                       .Case("vector-sint32", eFormatVectorOfSInt32)
5290b57cec5SDimitry Andric                       .Case("vector-uint32", eFormatVectorOfUInt32)
5300b57cec5SDimitry Andric                       .Case("vector-float32", eFormatVectorOfFloat32)
5310b57cec5SDimitry Andric                       .Case("vector-uint64", eFormatVectorOfUInt64)
5320b57cec5SDimitry Andric                       .Case("vector-uint128", eFormatVectorOfUInt128)
5330b57cec5SDimitry Andric                       .Default(eFormatInvalid);
5340b57cec5SDimitry Andric             }
5350b57cec5SDimitry Andric           } else if (name.equals("set")) {
5360b57cec5SDimitry Andric             set_name.SetString(value);
5370b57cec5SDimitry Andric           } else if (name.equals("gcc") || name.equals("ehframe")) {
5380b57cec5SDimitry Andric             if (value.getAsInteger(0, reg_info.kinds[eRegisterKindEHFrame]))
5390b57cec5SDimitry Andric               reg_info.kinds[eRegisterKindEHFrame] = LLDB_INVALID_REGNUM;
5400b57cec5SDimitry Andric           } else if (name.equals("dwarf")) {
5410b57cec5SDimitry Andric             if (value.getAsInteger(0, reg_info.kinds[eRegisterKindDWARF]))
5420b57cec5SDimitry Andric               reg_info.kinds[eRegisterKindDWARF] = LLDB_INVALID_REGNUM;
5430b57cec5SDimitry Andric           } else if (name.equals("generic")) {
5440b57cec5SDimitry Andric             reg_info.kinds[eRegisterKindGeneric] =
5450b57cec5SDimitry Andric                 Args::StringToGenericRegister(value);
5460b57cec5SDimitry Andric           } else if (name.equals("container-regs")) {
5470b57cec5SDimitry Andric             SplitCommaSeparatedRegisterNumberString(value, value_regs, 16);
5480b57cec5SDimitry Andric           } else if (name.equals("invalidate-regs")) {
5490b57cec5SDimitry Andric             SplitCommaSeparatedRegisterNumberString(value, invalidate_regs, 16);
5500b57cec5SDimitry Andric           } else if (name.equals("dynamic_size_dwarf_expr_bytes")) {
5510b57cec5SDimitry Andric             size_t dwarf_opcode_len = value.size() / 2;
5520b57cec5SDimitry Andric             assert(dwarf_opcode_len > 0);
5530b57cec5SDimitry Andric 
5540b57cec5SDimitry Andric             dwarf_opcode_bytes.resize(dwarf_opcode_len);
5550b57cec5SDimitry Andric             reg_info.dynamic_size_dwarf_len = dwarf_opcode_len;
5560b57cec5SDimitry Andric 
5570b57cec5SDimitry Andric             StringExtractor opcode_extractor(value);
5580b57cec5SDimitry Andric             uint32_t ret_val =
5590b57cec5SDimitry Andric                 opcode_extractor.GetHexBytesAvail(dwarf_opcode_bytes);
5600b57cec5SDimitry Andric             assert(dwarf_opcode_len == ret_val);
5610b57cec5SDimitry Andric             UNUSED_IF_ASSERT_DISABLED(ret_val);
5620b57cec5SDimitry Andric             reg_info.dynamic_size_dwarf_expr_bytes = dwarf_opcode_bytes.data();
5630b57cec5SDimitry Andric           }
5640b57cec5SDimitry Andric         }
5650b57cec5SDimitry Andric 
5660b57cec5SDimitry Andric         reg_info.byte_offset = reg_offset;
5670b57cec5SDimitry Andric         assert(reg_info.byte_size != 0);
5680b57cec5SDimitry Andric         reg_offset += reg_info.byte_size;
5690b57cec5SDimitry Andric         if (!value_regs.empty()) {
5700b57cec5SDimitry Andric           value_regs.push_back(LLDB_INVALID_REGNUM);
5710b57cec5SDimitry Andric           reg_info.value_regs = value_regs.data();
5720b57cec5SDimitry Andric         }
5730b57cec5SDimitry Andric         if (!invalidate_regs.empty()) {
5740b57cec5SDimitry Andric           invalidate_regs.push_back(LLDB_INVALID_REGNUM);
5750b57cec5SDimitry Andric           reg_info.invalidate_regs = invalidate_regs.data();
5760b57cec5SDimitry Andric         }
5770b57cec5SDimitry Andric 
578480093f4SDimitry Andric         reg_info.name = reg_name.AsCString();
5790b57cec5SDimitry Andric         // We have to make a temporary ABI here, and not use the GetABI because
5800b57cec5SDimitry Andric         // this code gets called in DidAttach, when the target architecture
5810b57cec5SDimitry Andric         // (and consequently the ABI we'll get from the process) may be wrong.
582480093f4SDimitry Andric         if (ABISP abi_sp = ABI::FindPlugin(shared_from_this(), arch_to_use))
583480093f4SDimitry Andric           abi_sp->AugmentRegisterInfo(reg_info);
5840b57cec5SDimitry Andric 
5850b57cec5SDimitry Andric         m_register_info.AddRegister(reg_info, reg_name, alt_name, set_name);
5860b57cec5SDimitry Andric       } else {
5870b57cec5SDimitry Andric         break; // ensure exit before reg_num is incremented
5880b57cec5SDimitry Andric       }
5890b57cec5SDimitry Andric     } else {
5900b57cec5SDimitry Andric       break;
5910b57cec5SDimitry Andric     }
5920b57cec5SDimitry Andric   }
5930b57cec5SDimitry Andric 
5940b57cec5SDimitry Andric   if (m_register_info.GetNumRegisters() > 0) {
5950b57cec5SDimitry Andric     m_register_info.Finalize(GetTarget().GetArchitecture());
5960b57cec5SDimitry Andric     return;
5970b57cec5SDimitry Andric   }
5980b57cec5SDimitry Andric 
5990b57cec5SDimitry Andric   // We didn't get anything if the accumulated reg_num is zero.  See if we are
6000b57cec5SDimitry Andric   // debugging ARM and fill with a hard coded register set until we can get an
6010b57cec5SDimitry Andric   // updated debugserver down on the devices. On the other hand, if the
6020b57cec5SDimitry Andric   // accumulated reg_num is positive, see if we can add composite registers to
6030b57cec5SDimitry Andric   // the existing primordial ones.
6040b57cec5SDimitry Andric   bool from_scratch = (m_register_info.GetNumRegisters() == 0);
6050b57cec5SDimitry Andric 
6060b57cec5SDimitry Andric   if (!target_arch.IsValid()) {
6070b57cec5SDimitry Andric     if (arch_to_use.IsValid() &&
6080b57cec5SDimitry Andric         (arch_to_use.GetMachine() == llvm::Triple::arm ||
6090b57cec5SDimitry Andric          arch_to_use.GetMachine() == llvm::Triple::thumb) &&
6100b57cec5SDimitry Andric         arch_to_use.GetTriple().getVendor() == llvm::Triple::Apple)
6110b57cec5SDimitry Andric       m_register_info.HardcodeARMRegisters(from_scratch);
6120b57cec5SDimitry Andric   } else if (target_arch.GetMachine() == llvm::Triple::arm ||
6130b57cec5SDimitry Andric              target_arch.GetMachine() == llvm::Triple::thumb) {
6140b57cec5SDimitry Andric     m_register_info.HardcodeARMRegisters(from_scratch);
6150b57cec5SDimitry Andric   }
6160b57cec5SDimitry Andric 
6170b57cec5SDimitry Andric   // At this point, we can finalize our register info.
6180b57cec5SDimitry Andric   m_register_info.Finalize(GetTarget().GetArchitecture());
6190b57cec5SDimitry Andric }
6200b57cec5SDimitry Andric 
6210b57cec5SDimitry Andric Status ProcessGDBRemote::WillLaunch(lldb_private::Module *module) {
6220b57cec5SDimitry Andric   return WillLaunchOrAttach();
6230b57cec5SDimitry Andric }
6240b57cec5SDimitry Andric 
6250b57cec5SDimitry Andric Status ProcessGDBRemote::WillAttachToProcessWithID(lldb::pid_t pid) {
6260b57cec5SDimitry Andric   return WillLaunchOrAttach();
6270b57cec5SDimitry Andric }
6280b57cec5SDimitry Andric 
6290b57cec5SDimitry Andric Status ProcessGDBRemote::WillAttachToProcessWithName(const char *process_name,
6300b57cec5SDimitry Andric                                                      bool wait_for_launch) {
6310b57cec5SDimitry Andric   return WillLaunchOrAttach();
6320b57cec5SDimitry Andric }
6330b57cec5SDimitry Andric 
6345ffd83dbSDimitry Andric Status ProcessGDBRemote::DoConnectRemote(llvm::StringRef remote_url) {
6350b57cec5SDimitry Andric   Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
6360b57cec5SDimitry Andric   Status error(WillLaunchOrAttach());
6370b57cec5SDimitry Andric 
6380b57cec5SDimitry Andric   if (error.Fail())
6390b57cec5SDimitry Andric     return error;
6400b57cec5SDimitry Andric 
6415ffd83dbSDimitry Andric   if (repro::Reproducer::Instance().IsReplaying())
6425ffd83dbSDimitry Andric     error = ConnectToReplayServer();
6435ffd83dbSDimitry Andric   else
6440b57cec5SDimitry Andric     error = ConnectToDebugserver(remote_url);
6450b57cec5SDimitry Andric 
6460b57cec5SDimitry Andric   if (error.Fail())
6470b57cec5SDimitry Andric     return error;
6480b57cec5SDimitry Andric   StartAsyncThread();
6490b57cec5SDimitry Andric 
6500b57cec5SDimitry Andric   lldb::pid_t pid = m_gdb_comm.GetCurrentProcessID();
6510b57cec5SDimitry Andric   if (pid == LLDB_INVALID_PROCESS_ID) {
6520b57cec5SDimitry Andric     // We don't have a valid process ID, so note that we are connected and
6530b57cec5SDimitry Andric     // could now request to launch or attach, or get remote process listings...
6540b57cec5SDimitry Andric     SetPrivateState(eStateConnected);
6550b57cec5SDimitry Andric   } else {
6560b57cec5SDimitry Andric     // We have a valid process
6570b57cec5SDimitry Andric     SetID(pid);
6580b57cec5SDimitry Andric     GetThreadList();
6590b57cec5SDimitry Andric     StringExtractorGDBRemote response;
6600b57cec5SDimitry Andric     if (m_gdb_comm.GetStopReply(response)) {
6610b57cec5SDimitry Andric       SetLastStopPacket(response);
6620b57cec5SDimitry Andric 
6630b57cec5SDimitry Andric       // '?' Packets must be handled differently in non-stop mode
6640b57cec5SDimitry Andric       if (GetTarget().GetNonStopModeEnabled())
6650b57cec5SDimitry Andric         HandleStopReplySequence();
6660b57cec5SDimitry Andric 
6670b57cec5SDimitry Andric       Target &target = GetTarget();
6680b57cec5SDimitry Andric       if (!target.GetArchitecture().IsValid()) {
6690b57cec5SDimitry Andric         if (m_gdb_comm.GetProcessArchitecture().IsValid()) {
6700b57cec5SDimitry Andric           target.SetArchitecture(m_gdb_comm.GetProcessArchitecture());
6710b57cec5SDimitry Andric         } else {
6720b57cec5SDimitry Andric           if (m_gdb_comm.GetHostArchitecture().IsValid()) {
6730b57cec5SDimitry Andric             target.SetArchitecture(m_gdb_comm.GetHostArchitecture());
6740b57cec5SDimitry Andric           }
6750b57cec5SDimitry Andric         }
6760b57cec5SDimitry Andric       }
6770b57cec5SDimitry Andric 
6780b57cec5SDimitry Andric       const StateType state = SetThreadStopInfo(response);
6790b57cec5SDimitry Andric       if (state != eStateInvalid) {
6800b57cec5SDimitry Andric         SetPrivateState(state);
6810b57cec5SDimitry Andric       } else
6820b57cec5SDimitry Andric         error.SetErrorStringWithFormat(
6830b57cec5SDimitry Andric             "Process %" PRIu64 " was reported after connecting to "
6840b57cec5SDimitry Andric             "'%s', but state was not stopped: %s",
6850b57cec5SDimitry Andric             pid, remote_url.str().c_str(), StateAsCString(state));
6860b57cec5SDimitry Andric     } else
6870b57cec5SDimitry Andric       error.SetErrorStringWithFormat("Process %" PRIu64
6880b57cec5SDimitry Andric                                      " was reported after connecting to '%s', "
6890b57cec5SDimitry Andric                                      "but no stop reply packet was received",
6900b57cec5SDimitry Andric                                      pid, remote_url.str().c_str());
6910b57cec5SDimitry Andric   }
6920b57cec5SDimitry Andric 
6939dba64beSDimitry Andric   LLDB_LOGF(log,
6949dba64beSDimitry Andric             "ProcessGDBRemote::%s pid %" PRIu64
6950b57cec5SDimitry Andric             ": normalizing target architecture initial triple: %s "
6960b57cec5SDimitry Andric             "(GetTarget().GetArchitecture().IsValid() %s, "
6970b57cec5SDimitry Andric             "m_gdb_comm.GetHostArchitecture().IsValid(): %s)",
6980b57cec5SDimitry Andric             __FUNCTION__, GetID(),
6990b57cec5SDimitry Andric             GetTarget().GetArchitecture().GetTriple().getTriple().c_str(),
7000b57cec5SDimitry Andric             GetTarget().GetArchitecture().IsValid() ? "true" : "false",
7010b57cec5SDimitry Andric             m_gdb_comm.GetHostArchitecture().IsValid() ? "true" : "false");
7020b57cec5SDimitry Andric 
7030b57cec5SDimitry Andric   if (error.Success() && !GetTarget().GetArchitecture().IsValid() &&
7040b57cec5SDimitry Andric       m_gdb_comm.GetHostArchitecture().IsValid()) {
7050b57cec5SDimitry Andric     // Prefer the *process'* architecture over that of the *host*, if
7060b57cec5SDimitry Andric     // available.
7070b57cec5SDimitry Andric     if (m_gdb_comm.GetProcessArchitecture().IsValid())
7080b57cec5SDimitry Andric       GetTarget().SetArchitecture(m_gdb_comm.GetProcessArchitecture());
7090b57cec5SDimitry Andric     else
7100b57cec5SDimitry Andric       GetTarget().SetArchitecture(m_gdb_comm.GetHostArchitecture());
7110b57cec5SDimitry Andric   }
7120b57cec5SDimitry Andric 
7139dba64beSDimitry Andric   LLDB_LOGF(log,
7149dba64beSDimitry Andric             "ProcessGDBRemote::%s pid %" PRIu64
7150b57cec5SDimitry Andric             ": normalized target architecture triple: %s",
7160b57cec5SDimitry Andric             __FUNCTION__, GetID(),
7170b57cec5SDimitry Andric             GetTarget().GetArchitecture().GetTriple().getTriple().c_str());
7180b57cec5SDimitry Andric 
7190b57cec5SDimitry Andric   if (error.Success()) {
7200b57cec5SDimitry Andric     PlatformSP platform_sp = GetTarget().GetPlatform();
7210b57cec5SDimitry Andric     if (platform_sp && platform_sp->IsConnected())
7220b57cec5SDimitry Andric       SetUnixSignals(platform_sp->GetUnixSignals());
7230b57cec5SDimitry Andric     else
7240b57cec5SDimitry Andric       SetUnixSignals(UnixSignals::Create(GetTarget().GetArchitecture()));
7250b57cec5SDimitry Andric   }
7260b57cec5SDimitry Andric 
7270b57cec5SDimitry Andric   return error;
7280b57cec5SDimitry Andric }
7290b57cec5SDimitry Andric 
7300b57cec5SDimitry Andric Status ProcessGDBRemote::WillLaunchOrAttach() {
7310b57cec5SDimitry Andric   Status error;
7320b57cec5SDimitry Andric   m_stdio_communication.Clear();
7330b57cec5SDimitry Andric   return error;
7340b57cec5SDimitry Andric }
7350b57cec5SDimitry Andric 
7360b57cec5SDimitry Andric // Process Control
7370b57cec5SDimitry Andric Status ProcessGDBRemote::DoLaunch(lldb_private::Module *exe_module,
7380b57cec5SDimitry Andric                                   ProcessLaunchInfo &launch_info) {
7390b57cec5SDimitry Andric   Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
7400b57cec5SDimitry Andric   Status error;
7410b57cec5SDimitry Andric 
7429dba64beSDimitry Andric   LLDB_LOGF(log, "ProcessGDBRemote::%s() entered", __FUNCTION__);
7430b57cec5SDimitry Andric 
7440b57cec5SDimitry Andric   uint32_t launch_flags = launch_info.GetFlags().Get();
7450b57cec5SDimitry Andric   FileSpec stdin_file_spec{};
7460b57cec5SDimitry Andric   FileSpec stdout_file_spec{};
7470b57cec5SDimitry Andric   FileSpec stderr_file_spec{};
7480b57cec5SDimitry Andric   FileSpec working_dir = launch_info.GetWorkingDirectory();
7490b57cec5SDimitry Andric 
7500b57cec5SDimitry Andric   const FileAction *file_action;
7510b57cec5SDimitry Andric   file_action = launch_info.GetFileActionForFD(STDIN_FILENO);
7520b57cec5SDimitry Andric   if (file_action) {
7530b57cec5SDimitry Andric     if (file_action->GetAction() == FileAction::eFileActionOpen)
7540b57cec5SDimitry Andric       stdin_file_spec = file_action->GetFileSpec();
7550b57cec5SDimitry Andric   }
7560b57cec5SDimitry Andric   file_action = launch_info.GetFileActionForFD(STDOUT_FILENO);
7570b57cec5SDimitry Andric   if (file_action) {
7580b57cec5SDimitry Andric     if (file_action->GetAction() == FileAction::eFileActionOpen)
7590b57cec5SDimitry Andric       stdout_file_spec = file_action->GetFileSpec();
7600b57cec5SDimitry Andric   }
7610b57cec5SDimitry Andric   file_action = launch_info.GetFileActionForFD(STDERR_FILENO);
7620b57cec5SDimitry Andric   if (file_action) {
7630b57cec5SDimitry Andric     if (file_action->GetAction() == FileAction::eFileActionOpen)
7640b57cec5SDimitry Andric       stderr_file_spec = file_action->GetFileSpec();
7650b57cec5SDimitry Andric   }
7660b57cec5SDimitry Andric 
7670b57cec5SDimitry Andric   if (log) {
7680b57cec5SDimitry Andric     if (stdin_file_spec || stdout_file_spec || stderr_file_spec)
7699dba64beSDimitry Andric       LLDB_LOGF(log,
7709dba64beSDimitry Andric                 "ProcessGDBRemote::%s provided with STDIO paths via "
7710b57cec5SDimitry Andric                 "launch_info: stdin=%s, stdout=%s, stderr=%s",
7720b57cec5SDimitry Andric                 __FUNCTION__,
7730b57cec5SDimitry Andric                 stdin_file_spec ? stdin_file_spec.GetCString() : "<null>",
7740b57cec5SDimitry Andric                 stdout_file_spec ? stdout_file_spec.GetCString() : "<null>",
7750b57cec5SDimitry Andric                 stderr_file_spec ? stderr_file_spec.GetCString() : "<null>");
7760b57cec5SDimitry Andric     else
7779dba64beSDimitry Andric       LLDB_LOGF(log,
7789dba64beSDimitry Andric                 "ProcessGDBRemote::%s no STDIO paths given via launch_info",
7790b57cec5SDimitry Andric                 __FUNCTION__);
7800b57cec5SDimitry Andric   }
7810b57cec5SDimitry Andric 
7820b57cec5SDimitry Andric   const bool disable_stdio = (launch_flags & eLaunchFlagDisableSTDIO) != 0;
7830b57cec5SDimitry Andric   if (stdin_file_spec || disable_stdio) {
7840b57cec5SDimitry Andric     // the inferior will be reading stdin from the specified file or stdio is
7850b57cec5SDimitry Andric     // completely disabled
7860b57cec5SDimitry Andric     m_stdin_forward = false;
7870b57cec5SDimitry Andric   } else {
7880b57cec5SDimitry Andric     m_stdin_forward = true;
7890b57cec5SDimitry Andric   }
7900b57cec5SDimitry Andric 
7910b57cec5SDimitry Andric   //  ::LogSetBitMask (GDBR_LOG_DEFAULT);
7920b57cec5SDimitry Andric   //  ::LogSetOptions (LLDB_LOG_OPTION_THREADSAFE |
7930b57cec5SDimitry Andric   //  LLDB_LOG_OPTION_PREPEND_TIMESTAMP |
7940b57cec5SDimitry Andric   //  LLDB_LOG_OPTION_PREPEND_PROC_AND_THREAD);
7950b57cec5SDimitry Andric   //  ::LogSetLogFile ("/dev/stdout");
7960b57cec5SDimitry Andric 
7970b57cec5SDimitry Andric   ObjectFile *object_file = exe_module->GetObjectFile();
7980b57cec5SDimitry Andric   if (object_file) {
7990b57cec5SDimitry Andric     error = EstablishConnectionIfNeeded(launch_info);
8000b57cec5SDimitry Andric     if (error.Success()) {
8010b57cec5SDimitry Andric       PseudoTerminal pty;
8020b57cec5SDimitry Andric       const bool disable_stdio = (launch_flags & eLaunchFlagDisableSTDIO) != 0;
8030b57cec5SDimitry Andric 
8040b57cec5SDimitry Andric       PlatformSP platform_sp(GetTarget().GetPlatform());
8050b57cec5SDimitry Andric       if (disable_stdio) {
8060b57cec5SDimitry Andric         // set to /dev/null unless redirected to a file above
8070b57cec5SDimitry Andric         if (!stdin_file_spec)
8080b57cec5SDimitry Andric           stdin_file_spec.SetFile(FileSystem::DEV_NULL,
8090b57cec5SDimitry Andric                                   FileSpec::Style::native);
8100b57cec5SDimitry Andric         if (!stdout_file_spec)
8110b57cec5SDimitry Andric           stdout_file_spec.SetFile(FileSystem::DEV_NULL,
8120b57cec5SDimitry Andric                                    FileSpec::Style::native);
8130b57cec5SDimitry Andric         if (!stderr_file_spec)
8140b57cec5SDimitry Andric           stderr_file_spec.SetFile(FileSystem::DEV_NULL,
8150b57cec5SDimitry Andric                                    FileSpec::Style::native);
8160b57cec5SDimitry Andric       } else if (platform_sp && platform_sp->IsHost()) {
8170b57cec5SDimitry Andric         // If the debugserver is local and we aren't disabling STDIO, lets use
8180b57cec5SDimitry Andric         // a pseudo terminal to instead of relying on the 'O' packets for stdio
8190b57cec5SDimitry Andric         // since 'O' packets can really slow down debugging if the inferior
8200b57cec5SDimitry Andric         // does a lot of output.
8210b57cec5SDimitry Andric         if ((!stdin_file_spec || !stdout_file_spec || !stderr_file_spec) &&
8225ffd83dbSDimitry Andric             pty.OpenFirstAvailablePrimary(O_RDWR | O_NOCTTY, nullptr, 0)) {
8235ffd83dbSDimitry Andric           FileSpec secondary_name{pty.GetSecondaryName(nullptr, 0)};
8240b57cec5SDimitry Andric 
8250b57cec5SDimitry Andric           if (!stdin_file_spec)
8265ffd83dbSDimitry Andric             stdin_file_spec = secondary_name;
8270b57cec5SDimitry Andric 
8280b57cec5SDimitry Andric           if (!stdout_file_spec)
8295ffd83dbSDimitry Andric             stdout_file_spec = secondary_name;
8300b57cec5SDimitry Andric 
8310b57cec5SDimitry Andric           if (!stderr_file_spec)
8325ffd83dbSDimitry Andric             stderr_file_spec = secondary_name;
8330b57cec5SDimitry Andric         }
8349dba64beSDimitry Andric         LLDB_LOGF(
8359dba64beSDimitry Andric             log,
8360b57cec5SDimitry Andric             "ProcessGDBRemote::%s adjusted STDIO paths for local platform "
8375ffd83dbSDimitry Andric             "(IsHost() is true) using secondary: stdin=%s, stdout=%s, "
8385ffd83dbSDimitry Andric             "stderr=%s",
8390b57cec5SDimitry Andric             __FUNCTION__,
8400b57cec5SDimitry Andric             stdin_file_spec ? stdin_file_spec.GetCString() : "<null>",
8410b57cec5SDimitry Andric             stdout_file_spec ? stdout_file_spec.GetCString() : "<null>",
8420b57cec5SDimitry Andric             stderr_file_spec ? stderr_file_spec.GetCString() : "<null>");
8430b57cec5SDimitry Andric       }
8440b57cec5SDimitry Andric 
8459dba64beSDimitry Andric       LLDB_LOGF(log,
8469dba64beSDimitry Andric                 "ProcessGDBRemote::%s final STDIO paths after all "
8470b57cec5SDimitry Andric                 "adjustments: stdin=%s, stdout=%s, stderr=%s",
8480b57cec5SDimitry Andric                 __FUNCTION__,
8490b57cec5SDimitry Andric                 stdin_file_spec ? stdin_file_spec.GetCString() : "<null>",
8500b57cec5SDimitry Andric                 stdout_file_spec ? stdout_file_spec.GetCString() : "<null>",
8519dba64beSDimitry Andric                 stderr_file_spec ? stderr_file_spec.GetCString() : "<null>");
8520b57cec5SDimitry Andric 
8530b57cec5SDimitry Andric       if (stdin_file_spec)
8540b57cec5SDimitry Andric         m_gdb_comm.SetSTDIN(stdin_file_spec);
8550b57cec5SDimitry Andric       if (stdout_file_spec)
8560b57cec5SDimitry Andric         m_gdb_comm.SetSTDOUT(stdout_file_spec);
8570b57cec5SDimitry Andric       if (stderr_file_spec)
8580b57cec5SDimitry Andric         m_gdb_comm.SetSTDERR(stderr_file_spec);
8590b57cec5SDimitry Andric 
8600b57cec5SDimitry Andric       m_gdb_comm.SetDisableASLR(launch_flags & eLaunchFlagDisableASLR);
8610b57cec5SDimitry Andric       m_gdb_comm.SetDetachOnError(launch_flags & eLaunchFlagDetachOnError);
8620b57cec5SDimitry Andric 
8630b57cec5SDimitry Andric       m_gdb_comm.SendLaunchArchPacket(
8640b57cec5SDimitry Andric           GetTarget().GetArchitecture().GetArchitectureName());
8650b57cec5SDimitry Andric 
8660b57cec5SDimitry Andric       const char *launch_event_data = launch_info.GetLaunchEventData();
8670b57cec5SDimitry Andric       if (launch_event_data != nullptr && *launch_event_data != '\0')
8680b57cec5SDimitry Andric         m_gdb_comm.SendLaunchEventDataPacket(launch_event_data);
8690b57cec5SDimitry Andric 
8700b57cec5SDimitry Andric       if (working_dir) {
8710b57cec5SDimitry Andric         m_gdb_comm.SetWorkingDir(working_dir);
8720b57cec5SDimitry Andric       }
8730b57cec5SDimitry Andric 
8740b57cec5SDimitry Andric       // Send the environment and the program + arguments after we connect
8750b57cec5SDimitry Andric       m_gdb_comm.SendEnvironment(launch_info.GetEnvironment());
8760b57cec5SDimitry Andric 
8770b57cec5SDimitry Andric       {
8780b57cec5SDimitry Andric         // Scope for the scoped timeout object
8790b57cec5SDimitry Andric         GDBRemoteCommunication::ScopedTimeout timeout(m_gdb_comm,
8800b57cec5SDimitry Andric                                                       std::chrono::seconds(10));
8810b57cec5SDimitry Andric 
8820b57cec5SDimitry Andric         int arg_packet_err = m_gdb_comm.SendArgumentsPacket(launch_info);
8830b57cec5SDimitry Andric         if (arg_packet_err == 0) {
8840b57cec5SDimitry Andric           std::string error_str;
8850b57cec5SDimitry Andric           if (m_gdb_comm.GetLaunchSuccess(error_str)) {
8860b57cec5SDimitry Andric             SetID(m_gdb_comm.GetCurrentProcessID());
8870b57cec5SDimitry Andric           } else {
8880b57cec5SDimitry Andric             error.SetErrorString(error_str.c_str());
8890b57cec5SDimitry Andric           }
8900b57cec5SDimitry Andric         } else {
8910b57cec5SDimitry Andric           error.SetErrorStringWithFormat("'A' packet returned an error: %i",
8920b57cec5SDimitry Andric                                          arg_packet_err);
8930b57cec5SDimitry Andric         }
8940b57cec5SDimitry Andric       }
8950b57cec5SDimitry Andric 
8960b57cec5SDimitry Andric       if (GetID() == LLDB_INVALID_PROCESS_ID) {
8979dba64beSDimitry Andric         LLDB_LOGF(log, "failed to connect to debugserver: %s",
8980b57cec5SDimitry Andric                   error.AsCString());
8990b57cec5SDimitry Andric         KillDebugserverProcess();
9000b57cec5SDimitry Andric         return error;
9010b57cec5SDimitry Andric       }
9020b57cec5SDimitry Andric 
9030b57cec5SDimitry Andric       StringExtractorGDBRemote response;
9040b57cec5SDimitry Andric       if (m_gdb_comm.GetStopReply(response)) {
9050b57cec5SDimitry Andric         SetLastStopPacket(response);
9060b57cec5SDimitry Andric         // '?' Packets must be handled differently in non-stop mode
9070b57cec5SDimitry Andric         if (GetTarget().GetNonStopModeEnabled())
9080b57cec5SDimitry Andric           HandleStopReplySequence();
9090b57cec5SDimitry Andric 
9100b57cec5SDimitry Andric         const ArchSpec &process_arch = m_gdb_comm.GetProcessArchitecture();
9110b57cec5SDimitry Andric 
9120b57cec5SDimitry Andric         if (process_arch.IsValid()) {
9130b57cec5SDimitry Andric           GetTarget().MergeArchitecture(process_arch);
9140b57cec5SDimitry Andric         } else {
9150b57cec5SDimitry Andric           const ArchSpec &host_arch = m_gdb_comm.GetHostArchitecture();
9160b57cec5SDimitry Andric           if (host_arch.IsValid())
9170b57cec5SDimitry Andric             GetTarget().MergeArchitecture(host_arch);
9180b57cec5SDimitry Andric         }
9190b57cec5SDimitry Andric 
9200b57cec5SDimitry Andric         SetPrivateState(SetThreadStopInfo(response));
9210b57cec5SDimitry Andric 
9220b57cec5SDimitry Andric         if (!disable_stdio) {
9235ffd83dbSDimitry Andric           if (pty.GetPrimaryFileDescriptor() != PseudoTerminal::invalid_fd)
9245ffd83dbSDimitry Andric             SetSTDIOFileDescriptor(pty.ReleasePrimaryFileDescriptor());
9250b57cec5SDimitry Andric         }
9260b57cec5SDimitry Andric       }
9270b57cec5SDimitry Andric     } else {
9289dba64beSDimitry Andric       LLDB_LOGF(log, "failed to connect to debugserver: %s", error.AsCString());
9290b57cec5SDimitry Andric     }
9300b57cec5SDimitry Andric   } else {
9310b57cec5SDimitry Andric     // Set our user ID to an invalid process ID.
9320b57cec5SDimitry Andric     SetID(LLDB_INVALID_PROCESS_ID);
9330b57cec5SDimitry Andric     error.SetErrorStringWithFormat(
9340b57cec5SDimitry Andric         "failed to get object file from '%s' for arch %s",
9350b57cec5SDimitry Andric         exe_module->GetFileSpec().GetFilename().AsCString(),
9360b57cec5SDimitry Andric         exe_module->GetArchitecture().GetArchitectureName());
9370b57cec5SDimitry Andric   }
9380b57cec5SDimitry Andric   return error;
9390b57cec5SDimitry Andric }
9400b57cec5SDimitry Andric 
9410b57cec5SDimitry Andric Status ProcessGDBRemote::ConnectToDebugserver(llvm::StringRef connect_url) {
9420b57cec5SDimitry Andric   Status error;
9430b57cec5SDimitry Andric   // Only connect if we have a valid connect URL
9440b57cec5SDimitry Andric   Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
9450b57cec5SDimitry Andric 
9460b57cec5SDimitry Andric   if (!connect_url.empty()) {
9479dba64beSDimitry Andric     LLDB_LOGF(log, "ProcessGDBRemote::%s Connecting to %s", __FUNCTION__,
9480b57cec5SDimitry Andric               connect_url.str().c_str());
9490b57cec5SDimitry Andric     std::unique_ptr<ConnectionFileDescriptor> conn_up(
9500b57cec5SDimitry Andric         new ConnectionFileDescriptor());
9510b57cec5SDimitry Andric     if (conn_up) {
9520b57cec5SDimitry Andric       const uint32_t max_retry_count = 50;
9530b57cec5SDimitry Andric       uint32_t retry_count = 0;
9540b57cec5SDimitry Andric       while (!m_gdb_comm.IsConnected()) {
9550b57cec5SDimitry Andric         if (conn_up->Connect(connect_url, &error) == eConnectionStatusSuccess) {
9565ffd83dbSDimitry Andric           m_gdb_comm.SetConnection(std::move(conn_up));
9570b57cec5SDimitry Andric           break;
9580b57cec5SDimitry Andric         } else if (error.WasInterrupted()) {
9590b57cec5SDimitry Andric           // If we were interrupted, don't keep retrying.
9600b57cec5SDimitry Andric           break;
9610b57cec5SDimitry Andric         }
9620b57cec5SDimitry Andric 
9630b57cec5SDimitry Andric         retry_count++;
9640b57cec5SDimitry Andric 
9650b57cec5SDimitry Andric         if (retry_count >= max_retry_count)
9660b57cec5SDimitry Andric           break;
9670b57cec5SDimitry Andric 
9689dba64beSDimitry Andric         std::this_thread::sleep_for(std::chrono::milliseconds(100));
9690b57cec5SDimitry Andric       }
9700b57cec5SDimitry Andric     }
9710b57cec5SDimitry Andric   }
9720b57cec5SDimitry Andric 
9730b57cec5SDimitry Andric   if (!m_gdb_comm.IsConnected()) {
9740b57cec5SDimitry Andric     if (error.Success())
9750b57cec5SDimitry Andric       error.SetErrorString("not connected to remote gdb server");
9760b57cec5SDimitry Andric     return error;
9770b57cec5SDimitry Andric   }
9780b57cec5SDimitry Andric 
9790b57cec5SDimitry Andric   // Start the communications read thread so all incoming data can be parsed
9800b57cec5SDimitry Andric   // into packets and queued as they arrive.
9810b57cec5SDimitry Andric   if (GetTarget().GetNonStopModeEnabled())
9820b57cec5SDimitry Andric     m_gdb_comm.StartReadThread();
9830b57cec5SDimitry Andric 
9840b57cec5SDimitry Andric   // We always seem to be able to open a connection to a local port so we need
9850b57cec5SDimitry Andric   // to make sure we can then send data to it. If we can't then we aren't
9860b57cec5SDimitry Andric   // actually connected to anything, so try and do the handshake with the
9870b57cec5SDimitry Andric   // remote GDB server and make sure that goes alright.
9880b57cec5SDimitry Andric   if (!m_gdb_comm.HandshakeWithServer(&error)) {
9890b57cec5SDimitry Andric     m_gdb_comm.Disconnect();
9900b57cec5SDimitry Andric     if (error.Success())
9910b57cec5SDimitry Andric       error.SetErrorString("not connected to remote gdb server");
9920b57cec5SDimitry Andric     return error;
9930b57cec5SDimitry Andric   }
9940b57cec5SDimitry Andric 
9950b57cec5SDimitry Andric   // Send $QNonStop:1 packet on startup if required
9960b57cec5SDimitry Andric   if (GetTarget().GetNonStopModeEnabled())
9970b57cec5SDimitry Andric     GetTarget().SetNonStopModeEnabled(m_gdb_comm.SetNonStopMode(true));
9980b57cec5SDimitry Andric 
9990b57cec5SDimitry Andric   m_gdb_comm.GetEchoSupported();
10000b57cec5SDimitry Andric   m_gdb_comm.GetThreadSuffixSupported();
10010b57cec5SDimitry Andric   m_gdb_comm.GetListThreadsInStopReplySupported();
10020b57cec5SDimitry Andric   m_gdb_comm.GetHostInfo();
10030b57cec5SDimitry Andric   m_gdb_comm.GetVContSupported('c');
10040b57cec5SDimitry Andric   m_gdb_comm.GetVAttachOrWaitSupported();
10050b57cec5SDimitry Andric   m_gdb_comm.EnableErrorStringInPacket();
10060b57cec5SDimitry Andric 
10070b57cec5SDimitry Andric   // Ask the remote server for the default thread id
10080b57cec5SDimitry Andric   if (GetTarget().GetNonStopModeEnabled())
10090b57cec5SDimitry Andric     m_gdb_comm.GetDefaultThreadId(m_initial_tid);
10100b57cec5SDimitry Andric 
10110b57cec5SDimitry Andric   size_t num_cmds = GetExtraStartupCommands().GetArgumentCount();
10120b57cec5SDimitry Andric   for (size_t idx = 0; idx < num_cmds; idx++) {
10130b57cec5SDimitry Andric     StringExtractorGDBRemote response;
10140b57cec5SDimitry Andric     m_gdb_comm.SendPacketAndWaitForResponse(
10150b57cec5SDimitry Andric         GetExtraStartupCommands().GetArgumentAtIndex(idx), response, false);
10160b57cec5SDimitry Andric   }
10170b57cec5SDimitry Andric   return error;
10180b57cec5SDimitry Andric }
10190b57cec5SDimitry Andric 
10200b57cec5SDimitry Andric void ProcessGDBRemote::DidLaunchOrAttach(ArchSpec &process_arch) {
10210b57cec5SDimitry Andric   Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
10220b57cec5SDimitry Andric   BuildDynamicRegisterInfo(false);
10230b57cec5SDimitry Andric 
10245ffd83dbSDimitry Andric   // See if the GDB server supports qHostInfo or qProcessInfo packets. Prefer
10255ffd83dbSDimitry Andric   // qProcessInfo as it will be more specific to our process.
10260b57cec5SDimitry Andric 
10270b57cec5SDimitry Andric   const ArchSpec &remote_process_arch = m_gdb_comm.GetProcessArchitecture();
10280b57cec5SDimitry Andric   if (remote_process_arch.IsValid()) {
10290b57cec5SDimitry Andric     process_arch = remote_process_arch;
10305ffd83dbSDimitry Andric     LLDB_LOG(log, "gdb-remote had process architecture, using {0} {1}",
10315ffd83dbSDimitry Andric              process_arch.GetArchitectureName(),
10325ffd83dbSDimitry Andric              process_arch.GetTriple().getTriple());
10330b57cec5SDimitry Andric   } else {
10340b57cec5SDimitry Andric     process_arch = m_gdb_comm.GetHostArchitecture();
10355ffd83dbSDimitry Andric     LLDB_LOG(log,
10365ffd83dbSDimitry Andric              "gdb-remote did not have process architecture, using gdb-remote "
10375ffd83dbSDimitry Andric              "host architecture {0} {1}",
10385ffd83dbSDimitry Andric              process_arch.GetArchitectureName(),
10395ffd83dbSDimitry Andric              process_arch.GetTriple().getTriple());
10400b57cec5SDimitry Andric   }
10410b57cec5SDimitry Andric 
10420b57cec5SDimitry Andric   if (process_arch.IsValid()) {
10430b57cec5SDimitry Andric     const ArchSpec &target_arch = GetTarget().GetArchitecture();
10440b57cec5SDimitry Andric     if (target_arch.IsValid()) {
10455ffd83dbSDimitry Andric       LLDB_LOG(log, "analyzing target arch, currently {0} {1}",
10465ffd83dbSDimitry Andric                target_arch.GetArchitectureName(),
10475ffd83dbSDimitry Andric                target_arch.GetTriple().getTriple());
10480b57cec5SDimitry Andric 
10490b57cec5SDimitry Andric       // If the remote host is ARM and we have apple as the vendor, then
10500b57cec5SDimitry Andric       // ARM executables and shared libraries can have mixed ARM
10510b57cec5SDimitry Andric       // architectures.
10520b57cec5SDimitry Andric       // You can have an armv6 executable, and if the host is armv7, then the
10530b57cec5SDimitry Andric       // system will load the best possible architecture for all shared
10540b57cec5SDimitry Andric       // libraries it has, so we really need to take the remote host
10550b57cec5SDimitry Andric       // architecture as our defacto architecture in this case.
10560b57cec5SDimitry Andric 
10570b57cec5SDimitry Andric       if ((process_arch.GetMachine() == llvm::Triple::arm ||
10580b57cec5SDimitry Andric            process_arch.GetMachine() == llvm::Triple::thumb) &&
10590b57cec5SDimitry Andric           process_arch.GetTriple().getVendor() == llvm::Triple::Apple) {
10600b57cec5SDimitry Andric         GetTarget().SetArchitecture(process_arch);
10615ffd83dbSDimitry Andric         LLDB_LOG(log,
10625ffd83dbSDimitry Andric                  "remote process is ARM/Apple, "
10635ffd83dbSDimitry Andric                  "setting target arch to {0} {1}",
10645ffd83dbSDimitry Andric                  process_arch.GetArchitectureName(),
10655ffd83dbSDimitry Andric                  process_arch.GetTriple().getTriple());
10660b57cec5SDimitry Andric       } else {
10670b57cec5SDimitry Andric         // Fill in what is missing in the triple
10680b57cec5SDimitry Andric         const llvm::Triple &remote_triple = process_arch.GetTriple();
10690b57cec5SDimitry Andric         llvm::Triple new_target_triple = target_arch.GetTriple();
10700b57cec5SDimitry Andric         if (new_target_triple.getVendorName().size() == 0) {
10710b57cec5SDimitry Andric           new_target_triple.setVendor(remote_triple.getVendor());
10720b57cec5SDimitry Andric 
10730b57cec5SDimitry Andric           if (new_target_triple.getOSName().size() == 0) {
10740b57cec5SDimitry Andric             new_target_triple.setOS(remote_triple.getOS());
10750b57cec5SDimitry Andric 
10760b57cec5SDimitry Andric             if (new_target_triple.getEnvironmentName().size() == 0)
10775ffd83dbSDimitry Andric               new_target_triple.setEnvironment(remote_triple.getEnvironment());
10780b57cec5SDimitry Andric           }
10790b57cec5SDimitry Andric 
10800b57cec5SDimitry Andric           ArchSpec new_target_arch = target_arch;
10810b57cec5SDimitry Andric           new_target_arch.SetTriple(new_target_triple);
10820b57cec5SDimitry Andric           GetTarget().SetArchitecture(new_target_arch);
10830b57cec5SDimitry Andric         }
10840b57cec5SDimitry Andric       }
10850b57cec5SDimitry Andric 
10865ffd83dbSDimitry Andric       LLDB_LOG(log,
10875ffd83dbSDimitry Andric                "final target arch after adjustments for remote architecture: "
10885ffd83dbSDimitry Andric                "{0} {1}",
10895ffd83dbSDimitry Andric                target_arch.GetArchitectureName(),
10905ffd83dbSDimitry Andric                target_arch.GetTriple().getTriple());
10910b57cec5SDimitry Andric     } else {
10920b57cec5SDimitry Andric       // The target doesn't have a valid architecture yet, set it from the
10930b57cec5SDimitry Andric       // architecture we got from the remote GDB server
10940b57cec5SDimitry Andric       GetTarget().SetArchitecture(process_arch);
10950b57cec5SDimitry Andric     }
10960b57cec5SDimitry Andric   }
10970b57cec5SDimitry Andric 
10985ffd83dbSDimitry Andric   MaybeLoadExecutableModule();
10995ffd83dbSDimitry Andric 
11000b57cec5SDimitry Andric   // Find out which StructuredDataPlugins are supported by the debug monitor.
11010b57cec5SDimitry Andric   // These plugins transmit data over async $J packets.
11025ffd83dbSDimitry Andric   if (StructuredData::Array *supported_packets =
11035ffd83dbSDimitry Andric           m_gdb_comm.GetSupportedStructuredDataPlugins())
11045ffd83dbSDimitry Andric     MapSupportedStructuredDataPlugins(*supported_packets);
11055ffd83dbSDimitry Andric }
11065ffd83dbSDimitry Andric 
11075ffd83dbSDimitry Andric void ProcessGDBRemote::MaybeLoadExecutableModule() {
11085ffd83dbSDimitry Andric   ModuleSP module_sp = GetTarget().GetExecutableModule();
11095ffd83dbSDimitry Andric   if (!module_sp)
11105ffd83dbSDimitry Andric     return;
11115ffd83dbSDimitry Andric 
11125ffd83dbSDimitry Andric   llvm::Optional<QOffsets> offsets = m_gdb_comm.GetQOffsets();
11135ffd83dbSDimitry Andric   if (!offsets)
11145ffd83dbSDimitry Andric     return;
11155ffd83dbSDimitry Andric 
11165ffd83dbSDimitry Andric   bool is_uniform =
11175ffd83dbSDimitry Andric       size_t(llvm::count(offsets->offsets, offsets->offsets[0])) ==
11185ffd83dbSDimitry Andric       offsets->offsets.size();
11195ffd83dbSDimitry Andric   if (!is_uniform)
11205ffd83dbSDimitry Andric     return; // TODO: Handle non-uniform responses.
11215ffd83dbSDimitry Andric 
11225ffd83dbSDimitry Andric   bool changed = false;
11235ffd83dbSDimitry Andric   module_sp->SetLoadAddress(GetTarget(), offsets->offsets[0],
11245ffd83dbSDimitry Andric                             /*value_is_offset=*/true, changed);
11255ffd83dbSDimitry Andric   if (changed) {
11265ffd83dbSDimitry Andric     ModuleList list;
11275ffd83dbSDimitry Andric     list.Append(module_sp);
11285ffd83dbSDimitry Andric     m_process->GetTarget().ModulesDidLoad(list);
11290b57cec5SDimitry Andric   }
11300b57cec5SDimitry Andric }
11310b57cec5SDimitry Andric 
11320b57cec5SDimitry Andric void ProcessGDBRemote::DidLaunch() {
11330b57cec5SDimitry Andric   ArchSpec process_arch;
11340b57cec5SDimitry Andric   DidLaunchOrAttach(process_arch);
11350b57cec5SDimitry Andric }
11360b57cec5SDimitry Andric 
11370b57cec5SDimitry Andric Status ProcessGDBRemote::DoAttachToProcessWithID(
11380b57cec5SDimitry Andric     lldb::pid_t attach_pid, const ProcessAttachInfo &attach_info) {
11390b57cec5SDimitry Andric   Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
11400b57cec5SDimitry Andric   Status error;
11410b57cec5SDimitry Andric 
11429dba64beSDimitry Andric   LLDB_LOGF(log, "ProcessGDBRemote::%s()", __FUNCTION__);
11430b57cec5SDimitry Andric 
11440b57cec5SDimitry Andric   // Clear out and clean up from any current state
11450b57cec5SDimitry Andric   Clear();
11460b57cec5SDimitry Andric   if (attach_pid != LLDB_INVALID_PROCESS_ID) {
11470b57cec5SDimitry Andric     error = EstablishConnectionIfNeeded(attach_info);
11480b57cec5SDimitry Andric     if (error.Success()) {
11490b57cec5SDimitry Andric       m_gdb_comm.SetDetachOnError(attach_info.GetDetachOnError());
11500b57cec5SDimitry Andric 
11510b57cec5SDimitry Andric       char packet[64];
11520b57cec5SDimitry Andric       const int packet_len =
11530b57cec5SDimitry Andric           ::snprintf(packet, sizeof(packet), "vAttach;%" PRIx64, attach_pid);
11540b57cec5SDimitry Andric       SetID(attach_pid);
11550b57cec5SDimitry Andric       m_async_broadcaster.BroadcastEvent(
11560b57cec5SDimitry Andric           eBroadcastBitAsyncContinue, new EventDataBytes(packet, packet_len));
11570b57cec5SDimitry Andric     } else
11580b57cec5SDimitry Andric       SetExitStatus(-1, error.AsCString());
11590b57cec5SDimitry Andric   }
11600b57cec5SDimitry Andric 
11610b57cec5SDimitry Andric   return error;
11620b57cec5SDimitry Andric }
11630b57cec5SDimitry Andric 
11640b57cec5SDimitry Andric Status ProcessGDBRemote::DoAttachToProcessWithName(
11650b57cec5SDimitry Andric     const char *process_name, const ProcessAttachInfo &attach_info) {
11660b57cec5SDimitry Andric   Status error;
11670b57cec5SDimitry Andric   // Clear out and clean up from any current state
11680b57cec5SDimitry Andric   Clear();
11690b57cec5SDimitry Andric 
11700b57cec5SDimitry Andric   if (process_name && process_name[0]) {
11710b57cec5SDimitry Andric     error = EstablishConnectionIfNeeded(attach_info);
11720b57cec5SDimitry Andric     if (error.Success()) {
11730b57cec5SDimitry Andric       StreamString packet;
11740b57cec5SDimitry Andric 
11750b57cec5SDimitry Andric       m_gdb_comm.SetDetachOnError(attach_info.GetDetachOnError());
11760b57cec5SDimitry Andric 
11770b57cec5SDimitry Andric       if (attach_info.GetWaitForLaunch()) {
11780b57cec5SDimitry Andric         if (!m_gdb_comm.GetVAttachOrWaitSupported()) {
11790b57cec5SDimitry Andric           packet.PutCString("vAttachWait");
11800b57cec5SDimitry Andric         } else {
11810b57cec5SDimitry Andric           if (attach_info.GetIgnoreExisting())
11820b57cec5SDimitry Andric             packet.PutCString("vAttachWait");
11830b57cec5SDimitry Andric           else
11840b57cec5SDimitry Andric             packet.PutCString("vAttachOrWait");
11850b57cec5SDimitry Andric         }
11860b57cec5SDimitry Andric       } else
11870b57cec5SDimitry Andric         packet.PutCString("vAttachName");
11880b57cec5SDimitry Andric       packet.PutChar(';');
11890b57cec5SDimitry Andric       packet.PutBytesAsRawHex8(process_name, strlen(process_name),
11900b57cec5SDimitry Andric                                endian::InlHostByteOrder(),
11910b57cec5SDimitry Andric                                endian::InlHostByteOrder());
11920b57cec5SDimitry Andric 
11930b57cec5SDimitry Andric       m_async_broadcaster.BroadcastEvent(
11940b57cec5SDimitry Andric           eBroadcastBitAsyncContinue,
11950b57cec5SDimitry Andric           new EventDataBytes(packet.GetString().data(), packet.GetSize()));
11960b57cec5SDimitry Andric 
11970b57cec5SDimitry Andric     } else
11980b57cec5SDimitry Andric       SetExitStatus(-1, error.AsCString());
11990b57cec5SDimitry Andric   }
12000b57cec5SDimitry Andric   return error;
12010b57cec5SDimitry Andric }
12020b57cec5SDimitry Andric 
12030b57cec5SDimitry Andric lldb::user_id_t ProcessGDBRemote::StartTrace(const TraceOptions &options,
12040b57cec5SDimitry Andric                                              Status &error) {
12050b57cec5SDimitry Andric   return m_gdb_comm.SendStartTracePacket(options, error);
12060b57cec5SDimitry Andric }
12070b57cec5SDimitry Andric 
12080b57cec5SDimitry Andric Status ProcessGDBRemote::StopTrace(lldb::user_id_t uid, lldb::tid_t thread_id) {
12090b57cec5SDimitry Andric   return m_gdb_comm.SendStopTracePacket(uid, thread_id);
12100b57cec5SDimitry Andric }
12110b57cec5SDimitry Andric 
12120b57cec5SDimitry Andric Status ProcessGDBRemote::GetData(lldb::user_id_t uid, lldb::tid_t thread_id,
12130b57cec5SDimitry Andric                                  llvm::MutableArrayRef<uint8_t> &buffer,
12140b57cec5SDimitry Andric                                  size_t offset) {
12150b57cec5SDimitry Andric   return m_gdb_comm.SendGetDataPacket(uid, thread_id, buffer, offset);
12160b57cec5SDimitry Andric }
12170b57cec5SDimitry Andric 
12180b57cec5SDimitry Andric Status ProcessGDBRemote::GetMetaData(lldb::user_id_t uid, lldb::tid_t thread_id,
12190b57cec5SDimitry Andric                                      llvm::MutableArrayRef<uint8_t> &buffer,
12200b57cec5SDimitry Andric                                      size_t offset) {
12210b57cec5SDimitry Andric   return m_gdb_comm.SendGetMetaDataPacket(uid, thread_id, buffer, offset);
12220b57cec5SDimitry Andric }
12230b57cec5SDimitry Andric 
12240b57cec5SDimitry Andric Status ProcessGDBRemote::GetTraceConfig(lldb::user_id_t uid,
12250b57cec5SDimitry Andric                                         TraceOptions &options) {
12260b57cec5SDimitry Andric   return m_gdb_comm.SendGetTraceConfigPacket(uid, options);
12270b57cec5SDimitry Andric }
12280b57cec5SDimitry Andric 
12290b57cec5SDimitry Andric void ProcessGDBRemote::DidExit() {
12300b57cec5SDimitry Andric   // When we exit, disconnect from the GDB server communications
12310b57cec5SDimitry Andric   m_gdb_comm.Disconnect();
12320b57cec5SDimitry Andric }
12330b57cec5SDimitry Andric 
12340b57cec5SDimitry Andric void ProcessGDBRemote::DidAttach(ArchSpec &process_arch) {
12350b57cec5SDimitry Andric   // If you can figure out what the architecture is, fill it in here.
12360b57cec5SDimitry Andric   process_arch.Clear();
12370b57cec5SDimitry Andric   DidLaunchOrAttach(process_arch);
12380b57cec5SDimitry Andric }
12390b57cec5SDimitry Andric 
12400b57cec5SDimitry Andric Status ProcessGDBRemote::WillResume() {
12410b57cec5SDimitry Andric   m_continue_c_tids.clear();
12420b57cec5SDimitry Andric   m_continue_C_tids.clear();
12430b57cec5SDimitry Andric   m_continue_s_tids.clear();
12440b57cec5SDimitry Andric   m_continue_S_tids.clear();
12450b57cec5SDimitry Andric   m_jstopinfo_sp.reset();
12460b57cec5SDimitry Andric   m_jthreadsinfo_sp.reset();
12470b57cec5SDimitry Andric   return Status();
12480b57cec5SDimitry Andric }
12490b57cec5SDimitry Andric 
12500b57cec5SDimitry Andric Status ProcessGDBRemote::DoResume() {
12510b57cec5SDimitry Andric   Status error;
12520b57cec5SDimitry Andric   Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
12539dba64beSDimitry Andric   LLDB_LOGF(log, "ProcessGDBRemote::Resume()");
12540b57cec5SDimitry Andric 
12550b57cec5SDimitry Andric   ListenerSP listener_sp(
12560b57cec5SDimitry Andric       Listener::MakeListener("gdb-remote.resume-packet-sent"));
12570b57cec5SDimitry Andric   if (listener_sp->StartListeningForEvents(
12580b57cec5SDimitry Andric           &m_gdb_comm, GDBRemoteCommunication::eBroadcastBitRunPacketSent)) {
12590b57cec5SDimitry Andric     listener_sp->StartListeningForEvents(
12600b57cec5SDimitry Andric         &m_async_broadcaster,
12610b57cec5SDimitry Andric         ProcessGDBRemote::eBroadcastBitAsyncThreadDidExit);
12620b57cec5SDimitry Andric 
12630b57cec5SDimitry Andric     const size_t num_threads = GetThreadList().GetSize();
12640b57cec5SDimitry Andric 
12650b57cec5SDimitry Andric     StreamString continue_packet;
12660b57cec5SDimitry Andric     bool continue_packet_error = false;
12670b57cec5SDimitry Andric     if (m_gdb_comm.HasAnyVContSupport()) {
12680b57cec5SDimitry Andric       if (!GetTarget().GetNonStopModeEnabled() &&
12690b57cec5SDimitry Andric           (m_continue_c_tids.size() == num_threads ||
12700b57cec5SDimitry Andric            (m_continue_c_tids.empty() && m_continue_C_tids.empty() &&
12710b57cec5SDimitry Andric             m_continue_s_tids.empty() && m_continue_S_tids.empty()))) {
12720b57cec5SDimitry Andric         // All threads are continuing, just send a "c" packet
12730b57cec5SDimitry Andric         continue_packet.PutCString("c");
12740b57cec5SDimitry Andric       } else {
12750b57cec5SDimitry Andric         continue_packet.PutCString("vCont");
12760b57cec5SDimitry Andric 
12770b57cec5SDimitry Andric         if (!m_continue_c_tids.empty()) {
12780b57cec5SDimitry Andric           if (m_gdb_comm.GetVContSupported('c')) {
12790b57cec5SDimitry Andric             for (tid_collection::const_iterator
12800b57cec5SDimitry Andric                      t_pos = m_continue_c_tids.begin(),
12810b57cec5SDimitry Andric                      t_end = m_continue_c_tids.end();
12820b57cec5SDimitry Andric                  t_pos != t_end; ++t_pos)
12830b57cec5SDimitry Andric               continue_packet.Printf(";c:%4.4" PRIx64, *t_pos);
12840b57cec5SDimitry Andric           } else
12850b57cec5SDimitry Andric             continue_packet_error = true;
12860b57cec5SDimitry Andric         }
12870b57cec5SDimitry Andric 
12880b57cec5SDimitry Andric         if (!continue_packet_error && !m_continue_C_tids.empty()) {
12890b57cec5SDimitry Andric           if (m_gdb_comm.GetVContSupported('C')) {
12900b57cec5SDimitry Andric             for (tid_sig_collection::const_iterator
12910b57cec5SDimitry Andric                      s_pos = m_continue_C_tids.begin(),
12920b57cec5SDimitry Andric                      s_end = m_continue_C_tids.end();
12930b57cec5SDimitry Andric                  s_pos != s_end; ++s_pos)
12940b57cec5SDimitry Andric               continue_packet.Printf(";C%2.2x:%4.4" PRIx64, s_pos->second,
12950b57cec5SDimitry Andric                                      s_pos->first);
12960b57cec5SDimitry Andric           } else
12970b57cec5SDimitry Andric             continue_packet_error = true;
12980b57cec5SDimitry Andric         }
12990b57cec5SDimitry Andric 
13000b57cec5SDimitry Andric         if (!continue_packet_error && !m_continue_s_tids.empty()) {
13010b57cec5SDimitry Andric           if (m_gdb_comm.GetVContSupported('s')) {
13020b57cec5SDimitry Andric             for (tid_collection::const_iterator
13030b57cec5SDimitry Andric                      t_pos = m_continue_s_tids.begin(),
13040b57cec5SDimitry Andric                      t_end = m_continue_s_tids.end();
13050b57cec5SDimitry Andric                  t_pos != t_end; ++t_pos)
13060b57cec5SDimitry Andric               continue_packet.Printf(";s:%4.4" PRIx64, *t_pos);
13070b57cec5SDimitry Andric           } else
13080b57cec5SDimitry Andric             continue_packet_error = true;
13090b57cec5SDimitry Andric         }
13100b57cec5SDimitry Andric 
13110b57cec5SDimitry Andric         if (!continue_packet_error && !m_continue_S_tids.empty()) {
13120b57cec5SDimitry Andric           if (m_gdb_comm.GetVContSupported('S')) {
13130b57cec5SDimitry Andric             for (tid_sig_collection::const_iterator
13140b57cec5SDimitry Andric                      s_pos = m_continue_S_tids.begin(),
13150b57cec5SDimitry Andric                      s_end = m_continue_S_tids.end();
13160b57cec5SDimitry Andric                  s_pos != s_end; ++s_pos)
13170b57cec5SDimitry Andric               continue_packet.Printf(";S%2.2x:%4.4" PRIx64, s_pos->second,
13180b57cec5SDimitry Andric                                      s_pos->first);
13190b57cec5SDimitry Andric           } else
13200b57cec5SDimitry Andric             continue_packet_error = true;
13210b57cec5SDimitry Andric         }
13220b57cec5SDimitry Andric 
13230b57cec5SDimitry Andric         if (continue_packet_error)
13240b57cec5SDimitry Andric           continue_packet.Clear();
13250b57cec5SDimitry Andric       }
13260b57cec5SDimitry Andric     } else
13270b57cec5SDimitry Andric       continue_packet_error = true;
13280b57cec5SDimitry Andric 
13290b57cec5SDimitry Andric     if (continue_packet_error) {
13300b57cec5SDimitry Andric       // Either no vCont support, or we tried to use part of the vCont packet
13310b57cec5SDimitry Andric       // that wasn't supported by the remote GDB server. We need to try and
13320b57cec5SDimitry Andric       // make a simple packet that can do our continue
13330b57cec5SDimitry Andric       const size_t num_continue_c_tids = m_continue_c_tids.size();
13340b57cec5SDimitry Andric       const size_t num_continue_C_tids = m_continue_C_tids.size();
13350b57cec5SDimitry Andric       const size_t num_continue_s_tids = m_continue_s_tids.size();
13360b57cec5SDimitry Andric       const size_t num_continue_S_tids = m_continue_S_tids.size();
13370b57cec5SDimitry Andric       if (num_continue_c_tids > 0) {
13380b57cec5SDimitry Andric         if (num_continue_c_tids == num_threads) {
13390b57cec5SDimitry Andric           // All threads are resuming...
13400b57cec5SDimitry Andric           m_gdb_comm.SetCurrentThreadForRun(-1);
13410b57cec5SDimitry Andric           continue_packet.PutChar('c');
13420b57cec5SDimitry Andric           continue_packet_error = false;
13430b57cec5SDimitry Andric         } else if (num_continue_c_tids == 1 && num_continue_C_tids == 0 &&
13440b57cec5SDimitry Andric                    num_continue_s_tids == 0 && num_continue_S_tids == 0) {
13450b57cec5SDimitry Andric           // Only one thread is continuing
13460b57cec5SDimitry Andric           m_gdb_comm.SetCurrentThreadForRun(m_continue_c_tids.front());
13470b57cec5SDimitry Andric           continue_packet.PutChar('c');
13480b57cec5SDimitry Andric           continue_packet_error = false;
13490b57cec5SDimitry Andric         }
13500b57cec5SDimitry Andric       }
13510b57cec5SDimitry Andric 
13520b57cec5SDimitry Andric       if (continue_packet_error && num_continue_C_tids > 0) {
13530b57cec5SDimitry Andric         if ((num_continue_C_tids + num_continue_c_tids) == num_threads &&
13540b57cec5SDimitry Andric             num_continue_C_tids > 0 && num_continue_s_tids == 0 &&
13550b57cec5SDimitry Andric             num_continue_S_tids == 0) {
13560b57cec5SDimitry Andric           const int continue_signo = m_continue_C_tids.front().second;
13570b57cec5SDimitry Andric           // Only one thread is continuing
13580b57cec5SDimitry Andric           if (num_continue_C_tids > 1) {
13590b57cec5SDimitry Andric             // More that one thread with a signal, yet we don't have vCont
13600b57cec5SDimitry Andric             // support and we are being asked to resume each thread with a
13610b57cec5SDimitry Andric             // signal, we need to make sure they are all the same signal, or we
13620b57cec5SDimitry Andric             // can't issue the continue accurately with the current support...
13630b57cec5SDimitry Andric             if (num_continue_C_tids > 1) {
13640b57cec5SDimitry Andric               continue_packet_error = false;
13650b57cec5SDimitry Andric               for (size_t i = 1; i < m_continue_C_tids.size(); ++i) {
13660b57cec5SDimitry Andric                 if (m_continue_C_tids[i].second != continue_signo)
13670b57cec5SDimitry Andric                   continue_packet_error = true;
13680b57cec5SDimitry Andric               }
13690b57cec5SDimitry Andric             }
13700b57cec5SDimitry Andric             if (!continue_packet_error)
13710b57cec5SDimitry Andric               m_gdb_comm.SetCurrentThreadForRun(-1);
13720b57cec5SDimitry Andric           } else {
13730b57cec5SDimitry Andric             // Set the continue thread ID
13740b57cec5SDimitry Andric             continue_packet_error = false;
13750b57cec5SDimitry Andric             m_gdb_comm.SetCurrentThreadForRun(m_continue_C_tids.front().first);
13760b57cec5SDimitry Andric           }
13770b57cec5SDimitry Andric           if (!continue_packet_error) {
13780b57cec5SDimitry Andric             // Add threads continuing with the same signo...
13790b57cec5SDimitry Andric             continue_packet.Printf("C%2.2x", continue_signo);
13800b57cec5SDimitry Andric           }
13810b57cec5SDimitry Andric         }
13820b57cec5SDimitry Andric       }
13830b57cec5SDimitry Andric 
13840b57cec5SDimitry Andric       if (continue_packet_error && num_continue_s_tids > 0) {
13850b57cec5SDimitry Andric         if (num_continue_s_tids == num_threads) {
13860b57cec5SDimitry Andric           // All threads are resuming...
13870b57cec5SDimitry Andric           m_gdb_comm.SetCurrentThreadForRun(-1);
13880b57cec5SDimitry Andric 
13890b57cec5SDimitry Andric           // If in Non-Stop-Mode use vCont when stepping
13900b57cec5SDimitry Andric           if (GetTarget().GetNonStopModeEnabled()) {
13910b57cec5SDimitry Andric             if (m_gdb_comm.GetVContSupported('s'))
13920b57cec5SDimitry Andric               continue_packet.PutCString("vCont;s");
13930b57cec5SDimitry Andric             else
13940b57cec5SDimitry Andric               continue_packet.PutChar('s');
13950b57cec5SDimitry Andric           } else
13960b57cec5SDimitry Andric             continue_packet.PutChar('s');
13970b57cec5SDimitry Andric 
13980b57cec5SDimitry Andric           continue_packet_error = false;
13990b57cec5SDimitry Andric         } else if (num_continue_c_tids == 0 && num_continue_C_tids == 0 &&
14000b57cec5SDimitry Andric                    num_continue_s_tids == 1 && num_continue_S_tids == 0) {
14010b57cec5SDimitry Andric           // Only one thread is stepping
14020b57cec5SDimitry Andric           m_gdb_comm.SetCurrentThreadForRun(m_continue_s_tids.front());
14030b57cec5SDimitry Andric           continue_packet.PutChar('s');
14040b57cec5SDimitry Andric           continue_packet_error = false;
14050b57cec5SDimitry Andric         }
14060b57cec5SDimitry Andric       }
14070b57cec5SDimitry Andric 
14080b57cec5SDimitry Andric       if (!continue_packet_error && num_continue_S_tids > 0) {
14090b57cec5SDimitry Andric         if (num_continue_S_tids == num_threads) {
14100b57cec5SDimitry Andric           const int step_signo = m_continue_S_tids.front().second;
14110b57cec5SDimitry Andric           // Are all threads trying to step with the same signal?
14120b57cec5SDimitry Andric           continue_packet_error = false;
14130b57cec5SDimitry Andric           if (num_continue_S_tids > 1) {
14140b57cec5SDimitry Andric             for (size_t i = 1; i < num_threads; ++i) {
14150b57cec5SDimitry Andric               if (m_continue_S_tids[i].second != step_signo)
14160b57cec5SDimitry Andric                 continue_packet_error = true;
14170b57cec5SDimitry Andric             }
14180b57cec5SDimitry Andric           }
14190b57cec5SDimitry Andric           if (!continue_packet_error) {
14200b57cec5SDimitry Andric             // Add threads stepping with the same signo...
14210b57cec5SDimitry Andric             m_gdb_comm.SetCurrentThreadForRun(-1);
14220b57cec5SDimitry Andric             continue_packet.Printf("S%2.2x", step_signo);
14230b57cec5SDimitry Andric           }
14240b57cec5SDimitry Andric         } else if (num_continue_c_tids == 0 && num_continue_C_tids == 0 &&
14250b57cec5SDimitry Andric                    num_continue_s_tids == 0 && num_continue_S_tids == 1) {
14260b57cec5SDimitry Andric           // Only one thread is stepping with signal
14270b57cec5SDimitry Andric           m_gdb_comm.SetCurrentThreadForRun(m_continue_S_tids.front().first);
14280b57cec5SDimitry Andric           continue_packet.Printf("S%2.2x", m_continue_S_tids.front().second);
14290b57cec5SDimitry Andric           continue_packet_error = false;
14300b57cec5SDimitry Andric         }
14310b57cec5SDimitry Andric       }
14320b57cec5SDimitry Andric     }
14330b57cec5SDimitry Andric 
14340b57cec5SDimitry Andric     if (continue_packet_error) {
14350b57cec5SDimitry Andric       error.SetErrorString("can't make continue packet for this resume");
14360b57cec5SDimitry Andric     } else {
14370b57cec5SDimitry Andric       EventSP event_sp;
14380b57cec5SDimitry Andric       if (!m_async_thread.IsJoinable()) {
14390b57cec5SDimitry Andric         error.SetErrorString("Trying to resume but the async thread is dead.");
14409dba64beSDimitry Andric         LLDB_LOGF(log, "ProcessGDBRemote::DoResume: Trying to resume but the "
14410b57cec5SDimitry Andric                        "async thread is dead.");
14420b57cec5SDimitry Andric         return error;
14430b57cec5SDimitry Andric       }
14440b57cec5SDimitry Andric 
14450b57cec5SDimitry Andric       m_async_broadcaster.BroadcastEvent(
14460b57cec5SDimitry Andric           eBroadcastBitAsyncContinue,
14470b57cec5SDimitry Andric           new EventDataBytes(continue_packet.GetString().data(),
14480b57cec5SDimitry Andric                              continue_packet.GetSize()));
14490b57cec5SDimitry Andric 
14500b57cec5SDimitry Andric       if (!listener_sp->GetEvent(event_sp, std::chrono::seconds(5))) {
14510b57cec5SDimitry Andric         error.SetErrorString("Resume timed out.");
14529dba64beSDimitry Andric         LLDB_LOGF(log, "ProcessGDBRemote::DoResume: Resume timed out.");
14530b57cec5SDimitry Andric       } else if (event_sp->BroadcasterIs(&m_async_broadcaster)) {
14540b57cec5SDimitry Andric         error.SetErrorString("Broadcast continue, but the async thread was "
14550b57cec5SDimitry Andric                              "killed before we got an ack back.");
14569dba64beSDimitry Andric         LLDB_LOGF(log,
14579dba64beSDimitry Andric                   "ProcessGDBRemote::DoResume: Broadcast continue, but the "
14580b57cec5SDimitry Andric                   "async thread was killed before we got an ack back.");
14590b57cec5SDimitry Andric         return error;
14600b57cec5SDimitry Andric       }
14610b57cec5SDimitry Andric     }
14620b57cec5SDimitry Andric   }
14630b57cec5SDimitry Andric 
14640b57cec5SDimitry Andric   return error;
14650b57cec5SDimitry Andric }
14660b57cec5SDimitry Andric 
14670b57cec5SDimitry Andric void ProcessGDBRemote::HandleStopReplySequence() {
14680b57cec5SDimitry Andric   while (true) {
14690b57cec5SDimitry Andric     // Send vStopped
14700b57cec5SDimitry Andric     StringExtractorGDBRemote response;
14710b57cec5SDimitry Andric     m_gdb_comm.SendPacketAndWaitForResponse("vStopped", response, false);
14720b57cec5SDimitry Andric 
14730b57cec5SDimitry Andric     // OK represents end of signal list
14740b57cec5SDimitry Andric     if (response.IsOKResponse())
14750b57cec5SDimitry Andric       break;
14760b57cec5SDimitry Andric 
14770b57cec5SDimitry Andric     // If not OK or a normal packet we have a problem
14780b57cec5SDimitry Andric     if (!response.IsNormalResponse())
14790b57cec5SDimitry Andric       break;
14800b57cec5SDimitry Andric 
14810b57cec5SDimitry Andric     SetLastStopPacket(response);
14820b57cec5SDimitry Andric   }
14830b57cec5SDimitry Andric }
14840b57cec5SDimitry Andric 
14850b57cec5SDimitry Andric void ProcessGDBRemote::ClearThreadIDList() {
14860b57cec5SDimitry Andric   std::lock_guard<std::recursive_mutex> guard(m_thread_list_real.GetMutex());
14870b57cec5SDimitry Andric   m_thread_ids.clear();
14880b57cec5SDimitry Andric   m_thread_pcs.clear();
14890b57cec5SDimitry Andric }
14900b57cec5SDimitry Andric 
14910b57cec5SDimitry Andric size_t
14920b57cec5SDimitry Andric ProcessGDBRemote::UpdateThreadIDsFromStopReplyThreadsValue(std::string &value) {
14930b57cec5SDimitry Andric   m_thread_ids.clear();
14940b57cec5SDimitry Andric   size_t comma_pos;
14950b57cec5SDimitry Andric   lldb::tid_t tid;
14960b57cec5SDimitry Andric   while ((comma_pos = value.find(',')) != std::string::npos) {
14970b57cec5SDimitry Andric     value[comma_pos] = '\0';
14980b57cec5SDimitry Andric     // thread in big endian hex
14990b57cec5SDimitry Andric     tid = StringConvert::ToUInt64(value.c_str(), LLDB_INVALID_THREAD_ID, 16);
15000b57cec5SDimitry Andric     if (tid != LLDB_INVALID_THREAD_ID)
15010b57cec5SDimitry Andric       m_thread_ids.push_back(tid);
15020b57cec5SDimitry Andric     value.erase(0, comma_pos + 1);
15030b57cec5SDimitry Andric   }
15040b57cec5SDimitry Andric   tid = StringConvert::ToUInt64(value.c_str(), LLDB_INVALID_THREAD_ID, 16);
15050b57cec5SDimitry Andric   if (tid != LLDB_INVALID_THREAD_ID)
15060b57cec5SDimitry Andric     m_thread_ids.push_back(tid);
15070b57cec5SDimitry Andric   return m_thread_ids.size();
15080b57cec5SDimitry Andric }
15090b57cec5SDimitry Andric 
15100b57cec5SDimitry Andric size_t
15110b57cec5SDimitry Andric ProcessGDBRemote::UpdateThreadPCsFromStopReplyThreadsValue(std::string &value) {
15120b57cec5SDimitry Andric   m_thread_pcs.clear();
15130b57cec5SDimitry Andric   size_t comma_pos;
15140b57cec5SDimitry Andric   lldb::addr_t pc;
15150b57cec5SDimitry Andric   while ((comma_pos = value.find(',')) != std::string::npos) {
15160b57cec5SDimitry Andric     value[comma_pos] = '\0';
15170b57cec5SDimitry Andric     pc = StringConvert::ToUInt64(value.c_str(), LLDB_INVALID_ADDRESS, 16);
15180b57cec5SDimitry Andric     if (pc != LLDB_INVALID_ADDRESS)
15190b57cec5SDimitry Andric       m_thread_pcs.push_back(pc);
15200b57cec5SDimitry Andric     value.erase(0, comma_pos + 1);
15210b57cec5SDimitry Andric   }
15220b57cec5SDimitry Andric   pc = StringConvert::ToUInt64(value.c_str(), LLDB_INVALID_ADDRESS, 16);
15230b57cec5SDimitry Andric   if (pc != LLDB_INVALID_THREAD_ID)
15240b57cec5SDimitry Andric     m_thread_pcs.push_back(pc);
15250b57cec5SDimitry Andric   return m_thread_pcs.size();
15260b57cec5SDimitry Andric }
15270b57cec5SDimitry Andric 
15280b57cec5SDimitry Andric bool ProcessGDBRemote::UpdateThreadIDList() {
15290b57cec5SDimitry Andric   std::lock_guard<std::recursive_mutex> guard(m_thread_list_real.GetMutex());
15300b57cec5SDimitry Andric 
15310b57cec5SDimitry Andric   if (m_jthreadsinfo_sp) {
15320b57cec5SDimitry Andric     // If we have the JSON threads info, we can get the thread list from that
15330b57cec5SDimitry Andric     StructuredData::Array *thread_infos = m_jthreadsinfo_sp->GetAsArray();
15340b57cec5SDimitry Andric     if (thread_infos && thread_infos->GetSize() > 0) {
15350b57cec5SDimitry Andric       m_thread_ids.clear();
15360b57cec5SDimitry Andric       m_thread_pcs.clear();
15370b57cec5SDimitry Andric       thread_infos->ForEach([this](StructuredData::Object *object) -> bool {
15380b57cec5SDimitry Andric         StructuredData::Dictionary *thread_dict = object->GetAsDictionary();
15390b57cec5SDimitry Andric         if (thread_dict) {
15400b57cec5SDimitry Andric           // Set the thread stop info from the JSON dictionary
15410b57cec5SDimitry Andric           SetThreadStopInfo(thread_dict);
15420b57cec5SDimitry Andric           lldb::tid_t tid = LLDB_INVALID_THREAD_ID;
15430b57cec5SDimitry Andric           if (thread_dict->GetValueForKeyAsInteger<lldb::tid_t>("tid", tid))
15440b57cec5SDimitry Andric             m_thread_ids.push_back(tid);
15450b57cec5SDimitry Andric         }
15460b57cec5SDimitry Andric         return true; // Keep iterating through all thread_info objects
15470b57cec5SDimitry Andric       });
15480b57cec5SDimitry Andric     }
15490b57cec5SDimitry Andric     if (!m_thread_ids.empty())
15500b57cec5SDimitry Andric       return true;
15510b57cec5SDimitry Andric   } else {
15520b57cec5SDimitry Andric     // See if we can get the thread IDs from the current stop reply packets
15530b57cec5SDimitry Andric     // that might contain a "threads" key/value pair
15540b57cec5SDimitry Andric 
15550b57cec5SDimitry Andric     // Lock the thread stack while we access it
15560b57cec5SDimitry Andric     // Mutex::Locker stop_stack_lock(m_last_stop_packet_mutex);
15570b57cec5SDimitry Andric     std::unique_lock<std::recursive_mutex> stop_stack_lock(
15580b57cec5SDimitry Andric         m_last_stop_packet_mutex, std::defer_lock);
15590b57cec5SDimitry Andric     if (stop_stack_lock.try_lock()) {
15600b57cec5SDimitry Andric       // Get the number of stop packets on the stack
15610b57cec5SDimitry Andric       int nItems = m_stop_packet_stack.size();
15620b57cec5SDimitry Andric       // Iterate over them
15630b57cec5SDimitry Andric       for (int i = 0; i < nItems; i++) {
15640b57cec5SDimitry Andric         // Get the thread stop info
15650b57cec5SDimitry Andric         StringExtractorGDBRemote &stop_info = m_stop_packet_stack[i];
15665ffd83dbSDimitry Andric         const std::string &stop_info_str =
15675ffd83dbSDimitry Andric             std::string(stop_info.GetStringRef());
15680b57cec5SDimitry Andric 
15690b57cec5SDimitry Andric         m_thread_pcs.clear();
15700b57cec5SDimitry Andric         const size_t thread_pcs_pos = stop_info_str.find(";thread-pcs:");
15710b57cec5SDimitry Andric         if (thread_pcs_pos != std::string::npos) {
15720b57cec5SDimitry Andric           const size_t start = thread_pcs_pos + strlen(";thread-pcs:");
15730b57cec5SDimitry Andric           const size_t end = stop_info_str.find(';', start);
15740b57cec5SDimitry Andric           if (end != std::string::npos) {
15750b57cec5SDimitry Andric             std::string value = stop_info_str.substr(start, end - start);
15760b57cec5SDimitry Andric             UpdateThreadPCsFromStopReplyThreadsValue(value);
15770b57cec5SDimitry Andric           }
15780b57cec5SDimitry Andric         }
15790b57cec5SDimitry Andric 
15800b57cec5SDimitry Andric         const size_t threads_pos = stop_info_str.find(";threads:");
15810b57cec5SDimitry Andric         if (threads_pos != std::string::npos) {
15820b57cec5SDimitry Andric           const size_t start = threads_pos + strlen(";threads:");
15830b57cec5SDimitry Andric           const size_t end = stop_info_str.find(';', start);
15840b57cec5SDimitry Andric           if (end != std::string::npos) {
15850b57cec5SDimitry Andric             std::string value = stop_info_str.substr(start, end - start);
15860b57cec5SDimitry Andric             if (UpdateThreadIDsFromStopReplyThreadsValue(value))
15870b57cec5SDimitry Andric               return true;
15880b57cec5SDimitry Andric           }
15890b57cec5SDimitry Andric         }
15900b57cec5SDimitry Andric       }
15910b57cec5SDimitry Andric     }
15920b57cec5SDimitry Andric   }
15930b57cec5SDimitry Andric 
15940b57cec5SDimitry Andric   bool sequence_mutex_unavailable = false;
15950b57cec5SDimitry Andric   m_gdb_comm.GetCurrentThreadIDs(m_thread_ids, sequence_mutex_unavailable);
15960b57cec5SDimitry Andric   if (sequence_mutex_unavailable) {
15970b57cec5SDimitry Andric     return false; // We just didn't get the list
15980b57cec5SDimitry Andric   }
15990b57cec5SDimitry Andric   return true;
16000b57cec5SDimitry Andric }
16010b57cec5SDimitry Andric 
16020b57cec5SDimitry Andric bool ProcessGDBRemote::UpdateThreadList(ThreadList &old_thread_list,
16030b57cec5SDimitry Andric                                         ThreadList &new_thread_list) {
16040b57cec5SDimitry Andric   // locker will keep a mutex locked until it goes out of scope
16050b57cec5SDimitry Andric   Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_THREAD));
16060b57cec5SDimitry Andric   LLDB_LOGV(log, "pid = {0}", GetID());
16070b57cec5SDimitry Andric 
16080b57cec5SDimitry Andric   size_t num_thread_ids = m_thread_ids.size();
16090b57cec5SDimitry Andric   // The "m_thread_ids" thread ID list should always be updated after each stop
16100b57cec5SDimitry Andric   // reply packet, but in case it isn't, update it here.
16110b57cec5SDimitry Andric   if (num_thread_ids == 0) {
16120b57cec5SDimitry Andric     if (!UpdateThreadIDList())
16130b57cec5SDimitry Andric       return false;
16140b57cec5SDimitry Andric     num_thread_ids = m_thread_ids.size();
16150b57cec5SDimitry Andric   }
16160b57cec5SDimitry Andric 
16170b57cec5SDimitry Andric   ThreadList old_thread_list_copy(old_thread_list);
16180b57cec5SDimitry Andric   if (num_thread_ids > 0) {
16190b57cec5SDimitry Andric     for (size_t i = 0; i < num_thread_ids; ++i) {
16200b57cec5SDimitry Andric       tid_t tid = m_thread_ids[i];
16210b57cec5SDimitry Andric       ThreadSP thread_sp(
16220b57cec5SDimitry Andric           old_thread_list_copy.RemoveThreadByProtocolID(tid, false));
16230b57cec5SDimitry Andric       if (!thread_sp) {
16240b57cec5SDimitry Andric         thread_sp = std::make_shared<ThreadGDBRemote>(*this, tid);
16250b57cec5SDimitry Andric         LLDB_LOGV(log, "Making new thread: {0} for thread ID: {1:x}.",
16260b57cec5SDimitry Andric                   thread_sp.get(), thread_sp->GetID());
16270b57cec5SDimitry Andric       } else {
16280b57cec5SDimitry Andric         LLDB_LOGV(log, "Found old thread: {0} for thread ID: {1:x}.",
16290b57cec5SDimitry Andric                   thread_sp.get(), thread_sp->GetID());
16300b57cec5SDimitry Andric       }
16310b57cec5SDimitry Andric 
16320b57cec5SDimitry Andric       SetThreadPc(thread_sp, i);
16330b57cec5SDimitry Andric       new_thread_list.AddThreadSortedByIndexID(thread_sp);
16340b57cec5SDimitry Andric     }
16350b57cec5SDimitry Andric   }
16360b57cec5SDimitry Andric 
16370b57cec5SDimitry Andric   // Whatever that is left in old_thread_list_copy are not present in
16380b57cec5SDimitry Andric   // new_thread_list. Remove non-existent threads from internal id table.
16390b57cec5SDimitry Andric   size_t old_num_thread_ids = old_thread_list_copy.GetSize(false);
16400b57cec5SDimitry Andric   for (size_t i = 0; i < old_num_thread_ids; i++) {
16410b57cec5SDimitry Andric     ThreadSP old_thread_sp(old_thread_list_copy.GetThreadAtIndex(i, false));
16420b57cec5SDimitry Andric     if (old_thread_sp) {
16430b57cec5SDimitry Andric       lldb::tid_t old_thread_id = old_thread_sp->GetProtocolID();
16440b57cec5SDimitry Andric       m_thread_id_to_index_id_map.erase(old_thread_id);
16450b57cec5SDimitry Andric     }
16460b57cec5SDimitry Andric   }
16470b57cec5SDimitry Andric 
16480b57cec5SDimitry Andric   return true;
16490b57cec5SDimitry Andric }
16500b57cec5SDimitry Andric 
16510b57cec5SDimitry Andric void ProcessGDBRemote::SetThreadPc(const ThreadSP &thread_sp, uint64_t index) {
16520b57cec5SDimitry Andric   if (m_thread_ids.size() == m_thread_pcs.size() && thread_sp.get() &&
16530b57cec5SDimitry Andric       GetByteOrder() != eByteOrderInvalid) {
16540b57cec5SDimitry Andric     ThreadGDBRemote *gdb_thread =
16550b57cec5SDimitry Andric         static_cast<ThreadGDBRemote *>(thread_sp.get());
16560b57cec5SDimitry Andric     RegisterContextSP reg_ctx_sp(thread_sp->GetRegisterContext());
16570b57cec5SDimitry Andric     if (reg_ctx_sp) {
16580b57cec5SDimitry Andric       uint32_t pc_regnum = reg_ctx_sp->ConvertRegisterKindToRegisterNumber(
16590b57cec5SDimitry Andric           eRegisterKindGeneric, LLDB_REGNUM_GENERIC_PC);
16600b57cec5SDimitry Andric       if (pc_regnum != LLDB_INVALID_REGNUM) {
16610b57cec5SDimitry Andric         gdb_thread->PrivateSetRegisterValue(pc_regnum, m_thread_pcs[index]);
16620b57cec5SDimitry Andric       }
16630b57cec5SDimitry Andric     }
16640b57cec5SDimitry Andric   }
16650b57cec5SDimitry Andric }
16660b57cec5SDimitry Andric 
16670b57cec5SDimitry Andric bool ProcessGDBRemote::GetThreadStopInfoFromJSON(
16680b57cec5SDimitry Andric     ThreadGDBRemote *thread, const StructuredData::ObjectSP &thread_infos_sp) {
16690b57cec5SDimitry Andric   // See if we got thread stop infos for all threads via the "jThreadsInfo"
16700b57cec5SDimitry Andric   // packet
16710b57cec5SDimitry Andric   if (thread_infos_sp) {
16720b57cec5SDimitry Andric     StructuredData::Array *thread_infos = thread_infos_sp->GetAsArray();
16730b57cec5SDimitry Andric     if (thread_infos) {
16740b57cec5SDimitry Andric       lldb::tid_t tid;
16750b57cec5SDimitry Andric       const size_t n = thread_infos->GetSize();
16760b57cec5SDimitry Andric       for (size_t i = 0; i < n; ++i) {
16770b57cec5SDimitry Andric         StructuredData::Dictionary *thread_dict =
16780b57cec5SDimitry Andric             thread_infos->GetItemAtIndex(i)->GetAsDictionary();
16790b57cec5SDimitry Andric         if (thread_dict) {
16800b57cec5SDimitry Andric           if (thread_dict->GetValueForKeyAsInteger<lldb::tid_t>(
16810b57cec5SDimitry Andric                   "tid", tid, LLDB_INVALID_THREAD_ID)) {
16820b57cec5SDimitry Andric             if (tid == thread->GetID())
16830b57cec5SDimitry Andric               return (bool)SetThreadStopInfo(thread_dict);
16840b57cec5SDimitry Andric           }
16850b57cec5SDimitry Andric         }
16860b57cec5SDimitry Andric       }
16870b57cec5SDimitry Andric     }
16880b57cec5SDimitry Andric   }
16890b57cec5SDimitry Andric   return false;
16900b57cec5SDimitry Andric }
16910b57cec5SDimitry Andric 
16920b57cec5SDimitry Andric bool ProcessGDBRemote::CalculateThreadStopInfo(ThreadGDBRemote *thread) {
16930b57cec5SDimitry Andric   // See if we got thread stop infos for all threads via the "jThreadsInfo"
16940b57cec5SDimitry Andric   // packet
16950b57cec5SDimitry Andric   if (GetThreadStopInfoFromJSON(thread, m_jthreadsinfo_sp))
16960b57cec5SDimitry Andric     return true;
16970b57cec5SDimitry Andric 
16980b57cec5SDimitry Andric   // See if we got thread stop info for any threads valid stop info reasons
16990b57cec5SDimitry Andric   // threads via the "jstopinfo" packet stop reply packet key/value pair?
17000b57cec5SDimitry Andric   if (m_jstopinfo_sp) {
17010b57cec5SDimitry Andric     // If we have "jstopinfo" then we have stop descriptions for all threads
17020b57cec5SDimitry Andric     // that have stop reasons, and if there is no entry for a thread, then it
17030b57cec5SDimitry Andric     // has no stop reason.
17040b57cec5SDimitry Andric     thread->GetRegisterContext()->InvalidateIfNeeded(true);
17050b57cec5SDimitry Andric     if (!GetThreadStopInfoFromJSON(thread, m_jstopinfo_sp)) {
17060b57cec5SDimitry Andric       thread->SetStopInfo(StopInfoSP());
17070b57cec5SDimitry Andric     }
17080b57cec5SDimitry Andric     return true;
17090b57cec5SDimitry Andric   }
17100b57cec5SDimitry Andric 
17110b57cec5SDimitry Andric   // Fall back to using the qThreadStopInfo packet
17120b57cec5SDimitry Andric   StringExtractorGDBRemote stop_packet;
17130b57cec5SDimitry Andric   if (GetGDBRemote().GetThreadStopInfo(thread->GetProtocolID(), stop_packet))
17140b57cec5SDimitry Andric     return SetThreadStopInfo(stop_packet) == eStateStopped;
17150b57cec5SDimitry Andric   return false;
17160b57cec5SDimitry Andric }
17170b57cec5SDimitry Andric 
17180b57cec5SDimitry Andric ThreadSP ProcessGDBRemote::SetThreadStopInfo(
17190b57cec5SDimitry Andric     lldb::tid_t tid, ExpeditedRegisterMap &expedited_register_map,
17200b57cec5SDimitry Andric     uint8_t signo, const std::string &thread_name, const std::string &reason,
17210b57cec5SDimitry Andric     const std::string &description, uint32_t exc_type,
17220b57cec5SDimitry Andric     const std::vector<addr_t> &exc_data, addr_t thread_dispatch_qaddr,
17230b57cec5SDimitry Andric     bool queue_vars_valid, // Set to true if queue_name, queue_kind and
17240b57cec5SDimitry Andric                            // queue_serial are valid
17250b57cec5SDimitry Andric     LazyBool associated_with_dispatch_queue, addr_t dispatch_queue_t,
17260b57cec5SDimitry Andric     std::string &queue_name, QueueKind queue_kind, uint64_t queue_serial) {
17270b57cec5SDimitry Andric   ThreadSP thread_sp;
17280b57cec5SDimitry Andric   if (tid != LLDB_INVALID_THREAD_ID) {
17290b57cec5SDimitry Andric     // Scope for "locker" below
17300b57cec5SDimitry Andric     {
17310b57cec5SDimitry Andric       // m_thread_list_real does have its own mutex, but we need to hold onto
17320b57cec5SDimitry Andric       // the mutex between the call to m_thread_list_real.FindThreadByID(...)
17330b57cec5SDimitry Andric       // and the m_thread_list_real.AddThread(...) so it doesn't change on us
17340b57cec5SDimitry Andric       std::lock_guard<std::recursive_mutex> guard(
17350b57cec5SDimitry Andric           m_thread_list_real.GetMutex());
17360b57cec5SDimitry Andric       thread_sp = m_thread_list_real.FindThreadByProtocolID(tid, false);
17370b57cec5SDimitry Andric 
17380b57cec5SDimitry Andric       if (!thread_sp) {
17390b57cec5SDimitry Andric         // Create the thread if we need to
17400b57cec5SDimitry Andric         thread_sp = std::make_shared<ThreadGDBRemote>(*this, tid);
17410b57cec5SDimitry Andric         m_thread_list_real.AddThread(thread_sp);
17420b57cec5SDimitry Andric       }
17430b57cec5SDimitry Andric     }
17440b57cec5SDimitry Andric 
17450b57cec5SDimitry Andric     if (thread_sp) {
17460b57cec5SDimitry Andric       ThreadGDBRemote *gdb_thread =
17470b57cec5SDimitry Andric           static_cast<ThreadGDBRemote *>(thread_sp.get());
17480b57cec5SDimitry Andric       gdb_thread->GetRegisterContext()->InvalidateIfNeeded(true);
17490b57cec5SDimitry Andric 
17500b57cec5SDimitry Andric       auto iter = std::find(m_thread_ids.begin(), m_thread_ids.end(), tid);
17510b57cec5SDimitry Andric       if (iter != m_thread_ids.end()) {
17520b57cec5SDimitry Andric         SetThreadPc(thread_sp, iter - m_thread_ids.begin());
17530b57cec5SDimitry Andric       }
17540b57cec5SDimitry Andric 
17550b57cec5SDimitry Andric       for (const auto &pair : expedited_register_map) {
17569dba64beSDimitry Andric         StringExtractor reg_value_extractor(pair.second);
17570b57cec5SDimitry Andric         DataBufferSP buffer_sp(new DataBufferHeap(
17580b57cec5SDimitry Andric             reg_value_extractor.GetStringRef().size() / 2, 0));
17590b57cec5SDimitry Andric         reg_value_extractor.GetHexBytes(buffer_sp->GetData(), '\xcc');
17600b57cec5SDimitry Andric         gdb_thread->PrivateSetRegisterValue(pair.first, buffer_sp->GetData());
17610b57cec5SDimitry Andric       }
17620b57cec5SDimitry Andric 
17630b57cec5SDimitry Andric       thread_sp->SetName(thread_name.empty() ? nullptr : thread_name.c_str());
17640b57cec5SDimitry Andric 
17650b57cec5SDimitry Andric       gdb_thread->SetThreadDispatchQAddr(thread_dispatch_qaddr);
17660b57cec5SDimitry Andric       // Check if the GDB server was able to provide the queue name, kind and
17670b57cec5SDimitry Andric       // serial number
17680b57cec5SDimitry Andric       if (queue_vars_valid)
17690b57cec5SDimitry Andric         gdb_thread->SetQueueInfo(std::move(queue_name), queue_kind,
17700b57cec5SDimitry Andric                                  queue_serial, dispatch_queue_t,
17710b57cec5SDimitry Andric                                  associated_with_dispatch_queue);
17720b57cec5SDimitry Andric       else
17730b57cec5SDimitry Andric         gdb_thread->ClearQueueInfo();
17740b57cec5SDimitry Andric 
17750b57cec5SDimitry Andric       gdb_thread->SetAssociatedWithLibdispatchQueue(
17760b57cec5SDimitry Andric           associated_with_dispatch_queue);
17770b57cec5SDimitry Andric 
17780b57cec5SDimitry Andric       if (dispatch_queue_t != LLDB_INVALID_ADDRESS)
17790b57cec5SDimitry Andric         gdb_thread->SetQueueLibdispatchQueueAddress(dispatch_queue_t);
17800b57cec5SDimitry Andric 
17810b57cec5SDimitry Andric       // Make sure we update our thread stop reason just once
17820b57cec5SDimitry Andric       if (!thread_sp->StopInfoIsUpToDate()) {
17830b57cec5SDimitry Andric         thread_sp->SetStopInfo(StopInfoSP());
17840b57cec5SDimitry Andric         // If there's a memory thread backed by this thread, we need to use it
17850b57cec5SDimitry Andric         // to calculate StopInfo.
17860b57cec5SDimitry Andric         if (ThreadSP memory_thread_sp =
17870b57cec5SDimitry Andric                 m_thread_list.GetBackingThread(thread_sp))
17880b57cec5SDimitry Andric           thread_sp = memory_thread_sp;
17890b57cec5SDimitry Andric 
17900b57cec5SDimitry Andric         if (exc_type != 0) {
17910b57cec5SDimitry Andric           const size_t exc_data_size = exc_data.size();
17920b57cec5SDimitry Andric 
17930b57cec5SDimitry Andric           thread_sp->SetStopInfo(
17940b57cec5SDimitry Andric               StopInfoMachException::CreateStopReasonWithMachException(
17950b57cec5SDimitry Andric                   *thread_sp, exc_type, exc_data_size,
17960b57cec5SDimitry Andric                   exc_data_size >= 1 ? exc_data[0] : 0,
17970b57cec5SDimitry Andric                   exc_data_size >= 2 ? exc_data[1] : 0,
17980b57cec5SDimitry Andric                   exc_data_size >= 3 ? exc_data[2] : 0));
17990b57cec5SDimitry Andric         } else {
18000b57cec5SDimitry Andric           bool handled = false;
18010b57cec5SDimitry Andric           bool did_exec = false;
18020b57cec5SDimitry Andric           if (!reason.empty()) {
18030b57cec5SDimitry Andric             if (reason == "trace") {
18040b57cec5SDimitry Andric               addr_t pc = thread_sp->GetRegisterContext()->GetPC();
18050b57cec5SDimitry Andric               lldb::BreakpointSiteSP bp_site_sp = thread_sp->GetProcess()
18060b57cec5SDimitry Andric                                                       ->GetBreakpointSiteList()
18070b57cec5SDimitry Andric                                                       .FindByAddress(pc);
18080b57cec5SDimitry Andric 
18090b57cec5SDimitry Andric               // If the current pc is a breakpoint site then the StopInfo
18100b57cec5SDimitry Andric               // should be set to Breakpoint Otherwise, it will be set to
18110b57cec5SDimitry Andric               // Trace.
18120b57cec5SDimitry Andric               if (bp_site_sp &&
18130b57cec5SDimitry Andric                   bp_site_sp->ValidForThisThread(thread_sp.get())) {
18140b57cec5SDimitry Andric                 thread_sp->SetStopInfo(
18150b57cec5SDimitry Andric                     StopInfo::CreateStopReasonWithBreakpointSiteID(
18160b57cec5SDimitry Andric                         *thread_sp, bp_site_sp->GetID()));
18170b57cec5SDimitry Andric               } else
18180b57cec5SDimitry Andric                 thread_sp->SetStopInfo(
18190b57cec5SDimitry Andric                     StopInfo::CreateStopReasonToTrace(*thread_sp));
18200b57cec5SDimitry Andric               handled = true;
18210b57cec5SDimitry Andric             } else if (reason == "breakpoint") {
18220b57cec5SDimitry Andric               addr_t pc = thread_sp->GetRegisterContext()->GetPC();
18230b57cec5SDimitry Andric               lldb::BreakpointSiteSP bp_site_sp = thread_sp->GetProcess()
18240b57cec5SDimitry Andric                                                       ->GetBreakpointSiteList()
18250b57cec5SDimitry Andric                                                       .FindByAddress(pc);
18260b57cec5SDimitry Andric               if (bp_site_sp) {
18270b57cec5SDimitry Andric                 // If the breakpoint is for this thread, then we'll report the
18280b57cec5SDimitry Andric                 // hit, but if it is for another thread, we can just report no
18290b57cec5SDimitry Andric                 // reason.  We don't need to worry about stepping over the
18300b57cec5SDimitry Andric                 // breakpoint here, that will be taken care of when the thread
18310b57cec5SDimitry Andric                 // resumes and notices that there's a breakpoint under the pc.
18320b57cec5SDimitry Andric                 handled = true;
18330b57cec5SDimitry Andric                 if (bp_site_sp->ValidForThisThread(thread_sp.get())) {
18340b57cec5SDimitry Andric                   thread_sp->SetStopInfo(
18350b57cec5SDimitry Andric                       StopInfo::CreateStopReasonWithBreakpointSiteID(
18360b57cec5SDimitry Andric                           *thread_sp, bp_site_sp->GetID()));
18370b57cec5SDimitry Andric                 } else {
18380b57cec5SDimitry Andric                   StopInfoSP invalid_stop_info_sp;
18390b57cec5SDimitry Andric                   thread_sp->SetStopInfo(invalid_stop_info_sp);
18400b57cec5SDimitry Andric                 }
18410b57cec5SDimitry Andric               }
18420b57cec5SDimitry Andric             } else if (reason == "trap") {
18430b57cec5SDimitry Andric               // Let the trap just use the standard signal stop reason below...
18440b57cec5SDimitry Andric             } else if (reason == "watchpoint") {
18450b57cec5SDimitry Andric               StringExtractor desc_extractor(description.c_str());
18460b57cec5SDimitry Andric               addr_t wp_addr = desc_extractor.GetU64(LLDB_INVALID_ADDRESS);
18470b57cec5SDimitry Andric               uint32_t wp_index = desc_extractor.GetU32(LLDB_INVALID_INDEX32);
18480b57cec5SDimitry Andric               addr_t wp_hit_addr = desc_extractor.GetU64(LLDB_INVALID_ADDRESS);
18490b57cec5SDimitry Andric               watch_id_t watch_id = LLDB_INVALID_WATCH_ID;
18500b57cec5SDimitry Andric               if (wp_addr != LLDB_INVALID_ADDRESS) {
18510b57cec5SDimitry Andric                 WatchpointSP wp_sp;
18520b57cec5SDimitry Andric                 ArchSpec::Core core = GetTarget().GetArchitecture().GetCore();
18530b57cec5SDimitry Andric                 if ((core >= ArchSpec::kCore_mips_first &&
18540b57cec5SDimitry Andric                      core <= ArchSpec::kCore_mips_last) ||
18550b57cec5SDimitry Andric                     (core >= ArchSpec::eCore_arm_generic &&
18560b57cec5SDimitry Andric                      core <= ArchSpec::eCore_arm_aarch64))
18570b57cec5SDimitry Andric                   wp_sp = GetTarget().GetWatchpointList().FindByAddress(
18580b57cec5SDimitry Andric                       wp_hit_addr);
18590b57cec5SDimitry Andric                 if (!wp_sp)
18600b57cec5SDimitry Andric                   wp_sp =
18610b57cec5SDimitry Andric                       GetTarget().GetWatchpointList().FindByAddress(wp_addr);
18620b57cec5SDimitry Andric                 if (wp_sp) {
18630b57cec5SDimitry Andric                   wp_sp->SetHardwareIndex(wp_index);
18640b57cec5SDimitry Andric                   watch_id = wp_sp->GetID();
18650b57cec5SDimitry Andric                 }
18660b57cec5SDimitry Andric               }
18670b57cec5SDimitry Andric               if (watch_id == LLDB_INVALID_WATCH_ID) {
18680b57cec5SDimitry Andric                 Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(
18690b57cec5SDimitry Andric                     GDBR_LOG_WATCHPOINTS));
18709dba64beSDimitry Andric                 LLDB_LOGF(log, "failed to find watchpoint");
18710b57cec5SDimitry Andric               }
18720b57cec5SDimitry Andric               thread_sp->SetStopInfo(StopInfo::CreateStopReasonWithWatchpointID(
18730b57cec5SDimitry Andric                   *thread_sp, watch_id, wp_hit_addr));
18740b57cec5SDimitry Andric               handled = true;
18750b57cec5SDimitry Andric             } else if (reason == "exception") {
18760b57cec5SDimitry Andric               thread_sp->SetStopInfo(StopInfo::CreateStopReasonWithException(
18770b57cec5SDimitry Andric                   *thread_sp, description.c_str()));
18780b57cec5SDimitry Andric               handled = true;
18790b57cec5SDimitry Andric             } else if (reason == "exec") {
18800b57cec5SDimitry Andric               did_exec = true;
18810b57cec5SDimitry Andric               thread_sp->SetStopInfo(
18820b57cec5SDimitry Andric                   StopInfo::CreateStopReasonWithExec(*thread_sp));
18830b57cec5SDimitry Andric               handled = true;
18840b57cec5SDimitry Andric             }
18850b57cec5SDimitry Andric           } else if (!signo) {
18860b57cec5SDimitry Andric             addr_t pc = thread_sp->GetRegisterContext()->GetPC();
18870b57cec5SDimitry Andric             lldb::BreakpointSiteSP bp_site_sp =
18880b57cec5SDimitry Andric                 thread_sp->GetProcess()->GetBreakpointSiteList().FindByAddress(
18890b57cec5SDimitry Andric                     pc);
18900b57cec5SDimitry Andric 
18910b57cec5SDimitry Andric             // If the current pc is a breakpoint site then the StopInfo should
18920b57cec5SDimitry Andric             // be set to Breakpoint even though the remote stub did not set it
18930b57cec5SDimitry Andric             // as such. This can happen when the thread is involuntarily
18940b57cec5SDimitry Andric             // interrupted (e.g. due to stops on other threads) just as it is
18950b57cec5SDimitry Andric             // about to execute the breakpoint instruction.
18960b57cec5SDimitry Andric             if (bp_site_sp && bp_site_sp->ValidForThisThread(thread_sp.get())) {
18970b57cec5SDimitry Andric               thread_sp->SetStopInfo(
18980b57cec5SDimitry Andric                   StopInfo::CreateStopReasonWithBreakpointSiteID(
18990b57cec5SDimitry Andric                       *thread_sp, bp_site_sp->GetID()));
19000b57cec5SDimitry Andric               handled = true;
19010b57cec5SDimitry Andric             }
19020b57cec5SDimitry Andric           }
19030b57cec5SDimitry Andric 
19040b57cec5SDimitry Andric           if (!handled && signo && !did_exec) {
19050b57cec5SDimitry Andric             if (signo == SIGTRAP) {
19060b57cec5SDimitry Andric               // Currently we are going to assume SIGTRAP means we are either
19070b57cec5SDimitry Andric               // hitting a breakpoint or hardware single stepping.
19080b57cec5SDimitry Andric               handled = true;
19090b57cec5SDimitry Andric               addr_t pc = thread_sp->GetRegisterContext()->GetPC() +
19100b57cec5SDimitry Andric                           m_breakpoint_pc_offset;
19110b57cec5SDimitry Andric               lldb::BreakpointSiteSP bp_site_sp = thread_sp->GetProcess()
19120b57cec5SDimitry Andric                                                       ->GetBreakpointSiteList()
19130b57cec5SDimitry Andric                                                       .FindByAddress(pc);
19140b57cec5SDimitry Andric 
19150b57cec5SDimitry Andric               if (bp_site_sp) {
19160b57cec5SDimitry Andric                 // If the breakpoint is for this thread, then we'll report the
19170b57cec5SDimitry Andric                 // hit, but if it is for another thread, we can just report no
19180b57cec5SDimitry Andric                 // reason.  We don't need to worry about stepping over the
19190b57cec5SDimitry Andric                 // breakpoint here, that will be taken care of when the thread
19200b57cec5SDimitry Andric                 // resumes and notices that there's a breakpoint under the pc.
19210b57cec5SDimitry Andric                 if (bp_site_sp->ValidForThisThread(thread_sp.get())) {
19220b57cec5SDimitry Andric                   if (m_breakpoint_pc_offset != 0)
19230b57cec5SDimitry Andric                     thread_sp->GetRegisterContext()->SetPC(pc);
19240b57cec5SDimitry Andric                   thread_sp->SetStopInfo(
19250b57cec5SDimitry Andric                       StopInfo::CreateStopReasonWithBreakpointSiteID(
19260b57cec5SDimitry Andric                           *thread_sp, bp_site_sp->GetID()));
19270b57cec5SDimitry Andric                 } else {
19280b57cec5SDimitry Andric                   StopInfoSP invalid_stop_info_sp;
19290b57cec5SDimitry Andric                   thread_sp->SetStopInfo(invalid_stop_info_sp);
19300b57cec5SDimitry Andric                 }
19310b57cec5SDimitry Andric               } else {
19320b57cec5SDimitry Andric                 // If we were stepping then assume the stop was the result of
19330b57cec5SDimitry Andric                 // the trace.  If we were not stepping then report the SIGTRAP.
19340b57cec5SDimitry Andric                 // FIXME: We are still missing the case where we single step
19350b57cec5SDimitry Andric                 // over a trap instruction.
19360b57cec5SDimitry Andric                 if (thread_sp->GetTemporaryResumeState() == eStateStepping)
19370b57cec5SDimitry Andric                   thread_sp->SetStopInfo(
19380b57cec5SDimitry Andric                       StopInfo::CreateStopReasonToTrace(*thread_sp));
19390b57cec5SDimitry Andric                 else
19400b57cec5SDimitry Andric                   thread_sp->SetStopInfo(StopInfo::CreateStopReasonWithSignal(
19410b57cec5SDimitry Andric                       *thread_sp, signo, description.c_str()));
19420b57cec5SDimitry Andric               }
19430b57cec5SDimitry Andric             }
19440b57cec5SDimitry Andric             if (!handled)
19450b57cec5SDimitry Andric               thread_sp->SetStopInfo(StopInfo::CreateStopReasonWithSignal(
19460b57cec5SDimitry Andric                   *thread_sp, signo, description.c_str()));
19470b57cec5SDimitry Andric           }
19480b57cec5SDimitry Andric 
19490b57cec5SDimitry Andric           if (!description.empty()) {
19500b57cec5SDimitry Andric             lldb::StopInfoSP stop_info_sp(thread_sp->GetStopInfo());
19510b57cec5SDimitry Andric             if (stop_info_sp) {
19520b57cec5SDimitry Andric               const char *stop_info_desc = stop_info_sp->GetDescription();
19530b57cec5SDimitry Andric               if (!stop_info_desc || !stop_info_desc[0])
19540b57cec5SDimitry Andric                 stop_info_sp->SetDescription(description.c_str());
19550b57cec5SDimitry Andric             } else {
19560b57cec5SDimitry Andric               thread_sp->SetStopInfo(StopInfo::CreateStopReasonWithException(
19570b57cec5SDimitry Andric                   *thread_sp, description.c_str()));
19580b57cec5SDimitry Andric             }
19590b57cec5SDimitry Andric           }
19600b57cec5SDimitry Andric         }
19610b57cec5SDimitry Andric       }
19620b57cec5SDimitry Andric     }
19630b57cec5SDimitry Andric   }
19640b57cec5SDimitry Andric   return thread_sp;
19650b57cec5SDimitry Andric }
19660b57cec5SDimitry Andric 
19670b57cec5SDimitry Andric lldb::ThreadSP
19680b57cec5SDimitry Andric ProcessGDBRemote::SetThreadStopInfo(StructuredData::Dictionary *thread_dict) {
19690b57cec5SDimitry Andric   static ConstString g_key_tid("tid");
19700b57cec5SDimitry Andric   static ConstString g_key_name("name");
19710b57cec5SDimitry Andric   static ConstString g_key_reason("reason");
19720b57cec5SDimitry Andric   static ConstString g_key_metype("metype");
19730b57cec5SDimitry Andric   static ConstString g_key_medata("medata");
19740b57cec5SDimitry Andric   static ConstString g_key_qaddr("qaddr");
19750b57cec5SDimitry Andric   static ConstString g_key_dispatch_queue_t("dispatch_queue_t");
19760b57cec5SDimitry Andric   static ConstString g_key_associated_with_dispatch_queue(
19770b57cec5SDimitry Andric       "associated_with_dispatch_queue");
19780b57cec5SDimitry Andric   static ConstString g_key_queue_name("qname");
19790b57cec5SDimitry Andric   static ConstString g_key_queue_kind("qkind");
19800b57cec5SDimitry Andric   static ConstString g_key_queue_serial_number("qserialnum");
19810b57cec5SDimitry Andric   static ConstString g_key_registers("registers");
19820b57cec5SDimitry Andric   static ConstString g_key_memory("memory");
19830b57cec5SDimitry Andric   static ConstString g_key_address("address");
19840b57cec5SDimitry Andric   static ConstString g_key_bytes("bytes");
19850b57cec5SDimitry Andric   static ConstString g_key_description("description");
19860b57cec5SDimitry Andric   static ConstString g_key_signal("signal");
19870b57cec5SDimitry Andric 
19880b57cec5SDimitry Andric   // Stop with signal and thread info
19890b57cec5SDimitry Andric   lldb::tid_t tid = LLDB_INVALID_THREAD_ID;
19900b57cec5SDimitry Andric   uint8_t signo = 0;
19910b57cec5SDimitry Andric   std::string value;
19920b57cec5SDimitry Andric   std::string thread_name;
19930b57cec5SDimitry Andric   std::string reason;
19940b57cec5SDimitry Andric   std::string description;
19950b57cec5SDimitry Andric   uint32_t exc_type = 0;
19960b57cec5SDimitry Andric   std::vector<addr_t> exc_data;
19970b57cec5SDimitry Andric   addr_t thread_dispatch_qaddr = LLDB_INVALID_ADDRESS;
19980b57cec5SDimitry Andric   ExpeditedRegisterMap expedited_register_map;
19990b57cec5SDimitry Andric   bool queue_vars_valid = false;
20000b57cec5SDimitry Andric   addr_t dispatch_queue_t = LLDB_INVALID_ADDRESS;
20010b57cec5SDimitry Andric   LazyBool associated_with_dispatch_queue = eLazyBoolCalculate;
20020b57cec5SDimitry Andric   std::string queue_name;
20030b57cec5SDimitry Andric   QueueKind queue_kind = eQueueKindUnknown;
20040b57cec5SDimitry Andric   uint64_t queue_serial_number = 0;
20050b57cec5SDimitry Andric   // Iterate through all of the thread dictionary key/value pairs from the
20060b57cec5SDimitry Andric   // structured data dictionary
20070b57cec5SDimitry Andric 
20080b57cec5SDimitry Andric   thread_dict->ForEach([this, &tid, &expedited_register_map, &thread_name,
20090b57cec5SDimitry Andric                         &signo, &reason, &description, &exc_type, &exc_data,
20100b57cec5SDimitry Andric                         &thread_dispatch_qaddr, &queue_vars_valid,
20110b57cec5SDimitry Andric                         &associated_with_dispatch_queue, &dispatch_queue_t,
20120b57cec5SDimitry Andric                         &queue_name, &queue_kind, &queue_serial_number](
20130b57cec5SDimitry Andric                            ConstString key,
20140b57cec5SDimitry Andric                            StructuredData::Object *object) -> bool {
20150b57cec5SDimitry Andric     if (key == g_key_tid) {
20160b57cec5SDimitry Andric       // thread in big endian hex
20170b57cec5SDimitry Andric       tid = object->GetIntegerValue(LLDB_INVALID_THREAD_ID);
20180b57cec5SDimitry Andric     } else if (key == g_key_metype) {
20190b57cec5SDimitry Andric       // exception type in big endian hex
20200b57cec5SDimitry Andric       exc_type = object->GetIntegerValue(0);
20210b57cec5SDimitry Andric     } else if (key == g_key_medata) {
20220b57cec5SDimitry Andric       // exception data in big endian hex
20230b57cec5SDimitry Andric       StructuredData::Array *array = object->GetAsArray();
20240b57cec5SDimitry Andric       if (array) {
20250b57cec5SDimitry Andric         array->ForEach([&exc_data](StructuredData::Object *object) -> bool {
20260b57cec5SDimitry Andric           exc_data.push_back(object->GetIntegerValue());
20270b57cec5SDimitry Andric           return true; // Keep iterating through all array items
20280b57cec5SDimitry Andric         });
20290b57cec5SDimitry Andric       }
20300b57cec5SDimitry Andric     } else if (key == g_key_name) {
20315ffd83dbSDimitry Andric       thread_name = std::string(object->GetStringValue());
20320b57cec5SDimitry Andric     } else if (key == g_key_qaddr) {
20330b57cec5SDimitry Andric       thread_dispatch_qaddr = object->GetIntegerValue(LLDB_INVALID_ADDRESS);
20340b57cec5SDimitry Andric     } else if (key == g_key_queue_name) {
20350b57cec5SDimitry Andric       queue_vars_valid = true;
20365ffd83dbSDimitry Andric       queue_name = std::string(object->GetStringValue());
20370b57cec5SDimitry Andric     } else if (key == g_key_queue_kind) {
20385ffd83dbSDimitry Andric       std::string queue_kind_str = std::string(object->GetStringValue());
20390b57cec5SDimitry Andric       if (queue_kind_str == "serial") {
20400b57cec5SDimitry Andric         queue_vars_valid = true;
20410b57cec5SDimitry Andric         queue_kind = eQueueKindSerial;
20420b57cec5SDimitry Andric       } else if (queue_kind_str == "concurrent") {
20430b57cec5SDimitry Andric         queue_vars_valid = true;
20440b57cec5SDimitry Andric         queue_kind = eQueueKindConcurrent;
20450b57cec5SDimitry Andric       }
20460b57cec5SDimitry Andric     } else if (key == g_key_queue_serial_number) {
20470b57cec5SDimitry Andric       queue_serial_number = object->GetIntegerValue(0);
20480b57cec5SDimitry Andric       if (queue_serial_number != 0)
20490b57cec5SDimitry Andric         queue_vars_valid = true;
20500b57cec5SDimitry Andric     } else if (key == g_key_dispatch_queue_t) {
20510b57cec5SDimitry Andric       dispatch_queue_t = object->GetIntegerValue(0);
20520b57cec5SDimitry Andric       if (dispatch_queue_t != 0 && dispatch_queue_t != LLDB_INVALID_ADDRESS)
20530b57cec5SDimitry Andric         queue_vars_valid = true;
20540b57cec5SDimitry Andric     } else if (key == g_key_associated_with_dispatch_queue) {
20550b57cec5SDimitry Andric       queue_vars_valid = true;
20560b57cec5SDimitry Andric       bool associated = object->GetBooleanValue();
20570b57cec5SDimitry Andric       if (associated)
20580b57cec5SDimitry Andric         associated_with_dispatch_queue = eLazyBoolYes;
20590b57cec5SDimitry Andric       else
20600b57cec5SDimitry Andric         associated_with_dispatch_queue = eLazyBoolNo;
20610b57cec5SDimitry Andric     } else if (key == g_key_reason) {
20625ffd83dbSDimitry Andric       reason = std::string(object->GetStringValue());
20630b57cec5SDimitry Andric     } else if (key == g_key_description) {
20645ffd83dbSDimitry Andric       description = std::string(object->GetStringValue());
20650b57cec5SDimitry Andric     } else if (key == g_key_registers) {
20660b57cec5SDimitry Andric       StructuredData::Dictionary *registers_dict = object->GetAsDictionary();
20670b57cec5SDimitry Andric 
20680b57cec5SDimitry Andric       if (registers_dict) {
20690b57cec5SDimitry Andric         registers_dict->ForEach(
20700b57cec5SDimitry Andric             [&expedited_register_map](ConstString key,
20710b57cec5SDimitry Andric                                       StructuredData::Object *object) -> bool {
20720b57cec5SDimitry Andric               const uint32_t reg =
20730b57cec5SDimitry Andric                   StringConvert::ToUInt32(key.GetCString(), UINT32_MAX, 10);
20740b57cec5SDimitry Andric               if (reg != UINT32_MAX)
20755ffd83dbSDimitry Andric                 expedited_register_map[reg] =
20765ffd83dbSDimitry Andric                     std::string(object->GetStringValue());
20770b57cec5SDimitry Andric               return true; // Keep iterating through all array items
20780b57cec5SDimitry Andric             });
20790b57cec5SDimitry Andric       }
20800b57cec5SDimitry Andric     } else if (key == g_key_memory) {
20810b57cec5SDimitry Andric       StructuredData::Array *array = object->GetAsArray();
20820b57cec5SDimitry Andric       if (array) {
20830b57cec5SDimitry Andric         array->ForEach([this](StructuredData::Object *object) -> bool {
20840b57cec5SDimitry Andric           StructuredData::Dictionary *mem_cache_dict =
20850b57cec5SDimitry Andric               object->GetAsDictionary();
20860b57cec5SDimitry Andric           if (mem_cache_dict) {
20870b57cec5SDimitry Andric             lldb::addr_t mem_cache_addr = LLDB_INVALID_ADDRESS;
20880b57cec5SDimitry Andric             if (mem_cache_dict->GetValueForKeyAsInteger<lldb::addr_t>(
20890b57cec5SDimitry Andric                     "address", mem_cache_addr)) {
20900b57cec5SDimitry Andric               if (mem_cache_addr != LLDB_INVALID_ADDRESS) {
20910b57cec5SDimitry Andric                 llvm::StringRef str;
20920b57cec5SDimitry Andric                 if (mem_cache_dict->GetValueForKeyAsString("bytes", str)) {
20930b57cec5SDimitry Andric                   StringExtractor bytes(str);
20940b57cec5SDimitry Andric                   bytes.SetFilePos(0);
20950b57cec5SDimitry Andric 
20960b57cec5SDimitry Andric                   const size_t byte_size = bytes.GetStringRef().size() / 2;
20970b57cec5SDimitry Andric                   DataBufferSP data_buffer_sp(new DataBufferHeap(byte_size, 0));
20980b57cec5SDimitry Andric                   const size_t bytes_copied =
20990b57cec5SDimitry Andric                       bytes.GetHexBytes(data_buffer_sp->GetData(), 0);
21000b57cec5SDimitry Andric                   if (bytes_copied == byte_size)
21010b57cec5SDimitry Andric                     m_memory_cache.AddL1CacheData(mem_cache_addr,
21020b57cec5SDimitry Andric                                                   data_buffer_sp);
21030b57cec5SDimitry Andric                 }
21040b57cec5SDimitry Andric               }
21050b57cec5SDimitry Andric             }
21060b57cec5SDimitry Andric           }
21070b57cec5SDimitry Andric           return true; // Keep iterating through all array items
21080b57cec5SDimitry Andric         });
21090b57cec5SDimitry Andric       }
21100b57cec5SDimitry Andric 
21110b57cec5SDimitry Andric     } else if (key == g_key_signal)
21120b57cec5SDimitry Andric       signo = object->GetIntegerValue(LLDB_INVALID_SIGNAL_NUMBER);
21130b57cec5SDimitry Andric     return true; // Keep iterating through all dictionary key/value pairs
21140b57cec5SDimitry Andric   });
21150b57cec5SDimitry Andric 
21160b57cec5SDimitry Andric   return SetThreadStopInfo(tid, expedited_register_map, signo, thread_name,
21170b57cec5SDimitry Andric                            reason, description, exc_type, exc_data,
21180b57cec5SDimitry Andric                            thread_dispatch_qaddr, queue_vars_valid,
21190b57cec5SDimitry Andric                            associated_with_dispatch_queue, dispatch_queue_t,
21200b57cec5SDimitry Andric                            queue_name, queue_kind, queue_serial_number);
21210b57cec5SDimitry Andric }
21220b57cec5SDimitry Andric 
21230b57cec5SDimitry Andric StateType ProcessGDBRemote::SetThreadStopInfo(StringExtractor &stop_packet) {
21240b57cec5SDimitry Andric   stop_packet.SetFilePos(0);
21250b57cec5SDimitry Andric   const char stop_type = stop_packet.GetChar();
21260b57cec5SDimitry Andric   switch (stop_type) {
21270b57cec5SDimitry Andric   case 'T':
21280b57cec5SDimitry Andric   case 'S': {
21290b57cec5SDimitry Andric     // This is a bit of a hack, but is is required. If we did exec, we need to
21300b57cec5SDimitry Andric     // clear our thread lists and also know to rebuild our dynamic register
21310b57cec5SDimitry Andric     // info before we lookup and threads and populate the expedited register
21320b57cec5SDimitry Andric     // values so we need to know this right away so we can cleanup and update
21330b57cec5SDimitry Andric     // our registers.
21340b57cec5SDimitry Andric     const uint32_t stop_id = GetStopID();
21350b57cec5SDimitry Andric     if (stop_id == 0) {
21360b57cec5SDimitry Andric       // Our first stop, make sure we have a process ID, and also make sure we
21370b57cec5SDimitry Andric       // know about our registers
21380b57cec5SDimitry Andric       if (GetID() == LLDB_INVALID_PROCESS_ID) {
21390b57cec5SDimitry Andric         lldb::pid_t pid = m_gdb_comm.GetCurrentProcessID();
21400b57cec5SDimitry Andric         if (pid != LLDB_INVALID_PROCESS_ID)
21410b57cec5SDimitry Andric           SetID(pid);
21420b57cec5SDimitry Andric       }
21430b57cec5SDimitry Andric       BuildDynamicRegisterInfo(true);
21440b57cec5SDimitry Andric     }
21450b57cec5SDimitry Andric     // Stop with signal and thread info
21460b57cec5SDimitry Andric     lldb::tid_t tid = LLDB_INVALID_THREAD_ID;
21470b57cec5SDimitry Andric     const uint8_t signo = stop_packet.GetHexU8();
21480b57cec5SDimitry Andric     llvm::StringRef key;
21490b57cec5SDimitry Andric     llvm::StringRef value;
21500b57cec5SDimitry Andric     std::string thread_name;
21510b57cec5SDimitry Andric     std::string reason;
21520b57cec5SDimitry Andric     std::string description;
21530b57cec5SDimitry Andric     uint32_t exc_type = 0;
21540b57cec5SDimitry Andric     std::vector<addr_t> exc_data;
21550b57cec5SDimitry Andric     addr_t thread_dispatch_qaddr = LLDB_INVALID_ADDRESS;
21560b57cec5SDimitry Andric     bool queue_vars_valid =
21570b57cec5SDimitry Andric         false; // says if locals below that start with "queue_" are valid
21580b57cec5SDimitry Andric     addr_t dispatch_queue_t = LLDB_INVALID_ADDRESS;
21590b57cec5SDimitry Andric     LazyBool associated_with_dispatch_queue = eLazyBoolCalculate;
21600b57cec5SDimitry Andric     std::string queue_name;
21610b57cec5SDimitry Andric     QueueKind queue_kind = eQueueKindUnknown;
21620b57cec5SDimitry Andric     uint64_t queue_serial_number = 0;
21630b57cec5SDimitry Andric     ExpeditedRegisterMap expedited_register_map;
21640b57cec5SDimitry Andric     while (stop_packet.GetNameColonValue(key, value)) {
21650b57cec5SDimitry Andric       if (key.compare("metype") == 0) {
21660b57cec5SDimitry Andric         // exception type in big endian hex
21670b57cec5SDimitry Andric         value.getAsInteger(16, exc_type);
21680b57cec5SDimitry Andric       } else if (key.compare("medata") == 0) {
21690b57cec5SDimitry Andric         // exception data in big endian hex
21700b57cec5SDimitry Andric         uint64_t x;
21710b57cec5SDimitry Andric         value.getAsInteger(16, x);
21720b57cec5SDimitry Andric         exc_data.push_back(x);
21730b57cec5SDimitry Andric       } else if (key.compare("thread") == 0) {
21740b57cec5SDimitry Andric         // thread in big endian hex
21750b57cec5SDimitry Andric         if (value.getAsInteger(16, tid))
21760b57cec5SDimitry Andric           tid = LLDB_INVALID_THREAD_ID;
21770b57cec5SDimitry Andric       } else if (key.compare("threads") == 0) {
21780b57cec5SDimitry Andric         std::lock_guard<std::recursive_mutex> guard(
21790b57cec5SDimitry Andric             m_thread_list_real.GetMutex());
21800b57cec5SDimitry Andric 
21810b57cec5SDimitry Andric         m_thread_ids.clear();
21820b57cec5SDimitry Andric         // A comma separated list of all threads in the current
21830b57cec5SDimitry Andric         // process that includes the thread for this stop reply packet
21840b57cec5SDimitry Andric         lldb::tid_t tid;
21850b57cec5SDimitry Andric         while (!value.empty()) {
21860b57cec5SDimitry Andric           llvm::StringRef tid_str;
21870b57cec5SDimitry Andric           std::tie(tid_str, value) = value.split(',');
21880b57cec5SDimitry Andric           if (tid_str.getAsInteger(16, tid))
21890b57cec5SDimitry Andric             tid = LLDB_INVALID_THREAD_ID;
21900b57cec5SDimitry Andric           m_thread_ids.push_back(tid);
21910b57cec5SDimitry Andric         }
21920b57cec5SDimitry Andric       } else if (key.compare("thread-pcs") == 0) {
21930b57cec5SDimitry Andric         m_thread_pcs.clear();
21940b57cec5SDimitry Andric         // A comma separated list of all threads in the current
21950b57cec5SDimitry Andric         // process that includes the thread for this stop reply packet
21960b57cec5SDimitry Andric         lldb::addr_t pc;
21970b57cec5SDimitry Andric         while (!value.empty()) {
21980b57cec5SDimitry Andric           llvm::StringRef pc_str;
21990b57cec5SDimitry Andric           std::tie(pc_str, value) = value.split(',');
22000b57cec5SDimitry Andric           if (pc_str.getAsInteger(16, pc))
22010b57cec5SDimitry Andric             pc = LLDB_INVALID_ADDRESS;
22020b57cec5SDimitry Andric           m_thread_pcs.push_back(pc);
22030b57cec5SDimitry Andric         }
22040b57cec5SDimitry Andric       } else if (key.compare("jstopinfo") == 0) {
22050b57cec5SDimitry Andric         StringExtractor json_extractor(value);
22060b57cec5SDimitry Andric         std::string json;
22070b57cec5SDimitry Andric         // Now convert the HEX bytes into a string value
22080b57cec5SDimitry Andric         json_extractor.GetHexByteString(json);
22090b57cec5SDimitry Andric 
22100b57cec5SDimitry Andric         // This JSON contains thread IDs and thread stop info for all threads.
22110b57cec5SDimitry Andric         // It doesn't contain expedited registers, memory or queue info.
22120b57cec5SDimitry Andric         m_jstopinfo_sp = StructuredData::ParseJSON(json);
22130b57cec5SDimitry Andric       } else if (key.compare("hexname") == 0) {
22140b57cec5SDimitry Andric         StringExtractor name_extractor(value);
22150b57cec5SDimitry Andric         std::string name;
22160b57cec5SDimitry Andric         // Now convert the HEX bytes into a string value
22170b57cec5SDimitry Andric         name_extractor.GetHexByteString(thread_name);
22180b57cec5SDimitry Andric       } else if (key.compare("name") == 0) {
22195ffd83dbSDimitry Andric         thread_name = std::string(value);
22200b57cec5SDimitry Andric       } else if (key.compare("qaddr") == 0) {
22210b57cec5SDimitry Andric         value.getAsInteger(16, thread_dispatch_qaddr);
22220b57cec5SDimitry Andric       } else if (key.compare("dispatch_queue_t") == 0) {
22230b57cec5SDimitry Andric         queue_vars_valid = true;
22240b57cec5SDimitry Andric         value.getAsInteger(16, dispatch_queue_t);
22250b57cec5SDimitry Andric       } else if (key.compare("qname") == 0) {
22260b57cec5SDimitry Andric         queue_vars_valid = true;
22270b57cec5SDimitry Andric         StringExtractor name_extractor(value);
22280b57cec5SDimitry Andric         // Now convert the HEX bytes into a string value
22290b57cec5SDimitry Andric         name_extractor.GetHexByteString(queue_name);
22300b57cec5SDimitry Andric       } else if (key.compare("qkind") == 0) {
22310b57cec5SDimitry Andric         queue_kind = llvm::StringSwitch<QueueKind>(value)
22320b57cec5SDimitry Andric                          .Case("serial", eQueueKindSerial)
22330b57cec5SDimitry Andric                          .Case("concurrent", eQueueKindConcurrent)
22340b57cec5SDimitry Andric                          .Default(eQueueKindUnknown);
22350b57cec5SDimitry Andric         queue_vars_valid = queue_kind != eQueueKindUnknown;
22360b57cec5SDimitry Andric       } else if (key.compare("qserialnum") == 0) {
22370b57cec5SDimitry Andric         if (!value.getAsInteger(0, queue_serial_number))
22380b57cec5SDimitry Andric           queue_vars_valid = true;
22390b57cec5SDimitry Andric       } else if (key.compare("reason") == 0) {
22405ffd83dbSDimitry Andric         reason = std::string(value);
22410b57cec5SDimitry Andric       } else if (key.compare("description") == 0) {
22420b57cec5SDimitry Andric         StringExtractor desc_extractor(value);
22430b57cec5SDimitry Andric         // Now convert the HEX bytes into a string value
22440b57cec5SDimitry Andric         desc_extractor.GetHexByteString(description);
22450b57cec5SDimitry Andric       } else if (key.compare("memory") == 0) {
22460b57cec5SDimitry Andric         // Expedited memory. GDB servers can choose to send back expedited
22470b57cec5SDimitry Andric         // memory that can populate the L1 memory cache in the process so that
22480b57cec5SDimitry Andric         // things like the frame pointer backchain can be expedited. This will
22490b57cec5SDimitry Andric         // help stack backtracing be more efficient by not having to send as
22500b57cec5SDimitry Andric         // many memory read requests down the remote GDB server.
22510b57cec5SDimitry Andric 
22520b57cec5SDimitry Andric         // Key/value pair format: memory:<addr>=<bytes>;
22530b57cec5SDimitry Andric         // <addr> is a number whose base will be interpreted by the prefix:
22540b57cec5SDimitry Andric         //      "0x[0-9a-fA-F]+" for hex
22550b57cec5SDimitry Andric         //      "0[0-7]+" for octal
22560b57cec5SDimitry Andric         //      "[1-9]+" for decimal
22570b57cec5SDimitry Andric         // <bytes> is native endian ASCII hex bytes just like the register
22580b57cec5SDimitry Andric         // values
22590b57cec5SDimitry Andric         llvm::StringRef addr_str, bytes_str;
22600b57cec5SDimitry Andric         std::tie(addr_str, bytes_str) = value.split('=');
22610b57cec5SDimitry Andric         if (!addr_str.empty() && !bytes_str.empty()) {
22620b57cec5SDimitry Andric           lldb::addr_t mem_cache_addr = LLDB_INVALID_ADDRESS;
22630b57cec5SDimitry Andric           if (!addr_str.getAsInteger(0, mem_cache_addr)) {
22640b57cec5SDimitry Andric             StringExtractor bytes(bytes_str);
22650b57cec5SDimitry Andric             const size_t byte_size = bytes.GetBytesLeft() / 2;
22660b57cec5SDimitry Andric             DataBufferSP data_buffer_sp(new DataBufferHeap(byte_size, 0));
22670b57cec5SDimitry Andric             const size_t bytes_copied =
22680b57cec5SDimitry Andric                 bytes.GetHexBytes(data_buffer_sp->GetData(), 0);
22690b57cec5SDimitry Andric             if (bytes_copied == byte_size)
22700b57cec5SDimitry Andric               m_memory_cache.AddL1CacheData(mem_cache_addr, data_buffer_sp);
22710b57cec5SDimitry Andric           }
22720b57cec5SDimitry Andric         }
22730b57cec5SDimitry Andric       } else if (key.compare("watch") == 0 || key.compare("rwatch") == 0 ||
22740b57cec5SDimitry Andric                  key.compare("awatch") == 0) {
22750b57cec5SDimitry Andric         // Support standard GDB remote stop reply packet 'TAAwatch:addr'
22760b57cec5SDimitry Andric         lldb::addr_t wp_addr = LLDB_INVALID_ADDRESS;
22770b57cec5SDimitry Andric         value.getAsInteger(16, wp_addr);
22780b57cec5SDimitry Andric 
22790b57cec5SDimitry Andric         WatchpointSP wp_sp =
22800b57cec5SDimitry Andric             GetTarget().GetWatchpointList().FindByAddress(wp_addr);
22810b57cec5SDimitry Andric         uint32_t wp_index = LLDB_INVALID_INDEX32;
22820b57cec5SDimitry Andric 
22830b57cec5SDimitry Andric         if (wp_sp)
22840b57cec5SDimitry Andric           wp_index = wp_sp->GetHardwareIndex();
22850b57cec5SDimitry Andric 
22860b57cec5SDimitry Andric         reason = "watchpoint";
22870b57cec5SDimitry Andric         StreamString ostr;
22880b57cec5SDimitry Andric         ostr.Printf("%" PRIu64 " %" PRIu32, wp_addr, wp_index);
22895ffd83dbSDimitry Andric         description = std::string(ostr.GetString());
22900b57cec5SDimitry Andric       } else if (key.compare("library") == 0) {
22919dba64beSDimitry Andric         auto error = LoadModules();
22929dba64beSDimitry Andric         if (error) {
22939dba64beSDimitry Andric           Log *log(
22949dba64beSDimitry Andric               ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
22959dba64beSDimitry Andric           LLDB_LOG_ERROR(log, std::move(error), "Failed to load modules: {0}");
22969dba64beSDimitry Andric         }
22970b57cec5SDimitry Andric       } else if (key.size() == 2 && ::isxdigit(key[0]) && ::isxdigit(key[1])) {
22980b57cec5SDimitry Andric         uint32_t reg = UINT32_MAX;
22990b57cec5SDimitry Andric         if (!key.getAsInteger(16, reg))
23005ffd83dbSDimitry Andric           expedited_register_map[reg] = std::string(std::move(value));
23010b57cec5SDimitry Andric       }
23020b57cec5SDimitry Andric     }
23030b57cec5SDimitry Andric 
23040b57cec5SDimitry Andric     if (tid == LLDB_INVALID_THREAD_ID) {
23050b57cec5SDimitry Andric       // A thread id may be invalid if the response is old style 'S' packet
23060b57cec5SDimitry Andric       // which does not provide the
23070b57cec5SDimitry Andric       // thread information. So update the thread list and choose the first
23080b57cec5SDimitry Andric       // one.
23090b57cec5SDimitry Andric       UpdateThreadIDList();
23100b57cec5SDimitry Andric 
23110b57cec5SDimitry Andric       if (!m_thread_ids.empty()) {
23120b57cec5SDimitry Andric         tid = m_thread_ids.front();
23130b57cec5SDimitry Andric       }
23140b57cec5SDimitry Andric     }
23150b57cec5SDimitry Andric 
23160b57cec5SDimitry Andric     ThreadSP thread_sp = SetThreadStopInfo(
23170b57cec5SDimitry Andric         tid, expedited_register_map, signo, thread_name, reason, description,
23180b57cec5SDimitry Andric         exc_type, exc_data, thread_dispatch_qaddr, queue_vars_valid,
23190b57cec5SDimitry Andric         associated_with_dispatch_queue, dispatch_queue_t, queue_name,
23200b57cec5SDimitry Andric         queue_kind, queue_serial_number);
23210b57cec5SDimitry Andric 
23220b57cec5SDimitry Andric     return eStateStopped;
23230b57cec5SDimitry Andric   } break;
23240b57cec5SDimitry Andric 
23250b57cec5SDimitry Andric   case 'W':
23260b57cec5SDimitry Andric   case 'X':
23270b57cec5SDimitry Andric     // process exited
23280b57cec5SDimitry Andric     return eStateExited;
23290b57cec5SDimitry Andric 
23300b57cec5SDimitry Andric   default:
23310b57cec5SDimitry Andric     break;
23320b57cec5SDimitry Andric   }
23330b57cec5SDimitry Andric   return eStateInvalid;
23340b57cec5SDimitry Andric }
23350b57cec5SDimitry Andric 
23360b57cec5SDimitry Andric void ProcessGDBRemote::RefreshStateAfterStop() {
23370b57cec5SDimitry Andric   std::lock_guard<std::recursive_mutex> guard(m_thread_list_real.GetMutex());
23380b57cec5SDimitry Andric 
23390b57cec5SDimitry Andric   m_thread_ids.clear();
23400b57cec5SDimitry Andric   m_thread_pcs.clear();
2341480093f4SDimitry Andric 
23420b57cec5SDimitry Andric   // Set the thread stop info. It might have a "threads" key whose value is a
23430b57cec5SDimitry Andric   // list of all thread IDs in the current process, so m_thread_ids might get
23440b57cec5SDimitry Andric   // set.
23450b57cec5SDimitry Andric   // Check to see if SetThreadStopInfo() filled in m_thread_ids?
23460b57cec5SDimitry Andric   if (m_thread_ids.empty()) {
23470b57cec5SDimitry Andric       // No, we need to fetch the thread list manually
23480b57cec5SDimitry Andric       UpdateThreadIDList();
23490b57cec5SDimitry Andric   }
2350480093f4SDimitry Andric 
23510b57cec5SDimitry Andric   // We might set some stop info's so make sure the thread list is up to
23520b57cec5SDimitry Andric   // date before we do that or we might overwrite what was computed here.
23530b57cec5SDimitry Andric   UpdateThreadListIfNeeded();
23540b57cec5SDimitry Andric 
2355480093f4SDimitry Andric   // Scope for the lock
2356480093f4SDimitry Andric   {
23570b57cec5SDimitry Andric     // Lock the thread stack while we access it
23580b57cec5SDimitry Andric     std::lock_guard<std::recursive_mutex> guard(m_last_stop_packet_mutex);
23590b57cec5SDimitry Andric     // Get the number of stop packets on the stack
23600b57cec5SDimitry Andric     int nItems = m_stop_packet_stack.size();
23610b57cec5SDimitry Andric     // Iterate over them
23620b57cec5SDimitry Andric     for (int i = 0; i < nItems; i++) {
23630b57cec5SDimitry Andric       // Get the thread stop info
23640b57cec5SDimitry Andric       StringExtractorGDBRemote stop_info = m_stop_packet_stack[i];
23650b57cec5SDimitry Andric       // Process thread stop info
23660b57cec5SDimitry Andric       SetThreadStopInfo(stop_info);
23670b57cec5SDimitry Andric     }
23680b57cec5SDimitry Andric     // Clear the thread stop stack
23690b57cec5SDimitry Andric     m_stop_packet_stack.clear();
23700b57cec5SDimitry Andric   }
23710b57cec5SDimitry Andric 
23720b57cec5SDimitry Andric   // If we have queried for a default thread id
23730b57cec5SDimitry Andric   if (m_initial_tid != LLDB_INVALID_THREAD_ID) {
23740b57cec5SDimitry Andric     m_thread_list.SetSelectedThreadByID(m_initial_tid);
23750b57cec5SDimitry Andric     m_initial_tid = LLDB_INVALID_THREAD_ID;
23760b57cec5SDimitry Andric   }
23770b57cec5SDimitry Andric 
23780b57cec5SDimitry Andric   // Let all threads recover from stopping and do any clean up based on the
23790b57cec5SDimitry Andric   // previous thread state (if any).
23800b57cec5SDimitry Andric   m_thread_list_real.RefreshStateAfterStop();
23810b57cec5SDimitry Andric }
23820b57cec5SDimitry Andric 
23830b57cec5SDimitry Andric Status ProcessGDBRemote::DoHalt(bool &caused_stop) {
23840b57cec5SDimitry Andric   Status error;
23850b57cec5SDimitry Andric 
23860b57cec5SDimitry Andric   if (m_public_state.GetValue() == eStateAttaching) {
23870b57cec5SDimitry Andric     // We are being asked to halt during an attach. We need to just close our
23880b57cec5SDimitry Andric     // file handle and debugserver will go away, and we can be done...
23890b57cec5SDimitry Andric     m_gdb_comm.Disconnect();
23900b57cec5SDimitry Andric   } else
23910b57cec5SDimitry Andric     caused_stop = m_gdb_comm.Interrupt();
23920b57cec5SDimitry Andric   return error;
23930b57cec5SDimitry Andric }
23940b57cec5SDimitry Andric 
23950b57cec5SDimitry Andric Status ProcessGDBRemote::DoDetach(bool keep_stopped) {
23960b57cec5SDimitry Andric   Status error;
23970b57cec5SDimitry Andric   Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
23989dba64beSDimitry Andric   LLDB_LOGF(log, "ProcessGDBRemote::DoDetach(keep_stopped: %i)", keep_stopped);
23990b57cec5SDimitry Andric 
24000b57cec5SDimitry Andric   error = m_gdb_comm.Detach(keep_stopped);
24010b57cec5SDimitry Andric   if (log) {
24020b57cec5SDimitry Andric     if (error.Success())
24030b57cec5SDimitry Andric       log->PutCString(
24040b57cec5SDimitry Andric           "ProcessGDBRemote::DoDetach() detach packet sent successfully");
24050b57cec5SDimitry Andric     else
24069dba64beSDimitry Andric       LLDB_LOGF(log,
24079dba64beSDimitry Andric                 "ProcessGDBRemote::DoDetach() detach packet send failed: %s",
24080b57cec5SDimitry Andric                 error.AsCString() ? error.AsCString() : "<unknown error>");
24090b57cec5SDimitry Andric   }
24100b57cec5SDimitry Andric 
24110b57cec5SDimitry Andric   if (!error.Success())
24120b57cec5SDimitry Andric     return error;
24130b57cec5SDimitry Andric 
24140b57cec5SDimitry Andric   // Sleep for one second to let the process get all detached...
24150b57cec5SDimitry Andric   StopAsyncThread();
24160b57cec5SDimitry Andric 
24170b57cec5SDimitry Andric   SetPrivateState(eStateDetached);
24180b57cec5SDimitry Andric   ResumePrivateStateThread();
24190b57cec5SDimitry Andric 
24200b57cec5SDimitry Andric   // KillDebugserverProcess ();
24210b57cec5SDimitry Andric   return error;
24220b57cec5SDimitry Andric }
24230b57cec5SDimitry Andric 
24240b57cec5SDimitry Andric Status ProcessGDBRemote::DoDestroy() {
24250b57cec5SDimitry Andric   Status error;
24260b57cec5SDimitry Andric   Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
24279dba64beSDimitry Andric   LLDB_LOGF(log, "ProcessGDBRemote::DoDestroy()");
24280b57cec5SDimitry Andric 
2429*580012d6SDimitry Andric #ifdef LLDB_ENABLE_ALL // XXX Currently no iOS target support on FreeBSD
24300b57cec5SDimitry Andric   // There is a bug in older iOS debugservers where they don't shut down the
24310b57cec5SDimitry Andric   // process they are debugging properly.  If the process is sitting at a
24320b57cec5SDimitry Andric   // breakpoint or an exception, this can cause problems with restarting.  So
24330b57cec5SDimitry Andric   // we check to see if any of our threads are stopped at a breakpoint, and if
24340b57cec5SDimitry Andric   // so we remove all the breakpoints, resume the process, and THEN destroy it
24350b57cec5SDimitry Andric   // again.
24360b57cec5SDimitry Andric   //
24370b57cec5SDimitry Andric   // Note, we don't have a good way to test the version of debugserver, but I
24380b57cec5SDimitry Andric   // happen to know that the set of all the iOS debugservers which don't
24390b57cec5SDimitry Andric   // support GetThreadSuffixSupported() and that of the debugservers with this
24400b57cec5SDimitry Andric   // bug are equal.  There really should be a better way to test this!
24410b57cec5SDimitry Andric   //
24420b57cec5SDimitry Andric   // We also use m_destroy_tried_resuming to make sure we only do this once, if
24430b57cec5SDimitry Andric   // we resume and then halt and get called here to destroy again and we're
24440b57cec5SDimitry Andric   // still at a breakpoint or exception, then we should just do the straight-
24450b57cec5SDimitry Andric   // forward kill.
24460b57cec5SDimitry Andric   //
24470b57cec5SDimitry Andric   // And of course, if we weren't able to stop the process by the time we get
24480b57cec5SDimitry Andric   // here, it isn't necessary (or helpful) to do any of this.
24490b57cec5SDimitry Andric 
24500b57cec5SDimitry Andric   if (!m_gdb_comm.GetThreadSuffixSupported() &&
24510b57cec5SDimitry Andric       m_public_state.GetValue() != eStateRunning) {
24520b57cec5SDimitry Andric     PlatformSP platform_sp = GetTarget().GetPlatform();
24530b57cec5SDimitry Andric 
24540b57cec5SDimitry Andric     // FIXME: These should be ConstStrings so we aren't doing strcmp'ing.
24550b57cec5SDimitry Andric     if (platform_sp && platform_sp->GetName() &&
24560b57cec5SDimitry Andric         platform_sp->GetName() == PlatformRemoteiOS::GetPluginNameStatic()) {
24570b57cec5SDimitry Andric       if (m_destroy_tried_resuming) {
24580b57cec5SDimitry Andric         if (log)
24590b57cec5SDimitry Andric           log->PutCString("ProcessGDBRemote::DoDestroy() - Tried resuming to "
24600b57cec5SDimitry Andric                           "destroy once already, not doing it again.");
24610b57cec5SDimitry Andric       } else {
24620b57cec5SDimitry Andric         // At present, the plans are discarded and the breakpoints disabled
24630b57cec5SDimitry Andric         // Process::Destroy, but we really need it to happen here and it
24640b57cec5SDimitry Andric         // doesn't matter if we do it twice.
24650b57cec5SDimitry Andric         m_thread_list.DiscardThreadPlans();
24660b57cec5SDimitry Andric         DisableAllBreakpointSites();
24670b57cec5SDimitry Andric 
24680b57cec5SDimitry Andric         bool stop_looks_like_crash = false;
24690b57cec5SDimitry Andric         ThreadList &threads = GetThreadList();
24700b57cec5SDimitry Andric 
24710b57cec5SDimitry Andric         {
24720b57cec5SDimitry Andric           std::lock_guard<std::recursive_mutex> guard(threads.GetMutex());
24730b57cec5SDimitry Andric 
24740b57cec5SDimitry Andric           size_t num_threads = threads.GetSize();
24750b57cec5SDimitry Andric           for (size_t i = 0; i < num_threads; i++) {
24760b57cec5SDimitry Andric             ThreadSP thread_sp = threads.GetThreadAtIndex(i);
24770b57cec5SDimitry Andric             StopInfoSP stop_info_sp = thread_sp->GetPrivateStopInfo();
24780b57cec5SDimitry Andric             StopReason reason = eStopReasonInvalid;
24790b57cec5SDimitry Andric             if (stop_info_sp)
24800b57cec5SDimitry Andric               reason = stop_info_sp->GetStopReason();
24810b57cec5SDimitry Andric             if (reason == eStopReasonBreakpoint ||
24820b57cec5SDimitry Andric                 reason == eStopReasonException) {
24839dba64beSDimitry Andric               LLDB_LOGF(log,
24840b57cec5SDimitry Andric                         "ProcessGDBRemote::DoDestroy() - thread: 0x%4.4" PRIx64
24850b57cec5SDimitry Andric                         " stopped with reason: %s.",
24869dba64beSDimitry Andric                         thread_sp->GetProtocolID(),
24879dba64beSDimitry Andric                         stop_info_sp->GetDescription());
24880b57cec5SDimitry Andric               stop_looks_like_crash = true;
24890b57cec5SDimitry Andric               break;
24900b57cec5SDimitry Andric             }
24910b57cec5SDimitry Andric           }
24920b57cec5SDimitry Andric         }
24930b57cec5SDimitry Andric 
24940b57cec5SDimitry Andric         if (stop_looks_like_crash) {
24950b57cec5SDimitry Andric           if (log)
24960b57cec5SDimitry Andric             log->PutCString("ProcessGDBRemote::DoDestroy() - Stopped at a "
24970b57cec5SDimitry Andric                             "breakpoint, continue and then kill.");
24980b57cec5SDimitry Andric           m_destroy_tried_resuming = true;
24990b57cec5SDimitry Andric 
25000b57cec5SDimitry Andric           // If we are going to run again before killing, it would be good to
25010b57cec5SDimitry Andric           // suspend all the threads before resuming so they won't get into
25020b57cec5SDimitry Andric           // more trouble.  Sadly, for the threads stopped with the breakpoint
25030b57cec5SDimitry Andric           // or exception, the exception doesn't get cleared if it is
25040b57cec5SDimitry Andric           // suspended, so we do have to run the risk of letting those threads
25050b57cec5SDimitry Andric           // proceed a bit.
25060b57cec5SDimitry Andric 
25070b57cec5SDimitry Andric           {
25080b57cec5SDimitry Andric             std::lock_guard<std::recursive_mutex> guard(threads.GetMutex());
25090b57cec5SDimitry Andric 
25100b57cec5SDimitry Andric             size_t num_threads = threads.GetSize();
25110b57cec5SDimitry Andric             for (size_t i = 0; i < num_threads; i++) {
25120b57cec5SDimitry Andric               ThreadSP thread_sp = threads.GetThreadAtIndex(i);
25130b57cec5SDimitry Andric               StopInfoSP stop_info_sp = thread_sp->GetPrivateStopInfo();
25140b57cec5SDimitry Andric               StopReason reason = eStopReasonInvalid;
25150b57cec5SDimitry Andric               if (stop_info_sp)
25160b57cec5SDimitry Andric                 reason = stop_info_sp->GetStopReason();
25170b57cec5SDimitry Andric               if (reason != eStopReasonBreakpoint &&
25180b57cec5SDimitry Andric                   reason != eStopReasonException) {
25199dba64beSDimitry Andric                 LLDB_LOGF(log,
25209dba64beSDimitry Andric                           "ProcessGDBRemote::DoDestroy() - Suspending "
25210b57cec5SDimitry Andric                           "thread: 0x%4.4" PRIx64 " before running.",
25220b57cec5SDimitry Andric                           thread_sp->GetProtocolID());
25230b57cec5SDimitry Andric                 thread_sp->SetResumeState(eStateSuspended);
25240b57cec5SDimitry Andric               }
25250b57cec5SDimitry Andric             }
25260b57cec5SDimitry Andric           }
25270b57cec5SDimitry Andric           Resume();
25280b57cec5SDimitry Andric           return Destroy(false);
25290b57cec5SDimitry Andric         }
25300b57cec5SDimitry Andric       }
25310b57cec5SDimitry Andric     }
25320b57cec5SDimitry Andric   }
2533*580012d6SDimitry Andric #endif // LLDB_ENABLE_ALL
25340b57cec5SDimitry Andric 
25350b57cec5SDimitry Andric   // Interrupt if our inferior is running...
25360b57cec5SDimitry Andric   int exit_status = SIGABRT;
25370b57cec5SDimitry Andric   std::string exit_string;
25380b57cec5SDimitry Andric 
25390b57cec5SDimitry Andric   if (m_gdb_comm.IsConnected()) {
25400b57cec5SDimitry Andric     if (m_public_state.GetValue() != eStateAttaching) {
25410b57cec5SDimitry Andric       StringExtractorGDBRemote response;
25420b57cec5SDimitry Andric       bool send_async = true;
25430b57cec5SDimitry Andric       GDBRemoteCommunication::ScopedTimeout(m_gdb_comm,
25440b57cec5SDimitry Andric                                             std::chrono::seconds(3));
25450b57cec5SDimitry Andric 
25460b57cec5SDimitry Andric       if (m_gdb_comm.SendPacketAndWaitForResponse("k", response, send_async) ==
25470b57cec5SDimitry Andric           GDBRemoteCommunication::PacketResult::Success) {
25480b57cec5SDimitry Andric         char packet_cmd = response.GetChar(0);
25490b57cec5SDimitry Andric 
25500b57cec5SDimitry Andric         if (packet_cmd == 'W' || packet_cmd == 'X') {
25510b57cec5SDimitry Andric #if defined(__APPLE__)
25520b57cec5SDimitry Andric           // For Native processes on Mac OS X, we launch through the Host
25530b57cec5SDimitry Andric           // Platform, then hand the process off to debugserver, which becomes
25540b57cec5SDimitry Andric           // the parent process through "PT_ATTACH".  Then when we go to kill
25550b57cec5SDimitry Andric           // the process on Mac OS X we call ptrace(PT_KILL) to kill it, then
25560b57cec5SDimitry Andric           // we call waitpid which returns with no error and the correct
25570b57cec5SDimitry Andric           // status.  But amusingly enough that doesn't seem to actually reap
25580b57cec5SDimitry Andric           // the process, but instead it is left around as a Zombie.  Probably
25590b57cec5SDimitry Andric           // the kernel is in the process of switching ownership back to lldb
25600b57cec5SDimitry Andric           // which was the original parent, and gets confused in the handoff.
25610b57cec5SDimitry Andric           // Anyway, so call waitpid here to finally reap it.
25620b57cec5SDimitry Andric           PlatformSP platform_sp(GetTarget().GetPlatform());
25630b57cec5SDimitry Andric           if (platform_sp && platform_sp->IsHost()) {
25640b57cec5SDimitry Andric             int status;
25650b57cec5SDimitry Andric             ::pid_t reap_pid;
25660b57cec5SDimitry Andric             reap_pid = waitpid(GetID(), &status, WNOHANG);
25679dba64beSDimitry Andric             LLDB_LOGF(log, "Reaped pid: %d, status: %d.\n", reap_pid, status);
25680b57cec5SDimitry Andric           }
25690b57cec5SDimitry Andric #endif
25700b57cec5SDimitry Andric           SetLastStopPacket(response);
25710b57cec5SDimitry Andric           ClearThreadIDList();
25720b57cec5SDimitry Andric           exit_status = response.GetHexU8();
25730b57cec5SDimitry Andric         } else {
25749dba64beSDimitry Andric           LLDB_LOGF(log,
25759dba64beSDimitry Andric                     "ProcessGDBRemote::DoDestroy - got unexpected response "
25760b57cec5SDimitry Andric                     "to k packet: %s",
25779dba64beSDimitry Andric                     response.GetStringRef().data());
25780b57cec5SDimitry Andric           exit_string.assign("got unexpected response to k packet: ");
25795ffd83dbSDimitry Andric           exit_string.append(std::string(response.GetStringRef()));
25800b57cec5SDimitry Andric         }
25810b57cec5SDimitry Andric       } else {
25829dba64beSDimitry Andric         LLDB_LOGF(log, "ProcessGDBRemote::DoDestroy - failed to send k packet");
25830b57cec5SDimitry Andric         exit_string.assign("failed to send the k packet");
25840b57cec5SDimitry Andric       }
25850b57cec5SDimitry Andric     } else {
25869dba64beSDimitry Andric       LLDB_LOGF(log,
25879dba64beSDimitry Andric                 "ProcessGDBRemote::DoDestroy - killed or interrupted while "
25880b57cec5SDimitry Andric                 "attaching");
25890b57cec5SDimitry Andric       exit_string.assign("killed or interrupted while attaching.");
25900b57cec5SDimitry Andric     }
25910b57cec5SDimitry Andric   } else {
25920b57cec5SDimitry Andric     // If we missed setting the exit status on the way out, do it here.
25930b57cec5SDimitry Andric     // NB set exit status can be called multiple times, the first one sets the
25940b57cec5SDimitry Andric     // status.
25950b57cec5SDimitry Andric     exit_string.assign("destroying when not connected to debugserver");
25960b57cec5SDimitry Andric   }
25970b57cec5SDimitry Andric 
25980b57cec5SDimitry Andric   SetExitStatus(exit_status, exit_string.c_str());
25990b57cec5SDimitry Andric 
26000b57cec5SDimitry Andric   StopAsyncThread();
26010b57cec5SDimitry Andric   KillDebugserverProcess();
26020b57cec5SDimitry Andric   return error;
26030b57cec5SDimitry Andric }
26040b57cec5SDimitry Andric 
26050b57cec5SDimitry Andric void ProcessGDBRemote::SetLastStopPacket(
26060b57cec5SDimitry Andric     const StringExtractorGDBRemote &response) {
26070b57cec5SDimitry Andric   const bool did_exec =
26080b57cec5SDimitry Andric       response.GetStringRef().find(";reason:exec;") != std::string::npos;
26090b57cec5SDimitry Andric   if (did_exec) {
26100b57cec5SDimitry Andric     Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
26119dba64beSDimitry Andric     LLDB_LOGF(log, "ProcessGDBRemote::SetLastStopPacket () - detected exec");
26120b57cec5SDimitry Andric 
26130b57cec5SDimitry Andric     m_thread_list_real.Clear();
26140b57cec5SDimitry Andric     m_thread_list.Clear();
26150b57cec5SDimitry Andric     BuildDynamicRegisterInfo(true);
26160b57cec5SDimitry Andric     m_gdb_comm.ResetDiscoverableSettings(did_exec);
26170b57cec5SDimitry Andric   }
26180b57cec5SDimitry Andric 
26190b57cec5SDimitry Andric   // Scope the lock
26200b57cec5SDimitry Andric   {
26210b57cec5SDimitry Andric     // Lock the thread stack while we access it
26220b57cec5SDimitry Andric     std::lock_guard<std::recursive_mutex> guard(m_last_stop_packet_mutex);
26230b57cec5SDimitry Andric 
26240b57cec5SDimitry Andric     // We are are not using non-stop mode, there can only be one last stop
26250b57cec5SDimitry Andric     // reply packet, so clear the list.
26260b57cec5SDimitry Andric     if (!GetTarget().GetNonStopModeEnabled())
26270b57cec5SDimitry Andric       m_stop_packet_stack.clear();
26280b57cec5SDimitry Andric 
26290b57cec5SDimitry Andric     // Add this stop packet to the stop packet stack This stack will get popped
26300b57cec5SDimitry Andric     // and examined when we switch to the Stopped state
26310b57cec5SDimitry Andric     m_stop_packet_stack.push_back(response);
26320b57cec5SDimitry Andric   }
26330b57cec5SDimitry Andric }
26340b57cec5SDimitry Andric 
26350b57cec5SDimitry Andric void ProcessGDBRemote::SetUnixSignals(const UnixSignalsSP &signals_sp) {
26360b57cec5SDimitry Andric   Process::SetUnixSignals(std::make_shared<GDBRemoteSignals>(signals_sp));
26370b57cec5SDimitry Andric }
26380b57cec5SDimitry Andric 
26390b57cec5SDimitry Andric // Process Queries
26400b57cec5SDimitry Andric 
26410b57cec5SDimitry Andric bool ProcessGDBRemote::IsAlive() {
26420b57cec5SDimitry Andric   return m_gdb_comm.IsConnected() && Process::IsAlive();
26430b57cec5SDimitry Andric }
26440b57cec5SDimitry Andric 
26450b57cec5SDimitry Andric addr_t ProcessGDBRemote::GetImageInfoAddress() {
26460b57cec5SDimitry Andric   // request the link map address via the $qShlibInfoAddr packet
26470b57cec5SDimitry Andric   lldb::addr_t addr = m_gdb_comm.GetShlibInfoAddr();
26480b57cec5SDimitry Andric 
26490b57cec5SDimitry Andric   // the loaded module list can also provides a link map address
26500b57cec5SDimitry Andric   if (addr == LLDB_INVALID_ADDRESS) {
26519dba64beSDimitry Andric     llvm::Expected<LoadedModuleInfoList> list = GetLoadedModuleList();
26529dba64beSDimitry Andric     if (!list) {
26539dba64beSDimitry Andric       Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
26549dba64beSDimitry Andric       LLDB_LOG_ERROR(log, list.takeError(), "Failed to read module list: {0}");
26559dba64beSDimitry Andric     } else {
26569dba64beSDimitry Andric       addr = list->m_link_map;
26579dba64beSDimitry Andric     }
26580b57cec5SDimitry Andric   }
26590b57cec5SDimitry Andric 
26600b57cec5SDimitry Andric   return addr;
26610b57cec5SDimitry Andric }
26620b57cec5SDimitry Andric 
26630b57cec5SDimitry Andric void ProcessGDBRemote::WillPublicStop() {
26640b57cec5SDimitry Andric   // See if the GDB remote client supports the JSON threads info. If so, we
26650b57cec5SDimitry Andric   // gather stop info for all threads, expedited registers, expedited memory,
26660b57cec5SDimitry Andric   // runtime queue information (iOS and MacOSX only), and more. Expediting
26670b57cec5SDimitry Andric   // memory will help stack backtracing be much faster. Expediting registers
26680b57cec5SDimitry Andric   // will make sure we don't have to read the thread registers for GPRs.
26690b57cec5SDimitry Andric   m_jthreadsinfo_sp = m_gdb_comm.GetThreadsInfo();
26700b57cec5SDimitry Andric 
26710b57cec5SDimitry Andric   if (m_jthreadsinfo_sp) {
26720b57cec5SDimitry Andric     // Now set the stop info for each thread and also expedite any registers
26730b57cec5SDimitry Andric     // and memory that was in the jThreadsInfo response.
26740b57cec5SDimitry Andric     StructuredData::Array *thread_infos = m_jthreadsinfo_sp->GetAsArray();
26750b57cec5SDimitry Andric     if (thread_infos) {
26760b57cec5SDimitry Andric       const size_t n = thread_infos->GetSize();
26770b57cec5SDimitry Andric       for (size_t i = 0; i < n; ++i) {
26780b57cec5SDimitry Andric         StructuredData::Dictionary *thread_dict =
26790b57cec5SDimitry Andric             thread_infos->GetItemAtIndex(i)->GetAsDictionary();
26800b57cec5SDimitry Andric         if (thread_dict)
26810b57cec5SDimitry Andric           SetThreadStopInfo(thread_dict);
26820b57cec5SDimitry Andric       }
26830b57cec5SDimitry Andric     }
26840b57cec5SDimitry Andric   }
26850b57cec5SDimitry Andric }
26860b57cec5SDimitry Andric 
26870b57cec5SDimitry Andric // Process Memory
26880b57cec5SDimitry Andric size_t ProcessGDBRemote::DoReadMemory(addr_t addr, void *buf, size_t size,
26890b57cec5SDimitry Andric                                       Status &error) {
26900b57cec5SDimitry Andric   GetMaxMemorySize();
26910b57cec5SDimitry Andric   bool binary_memory_read = m_gdb_comm.GetxPacketSupported();
26920b57cec5SDimitry Andric   // M and m packets take 2 bytes for 1 byte of memory
26930b57cec5SDimitry Andric   size_t max_memory_size =
26940b57cec5SDimitry Andric       binary_memory_read ? m_max_memory_size : m_max_memory_size / 2;
26950b57cec5SDimitry Andric   if (size > max_memory_size) {
26960b57cec5SDimitry Andric     // Keep memory read sizes down to a sane limit. This function will be
26970b57cec5SDimitry Andric     // called multiple times in order to complete the task by
26980b57cec5SDimitry Andric     // lldb_private::Process so it is ok to do this.
26990b57cec5SDimitry Andric     size = max_memory_size;
27000b57cec5SDimitry Andric   }
27010b57cec5SDimitry Andric 
27020b57cec5SDimitry Andric   char packet[64];
27030b57cec5SDimitry Andric   int packet_len;
27040b57cec5SDimitry Andric   packet_len = ::snprintf(packet, sizeof(packet), "%c%" PRIx64 ",%" PRIx64,
27050b57cec5SDimitry Andric                           binary_memory_read ? 'x' : 'm', (uint64_t)addr,
27060b57cec5SDimitry Andric                           (uint64_t)size);
27070b57cec5SDimitry Andric   assert(packet_len + 1 < (int)sizeof(packet));
27080b57cec5SDimitry Andric   UNUSED_IF_ASSERT_DISABLED(packet_len);
27090b57cec5SDimitry Andric   StringExtractorGDBRemote response;
27100b57cec5SDimitry Andric   if (m_gdb_comm.SendPacketAndWaitForResponse(packet, response, true) ==
27110b57cec5SDimitry Andric       GDBRemoteCommunication::PacketResult::Success) {
27120b57cec5SDimitry Andric     if (response.IsNormalResponse()) {
27130b57cec5SDimitry Andric       error.Clear();
27140b57cec5SDimitry Andric       if (binary_memory_read) {
27150b57cec5SDimitry Andric         // The lower level GDBRemoteCommunication packet receive layer has
27160b57cec5SDimitry Andric         // already de-quoted any 0x7d character escaping that was present in
27170b57cec5SDimitry Andric         // the packet
27180b57cec5SDimitry Andric 
27190b57cec5SDimitry Andric         size_t data_received_size = response.GetBytesLeft();
27200b57cec5SDimitry Andric         if (data_received_size > size) {
27210b57cec5SDimitry Andric           // Don't write past the end of BUF if the remote debug server gave us
27220b57cec5SDimitry Andric           // too much data for some reason.
27230b57cec5SDimitry Andric           data_received_size = size;
27240b57cec5SDimitry Andric         }
27250b57cec5SDimitry Andric         memcpy(buf, response.GetStringRef().data(), data_received_size);
27260b57cec5SDimitry Andric         return data_received_size;
27270b57cec5SDimitry Andric       } else {
27280b57cec5SDimitry Andric         return response.GetHexBytes(
27290b57cec5SDimitry Andric             llvm::MutableArrayRef<uint8_t>((uint8_t *)buf, size), '\xdd');
27300b57cec5SDimitry Andric       }
27310b57cec5SDimitry Andric     } else if (response.IsErrorResponse())
27320b57cec5SDimitry Andric       error.SetErrorStringWithFormat("memory read failed for 0x%" PRIx64, addr);
27330b57cec5SDimitry Andric     else if (response.IsUnsupportedResponse())
27340b57cec5SDimitry Andric       error.SetErrorStringWithFormat(
27350b57cec5SDimitry Andric           "GDB server does not support reading memory");
27360b57cec5SDimitry Andric     else
27370b57cec5SDimitry Andric       error.SetErrorStringWithFormat(
27380b57cec5SDimitry Andric           "unexpected response to GDB server memory read packet '%s': '%s'",
27399dba64beSDimitry Andric           packet, response.GetStringRef().data());
27400b57cec5SDimitry Andric   } else {
27410b57cec5SDimitry Andric     error.SetErrorStringWithFormat("failed to send packet: '%s'", packet);
27420b57cec5SDimitry Andric   }
27430b57cec5SDimitry Andric   return 0;
27440b57cec5SDimitry Andric }
27450b57cec5SDimitry Andric 
27460b57cec5SDimitry Andric Status ProcessGDBRemote::WriteObjectFile(
27470b57cec5SDimitry Andric     std::vector<ObjectFile::LoadableData> entries) {
27480b57cec5SDimitry Andric   Status error;
27490b57cec5SDimitry Andric   // Sort the entries by address because some writes, like those to flash
27500b57cec5SDimitry Andric   // memory, must happen in order of increasing address.
27510b57cec5SDimitry Andric   std::stable_sort(
27520b57cec5SDimitry Andric       std::begin(entries), std::end(entries),
27530b57cec5SDimitry Andric       [](const ObjectFile::LoadableData a, const ObjectFile::LoadableData b) {
27540b57cec5SDimitry Andric         return a.Dest < b.Dest;
27550b57cec5SDimitry Andric       });
27560b57cec5SDimitry Andric   m_allow_flash_writes = true;
27570b57cec5SDimitry Andric   error = Process::WriteObjectFile(entries);
27580b57cec5SDimitry Andric   if (error.Success())
27590b57cec5SDimitry Andric     error = FlashDone();
27600b57cec5SDimitry Andric   else
27610b57cec5SDimitry Andric     // Even though some of the writing failed, try to send a flash done if some
27620b57cec5SDimitry Andric     // of the writing succeeded so the flash state is reset to normal, but
27630b57cec5SDimitry Andric     // don't stomp on the error status that was set in the write failure since
27640b57cec5SDimitry Andric     // that's the one we want to report back.
27650b57cec5SDimitry Andric     FlashDone();
27660b57cec5SDimitry Andric   m_allow_flash_writes = false;
27670b57cec5SDimitry Andric   return error;
27680b57cec5SDimitry Andric }
27690b57cec5SDimitry Andric 
27700b57cec5SDimitry Andric bool ProcessGDBRemote::HasErased(FlashRange range) {
27710b57cec5SDimitry Andric   auto size = m_erased_flash_ranges.GetSize();
27720b57cec5SDimitry Andric   for (size_t i = 0; i < size; ++i)
27730b57cec5SDimitry Andric     if (m_erased_flash_ranges.GetEntryAtIndex(i)->Contains(range))
27740b57cec5SDimitry Andric       return true;
27750b57cec5SDimitry Andric   return false;
27760b57cec5SDimitry Andric }
27770b57cec5SDimitry Andric 
27780b57cec5SDimitry Andric Status ProcessGDBRemote::FlashErase(lldb::addr_t addr, size_t size) {
27790b57cec5SDimitry Andric   Status status;
27800b57cec5SDimitry Andric 
27810b57cec5SDimitry Andric   MemoryRegionInfo region;
27820b57cec5SDimitry Andric   status = GetMemoryRegionInfo(addr, region);
27830b57cec5SDimitry Andric   if (!status.Success())
27840b57cec5SDimitry Andric     return status;
27850b57cec5SDimitry Andric 
27860b57cec5SDimitry Andric   // The gdb spec doesn't say if erasures are allowed across multiple regions,
27870b57cec5SDimitry Andric   // but we'll disallow it to be safe and to keep the logic simple by worring
27880b57cec5SDimitry Andric   // about only one region's block size.  DoMemoryWrite is this function's
27890b57cec5SDimitry Andric   // primary user, and it can easily keep writes within a single memory region
27900b57cec5SDimitry Andric   if (addr + size > region.GetRange().GetRangeEnd()) {
27910b57cec5SDimitry Andric     status.SetErrorString("Unable to erase flash in multiple regions");
27920b57cec5SDimitry Andric     return status;
27930b57cec5SDimitry Andric   }
27940b57cec5SDimitry Andric 
27950b57cec5SDimitry Andric   uint64_t blocksize = region.GetBlocksize();
27960b57cec5SDimitry Andric   if (blocksize == 0) {
27970b57cec5SDimitry Andric     status.SetErrorString("Unable to erase flash because blocksize is 0");
27980b57cec5SDimitry Andric     return status;
27990b57cec5SDimitry Andric   }
28000b57cec5SDimitry Andric 
28010b57cec5SDimitry Andric   // Erasures can only be done on block boundary adresses, so round down addr
28020b57cec5SDimitry Andric   // and round up size
28030b57cec5SDimitry Andric   lldb::addr_t block_start_addr = addr - (addr % blocksize);
28040b57cec5SDimitry Andric   size += (addr - block_start_addr);
28050b57cec5SDimitry Andric   if ((size % blocksize) != 0)
28060b57cec5SDimitry Andric     size += (blocksize - size % blocksize);
28070b57cec5SDimitry Andric 
28080b57cec5SDimitry Andric   FlashRange range(block_start_addr, size);
28090b57cec5SDimitry Andric 
28100b57cec5SDimitry Andric   if (HasErased(range))
28110b57cec5SDimitry Andric     return status;
28120b57cec5SDimitry Andric 
28130b57cec5SDimitry Andric   // We haven't erased the entire range, but we may have erased part of it.
28140b57cec5SDimitry Andric   // (e.g., block A is already erased and range starts in A and ends in B). So,
28150b57cec5SDimitry Andric   // adjust range if necessary to exclude already erased blocks.
28160b57cec5SDimitry Andric   if (!m_erased_flash_ranges.IsEmpty()) {
28170b57cec5SDimitry Andric     // Assuming that writes and erasures are done in increasing addr order,
28180b57cec5SDimitry Andric     // because that is a requirement of the vFlashWrite command.  Therefore, we
28190b57cec5SDimitry Andric     // only need to look at the last range in the list for overlap.
28200b57cec5SDimitry Andric     const auto &last_range = *m_erased_flash_ranges.Back();
28210b57cec5SDimitry Andric     if (range.GetRangeBase() < last_range.GetRangeEnd()) {
28220b57cec5SDimitry Andric       auto overlap = last_range.GetRangeEnd() - range.GetRangeBase();
28230b57cec5SDimitry Andric       // overlap will be less than range.GetByteSize() or else HasErased()
28240b57cec5SDimitry Andric       // would have been true
28250b57cec5SDimitry Andric       range.SetByteSize(range.GetByteSize() - overlap);
28260b57cec5SDimitry Andric       range.SetRangeBase(range.GetRangeBase() + overlap);
28270b57cec5SDimitry Andric     }
28280b57cec5SDimitry Andric   }
28290b57cec5SDimitry Andric 
28300b57cec5SDimitry Andric   StreamString packet;
28310b57cec5SDimitry Andric   packet.Printf("vFlashErase:%" PRIx64 ",%" PRIx64, range.GetRangeBase(),
28320b57cec5SDimitry Andric                 (uint64_t)range.GetByteSize());
28330b57cec5SDimitry Andric 
28340b57cec5SDimitry Andric   StringExtractorGDBRemote response;
28350b57cec5SDimitry Andric   if (m_gdb_comm.SendPacketAndWaitForResponse(packet.GetString(), response,
28360b57cec5SDimitry Andric                                               true) ==
28370b57cec5SDimitry Andric       GDBRemoteCommunication::PacketResult::Success) {
28380b57cec5SDimitry Andric     if (response.IsOKResponse()) {
28390b57cec5SDimitry Andric       m_erased_flash_ranges.Insert(range, true);
28400b57cec5SDimitry Andric     } else {
28410b57cec5SDimitry Andric       if (response.IsErrorResponse())
28420b57cec5SDimitry Andric         status.SetErrorStringWithFormat("flash erase failed for 0x%" PRIx64,
28430b57cec5SDimitry Andric                                         addr);
28440b57cec5SDimitry Andric       else if (response.IsUnsupportedResponse())
28450b57cec5SDimitry Andric         status.SetErrorStringWithFormat("GDB server does not support flashing");
28460b57cec5SDimitry Andric       else
28470b57cec5SDimitry Andric         status.SetErrorStringWithFormat(
28480b57cec5SDimitry Andric             "unexpected response to GDB server flash erase packet '%s': '%s'",
28499dba64beSDimitry Andric             packet.GetData(), response.GetStringRef().data());
28500b57cec5SDimitry Andric     }
28510b57cec5SDimitry Andric   } else {
28520b57cec5SDimitry Andric     status.SetErrorStringWithFormat("failed to send packet: '%s'",
28530b57cec5SDimitry Andric                                     packet.GetData());
28540b57cec5SDimitry Andric   }
28550b57cec5SDimitry Andric   return status;
28560b57cec5SDimitry Andric }
28570b57cec5SDimitry Andric 
28580b57cec5SDimitry Andric Status ProcessGDBRemote::FlashDone() {
28590b57cec5SDimitry Andric   Status status;
28600b57cec5SDimitry Andric   // If we haven't erased any blocks, then we must not have written anything
28610b57cec5SDimitry Andric   // either, so there is no need to actually send a vFlashDone command
28620b57cec5SDimitry Andric   if (m_erased_flash_ranges.IsEmpty())
28630b57cec5SDimitry Andric     return status;
28640b57cec5SDimitry Andric   StringExtractorGDBRemote response;
28650b57cec5SDimitry Andric   if (m_gdb_comm.SendPacketAndWaitForResponse("vFlashDone", response, true) ==
28660b57cec5SDimitry Andric       GDBRemoteCommunication::PacketResult::Success) {
28670b57cec5SDimitry Andric     if (response.IsOKResponse()) {
28680b57cec5SDimitry Andric       m_erased_flash_ranges.Clear();
28690b57cec5SDimitry Andric     } else {
28700b57cec5SDimitry Andric       if (response.IsErrorResponse())
28710b57cec5SDimitry Andric         status.SetErrorStringWithFormat("flash done failed");
28720b57cec5SDimitry Andric       else if (response.IsUnsupportedResponse())
28730b57cec5SDimitry Andric         status.SetErrorStringWithFormat("GDB server does not support flashing");
28740b57cec5SDimitry Andric       else
28750b57cec5SDimitry Andric         status.SetErrorStringWithFormat(
28760b57cec5SDimitry Andric             "unexpected response to GDB server flash done packet: '%s'",
28779dba64beSDimitry Andric             response.GetStringRef().data());
28780b57cec5SDimitry Andric     }
28790b57cec5SDimitry Andric   } else {
28800b57cec5SDimitry Andric     status.SetErrorStringWithFormat("failed to send flash done packet");
28810b57cec5SDimitry Andric   }
28820b57cec5SDimitry Andric   return status;
28830b57cec5SDimitry Andric }
28840b57cec5SDimitry Andric 
28850b57cec5SDimitry Andric size_t ProcessGDBRemote::DoWriteMemory(addr_t addr, const void *buf,
28860b57cec5SDimitry Andric                                        size_t size, Status &error) {
28870b57cec5SDimitry Andric   GetMaxMemorySize();
28880b57cec5SDimitry Andric   // M and m packets take 2 bytes for 1 byte of memory
28890b57cec5SDimitry Andric   size_t max_memory_size = m_max_memory_size / 2;
28900b57cec5SDimitry Andric   if (size > max_memory_size) {
28910b57cec5SDimitry Andric     // Keep memory read sizes down to a sane limit. This function will be
28920b57cec5SDimitry Andric     // called multiple times in order to complete the task by
28930b57cec5SDimitry Andric     // lldb_private::Process so it is ok to do this.
28940b57cec5SDimitry Andric     size = max_memory_size;
28950b57cec5SDimitry Andric   }
28960b57cec5SDimitry Andric 
28970b57cec5SDimitry Andric   StreamGDBRemote packet;
28980b57cec5SDimitry Andric 
28990b57cec5SDimitry Andric   MemoryRegionInfo region;
29000b57cec5SDimitry Andric   Status region_status = GetMemoryRegionInfo(addr, region);
29010b57cec5SDimitry Andric 
29020b57cec5SDimitry Andric   bool is_flash =
29030b57cec5SDimitry Andric       region_status.Success() && region.GetFlash() == MemoryRegionInfo::eYes;
29040b57cec5SDimitry Andric 
29050b57cec5SDimitry Andric   if (is_flash) {
29060b57cec5SDimitry Andric     if (!m_allow_flash_writes) {
29070b57cec5SDimitry Andric       error.SetErrorString("Writing to flash memory is not allowed");
29080b57cec5SDimitry Andric       return 0;
29090b57cec5SDimitry Andric     }
29100b57cec5SDimitry Andric     // Keep the write within a flash memory region
29110b57cec5SDimitry Andric     if (addr + size > region.GetRange().GetRangeEnd())
29120b57cec5SDimitry Andric       size = region.GetRange().GetRangeEnd() - addr;
29130b57cec5SDimitry Andric     // Flash memory must be erased before it can be written
29140b57cec5SDimitry Andric     error = FlashErase(addr, size);
29150b57cec5SDimitry Andric     if (!error.Success())
29160b57cec5SDimitry Andric       return 0;
29170b57cec5SDimitry Andric     packet.Printf("vFlashWrite:%" PRIx64 ":", addr);
29180b57cec5SDimitry Andric     packet.PutEscapedBytes(buf, size);
29190b57cec5SDimitry Andric   } else {
29200b57cec5SDimitry Andric     packet.Printf("M%" PRIx64 ",%" PRIx64 ":", addr, (uint64_t)size);
29210b57cec5SDimitry Andric     packet.PutBytesAsRawHex8(buf, size, endian::InlHostByteOrder(),
29220b57cec5SDimitry Andric                              endian::InlHostByteOrder());
29230b57cec5SDimitry Andric   }
29240b57cec5SDimitry Andric   StringExtractorGDBRemote response;
29250b57cec5SDimitry Andric   if (m_gdb_comm.SendPacketAndWaitForResponse(packet.GetString(), response,
29260b57cec5SDimitry Andric                                               true) ==
29270b57cec5SDimitry Andric       GDBRemoteCommunication::PacketResult::Success) {
29280b57cec5SDimitry Andric     if (response.IsOKResponse()) {
29290b57cec5SDimitry Andric       error.Clear();
29300b57cec5SDimitry Andric       return size;
29310b57cec5SDimitry Andric     } else if (response.IsErrorResponse())
29320b57cec5SDimitry Andric       error.SetErrorStringWithFormat("memory write failed for 0x%" PRIx64,
29330b57cec5SDimitry Andric                                      addr);
29340b57cec5SDimitry Andric     else if (response.IsUnsupportedResponse())
29350b57cec5SDimitry Andric       error.SetErrorStringWithFormat(
29360b57cec5SDimitry Andric           "GDB server does not support writing memory");
29370b57cec5SDimitry Andric     else
29380b57cec5SDimitry Andric       error.SetErrorStringWithFormat(
29390b57cec5SDimitry Andric           "unexpected response to GDB server memory write packet '%s': '%s'",
29409dba64beSDimitry Andric           packet.GetData(), response.GetStringRef().data());
29410b57cec5SDimitry Andric   } else {
29420b57cec5SDimitry Andric     error.SetErrorStringWithFormat("failed to send packet: '%s'",
29430b57cec5SDimitry Andric                                    packet.GetData());
29440b57cec5SDimitry Andric   }
29450b57cec5SDimitry Andric   return 0;
29460b57cec5SDimitry Andric }
29470b57cec5SDimitry Andric 
29480b57cec5SDimitry Andric lldb::addr_t ProcessGDBRemote::DoAllocateMemory(size_t size,
29490b57cec5SDimitry Andric                                                 uint32_t permissions,
29500b57cec5SDimitry Andric                                                 Status &error) {
29510b57cec5SDimitry Andric   Log *log(
29520b57cec5SDimitry Andric       GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS | LIBLLDB_LOG_EXPRESSIONS));
29530b57cec5SDimitry Andric   addr_t allocated_addr = LLDB_INVALID_ADDRESS;
29540b57cec5SDimitry Andric 
29550b57cec5SDimitry Andric   if (m_gdb_comm.SupportsAllocDeallocMemory() != eLazyBoolNo) {
29560b57cec5SDimitry Andric     allocated_addr = m_gdb_comm.AllocateMemory(size, permissions);
29570b57cec5SDimitry Andric     if (allocated_addr != LLDB_INVALID_ADDRESS ||
29580b57cec5SDimitry Andric         m_gdb_comm.SupportsAllocDeallocMemory() == eLazyBoolYes)
29590b57cec5SDimitry Andric       return allocated_addr;
29600b57cec5SDimitry Andric   }
29610b57cec5SDimitry Andric 
29620b57cec5SDimitry Andric   if (m_gdb_comm.SupportsAllocDeallocMemory() == eLazyBoolNo) {
29630b57cec5SDimitry Andric     // Call mmap() to create memory in the inferior..
29640b57cec5SDimitry Andric     unsigned prot = 0;
29650b57cec5SDimitry Andric     if (permissions & lldb::ePermissionsReadable)
29660b57cec5SDimitry Andric       prot |= eMmapProtRead;
29670b57cec5SDimitry Andric     if (permissions & lldb::ePermissionsWritable)
29680b57cec5SDimitry Andric       prot |= eMmapProtWrite;
29690b57cec5SDimitry Andric     if (permissions & lldb::ePermissionsExecutable)
29700b57cec5SDimitry Andric       prot |= eMmapProtExec;
29710b57cec5SDimitry Andric 
29720b57cec5SDimitry Andric     if (InferiorCallMmap(this, allocated_addr, 0, size, prot,
29730b57cec5SDimitry Andric                          eMmapFlagsAnon | eMmapFlagsPrivate, -1, 0))
29740b57cec5SDimitry Andric       m_addr_to_mmap_size[allocated_addr] = size;
29750b57cec5SDimitry Andric     else {
29760b57cec5SDimitry Andric       allocated_addr = LLDB_INVALID_ADDRESS;
29779dba64beSDimitry Andric       LLDB_LOGF(log,
29789dba64beSDimitry Andric                 "ProcessGDBRemote::%s no direct stub support for memory "
29790b57cec5SDimitry Andric                 "allocation, and InferiorCallMmap also failed - is stub "
29800b57cec5SDimitry Andric                 "missing register context save/restore capability?",
29810b57cec5SDimitry Andric                 __FUNCTION__);
29820b57cec5SDimitry Andric     }
29830b57cec5SDimitry Andric   }
29840b57cec5SDimitry Andric 
29850b57cec5SDimitry Andric   if (allocated_addr == LLDB_INVALID_ADDRESS)
29860b57cec5SDimitry Andric     error.SetErrorStringWithFormat(
29870b57cec5SDimitry Andric         "unable to allocate %" PRIu64 " bytes of memory with permissions %s",
29880b57cec5SDimitry Andric         (uint64_t)size, GetPermissionsAsCString(permissions));
29890b57cec5SDimitry Andric   else
29900b57cec5SDimitry Andric     error.Clear();
29910b57cec5SDimitry Andric   return allocated_addr;
29920b57cec5SDimitry Andric }
29930b57cec5SDimitry Andric 
29940b57cec5SDimitry Andric Status ProcessGDBRemote::GetMemoryRegionInfo(addr_t load_addr,
29950b57cec5SDimitry Andric                                              MemoryRegionInfo &region_info) {
29960b57cec5SDimitry Andric 
29970b57cec5SDimitry Andric   Status error(m_gdb_comm.GetMemoryRegionInfo(load_addr, region_info));
29980b57cec5SDimitry Andric   return error;
29990b57cec5SDimitry Andric }
30000b57cec5SDimitry Andric 
30010b57cec5SDimitry Andric Status ProcessGDBRemote::GetWatchpointSupportInfo(uint32_t &num) {
30020b57cec5SDimitry Andric 
30030b57cec5SDimitry Andric   Status error(m_gdb_comm.GetWatchpointSupportInfo(num));
30040b57cec5SDimitry Andric   return error;
30050b57cec5SDimitry Andric }
30060b57cec5SDimitry Andric 
30070b57cec5SDimitry Andric Status ProcessGDBRemote::GetWatchpointSupportInfo(uint32_t &num, bool &after) {
30080b57cec5SDimitry Andric   Status error(m_gdb_comm.GetWatchpointSupportInfo(
30090b57cec5SDimitry Andric       num, after, GetTarget().GetArchitecture()));
30100b57cec5SDimitry Andric   return error;
30110b57cec5SDimitry Andric }
30120b57cec5SDimitry Andric 
30130b57cec5SDimitry Andric Status ProcessGDBRemote::DoDeallocateMemory(lldb::addr_t addr) {
30140b57cec5SDimitry Andric   Status error;
30150b57cec5SDimitry Andric   LazyBool supported = m_gdb_comm.SupportsAllocDeallocMemory();
30160b57cec5SDimitry Andric 
30170b57cec5SDimitry Andric   switch (supported) {
30180b57cec5SDimitry Andric   case eLazyBoolCalculate:
30190b57cec5SDimitry Andric     // We should never be deallocating memory without allocating memory first
30200b57cec5SDimitry Andric     // so we should never get eLazyBoolCalculate
30210b57cec5SDimitry Andric     error.SetErrorString(
30220b57cec5SDimitry Andric         "tried to deallocate memory without ever allocating memory");
30230b57cec5SDimitry Andric     break;
30240b57cec5SDimitry Andric 
30250b57cec5SDimitry Andric   case eLazyBoolYes:
30260b57cec5SDimitry Andric     if (!m_gdb_comm.DeallocateMemory(addr))
30270b57cec5SDimitry Andric       error.SetErrorStringWithFormat(
30280b57cec5SDimitry Andric           "unable to deallocate memory at 0x%" PRIx64, addr);
30290b57cec5SDimitry Andric     break;
30300b57cec5SDimitry Andric 
30310b57cec5SDimitry Andric   case eLazyBoolNo:
30320b57cec5SDimitry Andric     // Call munmap() to deallocate memory in the inferior..
30330b57cec5SDimitry Andric     {
30340b57cec5SDimitry Andric       MMapMap::iterator pos = m_addr_to_mmap_size.find(addr);
30350b57cec5SDimitry Andric       if (pos != m_addr_to_mmap_size.end() &&
30360b57cec5SDimitry Andric           InferiorCallMunmap(this, addr, pos->second))
30370b57cec5SDimitry Andric         m_addr_to_mmap_size.erase(pos);
30380b57cec5SDimitry Andric       else
30390b57cec5SDimitry Andric         error.SetErrorStringWithFormat(
30400b57cec5SDimitry Andric             "unable to deallocate memory at 0x%" PRIx64, addr);
30410b57cec5SDimitry Andric     }
30420b57cec5SDimitry Andric     break;
30430b57cec5SDimitry Andric   }
30440b57cec5SDimitry Andric 
30450b57cec5SDimitry Andric   return error;
30460b57cec5SDimitry Andric }
30470b57cec5SDimitry Andric 
30480b57cec5SDimitry Andric // Process STDIO
30490b57cec5SDimitry Andric size_t ProcessGDBRemote::PutSTDIN(const char *src, size_t src_len,
30500b57cec5SDimitry Andric                                   Status &error) {
30510b57cec5SDimitry Andric   if (m_stdio_communication.IsConnected()) {
30520b57cec5SDimitry Andric     ConnectionStatus status;
30530b57cec5SDimitry Andric     m_stdio_communication.Write(src, src_len, status, nullptr);
30540b57cec5SDimitry Andric   } else if (m_stdin_forward) {
30550b57cec5SDimitry Andric     m_gdb_comm.SendStdinNotification(src, src_len);
30560b57cec5SDimitry Andric   }
30570b57cec5SDimitry Andric   return 0;
30580b57cec5SDimitry Andric }
30590b57cec5SDimitry Andric 
30600b57cec5SDimitry Andric Status ProcessGDBRemote::EnableBreakpointSite(BreakpointSite *bp_site) {
30610b57cec5SDimitry Andric   Status error;
30620b57cec5SDimitry Andric   assert(bp_site != nullptr);
30630b57cec5SDimitry Andric 
30640b57cec5SDimitry Andric   // Get logging info
30650b57cec5SDimitry Andric   Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_BREAKPOINTS));
30660b57cec5SDimitry Andric   user_id_t site_id = bp_site->GetID();
30670b57cec5SDimitry Andric 
30680b57cec5SDimitry Andric   // Get the breakpoint address
30690b57cec5SDimitry Andric   const addr_t addr = bp_site->GetLoadAddress();
30700b57cec5SDimitry Andric 
30710b57cec5SDimitry Andric   // Log that a breakpoint was requested
30729dba64beSDimitry Andric   LLDB_LOGF(log,
30739dba64beSDimitry Andric             "ProcessGDBRemote::EnableBreakpointSite (size_id = %" PRIu64
30740b57cec5SDimitry Andric             ") address = 0x%" PRIx64,
30750b57cec5SDimitry Andric             site_id, (uint64_t)addr);
30760b57cec5SDimitry Andric 
30770b57cec5SDimitry Andric   // Breakpoint already exists and is enabled
30780b57cec5SDimitry Andric   if (bp_site->IsEnabled()) {
30799dba64beSDimitry Andric     LLDB_LOGF(log,
30809dba64beSDimitry Andric               "ProcessGDBRemote::EnableBreakpointSite (size_id = %" PRIu64
30810b57cec5SDimitry Andric               ") address = 0x%" PRIx64 " -- SUCCESS (already enabled)",
30820b57cec5SDimitry Andric               site_id, (uint64_t)addr);
30830b57cec5SDimitry Andric     return error;
30840b57cec5SDimitry Andric   }
30850b57cec5SDimitry Andric 
30860b57cec5SDimitry Andric   // Get the software breakpoint trap opcode size
30870b57cec5SDimitry Andric   const size_t bp_op_size = GetSoftwareBreakpointTrapOpcode(bp_site);
30880b57cec5SDimitry Andric 
30890b57cec5SDimitry Andric   // SupportsGDBStoppointPacket() simply checks a boolean, indicating if this
30900b57cec5SDimitry Andric   // breakpoint type is supported by the remote stub. These are set to true by
30910b57cec5SDimitry Andric   // default, and later set to false only after we receive an unimplemented
30920b57cec5SDimitry Andric   // response when sending a breakpoint packet. This means initially that
30930b57cec5SDimitry Andric   // unless we were specifically instructed to use a hardware breakpoint, LLDB
30940b57cec5SDimitry Andric   // will attempt to set a software breakpoint. HardwareRequired() also queries
30950b57cec5SDimitry Andric   // a boolean variable which indicates if the user specifically asked for
30960b57cec5SDimitry Andric   // hardware breakpoints.  If true then we will skip over software
30970b57cec5SDimitry Andric   // breakpoints.
30980b57cec5SDimitry Andric   if (m_gdb_comm.SupportsGDBStoppointPacket(eBreakpointSoftware) &&
30990b57cec5SDimitry Andric       (!bp_site->HardwareRequired())) {
31000b57cec5SDimitry Andric     // Try to send off a software breakpoint packet ($Z0)
31010b57cec5SDimitry Andric     uint8_t error_no = m_gdb_comm.SendGDBStoppointTypePacket(
31020b57cec5SDimitry Andric         eBreakpointSoftware, true, addr, bp_op_size);
31030b57cec5SDimitry Andric     if (error_no == 0) {
31040b57cec5SDimitry Andric       // The breakpoint was placed successfully
31050b57cec5SDimitry Andric       bp_site->SetEnabled(true);
31060b57cec5SDimitry Andric       bp_site->SetType(BreakpointSite::eExternal);
31070b57cec5SDimitry Andric       return error;
31080b57cec5SDimitry Andric     }
31090b57cec5SDimitry Andric 
31100b57cec5SDimitry Andric     // SendGDBStoppointTypePacket() will return an error if it was unable to
31110b57cec5SDimitry Andric     // set this breakpoint. We need to differentiate between a error specific
31120b57cec5SDimitry Andric     // to placing this breakpoint or if we have learned that this breakpoint
31130b57cec5SDimitry Andric     // type is unsupported. To do this, we must test the support boolean for
31140b57cec5SDimitry Andric     // this breakpoint type to see if it now indicates that this breakpoint
31150b57cec5SDimitry Andric     // type is unsupported.  If they are still supported then we should return
31160b57cec5SDimitry Andric     // with the error code.  If they are now unsupported, then we would like to
31170b57cec5SDimitry Andric     // fall through and try another form of breakpoint.
31180b57cec5SDimitry Andric     if (m_gdb_comm.SupportsGDBStoppointPacket(eBreakpointSoftware)) {
31190b57cec5SDimitry Andric       if (error_no != UINT8_MAX)
31200b57cec5SDimitry Andric         error.SetErrorStringWithFormat(
31215ffd83dbSDimitry Andric             "error: %d sending the breakpoint request", error_no);
31220b57cec5SDimitry Andric       else
31230b57cec5SDimitry Andric         error.SetErrorString("error sending the breakpoint request");
31240b57cec5SDimitry Andric       return error;
31250b57cec5SDimitry Andric     }
31260b57cec5SDimitry Andric 
31270b57cec5SDimitry Andric     // We reach here when software breakpoints have been found to be
31280b57cec5SDimitry Andric     // unsupported. For future calls to set a breakpoint, we will not attempt
31290b57cec5SDimitry Andric     // to set a breakpoint with a type that is known not to be supported.
31309dba64beSDimitry Andric     LLDB_LOGF(log, "Software breakpoints are unsupported");
31310b57cec5SDimitry Andric 
31320b57cec5SDimitry Andric     // So we will fall through and try a hardware breakpoint
31330b57cec5SDimitry Andric   }
31340b57cec5SDimitry Andric 
31350b57cec5SDimitry Andric   // The process of setting a hardware breakpoint is much the same as above.
31360b57cec5SDimitry Andric   // We check the supported boolean for this breakpoint type, and if it is
31370b57cec5SDimitry Andric   // thought to be supported then we will try to set this breakpoint with a
31380b57cec5SDimitry Andric   // hardware breakpoint.
31390b57cec5SDimitry Andric   if (m_gdb_comm.SupportsGDBStoppointPacket(eBreakpointHardware)) {
31400b57cec5SDimitry Andric     // Try to send off a hardware breakpoint packet ($Z1)
31410b57cec5SDimitry Andric     uint8_t error_no = m_gdb_comm.SendGDBStoppointTypePacket(
31420b57cec5SDimitry Andric         eBreakpointHardware, true, addr, bp_op_size);
31430b57cec5SDimitry Andric     if (error_no == 0) {
31440b57cec5SDimitry Andric       // The breakpoint was placed successfully
31450b57cec5SDimitry Andric       bp_site->SetEnabled(true);
31460b57cec5SDimitry Andric       bp_site->SetType(BreakpointSite::eHardware);
31470b57cec5SDimitry Andric       return error;
31480b57cec5SDimitry Andric     }
31490b57cec5SDimitry Andric 
31500b57cec5SDimitry Andric     // Check if the error was something other then an unsupported breakpoint
31510b57cec5SDimitry Andric     // type
31520b57cec5SDimitry Andric     if (m_gdb_comm.SupportsGDBStoppointPacket(eBreakpointHardware)) {
31530b57cec5SDimitry Andric       // Unable to set this hardware breakpoint
31540b57cec5SDimitry Andric       if (error_no != UINT8_MAX)
31550b57cec5SDimitry Andric         error.SetErrorStringWithFormat(
31560b57cec5SDimitry Andric             "error: %d sending the hardware breakpoint request "
31570b57cec5SDimitry Andric             "(hardware breakpoint resources might be exhausted or unavailable)",
31580b57cec5SDimitry Andric             error_no);
31590b57cec5SDimitry Andric       else
31600b57cec5SDimitry Andric         error.SetErrorString("error sending the hardware breakpoint request "
31610b57cec5SDimitry Andric                              "(hardware breakpoint resources "
31620b57cec5SDimitry Andric                              "might be exhausted or unavailable)");
31630b57cec5SDimitry Andric       return error;
31640b57cec5SDimitry Andric     }
31650b57cec5SDimitry Andric 
31660b57cec5SDimitry Andric     // We will reach here when the stub gives an unsupported response to a
31670b57cec5SDimitry Andric     // hardware breakpoint
31689dba64beSDimitry Andric     LLDB_LOGF(log, "Hardware breakpoints are unsupported");
31690b57cec5SDimitry Andric 
31700b57cec5SDimitry Andric     // Finally we will falling through to a #trap style breakpoint
31710b57cec5SDimitry Andric   }
31720b57cec5SDimitry Andric 
31730b57cec5SDimitry Andric   // Don't fall through when hardware breakpoints were specifically requested
31740b57cec5SDimitry Andric   if (bp_site->HardwareRequired()) {
31750b57cec5SDimitry Andric     error.SetErrorString("hardware breakpoints are not supported");
31760b57cec5SDimitry Andric     return error;
31770b57cec5SDimitry Andric   }
31780b57cec5SDimitry Andric 
31790b57cec5SDimitry Andric   // As a last resort we want to place a manual breakpoint. An instruction is
31800b57cec5SDimitry Andric   // placed into the process memory using memory write packets.
31810b57cec5SDimitry Andric   return EnableSoftwareBreakpoint(bp_site);
31820b57cec5SDimitry Andric }
31830b57cec5SDimitry Andric 
31840b57cec5SDimitry Andric Status ProcessGDBRemote::DisableBreakpointSite(BreakpointSite *bp_site) {
31850b57cec5SDimitry Andric   Status error;
31860b57cec5SDimitry Andric   assert(bp_site != nullptr);
31870b57cec5SDimitry Andric   addr_t addr = bp_site->GetLoadAddress();
31880b57cec5SDimitry Andric   user_id_t site_id = bp_site->GetID();
31890b57cec5SDimitry Andric   Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_BREAKPOINTS));
31909dba64beSDimitry Andric   LLDB_LOGF(log,
31919dba64beSDimitry Andric             "ProcessGDBRemote::DisableBreakpointSite (site_id = %" PRIu64
31920b57cec5SDimitry Andric             ") addr = 0x%8.8" PRIx64,
31930b57cec5SDimitry Andric             site_id, (uint64_t)addr);
31940b57cec5SDimitry Andric 
31950b57cec5SDimitry Andric   if (bp_site->IsEnabled()) {
31960b57cec5SDimitry Andric     const size_t bp_op_size = GetSoftwareBreakpointTrapOpcode(bp_site);
31970b57cec5SDimitry Andric 
31980b57cec5SDimitry Andric     BreakpointSite::Type bp_type = bp_site->GetType();
31990b57cec5SDimitry Andric     switch (bp_type) {
32000b57cec5SDimitry Andric     case BreakpointSite::eSoftware:
32010b57cec5SDimitry Andric       error = DisableSoftwareBreakpoint(bp_site);
32020b57cec5SDimitry Andric       break;
32030b57cec5SDimitry Andric 
32040b57cec5SDimitry Andric     case BreakpointSite::eHardware:
32050b57cec5SDimitry Andric       if (m_gdb_comm.SendGDBStoppointTypePacket(eBreakpointHardware, false,
32060b57cec5SDimitry Andric                                                 addr, bp_op_size))
32070b57cec5SDimitry Andric         error.SetErrorToGenericError();
32080b57cec5SDimitry Andric       break;
32090b57cec5SDimitry Andric 
32100b57cec5SDimitry Andric     case BreakpointSite::eExternal: {
32110b57cec5SDimitry Andric       GDBStoppointType stoppoint_type;
32120b57cec5SDimitry Andric       if (bp_site->IsHardware())
32130b57cec5SDimitry Andric         stoppoint_type = eBreakpointHardware;
32140b57cec5SDimitry Andric       else
32150b57cec5SDimitry Andric         stoppoint_type = eBreakpointSoftware;
32160b57cec5SDimitry Andric 
32170b57cec5SDimitry Andric       if (m_gdb_comm.SendGDBStoppointTypePacket(stoppoint_type, false, addr,
32180b57cec5SDimitry Andric                                                 bp_op_size))
32190b57cec5SDimitry Andric         error.SetErrorToGenericError();
32200b57cec5SDimitry Andric     } break;
32210b57cec5SDimitry Andric     }
32220b57cec5SDimitry Andric     if (error.Success())
32230b57cec5SDimitry Andric       bp_site->SetEnabled(false);
32240b57cec5SDimitry Andric   } else {
32259dba64beSDimitry Andric     LLDB_LOGF(log,
32269dba64beSDimitry Andric               "ProcessGDBRemote::DisableBreakpointSite (site_id = %" PRIu64
32270b57cec5SDimitry Andric               ") addr = 0x%8.8" PRIx64 " -- SUCCESS (already disabled)",
32280b57cec5SDimitry Andric               site_id, (uint64_t)addr);
32290b57cec5SDimitry Andric     return error;
32300b57cec5SDimitry Andric   }
32310b57cec5SDimitry Andric 
32320b57cec5SDimitry Andric   if (error.Success())
32330b57cec5SDimitry Andric     error.SetErrorToGenericError();
32340b57cec5SDimitry Andric   return error;
32350b57cec5SDimitry Andric }
32360b57cec5SDimitry Andric 
32370b57cec5SDimitry Andric // Pre-requisite: wp != NULL.
32380b57cec5SDimitry Andric static GDBStoppointType GetGDBStoppointType(Watchpoint *wp) {
32390b57cec5SDimitry Andric   assert(wp);
32400b57cec5SDimitry Andric   bool watch_read = wp->WatchpointRead();
32410b57cec5SDimitry Andric   bool watch_write = wp->WatchpointWrite();
32420b57cec5SDimitry Andric 
32430b57cec5SDimitry Andric   // watch_read and watch_write cannot both be false.
32440b57cec5SDimitry Andric   assert(watch_read || watch_write);
32450b57cec5SDimitry Andric   if (watch_read && watch_write)
32460b57cec5SDimitry Andric     return eWatchpointReadWrite;
32470b57cec5SDimitry Andric   else if (watch_read)
32480b57cec5SDimitry Andric     return eWatchpointRead;
32490b57cec5SDimitry Andric   else // Must be watch_write, then.
32500b57cec5SDimitry Andric     return eWatchpointWrite;
32510b57cec5SDimitry Andric }
32520b57cec5SDimitry Andric 
32530b57cec5SDimitry Andric Status ProcessGDBRemote::EnableWatchpoint(Watchpoint *wp, bool notify) {
32540b57cec5SDimitry Andric   Status error;
32550b57cec5SDimitry Andric   if (wp) {
32560b57cec5SDimitry Andric     user_id_t watchID = wp->GetID();
32570b57cec5SDimitry Andric     addr_t addr = wp->GetLoadAddress();
32580b57cec5SDimitry Andric     Log *log(
32590b57cec5SDimitry Andric         ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_WATCHPOINTS));
32609dba64beSDimitry Andric     LLDB_LOGF(log, "ProcessGDBRemote::EnableWatchpoint(watchID = %" PRIu64 ")",
32610b57cec5SDimitry Andric               watchID);
32620b57cec5SDimitry Andric     if (wp->IsEnabled()) {
32639dba64beSDimitry Andric       LLDB_LOGF(log,
32649dba64beSDimitry Andric                 "ProcessGDBRemote::EnableWatchpoint(watchID = %" PRIu64
32650b57cec5SDimitry Andric                 ") addr = 0x%8.8" PRIx64 ": watchpoint already enabled.",
32660b57cec5SDimitry Andric                 watchID, (uint64_t)addr);
32670b57cec5SDimitry Andric       return error;
32680b57cec5SDimitry Andric     }
32690b57cec5SDimitry Andric 
32700b57cec5SDimitry Andric     GDBStoppointType type = GetGDBStoppointType(wp);
32710b57cec5SDimitry Andric     // Pass down an appropriate z/Z packet...
32720b57cec5SDimitry Andric     if (m_gdb_comm.SupportsGDBStoppointPacket(type)) {
32730b57cec5SDimitry Andric       if (m_gdb_comm.SendGDBStoppointTypePacket(type, true, addr,
32740b57cec5SDimitry Andric                                                 wp->GetByteSize()) == 0) {
32750b57cec5SDimitry Andric         wp->SetEnabled(true, notify);
32760b57cec5SDimitry Andric         return error;
32770b57cec5SDimitry Andric       } else
32780b57cec5SDimitry Andric         error.SetErrorString("sending gdb watchpoint packet failed");
32790b57cec5SDimitry Andric     } else
32800b57cec5SDimitry Andric       error.SetErrorString("watchpoints not supported");
32810b57cec5SDimitry Andric   } else {
32820b57cec5SDimitry Andric     error.SetErrorString("Watchpoint argument was NULL.");
32830b57cec5SDimitry Andric   }
32840b57cec5SDimitry Andric   if (error.Success())
32850b57cec5SDimitry Andric     error.SetErrorToGenericError();
32860b57cec5SDimitry Andric   return error;
32870b57cec5SDimitry Andric }
32880b57cec5SDimitry Andric 
32890b57cec5SDimitry Andric Status ProcessGDBRemote::DisableWatchpoint(Watchpoint *wp, bool notify) {
32900b57cec5SDimitry Andric   Status error;
32910b57cec5SDimitry Andric   if (wp) {
32920b57cec5SDimitry Andric     user_id_t watchID = wp->GetID();
32930b57cec5SDimitry Andric 
32940b57cec5SDimitry Andric     Log *log(
32950b57cec5SDimitry Andric         ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_WATCHPOINTS));
32960b57cec5SDimitry Andric 
32970b57cec5SDimitry Andric     addr_t addr = wp->GetLoadAddress();
32980b57cec5SDimitry Andric 
32999dba64beSDimitry Andric     LLDB_LOGF(log,
33009dba64beSDimitry Andric               "ProcessGDBRemote::DisableWatchpoint (watchID = %" PRIu64
33010b57cec5SDimitry Andric               ") addr = 0x%8.8" PRIx64,
33020b57cec5SDimitry Andric               watchID, (uint64_t)addr);
33030b57cec5SDimitry Andric 
33040b57cec5SDimitry Andric     if (!wp->IsEnabled()) {
33059dba64beSDimitry Andric       LLDB_LOGF(log,
33069dba64beSDimitry Andric                 "ProcessGDBRemote::DisableWatchpoint (watchID = %" PRIu64
33070b57cec5SDimitry Andric                 ") addr = 0x%8.8" PRIx64 " -- SUCCESS (already disabled)",
33080b57cec5SDimitry Andric                 watchID, (uint64_t)addr);
33090b57cec5SDimitry Andric       // See also 'class WatchpointSentry' within StopInfo.cpp. This disabling
33100b57cec5SDimitry Andric       // attempt might come from the user-supplied actions, we'll route it in
33110b57cec5SDimitry Andric       // order for the watchpoint object to intelligently process this action.
33120b57cec5SDimitry Andric       wp->SetEnabled(false, notify);
33130b57cec5SDimitry Andric       return error;
33140b57cec5SDimitry Andric     }
33150b57cec5SDimitry Andric 
33160b57cec5SDimitry Andric     if (wp->IsHardware()) {
33170b57cec5SDimitry Andric       GDBStoppointType type = GetGDBStoppointType(wp);
33180b57cec5SDimitry Andric       // Pass down an appropriate z/Z packet...
33190b57cec5SDimitry Andric       if (m_gdb_comm.SendGDBStoppointTypePacket(type, false, addr,
33200b57cec5SDimitry Andric                                                 wp->GetByteSize()) == 0) {
33210b57cec5SDimitry Andric         wp->SetEnabled(false, notify);
33220b57cec5SDimitry Andric         return error;
33230b57cec5SDimitry Andric       } else
33240b57cec5SDimitry Andric         error.SetErrorString("sending gdb watchpoint packet failed");
33250b57cec5SDimitry Andric     }
33260b57cec5SDimitry Andric     // TODO: clear software watchpoints if we implement them
33270b57cec5SDimitry Andric   } else {
33280b57cec5SDimitry Andric     error.SetErrorString("Watchpoint argument was NULL.");
33290b57cec5SDimitry Andric   }
33300b57cec5SDimitry Andric   if (error.Success())
33310b57cec5SDimitry Andric     error.SetErrorToGenericError();
33320b57cec5SDimitry Andric   return error;
33330b57cec5SDimitry Andric }
33340b57cec5SDimitry Andric 
33350b57cec5SDimitry Andric void ProcessGDBRemote::Clear() {
33360b57cec5SDimitry Andric   m_thread_list_real.Clear();
33370b57cec5SDimitry Andric   m_thread_list.Clear();
33380b57cec5SDimitry Andric }
33390b57cec5SDimitry Andric 
33400b57cec5SDimitry Andric Status ProcessGDBRemote::DoSignal(int signo) {
33410b57cec5SDimitry Andric   Status error;
33420b57cec5SDimitry Andric   Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
33439dba64beSDimitry Andric   LLDB_LOGF(log, "ProcessGDBRemote::DoSignal (signal = %d)", signo);
33440b57cec5SDimitry Andric 
33450b57cec5SDimitry Andric   if (!m_gdb_comm.SendAsyncSignal(signo))
33460b57cec5SDimitry Andric     error.SetErrorStringWithFormat("failed to send signal %i", signo);
33470b57cec5SDimitry Andric   return error;
33480b57cec5SDimitry Andric }
33490b57cec5SDimitry Andric 
33505ffd83dbSDimitry Andric Status ProcessGDBRemote::ConnectToReplayServer() {
33515ffd83dbSDimitry Andric   Status status = m_gdb_replay_server.Connect(m_gdb_comm);
33525ffd83dbSDimitry Andric   if (status.Fail())
33535ffd83dbSDimitry Andric     return status;
33540b57cec5SDimitry Andric 
3355480093f4SDimitry Andric   // Enable replay mode.
3356480093f4SDimitry Andric   m_replay_mode = true;
3357480093f4SDimitry Andric 
33580b57cec5SDimitry Andric   // Start server thread.
33590b57cec5SDimitry Andric   m_gdb_replay_server.StartAsyncThread();
33600b57cec5SDimitry Andric 
33610b57cec5SDimitry Andric   // Start client thread.
33620b57cec5SDimitry Andric   StartAsyncThread();
33630b57cec5SDimitry Andric 
33640b57cec5SDimitry Andric   // Do the usual setup.
33650b57cec5SDimitry Andric   return ConnectToDebugserver("");
33660b57cec5SDimitry Andric }
33670b57cec5SDimitry Andric 
33680b57cec5SDimitry Andric Status
33690b57cec5SDimitry Andric ProcessGDBRemote::EstablishConnectionIfNeeded(const ProcessInfo &process_info) {
33700b57cec5SDimitry Andric   // Make sure we aren't already connected?
33710b57cec5SDimitry Andric   if (m_gdb_comm.IsConnected())
33720b57cec5SDimitry Andric     return Status();
33730b57cec5SDimitry Andric 
33740b57cec5SDimitry Andric   PlatformSP platform_sp(GetTarget().GetPlatform());
33750b57cec5SDimitry Andric   if (platform_sp && !platform_sp->IsHost())
33760b57cec5SDimitry Andric     return Status("Lost debug server connection");
33770b57cec5SDimitry Andric 
33785ffd83dbSDimitry Andric   if (repro::Reproducer::Instance().IsReplaying())
33795ffd83dbSDimitry Andric     return ConnectToReplayServer();
33800b57cec5SDimitry Andric 
33810b57cec5SDimitry Andric   auto error = LaunchAndConnectToDebugserver(process_info);
33820b57cec5SDimitry Andric   if (error.Fail()) {
33830b57cec5SDimitry Andric     const char *error_string = error.AsCString();
33840b57cec5SDimitry Andric     if (error_string == nullptr)
33850b57cec5SDimitry Andric       error_string = "unable to launch " DEBUGSERVER_BASENAME;
33860b57cec5SDimitry Andric   }
33870b57cec5SDimitry Andric   return error;
33880b57cec5SDimitry Andric }
33890b57cec5SDimitry Andric #if !defined(_WIN32)
33900b57cec5SDimitry Andric #define USE_SOCKETPAIR_FOR_LOCAL_CONNECTION 1
33910b57cec5SDimitry Andric #endif
33920b57cec5SDimitry Andric 
33930b57cec5SDimitry Andric #ifdef USE_SOCKETPAIR_FOR_LOCAL_CONNECTION
33940b57cec5SDimitry Andric static bool SetCloexecFlag(int fd) {
33950b57cec5SDimitry Andric #if defined(FD_CLOEXEC)
33960b57cec5SDimitry Andric   int flags = ::fcntl(fd, F_GETFD);
33970b57cec5SDimitry Andric   if (flags == -1)
33980b57cec5SDimitry Andric     return false;
33990b57cec5SDimitry Andric   return (::fcntl(fd, F_SETFD, flags | FD_CLOEXEC) == 0);
34000b57cec5SDimitry Andric #else
34010b57cec5SDimitry Andric   return false;
34020b57cec5SDimitry Andric #endif
34030b57cec5SDimitry Andric }
34040b57cec5SDimitry Andric #endif
34050b57cec5SDimitry Andric 
34060b57cec5SDimitry Andric Status ProcessGDBRemote::LaunchAndConnectToDebugserver(
34070b57cec5SDimitry Andric     const ProcessInfo &process_info) {
34080b57cec5SDimitry Andric   using namespace std::placeholders; // For _1, _2, etc.
34090b57cec5SDimitry Andric 
34100b57cec5SDimitry Andric   Status error;
34110b57cec5SDimitry Andric   if (m_debugserver_pid == LLDB_INVALID_PROCESS_ID) {
34120b57cec5SDimitry Andric     // If we locate debugserver, keep that located version around
34130b57cec5SDimitry Andric     static FileSpec g_debugserver_file_spec;
34140b57cec5SDimitry Andric 
34150b57cec5SDimitry Andric     ProcessLaunchInfo debugserver_launch_info;
34160b57cec5SDimitry Andric     // Make debugserver run in its own session so signals generated by special
34170b57cec5SDimitry Andric     // terminal key sequences (^C) don't affect debugserver.
34180b57cec5SDimitry Andric     debugserver_launch_info.SetLaunchInSeparateProcessGroup(true);
34190b57cec5SDimitry Andric 
34200b57cec5SDimitry Andric     const std::weak_ptr<ProcessGDBRemote> this_wp =
34210b57cec5SDimitry Andric         std::static_pointer_cast<ProcessGDBRemote>(shared_from_this());
34220b57cec5SDimitry Andric     debugserver_launch_info.SetMonitorProcessCallback(
34230b57cec5SDimitry Andric         std::bind(MonitorDebugserverProcess, this_wp, _1, _2, _3, _4), false);
34240b57cec5SDimitry Andric     debugserver_launch_info.SetUserID(process_info.GetUserID());
34250b57cec5SDimitry Andric 
34265ffd83dbSDimitry Andric #if defined(__APPLE__)
34275ffd83dbSDimitry Andric     // On macOS 11, we need to support x86_64 applications translated to
34285ffd83dbSDimitry Andric     // arm64. We check whether a binary is translated and spawn the correct
34295ffd83dbSDimitry Andric     // debugserver accordingly.
34305ffd83dbSDimitry Andric     int mib[] = { CTL_KERN, KERN_PROC, KERN_PROC_PID,
34315ffd83dbSDimitry Andric                   static_cast<int>(process_info.GetProcessID()) };
34325ffd83dbSDimitry Andric     struct kinfo_proc processInfo;
34335ffd83dbSDimitry Andric     size_t bufsize = sizeof(processInfo);
34345ffd83dbSDimitry Andric     if (sysctl(mib, (unsigned)(sizeof(mib)/sizeof(int)), &processInfo,
34355ffd83dbSDimitry Andric                &bufsize, NULL, 0) == 0 && bufsize > 0) {
34365ffd83dbSDimitry Andric       if (processInfo.kp_proc.p_flag & P_TRANSLATED) {
34375ffd83dbSDimitry Andric         FileSpec rosetta_debugserver("/Library/Apple/usr/libexec/oah/debugserver");
34385ffd83dbSDimitry Andric         debugserver_launch_info.SetExecutableFile(rosetta_debugserver, false);
34395ffd83dbSDimitry Andric       }
34405ffd83dbSDimitry Andric     }
34415ffd83dbSDimitry Andric #endif
34425ffd83dbSDimitry Andric 
34430b57cec5SDimitry Andric     int communication_fd = -1;
34440b57cec5SDimitry Andric #ifdef USE_SOCKETPAIR_FOR_LOCAL_CONNECTION
34450b57cec5SDimitry Andric     // Use a socketpair on non-Windows systems for security and performance
34460b57cec5SDimitry Andric     // reasons.
34470b57cec5SDimitry Andric     int sockets[2]; /* the pair of socket descriptors */
34480b57cec5SDimitry Andric     if (socketpair(AF_UNIX, SOCK_STREAM, 0, sockets) == -1) {
34490b57cec5SDimitry Andric       error.SetErrorToErrno();
34500b57cec5SDimitry Andric       return error;
34510b57cec5SDimitry Andric     }
34520b57cec5SDimitry Andric 
34530b57cec5SDimitry Andric     int our_socket = sockets[0];
34540b57cec5SDimitry Andric     int gdb_socket = sockets[1];
34559dba64beSDimitry Andric     auto cleanup_our = llvm::make_scope_exit([&]() { close(our_socket); });
34569dba64beSDimitry Andric     auto cleanup_gdb = llvm::make_scope_exit([&]() { close(gdb_socket); });
34570b57cec5SDimitry Andric 
34580b57cec5SDimitry Andric     // Don't let any child processes inherit our communication socket
34590b57cec5SDimitry Andric     SetCloexecFlag(our_socket);
34600b57cec5SDimitry Andric     communication_fd = gdb_socket;
34610b57cec5SDimitry Andric #endif
34620b57cec5SDimitry Andric 
34630b57cec5SDimitry Andric     error = m_gdb_comm.StartDebugserverProcess(
34640b57cec5SDimitry Andric         nullptr, GetTarget().GetPlatform().get(), debugserver_launch_info,
34650b57cec5SDimitry Andric         nullptr, nullptr, communication_fd);
34660b57cec5SDimitry Andric 
34670b57cec5SDimitry Andric     if (error.Success())
34680b57cec5SDimitry Andric       m_debugserver_pid = debugserver_launch_info.GetProcessID();
34690b57cec5SDimitry Andric     else
34700b57cec5SDimitry Andric       m_debugserver_pid = LLDB_INVALID_PROCESS_ID;
34710b57cec5SDimitry Andric 
34720b57cec5SDimitry Andric     if (m_debugserver_pid != LLDB_INVALID_PROCESS_ID) {
34730b57cec5SDimitry Andric #ifdef USE_SOCKETPAIR_FOR_LOCAL_CONNECTION
34740b57cec5SDimitry Andric       // Our process spawned correctly, we can now set our connection to use
34750b57cec5SDimitry Andric       // our end of the socket pair
34769dba64beSDimitry Andric       cleanup_our.release();
34775ffd83dbSDimitry Andric       m_gdb_comm.SetConnection(
34785ffd83dbSDimitry Andric           std::make_unique<ConnectionFileDescriptor>(our_socket, true));
34790b57cec5SDimitry Andric #endif
34800b57cec5SDimitry Andric       StartAsyncThread();
34810b57cec5SDimitry Andric     }
34820b57cec5SDimitry Andric 
34830b57cec5SDimitry Andric     if (error.Fail()) {
34840b57cec5SDimitry Andric       Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
34850b57cec5SDimitry Andric 
34869dba64beSDimitry Andric       LLDB_LOGF(log, "failed to start debugserver process: %s",
34870b57cec5SDimitry Andric                 error.AsCString());
34880b57cec5SDimitry Andric       return error;
34890b57cec5SDimitry Andric     }
34900b57cec5SDimitry Andric 
34910b57cec5SDimitry Andric     if (m_gdb_comm.IsConnected()) {
34920b57cec5SDimitry Andric       // Finish the connection process by doing the handshake without
34930b57cec5SDimitry Andric       // connecting (send NULL URL)
34940b57cec5SDimitry Andric       error = ConnectToDebugserver("");
34950b57cec5SDimitry Andric     } else {
34960b57cec5SDimitry Andric       error.SetErrorString("connection failed");
34970b57cec5SDimitry Andric     }
34980b57cec5SDimitry Andric   }
34990b57cec5SDimitry Andric   return error;
35000b57cec5SDimitry Andric }
35010b57cec5SDimitry Andric 
35020b57cec5SDimitry Andric bool ProcessGDBRemote::MonitorDebugserverProcess(
35030b57cec5SDimitry Andric     std::weak_ptr<ProcessGDBRemote> process_wp, lldb::pid_t debugserver_pid,
35040b57cec5SDimitry Andric     bool exited,    // True if the process did exit
35050b57cec5SDimitry Andric     int signo,      // Zero for no signal
35060b57cec5SDimitry Andric     int exit_status // Exit value of process if signal is zero
35070b57cec5SDimitry Andric ) {
35080b57cec5SDimitry Andric   // "debugserver_pid" argument passed in is the process ID for debugserver
35090b57cec5SDimitry Andric   // that we are tracking...
35100b57cec5SDimitry Andric   Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
35110b57cec5SDimitry Andric   const bool handled = true;
35120b57cec5SDimitry Andric 
35139dba64beSDimitry Andric   LLDB_LOGF(log,
35149dba64beSDimitry Andric             "ProcessGDBRemote::%s(process_wp, pid=%" PRIu64
35150b57cec5SDimitry Andric             ", signo=%i (0x%x), exit_status=%i)",
35160b57cec5SDimitry Andric             __FUNCTION__, debugserver_pid, signo, signo, exit_status);
35170b57cec5SDimitry Andric 
35180b57cec5SDimitry Andric   std::shared_ptr<ProcessGDBRemote> process_sp = process_wp.lock();
35199dba64beSDimitry Andric   LLDB_LOGF(log, "ProcessGDBRemote::%s(process = %p)", __FUNCTION__,
35200b57cec5SDimitry Andric             static_cast<void *>(process_sp.get()));
35210b57cec5SDimitry Andric   if (!process_sp || process_sp->m_debugserver_pid != debugserver_pid)
35220b57cec5SDimitry Andric     return handled;
35230b57cec5SDimitry Andric 
35240b57cec5SDimitry Andric   // Sleep for a half a second to make sure our inferior process has time to
35250b57cec5SDimitry Andric   // set its exit status before we set it incorrectly when both the debugserver
35260b57cec5SDimitry Andric   // and the inferior process shut down.
35279dba64beSDimitry Andric   std::this_thread::sleep_for(std::chrono::milliseconds(500));
35289dba64beSDimitry Andric 
35290b57cec5SDimitry Andric   // If our process hasn't yet exited, debugserver might have died. If the
35300b57cec5SDimitry Andric   // process did exit, then we are reaping it.
35310b57cec5SDimitry Andric   const StateType state = process_sp->GetState();
35320b57cec5SDimitry Andric 
35330b57cec5SDimitry Andric   if (state != eStateInvalid && state != eStateUnloaded &&
35340b57cec5SDimitry Andric       state != eStateExited && state != eStateDetached) {
35350b57cec5SDimitry Andric     char error_str[1024];
35360b57cec5SDimitry Andric     if (signo) {
35370b57cec5SDimitry Andric       const char *signal_cstr =
35380b57cec5SDimitry Andric           process_sp->GetUnixSignals()->GetSignalAsCString(signo);
35390b57cec5SDimitry Andric       if (signal_cstr)
35400b57cec5SDimitry Andric         ::snprintf(error_str, sizeof(error_str),
35410b57cec5SDimitry Andric                    DEBUGSERVER_BASENAME " died with signal %s", signal_cstr);
35420b57cec5SDimitry Andric       else
35430b57cec5SDimitry Andric         ::snprintf(error_str, sizeof(error_str),
35440b57cec5SDimitry Andric                    DEBUGSERVER_BASENAME " died with signal %i", signo);
35450b57cec5SDimitry Andric     } else {
35460b57cec5SDimitry Andric       ::snprintf(error_str, sizeof(error_str),
35470b57cec5SDimitry Andric                  DEBUGSERVER_BASENAME " died with an exit status of 0x%8.8x",
35480b57cec5SDimitry Andric                  exit_status);
35490b57cec5SDimitry Andric     }
35500b57cec5SDimitry Andric 
35510b57cec5SDimitry Andric     process_sp->SetExitStatus(-1, error_str);
35520b57cec5SDimitry Andric   }
35530b57cec5SDimitry Andric   // Debugserver has exited we need to let our ProcessGDBRemote know that it no
35540b57cec5SDimitry Andric   // longer has a debugserver instance
35550b57cec5SDimitry Andric   process_sp->m_debugserver_pid = LLDB_INVALID_PROCESS_ID;
35560b57cec5SDimitry Andric   return handled;
35570b57cec5SDimitry Andric }
35580b57cec5SDimitry Andric 
35590b57cec5SDimitry Andric void ProcessGDBRemote::KillDebugserverProcess() {
35600b57cec5SDimitry Andric   m_gdb_comm.Disconnect();
35610b57cec5SDimitry Andric   if (m_debugserver_pid != LLDB_INVALID_PROCESS_ID) {
35620b57cec5SDimitry Andric     Host::Kill(m_debugserver_pid, SIGINT);
35630b57cec5SDimitry Andric     m_debugserver_pid = LLDB_INVALID_PROCESS_ID;
35640b57cec5SDimitry Andric   }
35650b57cec5SDimitry Andric }
35660b57cec5SDimitry Andric 
35670b57cec5SDimitry Andric void ProcessGDBRemote::Initialize() {
35680b57cec5SDimitry Andric   static llvm::once_flag g_once_flag;
35690b57cec5SDimitry Andric 
35700b57cec5SDimitry Andric   llvm::call_once(g_once_flag, []() {
35710b57cec5SDimitry Andric     PluginManager::RegisterPlugin(GetPluginNameStatic(),
35720b57cec5SDimitry Andric                                   GetPluginDescriptionStatic(), CreateInstance,
35730b57cec5SDimitry Andric                                   DebuggerInitialize);
35740b57cec5SDimitry Andric   });
35750b57cec5SDimitry Andric }
35760b57cec5SDimitry Andric 
35770b57cec5SDimitry Andric void ProcessGDBRemote::DebuggerInitialize(Debugger &debugger) {
35780b57cec5SDimitry Andric   if (!PluginManager::GetSettingForProcessPlugin(
35790b57cec5SDimitry Andric           debugger, PluginProperties::GetSettingName())) {
35800b57cec5SDimitry Andric     const bool is_global_setting = true;
35810b57cec5SDimitry Andric     PluginManager::CreateSettingForProcessPlugin(
35820b57cec5SDimitry Andric         debugger, GetGlobalPluginProperties()->GetValueProperties(),
35830b57cec5SDimitry Andric         ConstString("Properties for the gdb-remote process plug-in."),
35840b57cec5SDimitry Andric         is_global_setting);
35850b57cec5SDimitry Andric   }
35860b57cec5SDimitry Andric }
35870b57cec5SDimitry Andric 
35880b57cec5SDimitry Andric bool ProcessGDBRemote::StartAsyncThread() {
35890b57cec5SDimitry Andric   Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
35900b57cec5SDimitry Andric 
35919dba64beSDimitry Andric   LLDB_LOGF(log, "ProcessGDBRemote::%s ()", __FUNCTION__);
35920b57cec5SDimitry Andric 
35930b57cec5SDimitry Andric   std::lock_guard<std::recursive_mutex> guard(m_async_thread_state_mutex);
35940b57cec5SDimitry Andric   if (!m_async_thread.IsJoinable()) {
35950b57cec5SDimitry Andric     // Create a thread that watches our internal state and controls which
35960b57cec5SDimitry Andric     // events make it to clients (into the DCProcess event queue).
35970b57cec5SDimitry Andric 
35980b57cec5SDimitry Andric     llvm::Expected<HostThread> async_thread = ThreadLauncher::LaunchThread(
35990b57cec5SDimitry Andric         "<lldb.process.gdb-remote.async>", ProcessGDBRemote::AsyncThread, this);
36000b57cec5SDimitry Andric     if (!async_thread) {
3601480093f4SDimitry Andric       LLDB_LOG_ERROR(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_HOST),
3602480093f4SDimitry Andric                      async_thread.takeError(),
3603480093f4SDimitry Andric                      "failed to launch host thread: {}");
36040b57cec5SDimitry Andric       return false;
36050b57cec5SDimitry Andric     }
36060b57cec5SDimitry Andric     m_async_thread = *async_thread;
36079dba64beSDimitry Andric   } else
36089dba64beSDimitry Andric     LLDB_LOGF(log,
36099dba64beSDimitry Andric               "ProcessGDBRemote::%s () - Called when Async thread was "
36100b57cec5SDimitry Andric               "already running.",
36110b57cec5SDimitry Andric               __FUNCTION__);
36120b57cec5SDimitry Andric 
36130b57cec5SDimitry Andric   return m_async_thread.IsJoinable();
36140b57cec5SDimitry Andric }
36150b57cec5SDimitry Andric 
36160b57cec5SDimitry Andric void ProcessGDBRemote::StopAsyncThread() {
36170b57cec5SDimitry Andric   Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
36180b57cec5SDimitry Andric 
36199dba64beSDimitry Andric   LLDB_LOGF(log, "ProcessGDBRemote::%s ()", __FUNCTION__);
36200b57cec5SDimitry Andric 
36210b57cec5SDimitry Andric   std::lock_guard<std::recursive_mutex> guard(m_async_thread_state_mutex);
36220b57cec5SDimitry Andric   if (m_async_thread.IsJoinable()) {
36230b57cec5SDimitry Andric     m_async_broadcaster.BroadcastEvent(eBroadcastBitAsyncThreadShouldExit);
36240b57cec5SDimitry Andric 
36250b57cec5SDimitry Andric     //  This will shut down the async thread.
36260b57cec5SDimitry Andric     m_gdb_comm.Disconnect(); // Disconnect from the debug server.
36270b57cec5SDimitry Andric 
36280b57cec5SDimitry Andric     // Stop the stdio thread
36290b57cec5SDimitry Andric     m_async_thread.Join(nullptr);
36300b57cec5SDimitry Andric     m_async_thread.Reset();
36319dba64beSDimitry Andric   } else
36329dba64beSDimitry Andric     LLDB_LOGF(
36339dba64beSDimitry Andric         log,
36340b57cec5SDimitry Andric         "ProcessGDBRemote::%s () - Called when Async thread was not running.",
36350b57cec5SDimitry Andric         __FUNCTION__);
36360b57cec5SDimitry Andric }
36370b57cec5SDimitry Andric 
36380b57cec5SDimitry Andric bool ProcessGDBRemote::HandleNotifyPacket(StringExtractorGDBRemote &packet) {
36390b57cec5SDimitry Andric   // get the packet at a string
36405ffd83dbSDimitry Andric   const std::string &pkt = std::string(packet.GetStringRef());
36410b57cec5SDimitry Andric   // skip %stop:
36420b57cec5SDimitry Andric   StringExtractorGDBRemote stop_info(pkt.c_str() + 5);
36430b57cec5SDimitry Andric 
36440b57cec5SDimitry Andric   // pass as a thread stop info packet
36450b57cec5SDimitry Andric   SetLastStopPacket(stop_info);
36460b57cec5SDimitry Andric 
36470b57cec5SDimitry Andric   // check for more stop reasons
36480b57cec5SDimitry Andric   HandleStopReplySequence();
36490b57cec5SDimitry Andric 
36500b57cec5SDimitry Andric   // if the process is stopped then we need to fake a resume so that we can
36510b57cec5SDimitry Andric   // stop properly with the new break. This is possible due to
36520b57cec5SDimitry Andric   // SetPrivateState() broadcasting the state change as a side effect.
36530b57cec5SDimitry Andric   if (GetPrivateState() == lldb::StateType::eStateStopped) {
36540b57cec5SDimitry Andric     SetPrivateState(lldb::StateType::eStateRunning);
36550b57cec5SDimitry Andric   }
36560b57cec5SDimitry Andric 
36570b57cec5SDimitry Andric   // since we have some stopped packets we can halt the process
36580b57cec5SDimitry Andric   SetPrivateState(lldb::StateType::eStateStopped);
36590b57cec5SDimitry Andric 
36600b57cec5SDimitry Andric   return true;
36610b57cec5SDimitry Andric }
36620b57cec5SDimitry Andric 
36630b57cec5SDimitry Andric thread_result_t ProcessGDBRemote::AsyncThread(void *arg) {
36640b57cec5SDimitry Andric   ProcessGDBRemote *process = (ProcessGDBRemote *)arg;
36650b57cec5SDimitry Andric 
36660b57cec5SDimitry Andric   Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
36679dba64beSDimitry Andric   LLDB_LOGF(log,
36689dba64beSDimitry Andric             "ProcessGDBRemote::%s (arg = %p, pid = %" PRIu64
36690b57cec5SDimitry Andric             ") thread starting...",
36700b57cec5SDimitry Andric             __FUNCTION__, arg, process->GetID());
36710b57cec5SDimitry Andric 
36720b57cec5SDimitry Andric   EventSP event_sp;
36730b57cec5SDimitry Andric   bool done = false;
36740b57cec5SDimitry Andric   while (!done) {
36759dba64beSDimitry Andric     LLDB_LOGF(log,
36769dba64beSDimitry Andric               "ProcessGDBRemote::%s (arg = %p, pid = %" PRIu64
36770b57cec5SDimitry Andric               ") listener.WaitForEvent (NULL, event_sp)...",
36780b57cec5SDimitry Andric               __FUNCTION__, arg, process->GetID());
36790b57cec5SDimitry Andric     if (process->m_async_listener_sp->GetEvent(event_sp, llvm::None)) {
36800b57cec5SDimitry Andric       const uint32_t event_type = event_sp->GetType();
36810b57cec5SDimitry Andric       if (event_sp->BroadcasterIs(&process->m_async_broadcaster)) {
36829dba64beSDimitry Andric         LLDB_LOGF(log,
36839dba64beSDimitry Andric                   "ProcessGDBRemote::%s (arg = %p, pid = %" PRIu64
36840b57cec5SDimitry Andric                   ") Got an event of type: %d...",
36850b57cec5SDimitry Andric                   __FUNCTION__, arg, process->GetID(), event_type);
36860b57cec5SDimitry Andric 
36870b57cec5SDimitry Andric         switch (event_type) {
36880b57cec5SDimitry Andric         case eBroadcastBitAsyncContinue: {
36890b57cec5SDimitry Andric           const EventDataBytes *continue_packet =
36900b57cec5SDimitry Andric               EventDataBytes::GetEventDataFromEvent(event_sp.get());
36910b57cec5SDimitry Andric 
36920b57cec5SDimitry Andric           if (continue_packet) {
36930b57cec5SDimitry Andric             const char *continue_cstr =
36940b57cec5SDimitry Andric                 (const char *)continue_packet->GetBytes();
36950b57cec5SDimitry Andric             const size_t continue_cstr_len = continue_packet->GetByteSize();
36969dba64beSDimitry Andric             LLDB_LOGF(log,
36979dba64beSDimitry Andric                       "ProcessGDBRemote::%s (arg = %p, pid = %" PRIu64
36980b57cec5SDimitry Andric                       ") got eBroadcastBitAsyncContinue: %s",
36990b57cec5SDimitry Andric                       __FUNCTION__, arg, process->GetID(), continue_cstr);
37000b57cec5SDimitry Andric 
37010b57cec5SDimitry Andric             if (::strstr(continue_cstr, "vAttach") == nullptr)
37020b57cec5SDimitry Andric               process->SetPrivateState(eStateRunning);
37030b57cec5SDimitry Andric             StringExtractorGDBRemote response;
37040b57cec5SDimitry Andric 
37050b57cec5SDimitry Andric             // If in Non-Stop-Mode
37060b57cec5SDimitry Andric             if (process->GetTarget().GetNonStopModeEnabled()) {
37070b57cec5SDimitry Andric               // send the vCont packet
37080b57cec5SDimitry Andric               if (!process->GetGDBRemote().SendvContPacket(
37090b57cec5SDimitry Andric                       llvm::StringRef(continue_cstr, continue_cstr_len),
37100b57cec5SDimitry Andric                       response)) {
37110b57cec5SDimitry Andric                 // Something went wrong
37120b57cec5SDimitry Andric                 done = true;
37130b57cec5SDimitry Andric                 break;
37140b57cec5SDimitry Andric               }
37150b57cec5SDimitry Andric             }
37160b57cec5SDimitry Andric             // If in All-Stop-Mode
37170b57cec5SDimitry Andric             else {
37180b57cec5SDimitry Andric               StateType stop_state =
37190b57cec5SDimitry Andric                   process->GetGDBRemote().SendContinuePacketAndWaitForResponse(
37200b57cec5SDimitry Andric                       *process, *process->GetUnixSignals(),
37210b57cec5SDimitry Andric                       llvm::StringRef(continue_cstr, continue_cstr_len),
37220b57cec5SDimitry Andric                       response);
37230b57cec5SDimitry Andric 
37240b57cec5SDimitry Andric               // We need to immediately clear the thread ID list so we are sure
37250b57cec5SDimitry Andric               // to get a valid list of threads. The thread ID list might be
37260b57cec5SDimitry Andric               // contained within the "response", or the stop reply packet that
37270b57cec5SDimitry Andric               // caused the stop. So clear it now before we give the stop reply
37280b57cec5SDimitry Andric               // packet to the process using the
37290b57cec5SDimitry Andric               // process->SetLastStopPacket()...
37300b57cec5SDimitry Andric               process->ClearThreadIDList();
37310b57cec5SDimitry Andric 
37320b57cec5SDimitry Andric               switch (stop_state) {
37330b57cec5SDimitry Andric               case eStateStopped:
37340b57cec5SDimitry Andric               case eStateCrashed:
37350b57cec5SDimitry Andric               case eStateSuspended:
37360b57cec5SDimitry Andric                 process->SetLastStopPacket(response);
37370b57cec5SDimitry Andric                 process->SetPrivateState(stop_state);
37380b57cec5SDimitry Andric                 break;
37390b57cec5SDimitry Andric 
37400b57cec5SDimitry Andric               case eStateExited: {
37410b57cec5SDimitry Andric                 process->SetLastStopPacket(response);
37420b57cec5SDimitry Andric                 process->ClearThreadIDList();
37430b57cec5SDimitry Andric                 response.SetFilePos(1);
37440b57cec5SDimitry Andric 
37450b57cec5SDimitry Andric                 int exit_status = response.GetHexU8();
37460b57cec5SDimitry Andric                 std::string desc_string;
37470b57cec5SDimitry Andric                 if (response.GetBytesLeft() > 0 &&
37480b57cec5SDimitry Andric                     response.GetChar('-') == ';') {
37490b57cec5SDimitry Andric                   llvm::StringRef desc_str;
37500b57cec5SDimitry Andric                   llvm::StringRef desc_token;
37510b57cec5SDimitry Andric                   while (response.GetNameColonValue(desc_token, desc_str)) {
37520b57cec5SDimitry Andric                     if (desc_token != "description")
37530b57cec5SDimitry Andric                       continue;
37540b57cec5SDimitry Andric                     StringExtractor extractor(desc_str);
37550b57cec5SDimitry Andric                     extractor.GetHexByteString(desc_string);
37560b57cec5SDimitry Andric                   }
37570b57cec5SDimitry Andric                 }
37580b57cec5SDimitry Andric                 process->SetExitStatus(exit_status, desc_string.c_str());
37590b57cec5SDimitry Andric                 done = true;
37600b57cec5SDimitry Andric                 break;
37610b57cec5SDimitry Andric               }
37620b57cec5SDimitry Andric               case eStateInvalid: {
37630b57cec5SDimitry Andric                 // Check to see if we were trying to attach and if we got back
37640b57cec5SDimitry Andric                 // the "E87" error code from debugserver -- this indicates that
37650b57cec5SDimitry Andric                 // the process is not debuggable.  Return a slightly more
37660b57cec5SDimitry Andric                 // helpful error message about why the attach failed.
37670b57cec5SDimitry Andric                 if (::strstr(continue_cstr, "vAttach") != nullptr &&
37680b57cec5SDimitry Andric                     response.GetError() == 0x87) {
37690b57cec5SDimitry Andric                   process->SetExitStatus(-1, "cannot attach to process due to "
37700b57cec5SDimitry Andric                                              "System Integrity Protection");
37710b57cec5SDimitry Andric                 } else if (::strstr(continue_cstr, "vAttach") != nullptr &&
37720b57cec5SDimitry Andric                            response.GetStatus().Fail()) {
37730b57cec5SDimitry Andric                   process->SetExitStatus(-1, response.GetStatus().AsCString());
37740b57cec5SDimitry Andric                 } else {
37750b57cec5SDimitry Andric                   process->SetExitStatus(-1, "lost connection");
37760b57cec5SDimitry Andric                 }
37770b57cec5SDimitry Andric                 break;
37780b57cec5SDimitry Andric               }
37790b57cec5SDimitry Andric 
37800b57cec5SDimitry Andric               default:
37810b57cec5SDimitry Andric                 process->SetPrivateState(stop_state);
37820b57cec5SDimitry Andric                 break;
37830b57cec5SDimitry Andric               } // switch(stop_state)
37840b57cec5SDimitry Andric             }   // else // if in All-stop-mode
37850b57cec5SDimitry Andric           }     // if (continue_packet)
37865ffd83dbSDimitry Andric         }       // case eBroadcastBitAsyncContinue
37870b57cec5SDimitry Andric         break;
37880b57cec5SDimitry Andric 
37890b57cec5SDimitry Andric         case eBroadcastBitAsyncThreadShouldExit:
37909dba64beSDimitry Andric           LLDB_LOGF(log,
37919dba64beSDimitry Andric                     "ProcessGDBRemote::%s (arg = %p, pid = %" PRIu64
37920b57cec5SDimitry Andric                     ") got eBroadcastBitAsyncThreadShouldExit...",
37930b57cec5SDimitry Andric                     __FUNCTION__, arg, process->GetID());
37940b57cec5SDimitry Andric           done = true;
37950b57cec5SDimitry Andric           break;
37960b57cec5SDimitry Andric 
37970b57cec5SDimitry Andric         default:
37989dba64beSDimitry Andric           LLDB_LOGF(log,
37999dba64beSDimitry Andric                     "ProcessGDBRemote::%s (arg = %p, pid = %" PRIu64
38000b57cec5SDimitry Andric                     ") got unknown event 0x%8.8x",
38010b57cec5SDimitry Andric                     __FUNCTION__, arg, process->GetID(), event_type);
38020b57cec5SDimitry Andric           done = true;
38030b57cec5SDimitry Andric           break;
38040b57cec5SDimitry Andric         }
38050b57cec5SDimitry Andric       } else if (event_sp->BroadcasterIs(&process->m_gdb_comm)) {
38060b57cec5SDimitry Andric         switch (event_type) {
38070b57cec5SDimitry Andric         case Communication::eBroadcastBitReadThreadDidExit:
38080b57cec5SDimitry Andric           process->SetExitStatus(-1, "lost connection");
38090b57cec5SDimitry Andric           done = true;
38100b57cec5SDimitry Andric           break;
38110b57cec5SDimitry Andric 
38120b57cec5SDimitry Andric         case GDBRemoteCommunication::eBroadcastBitGdbReadThreadGotNotify: {
38130b57cec5SDimitry Andric           lldb_private::Event *event = event_sp.get();
38140b57cec5SDimitry Andric           const EventDataBytes *continue_packet =
38150b57cec5SDimitry Andric               EventDataBytes::GetEventDataFromEvent(event);
38160b57cec5SDimitry Andric           StringExtractorGDBRemote notify(
38170b57cec5SDimitry Andric               (const char *)continue_packet->GetBytes());
38180b57cec5SDimitry Andric           // Hand this over to the process to handle
38190b57cec5SDimitry Andric           process->HandleNotifyPacket(notify);
38200b57cec5SDimitry Andric           break;
38210b57cec5SDimitry Andric         }
38220b57cec5SDimitry Andric 
38230b57cec5SDimitry Andric         default:
38249dba64beSDimitry Andric           LLDB_LOGF(log,
38259dba64beSDimitry Andric                     "ProcessGDBRemote::%s (arg = %p, pid = %" PRIu64
38260b57cec5SDimitry Andric                     ") got unknown event 0x%8.8x",
38270b57cec5SDimitry Andric                     __FUNCTION__, arg, process->GetID(), event_type);
38280b57cec5SDimitry Andric           done = true;
38290b57cec5SDimitry Andric           break;
38300b57cec5SDimitry Andric         }
38310b57cec5SDimitry Andric       }
38320b57cec5SDimitry Andric     } else {
38339dba64beSDimitry Andric       LLDB_LOGF(log,
38349dba64beSDimitry Andric                 "ProcessGDBRemote::%s (arg = %p, pid = %" PRIu64
38350b57cec5SDimitry Andric                 ") listener.WaitForEvent (NULL, event_sp) => false",
38360b57cec5SDimitry Andric                 __FUNCTION__, arg, process->GetID());
38370b57cec5SDimitry Andric       done = true;
38380b57cec5SDimitry Andric     }
38390b57cec5SDimitry Andric   }
38400b57cec5SDimitry Andric 
38419dba64beSDimitry Andric   LLDB_LOGF(log,
38429dba64beSDimitry Andric             "ProcessGDBRemote::%s (arg = %p, pid = %" PRIu64
38430b57cec5SDimitry Andric             ") thread exiting...",
38440b57cec5SDimitry Andric             __FUNCTION__, arg, process->GetID());
38450b57cec5SDimitry Andric 
38460b57cec5SDimitry Andric   return {};
38470b57cec5SDimitry Andric }
38480b57cec5SDimitry Andric 
38490b57cec5SDimitry Andric // uint32_t
38500b57cec5SDimitry Andric // ProcessGDBRemote::ListProcessesMatchingName (const char *name, StringList
38510b57cec5SDimitry Andric // &matches, std::vector<lldb::pid_t> &pids)
38520b57cec5SDimitry Andric //{
38530b57cec5SDimitry Andric //    // If we are planning to launch the debugserver remotely, then we need to
38540b57cec5SDimitry Andric //    fire up a debugserver
38550b57cec5SDimitry Andric //    // process and ask it for the list of processes. But if we are local, we
38560b57cec5SDimitry Andric //    can let the Host do it.
38570b57cec5SDimitry Andric //    if (m_local_debugserver)
38580b57cec5SDimitry Andric //    {
38590b57cec5SDimitry Andric //        return Host::ListProcessesMatchingName (name, matches, pids);
38600b57cec5SDimitry Andric //    }
38610b57cec5SDimitry Andric //    else
38620b57cec5SDimitry Andric //    {
38630b57cec5SDimitry Andric //        // FIXME: Implement talking to the remote debugserver.
38640b57cec5SDimitry Andric //        return 0;
38650b57cec5SDimitry Andric //    }
38660b57cec5SDimitry Andric //
38670b57cec5SDimitry Andric //}
38680b57cec5SDimitry Andric //
38690b57cec5SDimitry Andric bool ProcessGDBRemote::NewThreadNotifyBreakpointHit(
38700b57cec5SDimitry Andric     void *baton, StoppointCallbackContext *context, lldb::user_id_t break_id,
38710b57cec5SDimitry Andric     lldb::user_id_t break_loc_id) {
38720b57cec5SDimitry Andric   // I don't think I have to do anything here, just make sure I notice the new
38730b57cec5SDimitry Andric   // thread when it starts to
38740b57cec5SDimitry Andric   // run so I can stop it if that's what I want to do.
38750b57cec5SDimitry Andric   Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_STEP));
38769dba64beSDimitry Andric   LLDB_LOGF(log, "Hit New Thread Notification breakpoint.");
38770b57cec5SDimitry Andric   return false;
38780b57cec5SDimitry Andric }
38790b57cec5SDimitry Andric 
38800b57cec5SDimitry Andric Status ProcessGDBRemote::UpdateAutomaticSignalFiltering() {
38810b57cec5SDimitry Andric   Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
38820b57cec5SDimitry Andric   LLDB_LOG(log, "Check if need to update ignored signals");
38830b57cec5SDimitry Andric 
38840b57cec5SDimitry Andric   // QPassSignals package is not supported by the server, there is no way we
38850b57cec5SDimitry Andric   // can ignore any signals on server side.
38860b57cec5SDimitry Andric   if (!m_gdb_comm.GetQPassSignalsSupported())
38870b57cec5SDimitry Andric     return Status();
38880b57cec5SDimitry Andric 
38890b57cec5SDimitry Andric   // No signals, nothing to send.
38900b57cec5SDimitry Andric   if (m_unix_signals_sp == nullptr)
38910b57cec5SDimitry Andric     return Status();
38920b57cec5SDimitry Andric 
38930b57cec5SDimitry Andric   // Signals' version hasn't changed, no need to send anything.
38940b57cec5SDimitry Andric   uint64_t new_signals_version = m_unix_signals_sp->GetVersion();
38950b57cec5SDimitry Andric   if (new_signals_version == m_last_signals_version) {
38960b57cec5SDimitry Andric     LLDB_LOG(log, "Signals' version hasn't changed. version={0}",
38970b57cec5SDimitry Andric              m_last_signals_version);
38980b57cec5SDimitry Andric     return Status();
38990b57cec5SDimitry Andric   }
39000b57cec5SDimitry Andric 
39010b57cec5SDimitry Andric   auto signals_to_ignore =
39020b57cec5SDimitry Andric       m_unix_signals_sp->GetFilteredSignals(false, false, false);
39030b57cec5SDimitry Andric   Status error = m_gdb_comm.SendSignalsToIgnore(signals_to_ignore);
39040b57cec5SDimitry Andric 
39050b57cec5SDimitry Andric   LLDB_LOG(log,
39060b57cec5SDimitry Andric            "Signals' version changed. old version={0}, new version={1}, "
39070b57cec5SDimitry Andric            "signals ignored={2}, update result={3}",
39080b57cec5SDimitry Andric            m_last_signals_version, new_signals_version,
39090b57cec5SDimitry Andric            signals_to_ignore.size(), error);
39100b57cec5SDimitry Andric 
39110b57cec5SDimitry Andric   if (error.Success())
39120b57cec5SDimitry Andric     m_last_signals_version = new_signals_version;
39130b57cec5SDimitry Andric 
39140b57cec5SDimitry Andric   return error;
39150b57cec5SDimitry Andric }
39160b57cec5SDimitry Andric 
39170b57cec5SDimitry Andric bool ProcessGDBRemote::StartNoticingNewThreads() {
39180b57cec5SDimitry Andric   Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_STEP));
39190b57cec5SDimitry Andric   if (m_thread_create_bp_sp) {
39200b57cec5SDimitry Andric     if (log && log->GetVerbose())
39219dba64beSDimitry Andric       LLDB_LOGF(log, "Enabled noticing new thread breakpoint.");
39220b57cec5SDimitry Andric     m_thread_create_bp_sp->SetEnabled(true);
39230b57cec5SDimitry Andric   } else {
39240b57cec5SDimitry Andric     PlatformSP platform_sp(GetTarget().GetPlatform());
39250b57cec5SDimitry Andric     if (platform_sp) {
39260b57cec5SDimitry Andric       m_thread_create_bp_sp =
39270b57cec5SDimitry Andric           platform_sp->SetThreadCreationBreakpoint(GetTarget());
39280b57cec5SDimitry Andric       if (m_thread_create_bp_sp) {
39290b57cec5SDimitry Andric         if (log && log->GetVerbose())
39309dba64beSDimitry Andric           LLDB_LOGF(
39319dba64beSDimitry Andric               log, "Successfully created new thread notification breakpoint %i",
39320b57cec5SDimitry Andric               m_thread_create_bp_sp->GetID());
39330b57cec5SDimitry Andric         m_thread_create_bp_sp->SetCallback(
39340b57cec5SDimitry Andric             ProcessGDBRemote::NewThreadNotifyBreakpointHit, this, true);
39350b57cec5SDimitry Andric       } else {
39369dba64beSDimitry Andric         LLDB_LOGF(log, "Failed to create new thread notification breakpoint.");
39370b57cec5SDimitry Andric       }
39380b57cec5SDimitry Andric     }
39390b57cec5SDimitry Andric   }
39400b57cec5SDimitry Andric   return m_thread_create_bp_sp.get() != nullptr;
39410b57cec5SDimitry Andric }
39420b57cec5SDimitry Andric 
39430b57cec5SDimitry Andric bool ProcessGDBRemote::StopNoticingNewThreads() {
39440b57cec5SDimitry Andric   Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_STEP));
39450b57cec5SDimitry Andric   if (log && log->GetVerbose())
39469dba64beSDimitry Andric     LLDB_LOGF(log, "Disabling new thread notification breakpoint.");
39470b57cec5SDimitry Andric 
39480b57cec5SDimitry Andric   if (m_thread_create_bp_sp)
39490b57cec5SDimitry Andric     m_thread_create_bp_sp->SetEnabled(false);
39500b57cec5SDimitry Andric 
39510b57cec5SDimitry Andric   return true;
39520b57cec5SDimitry Andric }
39530b57cec5SDimitry Andric 
39540b57cec5SDimitry Andric DynamicLoader *ProcessGDBRemote::GetDynamicLoader() {
39550b57cec5SDimitry Andric   if (m_dyld_up.get() == nullptr)
39560b57cec5SDimitry Andric     m_dyld_up.reset(DynamicLoader::FindPlugin(this, nullptr));
39570b57cec5SDimitry Andric   return m_dyld_up.get();
39580b57cec5SDimitry Andric }
39590b57cec5SDimitry Andric 
39600b57cec5SDimitry Andric Status ProcessGDBRemote::SendEventData(const char *data) {
39610b57cec5SDimitry Andric   int return_value;
39620b57cec5SDimitry Andric   bool was_supported;
39630b57cec5SDimitry Andric 
39640b57cec5SDimitry Andric   Status error;
39650b57cec5SDimitry Andric 
39660b57cec5SDimitry Andric   return_value = m_gdb_comm.SendLaunchEventDataPacket(data, &was_supported);
39670b57cec5SDimitry Andric   if (return_value != 0) {
39680b57cec5SDimitry Andric     if (!was_supported)
39690b57cec5SDimitry Andric       error.SetErrorString("Sending events is not supported for this process.");
39700b57cec5SDimitry Andric     else
39710b57cec5SDimitry Andric       error.SetErrorStringWithFormat("Error sending event data: %d.",
39720b57cec5SDimitry Andric                                      return_value);
39730b57cec5SDimitry Andric   }
39740b57cec5SDimitry Andric   return error;
39750b57cec5SDimitry Andric }
39760b57cec5SDimitry Andric 
39770b57cec5SDimitry Andric DataExtractor ProcessGDBRemote::GetAuxvData() {
39780b57cec5SDimitry Andric   DataBufferSP buf;
39790b57cec5SDimitry Andric   if (m_gdb_comm.GetQXferAuxvReadSupported()) {
39800b57cec5SDimitry Andric     std::string response_string;
39810b57cec5SDimitry Andric     if (m_gdb_comm.SendPacketsAndConcatenateResponses("qXfer:auxv:read::",
39820b57cec5SDimitry Andric                                                       response_string) ==
39830b57cec5SDimitry Andric         GDBRemoteCommunication::PacketResult::Success)
39840b57cec5SDimitry Andric       buf = std::make_shared<DataBufferHeap>(response_string.c_str(),
39850b57cec5SDimitry Andric                                              response_string.length());
39860b57cec5SDimitry Andric   }
39870b57cec5SDimitry Andric   return DataExtractor(buf, GetByteOrder(), GetAddressByteSize());
39880b57cec5SDimitry Andric }
39890b57cec5SDimitry Andric 
39900b57cec5SDimitry Andric StructuredData::ObjectSP
39910b57cec5SDimitry Andric ProcessGDBRemote::GetExtendedInfoForThread(lldb::tid_t tid) {
39920b57cec5SDimitry Andric   StructuredData::ObjectSP object_sp;
39930b57cec5SDimitry Andric 
39940b57cec5SDimitry Andric   if (m_gdb_comm.GetThreadExtendedInfoSupported()) {
39950b57cec5SDimitry Andric     StructuredData::ObjectSP args_dict(new StructuredData::Dictionary());
39960b57cec5SDimitry Andric     SystemRuntime *runtime = GetSystemRuntime();
39970b57cec5SDimitry Andric     if (runtime) {
39980b57cec5SDimitry Andric       runtime->AddThreadExtendedInfoPacketHints(args_dict);
39990b57cec5SDimitry Andric     }
40000b57cec5SDimitry Andric     args_dict->GetAsDictionary()->AddIntegerItem("thread", tid);
40010b57cec5SDimitry Andric 
40020b57cec5SDimitry Andric     StreamString packet;
40030b57cec5SDimitry Andric     packet << "jThreadExtendedInfo:";
40040b57cec5SDimitry Andric     args_dict->Dump(packet, false);
40050b57cec5SDimitry Andric 
40060b57cec5SDimitry Andric     // FIXME the final character of a JSON dictionary, '}', is the escape
40070b57cec5SDimitry Andric     // character in gdb-remote binary mode.  lldb currently doesn't escape
40080b57cec5SDimitry Andric     // these characters in its packet output -- so we add the quoted version of
40090b57cec5SDimitry Andric     // the } character here manually in case we talk to a debugserver which un-
40100b57cec5SDimitry Andric     // escapes the characters at packet read time.
40110b57cec5SDimitry Andric     packet << (char)(0x7d ^ 0x20);
40120b57cec5SDimitry Andric 
40130b57cec5SDimitry Andric     StringExtractorGDBRemote response;
40140b57cec5SDimitry Andric     response.SetResponseValidatorToJSON();
40150b57cec5SDimitry Andric     if (m_gdb_comm.SendPacketAndWaitForResponse(packet.GetString(), response,
40160b57cec5SDimitry Andric                                                 false) ==
40170b57cec5SDimitry Andric         GDBRemoteCommunication::PacketResult::Success) {
40180b57cec5SDimitry Andric       StringExtractorGDBRemote::ResponseType response_type =
40190b57cec5SDimitry Andric           response.GetResponseType();
40200b57cec5SDimitry Andric       if (response_type == StringExtractorGDBRemote::eResponse) {
40210b57cec5SDimitry Andric         if (!response.Empty()) {
40225ffd83dbSDimitry Andric           object_sp =
40235ffd83dbSDimitry Andric               StructuredData::ParseJSON(std::string(response.GetStringRef()));
40240b57cec5SDimitry Andric         }
40250b57cec5SDimitry Andric       }
40260b57cec5SDimitry Andric     }
40270b57cec5SDimitry Andric   }
40280b57cec5SDimitry Andric   return object_sp;
40290b57cec5SDimitry Andric }
40300b57cec5SDimitry Andric 
40310b57cec5SDimitry Andric StructuredData::ObjectSP ProcessGDBRemote::GetLoadedDynamicLibrariesInfos(
40320b57cec5SDimitry Andric     lldb::addr_t image_list_address, lldb::addr_t image_count) {
40330b57cec5SDimitry Andric 
40340b57cec5SDimitry Andric   StructuredData::ObjectSP args_dict(new StructuredData::Dictionary());
40350b57cec5SDimitry Andric   args_dict->GetAsDictionary()->AddIntegerItem("image_list_address",
40360b57cec5SDimitry Andric                                                image_list_address);
40370b57cec5SDimitry Andric   args_dict->GetAsDictionary()->AddIntegerItem("image_count", image_count);
40380b57cec5SDimitry Andric 
40390b57cec5SDimitry Andric   return GetLoadedDynamicLibrariesInfos_sender(args_dict);
40400b57cec5SDimitry Andric }
40410b57cec5SDimitry Andric 
40420b57cec5SDimitry Andric StructuredData::ObjectSP ProcessGDBRemote::GetLoadedDynamicLibrariesInfos() {
40430b57cec5SDimitry Andric   StructuredData::ObjectSP args_dict(new StructuredData::Dictionary());
40440b57cec5SDimitry Andric 
40450b57cec5SDimitry Andric   args_dict->GetAsDictionary()->AddBooleanItem("fetch_all_solibs", true);
40460b57cec5SDimitry Andric 
40470b57cec5SDimitry Andric   return GetLoadedDynamicLibrariesInfos_sender(args_dict);
40480b57cec5SDimitry Andric }
40490b57cec5SDimitry Andric 
40500b57cec5SDimitry Andric StructuredData::ObjectSP ProcessGDBRemote::GetLoadedDynamicLibrariesInfos(
40510b57cec5SDimitry Andric     const std::vector<lldb::addr_t> &load_addresses) {
40520b57cec5SDimitry Andric   StructuredData::ObjectSP args_dict(new StructuredData::Dictionary());
40530b57cec5SDimitry Andric   StructuredData::ArraySP addresses(new StructuredData::Array);
40540b57cec5SDimitry Andric 
40550b57cec5SDimitry Andric   for (auto addr : load_addresses) {
40560b57cec5SDimitry Andric     StructuredData::ObjectSP addr_sp(new StructuredData::Integer(addr));
40570b57cec5SDimitry Andric     addresses->AddItem(addr_sp);
40580b57cec5SDimitry Andric   }
40590b57cec5SDimitry Andric 
40600b57cec5SDimitry Andric   args_dict->GetAsDictionary()->AddItem("solib_addresses", addresses);
40610b57cec5SDimitry Andric 
40620b57cec5SDimitry Andric   return GetLoadedDynamicLibrariesInfos_sender(args_dict);
40630b57cec5SDimitry Andric }
40640b57cec5SDimitry Andric 
40650b57cec5SDimitry Andric StructuredData::ObjectSP
40660b57cec5SDimitry Andric ProcessGDBRemote::GetLoadedDynamicLibrariesInfos_sender(
40670b57cec5SDimitry Andric     StructuredData::ObjectSP args_dict) {
40680b57cec5SDimitry Andric   StructuredData::ObjectSP object_sp;
40690b57cec5SDimitry Andric 
40700b57cec5SDimitry Andric   if (m_gdb_comm.GetLoadedDynamicLibrariesInfosSupported()) {
40710b57cec5SDimitry Andric     // Scope for the scoped timeout object
40720b57cec5SDimitry Andric     GDBRemoteCommunication::ScopedTimeout timeout(m_gdb_comm,
40730b57cec5SDimitry Andric                                                   std::chrono::seconds(10));
40740b57cec5SDimitry Andric 
40750b57cec5SDimitry Andric     StreamString packet;
40760b57cec5SDimitry Andric     packet << "jGetLoadedDynamicLibrariesInfos:";
40770b57cec5SDimitry Andric     args_dict->Dump(packet, false);
40780b57cec5SDimitry Andric 
40790b57cec5SDimitry Andric     // FIXME the final character of a JSON dictionary, '}', is the escape
40800b57cec5SDimitry Andric     // character in gdb-remote binary mode.  lldb currently doesn't escape
40810b57cec5SDimitry Andric     // these characters in its packet output -- so we add the quoted version of
40820b57cec5SDimitry Andric     // the } character here manually in case we talk to a debugserver which un-
40830b57cec5SDimitry Andric     // escapes the characters at packet read time.
40840b57cec5SDimitry Andric     packet << (char)(0x7d ^ 0x20);
40850b57cec5SDimitry Andric 
40860b57cec5SDimitry Andric     StringExtractorGDBRemote response;
40870b57cec5SDimitry Andric     response.SetResponseValidatorToJSON();
40880b57cec5SDimitry Andric     if (m_gdb_comm.SendPacketAndWaitForResponse(packet.GetString(), response,
40890b57cec5SDimitry Andric                                                 false) ==
40900b57cec5SDimitry Andric         GDBRemoteCommunication::PacketResult::Success) {
40910b57cec5SDimitry Andric       StringExtractorGDBRemote::ResponseType response_type =
40920b57cec5SDimitry Andric           response.GetResponseType();
40930b57cec5SDimitry Andric       if (response_type == StringExtractorGDBRemote::eResponse) {
40940b57cec5SDimitry Andric         if (!response.Empty()) {
40955ffd83dbSDimitry Andric           object_sp =
40965ffd83dbSDimitry Andric               StructuredData::ParseJSON(std::string(response.GetStringRef()));
40970b57cec5SDimitry Andric         }
40980b57cec5SDimitry Andric       }
40990b57cec5SDimitry Andric     }
41000b57cec5SDimitry Andric   }
41010b57cec5SDimitry Andric   return object_sp;
41020b57cec5SDimitry Andric }
41030b57cec5SDimitry Andric 
41040b57cec5SDimitry Andric StructuredData::ObjectSP ProcessGDBRemote::GetSharedCacheInfo() {
41050b57cec5SDimitry Andric   StructuredData::ObjectSP object_sp;
41060b57cec5SDimitry Andric   StructuredData::ObjectSP args_dict(new StructuredData::Dictionary());
41070b57cec5SDimitry Andric 
41080b57cec5SDimitry Andric   if (m_gdb_comm.GetSharedCacheInfoSupported()) {
41090b57cec5SDimitry Andric     StreamString packet;
41100b57cec5SDimitry Andric     packet << "jGetSharedCacheInfo:";
41110b57cec5SDimitry Andric     args_dict->Dump(packet, false);
41120b57cec5SDimitry Andric 
41130b57cec5SDimitry Andric     // FIXME the final character of a JSON dictionary, '}', is the escape
41140b57cec5SDimitry Andric     // character in gdb-remote binary mode.  lldb currently doesn't escape
41150b57cec5SDimitry Andric     // these characters in its packet output -- so we add the quoted version of
41160b57cec5SDimitry Andric     // the } character here manually in case we talk to a debugserver which un-
41170b57cec5SDimitry Andric     // escapes the characters at packet read time.
41180b57cec5SDimitry Andric     packet << (char)(0x7d ^ 0x20);
41190b57cec5SDimitry Andric 
41200b57cec5SDimitry Andric     StringExtractorGDBRemote response;
41210b57cec5SDimitry Andric     response.SetResponseValidatorToJSON();
41220b57cec5SDimitry Andric     if (m_gdb_comm.SendPacketAndWaitForResponse(packet.GetString(), response,
41230b57cec5SDimitry Andric                                                 false) ==
41240b57cec5SDimitry Andric         GDBRemoteCommunication::PacketResult::Success) {
41250b57cec5SDimitry Andric       StringExtractorGDBRemote::ResponseType response_type =
41260b57cec5SDimitry Andric           response.GetResponseType();
41270b57cec5SDimitry Andric       if (response_type == StringExtractorGDBRemote::eResponse) {
41280b57cec5SDimitry Andric         if (!response.Empty()) {
41295ffd83dbSDimitry Andric           object_sp =
41305ffd83dbSDimitry Andric               StructuredData::ParseJSON(std::string(response.GetStringRef()));
41310b57cec5SDimitry Andric         }
41320b57cec5SDimitry Andric       }
41330b57cec5SDimitry Andric     }
41340b57cec5SDimitry Andric   }
41350b57cec5SDimitry Andric   return object_sp;
41360b57cec5SDimitry Andric }
41370b57cec5SDimitry Andric 
41380b57cec5SDimitry Andric Status ProcessGDBRemote::ConfigureStructuredData(
41390b57cec5SDimitry Andric     ConstString type_name, const StructuredData::ObjectSP &config_sp) {
41400b57cec5SDimitry Andric   return m_gdb_comm.ConfigureRemoteStructuredData(type_name, config_sp);
41410b57cec5SDimitry Andric }
41420b57cec5SDimitry Andric 
41430b57cec5SDimitry Andric // Establish the largest memory read/write payloads we should use. If the
41440b57cec5SDimitry Andric // remote stub has a max packet size, stay under that size.
41450b57cec5SDimitry Andric //
41460b57cec5SDimitry Andric // If the remote stub's max packet size is crazy large, use a reasonable
41470b57cec5SDimitry Andric // largeish default.
41480b57cec5SDimitry Andric //
41490b57cec5SDimitry Andric // If the remote stub doesn't advertise a max packet size, use a conservative
41500b57cec5SDimitry Andric // default.
41510b57cec5SDimitry Andric 
41520b57cec5SDimitry Andric void ProcessGDBRemote::GetMaxMemorySize() {
41530b57cec5SDimitry Andric   const uint64_t reasonable_largeish_default = 128 * 1024;
41540b57cec5SDimitry Andric   const uint64_t conservative_default = 512;
41550b57cec5SDimitry Andric 
41560b57cec5SDimitry Andric   if (m_max_memory_size == 0) {
41570b57cec5SDimitry Andric     uint64_t stub_max_size = m_gdb_comm.GetRemoteMaxPacketSize();
41580b57cec5SDimitry Andric     if (stub_max_size != UINT64_MAX && stub_max_size != 0) {
41590b57cec5SDimitry Andric       // Save the stub's claimed maximum packet size
41600b57cec5SDimitry Andric       m_remote_stub_max_memory_size = stub_max_size;
41610b57cec5SDimitry Andric 
41620b57cec5SDimitry Andric       // Even if the stub says it can support ginormous packets, don't exceed
41630b57cec5SDimitry Andric       // our reasonable largeish default packet size.
41640b57cec5SDimitry Andric       if (stub_max_size > reasonable_largeish_default) {
41650b57cec5SDimitry Andric         stub_max_size = reasonable_largeish_default;
41660b57cec5SDimitry Andric       }
41670b57cec5SDimitry Andric 
41680b57cec5SDimitry Andric       // Memory packet have other overheads too like Maddr,size:#NN Instead of
41690b57cec5SDimitry Andric       // calculating the bytes taken by size and addr every time, we take a
41700b57cec5SDimitry Andric       // maximum guess here.
41710b57cec5SDimitry Andric       if (stub_max_size > 70)
41720b57cec5SDimitry Andric         stub_max_size -= 32 + 32 + 6;
41730b57cec5SDimitry Andric       else {
41740b57cec5SDimitry Andric         // In unlikely scenario that max packet size is less then 70, we will
41750b57cec5SDimitry Andric         // hope that data being written is small enough to fit.
41760b57cec5SDimitry Andric         Log *log(ProcessGDBRemoteLog::GetLogIfAnyCategoryIsSet(
41770b57cec5SDimitry Andric             GDBR_LOG_COMM | GDBR_LOG_MEMORY));
41780b57cec5SDimitry Andric         if (log)
41790b57cec5SDimitry Andric           log->Warning("Packet size is too small. "
41800b57cec5SDimitry Andric                        "LLDB may face problems while writing memory");
41810b57cec5SDimitry Andric       }
41820b57cec5SDimitry Andric 
41830b57cec5SDimitry Andric       m_max_memory_size = stub_max_size;
41840b57cec5SDimitry Andric     } else {
41850b57cec5SDimitry Andric       m_max_memory_size = conservative_default;
41860b57cec5SDimitry Andric     }
41870b57cec5SDimitry Andric   }
41880b57cec5SDimitry Andric }
41890b57cec5SDimitry Andric 
41900b57cec5SDimitry Andric void ProcessGDBRemote::SetUserSpecifiedMaxMemoryTransferSize(
41910b57cec5SDimitry Andric     uint64_t user_specified_max) {
41920b57cec5SDimitry Andric   if (user_specified_max != 0) {
41930b57cec5SDimitry Andric     GetMaxMemorySize();
41940b57cec5SDimitry Andric 
41950b57cec5SDimitry Andric     if (m_remote_stub_max_memory_size != 0) {
41960b57cec5SDimitry Andric       if (m_remote_stub_max_memory_size < user_specified_max) {
41970b57cec5SDimitry Andric         m_max_memory_size = m_remote_stub_max_memory_size; // user specified a
41980b57cec5SDimitry Andric                                                            // packet size too
41990b57cec5SDimitry Andric                                                            // big, go as big
42000b57cec5SDimitry Andric         // as the remote stub says we can go.
42010b57cec5SDimitry Andric       } else {
42020b57cec5SDimitry Andric         m_max_memory_size = user_specified_max; // user's packet size is good
42030b57cec5SDimitry Andric       }
42040b57cec5SDimitry Andric     } else {
42050b57cec5SDimitry Andric       m_max_memory_size =
42060b57cec5SDimitry Andric           user_specified_max; // user's packet size is probably fine
42070b57cec5SDimitry Andric     }
42080b57cec5SDimitry Andric   }
42090b57cec5SDimitry Andric }
42100b57cec5SDimitry Andric 
42110b57cec5SDimitry Andric bool ProcessGDBRemote::GetModuleSpec(const FileSpec &module_file_spec,
42120b57cec5SDimitry Andric                                      const ArchSpec &arch,
42130b57cec5SDimitry Andric                                      ModuleSpec &module_spec) {
42140b57cec5SDimitry Andric   Log *log = GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PLATFORM);
42150b57cec5SDimitry Andric 
42160b57cec5SDimitry Andric   const ModuleCacheKey key(module_file_spec.GetPath(),
42170b57cec5SDimitry Andric                            arch.GetTriple().getTriple());
42180b57cec5SDimitry Andric   auto cached = m_cached_module_specs.find(key);
42190b57cec5SDimitry Andric   if (cached != m_cached_module_specs.end()) {
42200b57cec5SDimitry Andric     module_spec = cached->second;
42210b57cec5SDimitry Andric     return bool(module_spec);
42220b57cec5SDimitry Andric   }
42230b57cec5SDimitry Andric 
42240b57cec5SDimitry Andric   if (!m_gdb_comm.GetModuleInfo(module_file_spec, arch, module_spec)) {
42259dba64beSDimitry Andric     LLDB_LOGF(log, "ProcessGDBRemote::%s - failed to get module info for %s:%s",
42260b57cec5SDimitry Andric               __FUNCTION__, module_file_spec.GetPath().c_str(),
42270b57cec5SDimitry Andric               arch.GetTriple().getTriple().c_str());
42280b57cec5SDimitry Andric     return false;
42290b57cec5SDimitry Andric   }
42300b57cec5SDimitry Andric 
42310b57cec5SDimitry Andric   if (log) {
42320b57cec5SDimitry Andric     StreamString stream;
42330b57cec5SDimitry Andric     module_spec.Dump(stream);
42349dba64beSDimitry Andric     LLDB_LOGF(log, "ProcessGDBRemote::%s - got module info for (%s:%s) : %s",
42350b57cec5SDimitry Andric               __FUNCTION__, module_file_spec.GetPath().c_str(),
42360b57cec5SDimitry Andric               arch.GetTriple().getTriple().c_str(), stream.GetData());
42370b57cec5SDimitry Andric   }
42380b57cec5SDimitry Andric 
42390b57cec5SDimitry Andric   m_cached_module_specs[key] = module_spec;
42400b57cec5SDimitry Andric   return true;
42410b57cec5SDimitry Andric }
42420b57cec5SDimitry Andric 
42430b57cec5SDimitry Andric void ProcessGDBRemote::PrefetchModuleSpecs(
42440b57cec5SDimitry Andric     llvm::ArrayRef<FileSpec> module_file_specs, const llvm::Triple &triple) {
42450b57cec5SDimitry Andric   auto module_specs = m_gdb_comm.GetModulesInfo(module_file_specs, triple);
42460b57cec5SDimitry Andric   if (module_specs) {
42470b57cec5SDimitry Andric     for (const FileSpec &spec : module_file_specs)
42480b57cec5SDimitry Andric       m_cached_module_specs[ModuleCacheKey(spec.GetPath(),
42490b57cec5SDimitry Andric                                            triple.getTriple())] = ModuleSpec();
42500b57cec5SDimitry Andric     for (const ModuleSpec &spec : *module_specs)
42510b57cec5SDimitry Andric       m_cached_module_specs[ModuleCacheKey(spec.GetFileSpec().GetPath(),
42520b57cec5SDimitry Andric                                            triple.getTriple())] = spec;
42530b57cec5SDimitry Andric   }
42540b57cec5SDimitry Andric }
42550b57cec5SDimitry Andric 
42560b57cec5SDimitry Andric llvm::VersionTuple ProcessGDBRemote::GetHostOSVersion() {
42570b57cec5SDimitry Andric   return m_gdb_comm.GetOSVersion();
42580b57cec5SDimitry Andric }
42590b57cec5SDimitry Andric 
42609dba64beSDimitry Andric llvm::VersionTuple ProcessGDBRemote::GetHostMacCatalystVersion() {
42619dba64beSDimitry Andric   return m_gdb_comm.GetMacCatalystVersion();
42629dba64beSDimitry Andric }
42639dba64beSDimitry Andric 
42640b57cec5SDimitry Andric namespace {
42650b57cec5SDimitry Andric 
42660b57cec5SDimitry Andric typedef std::vector<std::string> stringVec;
42670b57cec5SDimitry Andric 
42680b57cec5SDimitry Andric typedef std::vector<struct GdbServerRegisterInfo> GDBServerRegisterVec;
42690b57cec5SDimitry Andric struct RegisterSetInfo {
42700b57cec5SDimitry Andric   ConstString name;
42710b57cec5SDimitry Andric };
42720b57cec5SDimitry Andric 
42730b57cec5SDimitry Andric typedef std::map<uint32_t, RegisterSetInfo> RegisterSetMap;
42740b57cec5SDimitry Andric 
42750b57cec5SDimitry Andric struct GdbServerTargetInfo {
42760b57cec5SDimitry Andric   std::string arch;
42770b57cec5SDimitry Andric   std::string osabi;
42780b57cec5SDimitry Andric   stringVec includes;
42790b57cec5SDimitry Andric   RegisterSetMap reg_set_map;
42800b57cec5SDimitry Andric };
42810b57cec5SDimitry Andric 
42820b57cec5SDimitry Andric bool ParseRegisters(XMLNode feature_node, GdbServerTargetInfo &target_info,
42830b57cec5SDimitry Andric                     GDBRemoteDynamicRegisterInfo &dyn_reg_info, ABISP abi_sp,
42840b57cec5SDimitry Andric                     uint32_t &cur_reg_num, uint32_t &reg_offset) {
42850b57cec5SDimitry Andric   if (!feature_node)
42860b57cec5SDimitry Andric     return false;
42870b57cec5SDimitry Andric 
42880b57cec5SDimitry Andric   feature_node.ForEachChildElementWithName(
42890b57cec5SDimitry Andric       "reg",
42900b57cec5SDimitry Andric       [&target_info, &dyn_reg_info, &cur_reg_num, &reg_offset,
42910b57cec5SDimitry Andric        &abi_sp](const XMLNode &reg_node) -> bool {
42920b57cec5SDimitry Andric         std::string gdb_group;
42930b57cec5SDimitry Andric         std::string gdb_type;
42940b57cec5SDimitry Andric         ConstString reg_name;
42950b57cec5SDimitry Andric         ConstString alt_name;
42960b57cec5SDimitry Andric         ConstString set_name;
42970b57cec5SDimitry Andric         std::vector<uint32_t> value_regs;
42980b57cec5SDimitry Andric         std::vector<uint32_t> invalidate_regs;
42990b57cec5SDimitry Andric         std::vector<uint8_t> dwarf_opcode_bytes;
43000b57cec5SDimitry Andric         bool encoding_set = false;
43010b57cec5SDimitry Andric         bool format_set = false;
43020b57cec5SDimitry Andric         RegisterInfo reg_info = {
43030b57cec5SDimitry Andric             nullptr,       // Name
43040b57cec5SDimitry Andric             nullptr,       // Alt name
43050b57cec5SDimitry Andric             0,             // byte size
43060b57cec5SDimitry Andric             reg_offset,    // offset
43070b57cec5SDimitry Andric             eEncodingUint, // encoding
43080b57cec5SDimitry Andric             eFormatHex,    // format
43090b57cec5SDimitry Andric             {
43100b57cec5SDimitry Andric                 LLDB_INVALID_REGNUM, // eh_frame reg num
43110b57cec5SDimitry Andric                 LLDB_INVALID_REGNUM, // DWARF reg num
43120b57cec5SDimitry Andric                 LLDB_INVALID_REGNUM, // generic reg num
43130b57cec5SDimitry Andric                 cur_reg_num,         // process plugin reg num
43140b57cec5SDimitry Andric                 cur_reg_num          // native register number
43150b57cec5SDimitry Andric             },
43160b57cec5SDimitry Andric             nullptr,
43170b57cec5SDimitry Andric             nullptr,
43180b57cec5SDimitry Andric             nullptr, // Dwarf Expression opcode bytes pointer
43190b57cec5SDimitry Andric             0        // Dwarf Expression opcode bytes length
43200b57cec5SDimitry Andric         };
43210b57cec5SDimitry Andric 
43220b57cec5SDimitry Andric         reg_node.ForEachAttribute([&target_info, &gdb_group, &gdb_type,
43230b57cec5SDimitry Andric                                    &reg_name, &alt_name, &set_name, &value_regs,
43240b57cec5SDimitry Andric                                    &invalidate_regs, &encoding_set, &format_set,
43250b57cec5SDimitry Andric                                    &reg_info, &reg_offset, &dwarf_opcode_bytes](
43260b57cec5SDimitry Andric                                       const llvm::StringRef &name,
43270b57cec5SDimitry Andric                                       const llvm::StringRef &value) -> bool {
43280b57cec5SDimitry Andric           if (name == "name") {
43290b57cec5SDimitry Andric             reg_name.SetString(value);
43300b57cec5SDimitry Andric           } else if (name == "bitsize") {
43310b57cec5SDimitry Andric             reg_info.byte_size =
43320b57cec5SDimitry Andric                 StringConvert::ToUInt32(value.data(), 0, 0) / CHAR_BIT;
43330b57cec5SDimitry Andric           } else if (name == "type") {
43340b57cec5SDimitry Andric             gdb_type = value.str();
43350b57cec5SDimitry Andric           } else if (name == "group") {
43360b57cec5SDimitry Andric             gdb_group = value.str();
43370b57cec5SDimitry Andric           } else if (name == "regnum") {
43380b57cec5SDimitry Andric             const uint32_t regnum =
43390b57cec5SDimitry Andric                 StringConvert::ToUInt32(value.data(), LLDB_INVALID_REGNUM, 0);
43400b57cec5SDimitry Andric             if (regnum != LLDB_INVALID_REGNUM) {
43410b57cec5SDimitry Andric               reg_info.kinds[eRegisterKindProcessPlugin] = regnum;
43420b57cec5SDimitry Andric             }
43430b57cec5SDimitry Andric           } else if (name == "offset") {
43440b57cec5SDimitry Andric             reg_offset = StringConvert::ToUInt32(value.data(), UINT32_MAX, 0);
43450b57cec5SDimitry Andric           } else if (name == "altname") {
43460b57cec5SDimitry Andric             alt_name.SetString(value);
43470b57cec5SDimitry Andric           } else if (name == "encoding") {
43480b57cec5SDimitry Andric             encoding_set = true;
43490b57cec5SDimitry Andric             reg_info.encoding = Args::StringToEncoding(value, eEncodingUint);
43500b57cec5SDimitry Andric           } else if (name == "format") {
43510b57cec5SDimitry Andric             format_set = true;
43520b57cec5SDimitry Andric             Format format = eFormatInvalid;
43530b57cec5SDimitry Andric             if (OptionArgParser::ToFormat(value.data(), format, nullptr)
43540b57cec5SDimitry Andric                     .Success())
43550b57cec5SDimitry Andric               reg_info.format = format;
43560b57cec5SDimitry Andric             else if (value == "vector-sint8")
43570b57cec5SDimitry Andric               reg_info.format = eFormatVectorOfSInt8;
43580b57cec5SDimitry Andric             else if (value == "vector-uint8")
43590b57cec5SDimitry Andric               reg_info.format = eFormatVectorOfUInt8;
43600b57cec5SDimitry Andric             else if (value == "vector-sint16")
43610b57cec5SDimitry Andric               reg_info.format = eFormatVectorOfSInt16;
43620b57cec5SDimitry Andric             else if (value == "vector-uint16")
43630b57cec5SDimitry Andric               reg_info.format = eFormatVectorOfUInt16;
43640b57cec5SDimitry Andric             else if (value == "vector-sint32")
43650b57cec5SDimitry Andric               reg_info.format = eFormatVectorOfSInt32;
43660b57cec5SDimitry Andric             else if (value == "vector-uint32")
43670b57cec5SDimitry Andric               reg_info.format = eFormatVectorOfUInt32;
43680b57cec5SDimitry Andric             else if (value == "vector-float32")
43690b57cec5SDimitry Andric               reg_info.format = eFormatVectorOfFloat32;
43700b57cec5SDimitry Andric             else if (value == "vector-uint64")
43710b57cec5SDimitry Andric               reg_info.format = eFormatVectorOfUInt64;
43720b57cec5SDimitry Andric             else if (value == "vector-uint128")
43730b57cec5SDimitry Andric               reg_info.format = eFormatVectorOfUInt128;
43740b57cec5SDimitry Andric           } else if (name == "group_id") {
43750b57cec5SDimitry Andric             const uint32_t set_id =
43760b57cec5SDimitry Andric                 StringConvert::ToUInt32(value.data(), UINT32_MAX, 0);
43770b57cec5SDimitry Andric             RegisterSetMap::const_iterator pos =
43780b57cec5SDimitry Andric                 target_info.reg_set_map.find(set_id);
43790b57cec5SDimitry Andric             if (pos != target_info.reg_set_map.end())
43800b57cec5SDimitry Andric               set_name = pos->second.name;
43810b57cec5SDimitry Andric           } else if (name == "gcc_regnum" || name == "ehframe_regnum") {
43820b57cec5SDimitry Andric             reg_info.kinds[eRegisterKindEHFrame] =
43830b57cec5SDimitry Andric                 StringConvert::ToUInt32(value.data(), LLDB_INVALID_REGNUM, 0);
43840b57cec5SDimitry Andric           } else if (name == "dwarf_regnum") {
43850b57cec5SDimitry Andric             reg_info.kinds[eRegisterKindDWARF] =
43860b57cec5SDimitry Andric                 StringConvert::ToUInt32(value.data(), LLDB_INVALID_REGNUM, 0);
43870b57cec5SDimitry Andric           } else if (name == "generic") {
43880b57cec5SDimitry Andric             reg_info.kinds[eRegisterKindGeneric] =
43890b57cec5SDimitry Andric                 Args::StringToGenericRegister(value);
43900b57cec5SDimitry Andric           } else if (name == "value_regnums") {
43910b57cec5SDimitry Andric             SplitCommaSeparatedRegisterNumberString(value, value_regs, 0);
43920b57cec5SDimitry Andric           } else if (name == "invalidate_regnums") {
43930b57cec5SDimitry Andric             SplitCommaSeparatedRegisterNumberString(value, invalidate_regs, 0);
43940b57cec5SDimitry Andric           } else if (name == "dynamic_size_dwarf_expr_bytes") {
43950b57cec5SDimitry Andric             std::string opcode_string = value.str();
43960b57cec5SDimitry Andric             size_t dwarf_opcode_len = opcode_string.length() / 2;
43970b57cec5SDimitry Andric             assert(dwarf_opcode_len > 0);
43980b57cec5SDimitry Andric 
43990b57cec5SDimitry Andric             dwarf_opcode_bytes.resize(dwarf_opcode_len);
44000b57cec5SDimitry Andric             reg_info.dynamic_size_dwarf_len = dwarf_opcode_len;
44019dba64beSDimitry Andric             StringExtractor opcode_extractor(opcode_string);
44020b57cec5SDimitry Andric             uint32_t ret_val =
44030b57cec5SDimitry Andric                 opcode_extractor.GetHexBytesAvail(dwarf_opcode_bytes);
44040b57cec5SDimitry Andric             assert(dwarf_opcode_len == ret_val);
44050b57cec5SDimitry Andric             UNUSED_IF_ASSERT_DISABLED(ret_val);
44060b57cec5SDimitry Andric             reg_info.dynamic_size_dwarf_expr_bytes = dwarf_opcode_bytes.data();
44070b57cec5SDimitry Andric           } else {
44080b57cec5SDimitry Andric             printf("unhandled attribute %s = %s\n", name.data(), value.data());
44090b57cec5SDimitry Andric           }
44100b57cec5SDimitry Andric           return true; // Keep iterating through all attributes
44110b57cec5SDimitry Andric         });
44120b57cec5SDimitry Andric 
44130b57cec5SDimitry Andric         if (!gdb_type.empty() && !(encoding_set || format_set)) {
44145ffd83dbSDimitry Andric           if (llvm::StringRef(gdb_type).startswith("int")) {
44150b57cec5SDimitry Andric             reg_info.format = eFormatHex;
44160b57cec5SDimitry Andric             reg_info.encoding = eEncodingUint;
44170b57cec5SDimitry Andric           } else if (gdb_type == "data_ptr" || gdb_type == "code_ptr") {
44180b57cec5SDimitry Andric             reg_info.format = eFormatAddressInfo;
44190b57cec5SDimitry Andric             reg_info.encoding = eEncodingUint;
44200b57cec5SDimitry Andric           } else if (gdb_type == "i387_ext" || gdb_type == "float") {
44210b57cec5SDimitry Andric             reg_info.format = eFormatFloat;
44220b57cec5SDimitry Andric             reg_info.encoding = eEncodingIEEE754;
44230b57cec5SDimitry Andric           }
44240b57cec5SDimitry Andric         }
44250b57cec5SDimitry Andric 
44260b57cec5SDimitry Andric         // Only update the register set name if we didn't get a "reg_set"
44270b57cec5SDimitry Andric         // attribute. "set_name" will be empty if we didn't have a "reg_set"
44280b57cec5SDimitry Andric         // attribute.
44290b57cec5SDimitry Andric         if (!set_name) {
44300b57cec5SDimitry Andric           if (!gdb_group.empty()) {
44310b57cec5SDimitry Andric             set_name.SetCString(gdb_group.c_str());
44320b57cec5SDimitry Andric           } else {
44330b57cec5SDimitry Andric             // If no register group name provided anywhere,
44340b57cec5SDimitry Andric             // we'll create a 'general' register set
44350b57cec5SDimitry Andric             set_name.SetCString("general");
44360b57cec5SDimitry Andric           }
44370b57cec5SDimitry Andric         }
44380b57cec5SDimitry Andric 
44390b57cec5SDimitry Andric         reg_info.byte_offset = reg_offset;
44400b57cec5SDimitry Andric         assert(reg_info.byte_size != 0);
44410b57cec5SDimitry Andric         reg_offset += reg_info.byte_size;
44420b57cec5SDimitry Andric         if (!value_regs.empty()) {
44430b57cec5SDimitry Andric           value_regs.push_back(LLDB_INVALID_REGNUM);
44440b57cec5SDimitry Andric           reg_info.value_regs = value_regs.data();
44450b57cec5SDimitry Andric         }
44460b57cec5SDimitry Andric         if (!invalidate_regs.empty()) {
44470b57cec5SDimitry Andric           invalidate_regs.push_back(LLDB_INVALID_REGNUM);
44480b57cec5SDimitry Andric           reg_info.invalidate_regs = invalidate_regs.data();
44490b57cec5SDimitry Andric         }
44500b57cec5SDimitry Andric 
44510b57cec5SDimitry Andric         ++cur_reg_num;
4452480093f4SDimitry Andric         reg_info.name = reg_name.AsCString();
4453480093f4SDimitry Andric         if (abi_sp)
4454480093f4SDimitry Andric           abi_sp->AugmentRegisterInfo(reg_info);
44550b57cec5SDimitry Andric         dyn_reg_info.AddRegister(reg_info, reg_name, alt_name, set_name);
44560b57cec5SDimitry Andric 
44570b57cec5SDimitry Andric         return true; // Keep iterating through all "reg" elements
44580b57cec5SDimitry Andric       });
44590b57cec5SDimitry Andric   return true;
44600b57cec5SDimitry Andric }
44610b57cec5SDimitry Andric 
44620b57cec5SDimitry Andric } // namespace
44630b57cec5SDimitry Andric 
44640b57cec5SDimitry Andric // This method fetches a register description feature xml file from
44650b57cec5SDimitry Andric // the remote stub and adds registers/register groupsets/architecture
44660b57cec5SDimitry Andric // information to the current process.  It will call itself recursively
44670b57cec5SDimitry Andric // for nested register definition files.  It returns true if it was able
44680b57cec5SDimitry Andric // to fetch and parse an xml file.
44699dba64beSDimitry Andric bool ProcessGDBRemote::GetGDBServerRegisterInfoXMLAndProcess(
44709dba64beSDimitry Andric     ArchSpec &arch_to_use, std::string xml_filename, uint32_t &cur_reg_num,
44710b57cec5SDimitry Andric     uint32_t &reg_offset) {
44720b57cec5SDimitry Andric   // request the target xml file
44730b57cec5SDimitry Andric   std::string raw;
44740b57cec5SDimitry Andric   lldb_private::Status lldberr;
44750b57cec5SDimitry Andric   if (!m_gdb_comm.ReadExtFeature(ConstString("features"),
44769dba64beSDimitry Andric                                  ConstString(xml_filename.c_str()), raw,
44779dba64beSDimitry Andric                                  lldberr)) {
44780b57cec5SDimitry Andric     return false;
44790b57cec5SDimitry Andric   }
44800b57cec5SDimitry Andric 
44810b57cec5SDimitry Andric   XMLDocument xml_document;
44820b57cec5SDimitry Andric 
44830b57cec5SDimitry Andric   if (xml_document.ParseMemory(raw.c_str(), raw.size(), xml_filename.c_str())) {
44840b57cec5SDimitry Andric     GdbServerTargetInfo target_info;
44850b57cec5SDimitry Andric     std::vector<XMLNode> feature_nodes;
44860b57cec5SDimitry Andric 
44870b57cec5SDimitry Andric     // The top level feature XML file will start with a <target> tag.
44880b57cec5SDimitry Andric     XMLNode target_node = xml_document.GetRootElement("target");
44890b57cec5SDimitry Andric     if (target_node) {
44900b57cec5SDimitry Andric       target_node.ForEachChildElement([&target_info, &feature_nodes](
44910b57cec5SDimitry Andric                                           const XMLNode &node) -> bool {
44920b57cec5SDimitry Andric         llvm::StringRef name = node.GetName();
44930b57cec5SDimitry Andric         if (name == "architecture") {
44940b57cec5SDimitry Andric           node.GetElementText(target_info.arch);
44950b57cec5SDimitry Andric         } else if (name == "osabi") {
44960b57cec5SDimitry Andric           node.GetElementText(target_info.osabi);
44970b57cec5SDimitry Andric         } else if (name == "xi:include" || name == "include") {
44980b57cec5SDimitry Andric           llvm::StringRef href = node.GetAttributeValue("href");
44990b57cec5SDimitry Andric           if (!href.empty())
45000b57cec5SDimitry Andric             target_info.includes.push_back(href.str());
45010b57cec5SDimitry Andric         } else if (name == "feature") {
45020b57cec5SDimitry Andric           feature_nodes.push_back(node);
45030b57cec5SDimitry Andric         } else if (name == "groups") {
45040b57cec5SDimitry Andric           node.ForEachChildElementWithName(
45050b57cec5SDimitry Andric               "group", [&target_info](const XMLNode &node) -> bool {
45060b57cec5SDimitry Andric                 uint32_t set_id = UINT32_MAX;
45070b57cec5SDimitry Andric                 RegisterSetInfo set_info;
45080b57cec5SDimitry Andric 
45090b57cec5SDimitry Andric                 node.ForEachAttribute(
45100b57cec5SDimitry Andric                     [&set_id, &set_info](const llvm::StringRef &name,
45110b57cec5SDimitry Andric                                          const llvm::StringRef &value) -> bool {
45120b57cec5SDimitry Andric                       if (name == "id")
45130b57cec5SDimitry Andric                         set_id = StringConvert::ToUInt32(value.data(),
45140b57cec5SDimitry Andric                                                          UINT32_MAX, 0);
45150b57cec5SDimitry Andric                       if (name == "name")
45160b57cec5SDimitry Andric                         set_info.name = ConstString(value);
45170b57cec5SDimitry Andric                       return true; // Keep iterating through all attributes
45180b57cec5SDimitry Andric                     });
45190b57cec5SDimitry Andric 
45200b57cec5SDimitry Andric                 if (set_id != UINT32_MAX)
45210b57cec5SDimitry Andric                   target_info.reg_set_map[set_id] = set_info;
45220b57cec5SDimitry Andric                 return true; // Keep iterating through all "group" elements
45230b57cec5SDimitry Andric               });
45240b57cec5SDimitry Andric         }
45250b57cec5SDimitry Andric         return true; // Keep iterating through all children of the target_node
45260b57cec5SDimitry Andric       });
45270b57cec5SDimitry Andric     } else {
45280b57cec5SDimitry Andric       // In an included XML feature file, we're already "inside" the <target>
45290b57cec5SDimitry Andric       // tag of the initial XML file; this included file will likely only have
45300b57cec5SDimitry Andric       // a <feature> tag.  Need to check for any more included files in this
45310b57cec5SDimitry Andric       // <feature> element.
45320b57cec5SDimitry Andric       XMLNode feature_node = xml_document.GetRootElement("feature");
45330b57cec5SDimitry Andric       if (feature_node) {
45340b57cec5SDimitry Andric         feature_nodes.push_back(feature_node);
45350b57cec5SDimitry Andric         feature_node.ForEachChildElement([&target_info](
45360b57cec5SDimitry Andric                                         const XMLNode &node) -> bool {
45370b57cec5SDimitry Andric           llvm::StringRef name = node.GetName();
45380b57cec5SDimitry Andric           if (name == "xi:include" || name == "include") {
45390b57cec5SDimitry Andric             llvm::StringRef href = node.GetAttributeValue("href");
45400b57cec5SDimitry Andric             if (!href.empty())
45410b57cec5SDimitry Andric               target_info.includes.push_back(href.str());
45420b57cec5SDimitry Andric             }
45430b57cec5SDimitry Andric             return true;
45440b57cec5SDimitry Andric           });
45450b57cec5SDimitry Andric       }
45460b57cec5SDimitry Andric     }
45470b57cec5SDimitry Andric 
45480b57cec5SDimitry Andric     // If the target.xml includes an architecture entry like
45490b57cec5SDimitry Andric     //   <architecture>i386:x86-64</architecture> (seen from VMWare ESXi)
45500b57cec5SDimitry Andric     //   <architecture>arm</architecture> (seen from Segger JLink on unspecified arm board)
45510b57cec5SDimitry Andric     // use that if we don't have anything better.
45520b57cec5SDimitry Andric     if (!arch_to_use.IsValid() && !target_info.arch.empty()) {
45530b57cec5SDimitry Andric       if (target_info.arch == "i386:x86-64") {
45540b57cec5SDimitry Andric         // We don't have any information about vendor or OS.
45550b57cec5SDimitry Andric         arch_to_use.SetTriple("x86_64--");
45560b57cec5SDimitry Andric         GetTarget().MergeArchitecture(arch_to_use);
45570b57cec5SDimitry Andric       }
45580b57cec5SDimitry Andric 
45590b57cec5SDimitry Andric       // SEGGER J-Link jtag boards send this very-generic arch name,
45600b57cec5SDimitry Andric       // we'll need to use this if we have absolutely nothing better
45610b57cec5SDimitry Andric       // to work with or the register definitions won't be accepted.
45620b57cec5SDimitry Andric       if (target_info.arch == "arm") {
45630b57cec5SDimitry Andric         arch_to_use.SetTriple("arm--");
45640b57cec5SDimitry Andric         GetTarget().MergeArchitecture(arch_to_use);
45650b57cec5SDimitry Andric       }
45660b57cec5SDimitry Andric     }
45670b57cec5SDimitry Andric 
45680b57cec5SDimitry Andric     if (arch_to_use.IsValid()) {
45690b57cec5SDimitry Andric       // Don't use Process::GetABI, this code gets called from DidAttach, and
45700b57cec5SDimitry Andric       // in that context we haven't set the Target's architecture yet, so the
45710b57cec5SDimitry Andric       // ABI is also potentially incorrect.
45720b57cec5SDimitry Andric       ABISP abi_to_use_sp = ABI::FindPlugin(shared_from_this(), arch_to_use);
45730b57cec5SDimitry Andric       for (auto &feature_node : feature_nodes) {
45740b57cec5SDimitry Andric         ParseRegisters(feature_node, target_info, this->m_register_info,
45750b57cec5SDimitry Andric                        abi_to_use_sp, cur_reg_num, reg_offset);
45760b57cec5SDimitry Andric       }
45770b57cec5SDimitry Andric 
45780b57cec5SDimitry Andric       for (const auto &include : target_info.includes) {
45799dba64beSDimitry Andric         GetGDBServerRegisterInfoXMLAndProcess(arch_to_use, include, cur_reg_num,
45809dba64beSDimitry Andric                                               reg_offset);
45810b57cec5SDimitry Andric       }
45820b57cec5SDimitry Andric     }
45830b57cec5SDimitry Andric   } else {
45840b57cec5SDimitry Andric     return false;
45850b57cec5SDimitry Andric   }
45860b57cec5SDimitry Andric   return true;
45870b57cec5SDimitry Andric }
45880b57cec5SDimitry Andric 
45890b57cec5SDimitry Andric // query the target of gdb-remote for extended target information returns
45900b57cec5SDimitry Andric // true on success (got register definitions), false on failure (did not).
45910b57cec5SDimitry Andric bool ProcessGDBRemote::GetGDBServerRegisterInfo(ArchSpec &arch_to_use) {
45920b57cec5SDimitry Andric   // Make sure LLDB has an XML parser it can use first
45930b57cec5SDimitry Andric   if (!XMLDocument::XMLEnabled())
45940b57cec5SDimitry Andric     return false;
45950b57cec5SDimitry Andric 
45960b57cec5SDimitry Andric   // check that we have extended feature read support
45970b57cec5SDimitry Andric   if (!m_gdb_comm.GetQXferFeaturesReadSupported())
45980b57cec5SDimitry Andric     return false;
45990b57cec5SDimitry Andric 
46000b57cec5SDimitry Andric   uint32_t cur_reg_num = 0;
46010b57cec5SDimitry Andric   uint32_t reg_offset = 0;
46020b57cec5SDimitry Andric   if (GetGDBServerRegisterInfoXMLAndProcess (arch_to_use, "target.xml", cur_reg_num, reg_offset))
46030b57cec5SDimitry Andric     this->m_register_info.Finalize(arch_to_use);
46040b57cec5SDimitry Andric 
46050b57cec5SDimitry Andric   return m_register_info.GetNumRegisters() > 0;
46060b57cec5SDimitry Andric }
46070b57cec5SDimitry Andric 
46089dba64beSDimitry Andric llvm::Expected<LoadedModuleInfoList> ProcessGDBRemote::GetLoadedModuleList() {
46090b57cec5SDimitry Andric   // Make sure LLDB has an XML parser it can use first
46100b57cec5SDimitry Andric   if (!XMLDocument::XMLEnabled())
46119dba64beSDimitry Andric     return llvm::createStringError(llvm::inconvertibleErrorCode(),
46129dba64beSDimitry Andric                                    "XML parsing not available");
46130b57cec5SDimitry Andric 
46140b57cec5SDimitry Andric   Log *log = GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS);
46159dba64beSDimitry Andric   LLDB_LOGF(log, "ProcessGDBRemote::%s", __FUNCTION__);
46160b57cec5SDimitry Andric 
46179dba64beSDimitry Andric   LoadedModuleInfoList list;
46180b57cec5SDimitry Andric   GDBRemoteCommunicationClient &comm = m_gdb_comm;
46190b57cec5SDimitry Andric   bool can_use_svr4 = GetGlobalPluginProperties()->GetUseSVR4();
46200b57cec5SDimitry Andric 
46210b57cec5SDimitry Andric   // check that we have extended feature read support
46220b57cec5SDimitry Andric   if (can_use_svr4 && comm.GetQXferLibrariesSVR4ReadSupported()) {
46230b57cec5SDimitry Andric     // request the loaded library list
46240b57cec5SDimitry Andric     std::string raw;
46250b57cec5SDimitry Andric     lldb_private::Status lldberr;
46260b57cec5SDimitry Andric 
46270b57cec5SDimitry Andric     if (!comm.ReadExtFeature(ConstString("libraries-svr4"), ConstString(""),
46280b57cec5SDimitry Andric                              raw, lldberr))
46299dba64beSDimitry Andric       return llvm::createStringError(llvm::inconvertibleErrorCode(),
46309dba64beSDimitry Andric                                      "Error in libraries-svr4 packet");
46310b57cec5SDimitry Andric 
46320b57cec5SDimitry Andric     // parse the xml file in memory
46339dba64beSDimitry Andric     LLDB_LOGF(log, "parsing: %s", raw.c_str());
46340b57cec5SDimitry Andric     XMLDocument doc;
46350b57cec5SDimitry Andric 
46360b57cec5SDimitry Andric     if (!doc.ParseMemory(raw.c_str(), raw.size(), "noname.xml"))
46379dba64beSDimitry Andric       return llvm::createStringError(llvm::inconvertibleErrorCode(),
46389dba64beSDimitry Andric                                      "Error reading noname.xml");
46390b57cec5SDimitry Andric 
46400b57cec5SDimitry Andric     XMLNode root_element = doc.GetRootElement("library-list-svr4");
46410b57cec5SDimitry Andric     if (!root_element)
46429dba64beSDimitry Andric       return llvm::createStringError(
46439dba64beSDimitry Andric           llvm::inconvertibleErrorCode(),
46449dba64beSDimitry Andric           "Error finding library-list-svr4 xml element");
46450b57cec5SDimitry Andric 
46460b57cec5SDimitry Andric     // main link map structure
46470b57cec5SDimitry Andric     llvm::StringRef main_lm = root_element.GetAttributeValue("main-lm");
46480b57cec5SDimitry Andric     if (!main_lm.empty()) {
46490b57cec5SDimitry Andric       list.m_link_map =
46500b57cec5SDimitry Andric           StringConvert::ToUInt64(main_lm.data(), LLDB_INVALID_ADDRESS, 0);
46510b57cec5SDimitry Andric     }
46520b57cec5SDimitry Andric 
46530b57cec5SDimitry Andric     root_element.ForEachChildElementWithName(
46540b57cec5SDimitry Andric         "library", [log, &list](const XMLNode &library) -> bool {
46550b57cec5SDimitry Andric 
46560b57cec5SDimitry Andric           LoadedModuleInfoList::LoadedModuleInfo module;
46570b57cec5SDimitry Andric 
46580b57cec5SDimitry Andric           library.ForEachAttribute(
46590b57cec5SDimitry Andric               [&module](const llvm::StringRef &name,
46600b57cec5SDimitry Andric                         const llvm::StringRef &value) -> bool {
46610b57cec5SDimitry Andric 
46620b57cec5SDimitry Andric                 if (name == "name")
46630b57cec5SDimitry Andric                   module.set_name(value.str());
46640b57cec5SDimitry Andric                 else if (name == "lm") {
46650b57cec5SDimitry Andric                   // the address of the link_map struct.
46660b57cec5SDimitry Andric                   module.set_link_map(StringConvert::ToUInt64(
46670b57cec5SDimitry Andric                       value.data(), LLDB_INVALID_ADDRESS, 0));
46680b57cec5SDimitry Andric                 } else if (name == "l_addr") {
46690b57cec5SDimitry Andric                   // the displacement as read from the field 'l_addr' of the
46700b57cec5SDimitry Andric                   // link_map struct.
46710b57cec5SDimitry Andric                   module.set_base(StringConvert::ToUInt64(
46720b57cec5SDimitry Andric                       value.data(), LLDB_INVALID_ADDRESS, 0));
46730b57cec5SDimitry Andric                   // base address is always a displacement, not an absolute
46740b57cec5SDimitry Andric                   // value.
46750b57cec5SDimitry Andric                   module.set_base_is_offset(true);
46760b57cec5SDimitry Andric                 } else if (name == "l_ld") {
46775ffd83dbSDimitry Andric                   // the memory address of the libraries PT_DYNAMIC section.
46780b57cec5SDimitry Andric                   module.set_dynamic(StringConvert::ToUInt64(
46790b57cec5SDimitry Andric                       value.data(), LLDB_INVALID_ADDRESS, 0));
46800b57cec5SDimitry Andric                 }
46810b57cec5SDimitry Andric 
46820b57cec5SDimitry Andric                 return true; // Keep iterating over all properties of "library"
46830b57cec5SDimitry Andric               });
46840b57cec5SDimitry Andric 
46850b57cec5SDimitry Andric           if (log) {
46860b57cec5SDimitry Andric             std::string name;
46870b57cec5SDimitry Andric             lldb::addr_t lm = 0, base = 0, ld = 0;
46880b57cec5SDimitry Andric             bool base_is_offset;
46890b57cec5SDimitry Andric 
46900b57cec5SDimitry Andric             module.get_name(name);
46910b57cec5SDimitry Andric             module.get_link_map(lm);
46920b57cec5SDimitry Andric             module.get_base(base);
46930b57cec5SDimitry Andric             module.get_base_is_offset(base_is_offset);
46940b57cec5SDimitry Andric             module.get_dynamic(ld);
46950b57cec5SDimitry Andric 
46969dba64beSDimitry Andric             LLDB_LOGF(log,
46979dba64beSDimitry Andric                       "found (link_map:0x%08" PRIx64 ", base:0x%08" PRIx64
46980b57cec5SDimitry Andric                       "[%s], ld:0x%08" PRIx64 ", name:'%s')",
46990b57cec5SDimitry Andric                       lm, base, (base_is_offset ? "offset" : "absolute"), ld,
47000b57cec5SDimitry Andric                       name.c_str());
47010b57cec5SDimitry Andric           }
47020b57cec5SDimitry Andric 
47030b57cec5SDimitry Andric           list.add(module);
47040b57cec5SDimitry Andric           return true; // Keep iterating over all "library" elements in the root
47050b57cec5SDimitry Andric                        // node
47060b57cec5SDimitry Andric         });
47070b57cec5SDimitry Andric 
47080b57cec5SDimitry Andric     if (log)
47099dba64beSDimitry Andric       LLDB_LOGF(log, "found %" PRId32 " modules in total",
47100b57cec5SDimitry Andric                 (int)list.m_list.size());
47119dba64beSDimitry Andric     return list;
47120b57cec5SDimitry Andric   } else if (comm.GetQXferLibrariesReadSupported()) {
47130b57cec5SDimitry Andric     // request the loaded library list
47140b57cec5SDimitry Andric     std::string raw;
47150b57cec5SDimitry Andric     lldb_private::Status lldberr;
47160b57cec5SDimitry Andric 
47170b57cec5SDimitry Andric     if (!comm.ReadExtFeature(ConstString("libraries"), ConstString(""), raw,
47180b57cec5SDimitry Andric                              lldberr))
47199dba64beSDimitry Andric       return llvm::createStringError(llvm::inconvertibleErrorCode(),
47209dba64beSDimitry Andric                                      "Error in libraries packet");
47210b57cec5SDimitry Andric 
47229dba64beSDimitry Andric     LLDB_LOGF(log, "parsing: %s", raw.c_str());
47230b57cec5SDimitry Andric     XMLDocument doc;
47240b57cec5SDimitry Andric 
47250b57cec5SDimitry Andric     if (!doc.ParseMemory(raw.c_str(), raw.size(), "noname.xml"))
47269dba64beSDimitry Andric       return llvm::createStringError(llvm::inconvertibleErrorCode(),
47279dba64beSDimitry Andric                                      "Error reading noname.xml");
47280b57cec5SDimitry Andric 
47290b57cec5SDimitry Andric     XMLNode root_element = doc.GetRootElement("library-list");
47300b57cec5SDimitry Andric     if (!root_element)
47319dba64beSDimitry Andric       return llvm::createStringError(llvm::inconvertibleErrorCode(),
47329dba64beSDimitry Andric                                      "Error finding library-list xml element");
47330b57cec5SDimitry Andric 
47340b57cec5SDimitry Andric     root_element.ForEachChildElementWithName(
47350b57cec5SDimitry Andric         "library", [log, &list](const XMLNode &library) -> bool {
47360b57cec5SDimitry Andric           LoadedModuleInfoList::LoadedModuleInfo module;
47370b57cec5SDimitry Andric 
47380b57cec5SDimitry Andric           llvm::StringRef name = library.GetAttributeValue("name");
47390b57cec5SDimitry Andric           module.set_name(name.str());
47400b57cec5SDimitry Andric 
47410b57cec5SDimitry Andric           // The base address of a given library will be the address of its
47420b57cec5SDimitry Andric           // first section. Most remotes send only one section for Windows
47430b57cec5SDimitry Andric           // targets for example.
47440b57cec5SDimitry Andric           const XMLNode &section =
47450b57cec5SDimitry Andric               library.FindFirstChildElementWithName("section");
47460b57cec5SDimitry Andric           llvm::StringRef address = section.GetAttributeValue("address");
47470b57cec5SDimitry Andric           module.set_base(
47480b57cec5SDimitry Andric               StringConvert::ToUInt64(address.data(), LLDB_INVALID_ADDRESS, 0));
47490b57cec5SDimitry Andric           // These addresses are absolute values.
47500b57cec5SDimitry Andric           module.set_base_is_offset(false);
47510b57cec5SDimitry Andric 
47520b57cec5SDimitry Andric           if (log) {
47530b57cec5SDimitry Andric             std::string name;
47540b57cec5SDimitry Andric             lldb::addr_t base = 0;
47550b57cec5SDimitry Andric             bool base_is_offset;
47560b57cec5SDimitry Andric             module.get_name(name);
47570b57cec5SDimitry Andric             module.get_base(base);
47580b57cec5SDimitry Andric             module.get_base_is_offset(base_is_offset);
47590b57cec5SDimitry Andric 
47609dba64beSDimitry Andric             LLDB_LOGF(log, "found (base:0x%08" PRIx64 "[%s], name:'%s')", base,
47610b57cec5SDimitry Andric                       (base_is_offset ? "offset" : "absolute"), name.c_str());
47620b57cec5SDimitry Andric           }
47630b57cec5SDimitry Andric 
47640b57cec5SDimitry Andric           list.add(module);
47650b57cec5SDimitry Andric           return true; // Keep iterating over all "library" elements in the root
47660b57cec5SDimitry Andric                        // node
47670b57cec5SDimitry Andric         });
47680b57cec5SDimitry Andric 
47690b57cec5SDimitry Andric     if (log)
47709dba64beSDimitry Andric       LLDB_LOGF(log, "found %" PRId32 " modules in total",
47710b57cec5SDimitry Andric                 (int)list.m_list.size());
47729dba64beSDimitry Andric     return list;
47730b57cec5SDimitry Andric   } else {
47749dba64beSDimitry Andric     return llvm::createStringError(llvm::inconvertibleErrorCode(),
47759dba64beSDimitry Andric                                    "Remote libraries not supported");
47760b57cec5SDimitry Andric   }
47770b57cec5SDimitry Andric }
47780b57cec5SDimitry Andric 
47790b57cec5SDimitry Andric lldb::ModuleSP ProcessGDBRemote::LoadModuleAtAddress(const FileSpec &file,
47800b57cec5SDimitry Andric                                                      lldb::addr_t link_map,
47810b57cec5SDimitry Andric                                                      lldb::addr_t base_addr,
47820b57cec5SDimitry Andric                                                      bool value_is_offset) {
47830b57cec5SDimitry Andric   DynamicLoader *loader = GetDynamicLoader();
47840b57cec5SDimitry Andric   if (!loader)
47850b57cec5SDimitry Andric     return nullptr;
47860b57cec5SDimitry Andric 
47870b57cec5SDimitry Andric   return loader->LoadModuleAtAddress(file, link_map, base_addr,
47880b57cec5SDimitry Andric                                      value_is_offset);
47890b57cec5SDimitry Andric }
47900b57cec5SDimitry Andric 
47919dba64beSDimitry Andric llvm::Error ProcessGDBRemote::LoadModules() {
47920b57cec5SDimitry Andric   using lldb_private::process_gdb_remote::ProcessGDBRemote;
47930b57cec5SDimitry Andric 
47940b57cec5SDimitry Andric   // request a list of loaded libraries from GDBServer
47959dba64beSDimitry Andric   llvm::Expected<LoadedModuleInfoList> module_list = GetLoadedModuleList();
47969dba64beSDimitry Andric   if (!module_list)
47979dba64beSDimitry Andric     return module_list.takeError();
47980b57cec5SDimitry Andric 
47990b57cec5SDimitry Andric   // get a list of all the modules
48000b57cec5SDimitry Andric   ModuleList new_modules;
48010b57cec5SDimitry Andric 
48029dba64beSDimitry Andric   for (LoadedModuleInfoList::LoadedModuleInfo &modInfo : module_list->m_list) {
48030b57cec5SDimitry Andric     std::string mod_name;
48040b57cec5SDimitry Andric     lldb::addr_t mod_base;
48050b57cec5SDimitry Andric     lldb::addr_t link_map;
48060b57cec5SDimitry Andric     bool mod_base_is_offset;
48070b57cec5SDimitry Andric 
48080b57cec5SDimitry Andric     bool valid = true;
48090b57cec5SDimitry Andric     valid &= modInfo.get_name(mod_name);
48100b57cec5SDimitry Andric     valid &= modInfo.get_base(mod_base);
48110b57cec5SDimitry Andric     valid &= modInfo.get_base_is_offset(mod_base_is_offset);
48120b57cec5SDimitry Andric     if (!valid)
48130b57cec5SDimitry Andric       continue;
48140b57cec5SDimitry Andric 
48150b57cec5SDimitry Andric     if (!modInfo.get_link_map(link_map))
48160b57cec5SDimitry Andric       link_map = LLDB_INVALID_ADDRESS;
48170b57cec5SDimitry Andric 
48180b57cec5SDimitry Andric     FileSpec file(mod_name);
48190b57cec5SDimitry Andric     FileSystem::Instance().Resolve(file);
48200b57cec5SDimitry Andric     lldb::ModuleSP module_sp =
48210b57cec5SDimitry Andric         LoadModuleAtAddress(file, link_map, mod_base, mod_base_is_offset);
48220b57cec5SDimitry Andric 
48230b57cec5SDimitry Andric     if (module_sp.get())
48240b57cec5SDimitry Andric       new_modules.Append(module_sp);
48250b57cec5SDimitry Andric   }
48260b57cec5SDimitry Andric 
48270b57cec5SDimitry Andric   if (new_modules.GetSize() > 0) {
48280b57cec5SDimitry Andric     ModuleList removed_modules;
48290b57cec5SDimitry Andric     Target &target = GetTarget();
48300b57cec5SDimitry Andric     ModuleList &loaded_modules = m_process->GetTarget().GetImages();
48310b57cec5SDimitry Andric 
48320b57cec5SDimitry Andric     for (size_t i = 0; i < loaded_modules.GetSize(); ++i) {
48330b57cec5SDimitry Andric       const lldb::ModuleSP loaded_module = loaded_modules.GetModuleAtIndex(i);
48340b57cec5SDimitry Andric 
48350b57cec5SDimitry Andric       bool found = false;
48360b57cec5SDimitry Andric       for (size_t j = 0; j < new_modules.GetSize(); ++j) {
48370b57cec5SDimitry Andric         if (new_modules.GetModuleAtIndex(j).get() == loaded_module.get())
48380b57cec5SDimitry Andric           found = true;
48390b57cec5SDimitry Andric       }
48400b57cec5SDimitry Andric 
48410b57cec5SDimitry Andric       // The main executable will never be included in libraries-svr4, don't
48420b57cec5SDimitry Andric       // remove it
48430b57cec5SDimitry Andric       if (!found &&
48440b57cec5SDimitry Andric           loaded_module.get() != target.GetExecutableModulePointer()) {
48450b57cec5SDimitry Andric         removed_modules.Append(loaded_module);
48460b57cec5SDimitry Andric       }
48470b57cec5SDimitry Andric     }
48480b57cec5SDimitry Andric 
48490b57cec5SDimitry Andric     loaded_modules.Remove(removed_modules);
48500b57cec5SDimitry Andric     m_process->GetTarget().ModulesDidUnload(removed_modules, false);
48510b57cec5SDimitry Andric 
48520b57cec5SDimitry Andric     new_modules.ForEach([&target](const lldb::ModuleSP module_sp) -> bool {
48530b57cec5SDimitry Andric       lldb_private::ObjectFile *obj = module_sp->GetObjectFile();
48540b57cec5SDimitry Andric       if (!obj)
48550b57cec5SDimitry Andric         return true;
48560b57cec5SDimitry Andric 
48570b57cec5SDimitry Andric       if (obj->GetType() != ObjectFile::Type::eTypeExecutable)
48580b57cec5SDimitry Andric         return true;
48590b57cec5SDimitry Andric 
48600b57cec5SDimitry Andric       lldb::ModuleSP module_copy_sp = module_sp;
48610b57cec5SDimitry Andric       target.SetExecutableModule(module_copy_sp, eLoadDependentsNo);
48620b57cec5SDimitry Andric       return false;
48630b57cec5SDimitry Andric     });
48640b57cec5SDimitry Andric 
48650b57cec5SDimitry Andric     loaded_modules.AppendIfNeeded(new_modules);
48660b57cec5SDimitry Andric     m_process->GetTarget().ModulesDidLoad(new_modules);
48670b57cec5SDimitry Andric   }
48680b57cec5SDimitry Andric 
48699dba64beSDimitry Andric   return llvm::ErrorSuccess();
48700b57cec5SDimitry Andric }
48710b57cec5SDimitry Andric 
48720b57cec5SDimitry Andric Status ProcessGDBRemote::GetFileLoadAddress(const FileSpec &file,
48730b57cec5SDimitry Andric                                             bool &is_loaded,
48740b57cec5SDimitry Andric                                             lldb::addr_t &load_addr) {
48750b57cec5SDimitry Andric   is_loaded = false;
48760b57cec5SDimitry Andric   load_addr = LLDB_INVALID_ADDRESS;
48770b57cec5SDimitry Andric 
48780b57cec5SDimitry Andric   std::string file_path = file.GetPath(false);
48790b57cec5SDimitry Andric   if (file_path.empty())
48800b57cec5SDimitry Andric     return Status("Empty file name specified");
48810b57cec5SDimitry Andric 
48820b57cec5SDimitry Andric   StreamString packet;
48830b57cec5SDimitry Andric   packet.PutCString("qFileLoadAddress:");
48840b57cec5SDimitry Andric   packet.PutStringAsRawHex8(file_path);
48850b57cec5SDimitry Andric 
48860b57cec5SDimitry Andric   StringExtractorGDBRemote response;
48870b57cec5SDimitry Andric   if (m_gdb_comm.SendPacketAndWaitForResponse(packet.GetString(), response,
48880b57cec5SDimitry Andric                                               false) !=
48890b57cec5SDimitry Andric       GDBRemoteCommunication::PacketResult::Success)
48900b57cec5SDimitry Andric     return Status("Sending qFileLoadAddress packet failed");
48910b57cec5SDimitry Andric 
48920b57cec5SDimitry Andric   if (response.IsErrorResponse()) {
48930b57cec5SDimitry Andric     if (response.GetError() == 1) {
48940b57cec5SDimitry Andric       // The file is not loaded into the inferior
48950b57cec5SDimitry Andric       is_loaded = false;
48960b57cec5SDimitry Andric       load_addr = LLDB_INVALID_ADDRESS;
48970b57cec5SDimitry Andric       return Status();
48980b57cec5SDimitry Andric     }
48990b57cec5SDimitry Andric 
49000b57cec5SDimitry Andric     return Status(
49010b57cec5SDimitry Andric         "Fetching file load address from remote server returned an error");
49020b57cec5SDimitry Andric   }
49030b57cec5SDimitry Andric 
49040b57cec5SDimitry Andric   if (response.IsNormalResponse()) {
49050b57cec5SDimitry Andric     is_loaded = true;
49060b57cec5SDimitry Andric     load_addr = response.GetHexMaxU64(false, LLDB_INVALID_ADDRESS);
49070b57cec5SDimitry Andric     return Status();
49080b57cec5SDimitry Andric   }
49090b57cec5SDimitry Andric 
49100b57cec5SDimitry Andric   return Status(
49110b57cec5SDimitry Andric       "Unknown error happened during sending the load address packet");
49120b57cec5SDimitry Andric }
49130b57cec5SDimitry Andric 
49140b57cec5SDimitry Andric void ProcessGDBRemote::ModulesDidLoad(ModuleList &module_list) {
49150b57cec5SDimitry Andric   // We must call the lldb_private::Process::ModulesDidLoad () first before we
49160b57cec5SDimitry Andric   // do anything
49170b57cec5SDimitry Andric   Process::ModulesDidLoad(module_list);
49180b57cec5SDimitry Andric 
49190b57cec5SDimitry Andric   // After loading shared libraries, we can ask our remote GDB server if it
49200b57cec5SDimitry Andric   // needs any symbols.
49210b57cec5SDimitry Andric   m_gdb_comm.ServeSymbolLookups(this);
49220b57cec5SDimitry Andric }
49230b57cec5SDimitry Andric 
49240b57cec5SDimitry Andric void ProcessGDBRemote::HandleAsyncStdout(llvm::StringRef out) {
49250b57cec5SDimitry Andric   AppendSTDOUT(out.data(), out.size());
49260b57cec5SDimitry Andric }
49270b57cec5SDimitry Andric 
49280b57cec5SDimitry Andric static const char *end_delimiter = "--end--;";
49290b57cec5SDimitry Andric static const int end_delimiter_len = 8;
49300b57cec5SDimitry Andric 
49310b57cec5SDimitry Andric void ProcessGDBRemote::HandleAsyncMisc(llvm::StringRef data) {
49320b57cec5SDimitry Andric   std::string input = data.str(); // '1' to move beyond 'A'
49330b57cec5SDimitry Andric   if (m_partial_profile_data.length() > 0) {
49340b57cec5SDimitry Andric     m_partial_profile_data.append(input);
49350b57cec5SDimitry Andric     input = m_partial_profile_data;
49360b57cec5SDimitry Andric     m_partial_profile_data.clear();
49370b57cec5SDimitry Andric   }
49380b57cec5SDimitry Andric 
49390b57cec5SDimitry Andric   size_t found, pos = 0, len = input.length();
49400b57cec5SDimitry Andric   while ((found = input.find(end_delimiter, pos)) != std::string::npos) {
49410b57cec5SDimitry Andric     StringExtractorGDBRemote profileDataExtractor(
49420b57cec5SDimitry Andric         input.substr(pos, found).c_str());
49430b57cec5SDimitry Andric     std::string profile_data =
49440b57cec5SDimitry Andric         HarmonizeThreadIdsForProfileData(profileDataExtractor);
49450b57cec5SDimitry Andric     BroadcastAsyncProfileData(profile_data);
49460b57cec5SDimitry Andric 
49470b57cec5SDimitry Andric     pos = found + end_delimiter_len;
49480b57cec5SDimitry Andric   }
49490b57cec5SDimitry Andric 
49500b57cec5SDimitry Andric   if (pos < len) {
49510b57cec5SDimitry Andric     // Last incomplete chunk.
49520b57cec5SDimitry Andric     m_partial_profile_data = input.substr(pos);
49530b57cec5SDimitry Andric   }
49540b57cec5SDimitry Andric }
49550b57cec5SDimitry Andric 
49560b57cec5SDimitry Andric std::string ProcessGDBRemote::HarmonizeThreadIdsForProfileData(
49570b57cec5SDimitry Andric     StringExtractorGDBRemote &profileDataExtractor) {
49580b57cec5SDimitry Andric   std::map<uint64_t, uint32_t> new_thread_id_to_used_usec_map;
49590b57cec5SDimitry Andric   std::string output;
49600b57cec5SDimitry Andric   llvm::raw_string_ostream output_stream(output);
49610b57cec5SDimitry Andric   llvm::StringRef name, value;
49620b57cec5SDimitry Andric 
49630b57cec5SDimitry Andric   // Going to assuming thread_used_usec comes first, else bail out.
49640b57cec5SDimitry Andric   while (profileDataExtractor.GetNameColonValue(name, value)) {
49650b57cec5SDimitry Andric     if (name.compare("thread_used_id") == 0) {
49660b57cec5SDimitry Andric       StringExtractor threadIDHexExtractor(value);
49670b57cec5SDimitry Andric       uint64_t thread_id = threadIDHexExtractor.GetHexMaxU64(false, 0);
49680b57cec5SDimitry Andric 
49690b57cec5SDimitry Andric       bool has_used_usec = false;
49700b57cec5SDimitry Andric       uint32_t curr_used_usec = 0;
49710b57cec5SDimitry Andric       llvm::StringRef usec_name, usec_value;
49720b57cec5SDimitry Andric       uint32_t input_file_pos = profileDataExtractor.GetFilePos();
49730b57cec5SDimitry Andric       if (profileDataExtractor.GetNameColonValue(usec_name, usec_value)) {
49740b57cec5SDimitry Andric         if (usec_name.equals("thread_used_usec")) {
49750b57cec5SDimitry Andric           has_used_usec = true;
49760b57cec5SDimitry Andric           usec_value.getAsInteger(0, curr_used_usec);
49770b57cec5SDimitry Andric         } else {
49780b57cec5SDimitry Andric           // We didn't find what we want, it is probably an older version. Bail
49790b57cec5SDimitry Andric           // out.
49800b57cec5SDimitry Andric           profileDataExtractor.SetFilePos(input_file_pos);
49810b57cec5SDimitry Andric         }
49820b57cec5SDimitry Andric       }
49830b57cec5SDimitry Andric 
49840b57cec5SDimitry Andric       if (has_used_usec) {
49850b57cec5SDimitry Andric         uint32_t prev_used_usec = 0;
49860b57cec5SDimitry Andric         std::map<uint64_t, uint32_t>::iterator iterator =
49870b57cec5SDimitry Andric             m_thread_id_to_used_usec_map.find(thread_id);
49880b57cec5SDimitry Andric         if (iterator != m_thread_id_to_used_usec_map.end()) {
49890b57cec5SDimitry Andric           prev_used_usec = m_thread_id_to_used_usec_map[thread_id];
49900b57cec5SDimitry Andric         }
49910b57cec5SDimitry Andric 
49920b57cec5SDimitry Andric         uint32_t real_used_usec = curr_used_usec - prev_used_usec;
49930b57cec5SDimitry Andric         // A good first time record is one that runs for at least 0.25 sec
49940b57cec5SDimitry Andric         bool good_first_time =
49950b57cec5SDimitry Andric             (prev_used_usec == 0) && (real_used_usec > 250000);
49960b57cec5SDimitry Andric         bool good_subsequent_time =
49970b57cec5SDimitry Andric             (prev_used_usec > 0) &&
49980b57cec5SDimitry Andric             ((real_used_usec > 0) || (HasAssignedIndexIDToThread(thread_id)));
49990b57cec5SDimitry Andric 
50000b57cec5SDimitry Andric         if (good_first_time || good_subsequent_time) {
50010b57cec5SDimitry Andric           // We try to avoid doing too many index id reservation, resulting in
50020b57cec5SDimitry Andric           // fast increase of index ids.
50030b57cec5SDimitry Andric 
50040b57cec5SDimitry Andric           output_stream << name << ":";
50050b57cec5SDimitry Andric           int32_t index_id = AssignIndexIDToThread(thread_id);
50060b57cec5SDimitry Andric           output_stream << index_id << ";";
50070b57cec5SDimitry Andric 
50080b57cec5SDimitry Andric           output_stream << usec_name << ":" << usec_value << ";";
50090b57cec5SDimitry Andric         } else {
50100b57cec5SDimitry Andric           // Skip past 'thread_used_name'.
50110b57cec5SDimitry Andric           llvm::StringRef local_name, local_value;
50120b57cec5SDimitry Andric           profileDataExtractor.GetNameColonValue(local_name, local_value);
50130b57cec5SDimitry Andric         }
50140b57cec5SDimitry Andric 
50150b57cec5SDimitry Andric         // Store current time as previous time so that they can be compared
50160b57cec5SDimitry Andric         // later.
50170b57cec5SDimitry Andric         new_thread_id_to_used_usec_map[thread_id] = curr_used_usec;
50180b57cec5SDimitry Andric       } else {
50190b57cec5SDimitry Andric         // Bail out and use old string.
50200b57cec5SDimitry Andric         output_stream << name << ":" << value << ";";
50210b57cec5SDimitry Andric       }
50220b57cec5SDimitry Andric     } else {
50230b57cec5SDimitry Andric       output_stream << name << ":" << value << ";";
50240b57cec5SDimitry Andric     }
50250b57cec5SDimitry Andric   }
50260b57cec5SDimitry Andric   output_stream << end_delimiter;
50270b57cec5SDimitry Andric   m_thread_id_to_used_usec_map = new_thread_id_to_used_usec_map;
50280b57cec5SDimitry Andric 
50290b57cec5SDimitry Andric   return output_stream.str();
50300b57cec5SDimitry Andric }
50310b57cec5SDimitry Andric 
50320b57cec5SDimitry Andric void ProcessGDBRemote::HandleStopReply() {
50330b57cec5SDimitry Andric   if (GetStopID() != 0)
50340b57cec5SDimitry Andric     return;
50350b57cec5SDimitry Andric 
50360b57cec5SDimitry Andric   if (GetID() == LLDB_INVALID_PROCESS_ID) {
50370b57cec5SDimitry Andric     lldb::pid_t pid = m_gdb_comm.GetCurrentProcessID();
50380b57cec5SDimitry Andric     if (pid != LLDB_INVALID_PROCESS_ID)
50390b57cec5SDimitry Andric       SetID(pid);
50400b57cec5SDimitry Andric   }
50410b57cec5SDimitry Andric   BuildDynamicRegisterInfo(true);
50420b57cec5SDimitry Andric }
50430b57cec5SDimitry Andric 
50440b57cec5SDimitry Andric static const char *const s_async_json_packet_prefix = "JSON-async:";
50450b57cec5SDimitry Andric 
50460b57cec5SDimitry Andric static StructuredData::ObjectSP
50470b57cec5SDimitry Andric ParseStructuredDataPacket(llvm::StringRef packet) {
50480b57cec5SDimitry Andric   Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
50490b57cec5SDimitry Andric 
50500b57cec5SDimitry Andric   if (!packet.consume_front(s_async_json_packet_prefix)) {
50510b57cec5SDimitry Andric     if (log) {
50529dba64beSDimitry Andric       LLDB_LOGF(
50539dba64beSDimitry Andric           log,
50540b57cec5SDimitry Andric           "GDBRemoteCommunicationClientBase::%s() received $J packet "
50550b57cec5SDimitry Andric           "but was not a StructuredData packet: packet starts with "
50560b57cec5SDimitry Andric           "%s",
50570b57cec5SDimitry Andric           __FUNCTION__,
50580b57cec5SDimitry Andric           packet.slice(0, strlen(s_async_json_packet_prefix)).str().c_str());
50590b57cec5SDimitry Andric     }
50600b57cec5SDimitry Andric     return StructuredData::ObjectSP();
50610b57cec5SDimitry Andric   }
50620b57cec5SDimitry Andric 
50630b57cec5SDimitry Andric   // This is an asynchronous JSON packet, destined for a StructuredDataPlugin.
50645ffd83dbSDimitry Andric   StructuredData::ObjectSP json_sp =
50655ffd83dbSDimitry Andric       StructuredData::ParseJSON(std::string(packet));
50660b57cec5SDimitry Andric   if (log) {
50670b57cec5SDimitry Andric     if (json_sp) {
50680b57cec5SDimitry Andric       StreamString json_str;
50699dba64beSDimitry Andric       json_sp->Dump(json_str, true);
50700b57cec5SDimitry Andric       json_str.Flush();
50719dba64beSDimitry Andric       LLDB_LOGF(log,
50729dba64beSDimitry Andric                 "ProcessGDBRemote::%s() "
50730b57cec5SDimitry Andric                 "received Async StructuredData packet: %s",
50740b57cec5SDimitry Andric                 __FUNCTION__, json_str.GetData());
50750b57cec5SDimitry Andric     } else {
50769dba64beSDimitry Andric       LLDB_LOGF(log,
50779dba64beSDimitry Andric                 "ProcessGDBRemote::%s"
50780b57cec5SDimitry Andric                 "() received StructuredData packet:"
50790b57cec5SDimitry Andric                 " parse failure",
50800b57cec5SDimitry Andric                 __FUNCTION__);
50810b57cec5SDimitry Andric     }
50820b57cec5SDimitry Andric   }
50830b57cec5SDimitry Andric   return json_sp;
50840b57cec5SDimitry Andric }
50850b57cec5SDimitry Andric 
50860b57cec5SDimitry Andric void ProcessGDBRemote::HandleAsyncStructuredDataPacket(llvm::StringRef data) {
50870b57cec5SDimitry Andric   auto structured_data_sp = ParseStructuredDataPacket(data);
50880b57cec5SDimitry Andric   if (structured_data_sp)
50890b57cec5SDimitry Andric     RouteAsyncStructuredData(structured_data_sp);
50900b57cec5SDimitry Andric }
50910b57cec5SDimitry Andric 
50920b57cec5SDimitry Andric class CommandObjectProcessGDBRemoteSpeedTest : public CommandObjectParsed {
50930b57cec5SDimitry Andric public:
50940b57cec5SDimitry Andric   CommandObjectProcessGDBRemoteSpeedTest(CommandInterpreter &interpreter)
50950b57cec5SDimitry Andric       : CommandObjectParsed(interpreter, "process plugin packet speed-test",
50960b57cec5SDimitry Andric                             "Tests packet speeds of various sizes to determine "
50970b57cec5SDimitry Andric                             "the performance characteristics of the GDB remote "
50980b57cec5SDimitry Andric                             "connection. ",
50990b57cec5SDimitry Andric                             nullptr),
51000b57cec5SDimitry Andric         m_option_group(),
51010b57cec5SDimitry Andric         m_num_packets(LLDB_OPT_SET_1, false, "count", 'c', 0, eArgTypeCount,
51020b57cec5SDimitry Andric                       "The number of packets to send of each varying size "
51030b57cec5SDimitry Andric                       "(default is 1000).",
51040b57cec5SDimitry Andric                       1000),
51050b57cec5SDimitry Andric         m_max_send(LLDB_OPT_SET_1, false, "max-send", 's', 0, eArgTypeCount,
51060b57cec5SDimitry Andric                    "The maximum number of bytes to send in a packet. Sizes "
51070b57cec5SDimitry Andric                    "increase in powers of 2 while the size is less than or "
51080b57cec5SDimitry Andric                    "equal to this option value. (default 1024).",
51090b57cec5SDimitry Andric                    1024),
51100b57cec5SDimitry Andric         m_max_recv(LLDB_OPT_SET_1, false, "max-receive", 'r', 0, eArgTypeCount,
51110b57cec5SDimitry Andric                    "The maximum number of bytes to receive in a packet. Sizes "
51120b57cec5SDimitry Andric                    "increase in powers of 2 while the size is less than or "
51130b57cec5SDimitry Andric                    "equal to this option value. (default 1024).",
51140b57cec5SDimitry Andric                    1024),
51150b57cec5SDimitry Andric         m_json(LLDB_OPT_SET_1, false, "json", 'j',
51160b57cec5SDimitry Andric                "Print the output as JSON data for easy parsing.", false, true) {
51170b57cec5SDimitry Andric     m_option_group.Append(&m_num_packets, LLDB_OPT_SET_ALL, LLDB_OPT_SET_1);
51180b57cec5SDimitry Andric     m_option_group.Append(&m_max_send, LLDB_OPT_SET_ALL, LLDB_OPT_SET_1);
51190b57cec5SDimitry Andric     m_option_group.Append(&m_max_recv, LLDB_OPT_SET_ALL, LLDB_OPT_SET_1);
51200b57cec5SDimitry Andric     m_option_group.Append(&m_json, LLDB_OPT_SET_ALL, LLDB_OPT_SET_1);
51210b57cec5SDimitry Andric     m_option_group.Finalize();
51220b57cec5SDimitry Andric   }
51230b57cec5SDimitry Andric 
51240b57cec5SDimitry Andric   ~CommandObjectProcessGDBRemoteSpeedTest() override {}
51250b57cec5SDimitry Andric 
51260b57cec5SDimitry Andric   Options *GetOptions() override { return &m_option_group; }
51270b57cec5SDimitry Andric 
51280b57cec5SDimitry Andric   bool DoExecute(Args &command, CommandReturnObject &result) override {
51290b57cec5SDimitry Andric     const size_t argc = command.GetArgumentCount();
51300b57cec5SDimitry Andric     if (argc == 0) {
51310b57cec5SDimitry Andric       ProcessGDBRemote *process =
51320b57cec5SDimitry Andric           (ProcessGDBRemote *)m_interpreter.GetExecutionContext()
51330b57cec5SDimitry Andric               .GetProcessPtr();
51340b57cec5SDimitry Andric       if (process) {
51350b57cec5SDimitry Andric         StreamSP output_stream_sp(
51360b57cec5SDimitry Andric             m_interpreter.GetDebugger().GetAsyncOutputStream());
51370b57cec5SDimitry Andric         result.SetImmediateOutputStream(output_stream_sp);
51380b57cec5SDimitry Andric 
51390b57cec5SDimitry Andric         const uint32_t num_packets =
51400b57cec5SDimitry Andric             (uint32_t)m_num_packets.GetOptionValue().GetCurrentValue();
51410b57cec5SDimitry Andric         const uint64_t max_send = m_max_send.GetOptionValue().GetCurrentValue();
51420b57cec5SDimitry Andric         const uint64_t max_recv = m_max_recv.GetOptionValue().GetCurrentValue();
51430b57cec5SDimitry Andric         const bool json = m_json.GetOptionValue().GetCurrentValue();
51440b57cec5SDimitry Andric         const uint64_t k_recv_amount =
51450b57cec5SDimitry Andric             4 * 1024 * 1024; // Receive amount in bytes
51460b57cec5SDimitry Andric         process->GetGDBRemote().TestPacketSpeed(
51470b57cec5SDimitry Andric             num_packets, max_send, max_recv, k_recv_amount, json,
51480b57cec5SDimitry Andric             output_stream_sp ? *output_stream_sp : result.GetOutputStream());
51490b57cec5SDimitry Andric         result.SetStatus(eReturnStatusSuccessFinishResult);
51500b57cec5SDimitry Andric         return true;
51510b57cec5SDimitry Andric       }
51520b57cec5SDimitry Andric     } else {
51530b57cec5SDimitry Andric       result.AppendErrorWithFormat("'%s' takes no arguments",
51540b57cec5SDimitry Andric                                    m_cmd_name.c_str());
51550b57cec5SDimitry Andric     }
51560b57cec5SDimitry Andric     result.SetStatus(eReturnStatusFailed);
51570b57cec5SDimitry Andric     return false;
51580b57cec5SDimitry Andric   }
51590b57cec5SDimitry Andric 
51600b57cec5SDimitry Andric protected:
51610b57cec5SDimitry Andric   OptionGroupOptions m_option_group;
51620b57cec5SDimitry Andric   OptionGroupUInt64 m_num_packets;
51630b57cec5SDimitry Andric   OptionGroupUInt64 m_max_send;
51640b57cec5SDimitry Andric   OptionGroupUInt64 m_max_recv;
51650b57cec5SDimitry Andric   OptionGroupBoolean m_json;
51660b57cec5SDimitry Andric };
51670b57cec5SDimitry Andric 
51680b57cec5SDimitry Andric class CommandObjectProcessGDBRemotePacketHistory : public CommandObjectParsed {
51690b57cec5SDimitry Andric private:
51700b57cec5SDimitry Andric public:
51710b57cec5SDimitry Andric   CommandObjectProcessGDBRemotePacketHistory(CommandInterpreter &interpreter)
51720b57cec5SDimitry Andric       : CommandObjectParsed(interpreter, "process plugin packet history",
51730b57cec5SDimitry Andric                             "Dumps the packet history buffer. ", nullptr) {}
51740b57cec5SDimitry Andric 
51750b57cec5SDimitry Andric   ~CommandObjectProcessGDBRemotePacketHistory() override {}
51760b57cec5SDimitry Andric 
51770b57cec5SDimitry Andric   bool DoExecute(Args &command, CommandReturnObject &result) override {
51780b57cec5SDimitry Andric     const size_t argc = command.GetArgumentCount();
51790b57cec5SDimitry Andric     if (argc == 0) {
51800b57cec5SDimitry Andric       ProcessGDBRemote *process =
51810b57cec5SDimitry Andric           (ProcessGDBRemote *)m_interpreter.GetExecutionContext()
51820b57cec5SDimitry Andric               .GetProcessPtr();
51830b57cec5SDimitry Andric       if (process) {
51840b57cec5SDimitry Andric         process->GetGDBRemote().DumpHistory(result.GetOutputStream());
51850b57cec5SDimitry Andric         result.SetStatus(eReturnStatusSuccessFinishResult);
51860b57cec5SDimitry Andric         return true;
51870b57cec5SDimitry Andric       }
51880b57cec5SDimitry Andric     } else {
51890b57cec5SDimitry Andric       result.AppendErrorWithFormat("'%s' takes no arguments",
51900b57cec5SDimitry Andric                                    m_cmd_name.c_str());
51910b57cec5SDimitry Andric     }
51920b57cec5SDimitry Andric     result.SetStatus(eReturnStatusFailed);
51930b57cec5SDimitry Andric     return false;
51940b57cec5SDimitry Andric   }
51950b57cec5SDimitry Andric };
51960b57cec5SDimitry Andric 
51970b57cec5SDimitry Andric class CommandObjectProcessGDBRemotePacketXferSize : public CommandObjectParsed {
51980b57cec5SDimitry Andric private:
51990b57cec5SDimitry Andric public:
52000b57cec5SDimitry Andric   CommandObjectProcessGDBRemotePacketXferSize(CommandInterpreter &interpreter)
52010b57cec5SDimitry Andric       : CommandObjectParsed(
52020b57cec5SDimitry Andric             interpreter, "process plugin packet xfer-size",
52030b57cec5SDimitry Andric             "Maximum size that lldb will try to read/write one one chunk.",
52040b57cec5SDimitry Andric             nullptr) {}
52050b57cec5SDimitry Andric 
52060b57cec5SDimitry Andric   ~CommandObjectProcessGDBRemotePacketXferSize() override {}
52070b57cec5SDimitry Andric 
52080b57cec5SDimitry Andric   bool DoExecute(Args &command, CommandReturnObject &result) override {
52090b57cec5SDimitry Andric     const size_t argc = command.GetArgumentCount();
52100b57cec5SDimitry Andric     if (argc == 0) {
52110b57cec5SDimitry Andric       result.AppendErrorWithFormat("'%s' takes an argument to specify the max "
52120b57cec5SDimitry Andric                                    "amount to be transferred when "
52130b57cec5SDimitry Andric                                    "reading/writing",
52140b57cec5SDimitry Andric                                    m_cmd_name.c_str());
52150b57cec5SDimitry Andric       result.SetStatus(eReturnStatusFailed);
52160b57cec5SDimitry Andric       return false;
52170b57cec5SDimitry Andric     }
52180b57cec5SDimitry Andric 
52190b57cec5SDimitry Andric     ProcessGDBRemote *process =
52200b57cec5SDimitry Andric         (ProcessGDBRemote *)m_interpreter.GetExecutionContext().GetProcessPtr();
52210b57cec5SDimitry Andric     if (process) {
52220b57cec5SDimitry Andric       const char *packet_size = command.GetArgumentAtIndex(0);
52230b57cec5SDimitry Andric       errno = 0;
52240b57cec5SDimitry Andric       uint64_t user_specified_max = strtoul(packet_size, nullptr, 10);
52250b57cec5SDimitry Andric       if (errno == 0 && user_specified_max != 0) {
52260b57cec5SDimitry Andric         process->SetUserSpecifiedMaxMemoryTransferSize(user_specified_max);
52270b57cec5SDimitry Andric         result.SetStatus(eReturnStatusSuccessFinishResult);
52280b57cec5SDimitry Andric         return true;
52290b57cec5SDimitry Andric       }
52300b57cec5SDimitry Andric     }
52310b57cec5SDimitry Andric     result.SetStatus(eReturnStatusFailed);
52320b57cec5SDimitry Andric     return false;
52330b57cec5SDimitry Andric   }
52340b57cec5SDimitry Andric };
52350b57cec5SDimitry Andric 
52360b57cec5SDimitry Andric class CommandObjectProcessGDBRemotePacketSend : public CommandObjectParsed {
52370b57cec5SDimitry Andric private:
52380b57cec5SDimitry Andric public:
52390b57cec5SDimitry Andric   CommandObjectProcessGDBRemotePacketSend(CommandInterpreter &interpreter)
52400b57cec5SDimitry Andric       : CommandObjectParsed(interpreter, "process plugin packet send",
52410b57cec5SDimitry Andric                             "Send a custom packet through the GDB remote "
52420b57cec5SDimitry Andric                             "protocol and print the answer. "
52430b57cec5SDimitry Andric                             "The packet header and footer will automatically "
52440b57cec5SDimitry Andric                             "be added to the packet prior to sending and "
52450b57cec5SDimitry Andric                             "stripped from the result.",
52460b57cec5SDimitry Andric                             nullptr) {}
52470b57cec5SDimitry Andric 
52480b57cec5SDimitry Andric   ~CommandObjectProcessGDBRemotePacketSend() override {}
52490b57cec5SDimitry Andric 
52500b57cec5SDimitry Andric   bool DoExecute(Args &command, CommandReturnObject &result) override {
52510b57cec5SDimitry Andric     const size_t argc = command.GetArgumentCount();
52520b57cec5SDimitry Andric     if (argc == 0) {
52530b57cec5SDimitry Andric       result.AppendErrorWithFormat(
52540b57cec5SDimitry Andric           "'%s' takes a one or more packet content arguments",
52550b57cec5SDimitry Andric           m_cmd_name.c_str());
52560b57cec5SDimitry Andric       result.SetStatus(eReturnStatusFailed);
52570b57cec5SDimitry Andric       return false;
52580b57cec5SDimitry Andric     }
52590b57cec5SDimitry Andric 
52600b57cec5SDimitry Andric     ProcessGDBRemote *process =
52610b57cec5SDimitry Andric         (ProcessGDBRemote *)m_interpreter.GetExecutionContext().GetProcessPtr();
52620b57cec5SDimitry Andric     if (process) {
52630b57cec5SDimitry Andric       for (size_t i = 0; i < argc; ++i) {
52640b57cec5SDimitry Andric         const char *packet_cstr = command.GetArgumentAtIndex(0);
52650b57cec5SDimitry Andric         bool send_async = true;
52660b57cec5SDimitry Andric         StringExtractorGDBRemote response;
52670b57cec5SDimitry Andric         process->GetGDBRemote().SendPacketAndWaitForResponse(
52680b57cec5SDimitry Andric             packet_cstr, response, send_async);
52690b57cec5SDimitry Andric         result.SetStatus(eReturnStatusSuccessFinishResult);
52700b57cec5SDimitry Andric         Stream &output_strm = result.GetOutputStream();
52710b57cec5SDimitry Andric         output_strm.Printf("  packet: %s\n", packet_cstr);
52725ffd83dbSDimitry Andric         std::string response_str = std::string(response.GetStringRef());
52730b57cec5SDimitry Andric 
52740b57cec5SDimitry Andric         if (strstr(packet_cstr, "qGetProfileData") != nullptr) {
52750b57cec5SDimitry Andric           response_str = process->HarmonizeThreadIdsForProfileData(response);
52760b57cec5SDimitry Andric         }
52770b57cec5SDimitry Andric 
52780b57cec5SDimitry Andric         if (response_str.empty())
52790b57cec5SDimitry Andric           output_strm.PutCString("response: \nerror: UNIMPLEMENTED\n");
52800b57cec5SDimitry Andric         else
52819dba64beSDimitry Andric           output_strm.Printf("response: %s\n", response.GetStringRef().data());
52820b57cec5SDimitry Andric       }
52830b57cec5SDimitry Andric     }
52840b57cec5SDimitry Andric     return true;
52850b57cec5SDimitry Andric   }
52860b57cec5SDimitry Andric };
52870b57cec5SDimitry Andric 
52880b57cec5SDimitry Andric class CommandObjectProcessGDBRemotePacketMonitor : public CommandObjectRaw {
52890b57cec5SDimitry Andric private:
52900b57cec5SDimitry Andric public:
52910b57cec5SDimitry Andric   CommandObjectProcessGDBRemotePacketMonitor(CommandInterpreter &interpreter)
52920b57cec5SDimitry Andric       : CommandObjectRaw(interpreter, "process plugin packet monitor",
52930b57cec5SDimitry Andric                          "Send a qRcmd packet through the GDB remote protocol "
52940b57cec5SDimitry Andric                          "and print the response."
52950b57cec5SDimitry Andric                          "The argument passed to this command will be hex "
52960b57cec5SDimitry Andric                          "encoded into a valid 'qRcmd' packet, sent and the "
52970b57cec5SDimitry Andric                          "response will be printed.") {}
52980b57cec5SDimitry Andric 
52990b57cec5SDimitry Andric   ~CommandObjectProcessGDBRemotePacketMonitor() override {}
53000b57cec5SDimitry Andric 
53010b57cec5SDimitry Andric   bool DoExecute(llvm::StringRef command,
53020b57cec5SDimitry Andric                  CommandReturnObject &result) override {
53030b57cec5SDimitry Andric     if (command.empty()) {
53040b57cec5SDimitry Andric       result.AppendErrorWithFormat("'%s' takes a command string argument",
53050b57cec5SDimitry Andric                                    m_cmd_name.c_str());
53060b57cec5SDimitry Andric       result.SetStatus(eReturnStatusFailed);
53070b57cec5SDimitry Andric       return false;
53080b57cec5SDimitry Andric     }
53090b57cec5SDimitry Andric 
53100b57cec5SDimitry Andric     ProcessGDBRemote *process =
53110b57cec5SDimitry Andric         (ProcessGDBRemote *)m_interpreter.GetExecutionContext().GetProcessPtr();
53120b57cec5SDimitry Andric     if (process) {
53130b57cec5SDimitry Andric       StreamString packet;
53140b57cec5SDimitry Andric       packet.PutCString("qRcmd,");
53150b57cec5SDimitry Andric       packet.PutBytesAsRawHex8(command.data(), command.size());
53160b57cec5SDimitry Andric 
53170b57cec5SDimitry Andric       bool send_async = true;
53180b57cec5SDimitry Andric       StringExtractorGDBRemote response;
53190b57cec5SDimitry Andric       Stream &output_strm = result.GetOutputStream();
53200b57cec5SDimitry Andric       process->GetGDBRemote().SendPacketAndReceiveResponseWithOutputSupport(
53210b57cec5SDimitry Andric           packet.GetString(), response, send_async,
53220b57cec5SDimitry Andric           [&output_strm](llvm::StringRef output) { output_strm << output; });
53230b57cec5SDimitry Andric       result.SetStatus(eReturnStatusSuccessFinishResult);
53240b57cec5SDimitry Andric       output_strm.Printf("  packet: %s\n", packet.GetData());
53255ffd83dbSDimitry Andric       const std::string &response_str = std::string(response.GetStringRef());
53260b57cec5SDimitry Andric 
53270b57cec5SDimitry Andric       if (response_str.empty())
53280b57cec5SDimitry Andric         output_strm.PutCString("response: \nerror: UNIMPLEMENTED\n");
53290b57cec5SDimitry Andric       else
53309dba64beSDimitry Andric         output_strm.Printf("response: %s\n", response.GetStringRef().data());
53310b57cec5SDimitry Andric     }
53320b57cec5SDimitry Andric     return true;
53330b57cec5SDimitry Andric   }
53340b57cec5SDimitry Andric };
53350b57cec5SDimitry Andric 
53360b57cec5SDimitry Andric class CommandObjectProcessGDBRemotePacket : public CommandObjectMultiword {
53370b57cec5SDimitry Andric private:
53380b57cec5SDimitry Andric public:
53390b57cec5SDimitry Andric   CommandObjectProcessGDBRemotePacket(CommandInterpreter &interpreter)
53400b57cec5SDimitry Andric       : CommandObjectMultiword(interpreter, "process plugin packet",
53410b57cec5SDimitry Andric                                "Commands that deal with GDB remote packets.",
53420b57cec5SDimitry Andric                                nullptr) {
53430b57cec5SDimitry Andric     LoadSubCommand(
53440b57cec5SDimitry Andric         "history",
53450b57cec5SDimitry Andric         CommandObjectSP(
53460b57cec5SDimitry Andric             new CommandObjectProcessGDBRemotePacketHistory(interpreter)));
53470b57cec5SDimitry Andric     LoadSubCommand(
53480b57cec5SDimitry Andric         "send", CommandObjectSP(
53490b57cec5SDimitry Andric                     new CommandObjectProcessGDBRemotePacketSend(interpreter)));
53500b57cec5SDimitry Andric     LoadSubCommand(
53510b57cec5SDimitry Andric         "monitor",
53520b57cec5SDimitry Andric         CommandObjectSP(
53530b57cec5SDimitry Andric             new CommandObjectProcessGDBRemotePacketMonitor(interpreter)));
53540b57cec5SDimitry Andric     LoadSubCommand(
53550b57cec5SDimitry Andric         "xfer-size",
53560b57cec5SDimitry Andric         CommandObjectSP(
53570b57cec5SDimitry Andric             new CommandObjectProcessGDBRemotePacketXferSize(interpreter)));
53580b57cec5SDimitry Andric     LoadSubCommand("speed-test",
53590b57cec5SDimitry Andric                    CommandObjectSP(new CommandObjectProcessGDBRemoteSpeedTest(
53600b57cec5SDimitry Andric                        interpreter)));
53610b57cec5SDimitry Andric   }
53620b57cec5SDimitry Andric 
53630b57cec5SDimitry Andric   ~CommandObjectProcessGDBRemotePacket() override {}
53640b57cec5SDimitry Andric };
53650b57cec5SDimitry Andric 
53660b57cec5SDimitry Andric class CommandObjectMultiwordProcessGDBRemote : public CommandObjectMultiword {
53670b57cec5SDimitry Andric public:
53680b57cec5SDimitry Andric   CommandObjectMultiwordProcessGDBRemote(CommandInterpreter &interpreter)
53690b57cec5SDimitry Andric       : CommandObjectMultiword(
53700b57cec5SDimitry Andric             interpreter, "process plugin",
53710b57cec5SDimitry Andric             "Commands for operating on a ProcessGDBRemote process.",
53720b57cec5SDimitry Andric             "process plugin <subcommand> [<subcommand-options>]") {
53730b57cec5SDimitry Andric     LoadSubCommand(
53740b57cec5SDimitry Andric         "packet",
53750b57cec5SDimitry Andric         CommandObjectSP(new CommandObjectProcessGDBRemotePacket(interpreter)));
53760b57cec5SDimitry Andric   }
53770b57cec5SDimitry Andric 
53780b57cec5SDimitry Andric   ~CommandObjectMultiwordProcessGDBRemote() override {}
53790b57cec5SDimitry Andric };
53800b57cec5SDimitry Andric 
53810b57cec5SDimitry Andric CommandObject *ProcessGDBRemote::GetPluginCommandObject() {
53820b57cec5SDimitry Andric   if (!m_command_sp)
53830b57cec5SDimitry Andric     m_command_sp = std::make_shared<CommandObjectMultiwordProcessGDBRemote>(
53840b57cec5SDimitry Andric         GetTarget().GetDebugger().GetCommandInterpreter());
53850b57cec5SDimitry Andric   return m_command_sp.get();
53860b57cec5SDimitry Andric }
5387