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