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 = Status::FromErrorStringWithFormat( 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 = Status::FromErrorStringWithFormat( 574 "Process %" PRIu64 " 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 = Status::FromErrorStringWithFormatv( 765 "Cannot launch '{0}': {1}", 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 = Status::FromErrorString("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 = Status::FromErrorString("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 = 1368 Status::FromErrorString("can't make continue packet for this resume"); 1369 } else { 1370 EventSP event_sp; 1371 if (!m_async_thread.IsJoinable()) { 1372 error = Status::FromErrorString( 1373 "Trying to resume but the async thread is dead."); 1374 LLDB_LOGF(log, "ProcessGDBRemote::DoResume: Trying to resume but the " 1375 "async thread is dead."); 1376 return error; 1377 } 1378 1379 auto data_sp = 1380 std::make_shared<EventDataBytes>(continue_packet.GetString()); 1381 m_async_broadcaster.BroadcastEvent(eBroadcastBitAsyncContinue, data_sp); 1382 1383 if (!listener_sp->GetEvent(event_sp, std::chrono::seconds(5))) { 1384 error = Status::FromErrorString("Resume timed out."); 1385 LLDB_LOGF(log, "ProcessGDBRemote::DoResume: Resume timed out."); 1386 } else if (event_sp->BroadcasterIs(&m_async_broadcaster)) { 1387 error = Status::FromErrorString( 1388 "Broadcast continue, but the async thread was " 1389 "killed before we got an ack back."); 1390 LLDB_LOGF(log, 1391 "ProcessGDBRemote::DoResume: Broadcast continue, but the " 1392 "async thread was killed before we got an ack back."); 1393 return error; 1394 } 1395 } 1396 } 1397 1398 return error; 1399 } 1400 1401 void ProcessGDBRemote::ClearThreadIDList() { 1402 std::lock_guard<std::recursive_mutex> guard(m_thread_list_real.GetMutex()); 1403 m_thread_ids.clear(); 1404 m_thread_pcs.clear(); 1405 } 1406 1407 size_t ProcessGDBRemote::UpdateThreadIDsFromStopReplyThreadsValue( 1408 llvm::StringRef value) { 1409 m_thread_ids.clear(); 1410 lldb::pid_t pid = m_gdb_comm.GetCurrentProcessID(); 1411 StringExtractorGDBRemote thread_ids{value}; 1412 1413 do { 1414 auto pid_tid = thread_ids.GetPidTid(pid); 1415 if (pid_tid && pid_tid->first == pid) { 1416 lldb::tid_t tid = pid_tid->second; 1417 if (tid != LLDB_INVALID_THREAD_ID && 1418 tid != StringExtractorGDBRemote::AllProcesses) 1419 m_thread_ids.push_back(tid); 1420 } 1421 } while (thread_ids.GetChar() == ','); 1422 1423 return m_thread_ids.size(); 1424 } 1425 1426 size_t ProcessGDBRemote::UpdateThreadPCsFromStopReplyThreadsValue( 1427 llvm::StringRef value) { 1428 m_thread_pcs.clear(); 1429 for (llvm::StringRef x : llvm::split(value, ',')) { 1430 lldb::addr_t pc; 1431 if (llvm::to_integer(x, pc, 16)) 1432 m_thread_pcs.push_back(pc); 1433 } 1434 return m_thread_pcs.size(); 1435 } 1436 1437 bool ProcessGDBRemote::UpdateThreadIDList() { 1438 std::lock_guard<std::recursive_mutex> guard(m_thread_list_real.GetMutex()); 1439 1440 if (m_jthreadsinfo_sp) { 1441 // If we have the JSON threads info, we can get the thread list from that 1442 StructuredData::Array *thread_infos = m_jthreadsinfo_sp->GetAsArray(); 1443 if (thread_infos && thread_infos->GetSize() > 0) { 1444 m_thread_ids.clear(); 1445 m_thread_pcs.clear(); 1446 thread_infos->ForEach([this](StructuredData::Object *object) -> bool { 1447 StructuredData::Dictionary *thread_dict = object->GetAsDictionary(); 1448 if (thread_dict) { 1449 // Set the thread stop info from the JSON dictionary 1450 SetThreadStopInfo(thread_dict); 1451 lldb::tid_t tid = LLDB_INVALID_THREAD_ID; 1452 if (thread_dict->GetValueForKeyAsInteger<lldb::tid_t>("tid", tid)) 1453 m_thread_ids.push_back(tid); 1454 } 1455 return true; // Keep iterating through all thread_info objects 1456 }); 1457 } 1458 if (!m_thread_ids.empty()) 1459 return true; 1460 } else { 1461 // See if we can get the thread IDs from the current stop reply packets 1462 // that might contain a "threads" key/value pair 1463 1464 if (m_last_stop_packet) { 1465 // Get the thread stop info 1466 StringExtractorGDBRemote &stop_info = *m_last_stop_packet; 1467 const std::string &stop_info_str = std::string(stop_info.GetStringRef()); 1468 1469 m_thread_pcs.clear(); 1470 const size_t thread_pcs_pos = stop_info_str.find(";thread-pcs:"); 1471 if (thread_pcs_pos != std::string::npos) { 1472 const size_t start = thread_pcs_pos + strlen(";thread-pcs:"); 1473 const size_t end = stop_info_str.find(';', start); 1474 if (end != std::string::npos) { 1475 std::string value = stop_info_str.substr(start, end - start); 1476 UpdateThreadPCsFromStopReplyThreadsValue(value); 1477 } 1478 } 1479 1480 const size_t threads_pos = stop_info_str.find(";threads:"); 1481 if (threads_pos != std::string::npos) { 1482 const size_t start = threads_pos + strlen(";threads:"); 1483 const size_t end = stop_info_str.find(';', start); 1484 if (end != std::string::npos) { 1485 std::string value = stop_info_str.substr(start, end - start); 1486 if (UpdateThreadIDsFromStopReplyThreadsValue(value)) 1487 return true; 1488 } 1489 } 1490 } 1491 } 1492 1493 bool sequence_mutex_unavailable = false; 1494 m_gdb_comm.GetCurrentThreadIDs(m_thread_ids, sequence_mutex_unavailable); 1495 if (sequence_mutex_unavailable) { 1496 return false; // We just didn't get the list 1497 } 1498 return true; 1499 } 1500 1501 bool ProcessGDBRemote::DoUpdateThreadList(ThreadList &old_thread_list, 1502 ThreadList &new_thread_list) { 1503 // locker will keep a mutex locked until it goes out of scope 1504 Log *log = GetLog(GDBRLog::Thread); 1505 LLDB_LOGV(log, "pid = {0}", GetID()); 1506 1507 size_t num_thread_ids = m_thread_ids.size(); 1508 // The "m_thread_ids" thread ID list should always be updated after each stop 1509 // reply packet, but in case it isn't, update it here. 1510 if (num_thread_ids == 0) { 1511 if (!UpdateThreadIDList()) 1512 return false; 1513 num_thread_ids = m_thread_ids.size(); 1514 } 1515 1516 ThreadList old_thread_list_copy(old_thread_list); 1517 if (num_thread_ids > 0) { 1518 for (size_t i = 0; i < num_thread_ids; ++i) { 1519 lldb::tid_t tid = m_thread_ids[i]; 1520 ThreadSP thread_sp( 1521 old_thread_list_copy.RemoveThreadByProtocolID(tid, false)); 1522 if (!thread_sp) { 1523 thread_sp = std::make_shared<ThreadGDBRemote>(*this, tid); 1524 LLDB_LOGV(log, "Making new thread: {0} for thread ID: {1:x}.", 1525 thread_sp.get(), thread_sp->GetID()); 1526 } else { 1527 LLDB_LOGV(log, "Found old thread: {0} for thread ID: {1:x}.", 1528 thread_sp.get(), thread_sp->GetID()); 1529 } 1530 1531 SetThreadPc(thread_sp, i); 1532 new_thread_list.AddThreadSortedByIndexID(thread_sp); 1533 } 1534 } 1535 1536 // Whatever that is left in old_thread_list_copy are not present in 1537 // new_thread_list. Remove non-existent threads from internal id table. 1538 size_t old_num_thread_ids = old_thread_list_copy.GetSize(false); 1539 for (size_t i = 0; i < old_num_thread_ids; i++) { 1540 ThreadSP old_thread_sp(old_thread_list_copy.GetThreadAtIndex(i, false)); 1541 if (old_thread_sp) { 1542 lldb::tid_t old_thread_id = old_thread_sp->GetProtocolID(); 1543 m_thread_id_to_index_id_map.erase(old_thread_id); 1544 } 1545 } 1546 1547 return true; 1548 } 1549 1550 void ProcessGDBRemote::SetThreadPc(const ThreadSP &thread_sp, uint64_t index) { 1551 if (m_thread_ids.size() == m_thread_pcs.size() && thread_sp.get() && 1552 GetByteOrder() != eByteOrderInvalid) { 1553 ThreadGDBRemote *gdb_thread = 1554 static_cast<ThreadGDBRemote *>(thread_sp.get()); 1555 RegisterContextSP reg_ctx_sp(thread_sp->GetRegisterContext()); 1556 if (reg_ctx_sp) { 1557 uint32_t pc_regnum = reg_ctx_sp->ConvertRegisterKindToRegisterNumber( 1558 eRegisterKindGeneric, LLDB_REGNUM_GENERIC_PC); 1559 if (pc_regnum != LLDB_INVALID_REGNUM) { 1560 gdb_thread->PrivateSetRegisterValue(pc_regnum, m_thread_pcs[index]); 1561 } 1562 } 1563 } 1564 } 1565 1566 bool ProcessGDBRemote::GetThreadStopInfoFromJSON( 1567 ThreadGDBRemote *thread, const StructuredData::ObjectSP &thread_infos_sp) { 1568 // See if we got thread stop infos for all threads via the "jThreadsInfo" 1569 // packet 1570 if (thread_infos_sp) { 1571 StructuredData::Array *thread_infos = thread_infos_sp->GetAsArray(); 1572 if (thread_infos) { 1573 lldb::tid_t tid; 1574 const size_t n = thread_infos->GetSize(); 1575 for (size_t i = 0; i < n; ++i) { 1576 StructuredData::Dictionary *thread_dict = 1577 thread_infos->GetItemAtIndex(i)->GetAsDictionary(); 1578 if (thread_dict) { 1579 if (thread_dict->GetValueForKeyAsInteger<lldb::tid_t>( 1580 "tid", tid, LLDB_INVALID_THREAD_ID)) { 1581 if (tid == thread->GetID()) 1582 return (bool)SetThreadStopInfo(thread_dict); 1583 } 1584 } 1585 } 1586 } 1587 } 1588 return false; 1589 } 1590 1591 bool ProcessGDBRemote::CalculateThreadStopInfo(ThreadGDBRemote *thread) { 1592 // See if we got thread stop infos for all threads via the "jThreadsInfo" 1593 // packet 1594 if (GetThreadStopInfoFromJSON(thread, m_jthreadsinfo_sp)) 1595 return true; 1596 1597 // See if we got thread stop info for any threads valid stop info reasons 1598 // threads via the "jstopinfo" packet stop reply packet key/value pair? 1599 if (m_jstopinfo_sp) { 1600 // If we have "jstopinfo" then we have stop descriptions for all threads 1601 // that have stop reasons, and if there is no entry for a thread, then it 1602 // has no stop reason. 1603 thread->GetRegisterContext()->InvalidateIfNeeded(true); 1604 if (!GetThreadStopInfoFromJSON(thread, m_jstopinfo_sp)) { 1605 // If a thread is stopped at a breakpoint site, set that as the stop 1606 // reason even if it hasn't executed the breakpoint instruction yet. 1607 // We will silently step over the breakpoint when we resume execution 1608 // and miss the fact that this thread hit the breakpoint. 1609 const size_t num_thread_ids = m_thread_ids.size(); 1610 for (size_t i = 0; i < num_thread_ids; i++) { 1611 if (m_thread_ids[i] == thread->GetID() && m_thread_pcs.size() > i) { 1612 addr_t pc = m_thread_pcs[i]; 1613 lldb::BreakpointSiteSP bp_site_sp = 1614 thread->GetProcess()->GetBreakpointSiteList().FindByAddress(pc); 1615 if (bp_site_sp) { 1616 if (bp_site_sp->ValidForThisThread(*thread)) { 1617 thread->SetStopInfo( 1618 StopInfo::CreateStopReasonWithBreakpointSiteID( 1619 *thread, bp_site_sp->GetID())); 1620 return true; 1621 } 1622 } 1623 } 1624 } 1625 thread->SetStopInfo(StopInfoSP()); 1626 } 1627 return true; 1628 } 1629 1630 // Fall back to using the qThreadStopInfo packet 1631 StringExtractorGDBRemote stop_packet; 1632 if (GetGDBRemote().GetThreadStopInfo(thread->GetProtocolID(), stop_packet)) 1633 return SetThreadStopInfo(stop_packet) == eStateStopped; 1634 return false; 1635 } 1636 1637 void ProcessGDBRemote::ParseExpeditedRegisters( 1638 ExpeditedRegisterMap &expedited_register_map, ThreadSP thread_sp) { 1639 ThreadGDBRemote *gdb_thread = static_cast<ThreadGDBRemote *>(thread_sp.get()); 1640 RegisterContextSP gdb_reg_ctx_sp(gdb_thread->GetRegisterContext()); 1641 1642 for (const auto &pair : expedited_register_map) { 1643 StringExtractor reg_value_extractor(pair.second); 1644 WritableDataBufferSP buffer_sp( 1645 new DataBufferHeap(reg_value_extractor.GetStringRef().size() / 2, 0)); 1646 reg_value_extractor.GetHexBytes(buffer_sp->GetData(), '\xcc'); 1647 uint32_t lldb_regnum = gdb_reg_ctx_sp->ConvertRegisterKindToRegisterNumber( 1648 eRegisterKindProcessPlugin, pair.first); 1649 gdb_thread->PrivateSetRegisterValue(lldb_regnum, buffer_sp->GetData()); 1650 } 1651 } 1652 1653 ThreadSP ProcessGDBRemote::SetThreadStopInfo( 1654 lldb::tid_t tid, ExpeditedRegisterMap &expedited_register_map, 1655 uint8_t signo, const std::string &thread_name, const std::string &reason, 1656 const std::string &description, uint32_t exc_type, 1657 const std::vector<addr_t> &exc_data, addr_t thread_dispatch_qaddr, 1658 bool queue_vars_valid, // Set to true if queue_name, queue_kind and 1659 // queue_serial are valid 1660 LazyBool associated_with_dispatch_queue, addr_t dispatch_queue_t, 1661 std::string &queue_name, QueueKind queue_kind, uint64_t queue_serial) { 1662 1663 if (tid == LLDB_INVALID_THREAD_ID) 1664 return nullptr; 1665 1666 ThreadSP thread_sp; 1667 // Scope for "locker" below 1668 { 1669 // m_thread_list_real does have its own mutex, but we need to hold onto the 1670 // mutex between the call to m_thread_list_real.FindThreadByID(...) and the 1671 // m_thread_list_real.AddThread(...) so it doesn't change on us 1672 std::lock_guard<std::recursive_mutex> guard(m_thread_list_real.GetMutex()); 1673 thread_sp = m_thread_list_real.FindThreadByProtocolID(tid, false); 1674 1675 if (!thread_sp) { 1676 // Create the thread if we need to 1677 thread_sp = std::make_shared<ThreadGDBRemote>(*this, tid); 1678 m_thread_list_real.AddThread(thread_sp); 1679 } 1680 } 1681 1682 ThreadGDBRemote *gdb_thread = static_cast<ThreadGDBRemote *>(thread_sp.get()); 1683 RegisterContextSP reg_ctx_sp(gdb_thread->GetRegisterContext()); 1684 1685 reg_ctx_sp->InvalidateIfNeeded(true); 1686 1687 auto iter = std::find(m_thread_ids.begin(), m_thread_ids.end(), tid); 1688 if (iter != m_thread_ids.end()) 1689 SetThreadPc(thread_sp, iter - m_thread_ids.begin()); 1690 1691 ParseExpeditedRegisters(expedited_register_map, thread_sp); 1692 1693 if (reg_ctx_sp->ReconfigureRegisterInfo()) { 1694 // Now we have changed the offsets of all the registers, so the values 1695 // will be corrupted. 1696 reg_ctx_sp->InvalidateAllRegisters(); 1697 // Expedited registers values will never contain registers that would be 1698 // resized by a reconfigure. So we are safe to continue using these 1699 // values. 1700 ParseExpeditedRegisters(expedited_register_map, thread_sp); 1701 } 1702 1703 thread_sp->SetName(thread_name.empty() ? nullptr : thread_name.c_str()); 1704 1705 gdb_thread->SetThreadDispatchQAddr(thread_dispatch_qaddr); 1706 // Check if the GDB server was able to provide the queue name, kind and serial 1707 // number 1708 if (queue_vars_valid) 1709 gdb_thread->SetQueueInfo(std::move(queue_name), queue_kind, queue_serial, 1710 dispatch_queue_t, associated_with_dispatch_queue); 1711 else 1712 gdb_thread->ClearQueueInfo(); 1713 1714 gdb_thread->SetAssociatedWithLibdispatchQueue(associated_with_dispatch_queue); 1715 1716 if (dispatch_queue_t != LLDB_INVALID_ADDRESS) 1717 gdb_thread->SetQueueLibdispatchQueueAddress(dispatch_queue_t); 1718 1719 // Make sure we update our thread stop reason just once, but don't overwrite 1720 // the stop info for threads that haven't moved: 1721 StopInfoSP current_stop_info_sp = thread_sp->GetPrivateStopInfo(false); 1722 if (thread_sp->GetTemporaryResumeState() == eStateSuspended && 1723 current_stop_info_sp) { 1724 thread_sp->SetStopInfo(current_stop_info_sp); 1725 return thread_sp; 1726 } 1727 1728 if (!thread_sp->StopInfoIsUpToDate()) { 1729 thread_sp->SetStopInfo(StopInfoSP()); 1730 // If there's a memory thread backed by this thread, we need to use it to 1731 // calculate StopInfo. 1732 if (ThreadSP memory_thread_sp = m_thread_list.GetBackingThread(thread_sp)) 1733 thread_sp = memory_thread_sp; 1734 1735 if (exc_type != 0) { 1736 // For thread plan async interrupt, creating stop info on the 1737 // original async interrupt request thread instead. If interrupt thread 1738 // does not exist anymore we fallback to current signal receiving thread 1739 // instead. 1740 ThreadSP interrupt_thread; 1741 if (m_interrupt_tid != LLDB_INVALID_THREAD_ID) 1742 interrupt_thread = HandleThreadAsyncInterrupt(signo, description); 1743 if (interrupt_thread) 1744 thread_sp = interrupt_thread; 1745 else { 1746 const size_t exc_data_size = exc_data.size(); 1747 thread_sp->SetStopInfo( 1748 StopInfoMachException::CreateStopReasonWithMachException( 1749 *thread_sp, exc_type, exc_data_size, 1750 exc_data_size >= 1 ? exc_data[0] : 0, 1751 exc_data_size >= 2 ? exc_data[1] : 0, 1752 exc_data_size >= 3 ? exc_data[2] : 0)); 1753 } 1754 } else { 1755 bool handled = false; 1756 bool did_exec = false; 1757 // debugserver can send reason = "none" which is equivalent 1758 // to no reason. 1759 if (!reason.empty() && reason != "none") { 1760 if (reason == "trace") { 1761 addr_t pc = thread_sp->GetRegisterContext()->GetPC(); 1762 lldb::BreakpointSiteSP bp_site_sp = 1763 thread_sp->GetProcess()->GetBreakpointSiteList().FindByAddress( 1764 pc); 1765 1766 // If the current pc is a breakpoint site then the StopInfo should be 1767 // set to Breakpoint Otherwise, it will be set to Trace. 1768 if (bp_site_sp && bp_site_sp->ValidForThisThread(*thread_sp)) { 1769 thread_sp->SetStopInfo( 1770 StopInfo::CreateStopReasonWithBreakpointSiteID( 1771 *thread_sp, bp_site_sp->GetID())); 1772 } else 1773 thread_sp->SetStopInfo( 1774 StopInfo::CreateStopReasonToTrace(*thread_sp)); 1775 handled = true; 1776 } else if (reason == "breakpoint") { 1777 addr_t pc = thread_sp->GetRegisterContext()->GetPC(); 1778 lldb::BreakpointSiteSP bp_site_sp = 1779 thread_sp->GetProcess()->GetBreakpointSiteList().FindByAddress( 1780 pc); 1781 if (bp_site_sp) { 1782 // If the breakpoint is for this thread, then we'll report the hit, 1783 // but if it is for another thread, we can just report no reason. 1784 // We don't need to worry about stepping over the breakpoint here, 1785 // that will be taken care of when the thread resumes and notices 1786 // that there's a breakpoint under the pc. 1787 handled = true; 1788 if (bp_site_sp->ValidForThisThread(*thread_sp)) { 1789 thread_sp->SetStopInfo( 1790 StopInfo::CreateStopReasonWithBreakpointSiteID( 1791 *thread_sp, bp_site_sp->GetID())); 1792 } else { 1793 StopInfoSP invalid_stop_info_sp; 1794 thread_sp->SetStopInfo(invalid_stop_info_sp); 1795 } 1796 } 1797 } else if (reason == "trap") { 1798 // Let the trap just use the standard signal stop reason below... 1799 } else if (reason == "watchpoint") { 1800 // We will have between 1 and 3 fields in the description. 1801 // 1802 // \a wp_addr which is the original start address that 1803 // lldb requested be watched, or an address that the 1804 // hardware reported. This address should be within the 1805 // range of a currently active watchpoint region - lldb 1806 // should be able to find a watchpoint with this address. 1807 // 1808 // \a wp_index is the hardware watchpoint register number. 1809 // 1810 // \a wp_hit_addr is the actual address reported by the hardware, 1811 // which may be outside the range of a region we are watching. 1812 // 1813 // On MIPS, we may get a false watchpoint exception where an 1814 // access to the same 8 byte granule as a watchpoint will trigger, 1815 // even if the access was not within the range of the watched 1816 // region. When we get a \a wp_hit_addr outside the range of any 1817 // set watchpoint, continue execution without making it visible to 1818 // the user. 1819 // 1820 // On ARM, a related issue where a large access that starts 1821 // before the watched region (and extends into the watched 1822 // region) may report a hit address before the watched region. 1823 // lldb will not find the "nearest" watchpoint to 1824 // disable/step/re-enable it, so one of the valid watchpoint 1825 // addresses should be provided as \a wp_addr. 1826 StringExtractor desc_extractor(description.c_str()); 1827 // FIXME NativeThreadLinux::SetStoppedByWatchpoint sends this 1828 // up as 1829 // <address within wp range> <wp hw index> <actual accessed addr> 1830 // but this is not reading the <wp hw index>. Seems like it 1831 // wouldn't work on MIPS, where that third field is important. 1832 addr_t wp_addr = desc_extractor.GetU64(LLDB_INVALID_ADDRESS); 1833 addr_t wp_hit_addr = desc_extractor.GetU64(LLDB_INVALID_ADDRESS); 1834 watch_id_t watch_id = LLDB_INVALID_WATCH_ID; 1835 bool silently_continue = false; 1836 WatchpointResourceSP wp_resource_sp; 1837 if (wp_hit_addr != LLDB_INVALID_ADDRESS) { 1838 wp_resource_sp = 1839 m_watchpoint_resource_list.FindByAddress(wp_hit_addr); 1840 // On MIPS, \a wp_hit_addr outside the range of a watched 1841 // region means we should silently continue, it is a false hit. 1842 ArchSpec::Core core = GetTarget().GetArchitecture().GetCore(); 1843 if (!wp_resource_sp && core >= ArchSpec::kCore_mips_first && 1844 core <= ArchSpec::kCore_mips_last) 1845 silently_continue = true; 1846 } 1847 if (!wp_resource_sp && wp_addr != LLDB_INVALID_ADDRESS) 1848 wp_resource_sp = m_watchpoint_resource_list.FindByAddress(wp_addr); 1849 if (!wp_resource_sp) { 1850 Log *log(GetLog(GDBRLog::Watchpoints)); 1851 LLDB_LOGF(log, "failed to find watchpoint"); 1852 watch_id = LLDB_INVALID_SITE_ID; 1853 } else { 1854 // LWP_TODO: This is hardcoding a single Watchpoint in a 1855 // Resource, need to add 1856 // StopInfo::CreateStopReasonWithWatchpointResource which 1857 // represents all watchpoints that were tripped at this stop. 1858 watch_id = wp_resource_sp->GetConstituentAtIndex(0)->GetID(); 1859 } 1860 thread_sp->SetStopInfo(StopInfo::CreateStopReasonWithWatchpointID( 1861 *thread_sp, watch_id, silently_continue)); 1862 handled = true; 1863 } else if (reason == "exception") { 1864 thread_sp->SetStopInfo(StopInfo::CreateStopReasonWithException( 1865 *thread_sp, description.c_str())); 1866 handled = true; 1867 } else if (reason == "exec") { 1868 did_exec = true; 1869 thread_sp->SetStopInfo( 1870 StopInfo::CreateStopReasonWithExec(*thread_sp)); 1871 handled = true; 1872 } else if (reason == "processor trace") { 1873 thread_sp->SetStopInfo(StopInfo::CreateStopReasonProcessorTrace( 1874 *thread_sp, description.c_str())); 1875 } else if (reason == "fork") { 1876 StringExtractor desc_extractor(description.c_str()); 1877 lldb::pid_t child_pid = 1878 desc_extractor.GetU64(LLDB_INVALID_PROCESS_ID); 1879 lldb::tid_t child_tid = desc_extractor.GetU64(LLDB_INVALID_THREAD_ID); 1880 thread_sp->SetStopInfo( 1881 StopInfo::CreateStopReasonFork(*thread_sp, child_pid, child_tid)); 1882 handled = true; 1883 } else if (reason == "vfork") { 1884 StringExtractor desc_extractor(description.c_str()); 1885 lldb::pid_t child_pid = 1886 desc_extractor.GetU64(LLDB_INVALID_PROCESS_ID); 1887 lldb::tid_t child_tid = desc_extractor.GetU64(LLDB_INVALID_THREAD_ID); 1888 thread_sp->SetStopInfo(StopInfo::CreateStopReasonVFork( 1889 *thread_sp, child_pid, child_tid)); 1890 handled = true; 1891 } else if (reason == "vforkdone") { 1892 thread_sp->SetStopInfo( 1893 StopInfo::CreateStopReasonVForkDone(*thread_sp)); 1894 handled = true; 1895 } 1896 } else if (!signo) { 1897 addr_t pc = thread_sp->GetRegisterContext()->GetPC(); 1898 lldb::BreakpointSiteSP bp_site_sp = 1899 thread_sp->GetProcess()->GetBreakpointSiteList().FindByAddress(pc); 1900 1901 // If a thread is stopped at a breakpoint site, set that as the stop 1902 // reason even if it hasn't executed the breakpoint instruction yet. 1903 // We will silently step over the breakpoint when we resume execution 1904 // and miss the fact that this thread hit the breakpoint. 1905 if (bp_site_sp && bp_site_sp->ValidForThisThread(*thread_sp)) { 1906 thread_sp->SetStopInfo(StopInfo::CreateStopReasonWithBreakpointSiteID( 1907 *thread_sp, bp_site_sp->GetID())); 1908 handled = true; 1909 } 1910 } 1911 1912 if (!handled && signo && !did_exec) { 1913 if (signo == SIGTRAP) { 1914 // Currently we are going to assume SIGTRAP means we are either 1915 // hitting a breakpoint or hardware single stepping. 1916 handled = true; 1917 addr_t pc = 1918 thread_sp->GetRegisterContext()->GetPC() + m_breakpoint_pc_offset; 1919 lldb::BreakpointSiteSP bp_site_sp = 1920 thread_sp->GetProcess()->GetBreakpointSiteList().FindByAddress( 1921 pc); 1922 1923 if (bp_site_sp) { 1924 // If the breakpoint is for this thread, then we'll report the hit, 1925 // but if it is for another thread, we can just report no reason. 1926 // We don't need to worry about stepping over the breakpoint here, 1927 // that will be taken care of when the thread resumes and notices 1928 // that there's a breakpoint under the pc. 1929 if (bp_site_sp->ValidForThisThread(*thread_sp)) { 1930 if (m_breakpoint_pc_offset != 0) 1931 thread_sp->GetRegisterContext()->SetPC(pc); 1932 thread_sp->SetStopInfo( 1933 StopInfo::CreateStopReasonWithBreakpointSiteID( 1934 *thread_sp, bp_site_sp->GetID())); 1935 } else { 1936 StopInfoSP invalid_stop_info_sp; 1937 thread_sp->SetStopInfo(invalid_stop_info_sp); 1938 } 1939 } else { 1940 // If we were stepping then assume the stop was the result of the 1941 // trace. If we were not stepping then report the SIGTRAP. 1942 // FIXME: We are still missing the case where we single step over a 1943 // trap instruction. 1944 if (thread_sp->GetTemporaryResumeState() == eStateStepping) 1945 thread_sp->SetStopInfo( 1946 StopInfo::CreateStopReasonToTrace(*thread_sp)); 1947 else 1948 thread_sp->SetStopInfo(StopInfo::CreateStopReasonWithSignal( 1949 *thread_sp, signo, description.c_str())); 1950 } 1951 } 1952 if (!handled) { 1953 // For thread plan async interrupt, creating stop info on the 1954 // original async interrupt request thread instead. If interrupt 1955 // thread does not exist anymore we fallback to current signal 1956 // receiving thread instead. 1957 ThreadSP interrupt_thread; 1958 if (m_interrupt_tid != LLDB_INVALID_THREAD_ID) 1959 interrupt_thread = HandleThreadAsyncInterrupt(signo, description); 1960 if (interrupt_thread) 1961 thread_sp = interrupt_thread; 1962 else 1963 thread_sp->SetStopInfo(StopInfo::CreateStopReasonWithSignal( 1964 *thread_sp, signo, description.c_str())); 1965 } 1966 } 1967 1968 if (!description.empty()) { 1969 lldb::StopInfoSP stop_info_sp(thread_sp->GetStopInfo()); 1970 if (stop_info_sp) { 1971 const char *stop_info_desc = stop_info_sp->GetDescription(); 1972 if (!stop_info_desc || !stop_info_desc[0]) 1973 stop_info_sp->SetDescription(description.c_str()); 1974 } else { 1975 thread_sp->SetStopInfo(StopInfo::CreateStopReasonWithException( 1976 *thread_sp, description.c_str())); 1977 } 1978 } 1979 } 1980 } 1981 return thread_sp; 1982 } 1983 1984 ThreadSP 1985 ProcessGDBRemote::HandleThreadAsyncInterrupt(uint8_t signo, 1986 const std::string &description) { 1987 ThreadSP thread_sp; 1988 { 1989 std::lock_guard<std::recursive_mutex> guard(m_thread_list_real.GetMutex()); 1990 thread_sp = m_thread_list_real.FindThreadByProtocolID(m_interrupt_tid, 1991 /*can_update=*/false); 1992 } 1993 if (thread_sp) 1994 thread_sp->SetStopInfo(StopInfo::CreateStopReasonWithInterrupt( 1995 *thread_sp, signo, description.c_str())); 1996 // Clear m_interrupt_tid regardless we can find original interrupt thread or 1997 // not. 1998 m_interrupt_tid = LLDB_INVALID_THREAD_ID; 1999 return thread_sp; 2000 } 2001 2002 lldb::ThreadSP 2003 ProcessGDBRemote::SetThreadStopInfo(StructuredData::Dictionary *thread_dict) { 2004 static constexpr llvm::StringLiteral g_key_tid("tid"); 2005 static constexpr llvm::StringLiteral g_key_name("name"); 2006 static constexpr llvm::StringLiteral g_key_reason("reason"); 2007 static constexpr llvm::StringLiteral g_key_metype("metype"); 2008 static constexpr llvm::StringLiteral g_key_medata("medata"); 2009 static constexpr llvm::StringLiteral g_key_qaddr("qaddr"); 2010 static constexpr llvm::StringLiteral g_key_dispatch_queue_t( 2011 "dispatch_queue_t"); 2012 static constexpr llvm::StringLiteral g_key_associated_with_dispatch_queue( 2013 "associated_with_dispatch_queue"); 2014 static constexpr llvm::StringLiteral g_key_queue_name("qname"); 2015 static constexpr llvm::StringLiteral g_key_queue_kind("qkind"); 2016 static constexpr llvm::StringLiteral g_key_queue_serial_number("qserialnum"); 2017 static constexpr llvm::StringLiteral g_key_registers("registers"); 2018 static constexpr llvm::StringLiteral g_key_memory("memory"); 2019 static constexpr llvm::StringLiteral g_key_description("description"); 2020 static constexpr llvm::StringLiteral g_key_signal("signal"); 2021 2022 // Stop with signal and thread info 2023 lldb::tid_t tid = LLDB_INVALID_THREAD_ID; 2024 uint8_t signo = 0; 2025 std::string value; 2026 std::string thread_name; 2027 std::string reason; 2028 std::string description; 2029 uint32_t exc_type = 0; 2030 std::vector<addr_t> exc_data; 2031 addr_t thread_dispatch_qaddr = LLDB_INVALID_ADDRESS; 2032 ExpeditedRegisterMap expedited_register_map; 2033 bool queue_vars_valid = false; 2034 addr_t dispatch_queue_t = LLDB_INVALID_ADDRESS; 2035 LazyBool associated_with_dispatch_queue = eLazyBoolCalculate; 2036 std::string queue_name; 2037 QueueKind queue_kind = eQueueKindUnknown; 2038 uint64_t queue_serial_number = 0; 2039 // Iterate through all of the thread dictionary key/value pairs from the 2040 // structured data dictionary 2041 2042 // FIXME: we're silently ignoring invalid data here 2043 thread_dict->ForEach([this, &tid, &expedited_register_map, &thread_name, 2044 &signo, &reason, &description, &exc_type, &exc_data, 2045 &thread_dispatch_qaddr, &queue_vars_valid, 2046 &associated_with_dispatch_queue, &dispatch_queue_t, 2047 &queue_name, &queue_kind, &queue_serial_number]( 2048 llvm::StringRef key, 2049 StructuredData::Object *object) -> bool { 2050 if (key == g_key_tid) { 2051 // thread in big endian hex 2052 tid = object->GetUnsignedIntegerValue(LLDB_INVALID_THREAD_ID); 2053 } else if (key == g_key_metype) { 2054 // exception type in big endian hex 2055 exc_type = object->GetUnsignedIntegerValue(0); 2056 } else if (key == g_key_medata) { 2057 // exception data in big endian hex 2058 StructuredData::Array *array = object->GetAsArray(); 2059 if (array) { 2060 array->ForEach([&exc_data](StructuredData::Object *object) -> bool { 2061 exc_data.push_back(object->GetUnsignedIntegerValue()); 2062 return true; // Keep iterating through all array items 2063 }); 2064 } 2065 } else if (key == g_key_name) { 2066 thread_name = std::string(object->GetStringValue()); 2067 } else if (key == g_key_qaddr) { 2068 thread_dispatch_qaddr = 2069 object->GetUnsignedIntegerValue(LLDB_INVALID_ADDRESS); 2070 } else if (key == g_key_queue_name) { 2071 queue_vars_valid = true; 2072 queue_name = std::string(object->GetStringValue()); 2073 } else if (key == g_key_queue_kind) { 2074 std::string queue_kind_str = std::string(object->GetStringValue()); 2075 if (queue_kind_str == "serial") { 2076 queue_vars_valid = true; 2077 queue_kind = eQueueKindSerial; 2078 } else if (queue_kind_str == "concurrent") { 2079 queue_vars_valid = true; 2080 queue_kind = eQueueKindConcurrent; 2081 } 2082 } else if (key == g_key_queue_serial_number) { 2083 queue_serial_number = object->GetUnsignedIntegerValue(0); 2084 if (queue_serial_number != 0) 2085 queue_vars_valid = true; 2086 } else if (key == g_key_dispatch_queue_t) { 2087 dispatch_queue_t = object->GetUnsignedIntegerValue(0); 2088 if (dispatch_queue_t != 0 && dispatch_queue_t != LLDB_INVALID_ADDRESS) 2089 queue_vars_valid = true; 2090 } else if (key == g_key_associated_with_dispatch_queue) { 2091 queue_vars_valid = true; 2092 bool associated = object->GetBooleanValue(); 2093 if (associated) 2094 associated_with_dispatch_queue = eLazyBoolYes; 2095 else 2096 associated_with_dispatch_queue = eLazyBoolNo; 2097 } else if (key == g_key_reason) { 2098 reason = std::string(object->GetStringValue()); 2099 } else if (key == g_key_description) { 2100 description = std::string(object->GetStringValue()); 2101 } else if (key == g_key_registers) { 2102 StructuredData::Dictionary *registers_dict = object->GetAsDictionary(); 2103 2104 if (registers_dict) { 2105 registers_dict->ForEach( 2106 [&expedited_register_map](llvm::StringRef key, 2107 StructuredData::Object *object) -> bool { 2108 uint32_t reg; 2109 if (llvm::to_integer(key, reg)) 2110 expedited_register_map[reg] = 2111 std::string(object->GetStringValue()); 2112 return true; // Keep iterating through all array items 2113 }); 2114 } 2115 } else if (key == g_key_memory) { 2116 StructuredData::Array *array = object->GetAsArray(); 2117 if (array) { 2118 array->ForEach([this](StructuredData::Object *object) -> bool { 2119 StructuredData::Dictionary *mem_cache_dict = 2120 object->GetAsDictionary(); 2121 if (mem_cache_dict) { 2122 lldb::addr_t mem_cache_addr = LLDB_INVALID_ADDRESS; 2123 if (mem_cache_dict->GetValueForKeyAsInteger<lldb::addr_t>( 2124 "address", mem_cache_addr)) { 2125 if (mem_cache_addr != LLDB_INVALID_ADDRESS) { 2126 llvm::StringRef str; 2127 if (mem_cache_dict->GetValueForKeyAsString("bytes", str)) { 2128 StringExtractor bytes(str); 2129 bytes.SetFilePos(0); 2130 2131 const size_t byte_size = bytes.GetStringRef().size() / 2; 2132 WritableDataBufferSP data_buffer_sp( 2133 new DataBufferHeap(byte_size, 0)); 2134 const size_t bytes_copied = 2135 bytes.GetHexBytes(data_buffer_sp->GetData(), 0); 2136 if (bytes_copied == byte_size) 2137 m_memory_cache.AddL1CacheData(mem_cache_addr, 2138 data_buffer_sp); 2139 } 2140 } 2141 } 2142 } 2143 return true; // Keep iterating through all array items 2144 }); 2145 } 2146 2147 } else if (key == g_key_signal) 2148 signo = object->GetUnsignedIntegerValue(LLDB_INVALID_SIGNAL_NUMBER); 2149 return true; // Keep iterating through all dictionary key/value pairs 2150 }); 2151 2152 return SetThreadStopInfo(tid, expedited_register_map, signo, thread_name, 2153 reason, description, exc_type, exc_data, 2154 thread_dispatch_qaddr, queue_vars_valid, 2155 associated_with_dispatch_queue, dispatch_queue_t, 2156 queue_name, queue_kind, queue_serial_number); 2157 } 2158 2159 StateType ProcessGDBRemote::SetThreadStopInfo(StringExtractor &stop_packet) { 2160 lldb::pid_t pid = m_gdb_comm.GetCurrentProcessID(); 2161 stop_packet.SetFilePos(0); 2162 const char stop_type = stop_packet.GetChar(); 2163 switch (stop_type) { 2164 case 'T': 2165 case 'S': { 2166 // This is a bit of a hack, but it is required. If we did exec, we need to 2167 // clear our thread lists and also know to rebuild our dynamic register 2168 // info before we lookup and threads and populate the expedited register 2169 // values so we need to know this right away so we can cleanup and update 2170 // our registers. 2171 const uint32_t stop_id = GetStopID(); 2172 if (stop_id == 0) { 2173 // Our first stop, make sure we have a process ID, and also make sure we 2174 // know about our registers 2175 if (GetID() == LLDB_INVALID_PROCESS_ID && pid != LLDB_INVALID_PROCESS_ID) 2176 SetID(pid); 2177 BuildDynamicRegisterInfo(true); 2178 } 2179 // Stop with signal and thread info 2180 lldb::pid_t stop_pid = LLDB_INVALID_PROCESS_ID; 2181 lldb::tid_t tid = LLDB_INVALID_THREAD_ID; 2182 const uint8_t signo = stop_packet.GetHexU8(); 2183 llvm::StringRef key; 2184 llvm::StringRef value; 2185 std::string thread_name; 2186 std::string reason; 2187 std::string description; 2188 uint32_t exc_type = 0; 2189 std::vector<addr_t> exc_data; 2190 addr_t thread_dispatch_qaddr = LLDB_INVALID_ADDRESS; 2191 bool queue_vars_valid = 2192 false; // says if locals below that start with "queue_" are valid 2193 addr_t dispatch_queue_t = LLDB_INVALID_ADDRESS; 2194 LazyBool associated_with_dispatch_queue = eLazyBoolCalculate; 2195 std::string queue_name; 2196 QueueKind queue_kind = eQueueKindUnknown; 2197 uint64_t queue_serial_number = 0; 2198 ExpeditedRegisterMap expedited_register_map; 2199 AddressableBits addressable_bits; 2200 while (stop_packet.GetNameColonValue(key, value)) { 2201 if (key.compare("metype") == 0) { 2202 // exception type in big endian hex 2203 value.getAsInteger(16, exc_type); 2204 } else if (key.compare("medata") == 0) { 2205 // exception data in big endian hex 2206 uint64_t x; 2207 value.getAsInteger(16, x); 2208 exc_data.push_back(x); 2209 } else if (key.compare("thread") == 0) { 2210 // thread-id 2211 StringExtractorGDBRemote thread_id{value}; 2212 auto pid_tid = thread_id.GetPidTid(pid); 2213 if (pid_tid) { 2214 stop_pid = pid_tid->first; 2215 tid = pid_tid->second; 2216 } else 2217 tid = LLDB_INVALID_THREAD_ID; 2218 } else if (key.compare("threads") == 0) { 2219 std::lock_guard<std::recursive_mutex> guard( 2220 m_thread_list_real.GetMutex()); 2221 UpdateThreadIDsFromStopReplyThreadsValue(value); 2222 } else if (key.compare("thread-pcs") == 0) { 2223 m_thread_pcs.clear(); 2224 // A comma separated list of all threads in the current 2225 // process that includes the thread for this stop reply packet 2226 lldb::addr_t pc; 2227 while (!value.empty()) { 2228 llvm::StringRef pc_str; 2229 std::tie(pc_str, value) = value.split(','); 2230 if (pc_str.getAsInteger(16, pc)) 2231 pc = LLDB_INVALID_ADDRESS; 2232 m_thread_pcs.push_back(pc); 2233 } 2234 } else if (key.compare("jstopinfo") == 0) { 2235 StringExtractor json_extractor(value); 2236 std::string json; 2237 // Now convert the HEX bytes into a string value 2238 json_extractor.GetHexByteString(json); 2239 2240 // This JSON contains thread IDs and thread stop info for all threads. 2241 // It doesn't contain expedited registers, memory or queue info. 2242 m_jstopinfo_sp = StructuredData::ParseJSON(json); 2243 } else if (key.compare("hexname") == 0) { 2244 StringExtractor name_extractor(value); 2245 std::string name; 2246 // Now convert the HEX bytes into a string value 2247 name_extractor.GetHexByteString(thread_name); 2248 } else if (key.compare("name") == 0) { 2249 thread_name = std::string(value); 2250 } else if (key.compare("qaddr") == 0) { 2251 value.getAsInteger(16, thread_dispatch_qaddr); 2252 } else if (key.compare("dispatch_queue_t") == 0) { 2253 queue_vars_valid = true; 2254 value.getAsInteger(16, dispatch_queue_t); 2255 } else if (key.compare("qname") == 0) { 2256 queue_vars_valid = true; 2257 StringExtractor name_extractor(value); 2258 // Now convert the HEX bytes into a string value 2259 name_extractor.GetHexByteString(queue_name); 2260 } else if (key.compare("qkind") == 0) { 2261 queue_kind = llvm::StringSwitch<QueueKind>(value) 2262 .Case("serial", eQueueKindSerial) 2263 .Case("concurrent", eQueueKindConcurrent) 2264 .Default(eQueueKindUnknown); 2265 queue_vars_valid = queue_kind != eQueueKindUnknown; 2266 } else if (key.compare("qserialnum") == 0) { 2267 if (!value.getAsInteger(0, queue_serial_number)) 2268 queue_vars_valid = true; 2269 } else if (key.compare("reason") == 0) { 2270 reason = std::string(value); 2271 } else if (key.compare("description") == 0) { 2272 StringExtractor desc_extractor(value); 2273 // Now convert the HEX bytes into a string value 2274 desc_extractor.GetHexByteString(description); 2275 } else if (key.compare("memory") == 0) { 2276 // Expedited memory. GDB servers can choose to send back expedited 2277 // memory that can populate the L1 memory cache in the process so that 2278 // things like the frame pointer backchain can be expedited. This will 2279 // help stack backtracing be more efficient by not having to send as 2280 // many memory read requests down the remote GDB server. 2281 2282 // Key/value pair format: memory:<addr>=<bytes>; 2283 // <addr> is a number whose base will be interpreted by the prefix: 2284 // "0x[0-9a-fA-F]+" for hex 2285 // "0[0-7]+" for octal 2286 // "[1-9]+" for decimal 2287 // <bytes> is native endian ASCII hex bytes just like the register 2288 // values 2289 llvm::StringRef addr_str, bytes_str; 2290 std::tie(addr_str, bytes_str) = value.split('='); 2291 if (!addr_str.empty() && !bytes_str.empty()) { 2292 lldb::addr_t mem_cache_addr = LLDB_INVALID_ADDRESS; 2293 if (!addr_str.getAsInteger(0, mem_cache_addr)) { 2294 StringExtractor bytes(bytes_str); 2295 const size_t byte_size = bytes.GetBytesLeft() / 2; 2296 WritableDataBufferSP data_buffer_sp( 2297 new DataBufferHeap(byte_size, 0)); 2298 const size_t bytes_copied = 2299 bytes.GetHexBytes(data_buffer_sp->GetData(), 0); 2300 if (bytes_copied == byte_size) 2301 m_memory_cache.AddL1CacheData(mem_cache_addr, data_buffer_sp); 2302 } 2303 } 2304 } else if (key.compare("watch") == 0 || key.compare("rwatch") == 0 || 2305 key.compare("awatch") == 0) { 2306 // Support standard GDB remote stop reply packet 'TAAwatch:addr' 2307 lldb::addr_t wp_addr = LLDB_INVALID_ADDRESS; 2308 value.getAsInteger(16, wp_addr); 2309 2310 WatchpointResourceSP wp_resource_sp = 2311 m_watchpoint_resource_list.FindByAddress(wp_addr); 2312 2313 // Rewrite gdb standard watch/rwatch/awatch to 2314 // "reason:watchpoint" + "description:ADDR", 2315 // which is parsed in SetThreadStopInfo. 2316 reason = "watchpoint"; 2317 StreamString ostr; 2318 ostr.Printf("%" PRIu64, wp_addr); 2319 description = std::string(ostr.GetString()); 2320 } else if (key.compare("swbreak") == 0 || key.compare("hwbreak") == 0) { 2321 reason = "breakpoint"; 2322 } else if (key.compare("library") == 0) { 2323 auto error = LoadModules(); 2324 if (error) { 2325 Log *log(GetLog(GDBRLog::Process)); 2326 LLDB_LOG_ERROR(log, std::move(error), "Failed to load modules: {0}"); 2327 } 2328 } else if (key.compare("fork") == 0 || key.compare("vfork") == 0) { 2329 // fork includes child pid/tid in thread-id format 2330 StringExtractorGDBRemote thread_id{value}; 2331 auto pid_tid = thread_id.GetPidTid(LLDB_INVALID_PROCESS_ID); 2332 if (!pid_tid) { 2333 Log *log(GetLog(GDBRLog::Process)); 2334 LLDB_LOG(log, "Invalid PID/TID to fork: {0}", value); 2335 pid_tid = {{LLDB_INVALID_PROCESS_ID, LLDB_INVALID_THREAD_ID}}; 2336 } 2337 2338 reason = key.str(); 2339 StreamString ostr; 2340 ostr.Printf("%" PRIu64 " %" PRIu64, pid_tid->first, pid_tid->second); 2341 description = std::string(ostr.GetString()); 2342 } else if (key.compare("addressing_bits") == 0) { 2343 uint64_t addressing_bits; 2344 if (!value.getAsInteger(0, addressing_bits)) { 2345 addressable_bits.SetAddressableBits(addressing_bits); 2346 } 2347 } else if (key.compare("low_mem_addressing_bits") == 0) { 2348 uint64_t addressing_bits; 2349 if (!value.getAsInteger(0, addressing_bits)) { 2350 addressable_bits.SetLowmemAddressableBits(addressing_bits); 2351 } 2352 } else if (key.compare("high_mem_addressing_bits") == 0) { 2353 uint64_t addressing_bits; 2354 if (!value.getAsInteger(0, addressing_bits)) { 2355 addressable_bits.SetHighmemAddressableBits(addressing_bits); 2356 } 2357 } else if (key.size() == 2 && ::isxdigit(key[0]) && ::isxdigit(key[1])) { 2358 uint32_t reg = UINT32_MAX; 2359 if (!key.getAsInteger(16, reg)) 2360 expedited_register_map[reg] = std::string(std::move(value)); 2361 } 2362 // swbreak and hwbreak are also expected keys, but we don't need to 2363 // change our behaviour for them because lldb always expects the remote 2364 // to adjust the program counter (if relevant, e.g., for x86 targets) 2365 } 2366 2367 if (stop_pid != LLDB_INVALID_PROCESS_ID && stop_pid != pid) { 2368 Log *log = GetLog(GDBRLog::Process); 2369 LLDB_LOG(log, 2370 "Received stop for incorrect PID = {0} (inferior PID = {1})", 2371 stop_pid, pid); 2372 return eStateInvalid; 2373 } 2374 2375 if (tid == LLDB_INVALID_THREAD_ID) { 2376 // A thread id may be invalid if the response is old style 'S' packet 2377 // which does not provide the 2378 // thread information. So update the thread list and choose the first 2379 // one. 2380 UpdateThreadIDList(); 2381 2382 if (!m_thread_ids.empty()) { 2383 tid = m_thread_ids.front(); 2384 } 2385 } 2386 2387 SetAddressableBitMasks(addressable_bits); 2388 2389 ThreadSP thread_sp = SetThreadStopInfo( 2390 tid, expedited_register_map, signo, thread_name, reason, description, 2391 exc_type, exc_data, thread_dispatch_qaddr, queue_vars_valid, 2392 associated_with_dispatch_queue, dispatch_queue_t, queue_name, 2393 queue_kind, queue_serial_number); 2394 2395 return eStateStopped; 2396 } break; 2397 2398 case 'W': 2399 case 'X': 2400 // process exited 2401 return eStateExited; 2402 2403 default: 2404 break; 2405 } 2406 return eStateInvalid; 2407 } 2408 2409 void ProcessGDBRemote::RefreshStateAfterStop() { 2410 std::lock_guard<std::recursive_mutex> guard(m_thread_list_real.GetMutex()); 2411 2412 m_thread_ids.clear(); 2413 m_thread_pcs.clear(); 2414 2415 // Set the thread stop info. It might have a "threads" key whose value is a 2416 // list of all thread IDs in the current process, so m_thread_ids might get 2417 // set. 2418 // Check to see if SetThreadStopInfo() filled in m_thread_ids? 2419 if (m_thread_ids.empty()) { 2420 // No, we need to fetch the thread list manually 2421 UpdateThreadIDList(); 2422 } 2423 2424 // We might set some stop info's so make sure the thread list is up to 2425 // date before we do that or we might overwrite what was computed here. 2426 UpdateThreadListIfNeeded(); 2427 2428 if (m_last_stop_packet) 2429 SetThreadStopInfo(*m_last_stop_packet); 2430 m_last_stop_packet.reset(); 2431 2432 // If we have queried for a default thread id 2433 if (m_initial_tid != LLDB_INVALID_THREAD_ID) { 2434 m_thread_list.SetSelectedThreadByID(m_initial_tid); 2435 m_initial_tid = LLDB_INVALID_THREAD_ID; 2436 } 2437 2438 // Let all threads recover from stopping and do any clean up based on the 2439 // previous thread state (if any). 2440 m_thread_list_real.RefreshStateAfterStop(); 2441 } 2442 2443 Status ProcessGDBRemote::DoHalt(bool &caused_stop) { 2444 Status error; 2445 2446 if (m_public_state.GetValue() == eStateAttaching) { 2447 // We are being asked to halt during an attach. We used to just close our 2448 // file handle and debugserver will go away, but with remote proxies, it 2449 // is better to send a positive signal, so let's send the interrupt first... 2450 caused_stop = m_gdb_comm.Interrupt(GetInterruptTimeout()); 2451 m_gdb_comm.Disconnect(); 2452 } else 2453 caused_stop = m_gdb_comm.Interrupt(GetInterruptTimeout()); 2454 return error; 2455 } 2456 2457 Status ProcessGDBRemote::DoDetach(bool keep_stopped) { 2458 Status error; 2459 Log *log = GetLog(GDBRLog::Process); 2460 LLDB_LOGF(log, "ProcessGDBRemote::DoDetach(keep_stopped: %i)", keep_stopped); 2461 2462 error = m_gdb_comm.Detach(keep_stopped); 2463 if (log) { 2464 if (error.Success()) 2465 log->PutCString( 2466 "ProcessGDBRemote::DoDetach() detach packet sent successfully"); 2467 else 2468 LLDB_LOGF(log, 2469 "ProcessGDBRemote::DoDetach() detach packet send failed: %s", 2470 error.AsCString() ? error.AsCString() : "<unknown error>"); 2471 } 2472 2473 if (!error.Success()) 2474 return error; 2475 2476 // Sleep for one second to let the process get all detached... 2477 StopAsyncThread(); 2478 2479 SetPrivateState(eStateDetached); 2480 ResumePrivateStateThread(); 2481 2482 // KillDebugserverProcess (); 2483 return error; 2484 } 2485 2486 Status ProcessGDBRemote::DoDestroy() { 2487 Log *log = GetLog(GDBRLog::Process); 2488 LLDB_LOGF(log, "ProcessGDBRemote::DoDestroy()"); 2489 2490 // Interrupt if our inferior is running... 2491 int exit_status = SIGABRT; 2492 std::string exit_string; 2493 2494 if (m_gdb_comm.IsConnected()) { 2495 if (m_public_state.GetValue() != eStateAttaching) { 2496 llvm::Expected<int> kill_res = m_gdb_comm.KillProcess(GetID()); 2497 2498 if (kill_res) { 2499 exit_status = kill_res.get(); 2500 #if defined(__APPLE__) 2501 // For Native processes on Mac OS X, we launch through the Host 2502 // Platform, then hand the process off to debugserver, which becomes 2503 // the parent process through "PT_ATTACH". Then when we go to kill 2504 // the process on Mac OS X we call ptrace(PT_KILL) to kill it, then 2505 // we call waitpid which returns with no error and the correct 2506 // status. But amusingly enough that doesn't seem to actually reap 2507 // the process, but instead it is left around as a Zombie. Probably 2508 // the kernel is in the process of switching ownership back to lldb 2509 // which was the original parent, and gets confused in the handoff. 2510 // Anyway, so call waitpid here to finally reap it. 2511 PlatformSP platform_sp(GetTarget().GetPlatform()); 2512 if (platform_sp && platform_sp->IsHost()) { 2513 int status; 2514 ::pid_t reap_pid; 2515 reap_pid = waitpid(GetID(), &status, WNOHANG); 2516 LLDB_LOGF(log, "Reaped pid: %d, status: %d.\n", reap_pid, status); 2517 } 2518 #endif 2519 ClearThreadIDList(); 2520 exit_string.assign("killed"); 2521 } else { 2522 exit_string.assign(llvm::toString(kill_res.takeError())); 2523 } 2524 } else { 2525 exit_string.assign("killed or interrupted while attaching."); 2526 } 2527 } else { 2528 // If we missed setting the exit status on the way out, do it here. 2529 // NB set exit status can be called multiple times, the first one sets the 2530 // status. 2531 exit_string.assign("destroying when not connected to debugserver"); 2532 } 2533 2534 SetExitStatus(exit_status, exit_string.c_str()); 2535 2536 StopAsyncThread(); 2537 KillDebugserverProcess(); 2538 return Status(); 2539 } 2540 2541 void ProcessGDBRemote::SetLastStopPacket( 2542 const StringExtractorGDBRemote &response) { 2543 const bool did_exec = 2544 response.GetStringRef().find(";reason:exec;") != std::string::npos; 2545 if (did_exec) { 2546 Log *log = GetLog(GDBRLog::Process); 2547 LLDB_LOGF(log, "ProcessGDBRemote::SetLastStopPacket () - detected exec"); 2548 2549 m_thread_list_real.Clear(); 2550 m_thread_list.Clear(); 2551 BuildDynamicRegisterInfo(true); 2552 m_gdb_comm.ResetDiscoverableSettings(did_exec); 2553 } 2554 2555 m_last_stop_packet = response; 2556 } 2557 2558 void ProcessGDBRemote::SetUnixSignals(const UnixSignalsSP &signals_sp) { 2559 Process::SetUnixSignals(std::make_shared<GDBRemoteSignals>(signals_sp)); 2560 } 2561 2562 // Process Queries 2563 2564 bool ProcessGDBRemote::IsAlive() { 2565 return m_gdb_comm.IsConnected() && Process::IsAlive(); 2566 } 2567 2568 addr_t ProcessGDBRemote::GetImageInfoAddress() { 2569 // request the link map address via the $qShlibInfoAddr packet 2570 lldb::addr_t addr = m_gdb_comm.GetShlibInfoAddr(); 2571 2572 // the loaded module list can also provides a link map address 2573 if (addr == LLDB_INVALID_ADDRESS) { 2574 llvm::Expected<LoadedModuleInfoList> list = GetLoadedModuleList(); 2575 if (!list) { 2576 Log *log = GetLog(GDBRLog::Process); 2577 LLDB_LOG_ERROR(log, list.takeError(), "Failed to read module list: {0}."); 2578 } else { 2579 addr = list->m_link_map; 2580 } 2581 } 2582 2583 return addr; 2584 } 2585 2586 void ProcessGDBRemote::WillPublicStop() { 2587 // See if the GDB remote client supports the JSON threads info. If so, we 2588 // gather stop info for all threads, expedited registers, expedited memory, 2589 // runtime queue information (iOS and MacOSX only), and more. Expediting 2590 // memory will help stack backtracing be much faster. Expediting registers 2591 // will make sure we don't have to read the thread registers for GPRs. 2592 m_jthreadsinfo_sp = m_gdb_comm.GetThreadsInfo(); 2593 2594 if (m_jthreadsinfo_sp) { 2595 // Now set the stop info for each thread and also expedite any registers 2596 // and memory that was in the jThreadsInfo response. 2597 StructuredData::Array *thread_infos = m_jthreadsinfo_sp->GetAsArray(); 2598 if (thread_infos) { 2599 const size_t n = thread_infos->GetSize(); 2600 for (size_t i = 0; i < n; ++i) { 2601 StructuredData::Dictionary *thread_dict = 2602 thread_infos->GetItemAtIndex(i)->GetAsDictionary(); 2603 if (thread_dict) 2604 SetThreadStopInfo(thread_dict); 2605 } 2606 } 2607 } 2608 } 2609 2610 // Process Memory 2611 size_t ProcessGDBRemote::DoReadMemory(addr_t addr, void *buf, size_t size, 2612 Status &error) { 2613 GetMaxMemorySize(); 2614 bool binary_memory_read = m_gdb_comm.GetxPacketSupported(); 2615 // M and m packets take 2 bytes for 1 byte of memory 2616 size_t max_memory_size = 2617 binary_memory_read ? m_max_memory_size : m_max_memory_size / 2; 2618 if (size > max_memory_size) { 2619 // Keep memory read sizes down to a sane limit. This function will be 2620 // called multiple times in order to complete the task by 2621 // lldb_private::Process so it is ok to do this. 2622 size = max_memory_size; 2623 } 2624 2625 char packet[64]; 2626 int packet_len; 2627 packet_len = ::snprintf(packet, sizeof(packet), "%c%" PRIx64 ",%" PRIx64, 2628 binary_memory_read ? 'x' : 'm', (uint64_t)addr, 2629 (uint64_t)size); 2630 assert(packet_len + 1 < (int)sizeof(packet)); 2631 UNUSED_IF_ASSERT_DISABLED(packet_len); 2632 StringExtractorGDBRemote response; 2633 if (m_gdb_comm.SendPacketAndWaitForResponse(packet, response, 2634 GetInterruptTimeout()) == 2635 GDBRemoteCommunication::PacketResult::Success) { 2636 if (response.IsNormalResponse()) { 2637 error.Clear(); 2638 if (binary_memory_read) { 2639 // The lower level GDBRemoteCommunication packet receive layer has 2640 // already de-quoted any 0x7d character escaping that was present in 2641 // the packet 2642 2643 size_t data_received_size = response.GetBytesLeft(); 2644 if (data_received_size > size) { 2645 // Don't write past the end of BUF if the remote debug server gave us 2646 // too much data for some reason. 2647 data_received_size = size; 2648 } 2649 memcpy(buf, response.GetStringRef().data(), data_received_size); 2650 return data_received_size; 2651 } else { 2652 return response.GetHexBytes( 2653 llvm::MutableArrayRef<uint8_t>((uint8_t *)buf, size), '\xdd'); 2654 } 2655 } else if (response.IsErrorResponse()) 2656 error = Status::FromErrorStringWithFormat( 2657 "memory read failed for 0x%" PRIx64, addr); 2658 else if (response.IsUnsupportedResponse()) 2659 error = Status::FromErrorStringWithFormat( 2660 "GDB server does not support reading memory"); 2661 else 2662 error = Status::FromErrorStringWithFormat( 2663 "unexpected response to GDB server memory read packet '%s': '%s'", 2664 packet, response.GetStringRef().data()); 2665 } else { 2666 error = Status::FromErrorStringWithFormat("failed to send packet: '%s'", 2667 packet); 2668 } 2669 return 0; 2670 } 2671 2672 bool ProcessGDBRemote::SupportsMemoryTagging() { 2673 return m_gdb_comm.GetMemoryTaggingSupported(); 2674 } 2675 2676 llvm::Expected<std::vector<uint8_t>> 2677 ProcessGDBRemote::DoReadMemoryTags(lldb::addr_t addr, size_t len, 2678 int32_t type) { 2679 // By this point ReadMemoryTags has validated that tagging is enabled 2680 // for this target/process/address. 2681 DataBufferSP buffer_sp = m_gdb_comm.ReadMemoryTags(addr, len, type); 2682 if (!buffer_sp) { 2683 return llvm::createStringError(llvm::inconvertibleErrorCode(), 2684 "Error reading memory tags from remote"); 2685 } 2686 2687 // Return the raw tag data 2688 llvm::ArrayRef<uint8_t> tag_data = buffer_sp->GetData(); 2689 std::vector<uint8_t> got; 2690 got.reserve(tag_data.size()); 2691 std::copy(tag_data.begin(), tag_data.end(), std::back_inserter(got)); 2692 return got; 2693 } 2694 2695 Status ProcessGDBRemote::DoWriteMemoryTags(lldb::addr_t addr, size_t len, 2696 int32_t type, 2697 const std::vector<uint8_t> &tags) { 2698 // By now WriteMemoryTags should have validated that tagging is enabled 2699 // for this target/process. 2700 return m_gdb_comm.WriteMemoryTags(addr, len, type, tags); 2701 } 2702 2703 Status ProcessGDBRemote::WriteObjectFile( 2704 std::vector<ObjectFile::LoadableData> entries) { 2705 Status error; 2706 // Sort the entries by address because some writes, like those to flash 2707 // memory, must happen in order of increasing address. 2708 std::stable_sort( 2709 std::begin(entries), std::end(entries), 2710 [](const ObjectFile::LoadableData a, const ObjectFile::LoadableData b) { 2711 return a.Dest < b.Dest; 2712 }); 2713 m_allow_flash_writes = true; 2714 error = Process::WriteObjectFile(entries); 2715 if (error.Success()) 2716 error = FlashDone(); 2717 else 2718 // Even though some of the writing failed, try to send a flash done if some 2719 // of the writing succeeded so the flash state is reset to normal, but 2720 // don't stomp on the error status that was set in the write failure since 2721 // that's the one we want to report back. 2722 FlashDone(); 2723 m_allow_flash_writes = false; 2724 return error; 2725 } 2726 2727 bool ProcessGDBRemote::HasErased(FlashRange range) { 2728 auto size = m_erased_flash_ranges.GetSize(); 2729 for (size_t i = 0; i < size; ++i) 2730 if (m_erased_flash_ranges.GetEntryAtIndex(i)->Contains(range)) 2731 return true; 2732 return false; 2733 } 2734 2735 Status ProcessGDBRemote::FlashErase(lldb::addr_t addr, size_t size) { 2736 Status status; 2737 2738 MemoryRegionInfo region; 2739 status = GetMemoryRegionInfo(addr, region); 2740 if (!status.Success()) 2741 return status; 2742 2743 // The gdb spec doesn't say if erasures are allowed across multiple regions, 2744 // but we'll disallow it to be safe and to keep the logic simple by worring 2745 // about only one region's block size. DoMemoryWrite is this function's 2746 // primary user, and it can easily keep writes within a single memory region 2747 if (addr + size > region.GetRange().GetRangeEnd()) { 2748 status = 2749 Status::FromErrorString("Unable to erase flash in multiple regions"); 2750 return status; 2751 } 2752 2753 uint64_t blocksize = region.GetBlocksize(); 2754 if (blocksize == 0) { 2755 status = 2756 Status::FromErrorString("Unable to erase flash because blocksize is 0"); 2757 return status; 2758 } 2759 2760 // Erasures can only be done on block boundary adresses, so round down addr 2761 // and round up size 2762 lldb::addr_t block_start_addr = addr - (addr % blocksize); 2763 size += (addr - block_start_addr); 2764 if ((size % blocksize) != 0) 2765 size += (blocksize - size % blocksize); 2766 2767 FlashRange range(block_start_addr, size); 2768 2769 if (HasErased(range)) 2770 return status; 2771 2772 // We haven't erased the entire range, but we may have erased part of it. 2773 // (e.g., block A is already erased and range starts in A and ends in B). So, 2774 // adjust range if necessary to exclude already erased blocks. 2775 if (!m_erased_flash_ranges.IsEmpty()) { 2776 // Assuming that writes and erasures are done in increasing addr order, 2777 // because that is a requirement of the vFlashWrite command. Therefore, we 2778 // only need to look at the last range in the list for overlap. 2779 const auto &last_range = *m_erased_flash_ranges.Back(); 2780 if (range.GetRangeBase() < last_range.GetRangeEnd()) { 2781 auto overlap = last_range.GetRangeEnd() - range.GetRangeBase(); 2782 // overlap will be less than range.GetByteSize() or else HasErased() 2783 // would have been true 2784 range.SetByteSize(range.GetByteSize() - overlap); 2785 range.SetRangeBase(range.GetRangeBase() + overlap); 2786 } 2787 } 2788 2789 StreamString packet; 2790 packet.Printf("vFlashErase:%" PRIx64 ",%" PRIx64, range.GetRangeBase(), 2791 (uint64_t)range.GetByteSize()); 2792 2793 StringExtractorGDBRemote response; 2794 if (m_gdb_comm.SendPacketAndWaitForResponse(packet.GetString(), response, 2795 GetInterruptTimeout()) == 2796 GDBRemoteCommunication::PacketResult::Success) { 2797 if (response.IsOKResponse()) { 2798 m_erased_flash_ranges.Insert(range, true); 2799 } else { 2800 if (response.IsErrorResponse()) 2801 status = Status::FromErrorStringWithFormat( 2802 "flash erase failed for 0x%" PRIx64, addr); 2803 else if (response.IsUnsupportedResponse()) 2804 status = Status::FromErrorStringWithFormat( 2805 "GDB server does not support flashing"); 2806 else 2807 status = Status::FromErrorStringWithFormat( 2808 "unexpected response to GDB server flash erase packet '%s': '%s'", 2809 packet.GetData(), response.GetStringRef().data()); 2810 } 2811 } else { 2812 status = Status::FromErrorStringWithFormat("failed to send packet: '%s'", 2813 packet.GetData()); 2814 } 2815 return status; 2816 } 2817 2818 Status ProcessGDBRemote::FlashDone() { 2819 Status status; 2820 // If we haven't erased any blocks, then we must not have written anything 2821 // either, so there is no need to actually send a vFlashDone command 2822 if (m_erased_flash_ranges.IsEmpty()) 2823 return status; 2824 StringExtractorGDBRemote response; 2825 if (m_gdb_comm.SendPacketAndWaitForResponse("vFlashDone", response, 2826 GetInterruptTimeout()) == 2827 GDBRemoteCommunication::PacketResult::Success) { 2828 if (response.IsOKResponse()) { 2829 m_erased_flash_ranges.Clear(); 2830 } else { 2831 if (response.IsErrorResponse()) 2832 status = Status::FromErrorStringWithFormat("flash done failed"); 2833 else if (response.IsUnsupportedResponse()) 2834 status = Status::FromErrorStringWithFormat( 2835 "GDB server does not support flashing"); 2836 else 2837 status = Status::FromErrorStringWithFormat( 2838 "unexpected response to GDB server flash done packet: '%s'", 2839 response.GetStringRef().data()); 2840 } 2841 } else { 2842 status = 2843 Status::FromErrorStringWithFormat("failed to send flash done packet"); 2844 } 2845 return status; 2846 } 2847 2848 size_t ProcessGDBRemote::DoWriteMemory(addr_t addr, const void *buf, 2849 size_t size, Status &error) { 2850 GetMaxMemorySize(); 2851 // M and m packets take 2 bytes for 1 byte of memory 2852 size_t max_memory_size = m_max_memory_size / 2; 2853 if (size > max_memory_size) { 2854 // Keep memory read sizes down to a sane limit. This function will be 2855 // called multiple times in order to complete the task by 2856 // lldb_private::Process so it is ok to do this. 2857 size = max_memory_size; 2858 } 2859 2860 StreamGDBRemote packet; 2861 2862 MemoryRegionInfo region; 2863 Status region_status = GetMemoryRegionInfo(addr, region); 2864 2865 bool is_flash = 2866 region_status.Success() && region.GetFlash() == MemoryRegionInfo::eYes; 2867 2868 if (is_flash) { 2869 if (!m_allow_flash_writes) { 2870 error = Status::FromErrorString("Writing to flash memory is not allowed"); 2871 return 0; 2872 } 2873 // Keep the write within a flash memory region 2874 if (addr + size > region.GetRange().GetRangeEnd()) 2875 size = region.GetRange().GetRangeEnd() - addr; 2876 // Flash memory must be erased before it can be written 2877 error = FlashErase(addr, size); 2878 if (!error.Success()) 2879 return 0; 2880 packet.Printf("vFlashWrite:%" PRIx64 ":", addr); 2881 packet.PutEscapedBytes(buf, size); 2882 } else { 2883 packet.Printf("M%" PRIx64 ",%" PRIx64 ":", addr, (uint64_t)size); 2884 packet.PutBytesAsRawHex8(buf, size, endian::InlHostByteOrder(), 2885 endian::InlHostByteOrder()); 2886 } 2887 StringExtractorGDBRemote response; 2888 if (m_gdb_comm.SendPacketAndWaitForResponse(packet.GetString(), response, 2889 GetInterruptTimeout()) == 2890 GDBRemoteCommunication::PacketResult::Success) { 2891 if (response.IsOKResponse()) { 2892 error.Clear(); 2893 return size; 2894 } else if (response.IsErrorResponse()) 2895 error = Status::FromErrorStringWithFormat( 2896 "memory write failed for 0x%" PRIx64, addr); 2897 else if (response.IsUnsupportedResponse()) 2898 error = Status::FromErrorStringWithFormat( 2899 "GDB server does not support writing memory"); 2900 else 2901 error = Status::FromErrorStringWithFormat( 2902 "unexpected response to GDB server memory write packet '%s': '%s'", 2903 packet.GetData(), response.GetStringRef().data()); 2904 } else { 2905 error = Status::FromErrorStringWithFormat("failed to send packet: '%s'", 2906 packet.GetData()); 2907 } 2908 return 0; 2909 } 2910 2911 lldb::addr_t ProcessGDBRemote::DoAllocateMemory(size_t size, 2912 uint32_t permissions, 2913 Status &error) { 2914 Log *log = GetLog(LLDBLog::Process | LLDBLog::Expressions); 2915 addr_t allocated_addr = LLDB_INVALID_ADDRESS; 2916 2917 if (m_gdb_comm.SupportsAllocDeallocMemory() != eLazyBoolNo) { 2918 allocated_addr = m_gdb_comm.AllocateMemory(size, permissions); 2919 if (allocated_addr != LLDB_INVALID_ADDRESS || 2920 m_gdb_comm.SupportsAllocDeallocMemory() == eLazyBoolYes) 2921 return allocated_addr; 2922 } 2923 2924 if (m_gdb_comm.SupportsAllocDeallocMemory() == eLazyBoolNo) { 2925 // Call mmap() to create memory in the inferior.. 2926 unsigned prot = 0; 2927 if (permissions & lldb::ePermissionsReadable) 2928 prot |= eMmapProtRead; 2929 if (permissions & lldb::ePermissionsWritable) 2930 prot |= eMmapProtWrite; 2931 if (permissions & lldb::ePermissionsExecutable) 2932 prot |= eMmapProtExec; 2933 2934 if (InferiorCallMmap(this, allocated_addr, 0, size, prot, 2935 eMmapFlagsAnon | eMmapFlagsPrivate, -1, 0)) 2936 m_addr_to_mmap_size[allocated_addr] = size; 2937 else { 2938 allocated_addr = LLDB_INVALID_ADDRESS; 2939 LLDB_LOGF(log, 2940 "ProcessGDBRemote::%s no direct stub support for memory " 2941 "allocation, and InferiorCallMmap also failed - is stub " 2942 "missing register context save/restore capability?", 2943 __FUNCTION__); 2944 } 2945 } 2946 2947 if (allocated_addr == LLDB_INVALID_ADDRESS) 2948 error = Status::FromErrorStringWithFormat( 2949 "unable to allocate %" PRIu64 " bytes of memory with permissions %s", 2950 (uint64_t)size, GetPermissionsAsCString(permissions)); 2951 else 2952 error.Clear(); 2953 return allocated_addr; 2954 } 2955 2956 Status ProcessGDBRemote::DoGetMemoryRegionInfo(addr_t load_addr, 2957 MemoryRegionInfo ®ion_info) { 2958 2959 Status error(m_gdb_comm.GetMemoryRegionInfo(load_addr, region_info)); 2960 return error; 2961 } 2962 2963 std::optional<uint32_t> ProcessGDBRemote::GetWatchpointSlotCount() { 2964 return m_gdb_comm.GetWatchpointSlotCount(); 2965 } 2966 2967 std::optional<bool> ProcessGDBRemote::DoGetWatchpointReportedAfter() { 2968 return m_gdb_comm.GetWatchpointReportedAfter(); 2969 } 2970 2971 Status ProcessGDBRemote::DoDeallocateMemory(lldb::addr_t addr) { 2972 Status error; 2973 LazyBool supported = m_gdb_comm.SupportsAllocDeallocMemory(); 2974 2975 switch (supported) { 2976 case eLazyBoolCalculate: 2977 // We should never be deallocating memory without allocating memory first 2978 // so we should never get eLazyBoolCalculate 2979 error = Status::FromErrorString( 2980 "tried to deallocate memory without ever allocating memory"); 2981 break; 2982 2983 case eLazyBoolYes: 2984 if (!m_gdb_comm.DeallocateMemory(addr)) 2985 error = Status::FromErrorStringWithFormat( 2986 "unable to deallocate memory at 0x%" PRIx64, addr); 2987 break; 2988 2989 case eLazyBoolNo: 2990 // Call munmap() to deallocate memory in the inferior.. 2991 { 2992 MMapMap::iterator pos = m_addr_to_mmap_size.find(addr); 2993 if (pos != m_addr_to_mmap_size.end() && 2994 InferiorCallMunmap(this, addr, pos->second)) 2995 m_addr_to_mmap_size.erase(pos); 2996 else 2997 error = Status::FromErrorStringWithFormat( 2998 "unable to deallocate memory at 0x%" PRIx64, addr); 2999 } 3000 break; 3001 } 3002 3003 return error; 3004 } 3005 3006 // Process STDIO 3007 size_t ProcessGDBRemote::PutSTDIN(const char *src, size_t src_len, 3008 Status &error) { 3009 if (m_stdio_communication.IsConnected()) { 3010 ConnectionStatus status; 3011 m_stdio_communication.WriteAll(src, src_len, status, nullptr); 3012 } else if (m_stdin_forward) { 3013 m_gdb_comm.SendStdinNotification(src, src_len); 3014 } 3015 return 0; 3016 } 3017 3018 Status ProcessGDBRemote::EnableBreakpointSite(BreakpointSite *bp_site) { 3019 Status error; 3020 assert(bp_site != nullptr); 3021 3022 // Get logging info 3023 Log *log = GetLog(GDBRLog::Breakpoints); 3024 user_id_t site_id = bp_site->GetID(); 3025 3026 // Get the breakpoint address 3027 const addr_t addr = bp_site->GetLoadAddress(); 3028 3029 // Log that a breakpoint was requested 3030 LLDB_LOGF(log, 3031 "ProcessGDBRemote::EnableBreakpointSite (size_id = %" PRIu64 3032 ") address = 0x%" PRIx64, 3033 site_id, (uint64_t)addr); 3034 3035 // Breakpoint already exists and is enabled 3036 if (bp_site->IsEnabled()) { 3037 LLDB_LOGF(log, 3038 "ProcessGDBRemote::EnableBreakpointSite (size_id = %" PRIu64 3039 ") address = 0x%" PRIx64 " -- SUCCESS (already enabled)", 3040 site_id, (uint64_t)addr); 3041 return error; 3042 } 3043 3044 // Get the software breakpoint trap opcode size 3045 const size_t bp_op_size = GetSoftwareBreakpointTrapOpcode(bp_site); 3046 3047 // SupportsGDBStoppointPacket() simply checks a boolean, indicating if this 3048 // breakpoint type is supported by the remote stub. These are set to true by 3049 // default, and later set to false only after we receive an unimplemented 3050 // response when sending a breakpoint packet. This means initially that 3051 // unless we were specifically instructed to use a hardware breakpoint, LLDB 3052 // will attempt to set a software breakpoint. HardwareRequired() also queries 3053 // a boolean variable which indicates if the user specifically asked for 3054 // hardware breakpoints. If true then we will skip over software 3055 // breakpoints. 3056 if (m_gdb_comm.SupportsGDBStoppointPacket(eBreakpointSoftware) && 3057 (!bp_site->HardwareRequired())) { 3058 // Try to send off a software breakpoint packet ($Z0) 3059 uint8_t error_no = m_gdb_comm.SendGDBStoppointTypePacket( 3060 eBreakpointSoftware, true, addr, bp_op_size, GetInterruptTimeout()); 3061 if (error_no == 0) { 3062 // The breakpoint was placed successfully 3063 bp_site->SetEnabled(true); 3064 bp_site->SetType(BreakpointSite::eExternal); 3065 return error; 3066 } 3067 3068 // SendGDBStoppointTypePacket() will return an error if it was unable to 3069 // set this breakpoint. We need to differentiate between a error specific 3070 // to placing this breakpoint or if we have learned that this breakpoint 3071 // type is unsupported. To do this, we must test the support boolean for 3072 // this breakpoint type to see if it now indicates that this breakpoint 3073 // type is unsupported. If they are still supported then we should return 3074 // with the error code. If they are now unsupported, then we would like to 3075 // fall through and try another form of breakpoint. 3076 if (m_gdb_comm.SupportsGDBStoppointPacket(eBreakpointSoftware)) { 3077 if (error_no != UINT8_MAX) 3078 error = Status::FromErrorStringWithFormat( 3079 "error: %d sending the breakpoint request", error_no); 3080 else 3081 error = Status::FromErrorString("error sending the breakpoint request"); 3082 return error; 3083 } 3084 3085 // We reach here when software breakpoints have been found to be 3086 // unsupported. For future calls to set a breakpoint, we will not attempt 3087 // to set a breakpoint with a type that is known not to be supported. 3088 LLDB_LOGF(log, "Software breakpoints are unsupported"); 3089 3090 // So we will fall through and try a hardware breakpoint 3091 } 3092 3093 // The process of setting a hardware breakpoint is much the same as above. 3094 // We check the supported boolean for this breakpoint type, and if it is 3095 // thought to be supported then we will try to set this breakpoint with a 3096 // hardware breakpoint. 3097 if (m_gdb_comm.SupportsGDBStoppointPacket(eBreakpointHardware)) { 3098 // Try to send off a hardware breakpoint packet ($Z1) 3099 uint8_t error_no = m_gdb_comm.SendGDBStoppointTypePacket( 3100 eBreakpointHardware, true, addr, bp_op_size, GetInterruptTimeout()); 3101 if (error_no == 0) { 3102 // The breakpoint was placed successfully 3103 bp_site->SetEnabled(true); 3104 bp_site->SetType(BreakpointSite::eHardware); 3105 return error; 3106 } 3107 3108 // Check if the error was something other then an unsupported breakpoint 3109 // type 3110 if (m_gdb_comm.SupportsGDBStoppointPacket(eBreakpointHardware)) { 3111 // Unable to set this hardware breakpoint 3112 if (error_no != UINT8_MAX) 3113 error = Status::FromErrorStringWithFormat( 3114 "error: %d sending the hardware breakpoint request " 3115 "(hardware breakpoint resources might be exhausted or unavailable)", 3116 error_no); 3117 else 3118 error = Status::FromErrorString( 3119 "error sending the hardware breakpoint request " 3120 "(hardware breakpoint resources " 3121 "might be exhausted or unavailable)"); 3122 return error; 3123 } 3124 3125 // We will reach here when the stub gives an unsupported response to a 3126 // hardware breakpoint 3127 LLDB_LOGF(log, "Hardware breakpoints are unsupported"); 3128 3129 // Finally we will falling through to a #trap style breakpoint 3130 } 3131 3132 // Don't fall through when hardware breakpoints were specifically requested 3133 if (bp_site->HardwareRequired()) { 3134 error = Status::FromErrorString("hardware breakpoints are not supported"); 3135 return error; 3136 } 3137 3138 // As a last resort we want to place a manual breakpoint. An instruction is 3139 // placed into the process memory using memory write packets. 3140 return EnableSoftwareBreakpoint(bp_site); 3141 } 3142 3143 Status ProcessGDBRemote::DisableBreakpointSite(BreakpointSite *bp_site) { 3144 Status error; 3145 assert(bp_site != nullptr); 3146 addr_t addr = bp_site->GetLoadAddress(); 3147 user_id_t site_id = bp_site->GetID(); 3148 Log *log = GetLog(GDBRLog::Breakpoints); 3149 LLDB_LOGF(log, 3150 "ProcessGDBRemote::DisableBreakpointSite (site_id = %" PRIu64 3151 ") addr = 0x%8.8" PRIx64, 3152 site_id, (uint64_t)addr); 3153 3154 if (bp_site->IsEnabled()) { 3155 const size_t bp_op_size = GetSoftwareBreakpointTrapOpcode(bp_site); 3156 3157 BreakpointSite::Type bp_type = bp_site->GetType(); 3158 switch (bp_type) { 3159 case BreakpointSite::eSoftware: 3160 error = DisableSoftwareBreakpoint(bp_site); 3161 break; 3162 3163 case BreakpointSite::eHardware: 3164 if (m_gdb_comm.SendGDBStoppointTypePacket(eBreakpointHardware, false, 3165 addr, bp_op_size, 3166 GetInterruptTimeout())) 3167 error = Status::FromErrorString("unknown error"); 3168 break; 3169 3170 case BreakpointSite::eExternal: { 3171 if (m_gdb_comm.SendGDBStoppointTypePacket(eBreakpointSoftware, false, 3172 addr, bp_op_size, 3173 GetInterruptTimeout())) 3174 error = Status::FromErrorString("unknown error"); 3175 } break; 3176 } 3177 if (error.Success()) 3178 bp_site->SetEnabled(false); 3179 } else { 3180 LLDB_LOGF(log, 3181 "ProcessGDBRemote::DisableBreakpointSite (site_id = %" PRIu64 3182 ") addr = 0x%8.8" PRIx64 " -- SUCCESS (already disabled)", 3183 site_id, (uint64_t)addr); 3184 return error; 3185 } 3186 3187 if (error.Success()) 3188 error = Status::FromErrorString("unknown error"); 3189 return error; 3190 } 3191 3192 // Pre-requisite: wp != NULL. 3193 static GDBStoppointType 3194 GetGDBStoppointType(const WatchpointResourceSP &wp_res_sp) { 3195 assert(wp_res_sp); 3196 bool read = wp_res_sp->WatchpointResourceRead(); 3197 bool write = wp_res_sp->WatchpointResourceWrite(); 3198 3199 assert((read || write) && 3200 "WatchpointResource type is neither read nor write"); 3201 if (read && write) 3202 return eWatchpointReadWrite; 3203 else if (read) 3204 return eWatchpointRead; 3205 else 3206 return eWatchpointWrite; 3207 } 3208 3209 Status ProcessGDBRemote::EnableWatchpoint(WatchpointSP wp_sp, bool notify) { 3210 Status error; 3211 if (!wp_sp) { 3212 error = Status::FromErrorString("No watchpoint specified"); 3213 return error; 3214 } 3215 user_id_t watchID = wp_sp->GetID(); 3216 addr_t addr = wp_sp->GetLoadAddress(); 3217 Log *log(GetLog(GDBRLog::Watchpoints)); 3218 LLDB_LOGF(log, "ProcessGDBRemote::EnableWatchpoint(watchID = %" PRIu64 ")", 3219 watchID); 3220 if (wp_sp->IsEnabled()) { 3221 LLDB_LOGF(log, 3222 "ProcessGDBRemote::EnableWatchpoint(watchID = %" PRIu64 3223 ") addr = 0x%8.8" PRIx64 ": watchpoint already enabled.", 3224 watchID, (uint64_t)addr); 3225 return error; 3226 } 3227 3228 bool read = wp_sp->WatchpointRead(); 3229 bool write = wp_sp->WatchpointWrite() || wp_sp->WatchpointModify(); 3230 size_t size = wp_sp->GetByteSize(); 3231 3232 ArchSpec target_arch = GetTarget().GetArchitecture(); 3233 WatchpointHardwareFeature supported_features = 3234 m_gdb_comm.GetSupportedWatchpointTypes(); 3235 3236 std::vector<WatchpointResourceSP> resources = 3237 WatchpointAlgorithms::AtomizeWatchpointRequest( 3238 addr, size, read, write, supported_features, target_arch); 3239 3240 // LWP_TODO: Now that we know the WP Resources needed to implement this 3241 // Watchpoint, we need to look at currently allocated Resources in the 3242 // Process and if they match, or are within the same memory granule, or 3243 // overlapping memory ranges, then we need to combine them. e.g. one 3244 // Watchpoint watching 1 byte at 0x1002 and a second watchpoint watching 1 3245 // byte at 0x1003, they must use the same hardware watchpoint register 3246 // (Resource) to watch them. 3247 3248 // This may mean that an existing resource changes its type (read to 3249 // read+write) or address range it is watching, in which case the old 3250 // watchpoint needs to be disabled and the new Resource addr/size/type 3251 // watchpoint enabled. 3252 3253 // If we modify a shared Resource to accomodate this newly added Watchpoint, 3254 // and we are unable to set all of the Resources for it in the inferior, we 3255 // will return an error for this Watchpoint and the shared Resource should 3256 // be restored. e.g. this Watchpoint requires three Resources, one which 3257 // is shared with another Watchpoint. We extend the shared Resouce to 3258 // handle both Watchpoints and we try to set two new ones. But if we don't 3259 // have sufficient watchpoint register for all 3, we need to show an error 3260 // for creating this Watchpoint and we should reset the shared Resource to 3261 // its original configuration because it is no longer shared. 3262 3263 bool set_all_resources = true; 3264 std::vector<WatchpointResourceSP> succesfully_set_resources; 3265 for (const auto &wp_res_sp : resources) { 3266 addr_t addr = wp_res_sp->GetLoadAddress(); 3267 size_t size = wp_res_sp->GetByteSize(); 3268 GDBStoppointType type = GetGDBStoppointType(wp_res_sp); 3269 if (!m_gdb_comm.SupportsGDBStoppointPacket(type) || 3270 m_gdb_comm.SendGDBStoppointTypePacket(type, true, addr, size, 3271 GetInterruptTimeout())) { 3272 set_all_resources = false; 3273 break; 3274 } else { 3275 succesfully_set_resources.push_back(wp_res_sp); 3276 } 3277 } 3278 if (set_all_resources) { 3279 wp_sp->SetEnabled(true, notify); 3280 for (const auto &wp_res_sp : resources) { 3281 // LWP_TODO: If we expanded/reused an existing Resource, 3282 // it's already in the WatchpointResourceList. 3283 wp_res_sp->AddConstituent(wp_sp); 3284 m_watchpoint_resource_list.Add(wp_res_sp); 3285 } 3286 return error; 3287 } else { 3288 // We failed to allocate one of the resources. Unset all 3289 // of the new resources we did successfully set in the 3290 // process. 3291 for (const auto &wp_res_sp : succesfully_set_resources) { 3292 addr_t addr = wp_res_sp->GetLoadAddress(); 3293 size_t size = wp_res_sp->GetByteSize(); 3294 GDBStoppointType type = GetGDBStoppointType(wp_res_sp); 3295 m_gdb_comm.SendGDBStoppointTypePacket(type, false, addr, size, 3296 GetInterruptTimeout()); 3297 } 3298 error = Status::FromErrorString( 3299 "Setting one of the watchpoint resources failed"); 3300 } 3301 return error; 3302 } 3303 3304 Status ProcessGDBRemote::DisableWatchpoint(WatchpointSP wp_sp, bool notify) { 3305 Status error; 3306 if (!wp_sp) { 3307 error = Status::FromErrorString("Watchpoint argument was NULL."); 3308 return error; 3309 } 3310 3311 user_id_t watchID = wp_sp->GetID(); 3312 3313 Log *log(GetLog(GDBRLog::Watchpoints)); 3314 3315 addr_t addr = wp_sp->GetLoadAddress(); 3316 3317 LLDB_LOGF(log, 3318 "ProcessGDBRemote::DisableWatchpoint (watchID = %" PRIu64 3319 ") addr = 0x%8.8" PRIx64, 3320 watchID, (uint64_t)addr); 3321 3322 if (!wp_sp->IsEnabled()) { 3323 LLDB_LOGF(log, 3324 "ProcessGDBRemote::DisableWatchpoint (watchID = %" PRIu64 3325 ") addr = 0x%8.8" PRIx64 " -- SUCCESS (already disabled)", 3326 watchID, (uint64_t)addr); 3327 // See also 'class WatchpointSentry' within StopInfo.cpp. This disabling 3328 // attempt might come from the user-supplied actions, we'll route it in 3329 // order for the watchpoint object to intelligently process this action. 3330 wp_sp->SetEnabled(false, notify); 3331 return error; 3332 } 3333 3334 if (wp_sp->IsHardware()) { 3335 bool disabled_all = true; 3336 3337 std::vector<WatchpointResourceSP> unused_resources; 3338 for (const auto &wp_res_sp : m_watchpoint_resource_list.Sites()) { 3339 if (wp_res_sp->ConstituentsContains(wp_sp)) { 3340 GDBStoppointType type = GetGDBStoppointType(wp_res_sp); 3341 addr_t addr = wp_res_sp->GetLoadAddress(); 3342 size_t size = wp_res_sp->GetByteSize(); 3343 if (m_gdb_comm.SendGDBStoppointTypePacket(type, false, addr, size, 3344 GetInterruptTimeout())) { 3345 disabled_all = false; 3346 } else { 3347 wp_res_sp->RemoveConstituent(wp_sp); 3348 if (wp_res_sp->GetNumberOfConstituents() == 0) 3349 unused_resources.push_back(wp_res_sp); 3350 } 3351 } 3352 } 3353 for (auto &wp_res_sp : unused_resources) 3354 m_watchpoint_resource_list.Remove(wp_res_sp->GetID()); 3355 3356 wp_sp->SetEnabled(false, notify); 3357 if (!disabled_all) 3358 error = Status::FromErrorString( 3359 "Failure disabling one of the watchpoint locations"); 3360 } 3361 return error; 3362 } 3363 3364 void ProcessGDBRemote::Clear() { 3365 m_thread_list_real.Clear(); 3366 m_thread_list.Clear(); 3367 } 3368 3369 Status ProcessGDBRemote::DoSignal(int signo) { 3370 Status error; 3371 Log *log = GetLog(GDBRLog::Process); 3372 LLDB_LOGF(log, "ProcessGDBRemote::DoSignal (signal = %d)", signo); 3373 3374 if (!m_gdb_comm.SendAsyncSignal(signo, GetInterruptTimeout())) 3375 error = 3376 Status::FromErrorStringWithFormat("failed to send signal %i", signo); 3377 return error; 3378 } 3379 3380 Status 3381 ProcessGDBRemote::EstablishConnectionIfNeeded(const ProcessInfo &process_info) { 3382 // Make sure we aren't already connected? 3383 if (m_gdb_comm.IsConnected()) 3384 return Status(); 3385 3386 PlatformSP platform_sp(GetTarget().GetPlatform()); 3387 if (platform_sp && !platform_sp->IsHost()) 3388 return Status::FromErrorString("Lost debug server connection"); 3389 3390 auto error = LaunchAndConnectToDebugserver(process_info); 3391 if (error.Fail()) { 3392 const char *error_string = error.AsCString(); 3393 if (error_string == nullptr) 3394 error_string = "unable to launch " DEBUGSERVER_BASENAME; 3395 } 3396 return error; 3397 } 3398 #if !defined(_WIN32) 3399 #define USE_SOCKETPAIR_FOR_LOCAL_CONNECTION 1 3400 #endif 3401 3402 #ifdef USE_SOCKETPAIR_FOR_LOCAL_CONNECTION 3403 static bool SetCloexecFlag(int fd) { 3404 #if defined(FD_CLOEXEC) 3405 int flags = ::fcntl(fd, F_GETFD); 3406 if (flags == -1) 3407 return false; 3408 return (::fcntl(fd, F_SETFD, flags | FD_CLOEXEC) == 0); 3409 #else 3410 return false; 3411 #endif 3412 } 3413 #endif 3414 3415 Status ProcessGDBRemote::LaunchAndConnectToDebugserver( 3416 const ProcessInfo &process_info) { 3417 using namespace std::placeholders; // For _1, _2, etc. 3418 3419 Status error; 3420 if (m_debugserver_pid == LLDB_INVALID_PROCESS_ID) { 3421 // If we locate debugserver, keep that located version around 3422 static FileSpec g_debugserver_file_spec; 3423 3424 ProcessLaunchInfo debugserver_launch_info; 3425 // Make debugserver run in its own session so signals generated by special 3426 // terminal key sequences (^C) don't affect debugserver. 3427 debugserver_launch_info.SetLaunchInSeparateProcessGroup(true); 3428 3429 const std::weak_ptr<ProcessGDBRemote> this_wp = 3430 std::static_pointer_cast<ProcessGDBRemote>(shared_from_this()); 3431 debugserver_launch_info.SetMonitorProcessCallback( 3432 std::bind(MonitorDebugserverProcess, this_wp, _1, _2, _3)); 3433 debugserver_launch_info.SetUserID(process_info.GetUserID()); 3434 3435 #if defined(__APPLE__) 3436 // On macOS 11, we need to support x86_64 applications translated to 3437 // arm64. We check whether a binary is translated and spawn the correct 3438 // debugserver accordingly. 3439 int mib[] = { CTL_KERN, KERN_PROC, KERN_PROC_PID, 3440 static_cast<int>(process_info.GetProcessID()) }; 3441 struct kinfo_proc processInfo; 3442 size_t bufsize = sizeof(processInfo); 3443 if (sysctl(mib, (unsigned)(sizeof(mib)/sizeof(int)), &processInfo, 3444 &bufsize, NULL, 0) == 0 && bufsize > 0) { 3445 if (processInfo.kp_proc.p_flag & P_TRANSLATED) { 3446 FileSpec rosetta_debugserver("/Library/Apple/usr/libexec/oah/debugserver"); 3447 debugserver_launch_info.SetExecutableFile(rosetta_debugserver, false); 3448 } 3449 } 3450 #endif 3451 3452 shared_fd_t communication_fd = SharedSocket::kInvalidFD; 3453 #ifdef USE_SOCKETPAIR_FOR_LOCAL_CONNECTION 3454 // Use a socketpair on non-Windows systems for security and performance 3455 // reasons. 3456 int sockets[2]; /* the pair of socket descriptors */ 3457 if (socketpair(AF_UNIX, SOCK_STREAM, 0, sockets) == -1) { 3458 error = Status::FromErrno(); 3459 return error; 3460 } 3461 3462 int our_socket = sockets[0]; 3463 int gdb_socket = sockets[1]; 3464 auto cleanup_our = llvm::make_scope_exit([&]() { close(our_socket); }); 3465 auto cleanup_gdb = llvm::make_scope_exit([&]() { close(gdb_socket); }); 3466 3467 // Don't let any child processes inherit our communication socket 3468 SetCloexecFlag(our_socket); 3469 communication_fd = gdb_socket; 3470 #endif 3471 3472 error = m_gdb_comm.StartDebugserverProcess( 3473 nullptr, GetTarget().GetPlatform().get(), debugserver_launch_info, 3474 nullptr, nullptr, communication_fd); 3475 3476 if (error.Success()) 3477 m_debugserver_pid = debugserver_launch_info.GetProcessID(); 3478 else 3479 m_debugserver_pid = LLDB_INVALID_PROCESS_ID; 3480 3481 if (m_debugserver_pid != LLDB_INVALID_PROCESS_ID) { 3482 #ifdef USE_SOCKETPAIR_FOR_LOCAL_CONNECTION 3483 // Our process spawned correctly, we can now set our connection to use 3484 // our end of the socket pair 3485 cleanup_our.release(); 3486 m_gdb_comm.SetConnection( 3487 std::make_unique<ConnectionFileDescriptor>(our_socket, true)); 3488 #endif 3489 StartAsyncThread(); 3490 } 3491 3492 if (error.Fail()) { 3493 Log *log = GetLog(GDBRLog::Process); 3494 3495 LLDB_LOGF(log, "failed to start debugserver process: %s", 3496 error.AsCString()); 3497 return error; 3498 } 3499 3500 if (m_gdb_comm.IsConnected()) { 3501 // Finish the connection process by doing the handshake without 3502 // connecting (send NULL URL) 3503 error = ConnectToDebugserver(""); 3504 } else { 3505 error = Status::FromErrorString("connection failed"); 3506 } 3507 } 3508 return error; 3509 } 3510 3511 void ProcessGDBRemote::MonitorDebugserverProcess( 3512 std::weak_ptr<ProcessGDBRemote> process_wp, lldb::pid_t debugserver_pid, 3513 int signo, // Zero for no signal 3514 int exit_status // Exit value of process if signal is zero 3515 ) { 3516 // "debugserver_pid" argument passed in is the process ID for debugserver 3517 // that we are tracking... 3518 Log *log = GetLog(GDBRLog::Process); 3519 3520 LLDB_LOGF(log, 3521 "ProcessGDBRemote::%s(process_wp, pid=%" PRIu64 3522 ", signo=%i (0x%x), exit_status=%i)", 3523 __FUNCTION__, debugserver_pid, signo, signo, exit_status); 3524 3525 std::shared_ptr<ProcessGDBRemote> process_sp = process_wp.lock(); 3526 LLDB_LOGF(log, "ProcessGDBRemote::%s(process = %p)", __FUNCTION__, 3527 static_cast<void *>(process_sp.get())); 3528 if (!process_sp || process_sp->m_debugserver_pid != debugserver_pid) 3529 return; 3530 3531 // Sleep for a half a second to make sure our inferior process has time to 3532 // set its exit status before we set it incorrectly when both the debugserver 3533 // and the inferior process shut down. 3534 std::this_thread::sleep_for(std::chrono::milliseconds(500)); 3535 3536 // If our process hasn't yet exited, debugserver might have died. If the 3537 // process did exit, then we are reaping it. 3538 const StateType state = process_sp->GetState(); 3539 3540 if (state != eStateInvalid && state != eStateUnloaded && 3541 state != eStateExited && state != eStateDetached) { 3542 StreamString stream; 3543 if (signo == 0) 3544 stream.Format(DEBUGSERVER_BASENAME " died with an exit status of {0:x8}", 3545 exit_status); 3546 else { 3547 llvm::StringRef signal_name = 3548 process_sp->GetUnixSignals()->GetSignalAsStringRef(signo); 3549 const char *format_str = DEBUGSERVER_BASENAME " died with signal {0}"; 3550 if (!signal_name.empty()) 3551 stream.Format(format_str, signal_name); 3552 else 3553 stream.Format(format_str, signo); 3554 } 3555 process_sp->SetExitStatus(-1, stream.GetString()); 3556 } 3557 // Debugserver has exited we need to let our ProcessGDBRemote know that it no 3558 // longer has a debugserver instance 3559 process_sp->m_debugserver_pid = LLDB_INVALID_PROCESS_ID; 3560 } 3561 3562 void ProcessGDBRemote::KillDebugserverProcess() { 3563 m_gdb_comm.Disconnect(); 3564 if (m_debugserver_pid != LLDB_INVALID_PROCESS_ID) { 3565 Host::Kill(m_debugserver_pid, SIGINT); 3566 m_debugserver_pid = LLDB_INVALID_PROCESS_ID; 3567 } 3568 } 3569 3570 void ProcessGDBRemote::Initialize() { 3571 static llvm::once_flag g_once_flag; 3572 3573 llvm::call_once(g_once_flag, []() { 3574 PluginManager::RegisterPlugin(GetPluginNameStatic(), 3575 GetPluginDescriptionStatic(), CreateInstance, 3576 DebuggerInitialize); 3577 }); 3578 } 3579 3580 void ProcessGDBRemote::DebuggerInitialize(Debugger &debugger) { 3581 if (!PluginManager::GetSettingForProcessPlugin( 3582 debugger, PluginProperties::GetSettingName())) { 3583 const bool is_global_setting = true; 3584 PluginManager::CreateSettingForProcessPlugin( 3585 debugger, GetGlobalPluginProperties().GetValueProperties(), 3586 "Properties for the gdb-remote process plug-in.", is_global_setting); 3587 } 3588 } 3589 3590 bool ProcessGDBRemote::StartAsyncThread() { 3591 Log *log = GetLog(GDBRLog::Process); 3592 3593 LLDB_LOGF(log, "ProcessGDBRemote::%s ()", __FUNCTION__); 3594 3595 std::lock_guard<std::recursive_mutex> guard(m_async_thread_state_mutex); 3596 if (!m_async_thread.IsJoinable()) { 3597 // Create a thread that watches our internal state and controls which 3598 // events make it to clients (into the DCProcess event queue). 3599 3600 llvm::Expected<HostThread> async_thread = 3601 ThreadLauncher::LaunchThread("<lldb.process.gdb-remote.async>", [this] { 3602 return ProcessGDBRemote::AsyncThread(); 3603 }); 3604 if (!async_thread) { 3605 LLDB_LOG_ERROR(GetLog(LLDBLog::Host), async_thread.takeError(), 3606 "failed to launch host thread: {0}"); 3607 return false; 3608 } 3609 m_async_thread = *async_thread; 3610 } else 3611 LLDB_LOGF(log, 3612 "ProcessGDBRemote::%s () - Called when Async thread was " 3613 "already running.", 3614 __FUNCTION__); 3615 3616 return m_async_thread.IsJoinable(); 3617 } 3618 3619 void ProcessGDBRemote::StopAsyncThread() { 3620 Log *log = GetLog(GDBRLog::Process); 3621 3622 LLDB_LOGF(log, "ProcessGDBRemote::%s ()", __FUNCTION__); 3623 3624 std::lock_guard<std::recursive_mutex> guard(m_async_thread_state_mutex); 3625 if (m_async_thread.IsJoinable()) { 3626 m_async_broadcaster.BroadcastEvent(eBroadcastBitAsyncThreadShouldExit); 3627 3628 // This will shut down the async thread. 3629 m_gdb_comm.Disconnect(); // Disconnect from the debug server. 3630 3631 // Stop the stdio thread 3632 m_async_thread.Join(nullptr); 3633 m_async_thread.Reset(); 3634 } else 3635 LLDB_LOGF( 3636 log, 3637 "ProcessGDBRemote::%s () - Called when Async thread was not running.", 3638 __FUNCTION__); 3639 } 3640 3641 thread_result_t ProcessGDBRemote::AsyncThread() { 3642 Log *log = GetLog(GDBRLog::Process); 3643 LLDB_LOGF(log, "ProcessGDBRemote::%s(pid = %" PRIu64 ") thread starting...", 3644 __FUNCTION__, GetID()); 3645 3646 EventSP event_sp; 3647 3648 // We need to ignore any packets that come in after we have 3649 // have decided the process has exited. There are some 3650 // situations, for instance when we try to interrupt a running 3651 // process and the interrupt fails, where another packet might 3652 // get delivered after we've decided to give up on the process. 3653 // But once we've decided we are done with the process we will 3654 // not be in a state to do anything useful with new packets. 3655 // So it is safer to simply ignore any remaining packets by 3656 // explicitly checking for eStateExited before reentering the 3657 // fetch loop. 3658 3659 bool done = false; 3660 while (!done && GetPrivateState() != eStateExited) { 3661 LLDB_LOGF(log, 3662 "ProcessGDBRemote::%s(pid = %" PRIu64 3663 ") listener.WaitForEvent (NULL, event_sp)...", 3664 __FUNCTION__, GetID()); 3665 3666 if (m_async_listener_sp->GetEvent(event_sp, std::nullopt)) { 3667 const uint32_t event_type = event_sp->GetType(); 3668 if (event_sp->BroadcasterIs(&m_async_broadcaster)) { 3669 LLDB_LOGF(log, 3670 "ProcessGDBRemote::%s(pid = %" PRIu64 3671 ") Got an event of type: %d...", 3672 __FUNCTION__, GetID(), event_type); 3673 3674 switch (event_type) { 3675 case eBroadcastBitAsyncContinue: { 3676 const EventDataBytes *continue_packet = 3677 EventDataBytes::GetEventDataFromEvent(event_sp.get()); 3678 3679 if (continue_packet) { 3680 const char *continue_cstr = 3681 (const char *)continue_packet->GetBytes(); 3682 const size_t continue_cstr_len = continue_packet->GetByteSize(); 3683 LLDB_LOGF(log, 3684 "ProcessGDBRemote::%s(pid = %" PRIu64 3685 ") got eBroadcastBitAsyncContinue: %s", 3686 __FUNCTION__, GetID(), continue_cstr); 3687 3688 if (::strstr(continue_cstr, "vAttach") == nullptr) 3689 SetPrivateState(eStateRunning); 3690 StringExtractorGDBRemote response; 3691 3692 StateType stop_state = 3693 GetGDBRemote().SendContinuePacketAndWaitForResponse( 3694 *this, *GetUnixSignals(), 3695 llvm::StringRef(continue_cstr, continue_cstr_len), 3696 GetInterruptTimeout(), response); 3697 3698 // We need to immediately clear the thread ID list so we are sure 3699 // to get a valid list of threads. The thread ID list might be 3700 // contained within the "response", or the stop reply packet that 3701 // caused the stop. So clear it now before we give the stop reply 3702 // packet to the process using the 3703 // SetLastStopPacket()... 3704 ClearThreadIDList(); 3705 3706 switch (stop_state) { 3707 case eStateStopped: 3708 case eStateCrashed: 3709 case eStateSuspended: 3710 SetLastStopPacket(response); 3711 SetPrivateState(stop_state); 3712 break; 3713 3714 case eStateExited: { 3715 SetLastStopPacket(response); 3716 ClearThreadIDList(); 3717 response.SetFilePos(1); 3718 3719 int exit_status = response.GetHexU8(); 3720 std::string desc_string; 3721 if (response.GetBytesLeft() > 0 && response.GetChar('-') == ';') { 3722 llvm::StringRef desc_str; 3723 llvm::StringRef desc_token; 3724 while (response.GetNameColonValue(desc_token, desc_str)) { 3725 if (desc_token != "description") 3726 continue; 3727 StringExtractor extractor(desc_str); 3728 extractor.GetHexByteString(desc_string); 3729 } 3730 } 3731 SetExitStatus(exit_status, desc_string.c_str()); 3732 done = true; 3733 break; 3734 } 3735 case eStateInvalid: { 3736 // Check to see if we were trying to attach and if we got back 3737 // the "E87" error code from debugserver -- this indicates that 3738 // the process is not debuggable. Return a slightly more 3739 // helpful error message about why the attach failed. 3740 if (::strstr(continue_cstr, "vAttach") != nullptr && 3741 response.GetError() == 0x87) { 3742 SetExitStatus(-1, "cannot attach to process due to " 3743 "System Integrity Protection"); 3744 } else if (::strstr(continue_cstr, "vAttach") != nullptr && 3745 response.GetStatus().Fail()) { 3746 SetExitStatus(-1, response.GetStatus().AsCString()); 3747 } else { 3748 SetExitStatus(-1, "lost connection"); 3749 } 3750 done = true; 3751 break; 3752 } 3753 3754 default: 3755 SetPrivateState(stop_state); 3756 break; 3757 } // switch(stop_state) 3758 } // if (continue_packet) 3759 } // case eBroadcastBitAsyncContinue 3760 break; 3761 3762 case eBroadcastBitAsyncThreadShouldExit: 3763 LLDB_LOGF(log, 3764 "ProcessGDBRemote::%s(pid = %" PRIu64 3765 ") got eBroadcastBitAsyncThreadShouldExit...", 3766 __FUNCTION__, GetID()); 3767 done = true; 3768 break; 3769 3770 default: 3771 LLDB_LOGF(log, 3772 "ProcessGDBRemote::%s(pid = %" PRIu64 3773 ") got unknown event 0x%8.8x", 3774 __FUNCTION__, GetID(), event_type); 3775 done = true; 3776 break; 3777 } 3778 } 3779 } else { 3780 LLDB_LOGF(log, 3781 "ProcessGDBRemote::%s(pid = %" PRIu64 3782 ") listener.WaitForEvent (NULL, event_sp) => false", 3783 __FUNCTION__, GetID()); 3784 done = true; 3785 } 3786 } 3787 3788 LLDB_LOGF(log, "ProcessGDBRemote::%s(pid = %" PRIu64 ") thread exiting...", 3789 __FUNCTION__, GetID()); 3790 3791 return {}; 3792 } 3793 3794 // uint32_t 3795 // ProcessGDBRemote::ListProcessesMatchingName (const char *name, StringList 3796 // &matches, std::vector<lldb::pid_t> &pids) 3797 //{ 3798 // // If we are planning to launch the debugserver remotely, then we need to 3799 // fire up a debugserver 3800 // // process and ask it for the list of processes. But if we are local, we 3801 // can let the Host do it. 3802 // if (m_local_debugserver) 3803 // { 3804 // return Host::ListProcessesMatchingName (name, matches, pids); 3805 // } 3806 // else 3807 // { 3808 // // FIXME: Implement talking to the remote debugserver. 3809 // return 0; 3810 // } 3811 // 3812 //} 3813 // 3814 bool ProcessGDBRemote::NewThreadNotifyBreakpointHit( 3815 void *baton, StoppointCallbackContext *context, lldb::user_id_t break_id, 3816 lldb::user_id_t break_loc_id) { 3817 // I don't think I have to do anything here, just make sure I notice the new 3818 // thread when it starts to 3819 // run so I can stop it if that's what I want to do. 3820 Log *log = GetLog(LLDBLog::Step); 3821 LLDB_LOGF(log, "Hit New Thread Notification breakpoint."); 3822 return false; 3823 } 3824 3825 Status ProcessGDBRemote::UpdateAutomaticSignalFiltering() { 3826 Log *log = GetLog(GDBRLog::Process); 3827 LLDB_LOG(log, "Check if need to update ignored signals"); 3828 3829 // QPassSignals package is not supported by the server, there is no way we 3830 // can ignore any signals on server side. 3831 if (!m_gdb_comm.GetQPassSignalsSupported()) 3832 return Status(); 3833 3834 // No signals, nothing to send. 3835 if (m_unix_signals_sp == nullptr) 3836 return Status(); 3837 3838 // Signals' version hasn't changed, no need to send anything. 3839 uint64_t new_signals_version = m_unix_signals_sp->GetVersion(); 3840 if (new_signals_version == m_last_signals_version) { 3841 LLDB_LOG(log, "Signals' version hasn't changed. version={0}", 3842 m_last_signals_version); 3843 return Status(); 3844 } 3845 3846 auto signals_to_ignore = 3847 m_unix_signals_sp->GetFilteredSignals(false, false, false); 3848 Status error = m_gdb_comm.SendSignalsToIgnore(signals_to_ignore); 3849 3850 LLDB_LOG(log, 3851 "Signals' version changed. old version={0}, new version={1}, " 3852 "signals ignored={2}, update result={3}", 3853 m_last_signals_version, new_signals_version, 3854 signals_to_ignore.size(), error); 3855 3856 if (error.Success()) 3857 m_last_signals_version = new_signals_version; 3858 3859 return error; 3860 } 3861 3862 bool ProcessGDBRemote::StartNoticingNewThreads() { 3863 Log *log = GetLog(LLDBLog::Step); 3864 if (m_thread_create_bp_sp) { 3865 if (log && log->GetVerbose()) 3866 LLDB_LOGF(log, "Enabled noticing new thread breakpoint."); 3867 m_thread_create_bp_sp->SetEnabled(true); 3868 } else { 3869 PlatformSP platform_sp(GetTarget().GetPlatform()); 3870 if (platform_sp) { 3871 m_thread_create_bp_sp = 3872 platform_sp->SetThreadCreationBreakpoint(GetTarget()); 3873 if (m_thread_create_bp_sp) { 3874 if (log && log->GetVerbose()) 3875 LLDB_LOGF( 3876 log, "Successfully created new thread notification breakpoint %i", 3877 m_thread_create_bp_sp->GetID()); 3878 m_thread_create_bp_sp->SetCallback( 3879 ProcessGDBRemote::NewThreadNotifyBreakpointHit, this, true); 3880 } else { 3881 LLDB_LOGF(log, "Failed to create new thread notification breakpoint."); 3882 } 3883 } 3884 } 3885 return m_thread_create_bp_sp.get() != nullptr; 3886 } 3887 3888 bool ProcessGDBRemote::StopNoticingNewThreads() { 3889 Log *log = GetLog(LLDBLog::Step); 3890 if (log && log->GetVerbose()) 3891 LLDB_LOGF(log, "Disabling new thread notification breakpoint."); 3892 3893 if (m_thread_create_bp_sp) 3894 m_thread_create_bp_sp->SetEnabled(false); 3895 3896 return true; 3897 } 3898 3899 DynamicLoader *ProcessGDBRemote::GetDynamicLoader() { 3900 if (m_dyld_up.get() == nullptr) 3901 m_dyld_up.reset(DynamicLoader::FindPlugin(this, "")); 3902 return m_dyld_up.get(); 3903 } 3904 3905 Status ProcessGDBRemote::SendEventData(const char *data) { 3906 int return_value; 3907 bool was_supported; 3908 3909 Status error; 3910 3911 return_value = m_gdb_comm.SendLaunchEventDataPacket(data, &was_supported); 3912 if (return_value != 0) { 3913 if (!was_supported) 3914 error = Status::FromErrorString( 3915 "Sending events is not supported for this process."); 3916 else 3917 error = Status::FromErrorStringWithFormat("Error sending event data: %d.", 3918 return_value); 3919 } 3920 return error; 3921 } 3922 3923 DataExtractor ProcessGDBRemote::GetAuxvData() { 3924 DataBufferSP buf; 3925 if (m_gdb_comm.GetQXferAuxvReadSupported()) { 3926 llvm::Expected<std::string> response = m_gdb_comm.ReadExtFeature("auxv", ""); 3927 if (response) 3928 buf = std::make_shared<DataBufferHeap>(response->c_str(), 3929 response->length()); 3930 else 3931 LLDB_LOG_ERROR(GetLog(GDBRLog::Process), response.takeError(), "{0}"); 3932 } 3933 return DataExtractor(buf, GetByteOrder(), GetAddressByteSize()); 3934 } 3935 3936 StructuredData::ObjectSP 3937 ProcessGDBRemote::GetExtendedInfoForThread(lldb::tid_t tid) { 3938 StructuredData::ObjectSP object_sp; 3939 3940 if (m_gdb_comm.GetThreadExtendedInfoSupported()) { 3941 StructuredData::ObjectSP args_dict(new StructuredData::Dictionary()); 3942 SystemRuntime *runtime = GetSystemRuntime(); 3943 if (runtime) { 3944 runtime->AddThreadExtendedInfoPacketHints(args_dict); 3945 } 3946 args_dict->GetAsDictionary()->AddIntegerItem("thread", tid); 3947 3948 StreamString packet; 3949 packet << "jThreadExtendedInfo:"; 3950 args_dict->Dump(packet, false); 3951 3952 // FIXME the final character of a JSON dictionary, '}', is the escape 3953 // character in gdb-remote binary mode. lldb currently doesn't escape 3954 // these characters in its packet output -- so we add the quoted version of 3955 // the } character here manually in case we talk to a debugserver which un- 3956 // escapes the characters at packet read time. 3957 packet << (char)(0x7d ^ 0x20); 3958 3959 StringExtractorGDBRemote response; 3960 response.SetResponseValidatorToJSON(); 3961 if (m_gdb_comm.SendPacketAndWaitForResponse(packet.GetString(), response) == 3962 GDBRemoteCommunication::PacketResult::Success) { 3963 StringExtractorGDBRemote::ResponseType response_type = 3964 response.GetResponseType(); 3965 if (response_type == StringExtractorGDBRemote::eResponse) { 3966 if (!response.Empty()) { 3967 object_sp = StructuredData::ParseJSON(response.GetStringRef()); 3968 } 3969 } 3970 } 3971 } 3972 return object_sp; 3973 } 3974 3975 StructuredData::ObjectSP ProcessGDBRemote::GetLoadedDynamicLibrariesInfos( 3976 lldb::addr_t image_list_address, lldb::addr_t image_count) { 3977 3978 StructuredData::ObjectSP args_dict(new StructuredData::Dictionary()); 3979 args_dict->GetAsDictionary()->AddIntegerItem("image_list_address", 3980 image_list_address); 3981 args_dict->GetAsDictionary()->AddIntegerItem("image_count", image_count); 3982 3983 return GetLoadedDynamicLibrariesInfos_sender(args_dict); 3984 } 3985 3986 StructuredData::ObjectSP ProcessGDBRemote::GetLoadedDynamicLibrariesInfos() { 3987 StructuredData::ObjectSP args_dict(new StructuredData::Dictionary()); 3988 3989 args_dict->GetAsDictionary()->AddBooleanItem("fetch_all_solibs", true); 3990 3991 return GetLoadedDynamicLibrariesInfos_sender(args_dict); 3992 } 3993 3994 StructuredData::ObjectSP ProcessGDBRemote::GetLoadedDynamicLibrariesInfos( 3995 const std::vector<lldb::addr_t> &load_addresses) { 3996 StructuredData::ObjectSP args_dict(new StructuredData::Dictionary()); 3997 StructuredData::ArraySP addresses(new StructuredData::Array); 3998 3999 for (auto addr : load_addresses) 4000 addresses->AddIntegerItem(addr); 4001 4002 args_dict->GetAsDictionary()->AddItem("solib_addresses", addresses); 4003 4004 return GetLoadedDynamicLibrariesInfos_sender(args_dict); 4005 } 4006 4007 StructuredData::ObjectSP 4008 ProcessGDBRemote::GetLoadedDynamicLibrariesInfos_sender( 4009 StructuredData::ObjectSP args_dict) { 4010 StructuredData::ObjectSP object_sp; 4011 4012 if (m_gdb_comm.GetLoadedDynamicLibrariesInfosSupported()) { 4013 // Scope for the scoped timeout object 4014 GDBRemoteCommunication::ScopedTimeout timeout(m_gdb_comm, 4015 std::chrono::seconds(10)); 4016 4017 StreamString packet; 4018 packet << "jGetLoadedDynamicLibrariesInfos:"; 4019 args_dict->Dump(packet, false); 4020 4021 // FIXME the final character of a JSON dictionary, '}', is the escape 4022 // character in gdb-remote binary mode. lldb currently doesn't escape 4023 // these characters in its packet output -- so we add the quoted version of 4024 // the } character here manually in case we talk to a debugserver which un- 4025 // escapes the characters at packet read time. 4026 packet << (char)(0x7d ^ 0x20); 4027 4028 StringExtractorGDBRemote response; 4029 response.SetResponseValidatorToJSON(); 4030 if (m_gdb_comm.SendPacketAndWaitForResponse(packet.GetString(), response) == 4031 GDBRemoteCommunication::PacketResult::Success) { 4032 StringExtractorGDBRemote::ResponseType response_type = 4033 response.GetResponseType(); 4034 if (response_type == StringExtractorGDBRemote::eResponse) { 4035 if (!response.Empty()) { 4036 object_sp = StructuredData::ParseJSON(response.GetStringRef()); 4037 } 4038 } 4039 } 4040 } 4041 return object_sp; 4042 } 4043 4044 StructuredData::ObjectSP ProcessGDBRemote::GetDynamicLoaderProcessState() { 4045 StructuredData::ObjectSP object_sp; 4046 StructuredData::ObjectSP args_dict(new StructuredData::Dictionary()); 4047 4048 if (m_gdb_comm.GetDynamicLoaderProcessStateSupported()) { 4049 StringExtractorGDBRemote response; 4050 response.SetResponseValidatorToJSON(); 4051 if (m_gdb_comm.SendPacketAndWaitForResponse("jGetDyldProcessState", 4052 response) == 4053 GDBRemoteCommunication::PacketResult::Success) { 4054 StringExtractorGDBRemote::ResponseType response_type = 4055 response.GetResponseType(); 4056 if (response_type == StringExtractorGDBRemote::eResponse) { 4057 if (!response.Empty()) { 4058 object_sp = StructuredData::ParseJSON(response.GetStringRef()); 4059 } 4060 } 4061 } 4062 } 4063 return object_sp; 4064 } 4065 4066 StructuredData::ObjectSP ProcessGDBRemote::GetSharedCacheInfo() { 4067 StructuredData::ObjectSP object_sp; 4068 StructuredData::ObjectSP args_dict(new StructuredData::Dictionary()); 4069 4070 if (m_gdb_comm.GetSharedCacheInfoSupported()) { 4071 StreamString packet; 4072 packet << "jGetSharedCacheInfo:"; 4073 args_dict->Dump(packet, false); 4074 4075 // FIXME the final character of a JSON dictionary, '}', is the escape 4076 // character in gdb-remote binary mode. lldb currently doesn't escape 4077 // these characters in its packet output -- so we add the quoted version of 4078 // the } character here manually in case we talk to a debugserver which un- 4079 // escapes the characters at packet read time. 4080 packet << (char)(0x7d ^ 0x20); 4081 4082 StringExtractorGDBRemote response; 4083 response.SetResponseValidatorToJSON(); 4084 if (m_gdb_comm.SendPacketAndWaitForResponse(packet.GetString(), response) == 4085 GDBRemoteCommunication::PacketResult::Success) { 4086 StringExtractorGDBRemote::ResponseType response_type = 4087 response.GetResponseType(); 4088 if (response_type == StringExtractorGDBRemote::eResponse) { 4089 if (!response.Empty()) { 4090 object_sp = StructuredData::ParseJSON(response.GetStringRef()); 4091 } 4092 } 4093 } 4094 } 4095 return object_sp; 4096 } 4097 4098 Status ProcessGDBRemote::ConfigureStructuredData( 4099 llvm::StringRef type_name, const StructuredData::ObjectSP &config_sp) { 4100 return m_gdb_comm.ConfigureRemoteStructuredData(type_name, config_sp); 4101 } 4102 4103 // Establish the largest memory read/write payloads we should use. If the 4104 // remote stub has a max packet size, stay under that size. 4105 // 4106 // If the remote stub's max packet size is crazy large, use a reasonable 4107 // largeish default. 4108 // 4109 // If the remote stub doesn't advertise a max packet size, use a conservative 4110 // default. 4111 4112 void ProcessGDBRemote::GetMaxMemorySize() { 4113 const uint64_t reasonable_largeish_default = 128 * 1024; 4114 const uint64_t conservative_default = 512; 4115 4116 if (m_max_memory_size == 0) { 4117 uint64_t stub_max_size = m_gdb_comm.GetRemoteMaxPacketSize(); 4118 if (stub_max_size != UINT64_MAX && stub_max_size != 0) { 4119 // Save the stub's claimed maximum packet size 4120 m_remote_stub_max_memory_size = stub_max_size; 4121 4122 // Even if the stub says it can support ginormous packets, don't exceed 4123 // our reasonable largeish default packet size. 4124 if (stub_max_size > reasonable_largeish_default) { 4125 stub_max_size = reasonable_largeish_default; 4126 } 4127 4128 // Memory packet have other overheads too like Maddr,size:#NN Instead of 4129 // calculating the bytes taken by size and addr every time, we take a 4130 // maximum guess here. 4131 if (stub_max_size > 70) 4132 stub_max_size -= 32 + 32 + 6; 4133 else { 4134 // In unlikely scenario that max packet size is less then 70, we will 4135 // hope that data being written is small enough to fit. 4136 Log *log(GetLog(GDBRLog::Comm | GDBRLog::Memory)); 4137 if (log) 4138 log->Warning("Packet size is too small. " 4139 "LLDB may face problems while writing memory"); 4140 } 4141 4142 m_max_memory_size = stub_max_size; 4143 } else { 4144 m_max_memory_size = conservative_default; 4145 } 4146 } 4147 } 4148 4149 void ProcessGDBRemote::SetUserSpecifiedMaxMemoryTransferSize( 4150 uint64_t user_specified_max) { 4151 if (user_specified_max != 0) { 4152 GetMaxMemorySize(); 4153 4154 if (m_remote_stub_max_memory_size != 0) { 4155 if (m_remote_stub_max_memory_size < user_specified_max) { 4156 m_max_memory_size = m_remote_stub_max_memory_size; // user specified a 4157 // packet size too 4158 // big, go as big 4159 // as the remote stub says we can go. 4160 } else { 4161 m_max_memory_size = user_specified_max; // user's packet size is good 4162 } 4163 } else { 4164 m_max_memory_size = 4165 user_specified_max; // user's packet size is probably fine 4166 } 4167 } 4168 } 4169 4170 bool ProcessGDBRemote::GetModuleSpec(const FileSpec &module_file_spec, 4171 const ArchSpec &arch, 4172 ModuleSpec &module_spec) { 4173 Log *log = GetLog(LLDBLog::Platform); 4174 4175 const ModuleCacheKey key(module_file_spec.GetPath(), 4176 arch.GetTriple().getTriple()); 4177 auto cached = m_cached_module_specs.find(key); 4178 if (cached != m_cached_module_specs.end()) { 4179 module_spec = cached->second; 4180 return bool(module_spec); 4181 } 4182 4183 if (!m_gdb_comm.GetModuleInfo(module_file_spec, arch, module_spec)) { 4184 LLDB_LOGF(log, "ProcessGDBRemote::%s - failed to get module info for %s:%s", 4185 __FUNCTION__, module_file_spec.GetPath().c_str(), 4186 arch.GetTriple().getTriple().c_str()); 4187 return false; 4188 } 4189 4190 if (log) { 4191 StreamString stream; 4192 module_spec.Dump(stream); 4193 LLDB_LOGF(log, "ProcessGDBRemote::%s - got module info for (%s:%s) : %s", 4194 __FUNCTION__, module_file_spec.GetPath().c_str(), 4195 arch.GetTriple().getTriple().c_str(), stream.GetData()); 4196 } 4197 4198 m_cached_module_specs[key] = module_spec; 4199 return true; 4200 } 4201 4202 void ProcessGDBRemote::PrefetchModuleSpecs( 4203 llvm::ArrayRef<FileSpec> module_file_specs, const llvm::Triple &triple) { 4204 auto module_specs = m_gdb_comm.GetModulesInfo(module_file_specs, triple); 4205 if (module_specs) { 4206 for (const FileSpec &spec : module_file_specs) 4207 m_cached_module_specs[ModuleCacheKey(spec.GetPath(), 4208 triple.getTriple())] = ModuleSpec(); 4209 for (const ModuleSpec &spec : *module_specs) 4210 m_cached_module_specs[ModuleCacheKey(spec.GetFileSpec().GetPath(), 4211 triple.getTriple())] = spec; 4212 } 4213 } 4214 4215 llvm::VersionTuple ProcessGDBRemote::GetHostOSVersion() { 4216 return m_gdb_comm.GetOSVersion(); 4217 } 4218 4219 llvm::VersionTuple ProcessGDBRemote::GetHostMacCatalystVersion() { 4220 return m_gdb_comm.GetMacCatalystVersion(); 4221 } 4222 4223 namespace { 4224 4225 typedef std::vector<std::string> stringVec; 4226 4227 typedef std::vector<struct GdbServerRegisterInfo> GDBServerRegisterVec; 4228 struct RegisterSetInfo { 4229 ConstString name; 4230 }; 4231 4232 typedef std::map<uint32_t, RegisterSetInfo> RegisterSetMap; 4233 4234 struct GdbServerTargetInfo { 4235 std::string arch; 4236 std::string osabi; 4237 stringVec includes; 4238 RegisterSetMap reg_set_map; 4239 }; 4240 4241 static FieldEnum::Enumerators ParseEnumEvalues(const XMLNode &enum_node) { 4242 Log *log(GetLog(GDBRLog::Process)); 4243 // We will use the last instance of each value. Also we preserve the order 4244 // of declaration in the XML, as it may not be numerical. 4245 // For example, hardware may intially release with two states that softwware 4246 // can read from a register field: 4247 // 0 = startup, 1 = running 4248 // If in a future hardware release, the designers added a pre-startup state: 4249 // 0 = startup, 1 = running, 2 = pre-startup 4250 // Now it makes more sense to list them in this logical order as opposed to 4251 // numerical order: 4252 // 2 = pre-startup, 1 = startup, 0 = startup 4253 // This only matters for "register info" but let's trust what the server 4254 // chose regardless. 4255 std::map<uint64_t, FieldEnum::Enumerator> enumerators; 4256 4257 enum_node.ForEachChildElementWithName( 4258 "evalue", [&enumerators, &log](const XMLNode &enumerator_node) { 4259 std::optional<llvm::StringRef> name; 4260 std::optional<uint64_t> value; 4261 4262 enumerator_node.ForEachAttribute( 4263 [&name, &value, &log](const llvm::StringRef &attr_name, 4264 const llvm::StringRef &attr_value) { 4265 if (attr_name == "name") { 4266 if (attr_value.size()) 4267 name = attr_value; 4268 else 4269 LLDB_LOG(log, "ProcessGDBRemote::ParseEnumEvalues " 4270 "Ignoring empty name in evalue"); 4271 } else if (attr_name == "value") { 4272 uint64_t parsed_value = 0; 4273 if (llvm::to_integer(attr_value, parsed_value)) 4274 value = parsed_value; 4275 else 4276 LLDB_LOG(log, 4277 "ProcessGDBRemote::ParseEnumEvalues " 4278 "Invalid value \"{0}\" in " 4279 "evalue", 4280 attr_value.data()); 4281 } else 4282 LLDB_LOG(log, 4283 "ProcessGDBRemote::ParseEnumEvalues Ignoring " 4284 "unknown attribute " 4285 "\"{0}\" in evalue", 4286 attr_name.data()); 4287 4288 // Keep walking attributes. 4289 return true; 4290 }); 4291 4292 if (value && name) 4293 enumerators.insert_or_assign( 4294 *value, FieldEnum::Enumerator(*value, name->str())); 4295 4296 // Find all evalue elements. 4297 return true; 4298 }); 4299 4300 FieldEnum::Enumerators final_enumerators; 4301 for (auto [_, enumerator] : enumerators) 4302 final_enumerators.push_back(enumerator); 4303 4304 return final_enumerators; 4305 } 4306 4307 static void 4308 ParseEnums(XMLNode feature_node, 4309 llvm::StringMap<std::unique_ptr<FieldEnum>> ®isters_enum_types) { 4310 Log *log(GetLog(GDBRLog::Process)); 4311 4312 // The top level element is "<enum...". 4313 feature_node.ForEachChildElementWithName( 4314 "enum", [log, ®isters_enum_types](const XMLNode &enum_node) { 4315 std::string id; 4316 4317 enum_node.ForEachAttribute([&id](const llvm::StringRef &attr_name, 4318 const llvm::StringRef &attr_value) { 4319 if (attr_name == "id") 4320 id = attr_value; 4321 4322 // There is also a "size" attribute that is supposed to be the size in 4323 // bytes of the register this applies to. However: 4324 // * LLDB doesn't need this information. 4325 // * It is difficult to verify because you have to wait until the 4326 // enum is applied to a field. 4327 // 4328 // So we will emit this attribute in XML for GDB's sake, but will not 4329 // bother ingesting it. 4330 4331 // Walk all attributes. 4332 return true; 4333 }); 4334 4335 if (!id.empty()) { 4336 FieldEnum::Enumerators enumerators = ParseEnumEvalues(enum_node); 4337 if (!enumerators.empty()) { 4338 LLDB_LOG(log, 4339 "ProcessGDBRemote::ParseEnums Found enum type \"{0}\"", 4340 id); 4341 registers_enum_types.insert_or_assign( 4342 id, std::make_unique<FieldEnum>(id, enumerators)); 4343 } 4344 } 4345 4346 // Find all <enum> elements. 4347 return true; 4348 }); 4349 } 4350 4351 static std::vector<RegisterFlags::Field> ParseFlagsFields( 4352 XMLNode flags_node, unsigned size, 4353 const llvm::StringMap<std::unique_ptr<FieldEnum>> ®isters_enum_types) { 4354 Log *log(GetLog(GDBRLog::Process)); 4355 const unsigned max_start_bit = size * 8 - 1; 4356 4357 // Process the fields of this set of flags. 4358 std::vector<RegisterFlags::Field> fields; 4359 flags_node.ForEachChildElementWithName("field", [&fields, max_start_bit, &log, 4360 ®isters_enum_types]( 4361 const XMLNode 4362 &field_node) { 4363 std::optional<llvm::StringRef> name; 4364 std::optional<unsigned> start; 4365 std::optional<unsigned> end; 4366 std::optional<llvm::StringRef> type; 4367 4368 field_node.ForEachAttribute([&name, &start, &end, &type, max_start_bit, 4369 &log](const llvm::StringRef &attr_name, 4370 const llvm::StringRef &attr_value) { 4371 // Note that XML in general requires that each of these attributes only 4372 // appears once, so we don't have to handle that here. 4373 if (attr_name == "name") { 4374 LLDB_LOG( 4375 log, 4376 "ProcessGDBRemote::ParseFlagsFields Found field node name \"{0}\"", 4377 attr_value.data()); 4378 name = attr_value; 4379 } else if (attr_name == "start") { 4380 unsigned parsed_start = 0; 4381 if (llvm::to_integer(attr_value, parsed_start)) { 4382 if (parsed_start > max_start_bit) { 4383 LLDB_LOG(log, 4384 "ProcessGDBRemote::ParseFlagsFields Invalid start {0} in " 4385 "field node, " 4386 "cannot be > {1}", 4387 parsed_start, max_start_bit); 4388 } else 4389 start = parsed_start; 4390 } else { 4391 LLDB_LOG( 4392 log, 4393 "ProcessGDBRemote::ParseFlagsFields Invalid start \"{0}\" in " 4394 "field node", 4395 attr_value.data()); 4396 } 4397 } else if (attr_name == "end") { 4398 unsigned parsed_end = 0; 4399 if (llvm::to_integer(attr_value, parsed_end)) 4400 if (parsed_end > max_start_bit) { 4401 LLDB_LOG(log, 4402 "ProcessGDBRemote::ParseFlagsFields Invalid end {0} in " 4403 "field node, " 4404 "cannot be > {1}", 4405 parsed_end, max_start_bit); 4406 } else 4407 end = parsed_end; 4408 else { 4409 LLDB_LOG(log, 4410 "ProcessGDBRemote::ParseFlagsFields Invalid end \"{0}\" in " 4411 "field node", 4412 attr_value.data()); 4413 } 4414 } else if (attr_name == "type") { 4415 type = attr_value; 4416 } else { 4417 LLDB_LOG( 4418 log, 4419 "ProcessGDBRemote::ParseFlagsFields Ignoring unknown attribute " 4420 "\"{0}\" in field node", 4421 attr_name.data()); 4422 } 4423 4424 return true; // Walk all attributes of the field. 4425 }); 4426 4427 if (name && start && end) { 4428 if (*start > *end) 4429 LLDB_LOG( 4430 log, 4431 "ProcessGDBRemote::ParseFlagsFields Start {0} > end {1} in field " 4432 "\"{2}\", ignoring", 4433 *start, *end, name->data()); 4434 else { 4435 if (RegisterFlags::Field::GetSizeInBits(*start, *end) > 64) 4436 LLDB_LOG(log, 4437 "ProcessGDBRemote::ParseFlagsFields Ignoring field \"{2}\" " 4438 "that has " 4439 "size > 64 bits, this is not supported", 4440 name->data()); 4441 else { 4442 // A field's type may be set to the name of an enum type. 4443 const FieldEnum *enum_type = nullptr; 4444 if (type && !type->empty()) { 4445 auto found = registers_enum_types.find(*type); 4446 if (found != registers_enum_types.end()) { 4447 enum_type = found->second.get(); 4448 4449 // No enumerator can exceed the range of the field itself. 4450 uint64_t max_value = 4451 RegisterFlags::Field::GetMaxValue(*start, *end); 4452 for (const auto &enumerator : enum_type->GetEnumerators()) { 4453 if (enumerator.m_value > max_value) { 4454 enum_type = nullptr; 4455 LLDB_LOG( 4456 log, 4457 "ProcessGDBRemote::ParseFlagsFields In enum \"{0}\" " 4458 "evalue \"{1}\" with value {2} exceeds the maximum value " 4459 "of field \"{3}\" ({4}), ignoring enum", 4460 type->data(), enumerator.m_name, enumerator.m_value, 4461 name->data(), max_value); 4462 break; 4463 } 4464 } 4465 } else { 4466 LLDB_LOG(log, 4467 "ProcessGDBRemote::ParseFlagsFields Could not find type " 4468 "\"{0}\" " 4469 "for field \"{1}\", ignoring", 4470 type->data(), name->data()); 4471 } 4472 } 4473 4474 fields.push_back( 4475 RegisterFlags::Field(name->str(), *start, *end, enum_type)); 4476 } 4477 } 4478 } 4479 4480 return true; // Iterate all "field" nodes. 4481 }); 4482 return fields; 4483 } 4484 4485 void ParseFlags( 4486 XMLNode feature_node, 4487 llvm::StringMap<std::unique_ptr<RegisterFlags>> ®isters_flags_types, 4488 const llvm::StringMap<std::unique_ptr<FieldEnum>> ®isters_enum_types) { 4489 Log *log(GetLog(GDBRLog::Process)); 4490 4491 feature_node.ForEachChildElementWithName( 4492 "flags", 4493 [&log, ®isters_flags_types, 4494 ®isters_enum_types](const XMLNode &flags_node) -> bool { 4495 LLDB_LOG(log, "ProcessGDBRemote::ParseFlags Found flags node \"{0}\"", 4496 flags_node.GetAttributeValue("id").c_str()); 4497 4498 std::optional<llvm::StringRef> id; 4499 std::optional<unsigned> size; 4500 flags_node.ForEachAttribute( 4501 [&id, &size, &log](const llvm::StringRef &name, 4502 const llvm::StringRef &value) { 4503 if (name == "id") { 4504 id = value; 4505 } else if (name == "size") { 4506 unsigned parsed_size = 0; 4507 if (llvm::to_integer(value, parsed_size)) 4508 size = parsed_size; 4509 else { 4510 LLDB_LOG(log, 4511 "ProcessGDBRemote::ParseFlags Invalid size \"{0}\" " 4512 "in flags node", 4513 value.data()); 4514 } 4515 } else { 4516 LLDB_LOG(log, 4517 "ProcessGDBRemote::ParseFlags Ignoring unknown " 4518 "attribute \"{0}\" in flags node", 4519 name.data()); 4520 } 4521 return true; // Walk all attributes. 4522 }); 4523 4524 if (id && size) { 4525 // Process the fields of this set of flags. 4526 std::vector<RegisterFlags::Field> fields = 4527 ParseFlagsFields(flags_node, *size, registers_enum_types); 4528 if (fields.size()) { 4529 // Sort so that the fields with the MSBs are first. 4530 std::sort(fields.rbegin(), fields.rend()); 4531 std::vector<RegisterFlags::Field>::const_iterator overlap = 4532 std::adjacent_find(fields.begin(), fields.end(), 4533 [](const RegisterFlags::Field &lhs, 4534 const RegisterFlags::Field &rhs) { 4535 return lhs.Overlaps(rhs); 4536 }); 4537 4538 // If no fields overlap, use them. 4539 if (overlap == fields.end()) { 4540 if (registers_flags_types.contains(*id)) { 4541 // In theory you could define some flag set, use it with a 4542 // register then redefine it. We do not know if anyone does 4543 // that, or what they would expect to happen in that case. 4544 // 4545 // LLDB chooses to take the first definition and ignore the rest 4546 // as waiting until everything has been processed is more 4547 // expensive and difficult. This means that pointers to flag 4548 // sets in the register info remain valid if later the flag set 4549 // is redefined. If we allowed redefinitions, LLDB would crash 4550 // when you tried to print a register that used the original 4551 // definition. 4552 LLDB_LOG( 4553 log, 4554 "ProcessGDBRemote::ParseFlags Definition of flags " 4555 "\"{0}\" shadows " 4556 "previous definition, using original definition instead.", 4557 id->data()); 4558 } else { 4559 registers_flags_types.insert_or_assign( 4560 *id, std::make_unique<RegisterFlags>(id->str(), *size, 4561 std::move(fields))); 4562 } 4563 } else { 4564 // If any fields overlap, ignore the whole set of flags. 4565 std::vector<RegisterFlags::Field>::const_iterator next = 4566 std::next(overlap); 4567 LLDB_LOG( 4568 log, 4569 "ProcessGDBRemote::ParseFlags Ignoring flags because fields " 4570 "{0} (start: {1} end: {2}) and {3} (start: {4} end: {5}) " 4571 "overlap.", 4572 overlap->GetName().c_str(), overlap->GetStart(), 4573 overlap->GetEnd(), next->GetName().c_str(), next->GetStart(), 4574 next->GetEnd()); 4575 } 4576 } else { 4577 LLDB_LOG( 4578 log, 4579 "ProcessGDBRemote::ParseFlags Ignoring definition of flags " 4580 "\"{0}\" because it contains no fields.", 4581 id->data()); 4582 } 4583 } 4584 4585 return true; // Keep iterating through all "flags" elements. 4586 }); 4587 } 4588 4589 bool ParseRegisters( 4590 XMLNode feature_node, GdbServerTargetInfo &target_info, 4591 std::vector<DynamicRegisterInfo::Register> ®isters, 4592 llvm::StringMap<std::unique_ptr<RegisterFlags>> ®isters_flags_types, 4593 llvm::StringMap<std::unique_ptr<FieldEnum>> ®isters_enum_types) { 4594 if (!feature_node) 4595 return false; 4596 4597 Log *log(GetLog(GDBRLog::Process)); 4598 4599 // Enums first because they are referenced by fields in the flags. 4600 ParseEnums(feature_node, registers_enum_types); 4601 for (const auto &enum_type : registers_enum_types) 4602 enum_type.second->DumpToLog(log); 4603 4604 ParseFlags(feature_node, registers_flags_types, registers_enum_types); 4605 for (const auto &flags : registers_flags_types) 4606 flags.second->DumpToLog(log); 4607 4608 feature_node.ForEachChildElementWithName( 4609 "reg", 4610 [&target_info, ®isters, ®isters_flags_types, 4611 log](const XMLNode ®_node) -> bool { 4612 std::string gdb_group; 4613 std::string gdb_type; 4614 DynamicRegisterInfo::Register reg_info; 4615 bool encoding_set = false; 4616 bool format_set = false; 4617 4618 // FIXME: we're silently ignoring invalid data here 4619 reg_node.ForEachAttribute([&target_info, &gdb_group, &gdb_type, 4620 &encoding_set, &format_set, ®_info, 4621 log](const llvm::StringRef &name, 4622 const llvm::StringRef &value) -> bool { 4623 if (name == "name") { 4624 reg_info.name.SetString(value); 4625 } else if (name == "bitsize") { 4626 if (llvm::to_integer(value, reg_info.byte_size)) 4627 reg_info.byte_size = 4628 llvm::divideCeil(reg_info.byte_size, CHAR_BIT); 4629 } else if (name == "type") { 4630 gdb_type = value.str(); 4631 } else if (name == "group") { 4632 gdb_group = value.str(); 4633 } else if (name == "regnum") { 4634 llvm::to_integer(value, reg_info.regnum_remote); 4635 } else if (name == "offset") { 4636 llvm::to_integer(value, reg_info.byte_offset); 4637 } else if (name == "altname") { 4638 reg_info.alt_name.SetString(value); 4639 } else if (name == "encoding") { 4640 encoding_set = true; 4641 reg_info.encoding = Args::StringToEncoding(value, eEncodingUint); 4642 } else if (name == "format") { 4643 format_set = true; 4644 if (!OptionArgParser::ToFormat(value.data(), reg_info.format, 4645 nullptr) 4646 .Success()) 4647 reg_info.format = 4648 llvm::StringSwitch<lldb::Format>(value) 4649 .Case("vector-sint8", eFormatVectorOfSInt8) 4650 .Case("vector-uint8", eFormatVectorOfUInt8) 4651 .Case("vector-sint16", eFormatVectorOfSInt16) 4652 .Case("vector-uint16", eFormatVectorOfUInt16) 4653 .Case("vector-sint32", eFormatVectorOfSInt32) 4654 .Case("vector-uint32", eFormatVectorOfUInt32) 4655 .Case("vector-float32", eFormatVectorOfFloat32) 4656 .Case("vector-uint64", eFormatVectorOfUInt64) 4657 .Case("vector-uint128", eFormatVectorOfUInt128) 4658 .Default(eFormatInvalid); 4659 } else if (name == "group_id") { 4660 uint32_t set_id = UINT32_MAX; 4661 llvm::to_integer(value, set_id); 4662 RegisterSetMap::const_iterator pos = 4663 target_info.reg_set_map.find(set_id); 4664 if (pos != target_info.reg_set_map.end()) 4665 reg_info.set_name = pos->second.name; 4666 } else if (name == "gcc_regnum" || name == "ehframe_regnum") { 4667 llvm::to_integer(value, reg_info.regnum_ehframe); 4668 } else if (name == "dwarf_regnum") { 4669 llvm::to_integer(value, reg_info.regnum_dwarf); 4670 } else if (name == "generic") { 4671 reg_info.regnum_generic = Args::StringToGenericRegister(value); 4672 } else if (name == "value_regnums") { 4673 SplitCommaSeparatedRegisterNumberString(value, reg_info.value_regs, 4674 0); 4675 } else if (name == "invalidate_regnums") { 4676 SplitCommaSeparatedRegisterNumberString( 4677 value, reg_info.invalidate_regs, 0); 4678 } else { 4679 LLDB_LOGF(log, 4680 "ProcessGDBRemote::ParseRegisters unhandled reg " 4681 "attribute %s = %s", 4682 name.data(), value.data()); 4683 } 4684 return true; // Keep iterating through all attributes 4685 }); 4686 4687 if (!gdb_type.empty()) { 4688 // gdb_type could reference some flags type defined in XML. 4689 llvm::StringMap<std::unique_ptr<RegisterFlags>>::iterator it = 4690 registers_flags_types.find(gdb_type); 4691 if (it != registers_flags_types.end()) { 4692 auto flags_type = it->second.get(); 4693 if (reg_info.byte_size == flags_type->GetSize()) 4694 reg_info.flags_type = flags_type; 4695 else 4696 LLDB_LOGF(log, 4697 "ProcessGDBRemote::ParseRegisters Size of register " 4698 "flags %s (%d bytes) for " 4699 "register %s does not match the register size (%d " 4700 "bytes). Ignoring this set of flags.", 4701 flags_type->GetID().c_str(), flags_type->GetSize(), 4702 reg_info.name.AsCString(), reg_info.byte_size); 4703 } 4704 4705 // There's a slim chance that the gdb_type name is both a flags type 4706 // and a simple type. Just in case, look for that too (setting both 4707 // does no harm). 4708 if (!gdb_type.empty() && !(encoding_set || format_set)) { 4709 if (llvm::StringRef(gdb_type).starts_with("int")) { 4710 reg_info.format = eFormatHex; 4711 reg_info.encoding = eEncodingUint; 4712 } else if (gdb_type == "data_ptr" || gdb_type == "code_ptr") { 4713 reg_info.format = eFormatAddressInfo; 4714 reg_info.encoding = eEncodingUint; 4715 } else if (gdb_type == "float") { 4716 reg_info.format = eFormatFloat; 4717 reg_info.encoding = eEncodingIEEE754; 4718 } else if (gdb_type == "aarch64v" || 4719 llvm::StringRef(gdb_type).starts_with("vec") || 4720 gdb_type == "i387_ext" || gdb_type == "uint128") { 4721 // lldb doesn't handle 128-bit uints correctly (for ymm*h), so 4722 // treat them as vector (similarly to xmm/ymm) 4723 reg_info.format = eFormatVectorOfUInt8; 4724 reg_info.encoding = eEncodingVector; 4725 } else { 4726 LLDB_LOGF( 4727 log, 4728 "ProcessGDBRemote::ParseRegisters Could not determine lldb" 4729 "format and encoding for gdb type %s", 4730 gdb_type.c_str()); 4731 } 4732 } 4733 } 4734 4735 // Only update the register set name if we didn't get a "reg_set" 4736 // attribute. "set_name" will be empty if we didn't have a "reg_set" 4737 // attribute. 4738 if (!reg_info.set_name) { 4739 if (!gdb_group.empty()) { 4740 reg_info.set_name.SetCString(gdb_group.c_str()); 4741 } else { 4742 // If no register group name provided anywhere, 4743 // we'll create a 'general' register set 4744 reg_info.set_name.SetCString("general"); 4745 } 4746 } 4747 4748 if (reg_info.byte_size == 0) { 4749 LLDB_LOGF(log, 4750 "ProcessGDBRemote::%s Skipping zero bitsize register %s", 4751 __FUNCTION__, reg_info.name.AsCString()); 4752 } else 4753 registers.push_back(reg_info); 4754 4755 return true; // Keep iterating through all "reg" elements 4756 }); 4757 return true; 4758 } 4759 4760 } // namespace 4761 4762 // This method fetches a register description feature xml file from 4763 // the remote stub and adds registers/register groupsets/architecture 4764 // information to the current process. It will call itself recursively 4765 // for nested register definition files. It returns true if it was able 4766 // to fetch and parse an xml file. 4767 bool ProcessGDBRemote::GetGDBServerRegisterInfoXMLAndProcess( 4768 ArchSpec &arch_to_use, std::string xml_filename, 4769 std::vector<DynamicRegisterInfo::Register> ®isters) { 4770 // request the target xml file 4771 llvm::Expected<std::string> raw = m_gdb_comm.ReadExtFeature("features", xml_filename); 4772 if (errorToBool(raw.takeError())) 4773 return false; 4774 4775 XMLDocument xml_document; 4776 4777 if (xml_document.ParseMemory(raw->c_str(), raw->size(), 4778 xml_filename.c_str())) { 4779 GdbServerTargetInfo target_info; 4780 std::vector<XMLNode> feature_nodes; 4781 4782 // The top level feature XML file will start with a <target> tag. 4783 XMLNode target_node = xml_document.GetRootElement("target"); 4784 if (target_node) { 4785 target_node.ForEachChildElement([&target_info, &feature_nodes]( 4786 const XMLNode &node) -> bool { 4787 llvm::StringRef name = node.GetName(); 4788 if (name == "architecture") { 4789 node.GetElementText(target_info.arch); 4790 } else if (name == "osabi") { 4791 node.GetElementText(target_info.osabi); 4792 } else if (name == "xi:include" || name == "include") { 4793 std::string href = node.GetAttributeValue("href"); 4794 if (!href.empty()) 4795 target_info.includes.push_back(href); 4796 } else if (name == "feature") { 4797 feature_nodes.push_back(node); 4798 } else if (name == "groups") { 4799 node.ForEachChildElementWithName( 4800 "group", [&target_info](const XMLNode &node) -> bool { 4801 uint32_t set_id = UINT32_MAX; 4802 RegisterSetInfo set_info; 4803 4804 node.ForEachAttribute( 4805 [&set_id, &set_info](const llvm::StringRef &name, 4806 const llvm::StringRef &value) -> bool { 4807 // FIXME: we're silently ignoring invalid data here 4808 if (name == "id") 4809 llvm::to_integer(value, set_id); 4810 if (name == "name") 4811 set_info.name = ConstString(value); 4812 return true; // Keep iterating through all attributes 4813 }); 4814 4815 if (set_id != UINT32_MAX) 4816 target_info.reg_set_map[set_id] = set_info; 4817 return true; // Keep iterating through all "group" elements 4818 }); 4819 } 4820 return true; // Keep iterating through all children of the target_node 4821 }); 4822 } else { 4823 // In an included XML feature file, we're already "inside" the <target> 4824 // tag of the initial XML file; this included file will likely only have 4825 // a <feature> tag. Need to check for any more included files in this 4826 // <feature> element. 4827 XMLNode feature_node = xml_document.GetRootElement("feature"); 4828 if (feature_node) { 4829 feature_nodes.push_back(feature_node); 4830 feature_node.ForEachChildElement([&target_info]( 4831 const XMLNode &node) -> bool { 4832 llvm::StringRef name = node.GetName(); 4833 if (name == "xi:include" || name == "include") { 4834 std::string href = node.GetAttributeValue("href"); 4835 if (!href.empty()) 4836 target_info.includes.push_back(href); 4837 } 4838 return true; 4839 }); 4840 } 4841 } 4842 4843 // gdbserver does not implement the LLDB packets used to determine host 4844 // or process architecture. If that is the case, attempt to use 4845 // the <architecture/> field from target.xml, e.g.: 4846 // 4847 // <architecture>i386:x86-64</architecture> (seen from VMWare ESXi) 4848 // <architecture>arm</architecture> (seen from Segger JLink on unspecified 4849 // arm board) 4850 if (!arch_to_use.IsValid() && !target_info.arch.empty()) { 4851 // We don't have any information about vendor or OS. 4852 arch_to_use.SetTriple(llvm::StringSwitch<std::string>(target_info.arch) 4853 .Case("i386:x86-64", "x86_64") 4854 .Case("riscv:rv64", "riscv64") 4855 .Case("riscv:rv32", "riscv32") 4856 .Default(target_info.arch) + 4857 "--"); 4858 4859 if (arch_to_use.IsValid()) 4860 GetTarget().MergeArchitecture(arch_to_use); 4861 } 4862 4863 if (arch_to_use.IsValid()) { 4864 for (auto &feature_node : feature_nodes) { 4865 ParseRegisters(feature_node, target_info, registers, 4866 m_registers_flags_types, m_registers_enum_types); 4867 } 4868 4869 for (const auto &include : target_info.includes) { 4870 GetGDBServerRegisterInfoXMLAndProcess(arch_to_use, include, 4871 registers); 4872 } 4873 } 4874 } else { 4875 return false; 4876 } 4877 return true; 4878 } 4879 4880 void ProcessGDBRemote::AddRemoteRegisters( 4881 std::vector<DynamicRegisterInfo::Register> ®isters, 4882 const ArchSpec &arch_to_use) { 4883 std::map<uint32_t, uint32_t> remote_to_local_map; 4884 uint32_t remote_regnum = 0; 4885 for (auto it : llvm::enumerate(registers)) { 4886 DynamicRegisterInfo::Register &remote_reg_info = it.value(); 4887 4888 // Assign successive remote regnums if missing. 4889 if (remote_reg_info.regnum_remote == LLDB_INVALID_REGNUM) 4890 remote_reg_info.regnum_remote = remote_regnum; 4891 4892 // Create a mapping from remote to local regnos. 4893 remote_to_local_map[remote_reg_info.regnum_remote] = it.index(); 4894 4895 remote_regnum = remote_reg_info.regnum_remote + 1; 4896 } 4897 4898 for (DynamicRegisterInfo::Register &remote_reg_info : registers) { 4899 auto proc_to_lldb = [&remote_to_local_map](uint32_t process_regnum) { 4900 auto lldb_regit = remote_to_local_map.find(process_regnum); 4901 return lldb_regit != remote_to_local_map.end() ? lldb_regit->second 4902 : LLDB_INVALID_REGNUM; 4903 }; 4904 4905 llvm::transform(remote_reg_info.value_regs, 4906 remote_reg_info.value_regs.begin(), proc_to_lldb); 4907 llvm::transform(remote_reg_info.invalidate_regs, 4908 remote_reg_info.invalidate_regs.begin(), proc_to_lldb); 4909 } 4910 4911 // Don't use Process::GetABI, this code gets called from DidAttach, and 4912 // in that context we haven't set the Target's architecture yet, so the 4913 // ABI is also potentially incorrect. 4914 if (ABISP abi_sp = ABI::FindPlugin(shared_from_this(), arch_to_use)) 4915 abi_sp->AugmentRegisterInfo(registers); 4916 4917 m_register_info_sp->SetRegisterInfo(std::move(registers), arch_to_use); 4918 } 4919 4920 // query the target of gdb-remote for extended target information returns 4921 // true on success (got register definitions), false on failure (did not). 4922 bool ProcessGDBRemote::GetGDBServerRegisterInfo(ArchSpec &arch_to_use) { 4923 // Make sure LLDB has an XML parser it can use first 4924 if (!XMLDocument::XMLEnabled()) 4925 return false; 4926 4927 // check that we have extended feature read support 4928 if (!m_gdb_comm.GetQXferFeaturesReadSupported()) 4929 return false; 4930 4931 // These hold register type information for the whole of target.xml. 4932 // target.xml may include further documents that 4933 // GetGDBServerRegisterInfoXMLAndProcess will recurse to fetch and process. 4934 // That's why we clear the cache here, and not in 4935 // GetGDBServerRegisterInfoXMLAndProcess. To prevent it being cleared on every 4936 // include read. 4937 m_registers_flags_types.clear(); 4938 m_registers_enum_types.clear(); 4939 std::vector<DynamicRegisterInfo::Register> registers; 4940 if (GetGDBServerRegisterInfoXMLAndProcess(arch_to_use, "target.xml", 4941 registers) && 4942 // Target XML is not required to include register information. 4943 !registers.empty()) 4944 AddRemoteRegisters(registers, arch_to_use); 4945 4946 return m_register_info_sp->GetNumRegisters() > 0; 4947 } 4948 4949 llvm::Expected<LoadedModuleInfoList> ProcessGDBRemote::GetLoadedModuleList() { 4950 // Make sure LLDB has an XML parser it can use first 4951 if (!XMLDocument::XMLEnabled()) 4952 return llvm::createStringError(llvm::inconvertibleErrorCode(), 4953 "XML parsing not available"); 4954 4955 Log *log = GetLog(LLDBLog::Process); 4956 LLDB_LOGF(log, "ProcessGDBRemote::%s", __FUNCTION__); 4957 4958 LoadedModuleInfoList list; 4959 GDBRemoteCommunicationClient &comm = m_gdb_comm; 4960 bool can_use_svr4 = GetGlobalPluginProperties().GetUseSVR4(); 4961 4962 // check that we have extended feature read support 4963 if (can_use_svr4 && comm.GetQXferLibrariesSVR4ReadSupported()) { 4964 // request the loaded library list 4965 llvm::Expected<std::string> raw = comm.ReadExtFeature("libraries-svr4", ""); 4966 if (!raw) 4967 return raw.takeError(); 4968 4969 // parse the xml file in memory 4970 LLDB_LOGF(log, "parsing: %s", raw->c_str()); 4971 XMLDocument doc; 4972 4973 if (!doc.ParseMemory(raw->c_str(), raw->size(), "noname.xml")) 4974 return llvm::createStringError(llvm::inconvertibleErrorCode(), 4975 "Error reading noname.xml"); 4976 4977 XMLNode root_element = doc.GetRootElement("library-list-svr4"); 4978 if (!root_element) 4979 return llvm::createStringError( 4980 llvm::inconvertibleErrorCode(), 4981 "Error finding library-list-svr4 xml element"); 4982 4983 // main link map structure 4984 std::string main_lm = root_element.GetAttributeValue("main-lm"); 4985 // FIXME: we're silently ignoring invalid data here 4986 if (!main_lm.empty()) 4987 llvm::to_integer(main_lm, list.m_link_map); 4988 4989 root_element.ForEachChildElementWithName( 4990 "library", [log, &list](const XMLNode &library) -> bool { 4991 LoadedModuleInfoList::LoadedModuleInfo module; 4992 4993 // FIXME: we're silently ignoring invalid data here 4994 library.ForEachAttribute( 4995 [&module](const llvm::StringRef &name, 4996 const llvm::StringRef &value) -> bool { 4997 uint64_t uint_value = LLDB_INVALID_ADDRESS; 4998 if (name == "name") 4999 module.set_name(value.str()); 5000 else if (name == "lm") { 5001 // the address of the link_map struct. 5002 llvm::to_integer(value, uint_value); 5003 module.set_link_map(uint_value); 5004 } else if (name == "l_addr") { 5005 // the displacement as read from the field 'l_addr' of the 5006 // link_map struct. 5007 llvm::to_integer(value, uint_value); 5008 module.set_base(uint_value); 5009 // base address is always a displacement, not an absolute 5010 // value. 5011 module.set_base_is_offset(true); 5012 } else if (name == "l_ld") { 5013 // the memory address of the libraries PT_DYNAMIC section. 5014 llvm::to_integer(value, uint_value); 5015 module.set_dynamic(uint_value); 5016 } 5017 5018 return true; // Keep iterating over all properties of "library" 5019 }); 5020 5021 if (log) { 5022 std::string name; 5023 lldb::addr_t lm = 0, base = 0, ld = 0; 5024 bool base_is_offset; 5025 5026 module.get_name(name); 5027 module.get_link_map(lm); 5028 module.get_base(base); 5029 module.get_base_is_offset(base_is_offset); 5030 module.get_dynamic(ld); 5031 5032 LLDB_LOGF(log, 5033 "found (link_map:0x%08" PRIx64 ", base:0x%08" PRIx64 5034 "[%s], ld:0x%08" PRIx64 ", name:'%s')", 5035 lm, base, (base_is_offset ? "offset" : "absolute"), ld, 5036 name.c_str()); 5037 } 5038 5039 list.add(module); 5040 return true; // Keep iterating over all "library" elements in the root 5041 // node 5042 }); 5043 5044 if (log) 5045 LLDB_LOGF(log, "found %" PRId32 " modules in total", 5046 (int)list.m_list.size()); 5047 return list; 5048 } else if (comm.GetQXferLibrariesReadSupported()) { 5049 // request the loaded library list 5050 llvm::Expected<std::string> raw = comm.ReadExtFeature("libraries", ""); 5051 5052 if (!raw) 5053 return raw.takeError(); 5054 5055 LLDB_LOGF(log, "parsing: %s", raw->c_str()); 5056 XMLDocument doc; 5057 5058 if (!doc.ParseMemory(raw->c_str(), raw->size(), "noname.xml")) 5059 return llvm::createStringError(llvm::inconvertibleErrorCode(), 5060 "Error reading noname.xml"); 5061 5062 XMLNode root_element = doc.GetRootElement("library-list"); 5063 if (!root_element) 5064 return llvm::createStringError(llvm::inconvertibleErrorCode(), 5065 "Error finding library-list xml element"); 5066 5067 // FIXME: we're silently ignoring invalid data here 5068 root_element.ForEachChildElementWithName( 5069 "library", [log, &list](const XMLNode &library) -> bool { 5070 LoadedModuleInfoList::LoadedModuleInfo module; 5071 5072 std::string name = library.GetAttributeValue("name"); 5073 module.set_name(name); 5074 5075 // The base address of a given library will be the address of its 5076 // first section. Most remotes send only one section for Windows 5077 // targets for example. 5078 const XMLNode §ion = 5079 library.FindFirstChildElementWithName("section"); 5080 std::string address = section.GetAttributeValue("address"); 5081 uint64_t address_value = LLDB_INVALID_ADDRESS; 5082 llvm::to_integer(address, address_value); 5083 module.set_base(address_value); 5084 // These addresses are absolute values. 5085 module.set_base_is_offset(false); 5086 5087 if (log) { 5088 std::string name; 5089 lldb::addr_t base = 0; 5090 bool base_is_offset; 5091 module.get_name(name); 5092 module.get_base(base); 5093 module.get_base_is_offset(base_is_offset); 5094 5095 LLDB_LOGF(log, "found (base:0x%08" PRIx64 "[%s], name:'%s')", base, 5096 (base_is_offset ? "offset" : "absolute"), name.c_str()); 5097 } 5098 5099 list.add(module); 5100 return true; // Keep iterating over all "library" elements in the root 5101 // node 5102 }); 5103 5104 if (log) 5105 LLDB_LOGF(log, "found %" PRId32 " modules in total", 5106 (int)list.m_list.size()); 5107 return list; 5108 } else { 5109 return llvm::createStringError(llvm::inconvertibleErrorCode(), 5110 "Remote libraries not supported"); 5111 } 5112 } 5113 5114 lldb::ModuleSP ProcessGDBRemote::LoadModuleAtAddress(const FileSpec &file, 5115 lldb::addr_t link_map, 5116 lldb::addr_t base_addr, 5117 bool value_is_offset) { 5118 DynamicLoader *loader = GetDynamicLoader(); 5119 if (!loader) 5120 return nullptr; 5121 5122 return loader->LoadModuleAtAddress(file, link_map, base_addr, 5123 value_is_offset); 5124 } 5125 5126 llvm::Error ProcessGDBRemote::LoadModules() { 5127 using lldb_private::process_gdb_remote::ProcessGDBRemote; 5128 5129 // request a list of loaded libraries from GDBServer 5130 llvm::Expected<LoadedModuleInfoList> module_list = GetLoadedModuleList(); 5131 if (!module_list) 5132 return module_list.takeError(); 5133 5134 // get a list of all the modules 5135 ModuleList new_modules; 5136 5137 for (LoadedModuleInfoList::LoadedModuleInfo &modInfo : module_list->m_list) { 5138 std::string mod_name; 5139 lldb::addr_t mod_base; 5140 lldb::addr_t link_map; 5141 bool mod_base_is_offset; 5142 5143 bool valid = true; 5144 valid &= modInfo.get_name(mod_name); 5145 valid &= modInfo.get_base(mod_base); 5146 valid &= modInfo.get_base_is_offset(mod_base_is_offset); 5147 if (!valid) 5148 continue; 5149 5150 if (!modInfo.get_link_map(link_map)) 5151 link_map = LLDB_INVALID_ADDRESS; 5152 5153 FileSpec file(mod_name); 5154 FileSystem::Instance().Resolve(file); 5155 lldb::ModuleSP module_sp = 5156 LoadModuleAtAddress(file, link_map, mod_base, mod_base_is_offset); 5157 5158 if (module_sp.get()) 5159 new_modules.Append(module_sp); 5160 } 5161 5162 if (new_modules.GetSize() > 0) { 5163 ModuleList removed_modules; 5164 Target &target = GetTarget(); 5165 ModuleList &loaded_modules = m_process->GetTarget().GetImages(); 5166 5167 for (size_t i = 0; i < loaded_modules.GetSize(); ++i) { 5168 const lldb::ModuleSP loaded_module = loaded_modules.GetModuleAtIndex(i); 5169 5170 bool found = false; 5171 for (size_t j = 0; j < new_modules.GetSize(); ++j) { 5172 if (new_modules.GetModuleAtIndex(j).get() == loaded_module.get()) 5173 found = true; 5174 } 5175 5176 // The main executable will never be included in libraries-svr4, don't 5177 // remove it 5178 if (!found && 5179 loaded_module.get() != target.GetExecutableModulePointer()) { 5180 removed_modules.Append(loaded_module); 5181 } 5182 } 5183 5184 loaded_modules.Remove(removed_modules); 5185 m_process->GetTarget().ModulesDidUnload(removed_modules, false); 5186 5187 new_modules.ForEach([&target](const lldb::ModuleSP module_sp) -> bool { 5188 lldb_private::ObjectFile *obj = module_sp->GetObjectFile(); 5189 if (!obj) 5190 return true; 5191 5192 if (obj->GetType() != ObjectFile::Type::eTypeExecutable) 5193 return true; 5194 5195 lldb::ModuleSP module_copy_sp = module_sp; 5196 target.SetExecutableModule(module_copy_sp, eLoadDependentsNo); 5197 return false; 5198 }); 5199 5200 loaded_modules.AppendIfNeeded(new_modules); 5201 m_process->GetTarget().ModulesDidLoad(new_modules); 5202 } 5203 5204 return llvm::ErrorSuccess(); 5205 } 5206 5207 Status ProcessGDBRemote::GetFileLoadAddress(const FileSpec &file, 5208 bool &is_loaded, 5209 lldb::addr_t &load_addr) { 5210 is_loaded = false; 5211 load_addr = LLDB_INVALID_ADDRESS; 5212 5213 std::string file_path = file.GetPath(false); 5214 if (file_path.empty()) 5215 return Status::FromErrorString("Empty file name specified"); 5216 5217 StreamString packet; 5218 packet.PutCString("qFileLoadAddress:"); 5219 packet.PutStringAsRawHex8(file_path); 5220 5221 StringExtractorGDBRemote response; 5222 if (m_gdb_comm.SendPacketAndWaitForResponse(packet.GetString(), response) != 5223 GDBRemoteCommunication::PacketResult::Success) 5224 return Status::FromErrorString("Sending qFileLoadAddress packet failed"); 5225 5226 if (response.IsErrorResponse()) { 5227 if (response.GetError() == 1) { 5228 // The file is not loaded into the inferior 5229 is_loaded = false; 5230 load_addr = LLDB_INVALID_ADDRESS; 5231 return Status(); 5232 } 5233 5234 return Status::FromErrorString( 5235 "Fetching file load address from remote server returned an error"); 5236 } 5237 5238 if (response.IsNormalResponse()) { 5239 is_loaded = true; 5240 load_addr = response.GetHexMaxU64(false, LLDB_INVALID_ADDRESS); 5241 return Status(); 5242 } 5243 5244 return Status::FromErrorString( 5245 "Unknown error happened during sending the load address packet"); 5246 } 5247 5248 void ProcessGDBRemote::ModulesDidLoad(ModuleList &module_list) { 5249 // We must call the lldb_private::Process::ModulesDidLoad () first before we 5250 // do anything 5251 Process::ModulesDidLoad(module_list); 5252 5253 // After loading shared libraries, we can ask our remote GDB server if it 5254 // needs any symbols. 5255 m_gdb_comm.ServeSymbolLookups(this); 5256 } 5257 5258 void ProcessGDBRemote::HandleAsyncStdout(llvm::StringRef out) { 5259 AppendSTDOUT(out.data(), out.size()); 5260 } 5261 5262 static const char *end_delimiter = "--end--;"; 5263 static const int end_delimiter_len = 8; 5264 5265 void ProcessGDBRemote::HandleAsyncMisc(llvm::StringRef data) { 5266 std::string input = data.str(); // '1' to move beyond 'A' 5267 if (m_partial_profile_data.length() > 0) { 5268 m_partial_profile_data.append(input); 5269 input = m_partial_profile_data; 5270 m_partial_profile_data.clear(); 5271 } 5272 5273 size_t found, pos = 0, len = input.length(); 5274 while ((found = input.find(end_delimiter, pos)) != std::string::npos) { 5275 StringExtractorGDBRemote profileDataExtractor( 5276 input.substr(pos, found).c_str()); 5277 std::string profile_data = 5278 HarmonizeThreadIdsForProfileData(profileDataExtractor); 5279 BroadcastAsyncProfileData(profile_data); 5280 5281 pos = found + end_delimiter_len; 5282 } 5283 5284 if (pos < len) { 5285 // Last incomplete chunk. 5286 m_partial_profile_data = input.substr(pos); 5287 } 5288 } 5289 5290 std::string ProcessGDBRemote::HarmonizeThreadIdsForProfileData( 5291 StringExtractorGDBRemote &profileDataExtractor) { 5292 std::map<uint64_t, uint32_t> new_thread_id_to_used_usec_map; 5293 std::string output; 5294 llvm::raw_string_ostream output_stream(output); 5295 llvm::StringRef name, value; 5296 5297 // Going to assuming thread_used_usec comes first, else bail out. 5298 while (profileDataExtractor.GetNameColonValue(name, value)) { 5299 if (name.compare("thread_used_id") == 0) { 5300 StringExtractor threadIDHexExtractor(value); 5301 uint64_t thread_id = threadIDHexExtractor.GetHexMaxU64(false, 0); 5302 5303 bool has_used_usec = false; 5304 uint32_t curr_used_usec = 0; 5305 llvm::StringRef usec_name, usec_value; 5306 uint32_t input_file_pos = profileDataExtractor.GetFilePos(); 5307 if (profileDataExtractor.GetNameColonValue(usec_name, usec_value)) { 5308 if (usec_name == "thread_used_usec") { 5309 has_used_usec = true; 5310 usec_value.getAsInteger(0, curr_used_usec); 5311 } else { 5312 // We didn't find what we want, it is probably an older version. Bail 5313 // out. 5314 profileDataExtractor.SetFilePos(input_file_pos); 5315 } 5316 } 5317 5318 if (has_used_usec) { 5319 uint32_t prev_used_usec = 0; 5320 std::map<uint64_t, uint32_t>::iterator iterator = 5321 m_thread_id_to_used_usec_map.find(thread_id); 5322 if (iterator != m_thread_id_to_used_usec_map.end()) { 5323 prev_used_usec = m_thread_id_to_used_usec_map[thread_id]; 5324 } 5325 5326 uint32_t real_used_usec = curr_used_usec - prev_used_usec; 5327 // A good first time record is one that runs for at least 0.25 sec 5328 bool good_first_time = 5329 (prev_used_usec == 0) && (real_used_usec > 250000); 5330 bool good_subsequent_time = 5331 (prev_used_usec > 0) && 5332 ((real_used_usec > 0) || (HasAssignedIndexIDToThread(thread_id))); 5333 5334 if (good_first_time || good_subsequent_time) { 5335 // We try to avoid doing too many index id reservation, resulting in 5336 // fast increase of index ids. 5337 5338 output_stream << name << ":"; 5339 int32_t index_id = AssignIndexIDToThread(thread_id); 5340 output_stream << index_id << ";"; 5341 5342 output_stream << usec_name << ":" << usec_value << ";"; 5343 } else { 5344 // Skip past 'thread_used_name'. 5345 llvm::StringRef local_name, local_value; 5346 profileDataExtractor.GetNameColonValue(local_name, local_value); 5347 } 5348 5349 // Store current time as previous time so that they can be compared 5350 // later. 5351 new_thread_id_to_used_usec_map[thread_id] = curr_used_usec; 5352 } else { 5353 // Bail out and use old string. 5354 output_stream << name << ":" << value << ";"; 5355 } 5356 } else { 5357 output_stream << name << ":" << value << ";"; 5358 } 5359 } 5360 output_stream << end_delimiter; 5361 m_thread_id_to_used_usec_map = new_thread_id_to_used_usec_map; 5362 5363 return output; 5364 } 5365 5366 void ProcessGDBRemote::HandleStopReply() { 5367 if (GetStopID() != 0) 5368 return; 5369 5370 if (GetID() == LLDB_INVALID_PROCESS_ID) { 5371 lldb::pid_t pid = m_gdb_comm.GetCurrentProcessID(); 5372 if (pid != LLDB_INVALID_PROCESS_ID) 5373 SetID(pid); 5374 } 5375 BuildDynamicRegisterInfo(true); 5376 } 5377 5378 llvm::Expected<bool> ProcessGDBRemote::SaveCore(llvm::StringRef outfile) { 5379 if (!m_gdb_comm.GetSaveCoreSupported()) 5380 return false; 5381 5382 StreamString packet; 5383 packet.PutCString("qSaveCore;path-hint:"); 5384 packet.PutStringAsRawHex8(outfile); 5385 5386 StringExtractorGDBRemote response; 5387 if (m_gdb_comm.SendPacketAndWaitForResponse(packet.GetString(), response) == 5388 GDBRemoteCommunication::PacketResult::Success) { 5389 // TODO: grab error message from the packet? StringExtractor seems to 5390 // be missing a method for that 5391 if (response.IsErrorResponse()) 5392 return llvm::createStringError( 5393 llvm::inconvertibleErrorCode(), 5394 llvm::formatv("qSaveCore returned an error")); 5395 5396 std::string path; 5397 5398 // process the response 5399 for (auto x : llvm::split(response.GetStringRef(), ';')) { 5400 if (x.consume_front("core-path:")) 5401 StringExtractor(x).GetHexByteString(path); 5402 } 5403 5404 // verify that we've gotten what we need 5405 if (path.empty()) 5406 return llvm::createStringError(llvm::inconvertibleErrorCode(), 5407 "qSaveCore returned no core path"); 5408 5409 // now transfer the core file 5410 FileSpec remote_core{llvm::StringRef(path)}; 5411 Platform &platform = *GetTarget().GetPlatform(); 5412 Status error = platform.GetFile(remote_core, FileSpec(outfile)); 5413 5414 if (platform.IsRemote()) { 5415 // NB: we unlink the file on error too 5416 platform.Unlink(remote_core); 5417 if (error.Fail()) 5418 return error.ToError(); 5419 } 5420 5421 return true; 5422 } 5423 5424 return llvm::createStringError(llvm::inconvertibleErrorCode(), 5425 "Unable to send qSaveCore"); 5426 } 5427 5428 static const char *const s_async_json_packet_prefix = "JSON-async:"; 5429 5430 static StructuredData::ObjectSP 5431 ParseStructuredDataPacket(llvm::StringRef packet) { 5432 Log *log = GetLog(GDBRLog::Process); 5433 5434 if (!packet.consume_front(s_async_json_packet_prefix)) { 5435 if (log) { 5436 LLDB_LOGF( 5437 log, 5438 "GDBRemoteCommunicationClientBase::%s() received $J packet " 5439 "but was not a StructuredData packet: packet starts with " 5440 "%s", 5441 __FUNCTION__, 5442 packet.slice(0, strlen(s_async_json_packet_prefix)).str().c_str()); 5443 } 5444 return StructuredData::ObjectSP(); 5445 } 5446 5447 // This is an asynchronous JSON packet, destined for a StructuredDataPlugin. 5448 StructuredData::ObjectSP json_sp = StructuredData::ParseJSON(packet); 5449 if (log) { 5450 if (json_sp) { 5451 StreamString json_str; 5452 json_sp->Dump(json_str, true); 5453 json_str.Flush(); 5454 LLDB_LOGF(log, 5455 "ProcessGDBRemote::%s() " 5456 "received Async StructuredData packet: %s", 5457 __FUNCTION__, json_str.GetData()); 5458 } else { 5459 LLDB_LOGF(log, 5460 "ProcessGDBRemote::%s" 5461 "() received StructuredData packet:" 5462 " parse failure", 5463 __FUNCTION__); 5464 } 5465 } 5466 return json_sp; 5467 } 5468 5469 void ProcessGDBRemote::HandleAsyncStructuredDataPacket(llvm::StringRef data) { 5470 auto structured_data_sp = ParseStructuredDataPacket(data); 5471 if (structured_data_sp) 5472 RouteAsyncStructuredData(structured_data_sp); 5473 } 5474 5475 class CommandObjectProcessGDBRemoteSpeedTest : public CommandObjectParsed { 5476 public: 5477 CommandObjectProcessGDBRemoteSpeedTest(CommandInterpreter &interpreter) 5478 : CommandObjectParsed(interpreter, "process plugin packet speed-test", 5479 "Tests packet speeds of various sizes to determine " 5480 "the performance characteristics of the GDB remote " 5481 "connection. ", 5482 nullptr), 5483 m_option_group(), 5484 m_num_packets(LLDB_OPT_SET_1, false, "count", 'c', 0, eArgTypeCount, 5485 "The number of packets to send of each varying size " 5486 "(default is 1000).", 5487 1000), 5488 m_max_send(LLDB_OPT_SET_1, false, "max-send", 's', 0, eArgTypeCount, 5489 "The maximum number of bytes to send in a packet. Sizes " 5490 "increase in powers of 2 while the size is less than or " 5491 "equal to this option value. (default 1024).", 5492 1024), 5493 m_max_recv(LLDB_OPT_SET_1, false, "max-receive", 'r', 0, eArgTypeCount, 5494 "The maximum number of bytes to receive in a packet. Sizes " 5495 "increase in powers of 2 while the size is less than or " 5496 "equal to this option value. (default 1024).", 5497 1024), 5498 m_json(LLDB_OPT_SET_1, false, "json", 'j', 5499 "Print the output as JSON data for easy parsing.", false, true) { 5500 m_option_group.Append(&m_num_packets, LLDB_OPT_SET_ALL, LLDB_OPT_SET_1); 5501 m_option_group.Append(&m_max_send, LLDB_OPT_SET_ALL, LLDB_OPT_SET_1); 5502 m_option_group.Append(&m_max_recv, LLDB_OPT_SET_ALL, LLDB_OPT_SET_1); 5503 m_option_group.Append(&m_json, LLDB_OPT_SET_ALL, LLDB_OPT_SET_1); 5504 m_option_group.Finalize(); 5505 } 5506 5507 ~CommandObjectProcessGDBRemoteSpeedTest() override = default; 5508 5509 Options *GetOptions() override { return &m_option_group; } 5510 5511 void DoExecute(Args &command, CommandReturnObject &result) override { 5512 const size_t argc = command.GetArgumentCount(); 5513 if (argc == 0) { 5514 ProcessGDBRemote *process = 5515 (ProcessGDBRemote *)m_interpreter.GetExecutionContext() 5516 .GetProcessPtr(); 5517 if (process) { 5518 StreamSP output_stream_sp = result.GetImmediateOutputStream(); 5519 if (!output_stream_sp) 5520 output_stream_sp = 5521 StreamSP(m_interpreter.GetDebugger().GetAsyncOutputStream()); 5522 result.SetImmediateOutputStream(output_stream_sp); 5523 5524 const uint32_t num_packets = 5525 (uint32_t)m_num_packets.GetOptionValue().GetCurrentValue(); 5526 const uint64_t max_send = m_max_send.GetOptionValue().GetCurrentValue(); 5527 const uint64_t max_recv = m_max_recv.GetOptionValue().GetCurrentValue(); 5528 const bool json = m_json.GetOptionValue().GetCurrentValue(); 5529 const uint64_t k_recv_amount = 5530 4 * 1024 * 1024; // Receive amount in bytes 5531 process->GetGDBRemote().TestPacketSpeed( 5532 num_packets, max_send, max_recv, k_recv_amount, json, 5533 output_stream_sp ? *output_stream_sp : result.GetOutputStream()); 5534 result.SetStatus(eReturnStatusSuccessFinishResult); 5535 return; 5536 } 5537 } else { 5538 result.AppendErrorWithFormat("'%s' takes no arguments", 5539 m_cmd_name.c_str()); 5540 } 5541 result.SetStatus(eReturnStatusFailed); 5542 } 5543 5544 protected: 5545 OptionGroupOptions m_option_group; 5546 OptionGroupUInt64 m_num_packets; 5547 OptionGroupUInt64 m_max_send; 5548 OptionGroupUInt64 m_max_recv; 5549 OptionGroupBoolean m_json; 5550 }; 5551 5552 class CommandObjectProcessGDBRemotePacketHistory : public CommandObjectParsed { 5553 private: 5554 public: 5555 CommandObjectProcessGDBRemotePacketHistory(CommandInterpreter &interpreter) 5556 : CommandObjectParsed(interpreter, "process plugin packet history", 5557 "Dumps the packet history buffer. ", nullptr) {} 5558 5559 ~CommandObjectProcessGDBRemotePacketHistory() override = default; 5560 5561 void DoExecute(Args &command, CommandReturnObject &result) override { 5562 ProcessGDBRemote *process = 5563 (ProcessGDBRemote *)m_interpreter.GetExecutionContext().GetProcessPtr(); 5564 if (process) { 5565 process->DumpPluginHistory(result.GetOutputStream()); 5566 result.SetStatus(eReturnStatusSuccessFinishResult); 5567 return; 5568 } 5569 result.SetStatus(eReturnStatusFailed); 5570 } 5571 }; 5572 5573 class CommandObjectProcessGDBRemotePacketXferSize : public CommandObjectParsed { 5574 private: 5575 public: 5576 CommandObjectProcessGDBRemotePacketXferSize(CommandInterpreter &interpreter) 5577 : CommandObjectParsed( 5578 interpreter, "process plugin packet xfer-size", 5579 "Maximum size that lldb will try to read/write one one chunk.", 5580 nullptr) { 5581 AddSimpleArgumentList(eArgTypeUnsignedInteger); 5582 } 5583 5584 ~CommandObjectProcessGDBRemotePacketXferSize() override = default; 5585 5586 void DoExecute(Args &command, CommandReturnObject &result) override { 5587 const size_t argc = command.GetArgumentCount(); 5588 if (argc == 0) { 5589 result.AppendErrorWithFormat("'%s' takes an argument to specify the max " 5590 "amount to be transferred when " 5591 "reading/writing", 5592 m_cmd_name.c_str()); 5593 return; 5594 } 5595 5596 ProcessGDBRemote *process = 5597 (ProcessGDBRemote *)m_interpreter.GetExecutionContext().GetProcessPtr(); 5598 if (process) { 5599 const char *packet_size = command.GetArgumentAtIndex(0); 5600 errno = 0; 5601 uint64_t user_specified_max = strtoul(packet_size, nullptr, 10); 5602 if (errno == 0 && user_specified_max != 0) { 5603 process->SetUserSpecifiedMaxMemoryTransferSize(user_specified_max); 5604 result.SetStatus(eReturnStatusSuccessFinishResult); 5605 return; 5606 } 5607 } 5608 result.SetStatus(eReturnStatusFailed); 5609 } 5610 }; 5611 5612 class CommandObjectProcessGDBRemotePacketSend : public CommandObjectParsed { 5613 private: 5614 public: 5615 CommandObjectProcessGDBRemotePacketSend(CommandInterpreter &interpreter) 5616 : CommandObjectParsed(interpreter, "process plugin packet send", 5617 "Send a custom packet through the GDB remote " 5618 "protocol and print the answer. " 5619 "The packet header and footer will automatically " 5620 "be added to the packet prior to sending and " 5621 "stripped from the result.", 5622 nullptr) { 5623 AddSimpleArgumentList(eArgTypeNone, eArgRepeatStar); 5624 } 5625 5626 ~CommandObjectProcessGDBRemotePacketSend() override = default; 5627 5628 void DoExecute(Args &command, CommandReturnObject &result) override { 5629 const size_t argc = command.GetArgumentCount(); 5630 if (argc == 0) { 5631 result.AppendErrorWithFormat( 5632 "'%s' takes a one or more packet content arguments", 5633 m_cmd_name.c_str()); 5634 return; 5635 } 5636 5637 ProcessGDBRemote *process = 5638 (ProcessGDBRemote *)m_interpreter.GetExecutionContext().GetProcessPtr(); 5639 if (process) { 5640 for (size_t i = 0; i < argc; ++i) { 5641 const char *packet_cstr = command.GetArgumentAtIndex(0); 5642 StringExtractorGDBRemote response; 5643 process->GetGDBRemote().SendPacketAndWaitForResponse( 5644 packet_cstr, response, process->GetInterruptTimeout()); 5645 result.SetStatus(eReturnStatusSuccessFinishResult); 5646 Stream &output_strm = result.GetOutputStream(); 5647 output_strm.Printf(" packet: %s\n", packet_cstr); 5648 std::string response_str = std::string(response.GetStringRef()); 5649 5650 if (strstr(packet_cstr, "qGetProfileData") != nullptr) { 5651 response_str = process->HarmonizeThreadIdsForProfileData(response); 5652 } 5653 5654 if (response_str.empty()) 5655 output_strm.PutCString("response: \nerror: UNIMPLEMENTED\n"); 5656 else 5657 output_strm.Printf("response: %s\n", response.GetStringRef().data()); 5658 } 5659 } 5660 } 5661 }; 5662 5663 class CommandObjectProcessGDBRemotePacketMonitor : public CommandObjectRaw { 5664 private: 5665 public: 5666 CommandObjectProcessGDBRemotePacketMonitor(CommandInterpreter &interpreter) 5667 : CommandObjectRaw(interpreter, "process plugin packet monitor", 5668 "Send a qRcmd packet through the GDB remote protocol " 5669 "and print the response." 5670 "The argument passed to this command will be hex " 5671 "encoded into a valid 'qRcmd' packet, sent and the " 5672 "response will be printed.") {} 5673 5674 ~CommandObjectProcessGDBRemotePacketMonitor() override = default; 5675 5676 void DoExecute(llvm::StringRef command, 5677 CommandReturnObject &result) override { 5678 if (command.empty()) { 5679 result.AppendErrorWithFormat("'%s' takes a command string argument", 5680 m_cmd_name.c_str()); 5681 return; 5682 } 5683 5684 ProcessGDBRemote *process = 5685 (ProcessGDBRemote *)m_interpreter.GetExecutionContext().GetProcessPtr(); 5686 if (process) { 5687 StreamString packet; 5688 packet.PutCString("qRcmd,"); 5689 packet.PutBytesAsRawHex8(command.data(), command.size()); 5690 5691 StringExtractorGDBRemote response; 5692 Stream &output_strm = result.GetOutputStream(); 5693 process->GetGDBRemote().SendPacketAndReceiveResponseWithOutputSupport( 5694 packet.GetString(), response, process->GetInterruptTimeout(), 5695 [&output_strm](llvm::StringRef output) { output_strm << output; }); 5696 result.SetStatus(eReturnStatusSuccessFinishResult); 5697 output_strm.Printf(" packet: %s\n", packet.GetData()); 5698 const std::string &response_str = std::string(response.GetStringRef()); 5699 5700 if (response_str.empty()) 5701 output_strm.PutCString("response: \nerror: UNIMPLEMENTED\n"); 5702 else 5703 output_strm.Printf("response: %s\n", response.GetStringRef().data()); 5704 } 5705 } 5706 }; 5707 5708 class CommandObjectProcessGDBRemotePacket : public CommandObjectMultiword { 5709 private: 5710 public: 5711 CommandObjectProcessGDBRemotePacket(CommandInterpreter &interpreter) 5712 : CommandObjectMultiword(interpreter, "process plugin packet", 5713 "Commands that deal with GDB remote packets.", 5714 nullptr) { 5715 LoadSubCommand( 5716 "history", 5717 CommandObjectSP( 5718 new CommandObjectProcessGDBRemotePacketHistory(interpreter))); 5719 LoadSubCommand( 5720 "send", CommandObjectSP( 5721 new CommandObjectProcessGDBRemotePacketSend(interpreter))); 5722 LoadSubCommand( 5723 "monitor", 5724 CommandObjectSP( 5725 new CommandObjectProcessGDBRemotePacketMonitor(interpreter))); 5726 LoadSubCommand( 5727 "xfer-size", 5728 CommandObjectSP( 5729 new CommandObjectProcessGDBRemotePacketXferSize(interpreter))); 5730 LoadSubCommand("speed-test", 5731 CommandObjectSP(new CommandObjectProcessGDBRemoteSpeedTest( 5732 interpreter))); 5733 } 5734 5735 ~CommandObjectProcessGDBRemotePacket() override = default; 5736 }; 5737 5738 class CommandObjectMultiwordProcessGDBRemote : public CommandObjectMultiword { 5739 public: 5740 CommandObjectMultiwordProcessGDBRemote(CommandInterpreter &interpreter) 5741 : CommandObjectMultiword( 5742 interpreter, "process plugin", 5743 "Commands for operating on a ProcessGDBRemote process.", 5744 "process plugin <subcommand> [<subcommand-options>]") { 5745 LoadSubCommand( 5746 "packet", 5747 CommandObjectSP(new CommandObjectProcessGDBRemotePacket(interpreter))); 5748 } 5749 5750 ~CommandObjectMultiwordProcessGDBRemote() override = default; 5751 }; 5752 5753 CommandObject *ProcessGDBRemote::GetPluginCommandObject() { 5754 if (!m_command_sp) 5755 m_command_sp = std::make_shared<CommandObjectMultiwordProcessGDBRemote>( 5756 GetTarget().GetDebugger().GetCommandInterpreter()); 5757 return m_command_sp.get(); 5758 } 5759 5760 void ProcessGDBRemote::DidForkSwitchSoftwareBreakpoints(bool enable) { 5761 GetBreakpointSiteList().ForEach([this, enable](BreakpointSite *bp_site) { 5762 if (bp_site->IsEnabled() && 5763 (bp_site->GetType() == BreakpointSite::eSoftware || 5764 bp_site->GetType() == BreakpointSite::eExternal)) { 5765 m_gdb_comm.SendGDBStoppointTypePacket( 5766 eBreakpointSoftware, enable, bp_site->GetLoadAddress(), 5767 GetSoftwareBreakpointTrapOpcode(bp_site), GetInterruptTimeout()); 5768 } 5769 }); 5770 } 5771 5772 void ProcessGDBRemote::DidForkSwitchHardwareTraps(bool enable) { 5773 if (m_gdb_comm.SupportsGDBStoppointPacket(eBreakpointHardware)) { 5774 GetBreakpointSiteList().ForEach([this, enable](BreakpointSite *bp_site) { 5775 if (bp_site->IsEnabled() && 5776 bp_site->GetType() == BreakpointSite::eHardware) { 5777 m_gdb_comm.SendGDBStoppointTypePacket( 5778 eBreakpointHardware, enable, bp_site->GetLoadAddress(), 5779 GetSoftwareBreakpointTrapOpcode(bp_site), GetInterruptTimeout()); 5780 } 5781 }); 5782 } 5783 5784 for (const auto &wp_res_sp : m_watchpoint_resource_list.Sites()) { 5785 addr_t addr = wp_res_sp->GetLoadAddress(); 5786 size_t size = wp_res_sp->GetByteSize(); 5787 GDBStoppointType type = GetGDBStoppointType(wp_res_sp); 5788 m_gdb_comm.SendGDBStoppointTypePacket(type, enable, addr, size, 5789 GetInterruptTimeout()); 5790 } 5791 } 5792 5793 void ProcessGDBRemote::DidFork(lldb::pid_t child_pid, lldb::tid_t child_tid) { 5794 Log *log = GetLog(GDBRLog::Process); 5795 5796 lldb::pid_t parent_pid = m_gdb_comm.GetCurrentProcessID(); 5797 // Any valid TID will suffice, thread-relevant actions will set a proper TID 5798 // anyway. 5799 lldb::tid_t parent_tid = m_thread_ids.front(); 5800 5801 lldb::pid_t follow_pid, detach_pid; 5802 lldb::tid_t follow_tid, detach_tid; 5803 5804 switch (GetFollowForkMode()) { 5805 case eFollowParent: 5806 follow_pid = parent_pid; 5807 follow_tid = parent_tid; 5808 detach_pid = child_pid; 5809 detach_tid = child_tid; 5810 break; 5811 case eFollowChild: 5812 follow_pid = child_pid; 5813 follow_tid = child_tid; 5814 detach_pid = parent_pid; 5815 detach_tid = parent_tid; 5816 break; 5817 } 5818 5819 // Switch to the process that is going to be detached. 5820 if (!m_gdb_comm.SetCurrentThread(detach_tid, detach_pid)) { 5821 LLDB_LOG(log, "ProcessGDBRemote::DidFork() unable to set pid/tid"); 5822 return; 5823 } 5824 5825 // Disable all software breakpoints in the forked process. 5826 if (m_gdb_comm.SupportsGDBStoppointPacket(eBreakpointSoftware)) 5827 DidForkSwitchSoftwareBreakpoints(false); 5828 5829 // Remove hardware breakpoints / watchpoints from parent process if we're 5830 // following child. 5831 if (GetFollowForkMode() == eFollowChild) 5832 DidForkSwitchHardwareTraps(false); 5833 5834 // Switch to the process that is going to be followed 5835 if (!m_gdb_comm.SetCurrentThread(follow_tid, follow_pid) || 5836 !m_gdb_comm.SetCurrentThreadForRun(follow_tid, follow_pid)) { 5837 LLDB_LOG(log, "ProcessGDBRemote::DidFork() unable to reset pid/tid"); 5838 return; 5839 } 5840 5841 LLDB_LOG(log, "Detaching process {0}", detach_pid); 5842 Status error = m_gdb_comm.Detach(false, detach_pid); 5843 if (error.Fail()) { 5844 LLDB_LOG(log, "ProcessGDBRemote::DidFork() detach packet send failed: {0}", 5845 error.AsCString() ? error.AsCString() : "<unknown error>"); 5846 return; 5847 } 5848 5849 // Hardware breakpoints/watchpoints are not inherited implicitly, 5850 // so we need to readd them if we're following child. 5851 if (GetFollowForkMode() == eFollowChild) { 5852 DidForkSwitchHardwareTraps(true); 5853 // Update our PID 5854 SetID(child_pid); 5855 } 5856 } 5857 5858 void ProcessGDBRemote::DidVFork(lldb::pid_t child_pid, lldb::tid_t child_tid) { 5859 Log *log = GetLog(GDBRLog::Process); 5860 5861 LLDB_LOG( 5862 log, 5863 "ProcessGDBRemote::DidFork() called for child_pid: {0}, child_tid {1}", 5864 child_pid, child_tid); 5865 ++m_vfork_in_progress_count; 5866 5867 // Disable all software breakpoints for the duration of vfork. 5868 if (m_gdb_comm.SupportsGDBStoppointPacket(eBreakpointSoftware)) 5869 DidForkSwitchSoftwareBreakpoints(false); 5870 5871 lldb::pid_t detach_pid; 5872 lldb::tid_t detach_tid; 5873 5874 switch (GetFollowForkMode()) { 5875 case eFollowParent: 5876 detach_pid = child_pid; 5877 detach_tid = child_tid; 5878 break; 5879 case eFollowChild: 5880 detach_pid = m_gdb_comm.GetCurrentProcessID(); 5881 // Any valid TID will suffice, thread-relevant actions will set a proper TID 5882 // anyway. 5883 detach_tid = m_thread_ids.front(); 5884 5885 // Switch to the parent process before detaching it. 5886 if (!m_gdb_comm.SetCurrentThread(detach_tid, detach_pid)) { 5887 LLDB_LOG(log, "ProcessGDBRemote::DidFork() unable to set pid/tid"); 5888 return; 5889 } 5890 5891 // Remove hardware breakpoints / watchpoints from the parent process. 5892 DidForkSwitchHardwareTraps(false); 5893 5894 // Switch to the child process. 5895 if (!m_gdb_comm.SetCurrentThread(child_tid, child_pid) || 5896 !m_gdb_comm.SetCurrentThreadForRun(child_tid, child_pid)) { 5897 LLDB_LOG(log, "ProcessGDBRemote::DidFork() unable to reset pid/tid"); 5898 return; 5899 } 5900 break; 5901 } 5902 5903 LLDB_LOG(log, "Detaching process {0}", detach_pid); 5904 Status error = m_gdb_comm.Detach(false, detach_pid); 5905 if (error.Fail()) { 5906 LLDB_LOG(log, 5907 "ProcessGDBRemote::DidFork() detach packet send failed: {0}", 5908 error.AsCString() ? error.AsCString() : "<unknown error>"); 5909 return; 5910 } 5911 5912 if (GetFollowForkMode() == eFollowChild) { 5913 // Update our PID 5914 SetID(child_pid); 5915 } 5916 } 5917 5918 void ProcessGDBRemote::DidVForkDone() { 5919 assert(m_vfork_in_progress_count > 0); 5920 --m_vfork_in_progress_count; 5921 5922 // Reenable all software breakpoints that were enabled before vfork. 5923 if (m_gdb_comm.SupportsGDBStoppointPacket(eBreakpointSoftware)) 5924 DidForkSwitchSoftwareBreakpoints(true); 5925 } 5926 5927 void ProcessGDBRemote::DidExec() { 5928 // If we are following children, vfork is finished by exec (rather than 5929 // vforkdone that is submitted for parent). 5930 if (GetFollowForkMode() == eFollowChild) { 5931 if (m_vfork_in_progress_count > 0) 5932 --m_vfork_in_progress_count; 5933 } 5934 Process::DidExec(); 5935 } 5936