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