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