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