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/Value.h" 32 #include "lldb/DataFormatters/FormatManager.h" 33 #include "lldb/Host/ConnectionFileDescriptor.h" 34 #include "lldb/Host/FileSystem.h" 35 #include "lldb/Host/HostThread.h" 36 #include "lldb/Host/PosixApi.h" 37 #include "lldb/Host/PseudoTerminal.h" 38 #include "lldb/Host/StreamFile.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 llvm::StringRef GetSettingName() { 133 return 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 AddressableBits addressable_bits = m_gdb_comm.GetAddressableBits(); 903 addressable_bits.SetProcessMasks(*this); 904 905 if (process_arch.IsValid()) { 906 const ArchSpec &target_arch = GetTarget().GetArchitecture(); 907 if (target_arch.IsValid()) { 908 LLDB_LOG(log, "analyzing target arch, currently {0} {1}", 909 target_arch.GetArchitectureName(), 910 target_arch.GetTriple().getTriple()); 911 912 // If the remote host is ARM and we have apple as the vendor, then 913 // ARM executables and shared libraries can have mixed ARM 914 // architectures. 915 // You can have an armv6 executable, and if the host is armv7, then the 916 // system will load the best possible architecture for all shared 917 // libraries it has, so we really need to take the remote host 918 // architecture as our defacto architecture in this case. 919 920 if ((process_arch.GetMachine() == llvm::Triple::arm || 921 process_arch.GetMachine() == llvm::Triple::thumb) && 922 process_arch.GetTriple().getVendor() == llvm::Triple::Apple) { 923 GetTarget().SetArchitecture(process_arch); 924 LLDB_LOG(log, 925 "remote process is ARM/Apple, " 926 "setting target arch to {0} {1}", 927 process_arch.GetArchitectureName(), 928 process_arch.GetTriple().getTriple()); 929 } else { 930 // Fill in what is missing in the triple 931 const llvm::Triple &remote_triple = process_arch.GetTriple(); 932 llvm::Triple new_target_triple = target_arch.GetTriple(); 933 if (new_target_triple.getVendorName().size() == 0) { 934 new_target_triple.setVendor(remote_triple.getVendor()); 935 936 if (new_target_triple.getOSName().size() == 0) { 937 new_target_triple.setOS(remote_triple.getOS()); 938 939 if (new_target_triple.getEnvironmentName().size() == 0) 940 new_target_triple.setEnvironment(remote_triple.getEnvironment()); 941 } 942 943 ArchSpec new_target_arch = target_arch; 944 new_target_arch.SetTriple(new_target_triple); 945 GetTarget().SetArchitecture(new_target_arch); 946 } 947 } 948 949 LLDB_LOG(log, 950 "final target arch after adjustments for remote architecture: " 951 "{0} {1}", 952 target_arch.GetArchitectureName(), 953 target_arch.GetTriple().getTriple()); 954 } else { 955 // The target doesn't have a valid architecture yet, set it from the 956 // architecture we got from the remote GDB server 957 GetTarget().SetArchitecture(process_arch); 958 } 959 } 960 961 // Target and Process are reasonably initailized; 962 // load any binaries we have metadata for / set load address. 963 LoadStubBinaries(); 964 MaybeLoadExecutableModule(); 965 966 // Find out which StructuredDataPlugins are supported by the debug monitor. 967 // These plugins transmit data over async $J packets. 968 if (StructuredData::Array *supported_packets = 969 m_gdb_comm.GetSupportedStructuredDataPlugins()) 970 MapSupportedStructuredDataPlugins(*supported_packets); 971 972 // If connected to LLDB ("native-signals+"), use signal defs for 973 // the remote platform. If connected to GDB, just use the standard set. 974 if (!m_gdb_comm.UsesNativeSignals()) { 975 SetUnixSignals(std::make_shared<GDBRemoteSignals>()); 976 } else { 977 PlatformSP platform_sp = GetTarget().GetPlatform(); 978 if (platform_sp && platform_sp->IsConnected()) 979 SetUnixSignals(platform_sp->GetUnixSignals()); 980 else 981 SetUnixSignals(UnixSignals::Create(GetTarget().GetArchitecture())); 982 } 983 } 984 985 void ProcessGDBRemote::LoadStubBinaries() { 986 // The remote stub may know about the "main binary" in 987 // the context of a firmware debug session, and can 988 // give us a UUID and an address/slide of where the 989 // binary is loaded in memory. 990 UUID standalone_uuid; 991 addr_t standalone_value; 992 bool standalone_value_is_offset; 993 if (m_gdb_comm.GetProcessStandaloneBinary(standalone_uuid, standalone_value, 994 standalone_value_is_offset)) { 995 ModuleSP module_sp; 996 997 if (standalone_uuid.IsValid()) { 998 const bool force_symbol_search = true; 999 const bool notify = true; 1000 const bool set_address_in_target = true; 1001 const bool allow_memory_image_last_resort = false; 1002 DynamicLoader::LoadBinaryWithUUIDAndAddress( 1003 this, "", standalone_uuid, standalone_value, 1004 standalone_value_is_offset, force_symbol_search, notify, 1005 set_address_in_target, allow_memory_image_last_resort); 1006 } 1007 } 1008 1009 // The remote stub may know about a list of binaries to 1010 // force load into the process -- a firmware type situation 1011 // where multiple binaries are present in virtual memory, 1012 // and we are only given the addresses of the binaries. 1013 // Not intended for use with userland debugging, when we use 1014 // a DynamicLoader plugin that knows how to find the loaded 1015 // binaries, and will track updates as binaries are added. 1016 1017 std::vector<addr_t> bin_addrs = m_gdb_comm.GetProcessStandaloneBinaries(); 1018 if (bin_addrs.size()) { 1019 UUID uuid; 1020 const bool value_is_slide = false; 1021 for (addr_t addr : bin_addrs) { 1022 const bool notify = true; 1023 // First see if this is a special platform 1024 // binary that may determine the DynamicLoader and 1025 // Platform to be used in this Process and Target. 1026 if (GetTarget() 1027 .GetDebugger() 1028 .GetPlatformList() 1029 .LoadPlatformBinaryAndSetup(this, addr, notify)) 1030 continue; 1031 1032 const bool force_symbol_search = true; 1033 const bool set_address_in_target = true; 1034 const bool allow_memory_image_last_resort = false; 1035 // Second manually load this binary into the Target. 1036 DynamicLoader::LoadBinaryWithUUIDAndAddress( 1037 this, llvm::StringRef(), uuid, addr, value_is_slide, 1038 force_symbol_search, notify, set_address_in_target, 1039 allow_memory_image_last_resort); 1040 } 1041 } 1042 } 1043 1044 void ProcessGDBRemote::MaybeLoadExecutableModule() { 1045 ModuleSP module_sp = GetTarget().GetExecutableModule(); 1046 if (!module_sp) 1047 return; 1048 1049 std::optional<QOffsets> offsets = m_gdb_comm.GetQOffsets(); 1050 if (!offsets) 1051 return; 1052 1053 bool is_uniform = 1054 size_t(llvm::count(offsets->offsets, offsets->offsets[0])) == 1055 offsets->offsets.size(); 1056 if (!is_uniform) 1057 return; // TODO: Handle non-uniform responses. 1058 1059 bool changed = false; 1060 module_sp->SetLoadAddress(GetTarget(), offsets->offsets[0], 1061 /*value_is_offset=*/true, changed); 1062 if (changed) { 1063 ModuleList list; 1064 list.Append(module_sp); 1065 m_process->GetTarget().ModulesDidLoad(list); 1066 } 1067 } 1068 1069 void ProcessGDBRemote::DidLaunch() { 1070 ArchSpec process_arch; 1071 DidLaunchOrAttach(process_arch); 1072 } 1073 1074 Status ProcessGDBRemote::DoAttachToProcessWithID( 1075 lldb::pid_t attach_pid, const ProcessAttachInfo &attach_info) { 1076 Log *log = GetLog(GDBRLog::Process); 1077 Status error; 1078 1079 LLDB_LOGF(log, "ProcessGDBRemote::%s()", __FUNCTION__); 1080 1081 // Clear out and clean up from any current state 1082 Clear(); 1083 if (attach_pid != LLDB_INVALID_PROCESS_ID) { 1084 error = EstablishConnectionIfNeeded(attach_info); 1085 if (error.Success()) { 1086 m_gdb_comm.SetDetachOnError(attach_info.GetDetachOnError()); 1087 1088 char packet[64]; 1089 const int packet_len = 1090 ::snprintf(packet, sizeof(packet), "vAttach;%" PRIx64, attach_pid); 1091 SetID(attach_pid); 1092 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 constexpr llvm::StringLiteral g_key_tid("tid"); 1930 static constexpr llvm::StringLiteral g_key_name("name"); 1931 static constexpr llvm::StringLiteral g_key_reason("reason"); 1932 static constexpr llvm::StringLiteral g_key_metype("metype"); 1933 static constexpr llvm::StringLiteral g_key_medata("medata"); 1934 static constexpr llvm::StringLiteral g_key_qaddr("qaddr"); 1935 static constexpr llvm::StringLiteral g_key_dispatch_queue_t( 1936 "dispatch_queue_t"); 1937 static constexpr llvm::StringLiteral g_key_associated_with_dispatch_queue( 1938 "associated_with_dispatch_queue"); 1939 static constexpr llvm::StringLiteral g_key_queue_name("qname"); 1940 static constexpr llvm::StringLiteral g_key_queue_kind("qkind"); 1941 static constexpr llvm::StringLiteral g_key_queue_serial_number("qserialnum"); 1942 static constexpr llvm::StringLiteral g_key_registers("registers"); 1943 static constexpr llvm::StringLiteral g_key_memory("memory"); 1944 static constexpr llvm::StringLiteral g_key_description("description"); 1945 static constexpr llvm::StringLiteral g_key_signal("signal"); 1946 1947 // Stop with signal and thread info 1948 lldb::tid_t tid = LLDB_INVALID_THREAD_ID; 1949 uint8_t signo = 0; 1950 std::string value; 1951 std::string thread_name; 1952 std::string reason; 1953 std::string description; 1954 uint32_t exc_type = 0; 1955 std::vector<addr_t> exc_data; 1956 addr_t thread_dispatch_qaddr = LLDB_INVALID_ADDRESS; 1957 ExpeditedRegisterMap expedited_register_map; 1958 bool queue_vars_valid = false; 1959 addr_t dispatch_queue_t = LLDB_INVALID_ADDRESS; 1960 LazyBool associated_with_dispatch_queue = eLazyBoolCalculate; 1961 std::string queue_name; 1962 QueueKind queue_kind = eQueueKindUnknown; 1963 uint64_t queue_serial_number = 0; 1964 // Iterate through all of the thread dictionary key/value pairs from the 1965 // structured data dictionary 1966 1967 // FIXME: we're silently ignoring invalid data here 1968 thread_dict->ForEach([this, &tid, &expedited_register_map, &thread_name, 1969 &signo, &reason, &description, &exc_type, &exc_data, 1970 &thread_dispatch_qaddr, &queue_vars_valid, 1971 &associated_with_dispatch_queue, &dispatch_queue_t, 1972 &queue_name, &queue_kind, &queue_serial_number]( 1973 llvm::StringRef key, 1974 StructuredData::Object *object) -> bool { 1975 if (key == g_key_tid) { 1976 // thread in big endian hex 1977 tid = object->GetUnsignedIntegerValue(LLDB_INVALID_THREAD_ID); 1978 } else if (key == g_key_metype) { 1979 // exception type in big endian hex 1980 exc_type = object->GetUnsignedIntegerValue(0); 1981 } else if (key == g_key_medata) { 1982 // exception data in big endian hex 1983 StructuredData::Array *array = object->GetAsArray(); 1984 if (array) { 1985 array->ForEach([&exc_data](StructuredData::Object *object) -> bool { 1986 exc_data.push_back(object->GetUnsignedIntegerValue()); 1987 return true; // Keep iterating through all array items 1988 }); 1989 } 1990 } else if (key == g_key_name) { 1991 thread_name = std::string(object->GetStringValue()); 1992 } else if (key == g_key_qaddr) { 1993 thread_dispatch_qaddr = 1994 object->GetUnsignedIntegerValue(LLDB_INVALID_ADDRESS); 1995 } else if (key == g_key_queue_name) { 1996 queue_vars_valid = true; 1997 queue_name = std::string(object->GetStringValue()); 1998 } else if (key == g_key_queue_kind) { 1999 std::string queue_kind_str = std::string(object->GetStringValue()); 2000 if (queue_kind_str == "serial") { 2001 queue_vars_valid = true; 2002 queue_kind = eQueueKindSerial; 2003 } else if (queue_kind_str == "concurrent") { 2004 queue_vars_valid = true; 2005 queue_kind = eQueueKindConcurrent; 2006 } 2007 } else if (key == g_key_queue_serial_number) { 2008 queue_serial_number = object->GetUnsignedIntegerValue(0); 2009 if (queue_serial_number != 0) 2010 queue_vars_valid = true; 2011 } else if (key == g_key_dispatch_queue_t) { 2012 dispatch_queue_t = object->GetUnsignedIntegerValue(0); 2013 if (dispatch_queue_t != 0 && dispatch_queue_t != LLDB_INVALID_ADDRESS) 2014 queue_vars_valid = true; 2015 } else if (key == g_key_associated_with_dispatch_queue) { 2016 queue_vars_valid = true; 2017 bool associated = object->GetBooleanValue(); 2018 if (associated) 2019 associated_with_dispatch_queue = eLazyBoolYes; 2020 else 2021 associated_with_dispatch_queue = eLazyBoolNo; 2022 } else if (key == g_key_reason) { 2023 reason = std::string(object->GetStringValue()); 2024 } else if (key == g_key_description) { 2025 description = std::string(object->GetStringValue()); 2026 } else if (key == g_key_registers) { 2027 StructuredData::Dictionary *registers_dict = object->GetAsDictionary(); 2028 2029 if (registers_dict) { 2030 registers_dict->ForEach( 2031 [&expedited_register_map](llvm::StringRef key, 2032 StructuredData::Object *object) -> bool { 2033 uint32_t reg; 2034 if (llvm::to_integer(key, reg)) 2035 expedited_register_map[reg] = 2036 std::string(object->GetStringValue()); 2037 return true; // Keep iterating through all array items 2038 }); 2039 } 2040 } else if (key == g_key_memory) { 2041 StructuredData::Array *array = object->GetAsArray(); 2042 if (array) { 2043 array->ForEach([this](StructuredData::Object *object) -> bool { 2044 StructuredData::Dictionary *mem_cache_dict = 2045 object->GetAsDictionary(); 2046 if (mem_cache_dict) { 2047 lldb::addr_t mem_cache_addr = LLDB_INVALID_ADDRESS; 2048 if (mem_cache_dict->GetValueForKeyAsInteger<lldb::addr_t>( 2049 "address", mem_cache_addr)) { 2050 if (mem_cache_addr != LLDB_INVALID_ADDRESS) { 2051 llvm::StringRef str; 2052 if (mem_cache_dict->GetValueForKeyAsString("bytes", str)) { 2053 StringExtractor bytes(str); 2054 bytes.SetFilePos(0); 2055 2056 const size_t byte_size = bytes.GetStringRef().size() / 2; 2057 WritableDataBufferSP data_buffer_sp( 2058 new DataBufferHeap(byte_size, 0)); 2059 const size_t bytes_copied = 2060 bytes.GetHexBytes(data_buffer_sp->GetData(), 0); 2061 if (bytes_copied == byte_size) 2062 m_memory_cache.AddL1CacheData(mem_cache_addr, 2063 data_buffer_sp); 2064 } 2065 } 2066 } 2067 } 2068 return true; // Keep iterating through all array items 2069 }); 2070 } 2071 2072 } else if (key == g_key_signal) 2073 signo = object->GetUnsignedIntegerValue(LLDB_INVALID_SIGNAL_NUMBER); 2074 return true; // Keep iterating through all dictionary key/value pairs 2075 }); 2076 2077 return SetThreadStopInfo(tid, expedited_register_map, signo, thread_name, 2078 reason, description, exc_type, exc_data, 2079 thread_dispatch_qaddr, queue_vars_valid, 2080 associated_with_dispatch_queue, dispatch_queue_t, 2081 queue_name, queue_kind, queue_serial_number); 2082 } 2083 2084 StateType ProcessGDBRemote::SetThreadStopInfo(StringExtractor &stop_packet) { 2085 lldb::pid_t pid = m_gdb_comm.GetCurrentProcessID(); 2086 stop_packet.SetFilePos(0); 2087 const char stop_type = stop_packet.GetChar(); 2088 switch (stop_type) { 2089 case 'T': 2090 case 'S': { 2091 // This is a bit of a hack, but it is required. If we did exec, we need to 2092 // clear our thread lists and also know to rebuild our dynamic register 2093 // info before we lookup and threads and populate the expedited register 2094 // values so we need to know this right away so we can cleanup and update 2095 // our registers. 2096 const uint32_t stop_id = GetStopID(); 2097 if (stop_id == 0) { 2098 // Our first stop, make sure we have a process ID, and also make sure we 2099 // know about our registers 2100 if (GetID() == LLDB_INVALID_PROCESS_ID && pid != LLDB_INVALID_PROCESS_ID) 2101 SetID(pid); 2102 BuildDynamicRegisterInfo(true); 2103 } 2104 // Stop with signal and thread info 2105 lldb::pid_t stop_pid = LLDB_INVALID_PROCESS_ID; 2106 lldb::tid_t tid = LLDB_INVALID_THREAD_ID; 2107 const uint8_t signo = stop_packet.GetHexU8(); 2108 llvm::StringRef key; 2109 llvm::StringRef value; 2110 std::string thread_name; 2111 std::string reason; 2112 std::string description; 2113 uint32_t exc_type = 0; 2114 std::vector<addr_t> exc_data; 2115 addr_t thread_dispatch_qaddr = LLDB_INVALID_ADDRESS; 2116 bool queue_vars_valid = 2117 false; // says if locals below that start with "queue_" are valid 2118 addr_t dispatch_queue_t = LLDB_INVALID_ADDRESS; 2119 LazyBool associated_with_dispatch_queue = eLazyBoolCalculate; 2120 std::string queue_name; 2121 QueueKind queue_kind = eQueueKindUnknown; 2122 uint64_t queue_serial_number = 0; 2123 ExpeditedRegisterMap expedited_register_map; 2124 AddressableBits addressable_bits; 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 addressable_bits.SetAddressableBits(addressing_bits); 2273 } 2274 } else if (key.compare("low_mem_addressing_bits") == 0) { 2275 uint64_t addressing_bits; 2276 if (!value.getAsInteger(0, addressing_bits)) { 2277 addressable_bits.SetLowmemAddressableBits(addressing_bits); 2278 } 2279 } else if (key.compare("high_mem_addressing_bits") == 0) { 2280 uint64_t addressing_bits; 2281 if (!value.getAsInteger(0, addressing_bits)) { 2282 addressable_bits.SetHighmemAddressableBits(addressing_bits); 2283 } 2284 } else if (key.size() == 2 && ::isxdigit(key[0]) && ::isxdigit(key[1])) { 2285 uint32_t reg = UINT32_MAX; 2286 if (!key.getAsInteger(16, reg)) 2287 expedited_register_map[reg] = std::string(std::move(value)); 2288 } 2289 } 2290 2291 if (stop_pid != LLDB_INVALID_PROCESS_ID && stop_pid != pid) { 2292 Log *log = GetLog(GDBRLog::Process); 2293 LLDB_LOG(log, 2294 "Received stop for incorrect PID = {0} (inferior PID = {1})", 2295 stop_pid, pid); 2296 return eStateInvalid; 2297 } 2298 2299 if (tid == LLDB_INVALID_THREAD_ID) { 2300 // A thread id may be invalid if the response is old style 'S' packet 2301 // which does not provide the 2302 // thread information. So update the thread list and choose the first 2303 // one. 2304 UpdateThreadIDList(); 2305 2306 if (!m_thread_ids.empty()) { 2307 tid = m_thread_ids.front(); 2308 } 2309 } 2310 2311 addressable_bits.SetProcessMasks(*this); 2312 2313 ThreadSP thread_sp = SetThreadStopInfo( 2314 tid, expedited_register_map, signo, thread_name, reason, description, 2315 exc_type, exc_data, thread_dispatch_qaddr, queue_vars_valid, 2316 associated_with_dispatch_queue, dispatch_queue_t, queue_name, 2317 queue_kind, queue_serial_number); 2318 2319 return eStateStopped; 2320 } break; 2321 2322 case 'W': 2323 case 'X': 2324 // process exited 2325 return eStateExited; 2326 2327 default: 2328 break; 2329 } 2330 return eStateInvalid; 2331 } 2332 2333 void ProcessGDBRemote::RefreshStateAfterStop() { 2334 std::lock_guard<std::recursive_mutex> guard(m_thread_list_real.GetMutex()); 2335 2336 m_thread_ids.clear(); 2337 m_thread_pcs.clear(); 2338 2339 // Set the thread stop info. It might have a "threads" key whose value is a 2340 // list of all thread IDs in the current process, so m_thread_ids might get 2341 // set. 2342 // Check to see if SetThreadStopInfo() filled in m_thread_ids? 2343 if (m_thread_ids.empty()) { 2344 // No, we need to fetch the thread list manually 2345 UpdateThreadIDList(); 2346 } 2347 2348 // We might set some stop info's so make sure the thread list is up to 2349 // date before we do that or we might overwrite what was computed here. 2350 UpdateThreadListIfNeeded(); 2351 2352 if (m_last_stop_packet) 2353 SetThreadStopInfo(*m_last_stop_packet); 2354 m_last_stop_packet.reset(); 2355 2356 // If we have queried for a default thread id 2357 if (m_initial_tid != LLDB_INVALID_THREAD_ID) { 2358 m_thread_list.SetSelectedThreadByID(m_initial_tid); 2359 m_initial_tid = LLDB_INVALID_THREAD_ID; 2360 } 2361 2362 // Let all threads recover from stopping and do any clean up based on the 2363 // previous thread state (if any). 2364 m_thread_list_real.RefreshStateAfterStop(); 2365 } 2366 2367 Status ProcessGDBRemote::DoHalt(bool &caused_stop) { 2368 Status error; 2369 2370 if (m_public_state.GetValue() == eStateAttaching) { 2371 // We are being asked to halt during an attach. We need to just close our 2372 // file handle and debugserver will go away, and we can be done... 2373 m_gdb_comm.Disconnect(); 2374 } else 2375 caused_stop = m_gdb_comm.Interrupt(GetInterruptTimeout()); 2376 return error; 2377 } 2378 2379 Status ProcessGDBRemote::DoDetach(bool keep_stopped) { 2380 Status error; 2381 Log *log = GetLog(GDBRLog::Process); 2382 LLDB_LOGF(log, "ProcessGDBRemote::DoDetach(keep_stopped: %i)", keep_stopped); 2383 2384 error = m_gdb_comm.Detach(keep_stopped); 2385 if (log) { 2386 if (error.Success()) 2387 log->PutCString( 2388 "ProcessGDBRemote::DoDetach() detach packet sent successfully"); 2389 else 2390 LLDB_LOGF(log, 2391 "ProcessGDBRemote::DoDetach() detach packet send failed: %s", 2392 error.AsCString() ? error.AsCString() : "<unknown error>"); 2393 } 2394 2395 if (!error.Success()) 2396 return error; 2397 2398 // Sleep for one second to let the process get all detached... 2399 StopAsyncThread(); 2400 2401 SetPrivateState(eStateDetached); 2402 ResumePrivateStateThread(); 2403 2404 // KillDebugserverProcess (); 2405 return error; 2406 } 2407 2408 Status ProcessGDBRemote::DoDestroy() { 2409 Log *log = GetLog(GDBRLog::Process); 2410 LLDB_LOGF(log, "ProcessGDBRemote::DoDestroy()"); 2411 2412 // Interrupt if our inferior is running... 2413 int exit_status = SIGABRT; 2414 std::string exit_string; 2415 2416 if (m_gdb_comm.IsConnected()) { 2417 if (m_public_state.GetValue() != eStateAttaching) { 2418 llvm::Expected<int> kill_res = m_gdb_comm.KillProcess(GetID()); 2419 2420 if (kill_res) { 2421 exit_status = kill_res.get(); 2422 #if defined(__APPLE__) 2423 // For Native processes on Mac OS X, we launch through the Host 2424 // Platform, then hand the process off to debugserver, which becomes 2425 // the parent process through "PT_ATTACH". Then when we go to kill 2426 // the process on Mac OS X we call ptrace(PT_KILL) to kill it, then 2427 // we call waitpid which returns with no error and the correct 2428 // status. But amusingly enough that doesn't seem to actually reap 2429 // the process, but instead it is left around as a Zombie. Probably 2430 // the kernel is in the process of switching ownership back to lldb 2431 // which was the original parent, and gets confused in the handoff. 2432 // Anyway, so call waitpid here to finally reap it. 2433 PlatformSP platform_sp(GetTarget().GetPlatform()); 2434 if (platform_sp && platform_sp->IsHost()) { 2435 int status; 2436 ::pid_t reap_pid; 2437 reap_pid = waitpid(GetID(), &status, WNOHANG); 2438 LLDB_LOGF(log, "Reaped pid: %d, status: %d.\n", reap_pid, status); 2439 } 2440 #endif 2441 ClearThreadIDList(); 2442 exit_string.assign("killed"); 2443 } else { 2444 exit_string.assign(llvm::toString(kill_res.takeError())); 2445 } 2446 } else { 2447 exit_string.assign("killed or interrupted while attaching."); 2448 } 2449 } else { 2450 // If we missed setting the exit status on the way out, do it here. 2451 // NB set exit status can be called multiple times, the first one sets the 2452 // status. 2453 exit_string.assign("destroying when not connected to debugserver"); 2454 } 2455 2456 SetExitStatus(exit_status, exit_string.c_str()); 2457 2458 StopAsyncThread(); 2459 KillDebugserverProcess(); 2460 return Status(); 2461 } 2462 2463 void ProcessGDBRemote::SetLastStopPacket( 2464 const StringExtractorGDBRemote &response) { 2465 const bool did_exec = 2466 response.GetStringRef().find(";reason:exec;") != std::string::npos; 2467 if (did_exec) { 2468 Log *log = GetLog(GDBRLog::Process); 2469 LLDB_LOGF(log, "ProcessGDBRemote::SetLastStopPacket () - detected exec"); 2470 2471 m_thread_list_real.Clear(); 2472 m_thread_list.Clear(); 2473 BuildDynamicRegisterInfo(true); 2474 m_gdb_comm.ResetDiscoverableSettings(did_exec); 2475 } 2476 2477 m_last_stop_packet = response; 2478 } 2479 2480 void ProcessGDBRemote::SetUnixSignals(const UnixSignalsSP &signals_sp) { 2481 Process::SetUnixSignals(std::make_shared<GDBRemoteSignals>(signals_sp)); 2482 } 2483 2484 // Process Queries 2485 2486 bool ProcessGDBRemote::IsAlive() { 2487 return m_gdb_comm.IsConnected() && Process::IsAlive(); 2488 } 2489 2490 addr_t ProcessGDBRemote::GetImageInfoAddress() { 2491 // request the link map address via the $qShlibInfoAddr packet 2492 lldb::addr_t addr = m_gdb_comm.GetShlibInfoAddr(); 2493 2494 // the loaded module list can also provides a link map address 2495 if (addr == LLDB_INVALID_ADDRESS) { 2496 llvm::Expected<LoadedModuleInfoList> list = GetLoadedModuleList(); 2497 if (!list) { 2498 Log *log = GetLog(GDBRLog::Process); 2499 LLDB_LOG_ERROR(log, list.takeError(), "Failed to read module list: {0}."); 2500 } else { 2501 addr = list->m_link_map; 2502 } 2503 } 2504 2505 return addr; 2506 } 2507 2508 void ProcessGDBRemote::WillPublicStop() { 2509 // See if the GDB remote client supports the JSON threads info. If so, we 2510 // gather stop info for all threads, expedited registers, expedited memory, 2511 // runtime queue information (iOS and MacOSX only), and more. Expediting 2512 // memory will help stack backtracing be much faster. Expediting registers 2513 // will make sure we don't have to read the thread registers for GPRs. 2514 m_jthreadsinfo_sp = m_gdb_comm.GetThreadsInfo(); 2515 2516 if (m_jthreadsinfo_sp) { 2517 // Now set the stop info for each thread and also expedite any registers 2518 // and memory that was in the jThreadsInfo response. 2519 StructuredData::Array *thread_infos = m_jthreadsinfo_sp->GetAsArray(); 2520 if (thread_infos) { 2521 const size_t n = thread_infos->GetSize(); 2522 for (size_t i = 0; i < n; ++i) { 2523 StructuredData::Dictionary *thread_dict = 2524 thread_infos->GetItemAtIndex(i)->GetAsDictionary(); 2525 if (thread_dict) 2526 SetThreadStopInfo(thread_dict); 2527 } 2528 } 2529 } 2530 } 2531 2532 // Process Memory 2533 size_t ProcessGDBRemote::DoReadMemory(addr_t addr, void *buf, size_t size, 2534 Status &error) { 2535 GetMaxMemorySize(); 2536 bool binary_memory_read = m_gdb_comm.GetxPacketSupported(); 2537 // M and m packets take 2 bytes for 1 byte of memory 2538 size_t max_memory_size = 2539 binary_memory_read ? m_max_memory_size : m_max_memory_size / 2; 2540 if (size > max_memory_size) { 2541 // Keep memory read sizes down to a sane limit. This function will be 2542 // called multiple times in order to complete the task by 2543 // lldb_private::Process so it is ok to do this. 2544 size = max_memory_size; 2545 } 2546 2547 char packet[64]; 2548 int packet_len; 2549 packet_len = ::snprintf(packet, sizeof(packet), "%c%" PRIx64 ",%" PRIx64, 2550 binary_memory_read ? 'x' : 'm', (uint64_t)addr, 2551 (uint64_t)size); 2552 assert(packet_len + 1 < (int)sizeof(packet)); 2553 UNUSED_IF_ASSERT_DISABLED(packet_len); 2554 StringExtractorGDBRemote response; 2555 if (m_gdb_comm.SendPacketAndWaitForResponse(packet, response, 2556 GetInterruptTimeout()) == 2557 GDBRemoteCommunication::PacketResult::Success) { 2558 if (response.IsNormalResponse()) { 2559 error.Clear(); 2560 if (binary_memory_read) { 2561 // The lower level GDBRemoteCommunication packet receive layer has 2562 // already de-quoted any 0x7d character escaping that was present in 2563 // the packet 2564 2565 size_t data_received_size = response.GetBytesLeft(); 2566 if (data_received_size > size) { 2567 // Don't write past the end of BUF if the remote debug server gave us 2568 // too much data for some reason. 2569 data_received_size = size; 2570 } 2571 memcpy(buf, response.GetStringRef().data(), data_received_size); 2572 return data_received_size; 2573 } else { 2574 return response.GetHexBytes( 2575 llvm::MutableArrayRef<uint8_t>((uint8_t *)buf, size), '\xdd'); 2576 } 2577 } else if (response.IsErrorResponse()) 2578 error.SetErrorStringWithFormat("memory read failed for 0x%" PRIx64, addr); 2579 else if (response.IsUnsupportedResponse()) 2580 error.SetErrorStringWithFormat( 2581 "GDB server does not support reading memory"); 2582 else 2583 error.SetErrorStringWithFormat( 2584 "unexpected response to GDB server memory read packet '%s': '%s'", 2585 packet, response.GetStringRef().data()); 2586 } else { 2587 error.SetErrorStringWithFormat("failed to send packet: '%s'", packet); 2588 } 2589 return 0; 2590 } 2591 2592 bool ProcessGDBRemote::SupportsMemoryTagging() { 2593 return m_gdb_comm.GetMemoryTaggingSupported(); 2594 } 2595 2596 llvm::Expected<std::vector<uint8_t>> 2597 ProcessGDBRemote::DoReadMemoryTags(lldb::addr_t addr, size_t len, 2598 int32_t type) { 2599 // By this point ReadMemoryTags has validated that tagging is enabled 2600 // for this target/process/address. 2601 DataBufferSP buffer_sp = m_gdb_comm.ReadMemoryTags(addr, len, type); 2602 if (!buffer_sp) { 2603 return llvm::createStringError(llvm::inconvertibleErrorCode(), 2604 "Error reading memory tags from remote"); 2605 } 2606 2607 // Return the raw tag data 2608 llvm::ArrayRef<uint8_t> tag_data = buffer_sp->GetData(); 2609 std::vector<uint8_t> got; 2610 got.reserve(tag_data.size()); 2611 std::copy(tag_data.begin(), tag_data.end(), std::back_inserter(got)); 2612 return got; 2613 } 2614 2615 Status ProcessGDBRemote::DoWriteMemoryTags(lldb::addr_t addr, size_t len, 2616 int32_t type, 2617 const std::vector<uint8_t> &tags) { 2618 // By now WriteMemoryTags should have validated that tagging is enabled 2619 // for this target/process. 2620 return m_gdb_comm.WriteMemoryTags(addr, len, type, tags); 2621 } 2622 2623 Status ProcessGDBRemote::WriteObjectFile( 2624 std::vector<ObjectFile::LoadableData> entries) { 2625 Status error; 2626 // Sort the entries by address because some writes, like those to flash 2627 // memory, must happen in order of increasing address. 2628 std::stable_sort( 2629 std::begin(entries), std::end(entries), 2630 [](const ObjectFile::LoadableData a, const ObjectFile::LoadableData b) { 2631 return a.Dest < b.Dest; 2632 }); 2633 m_allow_flash_writes = true; 2634 error = Process::WriteObjectFile(entries); 2635 if (error.Success()) 2636 error = FlashDone(); 2637 else 2638 // Even though some of the writing failed, try to send a flash done if some 2639 // of the writing succeeded so the flash state is reset to normal, but 2640 // don't stomp on the error status that was set in the write failure since 2641 // that's the one we want to report back. 2642 FlashDone(); 2643 m_allow_flash_writes = false; 2644 return error; 2645 } 2646 2647 bool ProcessGDBRemote::HasErased(FlashRange range) { 2648 auto size = m_erased_flash_ranges.GetSize(); 2649 for (size_t i = 0; i < size; ++i) 2650 if (m_erased_flash_ranges.GetEntryAtIndex(i)->Contains(range)) 2651 return true; 2652 return false; 2653 } 2654 2655 Status ProcessGDBRemote::FlashErase(lldb::addr_t addr, size_t size) { 2656 Status status; 2657 2658 MemoryRegionInfo region; 2659 status = GetMemoryRegionInfo(addr, region); 2660 if (!status.Success()) 2661 return status; 2662 2663 // The gdb spec doesn't say if erasures are allowed across multiple regions, 2664 // but we'll disallow it to be safe and to keep the logic simple by worring 2665 // about only one region's block size. DoMemoryWrite is this function's 2666 // primary user, and it can easily keep writes within a single memory region 2667 if (addr + size > region.GetRange().GetRangeEnd()) { 2668 status.SetErrorString("Unable to erase flash in multiple regions"); 2669 return status; 2670 } 2671 2672 uint64_t blocksize = region.GetBlocksize(); 2673 if (blocksize == 0) { 2674 status.SetErrorString("Unable to erase flash because blocksize is 0"); 2675 return status; 2676 } 2677 2678 // Erasures can only be done on block boundary adresses, so round down addr 2679 // and round up size 2680 lldb::addr_t block_start_addr = addr - (addr % blocksize); 2681 size += (addr - block_start_addr); 2682 if ((size % blocksize) != 0) 2683 size += (blocksize - size % blocksize); 2684 2685 FlashRange range(block_start_addr, size); 2686 2687 if (HasErased(range)) 2688 return status; 2689 2690 // We haven't erased the entire range, but we may have erased part of it. 2691 // (e.g., block A is already erased and range starts in A and ends in B). So, 2692 // adjust range if necessary to exclude already erased blocks. 2693 if (!m_erased_flash_ranges.IsEmpty()) { 2694 // Assuming that writes and erasures are done in increasing addr order, 2695 // because that is a requirement of the vFlashWrite command. Therefore, we 2696 // only need to look at the last range in the list for overlap. 2697 const auto &last_range = *m_erased_flash_ranges.Back(); 2698 if (range.GetRangeBase() < last_range.GetRangeEnd()) { 2699 auto overlap = last_range.GetRangeEnd() - range.GetRangeBase(); 2700 // overlap will be less than range.GetByteSize() or else HasErased() 2701 // would have been true 2702 range.SetByteSize(range.GetByteSize() - overlap); 2703 range.SetRangeBase(range.GetRangeBase() + overlap); 2704 } 2705 } 2706 2707 StreamString packet; 2708 packet.Printf("vFlashErase:%" PRIx64 ",%" PRIx64, range.GetRangeBase(), 2709 (uint64_t)range.GetByteSize()); 2710 2711 StringExtractorGDBRemote response; 2712 if (m_gdb_comm.SendPacketAndWaitForResponse(packet.GetString(), response, 2713 GetInterruptTimeout()) == 2714 GDBRemoteCommunication::PacketResult::Success) { 2715 if (response.IsOKResponse()) { 2716 m_erased_flash_ranges.Insert(range, true); 2717 } else { 2718 if (response.IsErrorResponse()) 2719 status.SetErrorStringWithFormat("flash erase failed for 0x%" PRIx64, 2720 addr); 2721 else if (response.IsUnsupportedResponse()) 2722 status.SetErrorStringWithFormat("GDB server does not support flashing"); 2723 else 2724 status.SetErrorStringWithFormat( 2725 "unexpected response to GDB server flash erase packet '%s': '%s'", 2726 packet.GetData(), response.GetStringRef().data()); 2727 } 2728 } else { 2729 status.SetErrorStringWithFormat("failed to send packet: '%s'", 2730 packet.GetData()); 2731 } 2732 return status; 2733 } 2734 2735 Status ProcessGDBRemote::FlashDone() { 2736 Status status; 2737 // If we haven't erased any blocks, then we must not have written anything 2738 // either, so there is no need to actually send a vFlashDone command 2739 if (m_erased_flash_ranges.IsEmpty()) 2740 return status; 2741 StringExtractorGDBRemote response; 2742 if (m_gdb_comm.SendPacketAndWaitForResponse("vFlashDone", response, 2743 GetInterruptTimeout()) == 2744 GDBRemoteCommunication::PacketResult::Success) { 2745 if (response.IsOKResponse()) { 2746 m_erased_flash_ranges.Clear(); 2747 } else { 2748 if (response.IsErrorResponse()) 2749 status.SetErrorStringWithFormat("flash done failed"); 2750 else if (response.IsUnsupportedResponse()) 2751 status.SetErrorStringWithFormat("GDB server does not support flashing"); 2752 else 2753 status.SetErrorStringWithFormat( 2754 "unexpected response to GDB server flash done packet: '%s'", 2755 response.GetStringRef().data()); 2756 } 2757 } else { 2758 status.SetErrorStringWithFormat("failed to send flash done packet"); 2759 } 2760 return status; 2761 } 2762 2763 size_t ProcessGDBRemote::DoWriteMemory(addr_t addr, const void *buf, 2764 size_t size, Status &error) { 2765 GetMaxMemorySize(); 2766 // M and m packets take 2 bytes for 1 byte of memory 2767 size_t max_memory_size = m_max_memory_size / 2; 2768 if (size > max_memory_size) { 2769 // Keep memory read sizes down to a sane limit. This function will be 2770 // called multiple times in order to complete the task by 2771 // lldb_private::Process so it is ok to do this. 2772 size = max_memory_size; 2773 } 2774 2775 StreamGDBRemote packet; 2776 2777 MemoryRegionInfo region; 2778 Status region_status = GetMemoryRegionInfo(addr, region); 2779 2780 bool is_flash = 2781 region_status.Success() && region.GetFlash() == MemoryRegionInfo::eYes; 2782 2783 if (is_flash) { 2784 if (!m_allow_flash_writes) { 2785 error.SetErrorString("Writing to flash memory is not allowed"); 2786 return 0; 2787 } 2788 // Keep the write within a flash memory region 2789 if (addr + size > region.GetRange().GetRangeEnd()) 2790 size = region.GetRange().GetRangeEnd() - addr; 2791 // Flash memory must be erased before it can be written 2792 error = FlashErase(addr, size); 2793 if (!error.Success()) 2794 return 0; 2795 packet.Printf("vFlashWrite:%" PRIx64 ":", addr); 2796 packet.PutEscapedBytes(buf, size); 2797 } else { 2798 packet.Printf("M%" PRIx64 ",%" PRIx64 ":", addr, (uint64_t)size); 2799 packet.PutBytesAsRawHex8(buf, size, endian::InlHostByteOrder(), 2800 endian::InlHostByteOrder()); 2801 } 2802 StringExtractorGDBRemote response; 2803 if (m_gdb_comm.SendPacketAndWaitForResponse(packet.GetString(), response, 2804 GetInterruptTimeout()) == 2805 GDBRemoteCommunication::PacketResult::Success) { 2806 if (response.IsOKResponse()) { 2807 error.Clear(); 2808 return size; 2809 } else if (response.IsErrorResponse()) 2810 error.SetErrorStringWithFormat("memory write failed for 0x%" PRIx64, 2811 addr); 2812 else if (response.IsUnsupportedResponse()) 2813 error.SetErrorStringWithFormat( 2814 "GDB server does not support writing memory"); 2815 else 2816 error.SetErrorStringWithFormat( 2817 "unexpected response to GDB server memory write packet '%s': '%s'", 2818 packet.GetData(), response.GetStringRef().data()); 2819 } else { 2820 error.SetErrorStringWithFormat("failed to send packet: '%s'", 2821 packet.GetData()); 2822 } 2823 return 0; 2824 } 2825 2826 lldb::addr_t ProcessGDBRemote::DoAllocateMemory(size_t size, 2827 uint32_t permissions, 2828 Status &error) { 2829 Log *log = GetLog(LLDBLog::Process | LLDBLog::Expressions); 2830 addr_t allocated_addr = LLDB_INVALID_ADDRESS; 2831 2832 if (m_gdb_comm.SupportsAllocDeallocMemory() != eLazyBoolNo) { 2833 allocated_addr = m_gdb_comm.AllocateMemory(size, permissions); 2834 if (allocated_addr != LLDB_INVALID_ADDRESS || 2835 m_gdb_comm.SupportsAllocDeallocMemory() == eLazyBoolYes) 2836 return allocated_addr; 2837 } 2838 2839 if (m_gdb_comm.SupportsAllocDeallocMemory() == eLazyBoolNo) { 2840 // Call mmap() to create memory in the inferior.. 2841 unsigned prot = 0; 2842 if (permissions & lldb::ePermissionsReadable) 2843 prot |= eMmapProtRead; 2844 if (permissions & lldb::ePermissionsWritable) 2845 prot |= eMmapProtWrite; 2846 if (permissions & lldb::ePermissionsExecutable) 2847 prot |= eMmapProtExec; 2848 2849 if (InferiorCallMmap(this, allocated_addr, 0, size, prot, 2850 eMmapFlagsAnon | eMmapFlagsPrivate, -1, 0)) 2851 m_addr_to_mmap_size[allocated_addr] = size; 2852 else { 2853 allocated_addr = LLDB_INVALID_ADDRESS; 2854 LLDB_LOGF(log, 2855 "ProcessGDBRemote::%s no direct stub support for memory " 2856 "allocation, and InferiorCallMmap also failed - is stub " 2857 "missing register context save/restore capability?", 2858 __FUNCTION__); 2859 } 2860 } 2861 2862 if (allocated_addr == LLDB_INVALID_ADDRESS) 2863 error.SetErrorStringWithFormat( 2864 "unable to allocate %" PRIu64 " bytes of memory with permissions %s", 2865 (uint64_t)size, GetPermissionsAsCString(permissions)); 2866 else 2867 error.Clear(); 2868 return allocated_addr; 2869 } 2870 2871 Status ProcessGDBRemote::DoGetMemoryRegionInfo(addr_t load_addr, 2872 MemoryRegionInfo ®ion_info) { 2873 2874 Status error(m_gdb_comm.GetMemoryRegionInfo(load_addr, region_info)); 2875 return error; 2876 } 2877 2878 std::optional<uint32_t> ProcessGDBRemote::GetWatchpointSlotCount() { 2879 return m_gdb_comm.GetWatchpointSlotCount(); 2880 } 2881 2882 std::optional<bool> ProcessGDBRemote::DoGetWatchpointReportedAfter() { 2883 return m_gdb_comm.GetWatchpointReportedAfter(); 2884 } 2885 2886 Status ProcessGDBRemote::DoDeallocateMemory(lldb::addr_t addr) { 2887 Status error; 2888 LazyBool supported = m_gdb_comm.SupportsAllocDeallocMemory(); 2889 2890 switch (supported) { 2891 case eLazyBoolCalculate: 2892 // We should never be deallocating memory without allocating memory first 2893 // so we should never get eLazyBoolCalculate 2894 error.SetErrorString( 2895 "tried to deallocate memory without ever allocating memory"); 2896 break; 2897 2898 case eLazyBoolYes: 2899 if (!m_gdb_comm.DeallocateMemory(addr)) 2900 error.SetErrorStringWithFormat( 2901 "unable to deallocate memory at 0x%" PRIx64, addr); 2902 break; 2903 2904 case eLazyBoolNo: 2905 // Call munmap() to deallocate memory in the inferior.. 2906 { 2907 MMapMap::iterator pos = m_addr_to_mmap_size.find(addr); 2908 if (pos != m_addr_to_mmap_size.end() && 2909 InferiorCallMunmap(this, addr, pos->second)) 2910 m_addr_to_mmap_size.erase(pos); 2911 else 2912 error.SetErrorStringWithFormat( 2913 "unable to deallocate memory at 0x%" PRIx64, addr); 2914 } 2915 break; 2916 } 2917 2918 return error; 2919 } 2920 2921 // Process STDIO 2922 size_t ProcessGDBRemote::PutSTDIN(const char *src, size_t src_len, 2923 Status &error) { 2924 if (m_stdio_communication.IsConnected()) { 2925 ConnectionStatus status; 2926 m_stdio_communication.WriteAll(src, src_len, status, nullptr); 2927 } else if (m_stdin_forward) { 2928 m_gdb_comm.SendStdinNotification(src, src_len); 2929 } 2930 return 0; 2931 } 2932 2933 Status ProcessGDBRemote::EnableBreakpointSite(BreakpointSite *bp_site) { 2934 Status error; 2935 assert(bp_site != nullptr); 2936 2937 // Get logging info 2938 Log *log = GetLog(GDBRLog::Breakpoints); 2939 user_id_t site_id = bp_site->GetID(); 2940 2941 // Get the breakpoint address 2942 const addr_t addr = bp_site->GetLoadAddress(); 2943 2944 // Log that a breakpoint was requested 2945 LLDB_LOGF(log, 2946 "ProcessGDBRemote::EnableBreakpointSite (size_id = %" PRIu64 2947 ") address = 0x%" PRIx64, 2948 site_id, (uint64_t)addr); 2949 2950 // Breakpoint already exists and is enabled 2951 if (bp_site->IsEnabled()) { 2952 LLDB_LOGF(log, 2953 "ProcessGDBRemote::EnableBreakpointSite (size_id = %" PRIu64 2954 ") address = 0x%" PRIx64 " -- SUCCESS (already enabled)", 2955 site_id, (uint64_t)addr); 2956 return error; 2957 } 2958 2959 // Get the software breakpoint trap opcode size 2960 const size_t bp_op_size = GetSoftwareBreakpointTrapOpcode(bp_site); 2961 2962 // SupportsGDBStoppointPacket() simply checks a boolean, indicating if this 2963 // breakpoint type is supported by the remote stub. These are set to true by 2964 // default, and later set to false only after we receive an unimplemented 2965 // response when sending a breakpoint packet. This means initially that 2966 // unless we were specifically instructed to use a hardware breakpoint, LLDB 2967 // will attempt to set a software breakpoint. HardwareRequired() also queries 2968 // a boolean variable which indicates if the user specifically asked for 2969 // hardware breakpoints. If true then we will skip over software 2970 // breakpoints. 2971 if (m_gdb_comm.SupportsGDBStoppointPacket(eBreakpointSoftware) && 2972 (!bp_site->HardwareRequired())) { 2973 // Try to send off a software breakpoint packet ($Z0) 2974 uint8_t error_no = m_gdb_comm.SendGDBStoppointTypePacket( 2975 eBreakpointSoftware, true, addr, bp_op_size, GetInterruptTimeout()); 2976 if (error_no == 0) { 2977 // The breakpoint was placed successfully 2978 bp_site->SetEnabled(true); 2979 bp_site->SetType(BreakpointSite::eExternal); 2980 return error; 2981 } 2982 2983 // SendGDBStoppointTypePacket() will return an error if it was unable to 2984 // set this breakpoint. We need to differentiate between a error specific 2985 // to placing this breakpoint or if we have learned that this breakpoint 2986 // type is unsupported. To do this, we must test the support boolean for 2987 // this breakpoint type to see if it now indicates that this breakpoint 2988 // type is unsupported. If they are still supported then we should return 2989 // with the error code. If they are now unsupported, then we would like to 2990 // fall through and try another form of breakpoint. 2991 if (m_gdb_comm.SupportsGDBStoppointPacket(eBreakpointSoftware)) { 2992 if (error_no != UINT8_MAX) 2993 error.SetErrorStringWithFormat( 2994 "error: %d sending the breakpoint request", error_no); 2995 else 2996 error.SetErrorString("error sending the breakpoint request"); 2997 return error; 2998 } 2999 3000 // We reach here when software breakpoints have been found to be 3001 // unsupported. For future calls to set a breakpoint, we will not attempt 3002 // to set a breakpoint with a type that is known not to be supported. 3003 LLDB_LOGF(log, "Software breakpoints are unsupported"); 3004 3005 // So we will fall through and try a hardware breakpoint 3006 } 3007 3008 // The process of setting a hardware breakpoint is much the same as above. 3009 // We check the supported boolean for this breakpoint type, and if it is 3010 // thought to be supported then we will try to set this breakpoint with a 3011 // hardware breakpoint. 3012 if (m_gdb_comm.SupportsGDBStoppointPacket(eBreakpointHardware)) { 3013 // Try to send off a hardware breakpoint packet ($Z1) 3014 uint8_t error_no = m_gdb_comm.SendGDBStoppointTypePacket( 3015 eBreakpointHardware, true, addr, bp_op_size, GetInterruptTimeout()); 3016 if (error_no == 0) { 3017 // The breakpoint was placed successfully 3018 bp_site->SetEnabled(true); 3019 bp_site->SetType(BreakpointSite::eHardware); 3020 return error; 3021 } 3022 3023 // Check if the error was something other then an unsupported breakpoint 3024 // type 3025 if (m_gdb_comm.SupportsGDBStoppointPacket(eBreakpointHardware)) { 3026 // Unable to set this hardware breakpoint 3027 if (error_no != UINT8_MAX) 3028 error.SetErrorStringWithFormat( 3029 "error: %d sending the hardware breakpoint request " 3030 "(hardware breakpoint resources might be exhausted or unavailable)", 3031 error_no); 3032 else 3033 error.SetErrorString("error sending the hardware breakpoint request " 3034 "(hardware breakpoint resources " 3035 "might be exhausted or unavailable)"); 3036 return error; 3037 } 3038 3039 // We will reach here when the stub gives an unsupported response to a 3040 // hardware breakpoint 3041 LLDB_LOGF(log, "Hardware breakpoints are unsupported"); 3042 3043 // Finally we will falling through to a #trap style breakpoint 3044 } 3045 3046 // Don't fall through when hardware breakpoints were specifically requested 3047 if (bp_site->HardwareRequired()) { 3048 error.SetErrorString("hardware breakpoints are not supported"); 3049 return error; 3050 } 3051 3052 // As a last resort we want to place a manual breakpoint. An instruction is 3053 // placed into the process memory using memory write packets. 3054 return EnableSoftwareBreakpoint(bp_site); 3055 } 3056 3057 Status ProcessGDBRemote::DisableBreakpointSite(BreakpointSite *bp_site) { 3058 Status error; 3059 assert(bp_site != nullptr); 3060 addr_t addr = bp_site->GetLoadAddress(); 3061 user_id_t site_id = bp_site->GetID(); 3062 Log *log = GetLog(GDBRLog::Breakpoints); 3063 LLDB_LOGF(log, 3064 "ProcessGDBRemote::DisableBreakpointSite (site_id = %" PRIu64 3065 ") addr = 0x%8.8" PRIx64, 3066 site_id, (uint64_t)addr); 3067 3068 if (bp_site->IsEnabled()) { 3069 const size_t bp_op_size = GetSoftwareBreakpointTrapOpcode(bp_site); 3070 3071 BreakpointSite::Type bp_type = bp_site->GetType(); 3072 switch (bp_type) { 3073 case BreakpointSite::eSoftware: 3074 error = DisableSoftwareBreakpoint(bp_site); 3075 break; 3076 3077 case BreakpointSite::eHardware: 3078 if (m_gdb_comm.SendGDBStoppointTypePacket(eBreakpointHardware, false, 3079 addr, bp_op_size, 3080 GetInterruptTimeout())) 3081 error.SetErrorToGenericError(); 3082 break; 3083 3084 case BreakpointSite::eExternal: { 3085 if (m_gdb_comm.SendGDBStoppointTypePacket(eBreakpointSoftware, false, 3086 addr, bp_op_size, 3087 GetInterruptTimeout())) 3088 error.SetErrorToGenericError(); 3089 } break; 3090 } 3091 if (error.Success()) 3092 bp_site->SetEnabled(false); 3093 } else { 3094 LLDB_LOGF(log, 3095 "ProcessGDBRemote::DisableBreakpointSite (site_id = %" PRIu64 3096 ") addr = 0x%8.8" PRIx64 " -- SUCCESS (already disabled)", 3097 site_id, (uint64_t)addr); 3098 return error; 3099 } 3100 3101 if (error.Success()) 3102 error.SetErrorToGenericError(); 3103 return error; 3104 } 3105 3106 // Pre-requisite: wp != NULL. 3107 static GDBStoppointType GetGDBStoppointType(Watchpoint *wp) { 3108 assert(wp); 3109 bool watch_read = wp->WatchpointRead(); 3110 bool watch_write = wp->WatchpointWrite(); 3111 bool watch_modify = wp->WatchpointModify(); 3112 3113 // watch_read, watch_write, watch_modify cannot all be false. 3114 assert((watch_read || watch_write || watch_modify) && 3115 "watch_read, watch_write, watch_modify cannot all be false."); 3116 if (watch_read && (watch_write || watch_modify)) 3117 return eWatchpointReadWrite; 3118 else if (watch_read) 3119 return eWatchpointRead; 3120 else // Must be watch_write or watch_modify, then. 3121 return eWatchpointWrite; 3122 } 3123 3124 Status ProcessGDBRemote::EnableWatchpoint(Watchpoint *wp, bool notify) { 3125 Status error; 3126 if (wp) { 3127 user_id_t watchID = wp->GetID(); 3128 addr_t addr = wp->GetLoadAddress(); 3129 Log *log(GetLog(GDBRLog::Watchpoints)); 3130 LLDB_LOGF(log, "ProcessGDBRemote::EnableWatchpoint(watchID = %" PRIu64 ")", 3131 watchID); 3132 if (wp->IsEnabled()) { 3133 LLDB_LOGF(log, 3134 "ProcessGDBRemote::EnableWatchpoint(watchID = %" PRIu64 3135 ") addr = 0x%8.8" PRIx64 ": watchpoint already enabled.", 3136 watchID, (uint64_t)addr); 3137 return error; 3138 } 3139 3140 GDBStoppointType type = GetGDBStoppointType(wp); 3141 // Pass down an appropriate z/Z packet... 3142 if (m_gdb_comm.SupportsGDBStoppointPacket(type)) { 3143 if (m_gdb_comm.SendGDBStoppointTypePacket(type, true, addr, 3144 wp->GetByteSize(), 3145 GetInterruptTimeout()) == 0) { 3146 wp->SetEnabled(true, notify); 3147 return error; 3148 } else 3149 error.SetErrorString("sending gdb watchpoint packet failed"); 3150 } else 3151 error.SetErrorString("watchpoints not supported"); 3152 } else { 3153 error.SetErrorString("Watchpoint argument was NULL."); 3154 } 3155 if (error.Success()) 3156 error.SetErrorToGenericError(); 3157 return error; 3158 } 3159 3160 Status ProcessGDBRemote::DisableWatchpoint(Watchpoint *wp, bool notify) { 3161 Status error; 3162 if (wp) { 3163 user_id_t watchID = wp->GetID(); 3164 3165 Log *log(GetLog(GDBRLog::Watchpoints)); 3166 3167 addr_t addr = wp->GetLoadAddress(); 3168 3169 LLDB_LOGF(log, 3170 "ProcessGDBRemote::DisableWatchpoint (watchID = %" PRIu64 3171 ") addr = 0x%8.8" PRIx64, 3172 watchID, (uint64_t)addr); 3173 3174 if (!wp->IsEnabled()) { 3175 LLDB_LOGF(log, 3176 "ProcessGDBRemote::DisableWatchpoint (watchID = %" PRIu64 3177 ") addr = 0x%8.8" PRIx64 " -- SUCCESS (already disabled)", 3178 watchID, (uint64_t)addr); 3179 // See also 'class WatchpointSentry' within StopInfo.cpp. This disabling 3180 // attempt might come from the user-supplied actions, we'll route it in 3181 // order for the watchpoint object to intelligently process this action. 3182 wp->SetEnabled(false, notify); 3183 return error; 3184 } 3185 3186 if (wp->IsHardware()) { 3187 GDBStoppointType type = GetGDBStoppointType(wp); 3188 // Pass down an appropriate z/Z packet... 3189 if (m_gdb_comm.SendGDBStoppointTypePacket(type, false, addr, 3190 wp->GetByteSize(), 3191 GetInterruptTimeout()) == 0) { 3192 wp->SetEnabled(false, notify); 3193 return error; 3194 } else 3195 error.SetErrorString("sending gdb watchpoint packet failed"); 3196 } 3197 // TODO: clear software watchpoints if we implement them 3198 } else { 3199 error.SetErrorString("Watchpoint argument was NULL."); 3200 } 3201 if (error.Success()) 3202 error.SetErrorToGenericError(); 3203 return error; 3204 } 3205 3206 void ProcessGDBRemote::Clear() { 3207 m_thread_list_real.Clear(); 3208 m_thread_list.Clear(); 3209 } 3210 3211 Status ProcessGDBRemote::DoSignal(int signo) { 3212 Status error; 3213 Log *log = GetLog(GDBRLog::Process); 3214 LLDB_LOGF(log, "ProcessGDBRemote::DoSignal (signal = %d)", signo); 3215 3216 if (!m_gdb_comm.SendAsyncSignal(signo, GetInterruptTimeout())) 3217 error.SetErrorStringWithFormat("failed to send signal %i", signo); 3218 return error; 3219 } 3220 3221 Status 3222 ProcessGDBRemote::EstablishConnectionIfNeeded(const ProcessInfo &process_info) { 3223 // Make sure we aren't already connected? 3224 if (m_gdb_comm.IsConnected()) 3225 return Status(); 3226 3227 PlatformSP platform_sp(GetTarget().GetPlatform()); 3228 if (platform_sp && !platform_sp->IsHost()) 3229 return Status("Lost debug server connection"); 3230 3231 auto error = LaunchAndConnectToDebugserver(process_info); 3232 if (error.Fail()) { 3233 const char *error_string = error.AsCString(); 3234 if (error_string == nullptr) 3235 error_string = "unable to launch " DEBUGSERVER_BASENAME; 3236 } 3237 return error; 3238 } 3239 #if !defined(_WIN32) 3240 #define USE_SOCKETPAIR_FOR_LOCAL_CONNECTION 1 3241 #endif 3242 3243 #ifdef USE_SOCKETPAIR_FOR_LOCAL_CONNECTION 3244 static bool SetCloexecFlag(int fd) { 3245 #if defined(FD_CLOEXEC) 3246 int flags = ::fcntl(fd, F_GETFD); 3247 if (flags == -1) 3248 return false; 3249 return (::fcntl(fd, F_SETFD, flags | FD_CLOEXEC) == 0); 3250 #else 3251 return false; 3252 #endif 3253 } 3254 #endif 3255 3256 Status ProcessGDBRemote::LaunchAndConnectToDebugserver( 3257 const ProcessInfo &process_info) { 3258 using namespace std::placeholders; // For _1, _2, etc. 3259 3260 Status error; 3261 if (m_debugserver_pid == LLDB_INVALID_PROCESS_ID) { 3262 // If we locate debugserver, keep that located version around 3263 static FileSpec g_debugserver_file_spec; 3264 3265 ProcessLaunchInfo debugserver_launch_info; 3266 // Make debugserver run in its own session so signals generated by special 3267 // terminal key sequences (^C) don't affect debugserver. 3268 debugserver_launch_info.SetLaunchInSeparateProcessGroup(true); 3269 3270 const std::weak_ptr<ProcessGDBRemote> this_wp = 3271 std::static_pointer_cast<ProcessGDBRemote>(shared_from_this()); 3272 debugserver_launch_info.SetMonitorProcessCallback( 3273 std::bind(MonitorDebugserverProcess, this_wp, _1, _2, _3)); 3274 debugserver_launch_info.SetUserID(process_info.GetUserID()); 3275 3276 #if defined(__APPLE__) 3277 // On macOS 11, we need to support x86_64 applications translated to 3278 // arm64. We check whether a binary is translated and spawn the correct 3279 // debugserver accordingly. 3280 int mib[] = { CTL_KERN, KERN_PROC, KERN_PROC_PID, 3281 static_cast<int>(process_info.GetProcessID()) }; 3282 struct kinfo_proc processInfo; 3283 size_t bufsize = sizeof(processInfo); 3284 if (sysctl(mib, (unsigned)(sizeof(mib)/sizeof(int)), &processInfo, 3285 &bufsize, NULL, 0) == 0 && bufsize > 0) { 3286 if (processInfo.kp_proc.p_flag & P_TRANSLATED) { 3287 FileSpec rosetta_debugserver("/Library/Apple/usr/libexec/oah/debugserver"); 3288 debugserver_launch_info.SetExecutableFile(rosetta_debugserver, false); 3289 } 3290 } 3291 #endif 3292 3293 int communication_fd = -1; 3294 #ifdef USE_SOCKETPAIR_FOR_LOCAL_CONNECTION 3295 // Use a socketpair on non-Windows systems for security and performance 3296 // reasons. 3297 int sockets[2]; /* the pair of socket descriptors */ 3298 if (socketpair(AF_UNIX, SOCK_STREAM, 0, sockets) == -1) { 3299 error.SetErrorToErrno(); 3300 return error; 3301 } 3302 3303 int our_socket = sockets[0]; 3304 int gdb_socket = sockets[1]; 3305 auto cleanup_our = llvm::make_scope_exit([&]() { close(our_socket); }); 3306 auto cleanup_gdb = llvm::make_scope_exit([&]() { close(gdb_socket); }); 3307 3308 // Don't let any child processes inherit our communication socket 3309 SetCloexecFlag(our_socket); 3310 communication_fd = gdb_socket; 3311 #endif 3312 3313 error = m_gdb_comm.StartDebugserverProcess( 3314 nullptr, GetTarget().GetPlatform().get(), debugserver_launch_info, 3315 nullptr, nullptr, communication_fd); 3316 3317 if (error.Success()) 3318 m_debugserver_pid = debugserver_launch_info.GetProcessID(); 3319 else 3320 m_debugserver_pid = LLDB_INVALID_PROCESS_ID; 3321 3322 if (m_debugserver_pid != LLDB_INVALID_PROCESS_ID) { 3323 #ifdef USE_SOCKETPAIR_FOR_LOCAL_CONNECTION 3324 // Our process spawned correctly, we can now set our connection to use 3325 // our end of the socket pair 3326 cleanup_our.release(); 3327 m_gdb_comm.SetConnection( 3328 std::make_unique<ConnectionFileDescriptor>(our_socket, true)); 3329 #endif 3330 StartAsyncThread(); 3331 } 3332 3333 if (error.Fail()) { 3334 Log *log = GetLog(GDBRLog::Process); 3335 3336 LLDB_LOGF(log, "failed to start debugserver process: %s", 3337 error.AsCString()); 3338 return error; 3339 } 3340 3341 if (m_gdb_comm.IsConnected()) { 3342 // Finish the connection process by doing the handshake without 3343 // connecting (send NULL URL) 3344 error = ConnectToDebugserver(""); 3345 } else { 3346 error.SetErrorString("connection failed"); 3347 } 3348 } 3349 return error; 3350 } 3351 3352 void ProcessGDBRemote::MonitorDebugserverProcess( 3353 std::weak_ptr<ProcessGDBRemote> process_wp, lldb::pid_t debugserver_pid, 3354 int signo, // Zero for no signal 3355 int exit_status // Exit value of process if signal is zero 3356 ) { 3357 // "debugserver_pid" argument passed in is the process ID for debugserver 3358 // that we are tracking... 3359 Log *log = GetLog(GDBRLog::Process); 3360 3361 LLDB_LOGF(log, 3362 "ProcessGDBRemote::%s(process_wp, pid=%" PRIu64 3363 ", signo=%i (0x%x), exit_status=%i)", 3364 __FUNCTION__, debugserver_pid, signo, signo, exit_status); 3365 3366 std::shared_ptr<ProcessGDBRemote> process_sp = process_wp.lock(); 3367 LLDB_LOGF(log, "ProcessGDBRemote::%s(process = %p)", __FUNCTION__, 3368 static_cast<void *>(process_sp.get())); 3369 if (!process_sp || process_sp->m_debugserver_pid != debugserver_pid) 3370 return; 3371 3372 // Sleep for a half a second to make sure our inferior process has time to 3373 // set its exit status before we set it incorrectly when both the debugserver 3374 // and the inferior process shut down. 3375 std::this_thread::sleep_for(std::chrono::milliseconds(500)); 3376 3377 // If our process hasn't yet exited, debugserver might have died. If the 3378 // process did exit, then we are reaping it. 3379 const StateType state = process_sp->GetState(); 3380 3381 if (state != eStateInvalid && state != eStateUnloaded && 3382 state != eStateExited && state != eStateDetached) { 3383 StreamString stream; 3384 if (signo == 0) 3385 stream.Format(DEBUGSERVER_BASENAME " died with an exit status of {0:x8}", 3386 exit_status); 3387 else { 3388 llvm::StringRef signal_name = 3389 process_sp->GetUnixSignals()->GetSignalAsStringRef(signo); 3390 const char *format_str = DEBUGSERVER_BASENAME " died with signal {0}"; 3391 if (!signal_name.empty()) 3392 stream.Format(format_str, signal_name); 3393 else 3394 stream.Format(format_str, signo); 3395 } 3396 process_sp->SetExitStatus(-1, stream.GetString()); 3397 } 3398 // Debugserver has exited we need to let our ProcessGDBRemote know that it no 3399 // longer has a debugserver instance 3400 process_sp->m_debugserver_pid = LLDB_INVALID_PROCESS_ID; 3401 } 3402 3403 void ProcessGDBRemote::KillDebugserverProcess() { 3404 m_gdb_comm.Disconnect(); 3405 if (m_debugserver_pid != LLDB_INVALID_PROCESS_ID) { 3406 Host::Kill(m_debugserver_pid, SIGINT); 3407 m_debugserver_pid = LLDB_INVALID_PROCESS_ID; 3408 } 3409 } 3410 3411 void ProcessGDBRemote::Initialize() { 3412 static llvm::once_flag g_once_flag; 3413 3414 llvm::call_once(g_once_flag, []() { 3415 PluginManager::RegisterPlugin(GetPluginNameStatic(), 3416 GetPluginDescriptionStatic(), CreateInstance, 3417 DebuggerInitialize); 3418 }); 3419 } 3420 3421 void ProcessGDBRemote::DebuggerInitialize(Debugger &debugger) { 3422 if (!PluginManager::GetSettingForProcessPlugin( 3423 debugger, PluginProperties::GetSettingName())) { 3424 const bool is_global_setting = true; 3425 PluginManager::CreateSettingForProcessPlugin( 3426 debugger, GetGlobalPluginProperties().GetValueProperties(), 3427 "Properties for the gdb-remote process plug-in.", is_global_setting); 3428 } 3429 } 3430 3431 bool ProcessGDBRemote::StartAsyncThread() { 3432 Log *log = GetLog(GDBRLog::Process); 3433 3434 LLDB_LOGF(log, "ProcessGDBRemote::%s ()", __FUNCTION__); 3435 3436 std::lock_guard<std::recursive_mutex> guard(m_async_thread_state_mutex); 3437 if (!m_async_thread.IsJoinable()) { 3438 // Create a thread that watches our internal state and controls which 3439 // events make it to clients (into the DCProcess event queue). 3440 3441 llvm::Expected<HostThread> async_thread = 3442 ThreadLauncher::LaunchThread("<lldb.process.gdb-remote.async>", [this] { 3443 return ProcessGDBRemote::AsyncThread(); 3444 }); 3445 if (!async_thread) { 3446 LLDB_LOG_ERROR(GetLog(LLDBLog::Host), async_thread.takeError(), 3447 "failed to launch host thread: {0}"); 3448 return false; 3449 } 3450 m_async_thread = *async_thread; 3451 } else 3452 LLDB_LOGF(log, 3453 "ProcessGDBRemote::%s () - Called when Async thread was " 3454 "already running.", 3455 __FUNCTION__); 3456 3457 return m_async_thread.IsJoinable(); 3458 } 3459 3460 void ProcessGDBRemote::StopAsyncThread() { 3461 Log *log = GetLog(GDBRLog::Process); 3462 3463 LLDB_LOGF(log, "ProcessGDBRemote::%s ()", __FUNCTION__); 3464 3465 std::lock_guard<std::recursive_mutex> guard(m_async_thread_state_mutex); 3466 if (m_async_thread.IsJoinable()) { 3467 m_async_broadcaster.BroadcastEvent(eBroadcastBitAsyncThreadShouldExit); 3468 3469 // This will shut down the async thread. 3470 m_gdb_comm.Disconnect(); // Disconnect from the debug server. 3471 3472 // Stop the stdio thread 3473 m_async_thread.Join(nullptr); 3474 m_async_thread.Reset(); 3475 } else 3476 LLDB_LOGF( 3477 log, 3478 "ProcessGDBRemote::%s () - Called when Async thread was not running.", 3479 __FUNCTION__); 3480 } 3481 3482 thread_result_t ProcessGDBRemote::AsyncThread() { 3483 Log *log = GetLog(GDBRLog::Process); 3484 LLDB_LOGF(log, "ProcessGDBRemote::%s(pid = %" PRIu64 ") thread starting...", 3485 __FUNCTION__, GetID()); 3486 3487 EventSP event_sp; 3488 3489 // We need to ignore any packets that come in after we have 3490 // have decided the process has exited. There are some 3491 // situations, for instance when we try to interrupt a running 3492 // process and the interrupt fails, where another packet might 3493 // get delivered after we've decided to give up on the process. 3494 // But once we've decided we are done with the process we will 3495 // not be in a state to do anything useful with new packets. 3496 // So it is safer to simply ignore any remaining packets by 3497 // explicitly checking for eStateExited before reentering the 3498 // fetch loop. 3499 3500 bool done = false; 3501 while (!done && GetPrivateState() != eStateExited) { 3502 LLDB_LOGF(log, 3503 "ProcessGDBRemote::%s(pid = %" PRIu64 3504 ") listener.WaitForEvent (NULL, event_sp)...", 3505 __FUNCTION__, GetID()); 3506 3507 if (m_async_listener_sp->GetEvent(event_sp, std::nullopt)) { 3508 const uint32_t event_type = event_sp->GetType(); 3509 if (event_sp->BroadcasterIs(&m_async_broadcaster)) { 3510 LLDB_LOGF(log, 3511 "ProcessGDBRemote::%s(pid = %" PRIu64 3512 ") Got an event of type: %d...", 3513 __FUNCTION__, GetID(), event_type); 3514 3515 switch (event_type) { 3516 case eBroadcastBitAsyncContinue: { 3517 const EventDataBytes *continue_packet = 3518 EventDataBytes::GetEventDataFromEvent(event_sp.get()); 3519 3520 if (continue_packet) { 3521 const char *continue_cstr = 3522 (const char *)continue_packet->GetBytes(); 3523 const size_t continue_cstr_len = continue_packet->GetByteSize(); 3524 LLDB_LOGF(log, 3525 "ProcessGDBRemote::%s(pid = %" PRIu64 3526 ") got eBroadcastBitAsyncContinue: %s", 3527 __FUNCTION__, GetID(), continue_cstr); 3528 3529 if (::strstr(continue_cstr, "vAttach") == nullptr) 3530 SetPrivateState(eStateRunning); 3531 StringExtractorGDBRemote response; 3532 3533 StateType stop_state = 3534 GetGDBRemote().SendContinuePacketAndWaitForResponse( 3535 *this, *GetUnixSignals(), 3536 llvm::StringRef(continue_cstr, continue_cstr_len), 3537 GetInterruptTimeout(), response); 3538 3539 // We need to immediately clear the thread ID list so we are sure 3540 // to get a valid list of threads. The thread ID list might be 3541 // contained within the "response", or the stop reply packet that 3542 // caused the stop. So clear it now before we give the stop reply 3543 // packet to the process using the 3544 // SetLastStopPacket()... 3545 ClearThreadIDList(); 3546 3547 switch (stop_state) { 3548 case eStateStopped: 3549 case eStateCrashed: 3550 case eStateSuspended: 3551 SetLastStopPacket(response); 3552 SetPrivateState(stop_state); 3553 break; 3554 3555 case eStateExited: { 3556 SetLastStopPacket(response); 3557 ClearThreadIDList(); 3558 response.SetFilePos(1); 3559 3560 int exit_status = response.GetHexU8(); 3561 std::string desc_string; 3562 if (response.GetBytesLeft() > 0 && response.GetChar('-') == ';') { 3563 llvm::StringRef desc_str; 3564 llvm::StringRef desc_token; 3565 while (response.GetNameColonValue(desc_token, desc_str)) { 3566 if (desc_token != "description") 3567 continue; 3568 StringExtractor extractor(desc_str); 3569 extractor.GetHexByteString(desc_string); 3570 } 3571 } 3572 SetExitStatus(exit_status, desc_string.c_str()); 3573 done = true; 3574 break; 3575 } 3576 case eStateInvalid: { 3577 // Check to see if we were trying to attach and if we got back 3578 // the "E87" error code from debugserver -- this indicates that 3579 // the process is not debuggable. Return a slightly more 3580 // helpful error message about why the attach failed. 3581 if (::strstr(continue_cstr, "vAttach") != nullptr && 3582 response.GetError() == 0x87) { 3583 SetExitStatus(-1, "cannot attach to process due to " 3584 "System Integrity Protection"); 3585 } else if (::strstr(continue_cstr, "vAttach") != nullptr && 3586 response.GetStatus().Fail()) { 3587 SetExitStatus(-1, response.GetStatus().AsCString()); 3588 } else { 3589 SetExitStatus(-1, "lost connection"); 3590 } 3591 done = true; 3592 break; 3593 } 3594 3595 default: 3596 SetPrivateState(stop_state); 3597 break; 3598 } // switch(stop_state) 3599 } // if (continue_packet) 3600 } // case eBroadcastBitAsyncContinue 3601 break; 3602 3603 case eBroadcastBitAsyncThreadShouldExit: 3604 LLDB_LOGF(log, 3605 "ProcessGDBRemote::%s(pid = %" PRIu64 3606 ") got eBroadcastBitAsyncThreadShouldExit...", 3607 __FUNCTION__, GetID()); 3608 done = true; 3609 break; 3610 3611 default: 3612 LLDB_LOGF(log, 3613 "ProcessGDBRemote::%s(pid = %" PRIu64 3614 ") got unknown event 0x%8.8x", 3615 __FUNCTION__, GetID(), event_type); 3616 done = true; 3617 break; 3618 } 3619 } 3620 } else { 3621 LLDB_LOGF(log, 3622 "ProcessGDBRemote::%s(pid = %" PRIu64 3623 ") listener.WaitForEvent (NULL, event_sp) => false", 3624 __FUNCTION__, GetID()); 3625 done = true; 3626 } 3627 } 3628 3629 LLDB_LOGF(log, "ProcessGDBRemote::%s(pid = %" PRIu64 ") thread exiting...", 3630 __FUNCTION__, GetID()); 3631 3632 return {}; 3633 } 3634 3635 // uint32_t 3636 // ProcessGDBRemote::ListProcessesMatchingName (const char *name, StringList 3637 // &matches, std::vector<lldb::pid_t> &pids) 3638 //{ 3639 // // If we are planning to launch the debugserver remotely, then we need to 3640 // fire up a debugserver 3641 // // process and ask it for the list of processes. But if we are local, we 3642 // can let the Host do it. 3643 // if (m_local_debugserver) 3644 // { 3645 // return Host::ListProcessesMatchingName (name, matches, pids); 3646 // } 3647 // else 3648 // { 3649 // // FIXME: Implement talking to the remote debugserver. 3650 // return 0; 3651 // } 3652 // 3653 //} 3654 // 3655 bool ProcessGDBRemote::NewThreadNotifyBreakpointHit( 3656 void *baton, StoppointCallbackContext *context, lldb::user_id_t break_id, 3657 lldb::user_id_t break_loc_id) { 3658 // I don't think I have to do anything here, just make sure I notice the new 3659 // thread when it starts to 3660 // run so I can stop it if that's what I want to do. 3661 Log *log = GetLog(LLDBLog::Step); 3662 LLDB_LOGF(log, "Hit New Thread Notification breakpoint."); 3663 return false; 3664 } 3665 3666 Status ProcessGDBRemote::UpdateAutomaticSignalFiltering() { 3667 Log *log = GetLog(GDBRLog::Process); 3668 LLDB_LOG(log, "Check if need to update ignored signals"); 3669 3670 // QPassSignals package is not supported by the server, there is no way we 3671 // can ignore any signals on server side. 3672 if (!m_gdb_comm.GetQPassSignalsSupported()) 3673 return Status(); 3674 3675 // No signals, nothing to send. 3676 if (m_unix_signals_sp == nullptr) 3677 return Status(); 3678 3679 // Signals' version hasn't changed, no need to send anything. 3680 uint64_t new_signals_version = m_unix_signals_sp->GetVersion(); 3681 if (new_signals_version == m_last_signals_version) { 3682 LLDB_LOG(log, "Signals' version hasn't changed. version={0}", 3683 m_last_signals_version); 3684 return Status(); 3685 } 3686 3687 auto signals_to_ignore = 3688 m_unix_signals_sp->GetFilteredSignals(false, false, false); 3689 Status error = m_gdb_comm.SendSignalsToIgnore(signals_to_ignore); 3690 3691 LLDB_LOG(log, 3692 "Signals' version changed. old version={0}, new version={1}, " 3693 "signals ignored={2}, update result={3}", 3694 m_last_signals_version, new_signals_version, 3695 signals_to_ignore.size(), error); 3696 3697 if (error.Success()) 3698 m_last_signals_version = new_signals_version; 3699 3700 return error; 3701 } 3702 3703 bool ProcessGDBRemote::StartNoticingNewThreads() { 3704 Log *log = GetLog(LLDBLog::Step); 3705 if (m_thread_create_bp_sp) { 3706 if (log && log->GetVerbose()) 3707 LLDB_LOGF(log, "Enabled noticing new thread breakpoint."); 3708 m_thread_create_bp_sp->SetEnabled(true); 3709 } else { 3710 PlatformSP platform_sp(GetTarget().GetPlatform()); 3711 if (platform_sp) { 3712 m_thread_create_bp_sp = 3713 platform_sp->SetThreadCreationBreakpoint(GetTarget()); 3714 if (m_thread_create_bp_sp) { 3715 if (log && log->GetVerbose()) 3716 LLDB_LOGF( 3717 log, "Successfully created new thread notification breakpoint %i", 3718 m_thread_create_bp_sp->GetID()); 3719 m_thread_create_bp_sp->SetCallback( 3720 ProcessGDBRemote::NewThreadNotifyBreakpointHit, this, true); 3721 } else { 3722 LLDB_LOGF(log, "Failed to create new thread notification breakpoint."); 3723 } 3724 } 3725 } 3726 return m_thread_create_bp_sp.get() != nullptr; 3727 } 3728 3729 bool ProcessGDBRemote::StopNoticingNewThreads() { 3730 Log *log = GetLog(LLDBLog::Step); 3731 if (log && log->GetVerbose()) 3732 LLDB_LOGF(log, "Disabling new thread notification breakpoint."); 3733 3734 if (m_thread_create_bp_sp) 3735 m_thread_create_bp_sp->SetEnabled(false); 3736 3737 return true; 3738 } 3739 3740 DynamicLoader *ProcessGDBRemote::GetDynamicLoader() { 3741 if (m_dyld_up.get() == nullptr) 3742 m_dyld_up.reset(DynamicLoader::FindPlugin(this, "")); 3743 return m_dyld_up.get(); 3744 } 3745 3746 Status ProcessGDBRemote::SendEventData(const char *data) { 3747 int return_value; 3748 bool was_supported; 3749 3750 Status error; 3751 3752 return_value = m_gdb_comm.SendLaunchEventDataPacket(data, &was_supported); 3753 if (return_value != 0) { 3754 if (!was_supported) 3755 error.SetErrorString("Sending events is not supported for this process."); 3756 else 3757 error.SetErrorStringWithFormat("Error sending event data: %d.", 3758 return_value); 3759 } 3760 return error; 3761 } 3762 3763 DataExtractor ProcessGDBRemote::GetAuxvData() { 3764 DataBufferSP buf; 3765 if (m_gdb_comm.GetQXferAuxvReadSupported()) { 3766 llvm::Expected<std::string> response = m_gdb_comm.ReadExtFeature("auxv", ""); 3767 if (response) 3768 buf = std::make_shared<DataBufferHeap>(response->c_str(), 3769 response->length()); 3770 else 3771 LLDB_LOG_ERROR(GetLog(GDBRLog::Process), response.takeError(), "{0}"); 3772 } 3773 return DataExtractor(buf, GetByteOrder(), GetAddressByteSize()); 3774 } 3775 3776 StructuredData::ObjectSP 3777 ProcessGDBRemote::GetExtendedInfoForThread(lldb::tid_t tid) { 3778 StructuredData::ObjectSP object_sp; 3779 3780 if (m_gdb_comm.GetThreadExtendedInfoSupported()) { 3781 StructuredData::ObjectSP args_dict(new StructuredData::Dictionary()); 3782 SystemRuntime *runtime = GetSystemRuntime(); 3783 if (runtime) { 3784 runtime->AddThreadExtendedInfoPacketHints(args_dict); 3785 } 3786 args_dict->GetAsDictionary()->AddIntegerItem("thread", tid); 3787 3788 StreamString packet; 3789 packet << "jThreadExtendedInfo:"; 3790 args_dict->Dump(packet, false); 3791 3792 // FIXME the final character of a JSON dictionary, '}', is the escape 3793 // character in gdb-remote binary mode. lldb currently doesn't escape 3794 // these characters in its packet output -- so we add the quoted version of 3795 // the } character here manually in case we talk to a debugserver which un- 3796 // escapes the characters at packet read time. 3797 packet << (char)(0x7d ^ 0x20); 3798 3799 StringExtractorGDBRemote response; 3800 response.SetResponseValidatorToJSON(); 3801 if (m_gdb_comm.SendPacketAndWaitForResponse(packet.GetString(), response) == 3802 GDBRemoteCommunication::PacketResult::Success) { 3803 StringExtractorGDBRemote::ResponseType response_type = 3804 response.GetResponseType(); 3805 if (response_type == StringExtractorGDBRemote::eResponse) { 3806 if (!response.Empty()) { 3807 object_sp = StructuredData::ParseJSON(response.GetStringRef()); 3808 } 3809 } 3810 } 3811 } 3812 return object_sp; 3813 } 3814 3815 StructuredData::ObjectSP ProcessGDBRemote::GetLoadedDynamicLibrariesInfos( 3816 lldb::addr_t image_list_address, lldb::addr_t image_count) { 3817 3818 StructuredData::ObjectSP args_dict(new StructuredData::Dictionary()); 3819 args_dict->GetAsDictionary()->AddIntegerItem("image_list_address", 3820 image_list_address); 3821 args_dict->GetAsDictionary()->AddIntegerItem("image_count", image_count); 3822 3823 return GetLoadedDynamicLibrariesInfos_sender(args_dict); 3824 } 3825 3826 StructuredData::ObjectSP ProcessGDBRemote::GetLoadedDynamicLibrariesInfos() { 3827 StructuredData::ObjectSP args_dict(new StructuredData::Dictionary()); 3828 3829 args_dict->GetAsDictionary()->AddBooleanItem("fetch_all_solibs", true); 3830 3831 return GetLoadedDynamicLibrariesInfos_sender(args_dict); 3832 } 3833 3834 StructuredData::ObjectSP ProcessGDBRemote::GetLoadedDynamicLibrariesInfos( 3835 const std::vector<lldb::addr_t> &load_addresses) { 3836 StructuredData::ObjectSP args_dict(new StructuredData::Dictionary()); 3837 StructuredData::ArraySP addresses(new StructuredData::Array); 3838 3839 for (auto addr : load_addresses) 3840 addresses->AddIntegerItem(addr); 3841 3842 args_dict->GetAsDictionary()->AddItem("solib_addresses", addresses); 3843 3844 return GetLoadedDynamicLibrariesInfos_sender(args_dict); 3845 } 3846 3847 StructuredData::ObjectSP 3848 ProcessGDBRemote::GetLoadedDynamicLibrariesInfos_sender( 3849 StructuredData::ObjectSP args_dict) { 3850 StructuredData::ObjectSP object_sp; 3851 3852 if (m_gdb_comm.GetLoadedDynamicLibrariesInfosSupported()) { 3853 // Scope for the scoped timeout object 3854 GDBRemoteCommunication::ScopedTimeout timeout(m_gdb_comm, 3855 std::chrono::seconds(10)); 3856 3857 StreamString packet; 3858 packet << "jGetLoadedDynamicLibrariesInfos:"; 3859 args_dict->Dump(packet, false); 3860 3861 // FIXME the final character of a JSON dictionary, '}', is the escape 3862 // character in gdb-remote binary mode. lldb currently doesn't escape 3863 // these characters in its packet output -- so we add the quoted version of 3864 // the } character here manually in case we talk to a debugserver which un- 3865 // escapes the characters at packet read time. 3866 packet << (char)(0x7d ^ 0x20); 3867 3868 StringExtractorGDBRemote response; 3869 response.SetResponseValidatorToJSON(); 3870 if (m_gdb_comm.SendPacketAndWaitForResponse(packet.GetString(), response) == 3871 GDBRemoteCommunication::PacketResult::Success) { 3872 StringExtractorGDBRemote::ResponseType response_type = 3873 response.GetResponseType(); 3874 if (response_type == StringExtractorGDBRemote::eResponse) { 3875 if (!response.Empty()) { 3876 object_sp = StructuredData::ParseJSON(response.GetStringRef()); 3877 } 3878 } 3879 } 3880 } 3881 return object_sp; 3882 } 3883 3884 StructuredData::ObjectSP ProcessGDBRemote::GetDynamicLoaderProcessState() { 3885 StructuredData::ObjectSP object_sp; 3886 StructuredData::ObjectSP args_dict(new StructuredData::Dictionary()); 3887 3888 if (m_gdb_comm.GetDynamicLoaderProcessStateSupported()) { 3889 StringExtractorGDBRemote response; 3890 response.SetResponseValidatorToJSON(); 3891 if (m_gdb_comm.SendPacketAndWaitForResponse("jGetDyldProcessState", 3892 response) == 3893 GDBRemoteCommunication::PacketResult::Success) { 3894 StringExtractorGDBRemote::ResponseType response_type = 3895 response.GetResponseType(); 3896 if (response_type == StringExtractorGDBRemote::eResponse) { 3897 if (!response.Empty()) { 3898 object_sp = StructuredData::ParseJSON(response.GetStringRef()); 3899 } 3900 } 3901 } 3902 } 3903 return object_sp; 3904 } 3905 3906 StructuredData::ObjectSP ProcessGDBRemote::GetSharedCacheInfo() { 3907 StructuredData::ObjectSP object_sp; 3908 StructuredData::ObjectSP args_dict(new StructuredData::Dictionary()); 3909 3910 if (m_gdb_comm.GetSharedCacheInfoSupported()) { 3911 StreamString packet; 3912 packet << "jGetSharedCacheInfo:"; 3913 args_dict->Dump(packet, false); 3914 3915 // FIXME the final character of a JSON dictionary, '}', is the escape 3916 // character in gdb-remote binary mode. lldb currently doesn't escape 3917 // these characters in its packet output -- so we add the quoted version of 3918 // the } character here manually in case we talk to a debugserver which un- 3919 // escapes the characters at packet read time. 3920 packet << (char)(0x7d ^ 0x20); 3921 3922 StringExtractorGDBRemote response; 3923 response.SetResponseValidatorToJSON(); 3924 if (m_gdb_comm.SendPacketAndWaitForResponse(packet.GetString(), response) == 3925 GDBRemoteCommunication::PacketResult::Success) { 3926 StringExtractorGDBRemote::ResponseType response_type = 3927 response.GetResponseType(); 3928 if (response_type == StringExtractorGDBRemote::eResponse) { 3929 if (!response.Empty()) { 3930 object_sp = StructuredData::ParseJSON(response.GetStringRef()); 3931 } 3932 } 3933 } 3934 } 3935 return object_sp; 3936 } 3937 3938 Status ProcessGDBRemote::ConfigureStructuredData( 3939 llvm::StringRef type_name, const StructuredData::ObjectSP &config_sp) { 3940 return m_gdb_comm.ConfigureRemoteStructuredData(type_name, config_sp); 3941 } 3942 3943 // Establish the largest memory read/write payloads we should use. If the 3944 // remote stub has a max packet size, stay under that size. 3945 // 3946 // If the remote stub's max packet size is crazy large, use a reasonable 3947 // largeish default. 3948 // 3949 // If the remote stub doesn't advertise a max packet size, use a conservative 3950 // default. 3951 3952 void ProcessGDBRemote::GetMaxMemorySize() { 3953 const uint64_t reasonable_largeish_default = 128 * 1024; 3954 const uint64_t conservative_default = 512; 3955 3956 if (m_max_memory_size == 0) { 3957 uint64_t stub_max_size = m_gdb_comm.GetRemoteMaxPacketSize(); 3958 if (stub_max_size != UINT64_MAX && stub_max_size != 0) { 3959 // Save the stub's claimed maximum packet size 3960 m_remote_stub_max_memory_size = stub_max_size; 3961 3962 // Even if the stub says it can support ginormous packets, don't exceed 3963 // our reasonable largeish default packet size. 3964 if (stub_max_size > reasonable_largeish_default) { 3965 stub_max_size = reasonable_largeish_default; 3966 } 3967 3968 // Memory packet have other overheads too like Maddr,size:#NN Instead of 3969 // calculating the bytes taken by size and addr every time, we take a 3970 // maximum guess here. 3971 if (stub_max_size > 70) 3972 stub_max_size -= 32 + 32 + 6; 3973 else { 3974 // In unlikely scenario that max packet size is less then 70, we will 3975 // hope that data being written is small enough to fit. 3976 Log *log(GetLog(GDBRLog::Comm | GDBRLog::Memory)); 3977 if (log) 3978 log->Warning("Packet size is too small. " 3979 "LLDB may face problems while writing memory"); 3980 } 3981 3982 m_max_memory_size = stub_max_size; 3983 } else { 3984 m_max_memory_size = conservative_default; 3985 } 3986 } 3987 } 3988 3989 void ProcessGDBRemote::SetUserSpecifiedMaxMemoryTransferSize( 3990 uint64_t user_specified_max) { 3991 if (user_specified_max != 0) { 3992 GetMaxMemorySize(); 3993 3994 if (m_remote_stub_max_memory_size != 0) { 3995 if (m_remote_stub_max_memory_size < user_specified_max) { 3996 m_max_memory_size = m_remote_stub_max_memory_size; // user specified a 3997 // packet size too 3998 // big, go as big 3999 // as the remote stub says we can go. 4000 } else { 4001 m_max_memory_size = user_specified_max; // user's packet size is good 4002 } 4003 } else { 4004 m_max_memory_size = 4005 user_specified_max; // user's packet size is probably fine 4006 } 4007 } 4008 } 4009 4010 bool ProcessGDBRemote::GetModuleSpec(const FileSpec &module_file_spec, 4011 const ArchSpec &arch, 4012 ModuleSpec &module_spec) { 4013 Log *log = GetLog(LLDBLog::Platform); 4014 4015 const ModuleCacheKey key(module_file_spec.GetPath(), 4016 arch.GetTriple().getTriple()); 4017 auto cached = m_cached_module_specs.find(key); 4018 if (cached != m_cached_module_specs.end()) { 4019 module_spec = cached->second; 4020 return bool(module_spec); 4021 } 4022 4023 if (!m_gdb_comm.GetModuleInfo(module_file_spec, arch, module_spec)) { 4024 LLDB_LOGF(log, "ProcessGDBRemote::%s - failed to get module info for %s:%s", 4025 __FUNCTION__, module_file_spec.GetPath().c_str(), 4026 arch.GetTriple().getTriple().c_str()); 4027 return false; 4028 } 4029 4030 if (log) { 4031 StreamString stream; 4032 module_spec.Dump(stream); 4033 LLDB_LOGF(log, "ProcessGDBRemote::%s - got module info for (%s:%s) : %s", 4034 __FUNCTION__, module_file_spec.GetPath().c_str(), 4035 arch.GetTriple().getTriple().c_str(), stream.GetData()); 4036 } 4037 4038 m_cached_module_specs[key] = module_spec; 4039 return true; 4040 } 4041 4042 void ProcessGDBRemote::PrefetchModuleSpecs( 4043 llvm::ArrayRef<FileSpec> module_file_specs, const llvm::Triple &triple) { 4044 auto module_specs = m_gdb_comm.GetModulesInfo(module_file_specs, triple); 4045 if (module_specs) { 4046 for (const FileSpec &spec : module_file_specs) 4047 m_cached_module_specs[ModuleCacheKey(spec.GetPath(), 4048 triple.getTriple())] = ModuleSpec(); 4049 for (const ModuleSpec &spec : *module_specs) 4050 m_cached_module_specs[ModuleCacheKey(spec.GetFileSpec().GetPath(), 4051 triple.getTriple())] = spec; 4052 } 4053 } 4054 4055 llvm::VersionTuple ProcessGDBRemote::GetHostOSVersion() { 4056 return m_gdb_comm.GetOSVersion(); 4057 } 4058 4059 llvm::VersionTuple ProcessGDBRemote::GetHostMacCatalystVersion() { 4060 return m_gdb_comm.GetMacCatalystVersion(); 4061 } 4062 4063 namespace { 4064 4065 typedef std::vector<std::string> stringVec; 4066 4067 typedef std::vector<struct GdbServerRegisterInfo> GDBServerRegisterVec; 4068 struct RegisterSetInfo { 4069 ConstString name; 4070 }; 4071 4072 typedef std::map<uint32_t, RegisterSetInfo> RegisterSetMap; 4073 4074 struct GdbServerTargetInfo { 4075 std::string arch; 4076 std::string osabi; 4077 stringVec includes; 4078 RegisterSetMap reg_set_map; 4079 }; 4080 4081 static std::vector<RegisterFlags::Field> ParseFlagsFields(XMLNode flags_node, 4082 unsigned size) { 4083 Log *log(GetLog(GDBRLog::Process)); 4084 const unsigned max_start_bit = size * 8 - 1; 4085 4086 // Process the fields of this set of flags. 4087 std::vector<RegisterFlags::Field> fields; 4088 flags_node.ForEachChildElementWithName("field", [&fields, max_start_bit, 4089 &log](const XMLNode 4090 &field_node) { 4091 std::optional<llvm::StringRef> name; 4092 std::optional<unsigned> start; 4093 std::optional<unsigned> end; 4094 4095 field_node.ForEachAttribute([&name, &start, &end, max_start_bit, 4096 &log](const llvm::StringRef &attr_name, 4097 const llvm::StringRef &attr_value) { 4098 // Note that XML in general requires that each of these attributes only 4099 // appears once, so we don't have to handle that here. 4100 if (attr_name == "name") { 4101 LLDB_LOG(log, 4102 "ProcessGDBRemote::ParseFlags Found field node name \"{0}\"", 4103 attr_value.data()); 4104 name = attr_value; 4105 } else if (attr_name == "start") { 4106 unsigned parsed_start = 0; 4107 if (llvm::to_integer(attr_value, parsed_start)) { 4108 if (parsed_start > max_start_bit) { 4109 LLDB_LOG( 4110 log, 4111 "ProcessGDBRemote::ParseFlags Invalid start {0} in field node, " 4112 "cannot be > {1}", 4113 parsed_start, max_start_bit); 4114 } else 4115 start = parsed_start; 4116 } else { 4117 LLDB_LOG(log, 4118 "ProcessGDBRemote::ParseFlags Invalid start \"{0}\" in " 4119 "field node", 4120 attr_value.data()); 4121 } 4122 } else if (attr_name == "end") { 4123 unsigned parsed_end = 0; 4124 if (llvm::to_integer(attr_value, parsed_end)) 4125 if (parsed_end > max_start_bit) { 4126 LLDB_LOG( 4127 log, 4128 "ProcessGDBRemote::ParseFlags Invalid end {0} in field node, " 4129 "cannot be > {1}", 4130 parsed_end, max_start_bit); 4131 } else 4132 end = parsed_end; 4133 else { 4134 LLDB_LOG( 4135 log, 4136 "ProcessGDBRemote::ParseFlags Invalid end \"{0}\" in field node", 4137 attr_value.data()); 4138 } 4139 } else if (attr_name == "type") { 4140 // Type is a known attribute but we do not currently use it and it is 4141 // not required. 4142 } else { 4143 LLDB_LOG(log, 4144 "ProcessGDBRemote::ParseFlags Ignoring unknown attribute " 4145 "\"{0}\" in field node", 4146 attr_name.data()); 4147 } 4148 4149 return true; // Walk all attributes of the field. 4150 }); 4151 4152 if (name && start && end) { 4153 if (*start > *end) { 4154 LLDB_LOG(log, 4155 "ProcessGDBRemote::ParseFlags Start {0} > end {1} in field " 4156 "\"{2}\", ignoring", 4157 *start, *end, name->data()); 4158 } else { 4159 fields.push_back(RegisterFlags::Field(name->str(), *start, *end)); 4160 } 4161 } 4162 4163 return true; // Iterate all "field" nodes. 4164 }); 4165 return fields; 4166 } 4167 4168 void ParseFlags( 4169 XMLNode feature_node, 4170 llvm::StringMap<std::unique_ptr<RegisterFlags>> ®isters_flags_types) { 4171 Log *log(GetLog(GDBRLog::Process)); 4172 4173 feature_node.ForEachChildElementWithName( 4174 "flags", 4175 [&log, ®isters_flags_types](const XMLNode &flags_node) -> bool { 4176 LLDB_LOG(log, "ProcessGDBRemote::ParseFlags Found flags node \"{0}\"", 4177 flags_node.GetAttributeValue("id").c_str()); 4178 4179 std::optional<llvm::StringRef> id; 4180 std::optional<unsigned> size; 4181 flags_node.ForEachAttribute( 4182 [&id, &size, &log](const llvm::StringRef &name, 4183 const llvm::StringRef &value) { 4184 if (name == "id") { 4185 id = value; 4186 } else if (name == "size") { 4187 unsigned parsed_size = 0; 4188 if (llvm::to_integer(value, parsed_size)) 4189 size = parsed_size; 4190 else { 4191 LLDB_LOG(log, 4192 "ProcessGDBRemote::ParseFlags Invalid size \"{0}\" " 4193 "in flags node", 4194 value.data()); 4195 } 4196 } else { 4197 LLDB_LOG(log, 4198 "ProcessGDBRemote::ParseFlags Ignoring unknown " 4199 "attribute \"{0}\" in flags node", 4200 name.data()); 4201 } 4202 return true; // Walk all attributes. 4203 }); 4204 4205 if (id && size) { 4206 // Process the fields of this set of flags. 4207 std::vector<RegisterFlags::Field> fields = 4208 ParseFlagsFields(flags_node, *size); 4209 if (fields.size()) { 4210 // Sort so that the fields with the MSBs are first. 4211 std::sort(fields.rbegin(), fields.rend()); 4212 std::vector<RegisterFlags::Field>::const_iterator overlap = 4213 std::adjacent_find(fields.begin(), fields.end(), 4214 [](const RegisterFlags::Field &lhs, 4215 const RegisterFlags::Field &rhs) { 4216 return lhs.Overlaps(rhs); 4217 }); 4218 4219 // If no fields overlap, use them. 4220 if (overlap == fields.end()) { 4221 if (registers_flags_types.contains(*id)) { 4222 // In theory you could define some flag set, use it with a 4223 // register then redefine it. We do not know if anyone does 4224 // that, or what they would expect to happen in that case. 4225 // 4226 // LLDB chooses to take the first definition and ignore the rest 4227 // as waiting until everything has been processed is more 4228 // expensive and difficult. This means that pointers to flag 4229 // sets in the register info remain valid if later the flag set 4230 // is redefined. If we allowed redefinitions, LLDB would crash 4231 // when you tried to print a register that used the original 4232 // definition. 4233 LLDB_LOG( 4234 log, 4235 "ProcessGDBRemote::ParseFlags Definition of flags " 4236 "\"{0}\" shadows " 4237 "previous definition, using original definition instead.", 4238 id->data()); 4239 } else { 4240 registers_flags_types.insert_or_assign( 4241 *id, std::make_unique<RegisterFlags>(id->str(), *size, 4242 std::move(fields))); 4243 } 4244 } else { 4245 // If any fields overlap, ignore the whole set of flags. 4246 std::vector<RegisterFlags::Field>::const_iterator next = 4247 std::next(overlap); 4248 LLDB_LOG( 4249 log, 4250 "ProcessGDBRemote::ParseFlags Ignoring flags because fields " 4251 "{0} (start: {1} end: {2}) and {3} (start: {4} end: {5}) " 4252 "overlap.", 4253 overlap->GetName().c_str(), overlap->GetStart(), 4254 overlap->GetEnd(), next->GetName().c_str(), next->GetStart(), 4255 next->GetEnd()); 4256 } 4257 } else { 4258 LLDB_LOG( 4259 log, 4260 "ProcessGDBRemote::ParseFlags Ignoring definition of flags " 4261 "\"{0}\" because it contains no fields.", 4262 id->data()); 4263 } 4264 } 4265 4266 return true; // Keep iterating through all "flags" elements. 4267 }); 4268 } 4269 4270 bool ParseRegisters( 4271 XMLNode feature_node, GdbServerTargetInfo &target_info, 4272 std::vector<DynamicRegisterInfo::Register> ®isters, 4273 llvm::StringMap<std::unique_ptr<RegisterFlags>> ®isters_flags_types) { 4274 if (!feature_node) 4275 return false; 4276 4277 Log *log(GetLog(GDBRLog::Process)); 4278 4279 ParseFlags(feature_node, registers_flags_types); 4280 for (const auto &flags : registers_flags_types) 4281 flags.second->log(log); 4282 4283 feature_node.ForEachChildElementWithName( 4284 "reg", 4285 [&target_info, ®isters, ®isters_flags_types, 4286 log](const XMLNode ®_node) -> bool { 4287 std::string gdb_group; 4288 std::string gdb_type; 4289 DynamicRegisterInfo::Register reg_info; 4290 bool encoding_set = false; 4291 bool format_set = false; 4292 4293 // FIXME: we're silently ignoring invalid data here 4294 reg_node.ForEachAttribute([&target_info, &gdb_group, &gdb_type, 4295 &encoding_set, &format_set, ®_info, 4296 log](const llvm::StringRef &name, 4297 const llvm::StringRef &value) -> bool { 4298 if (name == "name") { 4299 reg_info.name.SetString(value); 4300 } else if (name == "bitsize") { 4301 if (llvm::to_integer(value, reg_info.byte_size)) 4302 reg_info.byte_size = 4303 llvm::divideCeil(reg_info.byte_size, CHAR_BIT); 4304 } else if (name == "type") { 4305 gdb_type = value.str(); 4306 } else if (name == "group") { 4307 gdb_group = value.str(); 4308 } else if (name == "regnum") { 4309 llvm::to_integer(value, reg_info.regnum_remote); 4310 } else if (name == "offset") { 4311 llvm::to_integer(value, reg_info.byte_offset); 4312 } else if (name == "altname") { 4313 reg_info.alt_name.SetString(value); 4314 } else if (name == "encoding") { 4315 encoding_set = true; 4316 reg_info.encoding = Args::StringToEncoding(value, eEncodingUint); 4317 } else if (name == "format") { 4318 format_set = true; 4319 if (!OptionArgParser::ToFormat(value.data(), reg_info.format, 4320 nullptr) 4321 .Success()) 4322 reg_info.format = 4323 llvm::StringSwitch<lldb::Format>(value) 4324 .Case("vector-sint8", eFormatVectorOfSInt8) 4325 .Case("vector-uint8", eFormatVectorOfUInt8) 4326 .Case("vector-sint16", eFormatVectorOfSInt16) 4327 .Case("vector-uint16", eFormatVectorOfUInt16) 4328 .Case("vector-sint32", eFormatVectorOfSInt32) 4329 .Case("vector-uint32", eFormatVectorOfUInt32) 4330 .Case("vector-float32", eFormatVectorOfFloat32) 4331 .Case("vector-uint64", eFormatVectorOfUInt64) 4332 .Case("vector-uint128", eFormatVectorOfUInt128) 4333 .Default(eFormatInvalid); 4334 } else if (name == "group_id") { 4335 uint32_t set_id = UINT32_MAX; 4336 llvm::to_integer(value, set_id); 4337 RegisterSetMap::const_iterator pos = 4338 target_info.reg_set_map.find(set_id); 4339 if (pos != target_info.reg_set_map.end()) 4340 reg_info.set_name = pos->second.name; 4341 } else if (name == "gcc_regnum" || name == "ehframe_regnum") { 4342 llvm::to_integer(value, reg_info.regnum_ehframe); 4343 } else if (name == "dwarf_regnum") { 4344 llvm::to_integer(value, reg_info.regnum_dwarf); 4345 } else if (name == "generic") { 4346 reg_info.regnum_generic = Args::StringToGenericRegister(value); 4347 } else if (name == "value_regnums") { 4348 SplitCommaSeparatedRegisterNumberString(value, reg_info.value_regs, 4349 0); 4350 } else if (name == "invalidate_regnums") { 4351 SplitCommaSeparatedRegisterNumberString( 4352 value, reg_info.invalidate_regs, 0); 4353 } else { 4354 LLDB_LOGF(log, 4355 "ProcessGDBRemote::ParseRegisters unhandled reg " 4356 "attribute %s = %s", 4357 name.data(), value.data()); 4358 } 4359 return true; // Keep iterating through all attributes 4360 }); 4361 4362 if (!gdb_type.empty()) { 4363 // gdb_type could reference some flags type defined in XML. 4364 llvm::StringMap<std::unique_ptr<RegisterFlags>>::iterator it = 4365 registers_flags_types.find(gdb_type); 4366 if (it != registers_flags_types.end()) { 4367 auto flags_type = it->second.get(); 4368 if (reg_info.byte_size == flags_type->GetSize()) 4369 reg_info.flags_type = flags_type; 4370 else 4371 LLDB_LOGF(log, 4372 "ProcessGDBRemote::ParseRegisters Size of register " 4373 "flags %s (%d bytes) for " 4374 "register %s does not match the register size (%d " 4375 "bytes). Ignoring this set of flags.", 4376 flags_type->GetID().c_str(), flags_type->GetSize(), 4377 reg_info.name.AsCString(), reg_info.byte_size); 4378 } 4379 4380 // There's a slim chance that the gdb_type name is both a flags type 4381 // and a simple type. Just in case, look for that too (setting both 4382 // does no harm). 4383 if (!gdb_type.empty() && !(encoding_set || format_set)) { 4384 if (llvm::StringRef(gdb_type).startswith("int")) { 4385 reg_info.format = eFormatHex; 4386 reg_info.encoding = eEncodingUint; 4387 } else if (gdb_type == "data_ptr" || gdb_type == "code_ptr") { 4388 reg_info.format = eFormatAddressInfo; 4389 reg_info.encoding = eEncodingUint; 4390 } else if (gdb_type == "float") { 4391 reg_info.format = eFormatFloat; 4392 reg_info.encoding = eEncodingIEEE754; 4393 } else if (gdb_type == "aarch64v" || 4394 llvm::StringRef(gdb_type).startswith("vec") || 4395 gdb_type == "i387_ext" || gdb_type == "uint128") { 4396 // lldb doesn't handle 128-bit uints correctly (for ymm*h), so 4397 // treat them as vector (similarly to xmm/ymm) 4398 reg_info.format = eFormatVectorOfUInt8; 4399 reg_info.encoding = eEncodingVector; 4400 } else { 4401 LLDB_LOGF( 4402 log, 4403 "ProcessGDBRemote::ParseRegisters Could not determine lldb" 4404 "format and encoding for gdb type %s", 4405 gdb_type.c_str()); 4406 } 4407 } 4408 } 4409 4410 // Only update the register set name if we didn't get a "reg_set" 4411 // attribute. "set_name" will be empty if we didn't have a "reg_set" 4412 // attribute. 4413 if (!reg_info.set_name) { 4414 if (!gdb_group.empty()) { 4415 reg_info.set_name.SetCString(gdb_group.c_str()); 4416 } else { 4417 // If no register group name provided anywhere, 4418 // we'll create a 'general' register set 4419 reg_info.set_name.SetCString("general"); 4420 } 4421 } 4422 4423 if (reg_info.byte_size == 0) { 4424 LLDB_LOGF(log, 4425 "ProcessGDBRemote::%s Skipping zero bitsize register %s", 4426 __FUNCTION__, reg_info.name.AsCString()); 4427 } else 4428 registers.push_back(reg_info); 4429 4430 return true; // Keep iterating through all "reg" elements 4431 }); 4432 return true; 4433 } 4434 4435 } // namespace 4436 4437 // This method fetches a register description feature xml file from 4438 // the remote stub and adds registers/register groupsets/architecture 4439 // information to the current process. It will call itself recursively 4440 // for nested register definition files. It returns true if it was able 4441 // to fetch and parse an xml file. 4442 bool ProcessGDBRemote::GetGDBServerRegisterInfoXMLAndProcess( 4443 ArchSpec &arch_to_use, std::string xml_filename, 4444 std::vector<DynamicRegisterInfo::Register> ®isters) { 4445 // request the target xml file 4446 llvm::Expected<std::string> raw = m_gdb_comm.ReadExtFeature("features", xml_filename); 4447 if (errorToBool(raw.takeError())) 4448 return false; 4449 4450 XMLDocument xml_document; 4451 4452 if (xml_document.ParseMemory(raw->c_str(), raw->size(), 4453 xml_filename.c_str())) { 4454 GdbServerTargetInfo target_info; 4455 std::vector<XMLNode> feature_nodes; 4456 4457 // The top level feature XML file will start with a <target> tag. 4458 XMLNode target_node = xml_document.GetRootElement("target"); 4459 if (target_node) { 4460 target_node.ForEachChildElement([&target_info, &feature_nodes]( 4461 const XMLNode &node) -> bool { 4462 llvm::StringRef name = node.GetName(); 4463 if (name == "architecture") { 4464 node.GetElementText(target_info.arch); 4465 } else if (name == "osabi") { 4466 node.GetElementText(target_info.osabi); 4467 } else if (name == "xi:include" || name == "include") { 4468 std::string href = node.GetAttributeValue("href"); 4469 if (!href.empty()) 4470 target_info.includes.push_back(href); 4471 } else if (name == "feature") { 4472 feature_nodes.push_back(node); 4473 } else if (name == "groups") { 4474 node.ForEachChildElementWithName( 4475 "group", [&target_info](const XMLNode &node) -> bool { 4476 uint32_t set_id = UINT32_MAX; 4477 RegisterSetInfo set_info; 4478 4479 node.ForEachAttribute( 4480 [&set_id, &set_info](const llvm::StringRef &name, 4481 const llvm::StringRef &value) -> bool { 4482 // FIXME: we're silently ignoring invalid data here 4483 if (name == "id") 4484 llvm::to_integer(value, set_id); 4485 if (name == "name") 4486 set_info.name = ConstString(value); 4487 return true; // Keep iterating through all attributes 4488 }); 4489 4490 if (set_id != UINT32_MAX) 4491 target_info.reg_set_map[set_id] = set_info; 4492 return true; // Keep iterating through all "group" elements 4493 }); 4494 } 4495 return true; // Keep iterating through all children of the target_node 4496 }); 4497 } else { 4498 // In an included XML feature file, we're already "inside" the <target> 4499 // tag of the initial XML file; this included file will likely only have 4500 // a <feature> tag. Need to check for any more included files in this 4501 // <feature> element. 4502 XMLNode feature_node = xml_document.GetRootElement("feature"); 4503 if (feature_node) { 4504 feature_nodes.push_back(feature_node); 4505 feature_node.ForEachChildElement([&target_info]( 4506 const XMLNode &node) -> bool { 4507 llvm::StringRef name = node.GetName(); 4508 if (name == "xi:include" || name == "include") { 4509 std::string href = node.GetAttributeValue("href"); 4510 if (!href.empty()) 4511 target_info.includes.push_back(href); 4512 } 4513 return true; 4514 }); 4515 } 4516 } 4517 4518 // gdbserver does not implement the LLDB packets used to determine host 4519 // or process architecture. If that is the case, attempt to use 4520 // the <architecture/> field from target.xml, e.g.: 4521 // 4522 // <architecture>i386:x86-64</architecture> (seen from VMWare ESXi) 4523 // <architecture>arm</architecture> (seen from Segger JLink on unspecified 4524 // arm board) 4525 if (!arch_to_use.IsValid() && !target_info.arch.empty()) { 4526 // We don't have any information about vendor or OS. 4527 arch_to_use.SetTriple(llvm::StringSwitch<std::string>(target_info.arch) 4528 .Case("i386:x86-64", "x86_64") 4529 .Default(target_info.arch) + 4530 "--"); 4531 4532 if (arch_to_use.IsValid()) 4533 GetTarget().MergeArchitecture(arch_to_use); 4534 } 4535 4536 if (arch_to_use.IsValid()) { 4537 for (auto &feature_node : feature_nodes) { 4538 ParseRegisters(feature_node, target_info, registers, 4539 m_registers_flags_types); 4540 } 4541 4542 for (const auto &include : target_info.includes) { 4543 GetGDBServerRegisterInfoXMLAndProcess(arch_to_use, include, 4544 registers); 4545 } 4546 } 4547 } else { 4548 return false; 4549 } 4550 return true; 4551 } 4552 4553 void ProcessGDBRemote::AddRemoteRegisters( 4554 std::vector<DynamicRegisterInfo::Register> ®isters, 4555 const ArchSpec &arch_to_use) { 4556 std::map<uint32_t, uint32_t> remote_to_local_map; 4557 uint32_t remote_regnum = 0; 4558 for (auto it : llvm::enumerate(registers)) { 4559 DynamicRegisterInfo::Register &remote_reg_info = it.value(); 4560 4561 // Assign successive remote regnums if missing. 4562 if (remote_reg_info.regnum_remote == LLDB_INVALID_REGNUM) 4563 remote_reg_info.regnum_remote = remote_regnum; 4564 4565 // Create a mapping from remote to local regnos. 4566 remote_to_local_map[remote_reg_info.regnum_remote] = it.index(); 4567 4568 remote_regnum = remote_reg_info.regnum_remote + 1; 4569 } 4570 4571 for (DynamicRegisterInfo::Register &remote_reg_info : registers) { 4572 auto proc_to_lldb = [&remote_to_local_map](uint32_t process_regnum) { 4573 auto lldb_regit = remote_to_local_map.find(process_regnum); 4574 return lldb_regit != remote_to_local_map.end() ? lldb_regit->second 4575 : LLDB_INVALID_REGNUM; 4576 }; 4577 4578 llvm::transform(remote_reg_info.value_regs, 4579 remote_reg_info.value_regs.begin(), proc_to_lldb); 4580 llvm::transform(remote_reg_info.invalidate_regs, 4581 remote_reg_info.invalidate_regs.begin(), proc_to_lldb); 4582 } 4583 4584 // Don't use Process::GetABI, this code gets called from DidAttach, and 4585 // in that context we haven't set the Target's architecture yet, so the 4586 // ABI is also potentially incorrect. 4587 if (ABISP abi_sp = ABI::FindPlugin(shared_from_this(), arch_to_use)) 4588 abi_sp->AugmentRegisterInfo(registers); 4589 4590 m_register_info_sp->SetRegisterInfo(std::move(registers), arch_to_use); 4591 } 4592 4593 // query the target of gdb-remote for extended target information returns 4594 // true on success (got register definitions), false on failure (did not). 4595 bool ProcessGDBRemote::GetGDBServerRegisterInfo(ArchSpec &arch_to_use) { 4596 // Make sure LLDB has an XML parser it can use first 4597 if (!XMLDocument::XMLEnabled()) 4598 return false; 4599 4600 // check that we have extended feature read support 4601 if (!m_gdb_comm.GetQXferFeaturesReadSupported()) 4602 return false; 4603 4604 // This holds register flags information for the whole of target.xml. 4605 // target.xml may include further documents that 4606 // GetGDBServerRegisterInfoXMLAndProcess will recurse to fetch and process. 4607 // That's why we clear the cache here, and not in 4608 // GetGDBServerRegisterInfoXMLAndProcess. To prevent it being cleared on every 4609 // include read. 4610 m_registers_flags_types.clear(); 4611 std::vector<DynamicRegisterInfo::Register> registers; 4612 if (GetGDBServerRegisterInfoXMLAndProcess(arch_to_use, "target.xml", 4613 registers)) 4614 AddRemoteRegisters(registers, arch_to_use); 4615 4616 return m_register_info_sp->GetNumRegisters() > 0; 4617 } 4618 4619 llvm::Expected<LoadedModuleInfoList> ProcessGDBRemote::GetLoadedModuleList() { 4620 // Make sure LLDB has an XML parser it can use first 4621 if (!XMLDocument::XMLEnabled()) 4622 return llvm::createStringError(llvm::inconvertibleErrorCode(), 4623 "XML parsing not available"); 4624 4625 Log *log = GetLog(LLDBLog::Process); 4626 LLDB_LOGF(log, "ProcessGDBRemote::%s", __FUNCTION__); 4627 4628 LoadedModuleInfoList list; 4629 GDBRemoteCommunicationClient &comm = m_gdb_comm; 4630 bool can_use_svr4 = GetGlobalPluginProperties().GetUseSVR4(); 4631 4632 // check that we have extended feature read support 4633 if (can_use_svr4 && comm.GetQXferLibrariesSVR4ReadSupported()) { 4634 // request the loaded library list 4635 llvm::Expected<std::string> raw = comm.ReadExtFeature("libraries-svr4", ""); 4636 if (!raw) 4637 return raw.takeError(); 4638 4639 // parse the xml file in memory 4640 LLDB_LOGF(log, "parsing: %s", raw->c_str()); 4641 XMLDocument doc; 4642 4643 if (!doc.ParseMemory(raw->c_str(), raw->size(), "noname.xml")) 4644 return llvm::createStringError(llvm::inconvertibleErrorCode(), 4645 "Error reading noname.xml"); 4646 4647 XMLNode root_element = doc.GetRootElement("library-list-svr4"); 4648 if (!root_element) 4649 return llvm::createStringError( 4650 llvm::inconvertibleErrorCode(), 4651 "Error finding library-list-svr4 xml element"); 4652 4653 // main link map structure 4654 std::string main_lm = root_element.GetAttributeValue("main-lm"); 4655 // FIXME: we're silently ignoring invalid data here 4656 if (!main_lm.empty()) 4657 llvm::to_integer(main_lm, list.m_link_map); 4658 4659 root_element.ForEachChildElementWithName( 4660 "library", [log, &list](const XMLNode &library) -> bool { 4661 LoadedModuleInfoList::LoadedModuleInfo module; 4662 4663 // FIXME: we're silently ignoring invalid data here 4664 library.ForEachAttribute( 4665 [&module](const llvm::StringRef &name, 4666 const llvm::StringRef &value) -> bool { 4667 uint64_t uint_value = LLDB_INVALID_ADDRESS; 4668 if (name == "name") 4669 module.set_name(value.str()); 4670 else if (name == "lm") { 4671 // the address of the link_map struct. 4672 llvm::to_integer(value, uint_value); 4673 module.set_link_map(uint_value); 4674 } else if (name == "l_addr") { 4675 // the displacement as read from the field 'l_addr' of the 4676 // link_map struct. 4677 llvm::to_integer(value, uint_value); 4678 module.set_base(uint_value); 4679 // base address is always a displacement, not an absolute 4680 // value. 4681 module.set_base_is_offset(true); 4682 } else if (name == "l_ld") { 4683 // the memory address of the libraries PT_DYNAMIC section. 4684 llvm::to_integer(value, uint_value); 4685 module.set_dynamic(uint_value); 4686 } 4687 4688 return true; // Keep iterating over all properties of "library" 4689 }); 4690 4691 if (log) { 4692 std::string name; 4693 lldb::addr_t lm = 0, base = 0, ld = 0; 4694 bool base_is_offset; 4695 4696 module.get_name(name); 4697 module.get_link_map(lm); 4698 module.get_base(base); 4699 module.get_base_is_offset(base_is_offset); 4700 module.get_dynamic(ld); 4701 4702 LLDB_LOGF(log, 4703 "found (link_map:0x%08" PRIx64 ", base:0x%08" PRIx64 4704 "[%s], ld:0x%08" PRIx64 ", name:'%s')", 4705 lm, base, (base_is_offset ? "offset" : "absolute"), ld, 4706 name.c_str()); 4707 } 4708 4709 list.add(module); 4710 return true; // Keep iterating over all "library" elements in the root 4711 // node 4712 }); 4713 4714 if (log) 4715 LLDB_LOGF(log, "found %" PRId32 " modules in total", 4716 (int)list.m_list.size()); 4717 return list; 4718 } else if (comm.GetQXferLibrariesReadSupported()) { 4719 // request the loaded library list 4720 llvm::Expected<std::string> raw = comm.ReadExtFeature("libraries", ""); 4721 4722 if (!raw) 4723 return raw.takeError(); 4724 4725 LLDB_LOGF(log, "parsing: %s", raw->c_str()); 4726 XMLDocument doc; 4727 4728 if (!doc.ParseMemory(raw->c_str(), raw->size(), "noname.xml")) 4729 return llvm::createStringError(llvm::inconvertibleErrorCode(), 4730 "Error reading noname.xml"); 4731 4732 XMLNode root_element = doc.GetRootElement("library-list"); 4733 if (!root_element) 4734 return llvm::createStringError(llvm::inconvertibleErrorCode(), 4735 "Error finding library-list xml element"); 4736 4737 // FIXME: we're silently ignoring invalid data here 4738 root_element.ForEachChildElementWithName( 4739 "library", [log, &list](const XMLNode &library) -> bool { 4740 LoadedModuleInfoList::LoadedModuleInfo module; 4741 4742 std::string name = library.GetAttributeValue("name"); 4743 module.set_name(name); 4744 4745 // The base address of a given library will be the address of its 4746 // first section. Most remotes send only one section for Windows 4747 // targets for example. 4748 const XMLNode §ion = 4749 library.FindFirstChildElementWithName("section"); 4750 std::string address = section.GetAttributeValue("address"); 4751 uint64_t address_value = LLDB_INVALID_ADDRESS; 4752 llvm::to_integer(address, address_value); 4753 module.set_base(address_value); 4754 // These addresses are absolute values. 4755 module.set_base_is_offset(false); 4756 4757 if (log) { 4758 std::string name; 4759 lldb::addr_t base = 0; 4760 bool base_is_offset; 4761 module.get_name(name); 4762 module.get_base(base); 4763 module.get_base_is_offset(base_is_offset); 4764 4765 LLDB_LOGF(log, "found (base:0x%08" PRIx64 "[%s], name:'%s')", base, 4766 (base_is_offset ? "offset" : "absolute"), name.c_str()); 4767 } 4768 4769 list.add(module); 4770 return true; // Keep iterating over all "library" elements in the root 4771 // node 4772 }); 4773 4774 if (log) 4775 LLDB_LOGF(log, "found %" PRId32 " modules in total", 4776 (int)list.m_list.size()); 4777 return list; 4778 } else { 4779 return llvm::createStringError(llvm::inconvertibleErrorCode(), 4780 "Remote libraries not supported"); 4781 } 4782 } 4783 4784 lldb::ModuleSP ProcessGDBRemote::LoadModuleAtAddress(const FileSpec &file, 4785 lldb::addr_t link_map, 4786 lldb::addr_t base_addr, 4787 bool value_is_offset) { 4788 DynamicLoader *loader = GetDynamicLoader(); 4789 if (!loader) 4790 return nullptr; 4791 4792 return loader->LoadModuleAtAddress(file, link_map, base_addr, 4793 value_is_offset); 4794 } 4795 4796 llvm::Error ProcessGDBRemote::LoadModules() { 4797 using lldb_private::process_gdb_remote::ProcessGDBRemote; 4798 4799 // request a list of loaded libraries from GDBServer 4800 llvm::Expected<LoadedModuleInfoList> module_list = GetLoadedModuleList(); 4801 if (!module_list) 4802 return module_list.takeError(); 4803 4804 // get a list of all the modules 4805 ModuleList new_modules; 4806 4807 for (LoadedModuleInfoList::LoadedModuleInfo &modInfo : module_list->m_list) { 4808 std::string mod_name; 4809 lldb::addr_t mod_base; 4810 lldb::addr_t link_map; 4811 bool mod_base_is_offset; 4812 4813 bool valid = true; 4814 valid &= modInfo.get_name(mod_name); 4815 valid &= modInfo.get_base(mod_base); 4816 valid &= modInfo.get_base_is_offset(mod_base_is_offset); 4817 if (!valid) 4818 continue; 4819 4820 if (!modInfo.get_link_map(link_map)) 4821 link_map = LLDB_INVALID_ADDRESS; 4822 4823 FileSpec file(mod_name); 4824 FileSystem::Instance().Resolve(file); 4825 lldb::ModuleSP module_sp = 4826 LoadModuleAtAddress(file, link_map, mod_base, mod_base_is_offset); 4827 4828 if (module_sp.get()) 4829 new_modules.Append(module_sp); 4830 } 4831 4832 if (new_modules.GetSize() > 0) { 4833 ModuleList removed_modules; 4834 Target &target = GetTarget(); 4835 ModuleList &loaded_modules = m_process->GetTarget().GetImages(); 4836 4837 for (size_t i = 0; i < loaded_modules.GetSize(); ++i) { 4838 const lldb::ModuleSP loaded_module = loaded_modules.GetModuleAtIndex(i); 4839 4840 bool found = false; 4841 for (size_t j = 0; j < new_modules.GetSize(); ++j) { 4842 if (new_modules.GetModuleAtIndex(j).get() == loaded_module.get()) 4843 found = true; 4844 } 4845 4846 // The main executable will never be included in libraries-svr4, don't 4847 // remove it 4848 if (!found && 4849 loaded_module.get() != target.GetExecutableModulePointer()) { 4850 removed_modules.Append(loaded_module); 4851 } 4852 } 4853 4854 loaded_modules.Remove(removed_modules); 4855 m_process->GetTarget().ModulesDidUnload(removed_modules, false); 4856 4857 new_modules.ForEach([&target](const lldb::ModuleSP module_sp) -> bool { 4858 lldb_private::ObjectFile *obj = module_sp->GetObjectFile(); 4859 if (!obj) 4860 return true; 4861 4862 if (obj->GetType() != ObjectFile::Type::eTypeExecutable) 4863 return true; 4864 4865 lldb::ModuleSP module_copy_sp = module_sp; 4866 target.SetExecutableModule(module_copy_sp, eLoadDependentsNo); 4867 return false; 4868 }); 4869 4870 loaded_modules.AppendIfNeeded(new_modules); 4871 m_process->GetTarget().ModulesDidLoad(new_modules); 4872 } 4873 4874 return llvm::ErrorSuccess(); 4875 } 4876 4877 Status ProcessGDBRemote::GetFileLoadAddress(const FileSpec &file, 4878 bool &is_loaded, 4879 lldb::addr_t &load_addr) { 4880 is_loaded = false; 4881 load_addr = LLDB_INVALID_ADDRESS; 4882 4883 std::string file_path = file.GetPath(false); 4884 if (file_path.empty()) 4885 return Status("Empty file name specified"); 4886 4887 StreamString packet; 4888 packet.PutCString("qFileLoadAddress:"); 4889 packet.PutStringAsRawHex8(file_path); 4890 4891 StringExtractorGDBRemote response; 4892 if (m_gdb_comm.SendPacketAndWaitForResponse(packet.GetString(), response) != 4893 GDBRemoteCommunication::PacketResult::Success) 4894 return Status("Sending qFileLoadAddress packet failed"); 4895 4896 if (response.IsErrorResponse()) { 4897 if (response.GetError() == 1) { 4898 // The file is not loaded into the inferior 4899 is_loaded = false; 4900 load_addr = LLDB_INVALID_ADDRESS; 4901 return Status(); 4902 } 4903 4904 return Status( 4905 "Fetching file load address from remote server returned an error"); 4906 } 4907 4908 if (response.IsNormalResponse()) { 4909 is_loaded = true; 4910 load_addr = response.GetHexMaxU64(false, LLDB_INVALID_ADDRESS); 4911 return Status(); 4912 } 4913 4914 return Status( 4915 "Unknown error happened during sending the load address packet"); 4916 } 4917 4918 void ProcessGDBRemote::ModulesDidLoad(ModuleList &module_list) { 4919 // We must call the lldb_private::Process::ModulesDidLoad () first before we 4920 // do anything 4921 Process::ModulesDidLoad(module_list); 4922 4923 // After loading shared libraries, we can ask our remote GDB server if it 4924 // needs any symbols. 4925 m_gdb_comm.ServeSymbolLookups(this); 4926 } 4927 4928 void ProcessGDBRemote::HandleAsyncStdout(llvm::StringRef out) { 4929 AppendSTDOUT(out.data(), out.size()); 4930 } 4931 4932 static const char *end_delimiter = "--end--;"; 4933 static const int end_delimiter_len = 8; 4934 4935 void ProcessGDBRemote::HandleAsyncMisc(llvm::StringRef data) { 4936 std::string input = data.str(); // '1' to move beyond 'A' 4937 if (m_partial_profile_data.length() > 0) { 4938 m_partial_profile_data.append(input); 4939 input = m_partial_profile_data; 4940 m_partial_profile_data.clear(); 4941 } 4942 4943 size_t found, pos = 0, len = input.length(); 4944 while ((found = input.find(end_delimiter, pos)) != std::string::npos) { 4945 StringExtractorGDBRemote profileDataExtractor( 4946 input.substr(pos, found).c_str()); 4947 std::string profile_data = 4948 HarmonizeThreadIdsForProfileData(profileDataExtractor); 4949 BroadcastAsyncProfileData(profile_data); 4950 4951 pos = found + end_delimiter_len; 4952 } 4953 4954 if (pos < len) { 4955 // Last incomplete chunk. 4956 m_partial_profile_data = input.substr(pos); 4957 } 4958 } 4959 4960 std::string ProcessGDBRemote::HarmonizeThreadIdsForProfileData( 4961 StringExtractorGDBRemote &profileDataExtractor) { 4962 std::map<uint64_t, uint32_t> new_thread_id_to_used_usec_map; 4963 std::string output; 4964 llvm::raw_string_ostream output_stream(output); 4965 llvm::StringRef name, value; 4966 4967 // Going to assuming thread_used_usec comes first, else bail out. 4968 while (profileDataExtractor.GetNameColonValue(name, value)) { 4969 if (name.compare("thread_used_id") == 0) { 4970 StringExtractor threadIDHexExtractor(value); 4971 uint64_t thread_id = threadIDHexExtractor.GetHexMaxU64(false, 0); 4972 4973 bool has_used_usec = false; 4974 uint32_t curr_used_usec = 0; 4975 llvm::StringRef usec_name, usec_value; 4976 uint32_t input_file_pos = profileDataExtractor.GetFilePos(); 4977 if (profileDataExtractor.GetNameColonValue(usec_name, usec_value)) { 4978 if (usec_name.equals("thread_used_usec")) { 4979 has_used_usec = true; 4980 usec_value.getAsInteger(0, curr_used_usec); 4981 } else { 4982 // We didn't find what we want, it is probably an older version. Bail 4983 // out. 4984 profileDataExtractor.SetFilePos(input_file_pos); 4985 } 4986 } 4987 4988 if (has_used_usec) { 4989 uint32_t prev_used_usec = 0; 4990 std::map<uint64_t, uint32_t>::iterator iterator = 4991 m_thread_id_to_used_usec_map.find(thread_id); 4992 if (iterator != m_thread_id_to_used_usec_map.end()) { 4993 prev_used_usec = m_thread_id_to_used_usec_map[thread_id]; 4994 } 4995 4996 uint32_t real_used_usec = curr_used_usec - prev_used_usec; 4997 // A good first time record is one that runs for at least 0.25 sec 4998 bool good_first_time = 4999 (prev_used_usec == 0) && (real_used_usec > 250000); 5000 bool good_subsequent_time = 5001 (prev_used_usec > 0) && 5002 ((real_used_usec > 0) || (HasAssignedIndexIDToThread(thread_id))); 5003 5004 if (good_first_time || good_subsequent_time) { 5005 // We try to avoid doing too many index id reservation, resulting in 5006 // fast increase of index ids. 5007 5008 output_stream << name << ":"; 5009 int32_t index_id = AssignIndexIDToThread(thread_id); 5010 output_stream << index_id << ";"; 5011 5012 output_stream << usec_name << ":" << usec_value << ";"; 5013 } else { 5014 // Skip past 'thread_used_name'. 5015 llvm::StringRef local_name, local_value; 5016 profileDataExtractor.GetNameColonValue(local_name, local_value); 5017 } 5018 5019 // Store current time as previous time so that they can be compared 5020 // later. 5021 new_thread_id_to_used_usec_map[thread_id] = curr_used_usec; 5022 } else { 5023 // Bail out and use old string. 5024 output_stream << name << ":" << value << ";"; 5025 } 5026 } else { 5027 output_stream << name << ":" << value << ";"; 5028 } 5029 } 5030 output_stream << end_delimiter; 5031 m_thread_id_to_used_usec_map = new_thread_id_to_used_usec_map; 5032 5033 return output_stream.str(); 5034 } 5035 5036 void ProcessGDBRemote::HandleStopReply() { 5037 if (GetStopID() != 0) 5038 return; 5039 5040 if (GetID() == LLDB_INVALID_PROCESS_ID) { 5041 lldb::pid_t pid = m_gdb_comm.GetCurrentProcessID(); 5042 if (pid != LLDB_INVALID_PROCESS_ID) 5043 SetID(pid); 5044 } 5045 BuildDynamicRegisterInfo(true); 5046 } 5047 5048 llvm::Expected<bool> ProcessGDBRemote::SaveCore(llvm::StringRef outfile) { 5049 if (!m_gdb_comm.GetSaveCoreSupported()) 5050 return false; 5051 5052 StreamString packet; 5053 packet.PutCString("qSaveCore;path-hint:"); 5054 packet.PutStringAsRawHex8(outfile); 5055 5056 StringExtractorGDBRemote response; 5057 if (m_gdb_comm.SendPacketAndWaitForResponse(packet.GetString(), response) == 5058 GDBRemoteCommunication::PacketResult::Success) { 5059 // TODO: grab error message from the packet? StringExtractor seems to 5060 // be missing a method for that 5061 if (response.IsErrorResponse()) 5062 return llvm::createStringError( 5063 llvm::inconvertibleErrorCode(), 5064 llvm::formatv("qSaveCore returned an error")); 5065 5066 std::string path; 5067 5068 // process the response 5069 for (auto x : llvm::split(response.GetStringRef(), ';')) { 5070 if (x.consume_front("core-path:")) 5071 StringExtractor(x).GetHexByteString(path); 5072 } 5073 5074 // verify that we've gotten what we need 5075 if (path.empty()) 5076 return llvm::createStringError(llvm::inconvertibleErrorCode(), 5077 "qSaveCore returned no core path"); 5078 5079 // now transfer the core file 5080 FileSpec remote_core{llvm::StringRef(path)}; 5081 Platform &platform = *GetTarget().GetPlatform(); 5082 Status error = platform.GetFile(remote_core, FileSpec(outfile)); 5083 5084 if (platform.IsRemote()) { 5085 // NB: we unlink the file on error too 5086 platform.Unlink(remote_core); 5087 if (error.Fail()) 5088 return error.ToError(); 5089 } 5090 5091 return true; 5092 } 5093 5094 return llvm::createStringError(llvm::inconvertibleErrorCode(), 5095 "Unable to send qSaveCore"); 5096 } 5097 5098 static const char *const s_async_json_packet_prefix = "JSON-async:"; 5099 5100 static StructuredData::ObjectSP 5101 ParseStructuredDataPacket(llvm::StringRef packet) { 5102 Log *log = GetLog(GDBRLog::Process); 5103 5104 if (!packet.consume_front(s_async_json_packet_prefix)) { 5105 if (log) { 5106 LLDB_LOGF( 5107 log, 5108 "GDBRemoteCommunicationClientBase::%s() received $J packet " 5109 "but was not a StructuredData packet: packet starts with " 5110 "%s", 5111 __FUNCTION__, 5112 packet.slice(0, strlen(s_async_json_packet_prefix)).str().c_str()); 5113 } 5114 return StructuredData::ObjectSP(); 5115 } 5116 5117 // This is an asynchronous JSON packet, destined for a StructuredDataPlugin. 5118 StructuredData::ObjectSP json_sp = StructuredData::ParseJSON(packet); 5119 if (log) { 5120 if (json_sp) { 5121 StreamString json_str; 5122 json_sp->Dump(json_str, true); 5123 json_str.Flush(); 5124 LLDB_LOGF(log, 5125 "ProcessGDBRemote::%s() " 5126 "received Async StructuredData packet: %s", 5127 __FUNCTION__, json_str.GetData()); 5128 } else { 5129 LLDB_LOGF(log, 5130 "ProcessGDBRemote::%s" 5131 "() received StructuredData packet:" 5132 " parse failure", 5133 __FUNCTION__); 5134 } 5135 } 5136 return json_sp; 5137 } 5138 5139 void ProcessGDBRemote::HandleAsyncStructuredDataPacket(llvm::StringRef data) { 5140 auto structured_data_sp = ParseStructuredDataPacket(data); 5141 if (structured_data_sp) 5142 RouteAsyncStructuredData(structured_data_sp); 5143 } 5144 5145 class CommandObjectProcessGDBRemoteSpeedTest : public CommandObjectParsed { 5146 public: 5147 CommandObjectProcessGDBRemoteSpeedTest(CommandInterpreter &interpreter) 5148 : CommandObjectParsed(interpreter, "process plugin packet speed-test", 5149 "Tests packet speeds of various sizes to determine " 5150 "the performance characteristics of the GDB remote " 5151 "connection. ", 5152 nullptr), 5153 m_option_group(), 5154 m_num_packets(LLDB_OPT_SET_1, false, "count", 'c', 0, eArgTypeCount, 5155 "The number of packets to send of each varying size " 5156 "(default is 1000).", 5157 1000), 5158 m_max_send(LLDB_OPT_SET_1, false, "max-send", 's', 0, eArgTypeCount, 5159 "The maximum number of bytes to send in a packet. Sizes " 5160 "increase in powers of 2 while the size is less than or " 5161 "equal to this option value. (default 1024).", 5162 1024), 5163 m_max_recv(LLDB_OPT_SET_1, false, "max-receive", 'r', 0, eArgTypeCount, 5164 "The maximum number of bytes to receive in a packet. Sizes " 5165 "increase in powers of 2 while the size is less than or " 5166 "equal to this option value. (default 1024).", 5167 1024), 5168 m_json(LLDB_OPT_SET_1, false, "json", 'j', 5169 "Print the output as JSON data for easy parsing.", false, true) { 5170 m_option_group.Append(&m_num_packets, LLDB_OPT_SET_ALL, LLDB_OPT_SET_1); 5171 m_option_group.Append(&m_max_send, LLDB_OPT_SET_ALL, LLDB_OPT_SET_1); 5172 m_option_group.Append(&m_max_recv, LLDB_OPT_SET_ALL, LLDB_OPT_SET_1); 5173 m_option_group.Append(&m_json, LLDB_OPT_SET_ALL, LLDB_OPT_SET_1); 5174 m_option_group.Finalize(); 5175 } 5176 5177 ~CommandObjectProcessGDBRemoteSpeedTest() override = default; 5178 5179 Options *GetOptions() override { return &m_option_group; } 5180 5181 bool DoExecute(Args &command, CommandReturnObject &result) override { 5182 const size_t argc = command.GetArgumentCount(); 5183 if (argc == 0) { 5184 ProcessGDBRemote *process = 5185 (ProcessGDBRemote *)m_interpreter.GetExecutionContext() 5186 .GetProcessPtr(); 5187 if (process) { 5188 StreamSP output_stream_sp( 5189 m_interpreter.GetDebugger().GetAsyncOutputStream()); 5190 result.SetImmediateOutputStream(output_stream_sp); 5191 5192 const uint32_t num_packets = 5193 (uint32_t)m_num_packets.GetOptionValue().GetCurrentValue(); 5194 const uint64_t max_send = m_max_send.GetOptionValue().GetCurrentValue(); 5195 const uint64_t max_recv = m_max_recv.GetOptionValue().GetCurrentValue(); 5196 const bool json = m_json.GetOptionValue().GetCurrentValue(); 5197 const uint64_t k_recv_amount = 5198 4 * 1024 * 1024; // Receive amount in bytes 5199 process->GetGDBRemote().TestPacketSpeed( 5200 num_packets, max_send, max_recv, k_recv_amount, json, 5201 output_stream_sp ? *output_stream_sp : result.GetOutputStream()); 5202 result.SetStatus(eReturnStatusSuccessFinishResult); 5203 return true; 5204 } 5205 } else { 5206 result.AppendErrorWithFormat("'%s' takes no arguments", 5207 m_cmd_name.c_str()); 5208 } 5209 result.SetStatus(eReturnStatusFailed); 5210 return false; 5211 } 5212 5213 protected: 5214 OptionGroupOptions m_option_group; 5215 OptionGroupUInt64 m_num_packets; 5216 OptionGroupUInt64 m_max_send; 5217 OptionGroupUInt64 m_max_recv; 5218 OptionGroupBoolean m_json; 5219 }; 5220 5221 class CommandObjectProcessGDBRemotePacketHistory : public CommandObjectParsed { 5222 private: 5223 public: 5224 CommandObjectProcessGDBRemotePacketHistory(CommandInterpreter &interpreter) 5225 : CommandObjectParsed(interpreter, "process plugin packet history", 5226 "Dumps the packet history buffer. ", nullptr) {} 5227 5228 ~CommandObjectProcessGDBRemotePacketHistory() override = default; 5229 5230 bool DoExecute(Args &command, CommandReturnObject &result) override { 5231 ProcessGDBRemote *process = 5232 (ProcessGDBRemote *)m_interpreter.GetExecutionContext().GetProcessPtr(); 5233 if (process) { 5234 process->DumpPluginHistory(result.GetOutputStream()); 5235 result.SetStatus(eReturnStatusSuccessFinishResult); 5236 return true; 5237 } 5238 result.SetStatus(eReturnStatusFailed); 5239 return false; 5240 } 5241 }; 5242 5243 class CommandObjectProcessGDBRemotePacketXferSize : public CommandObjectParsed { 5244 private: 5245 public: 5246 CommandObjectProcessGDBRemotePacketXferSize(CommandInterpreter &interpreter) 5247 : CommandObjectParsed( 5248 interpreter, "process plugin packet xfer-size", 5249 "Maximum size that lldb will try to read/write one one chunk.", 5250 nullptr) { 5251 CommandArgumentData max_arg{eArgTypeUnsignedInteger, eArgRepeatPlain}; 5252 m_arguments.push_back({max_arg}); 5253 } 5254 5255 ~CommandObjectProcessGDBRemotePacketXferSize() override = default; 5256 5257 bool DoExecute(Args &command, CommandReturnObject &result) override { 5258 const size_t argc = command.GetArgumentCount(); 5259 if (argc == 0) { 5260 result.AppendErrorWithFormat("'%s' takes an argument to specify the max " 5261 "amount to be transferred when " 5262 "reading/writing", 5263 m_cmd_name.c_str()); 5264 return false; 5265 } 5266 5267 ProcessGDBRemote *process = 5268 (ProcessGDBRemote *)m_interpreter.GetExecutionContext().GetProcessPtr(); 5269 if (process) { 5270 const char *packet_size = command.GetArgumentAtIndex(0); 5271 errno = 0; 5272 uint64_t user_specified_max = strtoul(packet_size, nullptr, 10); 5273 if (errno == 0 && user_specified_max != 0) { 5274 process->SetUserSpecifiedMaxMemoryTransferSize(user_specified_max); 5275 result.SetStatus(eReturnStatusSuccessFinishResult); 5276 return true; 5277 } 5278 } 5279 result.SetStatus(eReturnStatusFailed); 5280 return false; 5281 } 5282 }; 5283 5284 class CommandObjectProcessGDBRemotePacketSend : public CommandObjectParsed { 5285 private: 5286 public: 5287 CommandObjectProcessGDBRemotePacketSend(CommandInterpreter &interpreter) 5288 : CommandObjectParsed(interpreter, "process plugin packet send", 5289 "Send a custom packet through the GDB remote " 5290 "protocol and print the answer. " 5291 "The packet header and footer will automatically " 5292 "be added to the packet prior to sending and " 5293 "stripped from the result.", 5294 nullptr) { 5295 CommandArgumentData packet_arg{eArgTypeNone, eArgRepeatStar}; 5296 m_arguments.push_back({packet_arg}); 5297 } 5298 5299 ~CommandObjectProcessGDBRemotePacketSend() override = default; 5300 5301 bool DoExecute(Args &command, CommandReturnObject &result) override { 5302 const size_t argc = command.GetArgumentCount(); 5303 if (argc == 0) { 5304 result.AppendErrorWithFormat( 5305 "'%s' takes a one or more packet content arguments", 5306 m_cmd_name.c_str()); 5307 return false; 5308 } 5309 5310 ProcessGDBRemote *process = 5311 (ProcessGDBRemote *)m_interpreter.GetExecutionContext().GetProcessPtr(); 5312 if (process) { 5313 for (size_t i = 0; i < argc; ++i) { 5314 const char *packet_cstr = command.GetArgumentAtIndex(0); 5315 StringExtractorGDBRemote response; 5316 process->GetGDBRemote().SendPacketAndWaitForResponse( 5317 packet_cstr, response, process->GetInterruptTimeout()); 5318 result.SetStatus(eReturnStatusSuccessFinishResult); 5319 Stream &output_strm = result.GetOutputStream(); 5320 output_strm.Printf(" packet: %s\n", packet_cstr); 5321 std::string response_str = std::string(response.GetStringRef()); 5322 5323 if (strstr(packet_cstr, "qGetProfileData") != nullptr) { 5324 response_str = process->HarmonizeThreadIdsForProfileData(response); 5325 } 5326 5327 if (response_str.empty()) 5328 output_strm.PutCString("response: \nerror: UNIMPLEMENTED\n"); 5329 else 5330 output_strm.Printf("response: %s\n", response.GetStringRef().data()); 5331 } 5332 } 5333 return true; 5334 } 5335 }; 5336 5337 class CommandObjectProcessGDBRemotePacketMonitor : public CommandObjectRaw { 5338 private: 5339 public: 5340 CommandObjectProcessGDBRemotePacketMonitor(CommandInterpreter &interpreter) 5341 : CommandObjectRaw(interpreter, "process plugin packet monitor", 5342 "Send a qRcmd packet through the GDB remote protocol " 5343 "and print the response." 5344 "The argument passed to this command will be hex " 5345 "encoded into a valid 'qRcmd' packet, sent and the " 5346 "response will be printed.") {} 5347 5348 ~CommandObjectProcessGDBRemotePacketMonitor() override = default; 5349 5350 bool DoExecute(llvm::StringRef command, 5351 CommandReturnObject &result) override { 5352 if (command.empty()) { 5353 result.AppendErrorWithFormat("'%s' takes a command string argument", 5354 m_cmd_name.c_str()); 5355 return false; 5356 } 5357 5358 ProcessGDBRemote *process = 5359 (ProcessGDBRemote *)m_interpreter.GetExecutionContext().GetProcessPtr(); 5360 if (process) { 5361 StreamString packet; 5362 packet.PutCString("qRcmd,"); 5363 packet.PutBytesAsRawHex8(command.data(), command.size()); 5364 5365 StringExtractorGDBRemote response; 5366 Stream &output_strm = result.GetOutputStream(); 5367 process->GetGDBRemote().SendPacketAndReceiveResponseWithOutputSupport( 5368 packet.GetString(), response, process->GetInterruptTimeout(), 5369 [&output_strm](llvm::StringRef output) { output_strm << output; }); 5370 result.SetStatus(eReturnStatusSuccessFinishResult); 5371 output_strm.Printf(" packet: %s\n", packet.GetData()); 5372 const std::string &response_str = std::string(response.GetStringRef()); 5373 5374 if (response_str.empty()) 5375 output_strm.PutCString("response: \nerror: UNIMPLEMENTED\n"); 5376 else 5377 output_strm.Printf("response: %s\n", response.GetStringRef().data()); 5378 } 5379 return true; 5380 } 5381 }; 5382 5383 class CommandObjectProcessGDBRemotePacket : public CommandObjectMultiword { 5384 private: 5385 public: 5386 CommandObjectProcessGDBRemotePacket(CommandInterpreter &interpreter) 5387 : CommandObjectMultiword(interpreter, "process plugin packet", 5388 "Commands that deal with GDB remote packets.", 5389 nullptr) { 5390 LoadSubCommand( 5391 "history", 5392 CommandObjectSP( 5393 new CommandObjectProcessGDBRemotePacketHistory(interpreter))); 5394 LoadSubCommand( 5395 "send", CommandObjectSP( 5396 new CommandObjectProcessGDBRemotePacketSend(interpreter))); 5397 LoadSubCommand( 5398 "monitor", 5399 CommandObjectSP( 5400 new CommandObjectProcessGDBRemotePacketMonitor(interpreter))); 5401 LoadSubCommand( 5402 "xfer-size", 5403 CommandObjectSP( 5404 new CommandObjectProcessGDBRemotePacketXferSize(interpreter))); 5405 LoadSubCommand("speed-test", 5406 CommandObjectSP(new CommandObjectProcessGDBRemoteSpeedTest( 5407 interpreter))); 5408 } 5409 5410 ~CommandObjectProcessGDBRemotePacket() override = default; 5411 }; 5412 5413 class CommandObjectMultiwordProcessGDBRemote : public CommandObjectMultiword { 5414 public: 5415 CommandObjectMultiwordProcessGDBRemote(CommandInterpreter &interpreter) 5416 : CommandObjectMultiword( 5417 interpreter, "process plugin", 5418 "Commands for operating on a ProcessGDBRemote process.", 5419 "process plugin <subcommand> [<subcommand-options>]") { 5420 LoadSubCommand( 5421 "packet", 5422 CommandObjectSP(new CommandObjectProcessGDBRemotePacket(interpreter))); 5423 } 5424 5425 ~CommandObjectMultiwordProcessGDBRemote() override = default; 5426 }; 5427 5428 CommandObject *ProcessGDBRemote::GetPluginCommandObject() { 5429 if (!m_command_sp) 5430 m_command_sp = std::make_shared<CommandObjectMultiwordProcessGDBRemote>( 5431 GetTarget().GetDebugger().GetCommandInterpreter()); 5432 return m_command_sp.get(); 5433 } 5434 5435 void ProcessGDBRemote::DidForkSwitchSoftwareBreakpoints(bool enable) { 5436 GetBreakpointSiteList().ForEach([this, enable](BreakpointSite *bp_site) { 5437 if (bp_site->IsEnabled() && 5438 (bp_site->GetType() == BreakpointSite::eSoftware || 5439 bp_site->GetType() == BreakpointSite::eExternal)) { 5440 m_gdb_comm.SendGDBStoppointTypePacket( 5441 eBreakpointSoftware, enable, bp_site->GetLoadAddress(), 5442 GetSoftwareBreakpointTrapOpcode(bp_site), GetInterruptTimeout()); 5443 } 5444 }); 5445 } 5446 5447 void ProcessGDBRemote::DidForkSwitchHardwareTraps(bool enable) { 5448 if (m_gdb_comm.SupportsGDBStoppointPacket(eBreakpointHardware)) { 5449 GetBreakpointSiteList().ForEach([this, enable](BreakpointSite *bp_site) { 5450 if (bp_site->IsEnabled() && 5451 bp_site->GetType() == BreakpointSite::eHardware) { 5452 m_gdb_comm.SendGDBStoppointTypePacket( 5453 eBreakpointHardware, enable, bp_site->GetLoadAddress(), 5454 GetSoftwareBreakpointTrapOpcode(bp_site), GetInterruptTimeout()); 5455 } 5456 }); 5457 } 5458 5459 WatchpointList &wps = GetTarget().GetWatchpointList(); 5460 size_t wp_count = wps.GetSize(); 5461 for (size_t i = 0; i < wp_count; ++i) { 5462 WatchpointSP wp = wps.GetByIndex(i); 5463 if (wp->IsEnabled()) { 5464 GDBStoppointType type = GetGDBStoppointType(wp.get()); 5465 m_gdb_comm.SendGDBStoppointTypePacket(type, enable, wp->GetLoadAddress(), 5466 wp->GetByteSize(), 5467 GetInterruptTimeout()); 5468 } 5469 } 5470 } 5471 5472 void ProcessGDBRemote::DidFork(lldb::pid_t child_pid, lldb::tid_t child_tid) { 5473 Log *log = GetLog(GDBRLog::Process); 5474 5475 lldb::pid_t parent_pid = m_gdb_comm.GetCurrentProcessID(); 5476 // Any valid TID will suffice, thread-relevant actions will set a proper TID 5477 // anyway. 5478 lldb::tid_t parent_tid = m_thread_ids.front(); 5479 5480 lldb::pid_t follow_pid, detach_pid; 5481 lldb::tid_t follow_tid, detach_tid; 5482 5483 switch (GetFollowForkMode()) { 5484 case eFollowParent: 5485 follow_pid = parent_pid; 5486 follow_tid = parent_tid; 5487 detach_pid = child_pid; 5488 detach_tid = child_tid; 5489 break; 5490 case eFollowChild: 5491 follow_pid = child_pid; 5492 follow_tid = child_tid; 5493 detach_pid = parent_pid; 5494 detach_tid = parent_tid; 5495 break; 5496 } 5497 5498 // Switch to the process that is going to be detached. 5499 if (!m_gdb_comm.SetCurrentThread(detach_tid, detach_pid)) { 5500 LLDB_LOG(log, "ProcessGDBRemote::DidFork() unable to set pid/tid"); 5501 return; 5502 } 5503 5504 // Disable all software breakpoints in the forked process. 5505 if (m_gdb_comm.SupportsGDBStoppointPacket(eBreakpointSoftware)) 5506 DidForkSwitchSoftwareBreakpoints(false); 5507 5508 // Remove hardware breakpoints / watchpoints from parent process if we're 5509 // following child. 5510 if (GetFollowForkMode() == eFollowChild) 5511 DidForkSwitchHardwareTraps(false); 5512 5513 // Switch to the process that is going to be followed 5514 if (!m_gdb_comm.SetCurrentThread(follow_tid, follow_pid) || 5515 !m_gdb_comm.SetCurrentThreadForRun(follow_tid, follow_pid)) { 5516 LLDB_LOG(log, "ProcessGDBRemote::DidFork() unable to reset pid/tid"); 5517 return; 5518 } 5519 5520 LLDB_LOG(log, "Detaching process {0}", detach_pid); 5521 Status error = m_gdb_comm.Detach(false, detach_pid); 5522 if (error.Fail()) { 5523 LLDB_LOG(log, "ProcessGDBRemote::DidFork() detach packet send failed: {0}", 5524 error.AsCString() ? error.AsCString() : "<unknown error>"); 5525 return; 5526 } 5527 5528 // Hardware breakpoints/watchpoints are not inherited implicitly, 5529 // so we need to readd them if we're following child. 5530 if (GetFollowForkMode() == eFollowChild) { 5531 DidForkSwitchHardwareTraps(true); 5532 // Update our PID 5533 SetID(child_pid); 5534 } 5535 } 5536 5537 void ProcessGDBRemote::DidVFork(lldb::pid_t child_pid, lldb::tid_t child_tid) { 5538 Log *log = GetLog(GDBRLog::Process); 5539 5540 assert(!m_vfork_in_progress); 5541 m_vfork_in_progress = true; 5542 5543 // Disable all software breakpoints for the duration of vfork. 5544 if (m_gdb_comm.SupportsGDBStoppointPacket(eBreakpointSoftware)) 5545 DidForkSwitchSoftwareBreakpoints(false); 5546 5547 lldb::pid_t detach_pid; 5548 lldb::tid_t detach_tid; 5549 5550 switch (GetFollowForkMode()) { 5551 case eFollowParent: 5552 detach_pid = child_pid; 5553 detach_tid = child_tid; 5554 break; 5555 case eFollowChild: 5556 detach_pid = m_gdb_comm.GetCurrentProcessID(); 5557 // Any valid TID will suffice, thread-relevant actions will set a proper TID 5558 // anyway. 5559 detach_tid = m_thread_ids.front(); 5560 5561 // Switch to the parent process before detaching it. 5562 if (!m_gdb_comm.SetCurrentThread(detach_tid, detach_pid)) { 5563 LLDB_LOG(log, "ProcessGDBRemote::DidFork() unable to set pid/tid"); 5564 return; 5565 } 5566 5567 // Remove hardware breakpoints / watchpoints from the parent process. 5568 DidForkSwitchHardwareTraps(false); 5569 5570 // Switch to the child process. 5571 if (!m_gdb_comm.SetCurrentThread(child_tid, child_pid) || 5572 !m_gdb_comm.SetCurrentThreadForRun(child_tid, child_pid)) { 5573 LLDB_LOG(log, "ProcessGDBRemote::DidFork() unable to reset pid/tid"); 5574 return; 5575 } 5576 break; 5577 } 5578 5579 LLDB_LOG(log, "Detaching process {0}", detach_pid); 5580 Status error = m_gdb_comm.Detach(false, detach_pid); 5581 if (error.Fail()) { 5582 LLDB_LOG(log, 5583 "ProcessGDBRemote::DidFork() detach packet send failed: {0}", 5584 error.AsCString() ? error.AsCString() : "<unknown error>"); 5585 return; 5586 } 5587 5588 if (GetFollowForkMode() == eFollowChild) { 5589 // Update our PID 5590 SetID(child_pid); 5591 } 5592 } 5593 5594 void ProcessGDBRemote::DidVForkDone() { 5595 assert(m_vfork_in_progress); 5596 m_vfork_in_progress = false; 5597 5598 // Reenable all software breakpoints that were enabled before vfork. 5599 if (m_gdb_comm.SupportsGDBStoppointPacket(eBreakpointSoftware)) 5600 DidForkSwitchSoftwareBreakpoints(true); 5601 } 5602 5603 void ProcessGDBRemote::DidExec() { 5604 // If we are following children, vfork is finished by exec (rather than 5605 // vforkdone that is submitted for parent). 5606 if (GetFollowForkMode() == eFollowChild) 5607 m_vfork_in_progress = false; 5608 Process::DidExec(); 5609 } 5610