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