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