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