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