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