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