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