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