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