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