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