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