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