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