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