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