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