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