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->GetName() && 2408 platform_sp->GetName().GetStringRef() == 2409 PlatformRemoteiOS::GetPluginNameStatic()) { 2410 if (m_destroy_tried_resuming) { 2411 if (log) 2412 log->PutCString("ProcessGDBRemote::DoDestroy() - Tried resuming to " 2413 "destroy once already, not doing it again."); 2414 } else { 2415 // At present, the plans are discarded and the breakpoints disabled 2416 // Process::Destroy, but we really need it to happen here and it 2417 // doesn't matter if we do it twice. 2418 m_thread_list.DiscardThreadPlans(); 2419 DisableAllBreakpointSites(); 2420 2421 bool stop_looks_like_crash = false; 2422 ThreadList &threads = GetThreadList(); 2423 2424 { 2425 std::lock_guard<std::recursive_mutex> guard(threads.GetMutex()); 2426 2427 size_t num_threads = threads.GetSize(); 2428 for (size_t i = 0; i < num_threads; i++) { 2429 ThreadSP thread_sp = threads.GetThreadAtIndex(i); 2430 StopInfoSP stop_info_sp = thread_sp->GetPrivateStopInfo(); 2431 StopReason reason = eStopReasonInvalid; 2432 if (stop_info_sp) 2433 reason = stop_info_sp->GetStopReason(); 2434 if (reason == eStopReasonBreakpoint || 2435 reason == eStopReasonException) { 2436 LLDB_LOGF(log, 2437 "ProcessGDBRemote::DoDestroy() - thread: 0x%4.4" PRIx64 2438 " stopped with reason: %s.", 2439 thread_sp->GetProtocolID(), 2440 stop_info_sp->GetDescription()); 2441 stop_looks_like_crash = true; 2442 break; 2443 } 2444 } 2445 } 2446 2447 if (stop_looks_like_crash) { 2448 if (log) 2449 log->PutCString("ProcessGDBRemote::DoDestroy() - Stopped at a " 2450 "breakpoint, continue and then kill."); 2451 m_destroy_tried_resuming = true; 2452 2453 // If we are going to run again before killing, it would be good to 2454 // suspend all the threads before resuming so they won't get into 2455 // more trouble. Sadly, for the threads stopped with the breakpoint 2456 // or exception, the exception doesn't get cleared if it is 2457 // suspended, so we do have to run the risk of letting those threads 2458 // proceed a bit. 2459 2460 { 2461 std::lock_guard<std::recursive_mutex> guard(threads.GetMutex()); 2462 2463 size_t num_threads = threads.GetSize(); 2464 for (size_t i = 0; i < num_threads; i++) { 2465 ThreadSP thread_sp = threads.GetThreadAtIndex(i); 2466 StopInfoSP stop_info_sp = thread_sp->GetPrivateStopInfo(); 2467 StopReason reason = eStopReasonInvalid; 2468 if (stop_info_sp) 2469 reason = stop_info_sp->GetStopReason(); 2470 if (reason != eStopReasonBreakpoint && 2471 reason != eStopReasonException) { 2472 LLDB_LOGF(log, 2473 "ProcessGDBRemote::DoDestroy() - Suspending " 2474 "thread: 0x%4.4" PRIx64 " before running.", 2475 thread_sp->GetProtocolID()); 2476 thread_sp->SetResumeState(eStateSuspended); 2477 } 2478 } 2479 } 2480 Resume(); 2481 return Destroy(false); 2482 } 2483 } 2484 } 2485 } 2486 2487 // Interrupt if our inferior is running... 2488 int exit_status = SIGABRT; 2489 std::string exit_string; 2490 2491 if (m_gdb_comm.IsConnected()) { 2492 if (m_public_state.GetValue() != eStateAttaching) { 2493 StringExtractorGDBRemote response; 2494 GDBRemoteCommunication::ScopedTimeout(m_gdb_comm, 2495 std::chrono::seconds(3)); 2496 2497 if (m_gdb_comm.SendPacketAndWaitForResponse("k", response, 2498 GetInterruptTimeout()) == 2499 GDBRemoteCommunication::PacketResult::Success) { 2500 char packet_cmd = response.GetChar(0); 2501 2502 if (packet_cmd == 'W' || packet_cmd == 'X') { 2503 #if defined(__APPLE__) 2504 // For Native processes on Mac OS X, we launch through the Host 2505 // Platform, then hand the process off to debugserver, which becomes 2506 // the parent process through "PT_ATTACH". Then when we go to kill 2507 // the process on Mac OS X we call ptrace(PT_KILL) to kill it, then 2508 // we call waitpid which returns with no error and the correct 2509 // status. But amusingly enough that doesn't seem to actually reap 2510 // the process, but instead it is left around as a Zombie. Probably 2511 // the kernel is in the process of switching ownership back to lldb 2512 // which was the original parent, and gets confused in the handoff. 2513 // Anyway, so call waitpid here to finally reap it. 2514 PlatformSP platform_sp(GetTarget().GetPlatform()); 2515 if (platform_sp && platform_sp->IsHost()) { 2516 int status; 2517 ::pid_t reap_pid; 2518 reap_pid = waitpid(GetID(), &status, WNOHANG); 2519 LLDB_LOGF(log, "Reaped pid: %d, status: %d.\n", reap_pid, status); 2520 } 2521 #endif 2522 SetLastStopPacket(response); 2523 ClearThreadIDList(); 2524 exit_status = response.GetHexU8(); 2525 } else { 2526 LLDB_LOGF(log, 2527 "ProcessGDBRemote::DoDestroy - got unexpected response " 2528 "to k packet: %s", 2529 response.GetStringRef().data()); 2530 exit_string.assign("got unexpected response to k packet: "); 2531 exit_string.append(std::string(response.GetStringRef())); 2532 } 2533 } else { 2534 LLDB_LOGF(log, "ProcessGDBRemote::DoDestroy - failed to send k packet"); 2535 exit_string.assign("failed to send the k packet"); 2536 } 2537 } else { 2538 LLDB_LOGF(log, 2539 "ProcessGDBRemote::DoDestroy - killed or interrupted while " 2540 "attaching"); 2541 exit_string.assign("killed or interrupted while attaching."); 2542 } 2543 } else { 2544 // If we missed setting the exit status on the way out, do it here. 2545 // NB set exit status can be called multiple times, the first one sets the 2546 // status. 2547 exit_string.assign("destroying when not connected to debugserver"); 2548 } 2549 2550 SetExitStatus(exit_status, exit_string.c_str()); 2551 2552 StopAsyncThread(); 2553 KillDebugserverProcess(); 2554 return error; 2555 } 2556 2557 void ProcessGDBRemote::SetLastStopPacket( 2558 const StringExtractorGDBRemote &response) { 2559 const bool did_exec = 2560 response.GetStringRef().find(";reason:exec;") != std::string::npos; 2561 if (did_exec) { 2562 Log *log = GetLog(GDBRLog::Process); 2563 LLDB_LOGF(log, "ProcessGDBRemote::SetLastStopPacket () - detected exec"); 2564 2565 m_thread_list_real.Clear(); 2566 m_thread_list.Clear(); 2567 BuildDynamicRegisterInfo(true); 2568 m_gdb_comm.ResetDiscoverableSettings(did_exec); 2569 } 2570 2571 m_last_stop_packet = response; 2572 } 2573 2574 void ProcessGDBRemote::SetUnixSignals(const UnixSignalsSP &signals_sp) { 2575 Process::SetUnixSignals(std::make_shared<GDBRemoteSignals>(signals_sp)); 2576 } 2577 2578 // Process Queries 2579 2580 bool ProcessGDBRemote::IsAlive() { 2581 return m_gdb_comm.IsConnected() && Process::IsAlive(); 2582 } 2583 2584 addr_t ProcessGDBRemote::GetImageInfoAddress() { 2585 // request the link map address via the $qShlibInfoAddr packet 2586 lldb::addr_t addr = m_gdb_comm.GetShlibInfoAddr(); 2587 2588 // the loaded module list can also provides a link map address 2589 if (addr == LLDB_INVALID_ADDRESS) { 2590 llvm::Expected<LoadedModuleInfoList> list = GetLoadedModuleList(); 2591 if (!list) { 2592 Log *log = GetLog(GDBRLog::Process); 2593 LLDB_LOG_ERROR(log, list.takeError(), "Failed to read module list: {0}."); 2594 } else { 2595 addr = list->m_link_map; 2596 } 2597 } 2598 2599 return addr; 2600 } 2601 2602 void ProcessGDBRemote::WillPublicStop() { 2603 // See if the GDB remote client supports the JSON threads info. If so, we 2604 // gather stop info for all threads, expedited registers, expedited memory, 2605 // runtime queue information (iOS and MacOSX only), and more. Expediting 2606 // memory will help stack backtracing be much faster. Expediting registers 2607 // will make sure we don't have to read the thread registers for GPRs. 2608 m_jthreadsinfo_sp = m_gdb_comm.GetThreadsInfo(); 2609 2610 if (m_jthreadsinfo_sp) { 2611 // Now set the stop info for each thread and also expedite any registers 2612 // and memory that was in the jThreadsInfo response. 2613 StructuredData::Array *thread_infos = m_jthreadsinfo_sp->GetAsArray(); 2614 if (thread_infos) { 2615 const size_t n = thread_infos->GetSize(); 2616 for (size_t i = 0; i < n; ++i) { 2617 StructuredData::Dictionary *thread_dict = 2618 thread_infos->GetItemAtIndex(i)->GetAsDictionary(); 2619 if (thread_dict) 2620 SetThreadStopInfo(thread_dict); 2621 } 2622 } 2623 } 2624 } 2625 2626 // Process Memory 2627 size_t ProcessGDBRemote::DoReadMemory(addr_t addr, void *buf, size_t size, 2628 Status &error) { 2629 GetMaxMemorySize(); 2630 bool binary_memory_read = m_gdb_comm.GetxPacketSupported(); 2631 // M and m packets take 2 bytes for 1 byte of memory 2632 size_t max_memory_size = 2633 binary_memory_read ? m_max_memory_size : m_max_memory_size / 2; 2634 if (size > max_memory_size) { 2635 // Keep memory read sizes down to a sane limit. This function will be 2636 // called multiple times in order to complete the task by 2637 // lldb_private::Process so it is ok to do this. 2638 size = max_memory_size; 2639 } 2640 2641 char packet[64]; 2642 int packet_len; 2643 packet_len = ::snprintf(packet, sizeof(packet), "%c%" PRIx64 ",%" PRIx64, 2644 binary_memory_read ? 'x' : 'm', (uint64_t)addr, 2645 (uint64_t)size); 2646 assert(packet_len + 1 < (int)sizeof(packet)); 2647 UNUSED_IF_ASSERT_DISABLED(packet_len); 2648 StringExtractorGDBRemote response; 2649 if (m_gdb_comm.SendPacketAndWaitForResponse(packet, response, 2650 GetInterruptTimeout()) == 2651 GDBRemoteCommunication::PacketResult::Success) { 2652 if (response.IsNormalResponse()) { 2653 error.Clear(); 2654 if (binary_memory_read) { 2655 // The lower level GDBRemoteCommunication packet receive layer has 2656 // already de-quoted any 0x7d character escaping that was present in 2657 // the packet 2658 2659 size_t data_received_size = response.GetBytesLeft(); 2660 if (data_received_size > size) { 2661 // Don't write past the end of BUF if the remote debug server gave us 2662 // too much data for some reason. 2663 data_received_size = size; 2664 } 2665 memcpy(buf, response.GetStringRef().data(), data_received_size); 2666 return data_received_size; 2667 } else { 2668 return response.GetHexBytes( 2669 llvm::MutableArrayRef<uint8_t>((uint8_t *)buf, size), '\xdd'); 2670 } 2671 } else if (response.IsErrorResponse()) 2672 error.SetErrorStringWithFormat("memory read failed for 0x%" PRIx64, addr); 2673 else if (response.IsUnsupportedResponse()) 2674 error.SetErrorStringWithFormat( 2675 "GDB server does not support reading memory"); 2676 else 2677 error.SetErrorStringWithFormat( 2678 "unexpected response to GDB server memory read packet '%s': '%s'", 2679 packet, response.GetStringRef().data()); 2680 } else { 2681 error.SetErrorStringWithFormat("failed to send packet: '%s'", packet); 2682 } 2683 return 0; 2684 } 2685 2686 bool ProcessGDBRemote::SupportsMemoryTagging() { 2687 return m_gdb_comm.GetMemoryTaggingSupported(); 2688 } 2689 2690 llvm::Expected<std::vector<uint8_t>> 2691 ProcessGDBRemote::DoReadMemoryTags(lldb::addr_t addr, size_t len, 2692 int32_t type) { 2693 // By this point ReadMemoryTags has validated that tagging is enabled 2694 // for this target/process/address. 2695 DataBufferSP buffer_sp = m_gdb_comm.ReadMemoryTags(addr, len, type); 2696 if (!buffer_sp) { 2697 return llvm::createStringError(llvm::inconvertibleErrorCode(), 2698 "Error reading memory tags from remote"); 2699 } 2700 2701 // Return the raw tag data 2702 llvm::ArrayRef<uint8_t> tag_data = buffer_sp->GetData(); 2703 std::vector<uint8_t> got; 2704 got.reserve(tag_data.size()); 2705 std::copy(tag_data.begin(), tag_data.end(), std::back_inserter(got)); 2706 return got; 2707 } 2708 2709 Status ProcessGDBRemote::DoWriteMemoryTags(lldb::addr_t addr, size_t len, 2710 int32_t type, 2711 const std::vector<uint8_t> &tags) { 2712 // By now WriteMemoryTags should have validated that tagging is enabled 2713 // for this target/process. 2714 return m_gdb_comm.WriteMemoryTags(addr, len, type, tags); 2715 } 2716 2717 Status ProcessGDBRemote::WriteObjectFile( 2718 std::vector<ObjectFile::LoadableData> entries) { 2719 Status error; 2720 // Sort the entries by address because some writes, like those to flash 2721 // memory, must happen in order of increasing address. 2722 std::stable_sort( 2723 std::begin(entries), std::end(entries), 2724 [](const ObjectFile::LoadableData a, const ObjectFile::LoadableData b) { 2725 return a.Dest < b.Dest; 2726 }); 2727 m_allow_flash_writes = true; 2728 error = Process::WriteObjectFile(entries); 2729 if (error.Success()) 2730 error = FlashDone(); 2731 else 2732 // Even though some of the writing failed, try to send a flash done if some 2733 // of the writing succeeded so the flash state is reset to normal, but 2734 // don't stomp on the error status that was set in the write failure since 2735 // that's the one we want to report back. 2736 FlashDone(); 2737 m_allow_flash_writes = false; 2738 return error; 2739 } 2740 2741 bool ProcessGDBRemote::HasErased(FlashRange range) { 2742 auto size = m_erased_flash_ranges.GetSize(); 2743 for (size_t i = 0; i < size; ++i) 2744 if (m_erased_flash_ranges.GetEntryAtIndex(i)->Contains(range)) 2745 return true; 2746 return false; 2747 } 2748 2749 Status ProcessGDBRemote::FlashErase(lldb::addr_t addr, size_t size) { 2750 Status status; 2751 2752 MemoryRegionInfo region; 2753 status = GetMemoryRegionInfo(addr, region); 2754 if (!status.Success()) 2755 return status; 2756 2757 // The gdb spec doesn't say if erasures are allowed across multiple regions, 2758 // but we'll disallow it to be safe and to keep the logic simple by worring 2759 // about only one region's block size. DoMemoryWrite is this function's 2760 // primary user, and it can easily keep writes within a single memory region 2761 if (addr + size > region.GetRange().GetRangeEnd()) { 2762 status.SetErrorString("Unable to erase flash in multiple regions"); 2763 return status; 2764 } 2765 2766 uint64_t blocksize = region.GetBlocksize(); 2767 if (blocksize == 0) { 2768 status.SetErrorString("Unable to erase flash because blocksize is 0"); 2769 return status; 2770 } 2771 2772 // Erasures can only be done on block boundary adresses, so round down addr 2773 // and round up size 2774 lldb::addr_t block_start_addr = addr - (addr % blocksize); 2775 size += (addr - block_start_addr); 2776 if ((size % blocksize) != 0) 2777 size += (blocksize - size % blocksize); 2778 2779 FlashRange range(block_start_addr, size); 2780 2781 if (HasErased(range)) 2782 return status; 2783 2784 // We haven't erased the entire range, but we may have erased part of it. 2785 // (e.g., block A is already erased and range starts in A and ends in B). So, 2786 // adjust range if necessary to exclude already erased blocks. 2787 if (!m_erased_flash_ranges.IsEmpty()) { 2788 // Assuming that writes and erasures are done in increasing addr order, 2789 // because that is a requirement of the vFlashWrite command. Therefore, we 2790 // only need to look at the last range in the list for overlap. 2791 const auto &last_range = *m_erased_flash_ranges.Back(); 2792 if (range.GetRangeBase() < last_range.GetRangeEnd()) { 2793 auto overlap = last_range.GetRangeEnd() - range.GetRangeBase(); 2794 // overlap will be less than range.GetByteSize() or else HasErased() 2795 // would have been true 2796 range.SetByteSize(range.GetByteSize() - overlap); 2797 range.SetRangeBase(range.GetRangeBase() + overlap); 2798 } 2799 } 2800 2801 StreamString packet; 2802 packet.Printf("vFlashErase:%" PRIx64 ",%" PRIx64, range.GetRangeBase(), 2803 (uint64_t)range.GetByteSize()); 2804 2805 StringExtractorGDBRemote response; 2806 if (m_gdb_comm.SendPacketAndWaitForResponse(packet.GetString(), response, 2807 GetInterruptTimeout()) == 2808 GDBRemoteCommunication::PacketResult::Success) { 2809 if (response.IsOKResponse()) { 2810 m_erased_flash_ranges.Insert(range, true); 2811 } else { 2812 if (response.IsErrorResponse()) 2813 status.SetErrorStringWithFormat("flash erase failed for 0x%" PRIx64, 2814 addr); 2815 else if (response.IsUnsupportedResponse()) 2816 status.SetErrorStringWithFormat("GDB server does not support flashing"); 2817 else 2818 status.SetErrorStringWithFormat( 2819 "unexpected response to GDB server flash erase packet '%s': '%s'", 2820 packet.GetData(), response.GetStringRef().data()); 2821 } 2822 } else { 2823 status.SetErrorStringWithFormat("failed to send packet: '%s'", 2824 packet.GetData()); 2825 } 2826 return status; 2827 } 2828 2829 Status ProcessGDBRemote::FlashDone() { 2830 Status status; 2831 // If we haven't erased any blocks, then we must not have written anything 2832 // either, so there is no need to actually send a vFlashDone command 2833 if (m_erased_flash_ranges.IsEmpty()) 2834 return status; 2835 StringExtractorGDBRemote response; 2836 if (m_gdb_comm.SendPacketAndWaitForResponse("vFlashDone", response, 2837 GetInterruptTimeout()) == 2838 GDBRemoteCommunication::PacketResult::Success) { 2839 if (response.IsOKResponse()) { 2840 m_erased_flash_ranges.Clear(); 2841 } else { 2842 if (response.IsErrorResponse()) 2843 status.SetErrorStringWithFormat("flash done failed"); 2844 else if (response.IsUnsupportedResponse()) 2845 status.SetErrorStringWithFormat("GDB server does not support flashing"); 2846 else 2847 status.SetErrorStringWithFormat( 2848 "unexpected response to GDB server flash done packet: '%s'", 2849 response.GetStringRef().data()); 2850 } 2851 } else { 2852 status.SetErrorStringWithFormat("failed to send flash done packet"); 2853 } 2854 return status; 2855 } 2856 2857 size_t ProcessGDBRemote::DoWriteMemory(addr_t addr, const void *buf, 2858 size_t size, Status &error) { 2859 GetMaxMemorySize(); 2860 // M and m packets take 2 bytes for 1 byte of memory 2861 size_t max_memory_size = m_max_memory_size / 2; 2862 if (size > max_memory_size) { 2863 // Keep memory read sizes down to a sane limit. This function will be 2864 // called multiple times in order to complete the task by 2865 // lldb_private::Process so it is ok to do this. 2866 size = max_memory_size; 2867 } 2868 2869 StreamGDBRemote packet; 2870 2871 MemoryRegionInfo region; 2872 Status region_status = GetMemoryRegionInfo(addr, region); 2873 2874 bool is_flash = 2875 region_status.Success() && region.GetFlash() == MemoryRegionInfo::eYes; 2876 2877 if (is_flash) { 2878 if (!m_allow_flash_writes) { 2879 error.SetErrorString("Writing to flash memory is not allowed"); 2880 return 0; 2881 } 2882 // Keep the write within a flash memory region 2883 if (addr + size > region.GetRange().GetRangeEnd()) 2884 size = region.GetRange().GetRangeEnd() - addr; 2885 // Flash memory must be erased before it can be written 2886 error = FlashErase(addr, size); 2887 if (!error.Success()) 2888 return 0; 2889 packet.Printf("vFlashWrite:%" PRIx64 ":", addr); 2890 packet.PutEscapedBytes(buf, size); 2891 } else { 2892 packet.Printf("M%" PRIx64 ",%" PRIx64 ":", addr, (uint64_t)size); 2893 packet.PutBytesAsRawHex8(buf, size, endian::InlHostByteOrder(), 2894 endian::InlHostByteOrder()); 2895 } 2896 StringExtractorGDBRemote response; 2897 if (m_gdb_comm.SendPacketAndWaitForResponse(packet.GetString(), response, 2898 GetInterruptTimeout()) == 2899 GDBRemoteCommunication::PacketResult::Success) { 2900 if (response.IsOKResponse()) { 2901 error.Clear(); 2902 return size; 2903 } else if (response.IsErrorResponse()) 2904 error.SetErrorStringWithFormat("memory write failed for 0x%" PRIx64, 2905 addr); 2906 else if (response.IsUnsupportedResponse()) 2907 error.SetErrorStringWithFormat( 2908 "GDB server does not support writing memory"); 2909 else 2910 error.SetErrorStringWithFormat( 2911 "unexpected response to GDB server memory write packet '%s': '%s'", 2912 packet.GetData(), response.GetStringRef().data()); 2913 } else { 2914 error.SetErrorStringWithFormat("failed to send packet: '%s'", 2915 packet.GetData()); 2916 } 2917 return 0; 2918 } 2919 2920 lldb::addr_t ProcessGDBRemote::DoAllocateMemory(size_t size, 2921 uint32_t permissions, 2922 Status &error) { 2923 Log *log = GetLog(LLDBLog::Process | LLDBLog::Expressions); 2924 addr_t allocated_addr = LLDB_INVALID_ADDRESS; 2925 2926 if (m_gdb_comm.SupportsAllocDeallocMemory() != eLazyBoolNo) { 2927 allocated_addr = m_gdb_comm.AllocateMemory(size, permissions); 2928 if (allocated_addr != LLDB_INVALID_ADDRESS || 2929 m_gdb_comm.SupportsAllocDeallocMemory() == eLazyBoolYes) 2930 return allocated_addr; 2931 } 2932 2933 if (m_gdb_comm.SupportsAllocDeallocMemory() == eLazyBoolNo) { 2934 // Call mmap() to create memory in the inferior.. 2935 unsigned prot = 0; 2936 if (permissions & lldb::ePermissionsReadable) 2937 prot |= eMmapProtRead; 2938 if (permissions & lldb::ePermissionsWritable) 2939 prot |= eMmapProtWrite; 2940 if (permissions & lldb::ePermissionsExecutable) 2941 prot |= eMmapProtExec; 2942 2943 if (InferiorCallMmap(this, allocated_addr, 0, size, prot, 2944 eMmapFlagsAnon | eMmapFlagsPrivate, -1, 0)) 2945 m_addr_to_mmap_size[allocated_addr] = size; 2946 else { 2947 allocated_addr = LLDB_INVALID_ADDRESS; 2948 LLDB_LOGF(log, 2949 "ProcessGDBRemote::%s no direct stub support for memory " 2950 "allocation, and InferiorCallMmap also failed - is stub " 2951 "missing register context save/restore capability?", 2952 __FUNCTION__); 2953 } 2954 } 2955 2956 if (allocated_addr == LLDB_INVALID_ADDRESS) 2957 error.SetErrorStringWithFormat( 2958 "unable to allocate %" PRIu64 " bytes of memory with permissions %s", 2959 (uint64_t)size, GetPermissionsAsCString(permissions)); 2960 else 2961 error.Clear(); 2962 return allocated_addr; 2963 } 2964 2965 Status ProcessGDBRemote::DoGetMemoryRegionInfo(addr_t load_addr, 2966 MemoryRegionInfo ®ion_info) { 2967 2968 Status error(m_gdb_comm.GetMemoryRegionInfo(load_addr, region_info)); 2969 return error; 2970 } 2971 2972 Status ProcessGDBRemote::GetWatchpointSupportInfo(uint32_t &num) { 2973 2974 Status error(m_gdb_comm.GetWatchpointSupportInfo(num)); 2975 return error; 2976 } 2977 2978 Status ProcessGDBRemote::GetWatchpointSupportInfo(uint32_t &num, bool &after) { 2979 Status error(m_gdb_comm.GetWatchpointSupportInfo( 2980 num, after, GetTarget().GetArchitecture())); 2981 return error; 2982 } 2983 2984 Status ProcessGDBRemote::DoDeallocateMemory(lldb::addr_t addr) { 2985 Status error; 2986 LazyBool supported = m_gdb_comm.SupportsAllocDeallocMemory(); 2987 2988 switch (supported) { 2989 case eLazyBoolCalculate: 2990 // We should never be deallocating memory without allocating memory first 2991 // so we should never get eLazyBoolCalculate 2992 error.SetErrorString( 2993 "tried to deallocate memory without ever allocating memory"); 2994 break; 2995 2996 case eLazyBoolYes: 2997 if (!m_gdb_comm.DeallocateMemory(addr)) 2998 error.SetErrorStringWithFormat( 2999 "unable to deallocate memory at 0x%" PRIx64, addr); 3000 break; 3001 3002 case eLazyBoolNo: 3003 // Call munmap() to deallocate memory in the inferior.. 3004 { 3005 MMapMap::iterator pos = m_addr_to_mmap_size.find(addr); 3006 if (pos != m_addr_to_mmap_size.end() && 3007 InferiorCallMunmap(this, addr, pos->second)) 3008 m_addr_to_mmap_size.erase(pos); 3009 else 3010 error.SetErrorStringWithFormat( 3011 "unable to deallocate memory at 0x%" PRIx64, addr); 3012 } 3013 break; 3014 } 3015 3016 return error; 3017 } 3018 3019 // Process STDIO 3020 size_t ProcessGDBRemote::PutSTDIN(const char *src, size_t src_len, 3021 Status &error) { 3022 if (m_stdio_communication.IsConnected()) { 3023 ConnectionStatus status; 3024 m_stdio_communication.Write(src, src_len, status, nullptr); 3025 } else if (m_stdin_forward) { 3026 m_gdb_comm.SendStdinNotification(src, src_len); 3027 } 3028 return 0; 3029 } 3030 3031 Status ProcessGDBRemote::EnableBreakpointSite(BreakpointSite *bp_site) { 3032 Status error; 3033 assert(bp_site != nullptr); 3034 3035 // Get logging info 3036 Log *log = GetLog(GDBRLog::Breakpoints); 3037 user_id_t site_id = bp_site->GetID(); 3038 3039 // Get the breakpoint address 3040 const addr_t addr = bp_site->GetLoadAddress(); 3041 3042 // Log that a breakpoint was requested 3043 LLDB_LOGF(log, 3044 "ProcessGDBRemote::EnableBreakpointSite (size_id = %" PRIu64 3045 ") address = 0x%" PRIx64, 3046 site_id, (uint64_t)addr); 3047 3048 // Breakpoint already exists and is enabled 3049 if (bp_site->IsEnabled()) { 3050 LLDB_LOGF(log, 3051 "ProcessGDBRemote::EnableBreakpointSite (size_id = %" PRIu64 3052 ") address = 0x%" PRIx64 " -- SUCCESS (already enabled)", 3053 site_id, (uint64_t)addr); 3054 return error; 3055 } 3056 3057 // Get the software breakpoint trap opcode size 3058 const size_t bp_op_size = GetSoftwareBreakpointTrapOpcode(bp_site); 3059 3060 // SupportsGDBStoppointPacket() simply checks a boolean, indicating if this 3061 // breakpoint type is supported by the remote stub. These are set to true by 3062 // default, and later set to false only after we receive an unimplemented 3063 // response when sending a breakpoint packet. This means initially that 3064 // unless we were specifically instructed to use a hardware breakpoint, LLDB 3065 // will attempt to set a software breakpoint. HardwareRequired() also queries 3066 // a boolean variable which indicates if the user specifically asked for 3067 // hardware breakpoints. If true then we will skip over software 3068 // breakpoints. 3069 if (m_gdb_comm.SupportsGDBStoppointPacket(eBreakpointSoftware) && 3070 (!bp_site->HardwareRequired())) { 3071 // Try to send off a software breakpoint packet ($Z0) 3072 uint8_t error_no = m_gdb_comm.SendGDBStoppointTypePacket( 3073 eBreakpointSoftware, true, addr, bp_op_size, GetInterruptTimeout()); 3074 if (error_no == 0) { 3075 // The breakpoint was placed successfully 3076 bp_site->SetEnabled(true); 3077 bp_site->SetType(BreakpointSite::eExternal); 3078 return error; 3079 } 3080 3081 // SendGDBStoppointTypePacket() will return an error if it was unable to 3082 // set this breakpoint. We need to differentiate between a error specific 3083 // to placing this breakpoint or if we have learned that this breakpoint 3084 // type is unsupported. To do this, we must test the support boolean for 3085 // this breakpoint type to see if it now indicates that this breakpoint 3086 // type is unsupported. If they are still supported then we should return 3087 // with the error code. If they are now unsupported, then we would like to 3088 // fall through and try another form of breakpoint. 3089 if (m_gdb_comm.SupportsGDBStoppointPacket(eBreakpointSoftware)) { 3090 if (error_no != UINT8_MAX) 3091 error.SetErrorStringWithFormat( 3092 "error: %d sending the breakpoint request", error_no); 3093 else 3094 error.SetErrorString("error sending the breakpoint request"); 3095 return error; 3096 } 3097 3098 // We reach here when software breakpoints have been found to be 3099 // unsupported. For future calls to set a breakpoint, we will not attempt 3100 // to set a breakpoint with a type that is known not to be supported. 3101 LLDB_LOGF(log, "Software breakpoints are unsupported"); 3102 3103 // So we will fall through and try a hardware breakpoint 3104 } 3105 3106 // The process of setting a hardware breakpoint is much the same as above. 3107 // We check the supported boolean for this breakpoint type, and if it is 3108 // thought to be supported then we will try to set this breakpoint with a 3109 // hardware breakpoint. 3110 if (m_gdb_comm.SupportsGDBStoppointPacket(eBreakpointHardware)) { 3111 // Try to send off a hardware breakpoint packet ($Z1) 3112 uint8_t error_no = m_gdb_comm.SendGDBStoppointTypePacket( 3113 eBreakpointHardware, true, addr, bp_op_size, GetInterruptTimeout()); 3114 if (error_no == 0) { 3115 // The breakpoint was placed successfully 3116 bp_site->SetEnabled(true); 3117 bp_site->SetType(BreakpointSite::eHardware); 3118 return error; 3119 } 3120 3121 // Check if the error was something other then an unsupported breakpoint 3122 // type 3123 if (m_gdb_comm.SupportsGDBStoppointPacket(eBreakpointHardware)) { 3124 // Unable to set this hardware breakpoint 3125 if (error_no != UINT8_MAX) 3126 error.SetErrorStringWithFormat( 3127 "error: %d sending the hardware breakpoint request " 3128 "(hardware breakpoint resources might be exhausted or unavailable)", 3129 error_no); 3130 else 3131 error.SetErrorString("error sending the hardware breakpoint request " 3132 "(hardware breakpoint resources " 3133 "might be exhausted or unavailable)"); 3134 return error; 3135 } 3136 3137 // We will reach here when the stub gives an unsupported response to a 3138 // hardware breakpoint 3139 LLDB_LOGF(log, "Hardware breakpoints are unsupported"); 3140 3141 // Finally we will falling through to a #trap style breakpoint 3142 } 3143 3144 // Don't fall through when hardware breakpoints were specifically requested 3145 if (bp_site->HardwareRequired()) { 3146 error.SetErrorString("hardware breakpoints are not supported"); 3147 return error; 3148 } 3149 3150 // As a last resort we want to place a manual breakpoint. An instruction is 3151 // placed into the process memory using memory write packets. 3152 return EnableSoftwareBreakpoint(bp_site); 3153 } 3154 3155 Status ProcessGDBRemote::DisableBreakpointSite(BreakpointSite *bp_site) { 3156 Status error; 3157 assert(bp_site != nullptr); 3158 addr_t addr = bp_site->GetLoadAddress(); 3159 user_id_t site_id = bp_site->GetID(); 3160 Log *log = GetLog(GDBRLog::Breakpoints); 3161 LLDB_LOGF(log, 3162 "ProcessGDBRemote::DisableBreakpointSite (site_id = %" PRIu64 3163 ") addr = 0x%8.8" PRIx64, 3164 site_id, (uint64_t)addr); 3165 3166 if (bp_site->IsEnabled()) { 3167 const size_t bp_op_size = GetSoftwareBreakpointTrapOpcode(bp_site); 3168 3169 BreakpointSite::Type bp_type = bp_site->GetType(); 3170 switch (bp_type) { 3171 case BreakpointSite::eSoftware: 3172 error = DisableSoftwareBreakpoint(bp_site); 3173 break; 3174 3175 case BreakpointSite::eHardware: 3176 if (m_gdb_comm.SendGDBStoppointTypePacket(eBreakpointHardware, false, 3177 addr, bp_op_size, 3178 GetInterruptTimeout())) 3179 error.SetErrorToGenericError(); 3180 break; 3181 3182 case BreakpointSite::eExternal: { 3183 if (m_gdb_comm.SendGDBStoppointTypePacket(eBreakpointSoftware, false, 3184 addr, bp_op_size, 3185 GetInterruptTimeout())) 3186 error.SetErrorToGenericError(); 3187 } break; 3188 } 3189 if (error.Success()) 3190 bp_site->SetEnabled(false); 3191 } else { 3192 LLDB_LOGF(log, 3193 "ProcessGDBRemote::DisableBreakpointSite (site_id = %" PRIu64 3194 ") addr = 0x%8.8" PRIx64 " -- SUCCESS (already disabled)", 3195 site_id, (uint64_t)addr); 3196 return error; 3197 } 3198 3199 if (error.Success()) 3200 error.SetErrorToGenericError(); 3201 return error; 3202 } 3203 3204 // Pre-requisite: wp != NULL. 3205 static GDBStoppointType GetGDBStoppointType(Watchpoint *wp) { 3206 assert(wp); 3207 bool watch_read = wp->WatchpointRead(); 3208 bool watch_write = wp->WatchpointWrite(); 3209 3210 // watch_read and watch_write cannot both be false. 3211 assert(watch_read || watch_write); 3212 if (watch_read && watch_write) 3213 return eWatchpointReadWrite; 3214 else if (watch_read) 3215 return eWatchpointRead; 3216 else // Must be watch_write, then. 3217 return eWatchpointWrite; 3218 } 3219 3220 Status ProcessGDBRemote::EnableWatchpoint(Watchpoint *wp, bool notify) { 3221 Status error; 3222 if (wp) { 3223 user_id_t watchID = wp->GetID(); 3224 addr_t addr = wp->GetLoadAddress(); 3225 Log *log(GetLog(GDBRLog::Watchpoints)); 3226 LLDB_LOGF(log, "ProcessGDBRemote::EnableWatchpoint(watchID = %" PRIu64 ")", 3227 watchID); 3228 if (wp->IsEnabled()) { 3229 LLDB_LOGF(log, 3230 "ProcessGDBRemote::EnableWatchpoint(watchID = %" PRIu64 3231 ") addr = 0x%8.8" PRIx64 ": watchpoint already enabled.", 3232 watchID, (uint64_t)addr); 3233 return error; 3234 } 3235 3236 GDBStoppointType type = GetGDBStoppointType(wp); 3237 // Pass down an appropriate z/Z packet... 3238 if (m_gdb_comm.SupportsGDBStoppointPacket(type)) { 3239 if (m_gdb_comm.SendGDBStoppointTypePacket(type, true, addr, 3240 wp->GetByteSize(), 3241 GetInterruptTimeout()) == 0) { 3242 wp->SetEnabled(true, notify); 3243 return error; 3244 } else 3245 error.SetErrorString("sending gdb watchpoint packet failed"); 3246 } else 3247 error.SetErrorString("watchpoints not supported"); 3248 } else { 3249 error.SetErrorString("Watchpoint argument was NULL."); 3250 } 3251 if (error.Success()) 3252 error.SetErrorToGenericError(); 3253 return error; 3254 } 3255 3256 Status ProcessGDBRemote::DisableWatchpoint(Watchpoint *wp, bool notify) { 3257 Status error; 3258 if (wp) { 3259 user_id_t watchID = wp->GetID(); 3260 3261 Log *log(GetLog(GDBRLog::Watchpoints)); 3262 3263 addr_t addr = wp->GetLoadAddress(); 3264 3265 LLDB_LOGF(log, 3266 "ProcessGDBRemote::DisableWatchpoint (watchID = %" PRIu64 3267 ") addr = 0x%8.8" PRIx64, 3268 watchID, (uint64_t)addr); 3269 3270 if (!wp->IsEnabled()) { 3271 LLDB_LOGF(log, 3272 "ProcessGDBRemote::DisableWatchpoint (watchID = %" PRIu64 3273 ") addr = 0x%8.8" PRIx64 " -- SUCCESS (already disabled)", 3274 watchID, (uint64_t)addr); 3275 // See also 'class WatchpointSentry' within StopInfo.cpp. This disabling 3276 // attempt might come from the user-supplied actions, we'll route it in 3277 // order for the watchpoint object to intelligently process this action. 3278 wp->SetEnabled(false, notify); 3279 return error; 3280 } 3281 3282 if (wp->IsHardware()) { 3283 GDBStoppointType type = GetGDBStoppointType(wp); 3284 // Pass down an appropriate z/Z packet... 3285 if (m_gdb_comm.SendGDBStoppointTypePacket(type, false, addr, 3286 wp->GetByteSize(), 3287 GetInterruptTimeout()) == 0) { 3288 wp->SetEnabled(false, notify); 3289 return error; 3290 } else 3291 error.SetErrorString("sending gdb watchpoint packet failed"); 3292 } 3293 // TODO: clear software watchpoints if we implement them 3294 } else { 3295 error.SetErrorString("Watchpoint argument was NULL."); 3296 } 3297 if (error.Success()) 3298 error.SetErrorToGenericError(); 3299 return error; 3300 } 3301 3302 void ProcessGDBRemote::Clear() { 3303 m_thread_list_real.Clear(); 3304 m_thread_list.Clear(); 3305 } 3306 3307 Status ProcessGDBRemote::DoSignal(int signo) { 3308 Status error; 3309 Log *log = GetLog(GDBRLog::Process); 3310 LLDB_LOGF(log, "ProcessGDBRemote::DoSignal (signal = %d)", signo); 3311 3312 if (!m_gdb_comm.SendAsyncSignal(signo, GetInterruptTimeout())) 3313 error.SetErrorStringWithFormat("failed to send signal %i", signo); 3314 return error; 3315 } 3316 3317 Status 3318 ProcessGDBRemote::EstablishConnectionIfNeeded(const ProcessInfo &process_info) { 3319 // Make sure we aren't already connected? 3320 if (m_gdb_comm.IsConnected()) 3321 return Status(); 3322 3323 PlatformSP platform_sp(GetTarget().GetPlatform()); 3324 if (platform_sp && !platform_sp->IsHost()) 3325 return Status("Lost debug server connection"); 3326 3327 auto error = LaunchAndConnectToDebugserver(process_info); 3328 if (error.Fail()) { 3329 const char *error_string = error.AsCString(); 3330 if (error_string == nullptr) 3331 error_string = "unable to launch " DEBUGSERVER_BASENAME; 3332 } 3333 return error; 3334 } 3335 #if !defined(_WIN32) 3336 #define USE_SOCKETPAIR_FOR_LOCAL_CONNECTION 1 3337 #endif 3338 3339 #ifdef USE_SOCKETPAIR_FOR_LOCAL_CONNECTION 3340 static bool SetCloexecFlag(int fd) { 3341 #if defined(FD_CLOEXEC) 3342 int flags = ::fcntl(fd, F_GETFD); 3343 if (flags == -1) 3344 return false; 3345 return (::fcntl(fd, F_SETFD, flags | FD_CLOEXEC) == 0); 3346 #else 3347 return false; 3348 #endif 3349 } 3350 #endif 3351 3352 Status ProcessGDBRemote::LaunchAndConnectToDebugserver( 3353 const ProcessInfo &process_info) { 3354 using namespace std::placeholders; // For _1, _2, etc. 3355 3356 Status error; 3357 if (m_debugserver_pid == LLDB_INVALID_PROCESS_ID) { 3358 // If we locate debugserver, keep that located version around 3359 static FileSpec g_debugserver_file_spec; 3360 3361 ProcessLaunchInfo debugserver_launch_info; 3362 // Make debugserver run in its own session so signals generated by special 3363 // terminal key sequences (^C) don't affect debugserver. 3364 debugserver_launch_info.SetLaunchInSeparateProcessGroup(true); 3365 3366 const std::weak_ptr<ProcessGDBRemote> this_wp = 3367 std::static_pointer_cast<ProcessGDBRemote>(shared_from_this()); 3368 debugserver_launch_info.SetMonitorProcessCallback( 3369 std::bind(MonitorDebugserverProcess, this_wp, _1, _2, _3, _4), false); 3370 debugserver_launch_info.SetUserID(process_info.GetUserID()); 3371 3372 #if defined(__APPLE__) 3373 // On macOS 11, we need to support x86_64 applications translated to 3374 // arm64. We check whether a binary is translated and spawn the correct 3375 // debugserver accordingly. 3376 int mib[] = { CTL_KERN, KERN_PROC, KERN_PROC_PID, 3377 static_cast<int>(process_info.GetProcessID()) }; 3378 struct kinfo_proc processInfo; 3379 size_t bufsize = sizeof(processInfo); 3380 if (sysctl(mib, (unsigned)(sizeof(mib)/sizeof(int)), &processInfo, 3381 &bufsize, NULL, 0) == 0 && bufsize > 0) { 3382 if (processInfo.kp_proc.p_flag & P_TRANSLATED) { 3383 FileSpec rosetta_debugserver("/Library/Apple/usr/libexec/oah/debugserver"); 3384 debugserver_launch_info.SetExecutableFile(rosetta_debugserver, false); 3385 } 3386 } 3387 #endif 3388 3389 int communication_fd = -1; 3390 #ifdef USE_SOCKETPAIR_FOR_LOCAL_CONNECTION 3391 // Use a socketpair on non-Windows systems for security and performance 3392 // reasons. 3393 int sockets[2]; /* the pair of socket descriptors */ 3394 if (socketpair(AF_UNIX, SOCK_STREAM, 0, sockets) == -1) { 3395 error.SetErrorToErrno(); 3396 return error; 3397 } 3398 3399 int our_socket = sockets[0]; 3400 int gdb_socket = sockets[1]; 3401 auto cleanup_our = llvm::make_scope_exit([&]() { close(our_socket); }); 3402 auto cleanup_gdb = llvm::make_scope_exit([&]() { close(gdb_socket); }); 3403 3404 // Don't let any child processes inherit our communication socket 3405 SetCloexecFlag(our_socket); 3406 communication_fd = gdb_socket; 3407 #endif 3408 3409 error = m_gdb_comm.StartDebugserverProcess( 3410 nullptr, GetTarget().GetPlatform().get(), debugserver_launch_info, 3411 nullptr, nullptr, communication_fd); 3412 3413 if (error.Success()) 3414 m_debugserver_pid = debugserver_launch_info.GetProcessID(); 3415 else 3416 m_debugserver_pid = LLDB_INVALID_PROCESS_ID; 3417 3418 if (m_debugserver_pid != LLDB_INVALID_PROCESS_ID) { 3419 #ifdef USE_SOCKETPAIR_FOR_LOCAL_CONNECTION 3420 // Our process spawned correctly, we can now set our connection to use 3421 // our end of the socket pair 3422 cleanup_our.release(); 3423 m_gdb_comm.SetConnection( 3424 std::make_unique<ConnectionFileDescriptor>(our_socket, true)); 3425 #endif 3426 StartAsyncThread(); 3427 } 3428 3429 if (error.Fail()) { 3430 Log *log = GetLog(GDBRLog::Process); 3431 3432 LLDB_LOGF(log, "failed to start debugserver process: %s", 3433 error.AsCString()); 3434 return error; 3435 } 3436 3437 if (m_gdb_comm.IsConnected()) { 3438 // Finish the connection process by doing the handshake without 3439 // connecting (send NULL URL) 3440 error = ConnectToDebugserver(""); 3441 } else { 3442 error.SetErrorString("connection failed"); 3443 } 3444 } 3445 return error; 3446 } 3447 3448 bool ProcessGDBRemote::MonitorDebugserverProcess( 3449 std::weak_ptr<ProcessGDBRemote> process_wp, lldb::pid_t debugserver_pid, 3450 bool exited, // True if the process did exit 3451 int signo, // Zero for no signal 3452 int exit_status // Exit value of process if signal is zero 3453 ) { 3454 // "debugserver_pid" argument passed in is the process ID for debugserver 3455 // that we are tracking... 3456 Log *log = GetLog(GDBRLog::Process); 3457 const bool handled = true; 3458 3459 LLDB_LOGF(log, 3460 "ProcessGDBRemote::%s(process_wp, pid=%" PRIu64 3461 ", signo=%i (0x%x), exit_status=%i)", 3462 __FUNCTION__, debugserver_pid, signo, signo, exit_status); 3463 3464 std::shared_ptr<ProcessGDBRemote> process_sp = process_wp.lock(); 3465 LLDB_LOGF(log, "ProcessGDBRemote::%s(process = %p)", __FUNCTION__, 3466 static_cast<void *>(process_sp.get())); 3467 if (!process_sp || process_sp->m_debugserver_pid != debugserver_pid) 3468 return handled; 3469 3470 // Sleep for a half a second to make sure our inferior process has time to 3471 // set its exit status before we set it incorrectly when both the debugserver 3472 // and the inferior process shut down. 3473 std::this_thread::sleep_for(std::chrono::milliseconds(500)); 3474 3475 // If our process hasn't yet exited, debugserver might have died. If the 3476 // process did exit, then we are reaping it. 3477 const StateType state = process_sp->GetState(); 3478 3479 if (state != eStateInvalid && state != eStateUnloaded && 3480 state != eStateExited && state != eStateDetached) { 3481 char error_str[1024]; 3482 if (signo) { 3483 const char *signal_cstr = 3484 process_sp->GetUnixSignals()->GetSignalAsCString(signo); 3485 if (signal_cstr) 3486 ::snprintf(error_str, sizeof(error_str), 3487 DEBUGSERVER_BASENAME " died with signal %s", signal_cstr); 3488 else 3489 ::snprintf(error_str, sizeof(error_str), 3490 DEBUGSERVER_BASENAME " died with signal %i", signo); 3491 } else { 3492 ::snprintf(error_str, sizeof(error_str), 3493 DEBUGSERVER_BASENAME " died with an exit status of 0x%8.8x", 3494 exit_status); 3495 } 3496 3497 process_sp->SetExitStatus(-1, error_str); 3498 } 3499 // Debugserver has exited we need to let our ProcessGDBRemote know that it no 3500 // longer has a debugserver instance 3501 process_sp->m_debugserver_pid = LLDB_INVALID_PROCESS_ID; 3502 return handled; 3503 } 3504 3505 void ProcessGDBRemote::KillDebugserverProcess() { 3506 m_gdb_comm.Disconnect(); 3507 if (m_debugserver_pid != LLDB_INVALID_PROCESS_ID) { 3508 Host::Kill(m_debugserver_pid, SIGINT); 3509 m_debugserver_pid = LLDB_INVALID_PROCESS_ID; 3510 } 3511 } 3512 3513 void ProcessGDBRemote::Initialize() { 3514 static llvm::once_flag g_once_flag; 3515 3516 llvm::call_once(g_once_flag, []() { 3517 PluginManager::RegisterPlugin(GetPluginNameStatic(), 3518 GetPluginDescriptionStatic(), CreateInstance, 3519 DebuggerInitialize); 3520 }); 3521 } 3522 3523 void ProcessGDBRemote::DebuggerInitialize(Debugger &debugger) { 3524 if (!PluginManager::GetSettingForProcessPlugin( 3525 debugger, PluginProperties::GetSettingName())) { 3526 const bool is_global_setting = true; 3527 PluginManager::CreateSettingForProcessPlugin( 3528 debugger, GetGlobalPluginProperties().GetValueProperties(), 3529 ConstString("Properties for the gdb-remote process plug-in."), 3530 is_global_setting); 3531 } 3532 } 3533 3534 bool ProcessGDBRemote::StartAsyncThread() { 3535 Log *log = GetLog(GDBRLog::Process); 3536 3537 LLDB_LOGF(log, "ProcessGDBRemote::%s ()", __FUNCTION__); 3538 3539 std::lock_guard<std::recursive_mutex> guard(m_async_thread_state_mutex); 3540 if (!m_async_thread.IsJoinable()) { 3541 // Create a thread that watches our internal state and controls which 3542 // events make it to clients (into the DCProcess event queue). 3543 3544 llvm::Expected<HostThread> async_thread = ThreadLauncher::LaunchThread( 3545 "<lldb.process.gdb-remote.async>", ProcessGDBRemote::AsyncThread, this); 3546 if (!async_thread) { 3547 LLDB_LOG_ERROR(GetLog(LLDBLog::Host), async_thread.takeError(), 3548 "failed to launch host thread: {}"); 3549 return false; 3550 } 3551 m_async_thread = *async_thread; 3552 } else 3553 LLDB_LOGF(log, 3554 "ProcessGDBRemote::%s () - Called when Async thread was " 3555 "already running.", 3556 __FUNCTION__); 3557 3558 return m_async_thread.IsJoinable(); 3559 } 3560 3561 void ProcessGDBRemote::StopAsyncThread() { 3562 Log *log = GetLog(GDBRLog::Process); 3563 3564 LLDB_LOGF(log, "ProcessGDBRemote::%s ()", __FUNCTION__); 3565 3566 std::lock_guard<std::recursive_mutex> guard(m_async_thread_state_mutex); 3567 if (m_async_thread.IsJoinable()) { 3568 m_async_broadcaster.BroadcastEvent(eBroadcastBitAsyncThreadShouldExit); 3569 3570 // This will shut down the async thread. 3571 m_gdb_comm.Disconnect(); // Disconnect from the debug server. 3572 3573 // Stop the stdio thread 3574 m_async_thread.Join(nullptr); 3575 m_async_thread.Reset(); 3576 } else 3577 LLDB_LOGF( 3578 log, 3579 "ProcessGDBRemote::%s () - Called when Async thread was not running.", 3580 __FUNCTION__); 3581 } 3582 3583 thread_result_t ProcessGDBRemote::AsyncThread(void *arg) { 3584 ProcessGDBRemote *process = (ProcessGDBRemote *)arg; 3585 3586 Log *log = GetLog(GDBRLog::Process); 3587 LLDB_LOGF(log, 3588 "ProcessGDBRemote::%s (arg = %p, pid = %" PRIu64 3589 ") thread starting...", 3590 __FUNCTION__, arg, process->GetID()); 3591 3592 EventSP event_sp; 3593 3594 // We need to ignore any packets that come in after we have 3595 // have decided the process has exited. There are some 3596 // situations, for instance when we try to interrupt a running 3597 // process and the interrupt fails, where another packet might 3598 // get delivered after we've decided to give up on the process. 3599 // But once we've decided we are done with the process we will 3600 // not be in a state to do anything useful with new packets. 3601 // So it is safer to simply ignore any remaining packets by 3602 // explicitly checking for eStateExited before reentering the 3603 // fetch loop. 3604 3605 bool done = false; 3606 while (!done && process->GetPrivateState() != eStateExited) { 3607 LLDB_LOGF(log, 3608 "ProcessGDBRemote::%s (arg = %p, pid = %" PRIu64 3609 ") listener.WaitForEvent (NULL, event_sp)...", 3610 __FUNCTION__, arg, process->GetID()); 3611 3612 if (process->m_async_listener_sp->GetEvent(event_sp, llvm::None)) { 3613 const uint32_t event_type = event_sp->GetType(); 3614 if (event_sp->BroadcasterIs(&process->m_async_broadcaster)) { 3615 LLDB_LOGF(log, 3616 "ProcessGDBRemote::%s (arg = %p, pid = %" PRIu64 3617 ") Got an event of type: %d...", 3618 __FUNCTION__, arg, process->GetID(), event_type); 3619 3620 switch (event_type) { 3621 case eBroadcastBitAsyncContinue: { 3622 const EventDataBytes *continue_packet = 3623 EventDataBytes::GetEventDataFromEvent(event_sp.get()); 3624 3625 if (continue_packet) { 3626 const char *continue_cstr = 3627 (const char *)continue_packet->GetBytes(); 3628 const size_t continue_cstr_len = continue_packet->GetByteSize(); 3629 LLDB_LOGF(log, 3630 "ProcessGDBRemote::%s (arg = %p, pid = %" PRIu64 3631 ") got eBroadcastBitAsyncContinue: %s", 3632 __FUNCTION__, arg, process->GetID(), continue_cstr); 3633 3634 if (::strstr(continue_cstr, "vAttach") == nullptr) 3635 process->SetPrivateState(eStateRunning); 3636 StringExtractorGDBRemote response; 3637 3638 StateType stop_state = 3639 process->GetGDBRemote().SendContinuePacketAndWaitForResponse( 3640 *process, *process->GetUnixSignals(), 3641 llvm::StringRef(continue_cstr, continue_cstr_len), 3642 process->GetInterruptTimeout(), response); 3643 3644 // We need to immediately clear the thread ID list so we are sure 3645 // to get a valid list of threads. The thread ID list might be 3646 // contained within the "response", or the stop reply packet that 3647 // caused the stop. So clear it now before we give the stop reply 3648 // packet to the process using the 3649 // process->SetLastStopPacket()... 3650 process->ClearThreadIDList(); 3651 3652 switch (stop_state) { 3653 case eStateStopped: 3654 case eStateCrashed: 3655 case eStateSuspended: 3656 process->SetLastStopPacket(response); 3657 process->SetPrivateState(stop_state); 3658 break; 3659 3660 case eStateExited: { 3661 process->SetLastStopPacket(response); 3662 process->ClearThreadIDList(); 3663 response.SetFilePos(1); 3664 3665 int exit_status = response.GetHexU8(); 3666 std::string desc_string; 3667 if (response.GetBytesLeft() > 0 && response.GetChar('-') == ';') { 3668 llvm::StringRef desc_str; 3669 llvm::StringRef desc_token; 3670 while (response.GetNameColonValue(desc_token, desc_str)) { 3671 if (desc_token != "description") 3672 continue; 3673 StringExtractor extractor(desc_str); 3674 extractor.GetHexByteString(desc_string); 3675 } 3676 } 3677 process->SetExitStatus(exit_status, desc_string.c_str()); 3678 done = true; 3679 break; 3680 } 3681 case eStateInvalid: { 3682 // Check to see if we were trying to attach and if we got back 3683 // the "E87" error code from debugserver -- this indicates that 3684 // the process is not debuggable. Return a slightly more 3685 // helpful error message about why the attach failed. 3686 if (::strstr(continue_cstr, "vAttach") != nullptr && 3687 response.GetError() == 0x87) { 3688 process->SetExitStatus(-1, "cannot attach to process due to " 3689 "System Integrity Protection"); 3690 } else if (::strstr(continue_cstr, "vAttach") != nullptr && 3691 response.GetStatus().Fail()) { 3692 process->SetExitStatus(-1, response.GetStatus().AsCString()); 3693 } else { 3694 process->SetExitStatus(-1, "lost connection"); 3695 } 3696 done = true; 3697 break; 3698 } 3699 3700 default: 3701 process->SetPrivateState(stop_state); 3702 break; 3703 } // switch(stop_state) 3704 } // if (continue_packet) 3705 } // case eBroadcastBitAsyncContinue 3706 break; 3707 3708 case eBroadcastBitAsyncThreadShouldExit: 3709 LLDB_LOGF(log, 3710 "ProcessGDBRemote::%s (arg = %p, pid = %" PRIu64 3711 ") got eBroadcastBitAsyncThreadShouldExit...", 3712 __FUNCTION__, arg, process->GetID()); 3713 done = true; 3714 break; 3715 3716 default: 3717 LLDB_LOGF(log, 3718 "ProcessGDBRemote::%s (arg = %p, pid = %" PRIu64 3719 ") got unknown event 0x%8.8x", 3720 __FUNCTION__, arg, process->GetID(), event_type); 3721 done = true; 3722 break; 3723 } 3724 } else if (event_sp->BroadcasterIs(&process->m_gdb_comm)) { 3725 switch (event_type) { 3726 case Communication::eBroadcastBitReadThreadDidExit: 3727 process->SetExitStatus(-1, "lost connection"); 3728 done = true; 3729 break; 3730 3731 default: 3732 LLDB_LOGF(log, 3733 "ProcessGDBRemote::%s (arg = %p, pid = %" PRIu64 3734 ") got unknown event 0x%8.8x", 3735 __FUNCTION__, arg, process->GetID(), event_type); 3736 done = true; 3737 break; 3738 } 3739 } 3740 } else { 3741 LLDB_LOGF(log, 3742 "ProcessGDBRemote::%s (arg = %p, pid = %" PRIu64 3743 ") listener.WaitForEvent (NULL, event_sp) => false", 3744 __FUNCTION__, arg, process->GetID()); 3745 done = true; 3746 } 3747 } 3748 3749 LLDB_LOGF(log, 3750 "ProcessGDBRemote::%s (arg = %p, pid = %" PRIu64 3751 ") thread exiting...", 3752 __FUNCTION__, arg, process->GetID()); 3753 3754 return {}; 3755 } 3756 3757 // uint32_t 3758 // ProcessGDBRemote::ListProcessesMatchingName (const char *name, StringList 3759 // &matches, std::vector<lldb::pid_t> &pids) 3760 //{ 3761 // // If we are planning to launch the debugserver remotely, then we need to 3762 // fire up a debugserver 3763 // // process and ask it for the list of processes. But if we are local, we 3764 // can let the Host do it. 3765 // if (m_local_debugserver) 3766 // { 3767 // return Host::ListProcessesMatchingName (name, matches, pids); 3768 // } 3769 // else 3770 // { 3771 // // FIXME: Implement talking to the remote debugserver. 3772 // return 0; 3773 // } 3774 // 3775 //} 3776 // 3777 bool ProcessGDBRemote::NewThreadNotifyBreakpointHit( 3778 void *baton, StoppointCallbackContext *context, lldb::user_id_t break_id, 3779 lldb::user_id_t break_loc_id) { 3780 // I don't think I have to do anything here, just make sure I notice the new 3781 // thread when it starts to 3782 // run so I can stop it if that's what I want to do. 3783 Log *log = GetLog(LLDBLog::Step); 3784 LLDB_LOGF(log, "Hit New Thread Notification breakpoint."); 3785 return false; 3786 } 3787 3788 Status ProcessGDBRemote::UpdateAutomaticSignalFiltering() { 3789 Log *log = GetLog(GDBRLog::Process); 3790 LLDB_LOG(log, "Check if need to update ignored signals"); 3791 3792 // QPassSignals package is not supported by the server, there is no way we 3793 // can ignore any signals on server side. 3794 if (!m_gdb_comm.GetQPassSignalsSupported()) 3795 return Status(); 3796 3797 // No signals, nothing to send. 3798 if (m_unix_signals_sp == nullptr) 3799 return Status(); 3800 3801 // Signals' version hasn't changed, no need to send anything. 3802 uint64_t new_signals_version = m_unix_signals_sp->GetVersion(); 3803 if (new_signals_version == m_last_signals_version) { 3804 LLDB_LOG(log, "Signals' version hasn't changed. version={0}", 3805 m_last_signals_version); 3806 return Status(); 3807 } 3808 3809 auto signals_to_ignore = 3810 m_unix_signals_sp->GetFilteredSignals(false, false, false); 3811 Status error = m_gdb_comm.SendSignalsToIgnore(signals_to_ignore); 3812 3813 LLDB_LOG(log, 3814 "Signals' version changed. old version={0}, new version={1}, " 3815 "signals ignored={2}, update result={3}", 3816 m_last_signals_version, new_signals_version, 3817 signals_to_ignore.size(), error); 3818 3819 if (error.Success()) 3820 m_last_signals_version = new_signals_version; 3821 3822 return error; 3823 } 3824 3825 bool ProcessGDBRemote::StartNoticingNewThreads() { 3826 Log *log = GetLog(LLDBLog::Step); 3827 if (m_thread_create_bp_sp) { 3828 if (log && log->GetVerbose()) 3829 LLDB_LOGF(log, "Enabled noticing new thread breakpoint."); 3830 m_thread_create_bp_sp->SetEnabled(true); 3831 } else { 3832 PlatformSP platform_sp(GetTarget().GetPlatform()); 3833 if (platform_sp) { 3834 m_thread_create_bp_sp = 3835 platform_sp->SetThreadCreationBreakpoint(GetTarget()); 3836 if (m_thread_create_bp_sp) { 3837 if (log && log->GetVerbose()) 3838 LLDB_LOGF( 3839 log, "Successfully created new thread notification breakpoint %i", 3840 m_thread_create_bp_sp->GetID()); 3841 m_thread_create_bp_sp->SetCallback( 3842 ProcessGDBRemote::NewThreadNotifyBreakpointHit, this, true); 3843 } else { 3844 LLDB_LOGF(log, "Failed to create new thread notification breakpoint."); 3845 } 3846 } 3847 } 3848 return m_thread_create_bp_sp.get() != nullptr; 3849 } 3850 3851 bool ProcessGDBRemote::StopNoticingNewThreads() { 3852 Log *log = GetLog(LLDBLog::Step); 3853 if (log && log->GetVerbose()) 3854 LLDB_LOGF(log, "Disabling new thread notification breakpoint."); 3855 3856 if (m_thread_create_bp_sp) 3857 m_thread_create_bp_sp->SetEnabled(false); 3858 3859 return true; 3860 } 3861 3862 DynamicLoader *ProcessGDBRemote::GetDynamicLoader() { 3863 if (m_dyld_up.get() == nullptr) 3864 m_dyld_up.reset(DynamicLoader::FindPlugin(this, "")); 3865 return m_dyld_up.get(); 3866 } 3867 3868 Status ProcessGDBRemote::SendEventData(const char *data) { 3869 int return_value; 3870 bool was_supported; 3871 3872 Status error; 3873 3874 return_value = m_gdb_comm.SendLaunchEventDataPacket(data, &was_supported); 3875 if (return_value != 0) { 3876 if (!was_supported) 3877 error.SetErrorString("Sending events is not supported for this process."); 3878 else 3879 error.SetErrorStringWithFormat("Error sending event data: %d.", 3880 return_value); 3881 } 3882 return error; 3883 } 3884 3885 DataExtractor ProcessGDBRemote::GetAuxvData() { 3886 DataBufferSP buf; 3887 if (m_gdb_comm.GetQXferAuxvReadSupported()) { 3888 llvm::Expected<std::string> response = m_gdb_comm.ReadExtFeature("auxv", ""); 3889 if (response) 3890 buf = std::make_shared<DataBufferHeap>(response->c_str(), 3891 response->length()); 3892 else 3893 LLDB_LOG_ERROR(GetLog(GDBRLog::Process), response.takeError(), "{0}"); 3894 } 3895 return DataExtractor(buf, GetByteOrder(), GetAddressByteSize()); 3896 } 3897 3898 StructuredData::ObjectSP 3899 ProcessGDBRemote::GetExtendedInfoForThread(lldb::tid_t tid) { 3900 StructuredData::ObjectSP object_sp; 3901 3902 if (m_gdb_comm.GetThreadExtendedInfoSupported()) { 3903 StructuredData::ObjectSP args_dict(new StructuredData::Dictionary()); 3904 SystemRuntime *runtime = GetSystemRuntime(); 3905 if (runtime) { 3906 runtime->AddThreadExtendedInfoPacketHints(args_dict); 3907 } 3908 args_dict->GetAsDictionary()->AddIntegerItem("thread", tid); 3909 3910 StreamString packet; 3911 packet << "jThreadExtendedInfo:"; 3912 args_dict->Dump(packet, false); 3913 3914 // FIXME the final character of a JSON dictionary, '}', is the escape 3915 // character in gdb-remote binary mode. lldb currently doesn't escape 3916 // these characters in its packet output -- so we add the quoted version of 3917 // the } character here manually in case we talk to a debugserver which un- 3918 // escapes the characters at packet read time. 3919 packet << (char)(0x7d ^ 0x20); 3920 3921 StringExtractorGDBRemote response; 3922 response.SetResponseValidatorToJSON(); 3923 if (m_gdb_comm.SendPacketAndWaitForResponse(packet.GetString(), response) == 3924 GDBRemoteCommunication::PacketResult::Success) { 3925 StringExtractorGDBRemote::ResponseType response_type = 3926 response.GetResponseType(); 3927 if (response_type == StringExtractorGDBRemote::eResponse) { 3928 if (!response.Empty()) { 3929 object_sp = 3930 StructuredData::ParseJSON(std::string(response.GetStringRef())); 3931 } 3932 } 3933 } 3934 } 3935 return object_sp; 3936 } 3937 3938 StructuredData::ObjectSP ProcessGDBRemote::GetLoadedDynamicLibrariesInfos( 3939 lldb::addr_t image_list_address, lldb::addr_t image_count) { 3940 3941 StructuredData::ObjectSP args_dict(new StructuredData::Dictionary()); 3942 args_dict->GetAsDictionary()->AddIntegerItem("image_list_address", 3943 image_list_address); 3944 args_dict->GetAsDictionary()->AddIntegerItem("image_count", image_count); 3945 3946 return GetLoadedDynamicLibrariesInfos_sender(args_dict); 3947 } 3948 3949 StructuredData::ObjectSP ProcessGDBRemote::GetLoadedDynamicLibrariesInfos() { 3950 StructuredData::ObjectSP args_dict(new StructuredData::Dictionary()); 3951 3952 args_dict->GetAsDictionary()->AddBooleanItem("fetch_all_solibs", true); 3953 3954 return GetLoadedDynamicLibrariesInfos_sender(args_dict); 3955 } 3956 3957 StructuredData::ObjectSP ProcessGDBRemote::GetLoadedDynamicLibrariesInfos( 3958 const std::vector<lldb::addr_t> &load_addresses) { 3959 StructuredData::ObjectSP args_dict(new StructuredData::Dictionary()); 3960 StructuredData::ArraySP addresses(new StructuredData::Array); 3961 3962 for (auto addr : load_addresses) { 3963 StructuredData::ObjectSP addr_sp(new StructuredData::Integer(addr)); 3964 addresses->AddItem(addr_sp); 3965 } 3966 3967 args_dict->GetAsDictionary()->AddItem("solib_addresses", addresses); 3968 3969 return GetLoadedDynamicLibrariesInfos_sender(args_dict); 3970 } 3971 3972 StructuredData::ObjectSP 3973 ProcessGDBRemote::GetLoadedDynamicLibrariesInfos_sender( 3974 StructuredData::ObjectSP args_dict) { 3975 StructuredData::ObjectSP object_sp; 3976 3977 if (m_gdb_comm.GetLoadedDynamicLibrariesInfosSupported()) { 3978 // Scope for the scoped timeout object 3979 GDBRemoteCommunication::ScopedTimeout timeout(m_gdb_comm, 3980 std::chrono::seconds(10)); 3981 3982 StreamString packet; 3983 packet << "jGetLoadedDynamicLibrariesInfos:"; 3984 args_dict->Dump(packet, false); 3985 3986 // FIXME the final character of a JSON dictionary, '}', is the escape 3987 // character in gdb-remote binary mode. lldb currently doesn't escape 3988 // these characters in its packet output -- so we add the quoted version of 3989 // the } character here manually in case we talk to a debugserver which un- 3990 // escapes the characters at packet read time. 3991 packet << (char)(0x7d ^ 0x20); 3992 3993 StringExtractorGDBRemote response; 3994 response.SetResponseValidatorToJSON(); 3995 if (m_gdb_comm.SendPacketAndWaitForResponse(packet.GetString(), response) == 3996 GDBRemoteCommunication::PacketResult::Success) { 3997 StringExtractorGDBRemote::ResponseType response_type = 3998 response.GetResponseType(); 3999 if (response_type == StringExtractorGDBRemote::eResponse) { 4000 if (!response.Empty()) { 4001 object_sp = 4002 StructuredData::ParseJSON(std::string(response.GetStringRef())); 4003 } 4004 } 4005 } 4006 } 4007 return object_sp; 4008 } 4009 4010 StructuredData::ObjectSP ProcessGDBRemote::GetSharedCacheInfo() { 4011 StructuredData::ObjectSP object_sp; 4012 StructuredData::ObjectSP args_dict(new StructuredData::Dictionary()); 4013 4014 if (m_gdb_comm.GetSharedCacheInfoSupported()) { 4015 StreamString packet; 4016 packet << "jGetSharedCacheInfo:"; 4017 args_dict->Dump(packet, false); 4018 4019 // FIXME the final character of a JSON dictionary, '}', is the escape 4020 // character in gdb-remote binary mode. lldb currently doesn't escape 4021 // these characters in its packet output -- so we add the quoted version of 4022 // the } character here manually in case we talk to a debugserver which un- 4023 // escapes the characters at packet read time. 4024 packet << (char)(0x7d ^ 0x20); 4025 4026 StringExtractorGDBRemote response; 4027 response.SetResponseValidatorToJSON(); 4028 if (m_gdb_comm.SendPacketAndWaitForResponse(packet.GetString(), response) == 4029 GDBRemoteCommunication::PacketResult::Success) { 4030 StringExtractorGDBRemote::ResponseType response_type = 4031 response.GetResponseType(); 4032 if (response_type == StringExtractorGDBRemote::eResponse) { 4033 if (!response.Empty()) { 4034 object_sp = 4035 StructuredData::ParseJSON(std::string(response.GetStringRef())); 4036 } 4037 } 4038 } 4039 } 4040 return object_sp; 4041 } 4042 4043 Status ProcessGDBRemote::ConfigureStructuredData( 4044 ConstString type_name, const StructuredData::ObjectSP &config_sp) { 4045 return m_gdb_comm.ConfigureRemoteStructuredData(type_name, config_sp); 4046 } 4047 4048 // Establish the largest memory read/write payloads we should use. If the 4049 // remote stub has a max packet size, stay under that size. 4050 // 4051 // If the remote stub's max packet size is crazy large, use a reasonable 4052 // largeish default. 4053 // 4054 // If the remote stub doesn't advertise a max packet size, use a conservative 4055 // default. 4056 4057 void ProcessGDBRemote::GetMaxMemorySize() { 4058 const uint64_t reasonable_largeish_default = 128 * 1024; 4059 const uint64_t conservative_default = 512; 4060 4061 if (m_max_memory_size == 0) { 4062 uint64_t stub_max_size = m_gdb_comm.GetRemoteMaxPacketSize(); 4063 if (stub_max_size != UINT64_MAX && stub_max_size != 0) { 4064 // Save the stub's claimed maximum packet size 4065 m_remote_stub_max_memory_size = stub_max_size; 4066 4067 // Even if the stub says it can support ginormous packets, don't exceed 4068 // our reasonable largeish default packet size. 4069 if (stub_max_size > reasonable_largeish_default) { 4070 stub_max_size = reasonable_largeish_default; 4071 } 4072 4073 // Memory packet have other overheads too like Maddr,size:#NN Instead of 4074 // calculating the bytes taken by size and addr every time, we take a 4075 // maximum guess here. 4076 if (stub_max_size > 70) 4077 stub_max_size -= 32 + 32 + 6; 4078 else { 4079 // In unlikely scenario that max packet size is less then 70, we will 4080 // hope that data being written is small enough to fit. 4081 Log *log(GetLog(GDBRLog::Comm | GDBRLog::Memory)); 4082 if (log) 4083 log->Warning("Packet size is too small. " 4084 "LLDB may face problems while writing memory"); 4085 } 4086 4087 m_max_memory_size = stub_max_size; 4088 } else { 4089 m_max_memory_size = conservative_default; 4090 } 4091 } 4092 } 4093 4094 void ProcessGDBRemote::SetUserSpecifiedMaxMemoryTransferSize( 4095 uint64_t user_specified_max) { 4096 if (user_specified_max != 0) { 4097 GetMaxMemorySize(); 4098 4099 if (m_remote_stub_max_memory_size != 0) { 4100 if (m_remote_stub_max_memory_size < user_specified_max) { 4101 m_max_memory_size = m_remote_stub_max_memory_size; // user specified a 4102 // packet size too 4103 // big, go as big 4104 // as the remote stub says we can go. 4105 } else { 4106 m_max_memory_size = user_specified_max; // user's packet size is good 4107 } 4108 } else { 4109 m_max_memory_size = 4110 user_specified_max; // user's packet size is probably fine 4111 } 4112 } 4113 } 4114 4115 bool ProcessGDBRemote::GetModuleSpec(const FileSpec &module_file_spec, 4116 const ArchSpec &arch, 4117 ModuleSpec &module_spec) { 4118 Log *log = GetLog(LLDBLog::Platform); 4119 4120 const ModuleCacheKey key(module_file_spec.GetPath(), 4121 arch.GetTriple().getTriple()); 4122 auto cached = m_cached_module_specs.find(key); 4123 if (cached != m_cached_module_specs.end()) { 4124 module_spec = cached->second; 4125 return bool(module_spec); 4126 } 4127 4128 if (!m_gdb_comm.GetModuleInfo(module_file_spec, arch, module_spec)) { 4129 LLDB_LOGF(log, "ProcessGDBRemote::%s - failed to get module info for %s:%s", 4130 __FUNCTION__, module_file_spec.GetPath().c_str(), 4131 arch.GetTriple().getTriple().c_str()); 4132 return false; 4133 } 4134 4135 if (log) { 4136 StreamString stream; 4137 module_spec.Dump(stream); 4138 LLDB_LOGF(log, "ProcessGDBRemote::%s - got module info for (%s:%s) : %s", 4139 __FUNCTION__, module_file_spec.GetPath().c_str(), 4140 arch.GetTriple().getTriple().c_str(), stream.GetData()); 4141 } 4142 4143 m_cached_module_specs[key] = module_spec; 4144 return true; 4145 } 4146 4147 void ProcessGDBRemote::PrefetchModuleSpecs( 4148 llvm::ArrayRef<FileSpec> module_file_specs, const llvm::Triple &triple) { 4149 auto module_specs = m_gdb_comm.GetModulesInfo(module_file_specs, triple); 4150 if (module_specs) { 4151 for (const FileSpec &spec : module_file_specs) 4152 m_cached_module_specs[ModuleCacheKey(spec.GetPath(), 4153 triple.getTriple())] = ModuleSpec(); 4154 for (const ModuleSpec &spec : *module_specs) 4155 m_cached_module_specs[ModuleCacheKey(spec.GetFileSpec().GetPath(), 4156 triple.getTriple())] = spec; 4157 } 4158 } 4159 4160 llvm::VersionTuple ProcessGDBRemote::GetHostOSVersion() { 4161 return m_gdb_comm.GetOSVersion(); 4162 } 4163 4164 llvm::VersionTuple ProcessGDBRemote::GetHostMacCatalystVersion() { 4165 return m_gdb_comm.GetMacCatalystVersion(); 4166 } 4167 4168 namespace { 4169 4170 typedef std::vector<std::string> stringVec; 4171 4172 typedef std::vector<struct GdbServerRegisterInfo> GDBServerRegisterVec; 4173 struct RegisterSetInfo { 4174 ConstString name; 4175 }; 4176 4177 typedef std::map<uint32_t, RegisterSetInfo> RegisterSetMap; 4178 4179 struct GdbServerTargetInfo { 4180 std::string arch; 4181 std::string osabi; 4182 stringVec includes; 4183 RegisterSetMap reg_set_map; 4184 }; 4185 4186 bool ParseRegisters(XMLNode feature_node, GdbServerTargetInfo &target_info, 4187 std::vector<DynamicRegisterInfo::Register> ®isters) { 4188 if (!feature_node) 4189 return false; 4190 4191 feature_node.ForEachChildElementWithName( 4192 "reg", [&target_info, ®isters](const XMLNode ®_node) -> bool { 4193 std::string gdb_group; 4194 std::string gdb_type; 4195 DynamicRegisterInfo::Register reg_info; 4196 bool encoding_set = false; 4197 bool format_set = false; 4198 4199 // FIXME: we're silently ignoring invalid data here 4200 reg_node.ForEachAttribute([&target_info, &gdb_group, &gdb_type, 4201 &encoding_set, &format_set, ®_info]( 4202 const llvm::StringRef &name, 4203 const llvm::StringRef &value) -> bool { 4204 if (name == "name") { 4205 reg_info.name.SetString(value); 4206 } else if (name == "bitsize") { 4207 if (llvm::to_integer(value, reg_info.byte_size)) 4208 reg_info.byte_size = 4209 llvm::divideCeil(reg_info.byte_size, CHAR_BIT); 4210 } else if (name == "type") { 4211 gdb_type = value.str(); 4212 } else if (name == "group") { 4213 gdb_group = value.str(); 4214 } else if (name == "regnum") { 4215 llvm::to_integer(value, reg_info.regnum_remote); 4216 } else if (name == "offset") { 4217 llvm::to_integer(value, reg_info.byte_offset); 4218 } else if (name == "altname") { 4219 reg_info.alt_name.SetString(value); 4220 } else if (name == "encoding") { 4221 encoding_set = true; 4222 reg_info.encoding = Args::StringToEncoding(value, eEncodingUint); 4223 } else if (name == "format") { 4224 format_set = true; 4225 if (!OptionArgParser::ToFormat(value.data(), reg_info.format, 4226 nullptr) 4227 .Success()) 4228 reg_info.format = 4229 llvm::StringSwitch<lldb::Format>(value) 4230 .Case("vector-sint8", eFormatVectorOfSInt8) 4231 .Case("vector-uint8", eFormatVectorOfUInt8) 4232 .Case("vector-sint16", eFormatVectorOfSInt16) 4233 .Case("vector-uint16", eFormatVectorOfUInt16) 4234 .Case("vector-sint32", eFormatVectorOfSInt32) 4235 .Case("vector-uint32", eFormatVectorOfUInt32) 4236 .Case("vector-float32", eFormatVectorOfFloat32) 4237 .Case("vector-uint64", eFormatVectorOfUInt64) 4238 .Case("vector-uint128", eFormatVectorOfUInt128) 4239 .Default(eFormatInvalid); 4240 } else if (name == "group_id") { 4241 uint32_t set_id = UINT32_MAX; 4242 llvm::to_integer(value, set_id); 4243 RegisterSetMap::const_iterator pos = 4244 target_info.reg_set_map.find(set_id); 4245 if (pos != target_info.reg_set_map.end()) 4246 reg_info.set_name = pos->second.name; 4247 } else if (name == "gcc_regnum" || name == "ehframe_regnum") { 4248 llvm::to_integer(value, reg_info.regnum_ehframe); 4249 } else if (name == "dwarf_regnum") { 4250 llvm::to_integer(value, reg_info.regnum_dwarf); 4251 } else if (name == "generic") { 4252 reg_info.regnum_generic = Args::StringToGenericRegister(value); 4253 } else if (name == "value_regnums") { 4254 SplitCommaSeparatedRegisterNumberString(value, reg_info.value_regs, 4255 0); 4256 } else if (name == "invalidate_regnums") { 4257 SplitCommaSeparatedRegisterNumberString( 4258 value, reg_info.invalidate_regs, 0); 4259 } else { 4260 Log *log(GetLog(GDBRLog::Process)); 4261 LLDB_LOGF(log, 4262 "ProcessGDBRemote::%s unhandled reg attribute %s = %s", 4263 __FUNCTION__, name.data(), value.data()); 4264 } 4265 return true; // Keep iterating through all attributes 4266 }); 4267 4268 if (!gdb_type.empty() && !(encoding_set || format_set)) { 4269 if (llvm::StringRef(gdb_type).startswith("int")) { 4270 reg_info.format = eFormatHex; 4271 reg_info.encoding = eEncodingUint; 4272 } else if (gdb_type == "data_ptr" || gdb_type == "code_ptr") { 4273 reg_info.format = eFormatAddressInfo; 4274 reg_info.encoding = eEncodingUint; 4275 } else if (gdb_type == "float") { 4276 reg_info.format = eFormatFloat; 4277 reg_info.encoding = eEncodingIEEE754; 4278 } else if (gdb_type == "aarch64v" || 4279 llvm::StringRef(gdb_type).startswith("vec") || 4280 gdb_type == "i387_ext" || gdb_type == "uint128") { 4281 // lldb doesn't handle 128-bit uints correctly (for ymm*h), so treat 4282 // them as vector (similarly to xmm/ymm) 4283 reg_info.format = eFormatVectorOfUInt8; 4284 reg_info.encoding = eEncodingVector; 4285 } 4286 } 4287 4288 // Only update the register set name if we didn't get a "reg_set" 4289 // attribute. "set_name" will be empty if we didn't have a "reg_set" 4290 // attribute. 4291 if (!reg_info.set_name) { 4292 if (!gdb_group.empty()) { 4293 reg_info.set_name.SetCString(gdb_group.c_str()); 4294 } else { 4295 // If no register group name provided anywhere, 4296 // we'll create a 'general' register set 4297 reg_info.set_name.SetCString("general"); 4298 } 4299 } 4300 4301 if (reg_info.byte_size == 0) { 4302 Log *log(GetLog(GDBRLog::Process)); 4303 LLDB_LOGF(log, 4304 "ProcessGDBRemote::%s Skipping zero bitsize register %s", 4305 __FUNCTION__, reg_info.name.AsCString()); 4306 } else 4307 registers.push_back(reg_info); 4308 4309 return true; // Keep iterating through all "reg" elements 4310 }); 4311 return true; 4312 } 4313 4314 } // namespace 4315 4316 // This method fetches a register description feature xml file from 4317 // the remote stub and adds registers/register groupsets/architecture 4318 // information to the current process. It will call itself recursively 4319 // for nested register definition files. It returns true if it was able 4320 // to fetch and parse an xml file. 4321 bool ProcessGDBRemote::GetGDBServerRegisterInfoXMLAndProcess( 4322 ArchSpec &arch_to_use, std::string xml_filename, 4323 std::vector<DynamicRegisterInfo::Register> ®isters) { 4324 // request the target xml file 4325 llvm::Expected<std::string> raw = m_gdb_comm.ReadExtFeature("features", xml_filename); 4326 if (errorToBool(raw.takeError())) 4327 return false; 4328 4329 XMLDocument xml_document; 4330 4331 if (xml_document.ParseMemory(raw->c_str(), raw->size(), 4332 xml_filename.c_str())) { 4333 GdbServerTargetInfo target_info; 4334 std::vector<XMLNode> feature_nodes; 4335 4336 // The top level feature XML file will start with a <target> tag. 4337 XMLNode target_node = xml_document.GetRootElement("target"); 4338 if (target_node) { 4339 target_node.ForEachChildElement([&target_info, &feature_nodes]( 4340 const XMLNode &node) -> bool { 4341 llvm::StringRef name = node.GetName(); 4342 if (name == "architecture") { 4343 node.GetElementText(target_info.arch); 4344 } else if (name == "osabi") { 4345 node.GetElementText(target_info.osabi); 4346 } else if (name == "xi:include" || name == "include") { 4347 std::string href = node.GetAttributeValue("href"); 4348 if (!href.empty()) 4349 target_info.includes.push_back(href); 4350 } else if (name == "feature") { 4351 feature_nodes.push_back(node); 4352 } else if (name == "groups") { 4353 node.ForEachChildElementWithName( 4354 "group", [&target_info](const XMLNode &node) -> bool { 4355 uint32_t set_id = UINT32_MAX; 4356 RegisterSetInfo set_info; 4357 4358 node.ForEachAttribute( 4359 [&set_id, &set_info](const llvm::StringRef &name, 4360 const llvm::StringRef &value) -> bool { 4361 // FIXME: we're silently ignoring invalid data here 4362 if (name == "id") 4363 llvm::to_integer(value, set_id); 4364 if (name == "name") 4365 set_info.name = ConstString(value); 4366 return true; // Keep iterating through all attributes 4367 }); 4368 4369 if (set_id != UINT32_MAX) 4370 target_info.reg_set_map[set_id] = set_info; 4371 return true; // Keep iterating through all "group" elements 4372 }); 4373 } 4374 return true; // Keep iterating through all children of the target_node 4375 }); 4376 } else { 4377 // In an included XML feature file, we're already "inside" the <target> 4378 // tag of the initial XML file; this included file will likely only have 4379 // a <feature> tag. Need to check for any more included files in this 4380 // <feature> element. 4381 XMLNode feature_node = xml_document.GetRootElement("feature"); 4382 if (feature_node) { 4383 feature_nodes.push_back(feature_node); 4384 feature_node.ForEachChildElement([&target_info]( 4385 const XMLNode &node) -> bool { 4386 llvm::StringRef name = node.GetName(); 4387 if (name == "xi:include" || name == "include") { 4388 std::string href = node.GetAttributeValue("href"); 4389 if (!href.empty()) 4390 target_info.includes.push_back(href); 4391 } 4392 return true; 4393 }); 4394 } 4395 } 4396 4397 // gdbserver does not implement the LLDB packets used to determine host 4398 // or process architecture. If that is the case, attempt to use 4399 // the <architecture/> field from target.xml, e.g.: 4400 // 4401 // <architecture>i386:x86-64</architecture> (seen from VMWare ESXi) 4402 // <architecture>arm</architecture> (seen from Segger JLink on unspecified 4403 // arm board) 4404 if (!arch_to_use.IsValid() && !target_info.arch.empty()) { 4405 // We don't have any information about vendor or OS. 4406 arch_to_use.SetTriple(llvm::StringSwitch<std::string>(target_info.arch) 4407 .Case("i386:x86-64", "x86_64") 4408 .Default(target_info.arch) + 4409 "--"); 4410 4411 if (arch_to_use.IsValid()) 4412 GetTarget().MergeArchitecture(arch_to_use); 4413 } 4414 4415 if (arch_to_use.IsValid()) { 4416 for (auto &feature_node : feature_nodes) { 4417 ParseRegisters(feature_node, target_info, 4418 registers); 4419 } 4420 4421 for (const auto &include : target_info.includes) { 4422 GetGDBServerRegisterInfoXMLAndProcess(arch_to_use, include, 4423 registers); 4424 } 4425 } 4426 } else { 4427 return false; 4428 } 4429 return true; 4430 } 4431 4432 void ProcessGDBRemote::AddRemoteRegisters( 4433 std::vector<DynamicRegisterInfo::Register> ®isters, 4434 const ArchSpec &arch_to_use) { 4435 std::map<uint32_t, uint32_t> remote_to_local_map; 4436 uint32_t remote_regnum = 0; 4437 for (auto it : llvm::enumerate(registers)) { 4438 DynamicRegisterInfo::Register &remote_reg_info = it.value(); 4439 4440 // Assign successive remote regnums if missing. 4441 if (remote_reg_info.regnum_remote == LLDB_INVALID_REGNUM) 4442 remote_reg_info.regnum_remote = remote_regnum; 4443 4444 // Create a mapping from remote to local regnos. 4445 remote_to_local_map[remote_reg_info.regnum_remote] = it.index(); 4446 4447 remote_regnum = remote_reg_info.regnum_remote + 1; 4448 } 4449 4450 for (DynamicRegisterInfo::Register &remote_reg_info : registers) { 4451 auto proc_to_lldb = [&remote_to_local_map](uint32_t process_regnum) { 4452 auto lldb_regit = remote_to_local_map.find(process_regnum); 4453 return lldb_regit != remote_to_local_map.end() ? lldb_regit->second 4454 : LLDB_INVALID_REGNUM; 4455 }; 4456 4457 llvm::transform(remote_reg_info.value_regs, 4458 remote_reg_info.value_regs.begin(), proc_to_lldb); 4459 llvm::transform(remote_reg_info.invalidate_regs, 4460 remote_reg_info.invalidate_regs.begin(), proc_to_lldb); 4461 } 4462 4463 // Don't use Process::GetABI, this code gets called from DidAttach, and 4464 // in that context we haven't set the Target's architecture yet, so the 4465 // ABI is also potentially incorrect. 4466 if (ABISP abi_sp = ABI::FindPlugin(shared_from_this(), arch_to_use)) 4467 abi_sp->AugmentRegisterInfo(registers); 4468 4469 m_register_info_sp->SetRegisterInfo(std::move(registers), arch_to_use); 4470 } 4471 4472 // query the target of gdb-remote for extended target information returns 4473 // true on success (got register definitions), false on failure (did not). 4474 bool ProcessGDBRemote::GetGDBServerRegisterInfo(ArchSpec &arch_to_use) { 4475 // Make sure LLDB has an XML parser it can use first 4476 if (!XMLDocument::XMLEnabled()) 4477 return false; 4478 4479 // check that we have extended feature read support 4480 if (!m_gdb_comm.GetQXferFeaturesReadSupported()) 4481 return false; 4482 4483 std::vector<DynamicRegisterInfo::Register> registers; 4484 if (GetGDBServerRegisterInfoXMLAndProcess(arch_to_use, "target.xml", 4485 registers)) 4486 AddRemoteRegisters(registers, arch_to_use); 4487 4488 return m_register_info_sp->GetNumRegisters() > 0; 4489 } 4490 4491 llvm::Expected<LoadedModuleInfoList> ProcessGDBRemote::GetLoadedModuleList() { 4492 // Make sure LLDB has an XML parser it can use first 4493 if (!XMLDocument::XMLEnabled()) 4494 return llvm::createStringError(llvm::inconvertibleErrorCode(), 4495 "XML parsing not available"); 4496 4497 Log *log = GetLog(LLDBLog::Process); 4498 LLDB_LOGF(log, "ProcessGDBRemote::%s", __FUNCTION__); 4499 4500 LoadedModuleInfoList list; 4501 GDBRemoteCommunicationClient &comm = m_gdb_comm; 4502 bool can_use_svr4 = GetGlobalPluginProperties().GetUseSVR4(); 4503 4504 // check that we have extended feature read support 4505 if (can_use_svr4 && comm.GetQXferLibrariesSVR4ReadSupported()) { 4506 // request the loaded library list 4507 llvm::Expected<std::string> raw = comm.ReadExtFeature("libraries-svr4", ""); 4508 if (!raw) 4509 return raw.takeError(); 4510 4511 // parse the xml file in memory 4512 LLDB_LOGF(log, "parsing: %s", raw->c_str()); 4513 XMLDocument doc; 4514 4515 if (!doc.ParseMemory(raw->c_str(), raw->size(), "noname.xml")) 4516 return llvm::createStringError(llvm::inconvertibleErrorCode(), 4517 "Error reading noname.xml"); 4518 4519 XMLNode root_element = doc.GetRootElement("library-list-svr4"); 4520 if (!root_element) 4521 return llvm::createStringError( 4522 llvm::inconvertibleErrorCode(), 4523 "Error finding library-list-svr4 xml element"); 4524 4525 // main link map structure 4526 std::string main_lm = root_element.GetAttributeValue("main-lm"); 4527 // FIXME: we're silently ignoring invalid data here 4528 if (!main_lm.empty()) 4529 llvm::to_integer(main_lm, list.m_link_map); 4530 4531 root_element.ForEachChildElementWithName( 4532 "library", [log, &list](const XMLNode &library) -> bool { 4533 LoadedModuleInfoList::LoadedModuleInfo module; 4534 4535 // FIXME: we're silently ignoring invalid data here 4536 library.ForEachAttribute( 4537 [&module](const llvm::StringRef &name, 4538 const llvm::StringRef &value) -> bool { 4539 uint64_t uint_value = LLDB_INVALID_ADDRESS; 4540 if (name == "name") 4541 module.set_name(value.str()); 4542 else if (name == "lm") { 4543 // the address of the link_map struct. 4544 llvm::to_integer(value, uint_value); 4545 module.set_link_map(uint_value); 4546 } else if (name == "l_addr") { 4547 // the displacement as read from the field 'l_addr' of the 4548 // link_map struct. 4549 llvm::to_integer(value, uint_value); 4550 module.set_base(uint_value); 4551 // base address is always a displacement, not an absolute 4552 // value. 4553 module.set_base_is_offset(true); 4554 } else if (name == "l_ld") { 4555 // the memory address of the libraries PT_DYNAMIC section. 4556 llvm::to_integer(value, uint_value); 4557 module.set_dynamic(uint_value); 4558 } 4559 4560 return true; // Keep iterating over all properties of "library" 4561 }); 4562 4563 if (log) { 4564 std::string name; 4565 lldb::addr_t lm = 0, base = 0, ld = 0; 4566 bool base_is_offset; 4567 4568 module.get_name(name); 4569 module.get_link_map(lm); 4570 module.get_base(base); 4571 module.get_base_is_offset(base_is_offset); 4572 module.get_dynamic(ld); 4573 4574 LLDB_LOGF(log, 4575 "found (link_map:0x%08" PRIx64 ", base:0x%08" PRIx64 4576 "[%s], ld:0x%08" PRIx64 ", name:'%s')", 4577 lm, base, (base_is_offset ? "offset" : "absolute"), ld, 4578 name.c_str()); 4579 } 4580 4581 list.add(module); 4582 return true; // Keep iterating over all "library" elements in the root 4583 // node 4584 }); 4585 4586 if (log) 4587 LLDB_LOGF(log, "found %" PRId32 " modules in total", 4588 (int)list.m_list.size()); 4589 return list; 4590 } else if (comm.GetQXferLibrariesReadSupported()) { 4591 // request the loaded library list 4592 llvm::Expected<std::string> raw = comm.ReadExtFeature("libraries", ""); 4593 4594 if (!raw) 4595 return raw.takeError(); 4596 4597 LLDB_LOGF(log, "parsing: %s", raw->c_str()); 4598 XMLDocument doc; 4599 4600 if (!doc.ParseMemory(raw->c_str(), raw->size(), "noname.xml")) 4601 return llvm::createStringError(llvm::inconvertibleErrorCode(), 4602 "Error reading noname.xml"); 4603 4604 XMLNode root_element = doc.GetRootElement("library-list"); 4605 if (!root_element) 4606 return llvm::createStringError(llvm::inconvertibleErrorCode(), 4607 "Error finding library-list xml element"); 4608 4609 // FIXME: we're silently ignoring invalid data here 4610 root_element.ForEachChildElementWithName( 4611 "library", [log, &list](const XMLNode &library) -> bool { 4612 LoadedModuleInfoList::LoadedModuleInfo module; 4613 4614 std::string name = library.GetAttributeValue("name"); 4615 module.set_name(name); 4616 4617 // The base address of a given library will be the address of its 4618 // first section. Most remotes send only one section for Windows 4619 // targets for example. 4620 const XMLNode §ion = 4621 library.FindFirstChildElementWithName("section"); 4622 std::string address = section.GetAttributeValue("address"); 4623 uint64_t address_value = LLDB_INVALID_ADDRESS; 4624 llvm::to_integer(address, address_value); 4625 module.set_base(address_value); 4626 // These addresses are absolute values. 4627 module.set_base_is_offset(false); 4628 4629 if (log) { 4630 std::string name; 4631 lldb::addr_t base = 0; 4632 bool base_is_offset; 4633 module.get_name(name); 4634 module.get_base(base); 4635 module.get_base_is_offset(base_is_offset); 4636 4637 LLDB_LOGF(log, "found (base:0x%08" PRIx64 "[%s], name:'%s')", base, 4638 (base_is_offset ? "offset" : "absolute"), name.c_str()); 4639 } 4640 4641 list.add(module); 4642 return true; // Keep iterating over all "library" elements in the root 4643 // node 4644 }); 4645 4646 if (log) 4647 LLDB_LOGF(log, "found %" PRId32 " modules in total", 4648 (int)list.m_list.size()); 4649 return list; 4650 } else { 4651 return llvm::createStringError(llvm::inconvertibleErrorCode(), 4652 "Remote libraries not supported"); 4653 } 4654 } 4655 4656 lldb::ModuleSP ProcessGDBRemote::LoadModuleAtAddress(const FileSpec &file, 4657 lldb::addr_t link_map, 4658 lldb::addr_t base_addr, 4659 bool value_is_offset) { 4660 DynamicLoader *loader = GetDynamicLoader(); 4661 if (!loader) 4662 return nullptr; 4663 4664 return loader->LoadModuleAtAddress(file, link_map, base_addr, 4665 value_is_offset); 4666 } 4667 4668 llvm::Error ProcessGDBRemote::LoadModules() { 4669 using lldb_private::process_gdb_remote::ProcessGDBRemote; 4670 4671 // request a list of loaded libraries from GDBServer 4672 llvm::Expected<LoadedModuleInfoList> module_list = GetLoadedModuleList(); 4673 if (!module_list) 4674 return module_list.takeError(); 4675 4676 // get a list of all the modules 4677 ModuleList new_modules; 4678 4679 for (LoadedModuleInfoList::LoadedModuleInfo &modInfo : module_list->m_list) { 4680 std::string mod_name; 4681 lldb::addr_t mod_base; 4682 lldb::addr_t link_map; 4683 bool mod_base_is_offset; 4684 4685 bool valid = true; 4686 valid &= modInfo.get_name(mod_name); 4687 valid &= modInfo.get_base(mod_base); 4688 valid &= modInfo.get_base_is_offset(mod_base_is_offset); 4689 if (!valid) 4690 continue; 4691 4692 if (!modInfo.get_link_map(link_map)) 4693 link_map = LLDB_INVALID_ADDRESS; 4694 4695 FileSpec file(mod_name); 4696 FileSystem::Instance().Resolve(file); 4697 lldb::ModuleSP module_sp = 4698 LoadModuleAtAddress(file, link_map, mod_base, mod_base_is_offset); 4699 4700 if (module_sp.get()) 4701 new_modules.Append(module_sp); 4702 } 4703 4704 if (new_modules.GetSize() > 0) { 4705 ModuleList removed_modules; 4706 Target &target = GetTarget(); 4707 ModuleList &loaded_modules = m_process->GetTarget().GetImages(); 4708 4709 for (size_t i = 0; i < loaded_modules.GetSize(); ++i) { 4710 const lldb::ModuleSP loaded_module = loaded_modules.GetModuleAtIndex(i); 4711 4712 bool found = false; 4713 for (size_t j = 0; j < new_modules.GetSize(); ++j) { 4714 if (new_modules.GetModuleAtIndex(j).get() == loaded_module.get()) 4715 found = true; 4716 } 4717 4718 // The main executable will never be included in libraries-svr4, don't 4719 // remove it 4720 if (!found && 4721 loaded_module.get() != target.GetExecutableModulePointer()) { 4722 removed_modules.Append(loaded_module); 4723 } 4724 } 4725 4726 loaded_modules.Remove(removed_modules); 4727 m_process->GetTarget().ModulesDidUnload(removed_modules, false); 4728 4729 new_modules.ForEach([&target](const lldb::ModuleSP module_sp) -> bool { 4730 lldb_private::ObjectFile *obj = module_sp->GetObjectFile(); 4731 if (!obj) 4732 return true; 4733 4734 if (obj->GetType() != ObjectFile::Type::eTypeExecutable) 4735 return true; 4736 4737 lldb::ModuleSP module_copy_sp = module_sp; 4738 target.SetExecutableModule(module_copy_sp, eLoadDependentsNo); 4739 return false; 4740 }); 4741 4742 loaded_modules.AppendIfNeeded(new_modules); 4743 m_process->GetTarget().ModulesDidLoad(new_modules); 4744 } 4745 4746 return llvm::ErrorSuccess(); 4747 } 4748 4749 Status ProcessGDBRemote::GetFileLoadAddress(const FileSpec &file, 4750 bool &is_loaded, 4751 lldb::addr_t &load_addr) { 4752 is_loaded = false; 4753 load_addr = LLDB_INVALID_ADDRESS; 4754 4755 std::string file_path = file.GetPath(false); 4756 if (file_path.empty()) 4757 return Status("Empty file name specified"); 4758 4759 StreamString packet; 4760 packet.PutCString("qFileLoadAddress:"); 4761 packet.PutStringAsRawHex8(file_path); 4762 4763 StringExtractorGDBRemote response; 4764 if (m_gdb_comm.SendPacketAndWaitForResponse(packet.GetString(), response) != 4765 GDBRemoteCommunication::PacketResult::Success) 4766 return Status("Sending qFileLoadAddress packet failed"); 4767 4768 if (response.IsErrorResponse()) { 4769 if (response.GetError() == 1) { 4770 // The file is not loaded into the inferior 4771 is_loaded = false; 4772 load_addr = LLDB_INVALID_ADDRESS; 4773 return Status(); 4774 } 4775 4776 return Status( 4777 "Fetching file load address from remote server returned an error"); 4778 } 4779 4780 if (response.IsNormalResponse()) { 4781 is_loaded = true; 4782 load_addr = response.GetHexMaxU64(false, LLDB_INVALID_ADDRESS); 4783 return Status(); 4784 } 4785 4786 return Status( 4787 "Unknown error happened during sending the load address packet"); 4788 } 4789 4790 void ProcessGDBRemote::ModulesDidLoad(ModuleList &module_list) { 4791 // We must call the lldb_private::Process::ModulesDidLoad () first before we 4792 // do anything 4793 Process::ModulesDidLoad(module_list); 4794 4795 // After loading shared libraries, we can ask our remote GDB server if it 4796 // needs any symbols. 4797 m_gdb_comm.ServeSymbolLookups(this); 4798 } 4799 4800 void ProcessGDBRemote::HandleAsyncStdout(llvm::StringRef out) { 4801 AppendSTDOUT(out.data(), out.size()); 4802 } 4803 4804 static const char *end_delimiter = "--end--;"; 4805 static const int end_delimiter_len = 8; 4806 4807 void ProcessGDBRemote::HandleAsyncMisc(llvm::StringRef data) { 4808 std::string input = data.str(); // '1' to move beyond 'A' 4809 if (m_partial_profile_data.length() > 0) { 4810 m_partial_profile_data.append(input); 4811 input = m_partial_profile_data; 4812 m_partial_profile_data.clear(); 4813 } 4814 4815 size_t found, pos = 0, len = input.length(); 4816 while ((found = input.find(end_delimiter, pos)) != std::string::npos) { 4817 StringExtractorGDBRemote profileDataExtractor( 4818 input.substr(pos, found).c_str()); 4819 std::string profile_data = 4820 HarmonizeThreadIdsForProfileData(profileDataExtractor); 4821 BroadcastAsyncProfileData(profile_data); 4822 4823 pos = found + end_delimiter_len; 4824 } 4825 4826 if (pos < len) { 4827 // Last incomplete chunk. 4828 m_partial_profile_data = input.substr(pos); 4829 } 4830 } 4831 4832 std::string ProcessGDBRemote::HarmonizeThreadIdsForProfileData( 4833 StringExtractorGDBRemote &profileDataExtractor) { 4834 std::map<uint64_t, uint32_t> new_thread_id_to_used_usec_map; 4835 std::string output; 4836 llvm::raw_string_ostream output_stream(output); 4837 llvm::StringRef name, value; 4838 4839 // Going to assuming thread_used_usec comes first, else bail out. 4840 while (profileDataExtractor.GetNameColonValue(name, value)) { 4841 if (name.compare("thread_used_id") == 0) { 4842 StringExtractor threadIDHexExtractor(value); 4843 uint64_t thread_id = threadIDHexExtractor.GetHexMaxU64(false, 0); 4844 4845 bool has_used_usec = false; 4846 uint32_t curr_used_usec = 0; 4847 llvm::StringRef usec_name, usec_value; 4848 uint32_t input_file_pos = profileDataExtractor.GetFilePos(); 4849 if (profileDataExtractor.GetNameColonValue(usec_name, usec_value)) { 4850 if (usec_name.equals("thread_used_usec")) { 4851 has_used_usec = true; 4852 usec_value.getAsInteger(0, curr_used_usec); 4853 } else { 4854 // We didn't find what we want, it is probably an older version. Bail 4855 // out. 4856 profileDataExtractor.SetFilePos(input_file_pos); 4857 } 4858 } 4859 4860 if (has_used_usec) { 4861 uint32_t prev_used_usec = 0; 4862 std::map<uint64_t, uint32_t>::iterator iterator = 4863 m_thread_id_to_used_usec_map.find(thread_id); 4864 if (iterator != m_thread_id_to_used_usec_map.end()) { 4865 prev_used_usec = m_thread_id_to_used_usec_map[thread_id]; 4866 } 4867 4868 uint32_t real_used_usec = curr_used_usec - prev_used_usec; 4869 // A good first time record is one that runs for at least 0.25 sec 4870 bool good_first_time = 4871 (prev_used_usec == 0) && (real_used_usec > 250000); 4872 bool good_subsequent_time = 4873 (prev_used_usec > 0) && 4874 ((real_used_usec > 0) || (HasAssignedIndexIDToThread(thread_id))); 4875 4876 if (good_first_time || good_subsequent_time) { 4877 // We try to avoid doing too many index id reservation, resulting in 4878 // fast increase of index ids. 4879 4880 output_stream << name << ":"; 4881 int32_t index_id = AssignIndexIDToThread(thread_id); 4882 output_stream << index_id << ";"; 4883 4884 output_stream << usec_name << ":" << usec_value << ";"; 4885 } else { 4886 // Skip past 'thread_used_name'. 4887 llvm::StringRef local_name, local_value; 4888 profileDataExtractor.GetNameColonValue(local_name, local_value); 4889 } 4890 4891 // Store current time as previous time so that they can be compared 4892 // later. 4893 new_thread_id_to_used_usec_map[thread_id] = curr_used_usec; 4894 } else { 4895 // Bail out and use old string. 4896 output_stream << name << ":" << value << ";"; 4897 } 4898 } else { 4899 output_stream << name << ":" << value << ";"; 4900 } 4901 } 4902 output_stream << end_delimiter; 4903 m_thread_id_to_used_usec_map = new_thread_id_to_used_usec_map; 4904 4905 return output_stream.str(); 4906 } 4907 4908 void ProcessGDBRemote::HandleStopReply() { 4909 if (GetStopID() != 0) 4910 return; 4911 4912 if (GetID() == LLDB_INVALID_PROCESS_ID) { 4913 lldb::pid_t pid = m_gdb_comm.GetCurrentProcessID(); 4914 if (pid != LLDB_INVALID_PROCESS_ID) 4915 SetID(pid); 4916 } 4917 BuildDynamicRegisterInfo(true); 4918 } 4919 4920 llvm::Expected<bool> ProcessGDBRemote::SaveCore(llvm::StringRef outfile) { 4921 if (!m_gdb_comm.GetSaveCoreSupported()) 4922 return false; 4923 4924 StreamString packet; 4925 packet.PutCString("qSaveCore;path-hint:"); 4926 packet.PutStringAsRawHex8(outfile); 4927 4928 StringExtractorGDBRemote response; 4929 if (m_gdb_comm.SendPacketAndWaitForResponse(packet.GetString(), response) == 4930 GDBRemoteCommunication::PacketResult::Success) { 4931 // TODO: grab error message from the packet? StringExtractor seems to 4932 // be missing a method for that 4933 if (response.IsErrorResponse()) 4934 return llvm::createStringError( 4935 llvm::inconvertibleErrorCode(), 4936 llvm::formatv("qSaveCore returned an error")); 4937 4938 std::string path; 4939 4940 // process the response 4941 for (auto x : llvm::split(response.GetStringRef(), ';')) { 4942 if (x.consume_front("core-path:")) 4943 StringExtractor(x).GetHexByteString(path); 4944 } 4945 4946 // verify that we've gotten what we need 4947 if (path.empty()) 4948 return llvm::createStringError(llvm::inconvertibleErrorCode(), 4949 "qSaveCore returned no core path"); 4950 4951 // now transfer the core file 4952 FileSpec remote_core{llvm::StringRef(path)}; 4953 Platform &platform = *GetTarget().GetPlatform(); 4954 Status error = platform.GetFile(remote_core, FileSpec(outfile)); 4955 4956 if (platform.IsRemote()) { 4957 // NB: we unlink the file on error too 4958 platform.Unlink(remote_core); 4959 if (error.Fail()) 4960 return error.ToError(); 4961 } 4962 4963 return true; 4964 } 4965 4966 return llvm::createStringError(llvm::inconvertibleErrorCode(), 4967 "Unable to send qSaveCore"); 4968 } 4969 4970 static const char *const s_async_json_packet_prefix = "JSON-async:"; 4971 4972 static StructuredData::ObjectSP 4973 ParseStructuredDataPacket(llvm::StringRef packet) { 4974 Log *log = GetLog(GDBRLog::Process); 4975 4976 if (!packet.consume_front(s_async_json_packet_prefix)) { 4977 if (log) { 4978 LLDB_LOGF( 4979 log, 4980 "GDBRemoteCommunicationClientBase::%s() received $J packet " 4981 "but was not a StructuredData packet: packet starts with " 4982 "%s", 4983 __FUNCTION__, 4984 packet.slice(0, strlen(s_async_json_packet_prefix)).str().c_str()); 4985 } 4986 return StructuredData::ObjectSP(); 4987 } 4988 4989 // This is an asynchronous JSON packet, destined for a StructuredDataPlugin. 4990 StructuredData::ObjectSP json_sp = 4991 StructuredData::ParseJSON(std::string(packet)); 4992 if (log) { 4993 if (json_sp) { 4994 StreamString json_str; 4995 json_sp->Dump(json_str, true); 4996 json_str.Flush(); 4997 LLDB_LOGF(log, 4998 "ProcessGDBRemote::%s() " 4999 "received Async StructuredData packet: %s", 5000 __FUNCTION__, json_str.GetData()); 5001 } else { 5002 LLDB_LOGF(log, 5003 "ProcessGDBRemote::%s" 5004 "() received StructuredData packet:" 5005 " parse failure", 5006 __FUNCTION__); 5007 } 5008 } 5009 return json_sp; 5010 } 5011 5012 void ProcessGDBRemote::HandleAsyncStructuredDataPacket(llvm::StringRef data) { 5013 auto structured_data_sp = ParseStructuredDataPacket(data); 5014 if (structured_data_sp) 5015 RouteAsyncStructuredData(structured_data_sp); 5016 } 5017 5018 class CommandObjectProcessGDBRemoteSpeedTest : public CommandObjectParsed { 5019 public: 5020 CommandObjectProcessGDBRemoteSpeedTest(CommandInterpreter &interpreter) 5021 : CommandObjectParsed(interpreter, "process plugin packet speed-test", 5022 "Tests packet speeds of various sizes to determine " 5023 "the performance characteristics of the GDB remote " 5024 "connection. ", 5025 nullptr), 5026 m_option_group(), 5027 m_num_packets(LLDB_OPT_SET_1, false, "count", 'c', 0, eArgTypeCount, 5028 "The number of packets to send of each varying size " 5029 "(default is 1000).", 5030 1000), 5031 m_max_send(LLDB_OPT_SET_1, false, "max-send", 's', 0, eArgTypeCount, 5032 "The maximum number of bytes to send in a packet. Sizes " 5033 "increase in powers of 2 while the size is less than or " 5034 "equal to this option value. (default 1024).", 5035 1024), 5036 m_max_recv(LLDB_OPT_SET_1, false, "max-receive", 'r', 0, eArgTypeCount, 5037 "The maximum number of bytes to receive in a packet. Sizes " 5038 "increase in powers of 2 while the size is less than or " 5039 "equal to this option value. (default 1024).", 5040 1024), 5041 m_json(LLDB_OPT_SET_1, false, "json", 'j', 5042 "Print the output as JSON data for easy parsing.", false, true) { 5043 m_option_group.Append(&m_num_packets, LLDB_OPT_SET_ALL, LLDB_OPT_SET_1); 5044 m_option_group.Append(&m_max_send, LLDB_OPT_SET_ALL, LLDB_OPT_SET_1); 5045 m_option_group.Append(&m_max_recv, LLDB_OPT_SET_ALL, LLDB_OPT_SET_1); 5046 m_option_group.Append(&m_json, LLDB_OPT_SET_ALL, LLDB_OPT_SET_1); 5047 m_option_group.Finalize(); 5048 } 5049 5050 ~CommandObjectProcessGDBRemoteSpeedTest() override = default; 5051 5052 Options *GetOptions() override { return &m_option_group; } 5053 5054 bool DoExecute(Args &command, CommandReturnObject &result) override { 5055 const size_t argc = command.GetArgumentCount(); 5056 if (argc == 0) { 5057 ProcessGDBRemote *process = 5058 (ProcessGDBRemote *)m_interpreter.GetExecutionContext() 5059 .GetProcessPtr(); 5060 if (process) { 5061 StreamSP output_stream_sp( 5062 m_interpreter.GetDebugger().GetAsyncOutputStream()); 5063 result.SetImmediateOutputStream(output_stream_sp); 5064 5065 const uint32_t num_packets = 5066 (uint32_t)m_num_packets.GetOptionValue().GetCurrentValue(); 5067 const uint64_t max_send = m_max_send.GetOptionValue().GetCurrentValue(); 5068 const uint64_t max_recv = m_max_recv.GetOptionValue().GetCurrentValue(); 5069 const bool json = m_json.GetOptionValue().GetCurrentValue(); 5070 const uint64_t k_recv_amount = 5071 4 * 1024 * 1024; // Receive amount in bytes 5072 process->GetGDBRemote().TestPacketSpeed( 5073 num_packets, max_send, max_recv, k_recv_amount, json, 5074 output_stream_sp ? *output_stream_sp : result.GetOutputStream()); 5075 result.SetStatus(eReturnStatusSuccessFinishResult); 5076 return true; 5077 } 5078 } else { 5079 result.AppendErrorWithFormat("'%s' takes no arguments", 5080 m_cmd_name.c_str()); 5081 } 5082 result.SetStatus(eReturnStatusFailed); 5083 return false; 5084 } 5085 5086 protected: 5087 OptionGroupOptions m_option_group; 5088 OptionGroupUInt64 m_num_packets; 5089 OptionGroupUInt64 m_max_send; 5090 OptionGroupUInt64 m_max_recv; 5091 OptionGroupBoolean m_json; 5092 }; 5093 5094 class CommandObjectProcessGDBRemotePacketHistory : public CommandObjectParsed { 5095 private: 5096 public: 5097 CommandObjectProcessGDBRemotePacketHistory(CommandInterpreter &interpreter) 5098 : CommandObjectParsed(interpreter, "process plugin packet history", 5099 "Dumps the packet history buffer. ", nullptr) {} 5100 5101 ~CommandObjectProcessGDBRemotePacketHistory() override = default; 5102 5103 bool DoExecute(Args &command, CommandReturnObject &result) override { 5104 const size_t argc = command.GetArgumentCount(); 5105 if (argc == 0) { 5106 ProcessGDBRemote *process = 5107 (ProcessGDBRemote *)m_interpreter.GetExecutionContext() 5108 .GetProcessPtr(); 5109 if (process) { 5110 process->GetGDBRemote().DumpHistory(result.GetOutputStream()); 5111 result.SetStatus(eReturnStatusSuccessFinishResult); 5112 return true; 5113 } 5114 } else { 5115 result.AppendErrorWithFormat("'%s' takes no arguments", 5116 m_cmd_name.c_str()); 5117 } 5118 result.SetStatus(eReturnStatusFailed); 5119 return false; 5120 } 5121 }; 5122 5123 class CommandObjectProcessGDBRemotePacketXferSize : public CommandObjectParsed { 5124 private: 5125 public: 5126 CommandObjectProcessGDBRemotePacketXferSize(CommandInterpreter &interpreter) 5127 : CommandObjectParsed( 5128 interpreter, "process plugin packet xfer-size", 5129 "Maximum size that lldb will try to read/write one one chunk.", 5130 nullptr) {} 5131 5132 ~CommandObjectProcessGDBRemotePacketXferSize() override = default; 5133 5134 bool DoExecute(Args &command, CommandReturnObject &result) override { 5135 const size_t argc = command.GetArgumentCount(); 5136 if (argc == 0) { 5137 result.AppendErrorWithFormat("'%s' takes an argument to specify the max " 5138 "amount to be transferred when " 5139 "reading/writing", 5140 m_cmd_name.c_str()); 5141 return false; 5142 } 5143 5144 ProcessGDBRemote *process = 5145 (ProcessGDBRemote *)m_interpreter.GetExecutionContext().GetProcessPtr(); 5146 if (process) { 5147 const char *packet_size = command.GetArgumentAtIndex(0); 5148 errno = 0; 5149 uint64_t user_specified_max = strtoul(packet_size, nullptr, 10); 5150 if (errno == 0 && user_specified_max != 0) { 5151 process->SetUserSpecifiedMaxMemoryTransferSize(user_specified_max); 5152 result.SetStatus(eReturnStatusSuccessFinishResult); 5153 return true; 5154 } 5155 } 5156 result.SetStatus(eReturnStatusFailed); 5157 return false; 5158 } 5159 }; 5160 5161 class CommandObjectProcessGDBRemotePacketSend : public CommandObjectParsed { 5162 private: 5163 public: 5164 CommandObjectProcessGDBRemotePacketSend(CommandInterpreter &interpreter) 5165 : CommandObjectParsed(interpreter, "process plugin packet send", 5166 "Send a custom packet through the GDB remote " 5167 "protocol and print the answer. " 5168 "The packet header and footer will automatically " 5169 "be added to the packet prior to sending and " 5170 "stripped from the result.", 5171 nullptr) {} 5172 5173 ~CommandObjectProcessGDBRemotePacketSend() override = default; 5174 5175 bool DoExecute(Args &command, CommandReturnObject &result) override { 5176 const size_t argc = command.GetArgumentCount(); 5177 if (argc == 0) { 5178 result.AppendErrorWithFormat( 5179 "'%s' takes a one or more packet content arguments", 5180 m_cmd_name.c_str()); 5181 return false; 5182 } 5183 5184 ProcessGDBRemote *process = 5185 (ProcessGDBRemote *)m_interpreter.GetExecutionContext().GetProcessPtr(); 5186 if (process) { 5187 for (size_t i = 0; i < argc; ++i) { 5188 const char *packet_cstr = command.GetArgumentAtIndex(0); 5189 StringExtractorGDBRemote response; 5190 process->GetGDBRemote().SendPacketAndWaitForResponse( 5191 packet_cstr, response, process->GetInterruptTimeout()); 5192 result.SetStatus(eReturnStatusSuccessFinishResult); 5193 Stream &output_strm = result.GetOutputStream(); 5194 output_strm.Printf(" packet: %s\n", packet_cstr); 5195 std::string response_str = std::string(response.GetStringRef()); 5196 5197 if (strstr(packet_cstr, "qGetProfileData") != nullptr) { 5198 response_str = process->HarmonizeThreadIdsForProfileData(response); 5199 } 5200 5201 if (response_str.empty()) 5202 output_strm.PutCString("response: \nerror: UNIMPLEMENTED\n"); 5203 else 5204 output_strm.Printf("response: %s\n", response.GetStringRef().data()); 5205 } 5206 } 5207 return true; 5208 } 5209 }; 5210 5211 class CommandObjectProcessGDBRemotePacketMonitor : public CommandObjectRaw { 5212 private: 5213 public: 5214 CommandObjectProcessGDBRemotePacketMonitor(CommandInterpreter &interpreter) 5215 : CommandObjectRaw(interpreter, "process plugin packet monitor", 5216 "Send a qRcmd packet through the GDB remote protocol " 5217 "and print the response." 5218 "The argument passed to this command will be hex " 5219 "encoded into a valid 'qRcmd' packet, sent and the " 5220 "response will be printed.") {} 5221 5222 ~CommandObjectProcessGDBRemotePacketMonitor() override = default; 5223 5224 bool DoExecute(llvm::StringRef command, 5225 CommandReturnObject &result) override { 5226 if (command.empty()) { 5227 result.AppendErrorWithFormat("'%s' takes a command string argument", 5228 m_cmd_name.c_str()); 5229 return false; 5230 } 5231 5232 ProcessGDBRemote *process = 5233 (ProcessGDBRemote *)m_interpreter.GetExecutionContext().GetProcessPtr(); 5234 if (process) { 5235 StreamString packet; 5236 packet.PutCString("qRcmd,"); 5237 packet.PutBytesAsRawHex8(command.data(), command.size()); 5238 5239 StringExtractorGDBRemote response; 5240 Stream &output_strm = result.GetOutputStream(); 5241 process->GetGDBRemote().SendPacketAndReceiveResponseWithOutputSupport( 5242 packet.GetString(), response, process->GetInterruptTimeout(), 5243 [&output_strm](llvm::StringRef output) { output_strm << output; }); 5244 result.SetStatus(eReturnStatusSuccessFinishResult); 5245 output_strm.Printf(" packet: %s\n", packet.GetData()); 5246 const std::string &response_str = std::string(response.GetStringRef()); 5247 5248 if (response_str.empty()) 5249 output_strm.PutCString("response: \nerror: UNIMPLEMENTED\n"); 5250 else 5251 output_strm.Printf("response: %s\n", response.GetStringRef().data()); 5252 } 5253 return true; 5254 } 5255 }; 5256 5257 class CommandObjectProcessGDBRemotePacket : public CommandObjectMultiword { 5258 private: 5259 public: 5260 CommandObjectProcessGDBRemotePacket(CommandInterpreter &interpreter) 5261 : CommandObjectMultiword(interpreter, "process plugin packet", 5262 "Commands that deal with GDB remote packets.", 5263 nullptr) { 5264 LoadSubCommand( 5265 "history", 5266 CommandObjectSP( 5267 new CommandObjectProcessGDBRemotePacketHistory(interpreter))); 5268 LoadSubCommand( 5269 "send", CommandObjectSP( 5270 new CommandObjectProcessGDBRemotePacketSend(interpreter))); 5271 LoadSubCommand( 5272 "monitor", 5273 CommandObjectSP( 5274 new CommandObjectProcessGDBRemotePacketMonitor(interpreter))); 5275 LoadSubCommand( 5276 "xfer-size", 5277 CommandObjectSP( 5278 new CommandObjectProcessGDBRemotePacketXferSize(interpreter))); 5279 LoadSubCommand("speed-test", 5280 CommandObjectSP(new CommandObjectProcessGDBRemoteSpeedTest( 5281 interpreter))); 5282 } 5283 5284 ~CommandObjectProcessGDBRemotePacket() override = default; 5285 }; 5286 5287 class CommandObjectMultiwordProcessGDBRemote : public CommandObjectMultiword { 5288 public: 5289 CommandObjectMultiwordProcessGDBRemote(CommandInterpreter &interpreter) 5290 : CommandObjectMultiword( 5291 interpreter, "process plugin", 5292 "Commands for operating on a ProcessGDBRemote process.", 5293 "process plugin <subcommand> [<subcommand-options>]") { 5294 LoadSubCommand( 5295 "packet", 5296 CommandObjectSP(new CommandObjectProcessGDBRemotePacket(interpreter))); 5297 } 5298 5299 ~CommandObjectMultiwordProcessGDBRemote() override = default; 5300 }; 5301 5302 CommandObject *ProcessGDBRemote::GetPluginCommandObject() { 5303 if (!m_command_sp) 5304 m_command_sp = std::make_shared<CommandObjectMultiwordProcessGDBRemote>( 5305 GetTarget().GetDebugger().GetCommandInterpreter()); 5306 return m_command_sp.get(); 5307 } 5308 5309 void ProcessGDBRemote::DidForkSwitchSoftwareBreakpoints(bool enable) { 5310 GetBreakpointSiteList().ForEach([this, enable](BreakpointSite *bp_site) { 5311 if (bp_site->IsEnabled() && 5312 (bp_site->GetType() == BreakpointSite::eSoftware || 5313 bp_site->GetType() == BreakpointSite::eExternal)) { 5314 m_gdb_comm.SendGDBStoppointTypePacket( 5315 eBreakpointSoftware, enable, bp_site->GetLoadAddress(), 5316 GetSoftwareBreakpointTrapOpcode(bp_site), GetInterruptTimeout()); 5317 } 5318 }); 5319 } 5320 5321 void ProcessGDBRemote::DidForkSwitchHardwareTraps(bool enable) { 5322 if (m_gdb_comm.SupportsGDBStoppointPacket(eBreakpointHardware)) { 5323 GetBreakpointSiteList().ForEach([this, enable](BreakpointSite *bp_site) { 5324 if (bp_site->IsEnabled() && 5325 bp_site->GetType() == BreakpointSite::eHardware) { 5326 m_gdb_comm.SendGDBStoppointTypePacket( 5327 eBreakpointHardware, enable, bp_site->GetLoadAddress(), 5328 GetSoftwareBreakpointTrapOpcode(bp_site), GetInterruptTimeout()); 5329 } 5330 }); 5331 } 5332 5333 WatchpointList &wps = GetTarget().GetWatchpointList(); 5334 size_t wp_count = wps.GetSize(); 5335 for (size_t i = 0; i < wp_count; ++i) { 5336 WatchpointSP wp = wps.GetByIndex(i); 5337 if (wp->IsEnabled()) { 5338 GDBStoppointType type = GetGDBStoppointType(wp.get()); 5339 m_gdb_comm.SendGDBStoppointTypePacket(type, enable, wp->GetLoadAddress(), 5340 wp->GetByteSize(), 5341 GetInterruptTimeout()); 5342 } 5343 } 5344 } 5345 5346 void ProcessGDBRemote::DidFork(lldb::pid_t child_pid, lldb::tid_t child_tid) { 5347 Log *log = GetLog(GDBRLog::Process); 5348 5349 lldb::pid_t parent_pid = m_gdb_comm.GetCurrentProcessID(); 5350 // Any valid TID will suffice, thread-relevant actions will set a proper TID 5351 // anyway. 5352 lldb::tid_t parent_tid = m_thread_ids.front(); 5353 5354 lldb::pid_t follow_pid, detach_pid; 5355 lldb::tid_t follow_tid, detach_tid; 5356 5357 switch (GetFollowForkMode()) { 5358 case eFollowParent: 5359 follow_pid = parent_pid; 5360 follow_tid = parent_tid; 5361 detach_pid = child_pid; 5362 detach_tid = child_tid; 5363 break; 5364 case eFollowChild: 5365 follow_pid = child_pid; 5366 follow_tid = child_tid; 5367 detach_pid = parent_pid; 5368 detach_tid = parent_tid; 5369 break; 5370 } 5371 5372 // Switch to the process that is going to be detached. 5373 if (!m_gdb_comm.SetCurrentThread(detach_tid, detach_pid)) { 5374 LLDB_LOG(log, "ProcessGDBRemote::DidFork() unable to set pid/tid"); 5375 return; 5376 } 5377 5378 // Disable all software breakpoints in the forked process. 5379 if (m_gdb_comm.SupportsGDBStoppointPacket(eBreakpointSoftware)) 5380 DidForkSwitchSoftwareBreakpoints(false); 5381 5382 // Remove hardware breakpoints / watchpoints from parent process if we're 5383 // following child. 5384 if (GetFollowForkMode() == eFollowChild) 5385 DidForkSwitchHardwareTraps(false); 5386 5387 // Switch to the process that is going to be followed 5388 if (!m_gdb_comm.SetCurrentThread(follow_tid, follow_pid) || 5389 !m_gdb_comm.SetCurrentThreadForRun(follow_tid, follow_pid)) { 5390 LLDB_LOG(log, "ProcessGDBRemote::DidFork() unable to reset pid/tid"); 5391 return; 5392 } 5393 5394 LLDB_LOG(log, "Detaching process {0}", detach_pid); 5395 Status error = m_gdb_comm.Detach(false, detach_pid); 5396 if (error.Fail()) { 5397 LLDB_LOG(log, "ProcessGDBRemote::DidFork() detach packet send failed: {0}", 5398 error.AsCString() ? error.AsCString() : "<unknown error>"); 5399 return; 5400 } 5401 5402 // Hardware breakpoints/watchpoints are not inherited implicitly, 5403 // so we need to readd them if we're following child. 5404 if (GetFollowForkMode() == eFollowChild) 5405 DidForkSwitchHardwareTraps(true); 5406 } 5407 5408 void ProcessGDBRemote::DidVFork(lldb::pid_t child_pid, lldb::tid_t child_tid) { 5409 Log *log = GetLog(GDBRLog::Process); 5410 5411 assert(!m_vfork_in_progress); 5412 m_vfork_in_progress = true; 5413 5414 // Disable all software breakpoints for the duration of vfork. 5415 if (m_gdb_comm.SupportsGDBStoppointPacket(eBreakpointSoftware)) 5416 DidForkSwitchSoftwareBreakpoints(false); 5417 5418 lldb::pid_t detach_pid; 5419 lldb::tid_t detach_tid; 5420 5421 switch (GetFollowForkMode()) { 5422 case eFollowParent: 5423 detach_pid = child_pid; 5424 detach_tid = child_tid; 5425 break; 5426 case eFollowChild: 5427 detach_pid = m_gdb_comm.GetCurrentProcessID(); 5428 // Any valid TID will suffice, thread-relevant actions will set a proper TID 5429 // anyway. 5430 detach_tid = m_thread_ids.front(); 5431 5432 // Switch to the parent process before detaching it. 5433 if (!m_gdb_comm.SetCurrentThread(detach_tid, detach_pid)) { 5434 LLDB_LOG(log, "ProcessGDBRemote::DidFork() unable to set pid/tid"); 5435 return; 5436 } 5437 5438 // Remove hardware breakpoints / watchpoints from the parent process. 5439 DidForkSwitchHardwareTraps(false); 5440 5441 // Switch to the child process. 5442 if (!m_gdb_comm.SetCurrentThread(child_tid, child_pid) || 5443 !m_gdb_comm.SetCurrentThreadForRun(child_tid, child_pid)) { 5444 LLDB_LOG(log, "ProcessGDBRemote::DidFork() unable to reset pid/tid"); 5445 return; 5446 } 5447 break; 5448 } 5449 5450 LLDB_LOG(log, "Detaching process {0}", detach_pid); 5451 Status error = m_gdb_comm.Detach(false, detach_pid); 5452 if (error.Fail()) { 5453 LLDB_LOG(log, 5454 "ProcessGDBRemote::DidFork() detach packet send failed: {0}", 5455 error.AsCString() ? error.AsCString() : "<unknown error>"); 5456 return; 5457 } 5458 } 5459 5460 void ProcessGDBRemote::DidVForkDone() { 5461 assert(m_vfork_in_progress); 5462 m_vfork_in_progress = false; 5463 5464 // Reenable all software breakpoints that were enabled before vfork. 5465 if (m_gdb_comm.SupportsGDBStoppointPacket(eBreakpointSoftware)) 5466 DidForkSwitchSoftwareBreakpoints(true); 5467 } 5468 5469 void ProcessGDBRemote::DidExec() { 5470 // If we are following children, vfork is finished by exec (rather than 5471 // vforkdone that is submitted for parent). 5472 if (GetFollowForkMode() == eFollowChild) 5473 m_vfork_in_progress = false; 5474 Process::DidExec(); 5475 } 5476