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