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