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