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