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