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 1491 ProcessGDBRemote::UpdateThreadIDsFromStopReplyThreadsValue(std::string &value) { 1492 m_thread_ids.clear(); 1493 size_t comma_pos; 1494 lldb::tid_t tid; 1495 while ((comma_pos = value.find(',')) != std::string::npos) { 1496 value[comma_pos] = '\0'; 1497 // thread in big endian hex 1498 tid = StringConvert::ToUInt64(value.c_str(), LLDB_INVALID_THREAD_ID, 16); 1499 if (tid != LLDB_INVALID_THREAD_ID) 1500 m_thread_ids.push_back(tid); 1501 value.erase(0, comma_pos + 1); 1502 } 1503 tid = StringConvert::ToUInt64(value.c_str(), LLDB_INVALID_THREAD_ID, 16); 1504 if (tid != LLDB_INVALID_THREAD_ID) 1505 m_thread_ids.push_back(tid); 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_THREAD_ID) 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 stop_packet.SetFilePos(0); 2145 const char stop_type = stop_packet.GetChar(); 2146 switch (stop_type) { 2147 case 'T': 2148 case 'S': { 2149 // This is a bit of a hack, but is is required. If we did exec, we need to 2150 // clear our thread lists and also know to rebuild our dynamic register 2151 // info before we lookup and threads and populate the expedited register 2152 // values so we need to know this right away so we can cleanup and update 2153 // our registers. 2154 const uint32_t stop_id = GetStopID(); 2155 if (stop_id == 0) { 2156 // Our first stop, make sure we have a process ID, and also make sure we 2157 // know about our registers 2158 if (GetID() == LLDB_INVALID_PROCESS_ID) { 2159 lldb::pid_t pid = m_gdb_comm.GetCurrentProcessID(); 2160 if (pid != LLDB_INVALID_PROCESS_ID) 2161 SetID(pid); 2162 } 2163 BuildDynamicRegisterInfo(true); 2164 } 2165 // Stop with signal and thread info 2166 lldb::tid_t tid = LLDB_INVALID_THREAD_ID; 2167 const uint8_t signo = stop_packet.GetHexU8(); 2168 llvm::StringRef key; 2169 llvm::StringRef value; 2170 std::string thread_name; 2171 std::string reason; 2172 std::string description; 2173 uint32_t exc_type = 0; 2174 std::vector<addr_t> exc_data; 2175 addr_t thread_dispatch_qaddr = LLDB_INVALID_ADDRESS; 2176 bool queue_vars_valid = 2177 false; // says if locals below that start with "queue_" are valid 2178 addr_t dispatch_queue_t = LLDB_INVALID_ADDRESS; 2179 LazyBool associated_with_dispatch_queue = eLazyBoolCalculate; 2180 std::string queue_name; 2181 QueueKind queue_kind = eQueueKindUnknown; 2182 uint64_t queue_serial_number = 0; 2183 ExpeditedRegisterMap expedited_register_map; 2184 while (stop_packet.GetNameColonValue(key, value)) { 2185 if (key.compare("metype") == 0) { 2186 // exception type in big endian hex 2187 value.getAsInteger(16, exc_type); 2188 } else if (key.compare("medata") == 0) { 2189 // exception data in big endian hex 2190 uint64_t x; 2191 value.getAsInteger(16, x); 2192 exc_data.push_back(x); 2193 } else if (key.compare("thread") == 0) { 2194 // thread in big endian hex 2195 if (value.getAsInteger(16, tid)) 2196 tid = LLDB_INVALID_THREAD_ID; 2197 } else if (key.compare("threads") == 0) { 2198 std::lock_guard<std::recursive_mutex> guard( 2199 m_thread_list_real.GetMutex()); 2200 2201 m_thread_ids.clear(); 2202 // A comma separated list of all threads in the current 2203 // process that includes the thread for this stop reply packet 2204 lldb::tid_t tid; 2205 while (!value.empty()) { 2206 llvm::StringRef tid_str; 2207 std::tie(tid_str, value) = value.split(','); 2208 if (tid_str.getAsInteger(16, tid)) 2209 tid = LLDB_INVALID_THREAD_ID; 2210 m_thread_ids.push_back(tid); 2211 } 2212 } else if (key.compare("thread-pcs") == 0) { 2213 m_thread_pcs.clear(); 2214 // A comma separated list of all threads in the current 2215 // process that includes the thread for this stop reply packet 2216 lldb::addr_t pc; 2217 while (!value.empty()) { 2218 llvm::StringRef pc_str; 2219 std::tie(pc_str, value) = value.split(','); 2220 if (pc_str.getAsInteger(16, pc)) 2221 pc = LLDB_INVALID_ADDRESS; 2222 m_thread_pcs.push_back(pc); 2223 } 2224 } else if (key.compare("jstopinfo") == 0) { 2225 StringExtractor json_extractor(value); 2226 std::string json; 2227 // Now convert the HEX bytes into a string value 2228 json_extractor.GetHexByteString(json); 2229 2230 // This JSON contains thread IDs and thread stop info for all threads. 2231 // It doesn't contain expedited registers, memory or queue info. 2232 m_jstopinfo_sp = StructuredData::ParseJSON(json); 2233 } else if (key.compare("hexname") == 0) { 2234 StringExtractor name_extractor(value); 2235 std::string name; 2236 // Now convert the HEX bytes into a string value 2237 name_extractor.GetHexByteString(thread_name); 2238 } else if (key.compare("name") == 0) { 2239 thread_name = std::string(value); 2240 } else if (key.compare("qaddr") == 0) { 2241 value.getAsInteger(16, thread_dispatch_qaddr); 2242 } else if (key.compare("dispatch_queue_t") == 0) { 2243 queue_vars_valid = true; 2244 value.getAsInteger(16, dispatch_queue_t); 2245 } else if (key.compare("qname") == 0) { 2246 queue_vars_valid = true; 2247 StringExtractor name_extractor(value); 2248 // Now convert the HEX bytes into a string value 2249 name_extractor.GetHexByteString(queue_name); 2250 } else if (key.compare("qkind") == 0) { 2251 queue_kind = llvm::StringSwitch<QueueKind>(value) 2252 .Case("serial", eQueueKindSerial) 2253 .Case("concurrent", eQueueKindConcurrent) 2254 .Default(eQueueKindUnknown); 2255 queue_vars_valid = queue_kind != eQueueKindUnknown; 2256 } else if (key.compare("qserialnum") == 0) { 2257 if (!value.getAsInteger(0, queue_serial_number)) 2258 queue_vars_valid = true; 2259 } else if (key.compare("reason") == 0) { 2260 reason = std::string(value); 2261 } else if (key.compare("description") == 0) { 2262 StringExtractor desc_extractor(value); 2263 // Now convert the HEX bytes into a string value 2264 desc_extractor.GetHexByteString(description); 2265 } else if (key.compare("memory") == 0) { 2266 // Expedited memory. GDB servers can choose to send back expedited 2267 // memory that can populate the L1 memory cache in the process so that 2268 // things like the frame pointer backchain can be expedited. This will 2269 // help stack backtracing be more efficient by not having to send as 2270 // many memory read requests down the remote GDB server. 2271 2272 // Key/value pair format: memory:<addr>=<bytes>; 2273 // <addr> is a number whose base will be interpreted by the prefix: 2274 // "0x[0-9a-fA-F]+" for hex 2275 // "0[0-7]+" for octal 2276 // "[1-9]+" for decimal 2277 // <bytes> is native endian ASCII hex bytes just like the register 2278 // values 2279 llvm::StringRef addr_str, bytes_str; 2280 std::tie(addr_str, bytes_str) = value.split('='); 2281 if (!addr_str.empty() && !bytes_str.empty()) { 2282 lldb::addr_t mem_cache_addr = LLDB_INVALID_ADDRESS; 2283 if (!addr_str.getAsInteger(0, mem_cache_addr)) { 2284 StringExtractor bytes(bytes_str); 2285 const size_t byte_size = bytes.GetBytesLeft() / 2; 2286 DataBufferSP data_buffer_sp(new DataBufferHeap(byte_size, 0)); 2287 const size_t bytes_copied = 2288 bytes.GetHexBytes(data_buffer_sp->GetData(), 0); 2289 if (bytes_copied == byte_size) 2290 m_memory_cache.AddL1CacheData(mem_cache_addr, data_buffer_sp); 2291 } 2292 } 2293 } else if (key.compare("watch") == 0 || key.compare("rwatch") == 0 || 2294 key.compare("awatch") == 0) { 2295 // Support standard GDB remote stop reply packet 'TAAwatch:addr' 2296 lldb::addr_t wp_addr = LLDB_INVALID_ADDRESS; 2297 value.getAsInteger(16, wp_addr); 2298 2299 WatchpointSP wp_sp = 2300 GetTarget().GetWatchpointList().FindByAddress(wp_addr); 2301 uint32_t wp_index = LLDB_INVALID_INDEX32; 2302 2303 if (wp_sp) 2304 wp_index = wp_sp->GetHardwareIndex(); 2305 2306 reason = "watchpoint"; 2307 StreamString ostr; 2308 ostr.Printf("%" PRIu64 " %" PRIu32, wp_addr, wp_index); 2309 description = std::string(ostr.GetString()); 2310 } else if (key.compare("library") == 0) { 2311 auto error = LoadModules(); 2312 if (error) { 2313 Log *log( 2314 ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS)); 2315 LLDB_LOG_ERROR(log, std::move(error), "Failed to load modules: {0}"); 2316 } 2317 } else if (key.size() == 2 && ::isxdigit(key[0]) && ::isxdigit(key[1])) { 2318 uint32_t reg = UINT32_MAX; 2319 if (!key.getAsInteger(16, reg)) 2320 expedited_register_map[reg] = std::string(std::move(value)); 2321 } 2322 } 2323 2324 if (tid == LLDB_INVALID_THREAD_ID) { 2325 // A thread id may be invalid if the response is old style 'S' packet 2326 // which does not provide the 2327 // thread information. So update the thread list and choose the first 2328 // one. 2329 UpdateThreadIDList(); 2330 2331 if (!m_thread_ids.empty()) { 2332 tid = m_thread_ids.front(); 2333 } 2334 } 2335 2336 ThreadSP thread_sp = SetThreadStopInfo( 2337 tid, expedited_register_map, signo, thread_name, reason, description, 2338 exc_type, exc_data, thread_dispatch_qaddr, queue_vars_valid, 2339 associated_with_dispatch_queue, dispatch_queue_t, queue_name, 2340 queue_kind, queue_serial_number); 2341 2342 return eStateStopped; 2343 } break; 2344 2345 case 'W': 2346 case 'X': 2347 // process exited 2348 return eStateExited; 2349 2350 default: 2351 break; 2352 } 2353 return eStateInvalid; 2354 } 2355 2356 void ProcessGDBRemote::RefreshStateAfterStop() { 2357 std::lock_guard<std::recursive_mutex> guard(m_thread_list_real.GetMutex()); 2358 2359 m_thread_ids.clear(); 2360 m_thread_pcs.clear(); 2361 2362 // Set the thread stop info. It might have a "threads" key whose value is a 2363 // list of all thread IDs in the current process, so m_thread_ids might get 2364 // set. 2365 // Check to see if SetThreadStopInfo() filled in m_thread_ids? 2366 if (m_thread_ids.empty()) { 2367 // No, we need to fetch the thread list manually 2368 UpdateThreadIDList(); 2369 } 2370 2371 // We might set some stop info's so make sure the thread list is up to 2372 // date before we do that or we might overwrite what was computed here. 2373 UpdateThreadListIfNeeded(); 2374 2375 // Scope for the lock 2376 { 2377 // Lock the thread stack while we access it 2378 std::lock_guard<std::recursive_mutex> guard(m_last_stop_packet_mutex); 2379 // Get the number of stop packets on the stack 2380 int nItems = m_stop_packet_stack.size(); 2381 // Iterate over them 2382 for (int i = 0; i < nItems; i++) { 2383 // Get the thread stop info 2384 StringExtractorGDBRemote stop_info = m_stop_packet_stack[i]; 2385 // Process thread stop info 2386 SetThreadStopInfo(stop_info); 2387 } 2388 // Clear the thread stop stack 2389 m_stop_packet_stack.clear(); 2390 } 2391 2392 // If we have queried for a default thread id 2393 if (m_initial_tid != LLDB_INVALID_THREAD_ID) { 2394 m_thread_list.SetSelectedThreadByID(m_initial_tid); 2395 m_initial_tid = LLDB_INVALID_THREAD_ID; 2396 } 2397 2398 // Let all threads recover from stopping and do any clean up based on the 2399 // previous thread state (if any). 2400 m_thread_list_real.RefreshStateAfterStop(); 2401 } 2402 2403 Status ProcessGDBRemote::DoHalt(bool &caused_stop) { 2404 Status error; 2405 2406 if (m_public_state.GetValue() == eStateAttaching) { 2407 // We are being asked to halt during an attach. We need to just close our 2408 // file handle and debugserver will go away, and we can be done... 2409 m_gdb_comm.Disconnect(); 2410 } else 2411 caused_stop = m_gdb_comm.Interrupt(); 2412 return error; 2413 } 2414 2415 Status ProcessGDBRemote::DoDetach(bool keep_stopped) { 2416 Status error; 2417 Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS)); 2418 LLDB_LOGF(log, "ProcessGDBRemote::DoDetach(keep_stopped: %i)", keep_stopped); 2419 2420 error = m_gdb_comm.Detach(keep_stopped); 2421 if (log) { 2422 if (error.Success()) 2423 log->PutCString( 2424 "ProcessGDBRemote::DoDetach() detach packet sent successfully"); 2425 else 2426 LLDB_LOGF(log, 2427 "ProcessGDBRemote::DoDetach() detach packet send failed: %s", 2428 error.AsCString() ? error.AsCString() : "<unknown error>"); 2429 } 2430 2431 if (!error.Success()) 2432 return error; 2433 2434 // Sleep for one second to let the process get all detached... 2435 StopAsyncThread(); 2436 2437 SetPrivateState(eStateDetached); 2438 ResumePrivateStateThread(); 2439 2440 // KillDebugserverProcess (); 2441 return error; 2442 } 2443 2444 Status ProcessGDBRemote::DoDestroy() { 2445 Status error; 2446 Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS)); 2447 LLDB_LOGF(log, "ProcessGDBRemote::DoDestroy()"); 2448 2449 // There is a bug in older iOS debugservers where they don't shut down the 2450 // process they are debugging properly. If the process is sitting at a 2451 // breakpoint or an exception, this can cause problems with restarting. So 2452 // we check to see if any of our threads are stopped at a breakpoint, and if 2453 // so we remove all the breakpoints, resume the process, and THEN destroy it 2454 // again. 2455 // 2456 // Note, we don't have a good way to test the version of debugserver, but I 2457 // happen to know that the set of all the iOS debugservers which don't 2458 // support GetThreadSuffixSupported() and that of the debugservers with this 2459 // bug are equal. There really should be a better way to test this! 2460 // 2461 // We also use m_destroy_tried_resuming to make sure we only do this once, if 2462 // we resume and then halt and get called here to destroy again and we're 2463 // still at a breakpoint or exception, then we should just do the straight- 2464 // forward kill. 2465 // 2466 // And of course, if we weren't able to stop the process by the time we get 2467 // here, it isn't necessary (or helpful) to do any of this. 2468 2469 if (!m_gdb_comm.GetThreadSuffixSupported() && 2470 m_public_state.GetValue() != eStateRunning) { 2471 PlatformSP platform_sp = GetTarget().GetPlatform(); 2472 2473 // FIXME: These should be ConstStrings so we aren't doing strcmp'ing. 2474 if (platform_sp && platform_sp->GetName() && 2475 platform_sp->GetName() == PlatformRemoteiOS::GetPluginNameStatic()) { 2476 if (m_destroy_tried_resuming) { 2477 if (log) 2478 log->PutCString("ProcessGDBRemote::DoDestroy() - Tried resuming to " 2479 "destroy once already, not doing it again."); 2480 } else { 2481 // At present, the plans are discarded and the breakpoints disabled 2482 // Process::Destroy, but we really need it to happen here and it 2483 // doesn't matter if we do it twice. 2484 m_thread_list.DiscardThreadPlans(); 2485 DisableAllBreakpointSites(); 2486 2487 bool stop_looks_like_crash = false; 2488 ThreadList &threads = GetThreadList(); 2489 2490 { 2491 std::lock_guard<std::recursive_mutex> guard(threads.GetMutex()); 2492 2493 size_t num_threads = threads.GetSize(); 2494 for (size_t i = 0; i < num_threads; i++) { 2495 ThreadSP thread_sp = threads.GetThreadAtIndex(i); 2496 StopInfoSP stop_info_sp = thread_sp->GetPrivateStopInfo(); 2497 StopReason reason = eStopReasonInvalid; 2498 if (stop_info_sp) 2499 reason = stop_info_sp->GetStopReason(); 2500 if (reason == eStopReasonBreakpoint || 2501 reason == eStopReasonException) { 2502 LLDB_LOGF(log, 2503 "ProcessGDBRemote::DoDestroy() - thread: 0x%4.4" PRIx64 2504 " stopped with reason: %s.", 2505 thread_sp->GetProtocolID(), 2506 stop_info_sp->GetDescription()); 2507 stop_looks_like_crash = true; 2508 break; 2509 } 2510 } 2511 } 2512 2513 if (stop_looks_like_crash) { 2514 if (log) 2515 log->PutCString("ProcessGDBRemote::DoDestroy() - Stopped at a " 2516 "breakpoint, continue and then kill."); 2517 m_destroy_tried_resuming = true; 2518 2519 // If we are going to run again before killing, it would be good to 2520 // suspend all the threads before resuming so they won't get into 2521 // more trouble. Sadly, for the threads stopped with the breakpoint 2522 // or exception, the exception doesn't get cleared if it is 2523 // suspended, so we do have to run the risk of letting those threads 2524 // proceed a bit. 2525 2526 { 2527 std::lock_guard<std::recursive_mutex> guard(threads.GetMutex()); 2528 2529 size_t num_threads = threads.GetSize(); 2530 for (size_t i = 0; i < num_threads; i++) { 2531 ThreadSP thread_sp = threads.GetThreadAtIndex(i); 2532 StopInfoSP stop_info_sp = thread_sp->GetPrivateStopInfo(); 2533 StopReason reason = eStopReasonInvalid; 2534 if (stop_info_sp) 2535 reason = stop_info_sp->GetStopReason(); 2536 if (reason != eStopReasonBreakpoint && 2537 reason != eStopReasonException) { 2538 LLDB_LOGF(log, 2539 "ProcessGDBRemote::DoDestroy() - Suspending " 2540 "thread: 0x%4.4" PRIx64 " before running.", 2541 thread_sp->GetProtocolID()); 2542 thread_sp->SetResumeState(eStateSuspended); 2543 } 2544 } 2545 } 2546 Resume(); 2547 return Destroy(false); 2548 } 2549 } 2550 } 2551 } 2552 2553 // Interrupt if our inferior is running... 2554 int exit_status = SIGABRT; 2555 std::string exit_string; 2556 2557 if (m_gdb_comm.IsConnected()) { 2558 if (m_public_state.GetValue() != eStateAttaching) { 2559 StringExtractorGDBRemote response; 2560 bool send_async = true; 2561 GDBRemoteCommunication::ScopedTimeout(m_gdb_comm, 2562 std::chrono::seconds(3)); 2563 2564 if (m_gdb_comm.SendPacketAndWaitForResponse("k", response, send_async) == 2565 GDBRemoteCommunication::PacketResult::Success) { 2566 char packet_cmd = response.GetChar(0); 2567 2568 if (packet_cmd == 'W' || packet_cmd == 'X') { 2569 #if defined(__APPLE__) 2570 // For Native processes on Mac OS X, we launch through the Host 2571 // Platform, then hand the process off to debugserver, which becomes 2572 // the parent process through "PT_ATTACH". Then when we go to kill 2573 // the process on Mac OS X we call ptrace(PT_KILL) to kill it, then 2574 // we call waitpid which returns with no error and the correct 2575 // status. But amusingly enough that doesn't seem to actually reap 2576 // the process, but instead it is left around as a Zombie. Probably 2577 // the kernel is in the process of switching ownership back to lldb 2578 // which was the original parent, and gets confused in the handoff. 2579 // Anyway, so call waitpid here to finally reap it. 2580 PlatformSP platform_sp(GetTarget().GetPlatform()); 2581 if (platform_sp && platform_sp->IsHost()) { 2582 int status; 2583 ::pid_t reap_pid; 2584 reap_pid = waitpid(GetID(), &status, WNOHANG); 2585 LLDB_LOGF(log, "Reaped pid: %d, status: %d.\n", reap_pid, status); 2586 } 2587 #endif 2588 SetLastStopPacket(response); 2589 ClearThreadIDList(); 2590 exit_status = response.GetHexU8(); 2591 } else { 2592 LLDB_LOGF(log, 2593 "ProcessGDBRemote::DoDestroy - got unexpected response " 2594 "to k packet: %s", 2595 response.GetStringRef().data()); 2596 exit_string.assign("got unexpected response to k packet: "); 2597 exit_string.append(std::string(response.GetStringRef())); 2598 } 2599 } else { 2600 LLDB_LOGF(log, "ProcessGDBRemote::DoDestroy - failed to send k packet"); 2601 exit_string.assign("failed to send the k packet"); 2602 } 2603 } else { 2604 LLDB_LOGF(log, 2605 "ProcessGDBRemote::DoDestroy - killed or interrupted while " 2606 "attaching"); 2607 exit_string.assign("killed or interrupted while attaching."); 2608 } 2609 } else { 2610 // If we missed setting the exit status on the way out, do it here. 2611 // NB set exit status can be called multiple times, the first one sets the 2612 // status. 2613 exit_string.assign("destroying when not connected to debugserver"); 2614 } 2615 2616 SetExitStatus(exit_status, exit_string.c_str()); 2617 2618 StopAsyncThread(); 2619 KillDebugserverProcess(); 2620 return error; 2621 } 2622 2623 void ProcessGDBRemote::SetLastStopPacket( 2624 const StringExtractorGDBRemote &response) { 2625 const bool did_exec = 2626 response.GetStringRef().find(";reason:exec;") != std::string::npos; 2627 if (did_exec) { 2628 Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS)); 2629 LLDB_LOGF(log, "ProcessGDBRemote::SetLastStopPacket () - detected exec"); 2630 2631 m_thread_list_real.Clear(); 2632 m_thread_list.Clear(); 2633 BuildDynamicRegisterInfo(true); 2634 m_gdb_comm.ResetDiscoverableSettings(did_exec); 2635 } 2636 2637 // Scope the lock 2638 { 2639 // Lock the thread stack while we access it 2640 std::lock_guard<std::recursive_mutex> guard(m_last_stop_packet_mutex); 2641 2642 // We are are not using non-stop mode, there can only be one last stop 2643 // reply packet, so clear the list. 2644 if (!GetTarget().GetNonStopModeEnabled()) 2645 m_stop_packet_stack.clear(); 2646 2647 // Add this stop packet to the stop packet stack This stack will get popped 2648 // and examined when we switch to the Stopped state 2649 m_stop_packet_stack.push_back(response); 2650 } 2651 } 2652 2653 void ProcessGDBRemote::SetUnixSignals(const UnixSignalsSP &signals_sp) { 2654 Process::SetUnixSignals(std::make_shared<GDBRemoteSignals>(signals_sp)); 2655 } 2656 2657 // Process Queries 2658 2659 bool ProcessGDBRemote::IsAlive() { 2660 return m_gdb_comm.IsConnected() && Process::IsAlive(); 2661 } 2662 2663 addr_t ProcessGDBRemote::GetImageInfoAddress() { 2664 // request the link map address via the $qShlibInfoAddr packet 2665 lldb::addr_t addr = m_gdb_comm.GetShlibInfoAddr(); 2666 2667 // the loaded module list can also provides a link map address 2668 if (addr == LLDB_INVALID_ADDRESS) { 2669 llvm::Expected<LoadedModuleInfoList> list = GetLoadedModuleList(); 2670 if (!list) { 2671 Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS)); 2672 LLDB_LOG_ERROR(log, list.takeError(), "Failed to read module list: {0}."); 2673 } else { 2674 addr = list->m_link_map; 2675 } 2676 } 2677 2678 return addr; 2679 } 2680 2681 void ProcessGDBRemote::WillPublicStop() { 2682 // See if the GDB remote client supports the JSON threads info. If so, we 2683 // gather stop info for all threads, expedited registers, expedited memory, 2684 // runtime queue information (iOS and MacOSX only), and more. Expediting 2685 // memory will help stack backtracing be much faster. Expediting registers 2686 // will make sure we don't have to read the thread registers for GPRs. 2687 m_jthreadsinfo_sp = m_gdb_comm.GetThreadsInfo(); 2688 2689 if (m_jthreadsinfo_sp) { 2690 // Now set the stop info for each thread and also expedite any registers 2691 // and memory that was in the jThreadsInfo response. 2692 StructuredData::Array *thread_infos = m_jthreadsinfo_sp->GetAsArray(); 2693 if (thread_infos) { 2694 const size_t n = thread_infos->GetSize(); 2695 for (size_t i = 0; i < n; ++i) { 2696 StructuredData::Dictionary *thread_dict = 2697 thread_infos->GetItemAtIndex(i)->GetAsDictionary(); 2698 if (thread_dict) 2699 SetThreadStopInfo(thread_dict); 2700 } 2701 } 2702 } 2703 } 2704 2705 // Process Memory 2706 size_t ProcessGDBRemote::DoReadMemory(addr_t addr, void *buf, size_t size, 2707 Status &error) { 2708 GetMaxMemorySize(); 2709 bool binary_memory_read = m_gdb_comm.GetxPacketSupported(); 2710 // M and m packets take 2 bytes for 1 byte of memory 2711 size_t max_memory_size = 2712 binary_memory_read ? m_max_memory_size : m_max_memory_size / 2; 2713 if (size > max_memory_size) { 2714 // Keep memory read sizes down to a sane limit. This function will be 2715 // called multiple times in order to complete the task by 2716 // lldb_private::Process so it is ok to do this. 2717 size = max_memory_size; 2718 } 2719 2720 char packet[64]; 2721 int packet_len; 2722 packet_len = ::snprintf(packet, sizeof(packet), "%c%" PRIx64 ",%" PRIx64, 2723 binary_memory_read ? 'x' : 'm', (uint64_t)addr, 2724 (uint64_t)size); 2725 assert(packet_len + 1 < (int)sizeof(packet)); 2726 UNUSED_IF_ASSERT_DISABLED(packet_len); 2727 StringExtractorGDBRemote response; 2728 if (m_gdb_comm.SendPacketAndWaitForResponse(packet, response, true) == 2729 GDBRemoteCommunication::PacketResult::Success) { 2730 if (response.IsNormalResponse()) { 2731 error.Clear(); 2732 if (binary_memory_read) { 2733 // The lower level GDBRemoteCommunication packet receive layer has 2734 // already de-quoted any 0x7d character escaping that was present in 2735 // the packet 2736 2737 size_t data_received_size = response.GetBytesLeft(); 2738 if (data_received_size > size) { 2739 // Don't write past the end of BUF if the remote debug server gave us 2740 // too much data for some reason. 2741 data_received_size = size; 2742 } 2743 memcpy(buf, response.GetStringRef().data(), data_received_size); 2744 return data_received_size; 2745 } else { 2746 return response.GetHexBytes( 2747 llvm::MutableArrayRef<uint8_t>((uint8_t *)buf, size), '\xdd'); 2748 } 2749 } else if (response.IsErrorResponse()) 2750 error.SetErrorStringWithFormat("memory read failed for 0x%" PRIx64, addr); 2751 else if (response.IsUnsupportedResponse()) 2752 error.SetErrorStringWithFormat( 2753 "GDB server does not support reading memory"); 2754 else 2755 error.SetErrorStringWithFormat( 2756 "unexpected response to GDB server memory read packet '%s': '%s'", 2757 packet, response.GetStringRef().data()); 2758 } else { 2759 error.SetErrorStringWithFormat("failed to send packet: '%s'", packet); 2760 } 2761 return 0; 2762 } 2763 2764 Status ProcessGDBRemote::WriteObjectFile( 2765 std::vector<ObjectFile::LoadableData> entries) { 2766 Status error; 2767 // Sort the entries by address because some writes, like those to flash 2768 // memory, must happen in order of increasing address. 2769 std::stable_sort( 2770 std::begin(entries), std::end(entries), 2771 [](const ObjectFile::LoadableData a, const ObjectFile::LoadableData b) { 2772 return a.Dest < b.Dest; 2773 }); 2774 m_allow_flash_writes = true; 2775 error = Process::WriteObjectFile(entries); 2776 if (error.Success()) 2777 error = FlashDone(); 2778 else 2779 // Even though some of the writing failed, try to send a flash done if some 2780 // of the writing succeeded so the flash state is reset to normal, but 2781 // don't stomp on the error status that was set in the write failure since 2782 // that's the one we want to report back. 2783 FlashDone(); 2784 m_allow_flash_writes = false; 2785 return error; 2786 } 2787 2788 bool ProcessGDBRemote::HasErased(FlashRange range) { 2789 auto size = m_erased_flash_ranges.GetSize(); 2790 for (size_t i = 0; i < size; ++i) 2791 if (m_erased_flash_ranges.GetEntryAtIndex(i)->Contains(range)) 2792 return true; 2793 return false; 2794 } 2795 2796 Status ProcessGDBRemote::FlashErase(lldb::addr_t addr, size_t size) { 2797 Status status; 2798 2799 MemoryRegionInfo region; 2800 status = GetMemoryRegionInfo(addr, region); 2801 if (!status.Success()) 2802 return status; 2803 2804 // The gdb spec doesn't say if erasures are allowed across multiple regions, 2805 // but we'll disallow it to be safe and to keep the logic simple by worring 2806 // about only one region's block size. DoMemoryWrite is this function's 2807 // primary user, and it can easily keep writes within a single memory region 2808 if (addr + size > region.GetRange().GetRangeEnd()) { 2809 status.SetErrorString("Unable to erase flash in multiple regions"); 2810 return status; 2811 } 2812 2813 uint64_t blocksize = region.GetBlocksize(); 2814 if (blocksize == 0) { 2815 status.SetErrorString("Unable to erase flash because blocksize is 0"); 2816 return status; 2817 } 2818 2819 // Erasures can only be done on block boundary adresses, so round down addr 2820 // and round up size 2821 lldb::addr_t block_start_addr = addr - (addr % blocksize); 2822 size += (addr - block_start_addr); 2823 if ((size % blocksize) != 0) 2824 size += (blocksize - size % blocksize); 2825 2826 FlashRange range(block_start_addr, size); 2827 2828 if (HasErased(range)) 2829 return status; 2830 2831 // We haven't erased the entire range, but we may have erased part of it. 2832 // (e.g., block A is already erased and range starts in A and ends in B). So, 2833 // adjust range if necessary to exclude already erased blocks. 2834 if (!m_erased_flash_ranges.IsEmpty()) { 2835 // Assuming that writes and erasures are done in increasing addr order, 2836 // because that is a requirement of the vFlashWrite command. Therefore, we 2837 // only need to look at the last range in the list for overlap. 2838 const auto &last_range = *m_erased_flash_ranges.Back(); 2839 if (range.GetRangeBase() < last_range.GetRangeEnd()) { 2840 auto overlap = last_range.GetRangeEnd() - range.GetRangeBase(); 2841 // overlap will be less than range.GetByteSize() or else HasErased() 2842 // would have been true 2843 range.SetByteSize(range.GetByteSize() - overlap); 2844 range.SetRangeBase(range.GetRangeBase() + overlap); 2845 } 2846 } 2847 2848 StreamString packet; 2849 packet.Printf("vFlashErase:%" PRIx64 ",%" PRIx64, range.GetRangeBase(), 2850 (uint64_t)range.GetByteSize()); 2851 2852 StringExtractorGDBRemote response; 2853 if (m_gdb_comm.SendPacketAndWaitForResponse(packet.GetString(), response, 2854 true) == 2855 GDBRemoteCommunication::PacketResult::Success) { 2856 if (response.IsOKResponse()) { 2857 m_erased_flash_ranges.Insert(range, true); 2858 } else { 2859 if (response.IsErrorResponse()) 2860 status.SetErrorStringWithFormat("flash erase failed for 0x%" PRIx64, 2861 addr); 2862 else if (response.IsUnsupportedResponse()) 2863 status.SetErrorStringWithFormat("GDB server does not support flashing"); 2864 else 2865 status.SetErrorStringWithFormat( 2866 "unexpected response to GDB server flash erase packet '%s': '%s'", 2867 packet.GetData(), response.GetStringRef().data()); 2868 } 2869 } else { 2870 status.SetErrorStringWithFormat("failed to send packet: '%s'", 2871 packet.GetData()); 2872 } 2873 return status; 2874 } 2875 2876 Status ProcessGDBRemote::FlashDone() { 2877 Status status; 2878 // If we haven't erased any blocks, then we must not have written anything 2879 // either, so there is no need to actually send a vFlashDone command 2880 if (m_erased_flash_ranges.IsEmpty()) 2881 return status; 2882 StringExtractorGDBRemote response; 2883 if (m_gdb_comm.SendPacketAndWaitForResponse("vFlashDone", response, true) == 2884 GDBRemoteCommunication::PacketResult::Success) { 2885 if (response.IsOKResponse()) { 2886 m_erased_flash_ranges.Clear(); 2887 } else { 2888 if (response.IsErrorResponse()) 2889 status.SetErrorStringWithFormat("flash done failed"); 2890 else if (response.IsUnsupportedResponse()) 2891 status.SetErrorStringWithFormat("GDB server does not support flashing"); 2892 else 2893 status.SetErrorStringWithFormat( 2894 "unexpected response to GDB server flash done packet: '%s'", 2895 response.GetStringRef().data()); 2896 } 2897 } else { 2898 status.SetErrorStringWithFormat("failed to send flash done packet"); 2899 } 2900 return status; 2901 } 2902 2903 size_t ProcessGDBRemote::DoWriteMemory(addr_t addr, const void *buf, 2904 size_t size, Status &error) { 2905 GetMaxMemorySize(); 2906 // M and m packets take 2 bytes for 1 byte of memory 2907 size_t max_memory_size = m_max_memory_size / 2; 2908 if (size > max_memory_size) { 2909 // Keep memory read sizes down to a sane limit. This function will be 2910 // called multiple times in order to complete the task by 2911 // lldb_private::Process so it is ok to do this. 2912 size = max_memory_size; 2913 } 2914 2915 StreamGDBRemote packet; 2916 2917 MemoryRegionInfo region; 2918 Status region_status = GetMemoryRegionInfo(addr, region); 2919 2920 bool is_flash = 2921 region_status.Success() && region.GetFlash() == MemoryRegionInfo::eYes; 2922 2923 if (is_flash) { 2924 if (!m_allow_flash_writes) { 2925 error.SetErrorString("Writing to flash memory is not allowed"); 2926 return 0; 2927 } 2928 // Keep the write within a flash memory region 2929 if (addr + size > region.GetRange().GetRangeEnd()) 2930 size = region.GetRange().GetRangeEnd() - addr; 2931 // Flash memory must be erased before it can be written 2932 error = FlashErase(addr, size); 2933 if (!error.Success()) 2934 return 0; 2935 packet.Printf("vFlashWrite:%" PRIx64 ":", addr); 2936 packet.PutEscapedBytes(buf, size); 2937 } else { 2938 packet.Printf("M%" PRIx64 ",%" PRIx64 ":", addr, (uint64_t)size); 2939 packet.PutBytesAsRawHex8(buf, size, endian::InlHostByteOrder(), 2940 endian::InlHostByteOrder()); 2941 } 2942 StringExtractorGDBRemote response; 2943 if (m_gdb_comm.SendPacketAndWaitForResponse(packet.GetString(), response, 2944 true) == 2945 GDBRemoteCommunication::PacketResult::Success) { 2946 if (response.IsOKResponse()) { 2947 error.Clear(); 2948 return size; 2949 } else if (response.IsErrorResponse()) 2950 error.SetErrorStringWithFormat("memory write failed for 0x%" PRIx64, 2951 addr); 2952 else if (response.IsUnsupportedResponse()) 2953 error.SetErrorStringWithFormat( 2954 "GDB server does not support writing memory"); 2955 else 2956 error.SetErrorStringWithFormat( 2957 "unexpected response to GDB server memory write packet '%s': '%s'", 2958 packet.GetData(), response.GetStringRef().data()); 2959 } else { 2960 error.SetErrorStringWithFormat("failed to send packet: '%s'", 2961 packet.GetData()); 2962 } 2963 return 0; 2964 } 2965 2966 lldb::addr_t ProcessGDBRemote::DoAllocateMemory(size_t size, 2967 uint32_t permissions, 2968 Status &error) { 2969 Log *log( 2970 GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS | LIBLLDB_LOG_EXPRESSIONS)); 2971 addr_t allocated_addr = LLDB_INVALID_ADDRESS; 2972 2973 if (m_gdb_comm.SupportsAllocDeallocMemory() != eLazyBoolNo) { 2974 allocated_addr = m_gdb_comm.AllocateMemory(size, permissions); 2975 if (allocated_addr != LLDB_INVALID_ADDRESS || 2976 m_gdb_comm.SupportsAllocDeallocMemory() == eLazyBoolYes) 2977 return allocated_addr; 2978 } 2979 2980 if (m_gdb_comm.SupportsAllocDeallocMemory() == eLazyBoolNo) { 2981 // Call mmap() to create memory in the inferior.. 2982 unsigned prot = 0; 2983 if (permissions & lldb::ePermissionsReadable) 2984 prot |= eMmapProtRead; 2985 if (permissions & lldb::ePermissionsWritable) 2986 prot |= eMmapProtWrite; 2987 if (permissions & lldb::ePermissionsExecutable) 2988 prot |= eMmapProtExec; 2989 2990 if (InferiorCallMmap(this, allocated_addr, 0, size, prot, 2991 eMmapFlagsAnon | eMmapFlagsPrivate, -1, 0)) 2992 m_addr_to_mmap_size[allocated_addr] = size; 2993 else { 2994 allocated_addr = LLDB_INVALID_ADDRESS; 2995 LLDB_LOGF(log, 2996 "ProcessGDBRemote::%s no direct stub support for memory " 2997 "allocation, and InferiorCallMmap also failed - is stub " 2998 "missing register context save/restore capability?", 2999 __FUNCTION__); 3000 } 3001 } 3002 3003 if (allocated_addr == LLDB_INVALID_ADDRESS) 3004 error.SetErrorStringWithFormat( 3005 "unable to allocate %" PRIu64 " bytes of memory with permissions %s", 3006 (uint64_t)size, GetPermissionsAsCString(permissions)); 3007 else 3008 error.Clear(); 3009 return allocated_addr; 3010 } 3011 3012 Status ProcessGDBRemote::GetMemoryRegionInfo(addr_t load_addr, 3013 MemoryRegionInfo ®ion_info) { 3014 3015 Status error(m_gdb_comm.GetMemoryRegionInfo(load_addr, region_info)); 3016 return error; 3017 } 3018 3019 Status ProcessGDBRemote::GetWatchpointSupportInfo(uint32_t &num) { 3020 3021 Status error(m_gdb_comm.GetWatchpointSupportInfo(num)); 3022 return error; 3023 } 3024 3025 Status ProcessGDBRemote::GetWatchpointSupportInfo(uint32_t &num, bool &after) { 3026 Status error(m_gdb_comm.GetWatchpointSupportInfo( 3027 num, after, GetTarget().GetArchitecture())); 3028 return error; 3029 } 3030 3031 Status ProcessGDBRemote::DoDeallocateMemory(lldb::addr_t addr) { 3032 Status error; 3033 LazyBool supported = m_gdb_comm.SupportsAllocDeallocMemory(); 3034 3035 switch (supported) { 3036 case eLazyBoolCalculate: 3037 // We should never be deallocating memory without allocating memory first 3038 // so we should never get eLazyBoolCalculate 3039 error.SetErrorString( 3040 "tried to deallocate memory without ever allocating memory"); 3041 break; 3042 3043 case eLazyBoolYes: 3044 if (!m_gdb_comm.DeallocateMemory(addr)) 3045 error.SetErrorStringWithFormat( 3046 "unable to deallocate memory at 0x%" PRIx64, addr); 3047 break; 3048 3049 case eLazyBoolNo: 3050 // Call munmap() to deallocate memory in the inferior.. 3051 { 3052 MMapMap::iterator pos = m_addr_to_mmap_size.find(addr); 3053 if (pos != m_addr_to_mmap_size.end() && 3054 InferiorCallMunmap(this, addr, pos->second)) 3055 m_addr_to_mmap_size.erase(pos); 3056 else 3057 error.SetErrorStringWithFormat( 3058 "unable to deallocate memory at 0x%" PRIx64, addr); 3059 } 3060 break; 3061 } 3062 3063 return error; 3064 } 3065 3066 // Process STDIO 3067 size_t ProcessGDBRemote::PutSTDIN(const char *src, size_t src_len, 3068 Status &error) { 3069 if (m_stdio_communication.IsConnected()) { 3070 ConnectionStatus status; 3071 m_stdio_communication.Write(src, src_len, status, nullptr); 3072 } else if (m_stdin_forward) { 3073 m_gdb_comm.SendStdinNotification(src, src_len); 3074 } 3075 return 0; 3076 } 3077 3078 Status ProcessGDBRemote::EnableBreakpointSite(BreakpointSite *bp_site) { 3079 Status error; 3080 assert(bp_site != nullptr); 3081 3082 // Get logging info 3083 Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_BREAKPOINTS)); 3084 user_id_t site_id = bp_site->GetID(); 3085 3086 // Get the breakpoint address 3087 const addr_t addr = bp_site->GetLoadAddress(); 3088 3089 // Log that a breakpoint was requested 3090 LLDB_LOGF(log, 3091 "ProcessGDBRemote::EnableBreakpointSite (size_id = %" PRIu64 3092 ") address = 0x%" PRIx64, 3093 site_id, (uint64_t)addr); 3094 3095 // Breakpoint already exists and is enabled 3096 if (bp_site->IsEnabled()) { 3097 LLDB_LOGF(log, 3098 "ProcessGDBRemote::EnableBreakpointSite (size_id = %" PRIu64 3099 ") address = 0x%" PRIx64 " -- SUCCESS (already enabled)", 3100 site_id, (uint64_t)addr); 3101 return error; 3102 } 3103 3104 // Get the software breakpoint trap opcode size 3105 const size_t bp_op_size = GetSoftwareBreakpointTrapOpcode(bp_site); 3106 3107 // SupportsGDBStoppointPacket() simply checks a boolean, indicating if this 3108 // breakpoint type is supported by the remote stub. These are set to true by 3109 // default, and later set to false only after we receive an unimplemented 3110 // response when sending a breakpoint packet. This means initially that 3111 // unless we were specifically instructed to use a hardware breakpoint, LLDB 3112 // will attempt to set a software breakpoint. HardwareRequired() also queries 3113 // a boolean variable which indicates if the user specifically asked for 3114 // hardware breakpoints. If true then we will skip over software 3115 // breakpoints. 3116 if (m_gdb_comm.SupportsGDBStoppointPacket(eBreakpointSoftware) && 3117 (!bp_site->HardwareRequired())) { 3118 // Try to send off a software breakpoint packet ($Z0) 3119 uint8_t error_no = m_gdb_comm.SendGDBStoppointTypePacket( 3120 eBreakpointSoftware, true, addr, bp_op_size); 3121 if (error_no == 0) { 3122 // The breakpoint was placed successfully 3123 bp_site->SetEnabled(true); 3124 bp_site->SetType(BreakpointSite::eExternal); 3125 return error; 3126 } 3127 3128 // SendGDBStoppointTypePacket() will return an error if it was unable to 3129 // set this breakpoint. We need to differentiate between a error specific 3130 // to placing this breakpoint or if we have learned that this breakpoint 3131 // type is unsupported. To do this, we must test the support boolean for 3132 // this breakpoint type to see if it now indicates that this breakpoint 3133 // type is unsupported. If they are still supported then we should return 3134 // with the error code. If they are now unsupported, then we would like to 3135 // fall through and try another form of breakpoint. 3136 if (m_gdb_comm.SupportsGDBStoppointPacket(eBreakpointSoftware)) { 3137 if (error_no != UINT8_MAX) 3138 error.SetErrorStringWithFormat( 3139 "error: %d sending the breakpoint request", error_no); 3140 else 3141 error.SetErrorString("error sending the breakpoint request"); 3142 return error; 3143 } 3144 3145 // We reach here when software breakpoints have been found to be 3146 // unsupported. For future calls to set a breakpoint, we will not attempt 3147 // to set a breakpoint with a type that is known not to be supported. 3148 LLDB_LOGF(log, "Software breakpoints are unsupported"); 3149 3150 // So we will fall through and try a hardware breakpoint 3151 } 3152 3153 // The process of setting a hardware breakpoint is much the same as above. 3154 // We check the supported boolean for this breakpoint type, and if it is 3155 // thought to be supported then we will try to set this breakpoint with a 3156 // hardware breakpoint. 3157 if (m_gdb_comm.SupportsGDBStoppointPacket(eBreakpointHardware)) { 3158 // Try to send off a hardware breakpoint packet ($Z1) 3159 uint8_t error_no = m_gdb_comm.SendGDBStoppointTypePacket( 3160 eBreakpointHardware, true, addr, bp_op_size); 3161 if (error_no == 0) { 3162 // The breakpoint was placed successfully 3163 bp_site->SetEnabled(true); 3164 bp_site->SetType(BreakpointSite::eHardware); 3165 return error; 3166 } 3167 3168 // Check if the error was something other then an unsupported breakpoint 3169 // type 3170 if (m_gdb_comm.SupportsGDBStoppointPacket(eBreakpointHardware)) { 3171 // Unable to set this hardware breakpoint 3172 if (error_no != UINT8_MAX) 3173 error.SetErrorStringWithFormat( 3174 "error: %d sending the hardware breakpoint request " 3175 "(hardware breakpoint resources might be exhausted or unavailable)", 3176 error_no); 3177 else 3178 error.SetErrorString("error sending the hardware breakpoint request " 3179 "(hardware breakpoint resources " 3180 "might be exhausted or unavailable)"); 3181 return error; 3182 } 3183 3184 // We will reach here when the stub gives an unsupported response to a 3185 // hardware breakpoint 3186 LLDB_LOGF(log, "Hardware breakpoints are unsupported"); 3187 3188 // Finally we will falling through to a #trap style breakpoint 3189 } 3190 3191 // Don't fall through when hardware breakpoints were specifically requested 3192 if (bp_site->HardwareRequired()) { 3193 error.SetErrorString("hardware breakpoints are not supported"); 3194 return error; 3195 } 3196 3197 // As a last resort we want to place a manual breakpoint. An instruction is 3198 // placed into the process memory using memory write packets. 3199 return EnableSoftwareBreakpoint(bp_site); 3200 } 3201 3202 Status ProcessGDBRemote::DisableBreakpointSite(BreakpointSite *bp_site) { 3203 Status error; 3204 assert(bp_site != nullptr); 3205 addr_t addr = bp_site->GetLoadAddress(); 3206 user_id_t site_id = bp_site->GetID(); 3207 Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_BREAKPOINTS)); 3208 LLDB_LOGF(log, 3209 "ProcessGDBRemote::DisableBreakpointSite (site_id = %" PRIu64 3210 ") addr = 0x%8.8" PRIx64, 3211 site_id, (uint64_t)addr); 3212 3213 if (bp_site->IsEnabled()) { 3214 const size_t bp_op_size = GetSoftwareBreakpointTrapOpcode(bp_site); 3215 3216 BreakpointSite::Type bp_type = bp_site->GetType(); 3217 switch (bp_type) { 3218 case BreakpointSite::eSoftware: 3219 error = DisableSoftwareBreakpoint(bp_site); 3220 break; 3221 3222 case BreakpointSite::eHardware: 3223 if (m_gdb_comm.SendGDBStoppointTypePacket(eBreakpointHardware, false, 3224 addr, bp_op_size)) 3225 error.SetErrorToGenericError(); 3226 break; 3227 3228 case BreakpointSite::eExternal: { 3229 if (m_gdb_comm.SendGDBStoppointTypePacket(eBreakpointSoftware, false, 3230 addr, bp_op_size)) 3231 error.SetErrorToGenericError(); 3232 } break; 3233 } 3234 if (error.Success()) 3235 bp_site->SetEnabled(false); 3236 } else { 3237 LLDB_LOGF(log, 3238 "ProcessGDBRemote::DisableBreakpointSite (site_id = %" PRIu64 3239 ") addr = 0x%8.8" PRIx64 " -- SUCCESS (already disabled)", 3240 site_id, (uint64_t)addr); 3241 return error; 3242 } 3243 3244 if (error.Success()) 3245 error.SetErrorToGenericError(); 3246 return error; 3247 } 3248 3249 // Pre-requisite: wp != NULL. 3250 static GDBStoppointType GetGDBStoppointType(Watchpoint *wp) { 3251 assert(wp); 3252 bool watch_read = wp->WatchpointRead(); 3253 bool watch_write = wp->WatchpointWrite(); 3254 3255 // watch_read and watch_write cannot both be false. 3256 assert(watch_read || watch_write); 3257 if (watch_read && watch_write) 3258 return eWatchpointReadWrite; 3259 else if (watch_read) 3260 return eWatchpointRead; 3261 else // Must be watch_write, then. 3262 return eWatchpointWrite; 3263 } 3264 3265 Status ProcessGDBRemote::EnableWatchpoint(Watchpoint *wp, bool notify) { 3266 Status error; 3267 if (wp) { 3268 user_id_t watchID = wp->GetID(); 3269 addr_t addr = wp->GetLoadAddress(); 3270 Log *log( 3271 ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_WATCHPOINTS)); 3272 LLDB_LOGF(log, "ProcessGDBRemote::EnableWatchpoint(watchID = %" PRIu64 ")", 3273 watchID); 3274 if (wp->IsEnabled()) { 3275 LLDB_LOGF(log, 3276 "ProcessGDBRemote::EnableWatchpoint(watchID = %" PRIu64 3277 ") addr = 0x%8.8" PRIx64 ": watchpoint already enabled.", 3278 watchID, (uint64_t)addr); 3279 return error; 3280 } 3281 3282 GDBStoppointType type = GetGDBStoppointType(wp); 3283 // Pass down an appropriate z/Z packet... 3284 if (m_gdb_comm.SupportsGDBStoppointPacket(type)) { 3285 if (m_gdb_comm.SendGDBStoppointTypePacket(type, true, addr, 3286 wp->GetByteSize()) == 0) { 3287 wp->SetEnabled(true, notify); 3288 return error; 3289 } else 3290 error.SetErrorString("sending gdb watchpoint packet failed"); 3291 } else 3292 error.SetErrorString("watchpoints not supported"); 3293 } else { 3294 error.SetErrorString("Watchpoint argument was NULL."); 3295 } 3296 if (error.Success()) 3297 error.SetErrorToGenericError(); 3298 return error; 3299 } 3300 3301 Status ProcessGDBRemote::DisableWatchpoint(Watchpoint *wp, bool notify) { 3302 Status error; 3303 if (wp) { 3304 user_id_t watchID = wp->GetID(); 3305 3306 Log *log( 3307 ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_WATCHPOINTS)); 3308 3309 addr_t addr = wp->GetLoadAddress(); 3310 3311 LLDB_LOGF(log, 3312 "ProcessGDBRemote::DisableWatchpoint (watchID = %" PRIu64 3313 ") addr = 0x%8.8" PRIx64, 3314 watchID, (uint64_t)addr); 3315 3316 if (!wp->IsEnabled()) { 3317 LLDB_LOGF(log, 3318 "ProcessGDBRemote::DisableWatchpoint (watchID = %" PRIu64 3319 ") addr = 0x%8.8" PRIx64 " -- SUCCESS (already disabled)", 3320 watchID, (uint64_t)addr); 3321 // See also 'class WatchpointSentry' within StopInfo.cpp. This disabling 3322 // attempt might come from the user-supplied actions, we'll route it in 3323 // order for the watchpoint object to intelligently process this action. 3324 wp->SetEnabled(false, notify); 3325 return error; 3326 } 3327 3328 if (wp->IsHardware()) { 3329 GDBStoppointType type = GetGDBStoppointType(wp); 3330 // Pass down an appropriate z/Z packet... 3331 if (m_gdb_comm.SendGDBStoppointTypePacket(type, false, addr, 3332 wp->GetByteSize()) == 0) { 3333 wp->SetEnabled(false, notify); 3334 return error; 3335 } else 3336 error.SetErrorString("sending gdb watchpoint packet failed"); 3337 } 3338 // TODO: clear software watchpoints if we implement them 3339 } else { 3340 error.SetErrorString("Watchpoint argument was NULL."); 3341 } 3342 if (error.Success()) 3343 error.SetErrorToGenericError(); 3344 return error; 3345 } 3346 3347 void ProcessGDBRemote::Clear() { 3348 m_thread_list_real.Clear(); 3349 m_thread_list.Clear(); 3350 } 3351 3352 Status ProcessGDBRemote::DoSignal(int signo) { 3353 Status error; 3354 Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS)); 3355 LLDB_LOGF(log, "ProcessGDBRemote::DoSignal (signal = %d)", signo); 3356 3357 if (!m_gdb_comm.SendAsyncSignal(signo)) 3358 error.SetErrorStringWithFormat("failed to send signal %i", signo); 3359 return error; 3360 } 3361 3362 Status ProcessGDBRemote::ConnectToReplayServer() { 3363 Status status = m_gdb_replay_server.Connect(m_gdb_comm); 3364 if (status.Fail()) 3365 return status; 3366 3367 // Enable replay mode. 3368 m_replay_mode = true; 3369 3370 // Start server thread. 3371 m_gdb_replay_server.StartAsyncThread(); 3372 3373 // Start client thread. 3374 StartAsyncThread(); 3375 3376 // Do the usual setup. 3377 return ConnectToDebugserver(""); 3378 } 3379 3380 Status 3381 ProcessGDBRemote::EstablishConnectionIfNeeded(const ProcessInfo &process_info) { 3382 // Make sure we aren't already connected? 3383 if (m_gdb_comm.IsConnected()) 3384 return Status(); 3385 3386 PlatformSP platform_sp(GetTarget().GetPlatform()); 3387 if (platform_sp && !platform_sp->IsHost()) 3388 return Status("Lost debug server connection"); 3389 3390 if (repro::Reproducer::Instance().IsReplaying()) 3391 return ConnectToReplayServer(); 3392 3393 auto error = LaunchAndConnectToDebugserver(process_info); 3394 if (error.Fail()) { 3395 const char *error_string = error.AsCString(); 3396 if (error_string == nullptr) 3397 error_string = "unable to launch " DEBUGSERVER_BASENAME; 3398 } 3399 return error; 3400 } 3401 #if !defined(_WIN32) 3402 #define USE_SOCKETPAIR_FOR_LOCAL_CONNECTION 1 3403 #endif 3404 3405 #ifdef USE_SOCKETPAIR_FOR_LOCAL_CONNECTION 3406 static bool SetCloexecFlag(int fd) { 3407 #if defined(FD_CLOEXEC) 3408 int flags = ::fcntl(fd, F_GETFD); 3409 if (flags == -1) 3410 return false; 3411 return (::fcntl(fd, F_SETFD, flags | FD_CLOEXEC) == 0); 3412 #else 3413 return false; 3414 #endif 3415 } 3416 #endif 3417 3418 Status ProcessGDBRemote::LaunchAndConnectToDebugserver( 3419 const ProcessInfo &process_info) { 3420 using namespace std::placeholders; // For _1, _2, etc. 3421 3422 Status error; 3423 if (m_debugserver_pid == LLDB_INVALID_PROCESS_ID) { 3424 // If we locate debugserver, keep that located version around 3425 static FileSpec g_debugserver_file_spec; 3426 3427 ProcessLaunchInfo debugserver_launch_info; 3428 // Make debugserver run in its own session so signals generated by special 3429 // terminal key sequences (^C) don't affect debugserver. 3430 debugserver_launch_info.SetLaunchInSeparateProcessGroup(true); 3431 3432 const std::weak_ptr<ProcessGDBRemote> this_wp = 3433 std::static_pointer_cast<ProcessGDBRemote>(shared_from_this()); 3434 debugserver_launch_info.SetMonitorProcessCallback( 3435 std::bind(MonitorDebugserverProcess, this_wp, _1, _2, _3, _4), false); 3436 debugserver_launch_info.SetUserID(process_info.GetUserID()); 3437 3438 #if defined(__APPLE__) 3439 // On macOS 11, we need to support x86_64 applications translated to 3440 // arm64. We check whether a binary is translated and spawn the correct 3441 // debugserver accordingly. 3442 int mib[] = { CTL_KERN, KERN_PROC, KERN_PROC_PID, 3443 static_cast<int>(process_info.GetProcessID()) }; 3444 struct kinfo_proc processInfo; 3445 size_t bufsize = sizeof(processInfo); 3446 if (sysctl(mib, (unsigned)(sizeof(mib)/sizeof(int)), &processInfo, 3447 &bufsize, NULL, 0) == 0 && bufsize > 0) { 3448 if (processInfo.kp_proc.p_flag & P_TRANSLATED) { 3449 FileSpec rosetta_debugserver("/Library/Apple/usr/libexec/oah/debugserver"); 3450 debugserver_launch_info.SetExecutableFile(rosetta_debugserver, false); 3451 } 3452 } 3453 #endif 3454 3455 int communication_fd = -1; 3456 #ifdef USE_SOCKETPAIR_FOR_LOCAL_CONNECTION 3457 // Use a socketpair on non-Windows systems for security and performance 3458 // reasons. 3459 int sockets[2]; /* the pair of socket descriptors */ 3460 if (socketpair(AF_UNIX, SOCK_STREAM, 0, sockets) == -1) { 3461 error.SetErrorToErrno(); 3462 return error; 3463 } 3464 3465 int our_socket = sockets[0]; 3466 int gdb_socket = sockets[1]; 3467 auto cleanup_our = llvm::make_scope_exit([&]() { close(our_socket); }); 3468 auto cleanup_gdb = llvm::make_scope_exit([&]() { close(gdb_socket); }); 3469 3470 // Don't let any child processes inherit our communication socket 3471 SetCloexecFlag(our_socket); 3472 communication_fd = gdb_socket; 3473 #endif 3474 3475 error = m_gdb_comm.StartDebugserverProcess( 3476 nullptr, GetTarget().GetPlatform().get(), debugserver_launch_info, 3477 nullptr, nullptr, communication_fd); 3478 3479 if (error.Success()) 3480 m_debugserver_pid = debugserver_launch_info.GetProcessID(); 3481 else 3482 m_debugserver_pid = LLDB_INVALID_PROCESS_ID; 3483 3484 if (m_debugserver_pid != LLDB_INVALID_PROCESS_ID) { 3485 #ifdef USE_SOCKETPAIR_FOR_LOCAL_CONNECTION 3486 // Our process spawned correctly, we can now set our connection to use 3487 // our end of the socket pair 3488 cleanup_our.release(); 3489 m_gdb_comm.SetConnection( 3490 std::make_unique<ConnectionFileDescriptor>(our_socket, true)); 3491 #endif 3492 StartAsyncThread(); 3493 } 3494 3495 if (error.Fail()) { 3496 Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS)); 3497 3498 LLDB_LOGF(log, "failed to start debugserver process: %s", 3499 error.AsCString()); 3500 return error; 3501 } 3502 3503 if (m_gdb_comm.IsConnected()) { 3504 // Finish the connection process by doing the handshake without 3505 // connecting (send NULL URL) 3506 error = ConnectToDebugserver(""); 3507 } else { 3508 error.SetErrorString("connection failed"); 3509 } 3510 } 3511 return error; 3512 } 3513 3514 bool ProcessGDBRemote::MonitorDebugserverProcess( 3515 std::weak_ptr<ProcessGDBRemote> process_wp, lldb::pid_t debugserver_pid, 3516 bool exited, // True if the process did exit 3517 int signo, // Zero for no signal 3518 int exit_status // Exit value of process if signal is zero 3519 ) { 3520 // "debugserver_pid" argument passed in is the process ID for debugserver 3521 // that we are tracking... 3522 Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS)); 3523 const bool handled = true; 3524 3525 LLDB_LOGF(log, 3526 "ProcessGDBRemote::%s(process_wp, pid=%" PRIu64 3527 ", signo=%i (0x%x), exit_status=%i)", 3528 __FUNCTION__, debugserver_pid, signo, signo, exit_status); 3529 3530 std::shared_ptr<ProcessGDBRemote> process_sp = process_wp.lock(); 3531 LLDB_LOGF(log, "ProcessGDBRemote::%s(process = %p)", __FUNCTION__, 3532 static_cast<void *>(process_sp.get())); 3533 if (!process_sp || process_sp->m_debugserver_pid != debugserver_pid) 3534 return handled; 3535 3536 // Sleep for a half a second to make sure our inferior process has time to 3537 // set its exit status before we set it incorrectly when both the debugserver 3538 // and the inferior process shut down. 3539 std::this_thread::sleep_for(std::chrono::milliseconds(500)); 3540 3541 // If our process hasn't yet exited, debugserver might have died. If the 3542 // process did exit, then we are reaping it. 3543 const StateType state = process_sp->GetState(); 3544 3545 if (state != eStateInvalid && state != eStateUnloaded && 3546 state != eStateExited && state != eStateDetached) { 3547 char error_str[1024]; 3548 if (signo) { 3549 const char *signal_cstr = 3550 process_sp->GetUnixSignals()->GetSignalAsCString(signo); 3551 if (signal_cstr) 3552 ::snprintf(error_str, sizeof(error_str), 3553 DEBUGSERVER_BASENAME " died with signal %s", signal_cstr); 3554 else 3555 ::snprintf(error_str, sizeof(error_str), 3556 DEBUGSERVER_BASENAME " died with signal %i", signo); 3557 } else { 3558 ::snprintf(error_str, sizeof(error_str), 3559 DEBUGSERVER_BASENAME " died with an exit status of 0x%8.8x", 3560 exit_status); 3561 } 3562 3563 process_sp->SetExitStatus(-1, error_str); 3564 } 3565 // Debugserver has exited we need to let our ProcessGDBRemote know that it no 3566 // longer has a debugserver instance 3567 process_sp->m_debugserver_pid = LLDB_INVALID_PROCESS_ID; 3568 return handled; 3569 } 3570 3571 void ProcessGDBRemote::KillDebugserverProcess() { 3572 m_gdb_comm.Disconnect(); 3573 if (m_debugserver_pid != LLDB_INVALID_PROCESS_ID) { 3574 Host::Kill(m_debugserver_pid, SIGINT); 3575 m_debugserver_pid = LLDB_INVALID_PROCESS_ID; 3576 } 3577 } 3578 3579 void ProcessGDBRemote::Initialize() { 3580 static llvm::once_flag g_once_flag; 3581 3582 llvm::call_once(g_once_flag, []() { 3583 PluginManager::RegisterPlugin(GetPluginNameStatic(), 3584 GetPluginDescriptionStatic(), CreateInstance, 3585 DebuggerInitialize); 3586 }); 3587 } 3588 3589 void ProcessGDBRemote::DebuggerInitialize(Debugger &debugger) { 3590 if (!PluginManager::GetSettingForProcessPlugin( 3591 debugger, PluginProperties::GetSettingName())) { 3592 const bool is_global_setting = true; 3593 PluginManager::CreateSettingForProcessPlugin( 3594 debugger, GetGlobalPluginProperties()->GetValueProperties(), 3595 ConstString("Properties for the gdb-remote process plug-in."), 3596 is_global_setting); 3597 } 3598 } 3599 3600 bool ProcessGDBRemote::StartAsyncThread() { 3601 Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS)); 3602 3603 LLDB_LOGF(log, "ProcessGDBRemote::%s ()", __FUNCTION__); 3604 3605 std::lock_guard<std::recursive_mutex> guard(m_async_thread_state_mutex); 3606 if (!m_async_thread.IsJoinable()) { 3607 // Create a thread that watches our internal state and controls which 3608 // events make it to clients (into the DCProcess event queue). 3609 3610 llvm::Expected<HostThread> async_thread = ThreadLauncher::LaunchThread( 3611 "<lldb.process.gdb-remote.async>", ProcessGDBRemote::AsyncThread, this); 3612 if (!async_thread) { 3613 LLDB_LOG_ERROR(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_HOST), 3614 async_thread.takeError(), 3615 "failed to launch host thread: {}"); 3616 return false; 3617 } 3618 m_async_thread = *async_thread; 3619 } else 3620 LLDB_LOGF(log, 3621 "ProcessGDBRemote::%s () - Called when Async thread was " 3622 "already running.", 3623 __FUNCTION__); 3624 3625 return m_async_thread.IsJoinable(); 3626 } 3627 3628 void ProcessGDBRemote::StopAsyncThread() { 3629 Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS)); 3630 3631 LLDB_LOGF(log, "ProcessGDBRemote::%s ()", __FUNCTION__); 3632 3633 std::lock_guard<std::recursive_mutex> guard(m_async_thread_state_mutex); 3634 if (m_async_thread.IsJoinable()) { 3635 m_async_broadcaster.BroadcastEvent(eBroadcastBitAsyncThreadShouldExit); 3636 3637 // This will shut down the async thread. 3638 m_gdb_comm.Disconnect(); // Disconnect from the debug server. 3639 3640 // Stop the stdio thread 3641 m_async_thread.Join(nullptr); 3642 m_async_thread.Reset(); 3643 } else 3644 LLDB_LOGF( 3645 log, 3646 "ProcessGDBRemote::%s () - Called when Async thread was not running.", 3647 __FUNCTION__); 3648 } 3649 3650 bool ProcessGDBRemote::HandleNotifyPacket(StringExtractorGDBRemote &packet) { 3651 // get the packet at a string 3652 const std::string &pkt = std::string(packet.GetStringRef()); 3653 // skip %stop: 3654 StringExtractorGDBRemote stop_info(pkt.c_str() + 5); 3655 3656 // pass as a thread stop info packet 3657 SetLastStopPacket(stop_info); 3658 3659 // check for more stop reasons 3660 HandleStopReplySequence(); 3661 3662 // if the process is stopped then we need to fake a resume so that we can 3663 // stop properly with the new break. This is possible due to 3664 // SetPrivateState() broadcasting the state change as a side effect. 3665 if (GetPrivateState() == lldb::StateType::eStateStopped) { 3666 SetPrivateState(lldb::StateType::eStateRunning); 3667 } 3668 3669 // since we have some stopped packets we can halt the process 3670 SetPrivateState(lldb::StateType::eStateStopped); 3671 3672 return true; 3673 } 3674 3675 thread_result_t ProcessGDBRemote::AsyncThread(void *arg) { 3676 ProcessGDBRemote *process = (ProcessGDBRemote *)arg; 3677 3678 Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS)); 3679 LLDB_LOGF(log, 3680 "ProcessGDBRemote::%s (arg = %p, pid = %" PRIu64 3681 ") thread starting...", 3682 __FUNCTION__, arg, process->GetID()); 3683 3684 EventSP event_sp; 3685 bool done = false; 3686 while (!done) { 3687 LLDB_LOGF(log, 3688 "ProcessGDBRemote::%s (arg = %p, pid = %" PRIu64 3689 ") listener.WaitForEvent (NULL, event_sp)...", 3690 __FUNCTION__, arg, process->GetID()); 3691 if (process->m_async_listener_sp->GetEvent(event_sp, llvm::None)) { 3692 const uint32_t event_type = event_sp->GetType(); 3693 if (event_sp->BroadcasterIs(&process->m_async_broadcaster)) { 3694 LLDB_LOGF(log, 3695 "ProcessGDBRemote::%s (arg = %p, pid = %" PRIu64 3696 ") Got an event of type: %d...", 3697 __FUNCTION__, arg, process->GetID(), event_type); 3698 3699 switch (event_type) { 3700 case eBroadcastBitAsyncContinue: { 3701 const EventDataBytes *continue_packet = 3702 EventDataBytes::GetEventDataFromEvent(event_sp.get()); 3703 3704 if (continue_packet) { 3705 const char *continue_cstr = 3706 (const char *)continue_packet->GetBytes(); 3707 const size_t continue_cstr_len = continue_packet->GetByteSize(); 3708 LLDB_LOGF(log, 3709 "ProcessGDBRemote::%s (arg = %p, pid = %" PRIu64 3710 ") got eBroadcastBitAsyncContinue: %s", 3711 __FUNCTION__, arg, process->GetID(), continue_cstr); 3712 3713 if (::strstr(continue_cstr, "vAttach") == nullptr) 3714 process->SetPrivateState(eStateRunning); 3715 StringExtractorGDBRemote response; 3716 3717 // If in Non-Stop-Mode 3718 if (process->GetTarget().GetNonStopModeEnabled()) { 3719 // send the vCont packet 3720 if (!process->GetGDBRemote().SendvContPacket( 3721 llvm::StringRef(continue_cstr, continue_cstr_len), 3722 response)) { 3723 // Something went wrong 3724 done = true; 3725 break; 3726 } 3727 } 3728 // If in All-Stop-Mode 3729 else { 3730 StateType stop_state = 3731 process->GetGDBRemote().SendContinuePacketAndWaitForResponse( 3732 *process, *process->GetUnixSignals(), 3733 llvm::StringRef(continue_cstr, continue_cstr_len), 3734 response); 3735 3736 // We need to immediately clear the thread ID list so we are sure 3737 // to get a valid list of threads. The thread ID list might be 3738 // contained within the "response", or the stop reply packet that 3739 // caused the stop. So clear it now before we give the stop reply 3740 // packet to the process using the 3741 // process->SetLastStopPacket()... 3742 process->ClearThreadIDList(); 3743 3744 switch (stop_state) { 3745 case eStateStopped: 3746 case eStateCrashed: 3747 case eStateSuspended: 3748 process->SetLastStopPacket(response); 3749 process->SetPrivateState(stop_state); 3750 break; 3751 3752 case eStateExited: { 3753 process->SetLastStopPacket(response); 3754 process->ClearThreadIDList(); 3755 response.SetFilePos(1); 3756 3757 int exit_status = response.GetHexU8(); 3758 std::string desc_string; 3759 if (response.GetBytesLeft() > 0 && 3760 response.GetChar('-') == ';') { 3761 llvm::StringRef desc_str; 3762 llvm::StringRef desc_token; 3763 while (response.GetNameColonValue(desc_token, desc_str)) { 3764 if (desc_token != "description") 3765 continue; 3766 StringExtractor extractor(desc_str); 3767 extractor.GetHexByteString(desc_string); 3768 } 3769 } 3770 process->SetExitStatus(exit_status, desc_string.c_str()); 3771 done = true; 3772 break; 3773 } 3774 case eStateInvalid: { 3775 // Check to see if we were trying to attach and if we got back 3776 // the "E87" error code from debugserver -- this indicates that 3777 // the process is not debuggable. Return a slightly more 3778 // helpful error message about why the attach failed. 3779 if (::strstr(continue_cstr, "vAttach") != nullptr && 3780 response.GetError() == 0x87) { 3781 process->SetExitStatus(-1, "cannot attach to process due to " 3782 "System Integrity Protection"); 3783 } else if (::strstr(continue_cstr, "vAttach") != nullptr && 3784 response.GetStatus().Fail()) { 3785 process->SetExitStatus(-1, response.GetStatus().AsCString()); 3786 } else { 3787 process->SetExitStatus(-1, "lost connection"); 3788 } 3789 break; 3790 } 3791 3792 default: 3793 process->SetPrivateState(stop_state); 3794 break; 3795 } // switch(stop_state) 3796 } // else // if in All-stop-mode 3797 } // if (continue_packet) 3798 } // case eBroadcastBitAsyncContinue 3799 break; 3800 3801 case eBroadcastBitAsyncThreadShouldExit: 3802 LLDB_LOGF(log, 3803 "ProcessGDBRemote::%s (arg = %p, pid = %" PRIu64 3804 ") got eBroadcastBitAsyncThreadShouldExit...", 3805 __FUNCTION__, arg, process->GetID()); 3806 done = true; 3807 break; 3808 3809 default: 3810 LLDB_LOGF(log, 3811 "ProcessGDBRemote::%s (arg = %p, pid = %" PRIu64 3812 ") got unknown event 0x%8.8x", 3813 __FUNCTION__, arg, process->GetID(), event_type); 3814 done = true; 3815 break; 3816 } 3817 } else if (event_sp->BroadcasterIs(&process->m_gdb_comm)) { 3818 switch (event_type) { 3819 case Communication::eBroadcastBitReadThreadDidExit: 3820 process->SetExitStatus(-1, "lost connection"); 3821 done = true; 3822 break; 3823 3824 case GDBRemoteCommunication::eBroadcastBitGdbReadThreadGotNotify: { 3825 lldb_private::Event *event = event_sp.get(); 3826 const EventDataBytes *continue_packet = 3827 EventDataBytes::GetEventDataFromEvent(event); 3828 StringExtractorGDBRemote notify( 3829 (const char *)continue_packet->GetBytes()); 3830 // Hand this over to the process to handle 3831 process->HandleNotifyPacket(notify); 3832 break; 3833 } 3834 3835 default: 3836 LLDB_LOGF(log, 3837 "ProcessGDBRemote::%s (arg = %p, pid = %" PRIu64 3838 ") got unknown event 0x%8.8x", 3839 __FUNCTION__, arg, process->GetID(), event_type); 3840 done = true; 3841 break; 3842 } 3843 } 3844 } else { 3845 LLDB_LOGF(log, 3846 "ProcessGDBRemote::%s (arg = %p, pid = %" PRIu64 3847 ") listener.WaitForEvent (NULL, event_sp) => false", 3848 __FUNCTION__, arg, process->GetID()); 3849 done = true; 3850 } 3851 } 3852 3853 LLDB_LOGF(log, 3854 "ProcessGDBRemote::%s (arg = %p, pid = %" PRIu64 3855 ") thread exiting...", 3856 __FUNCTION__, arg, process->GetID()); 3857 3858 return {}; 3859 } 3860 3861 // uint32_t 3862 // ProcessGDBRemote::ListProcessesMatchingName (const char *name, StringList 3863 // &matches, std::vector<lldb::pid_t> &pids) 3864 //{ 3865 // // If we are planning to launch the debugserver remotely, then we need to 3866 // fire up a debugserver 3867 // // process and ask it for the list of processes. But if we are local, we 3868 // can let the Host do it. 3869 // if (m_local_debugserver) 3870 // { 3871 // return Host::ListProcessesMatchingName (name, matches, pids); 3872 // } 3873 // else 3874 // { 3875 // // FIXME: Implement talking to the remote debugserver. 3876 // return 0; 3877 // } 3878 // 3879 //} 3880 // 3881 bool ProcessGDBRemote::NewThreadNotifyBreakpointHit( 3882 void *baton, StoppointCallbackContext *context, lldb::user_id_t break_id, 3883 lldb::user_id_t break_loc_id) { 3884 // I don't think I have to do anything here, just make sure I notice the new 3885 // thread when it starts to 3886 // run so I can stop it if that's what I want to do. 3887 Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_STEP)); 3888 LLDB_LOGF(log, "Hit New Thread Notification breakpoint."); 3889 return false; 3890 } 3891 3892 Status ProcessGDBRemote::UpdateAutomaticSignalFiltering() { 3893 Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS)); 3894 LLDB_LOG(log, "Check if need to update ignored signals"); 3895 3896 // QPassSignals package is not supported by the server, there is no way we 3897 // can ignore any signals on server side. 3898 if (!m_gdb_comm.GetQPassSignalsSupported()) 3899 return Status(); 3900 3901 // No signals, nothing to send. 3902 if (m_unix_signals_sp == nullptr) 3903 return Status(); 3904 3905 // Signals' version hasn't changed, no need to send anything. 3906 uint64_t new_signals_version = m_unix_signals_sp->GetVersion(); 3907 if (new_signals_version == m_last_signals_version) { 3908 LLDB_LOG(log, "Signals' version hasn't changed. version={0}", 3909 m_last_signals_version); 3910 return Status(); 3911 } 3912 3913 auto signals_to_ignore = 3914 m_unix_signals_sp->GetFilteredSignals(false, false, false); 3915 Status error = m_gdb_comm.SendSignalsToIgnore(signals_to_ignore); 3916 3917 LLDB_LOG(log, 3918 "Signals' version changed. old version={0}, new version={1}, " 3919 "signals ignored={2}, update result={3}", 3920 m_last_signals_version, new_signals_version, 3921 signals_to_ignore.size(), error); 3922 3923 if (error.Success()) 3924 m_last_signals_version = new_signals_version; 3925 3926 return error; 3927 } 3928 3929 bool ProcessGDBRemote::StartNoticingNewThreads() { 3930 Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_STEP)); 3931 if (m_thread_create_bp_sp) { 3932 if (log && log->GetVerbose()) 3933 LLDB_LOGF(log, "Enabled noticing new thread breakpoint."); 3934 m_thread_create_bp_sp->SetEnabled(true); 3935 } else { 3936 PlatformSP platform_sp(GetTarget().GetPlatform()); 3937 if (platform_sp) { 3938 m_thread_create_bp_sp = 3939 platform_sp->SetThreadCreationBreakpoint(GetTarget()); 3940 if (m_thread_create_bp_sp) { 3941 if (log && log->GetVerbose()) 3942 LLDB_LOGF( 3943 log, "Successfully created new thread notification breakpoint %i", 3944 m_thread_create_bp_sp->GetID()); 3945 m_thread_create_bp_sp->SetCallback( 3946 ProcessGDBRemote::NewThreadNotifyBreakpointHit, this, true); 3947 } else { 3948 LLDB_LOGF(log, "Failed to create new thread notification breakpoint."); 3949 } 3950 } 3951 } 3952 return m_thread_create_bp_sp.get() != nullptr; 3953 } 3954 3955 bool ProcessGDBRemote::StopNoticingNewThreads() { 3956 Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_STEP)); 3957 if (log && log->GetVerbose()) 3958 LLDB_LOGF(log, "Disabling new thread notification breakpoint."); 3959 3960 if (m_thread_create_bp_sp) 3961 m_thread_create_bp_sp->SetEnabled(false); 3962 3963 return true; 3964 } 3965 3966 DynamicLoader *ProcessGDBRemote::GetDynamicLoader() { 3967 if (m_dyld_up.get() == nullptr) 3968 m_dyld_up.reset(DynamicLoader::FindPlugin(this, nullptr)); 3969 return m_dyld_up.get(); 3970 } 3971 3972 Status ProcessGDBRemote::SendEventData(const char *data) { 3973 int return_value; 3974 bool was_supported; 3975 3976 Status error; 3977 3978 return_value = m_gdb_comm.SendLaunchEventDataPacket(data, &was_supported); 3979 if (return_value != 0) { 3980 if (!was_supported) 3981 error.SetErrorString("Sending events is not supported for this process."); 3982 else 3983 error.SetErrorStringWithFormat("Error sending event data: %d.", 3984 return_value); 3985 } 3986 return error; 3987 } 3988 3989 DataExtractor ProcessGDBRemote::GetAuxvData() { 3990 DataBufferSP buf; 3991 if (m_gdb_comm.GetQXferAuxvReadSupported()) { 3992 std::string response_string; 3993 if (m_gdb_comm.SendPacketsAndConcatenateResponses("qXfer:auxv:read::", 3994 response_string) == 3995 GDBRemoteCommunication::PacketResult::Success) 3996 buf = std::make_shared<DataBufferHeap>(response_string.c_str(), 3997 response_string.length()); 3998 } 3999 return DataExtractor(buf, GetByteOrder(), GetAddressByteSize()); 4000 } 4001 4002 StructuredData::ObjectSP 4003 ProcessGDBRemote::GetExtendedInfoForThread(lldb::tid_t tid) { 4004 StructuredData::ObjectSP object_sp; 4005 4006 if (m_gdb_comm.GetThreadExtendedInfoSupported()) { 4007 StructuredData::ObjectSP args_dict(new StructuredData::Dictionary()); 4008 SystemRuntime *runtime = GetSystemRuntime(); 4009 if (runtime) { 4010 runtime->AddThreadExtendedInfoPacketHints(args_dict); 4011 } 4012 args_dict->GetAsDictionary()->AddIntegerItem("thread", tid); 4013 4014 StreamString packet; 4015 packet << "jThreadExtendedInfo:"; 4016 args_dict->Dump(packet, false); 4017 4018 // FIXME the final character of a JSON dictionary, '}', is the escape 4019 // character in gdb-remote binary mode. lldb currently doesn't escape 4020 // these characters in its packet output -- so we add the quoted version of 4021 // the } character here manually in case we talk to a debugserver which un- 4022 // escapes the characters at packet read time. 4023 packet << (char)(0x7d ^ 0x20); 4024 4025 StringExtractorGDBRemote response; 4026 response.SetResponseValidatorToJSON(); 4027 if (m_gdb_comm.SendPacketAndWaitForResponse(packet.GetString(), response, 4028 false) == 4029 GDBRemoteCommunication::PacketResult::Success) { 4030 StringExtractorGDBRemote::ResponseType response_type = 4031 response.GetResponseType(); 4032 if (response_type == StringExtractorGDBRemote::eResponse) { 4033 if (!response.Empty()) { 4034 object_sp = 4035 StructuredData::ParseJSON(std::string(response.GetStringRef())); 4036 } 4037 } 4038 } 4039 } 4040 return object_sp; 4041 } 4042 4043 StructuredData::ObjectSP ProcessGDBRemote::GetLoadedDynamicLibrariesInfos( 4044 lldb::addr_t image_list_address, lldb::addr_t image_count) { 4045 4046 StructuredData::ObjectSP args_dict(new StructuredData::Dictionary()); 4047 args_dict->GetAsDictionary()->AddIntegerItem("image_list_address", 4048 image_list_address); 4049 args_dict->GetAsDictionary()->AddIntegerItem("image_count", image_count); 4050 4051 return GetLoadedDynamicLibrariesInfos_sender(args_dict); 4052 } 4053 4054 StructuredData::ObjectSP ProcessGDBRemote::GetLoadedDynamicLibrariesInfos() { 4055 StructuredData::ObjectSP args_dict(new StructuredData::Dictionary()); 4056 4057 args_dict->GetAsDictionary()->AddBooleanItem("fetch_all_solibs", true); 4058 4059 return GetLoadedDynamicLibrariesInfos_sender(args_dict); 4060 } 4061 4062 StructuredData::ObjectSP ProcessGDBRemote::GetLoadedDynamicLibrariesInfos( 4063 const std::vector<lldb::addr_t> &load_addresses) { 4064 StructuredData::ObjectSP args_dict(new StructuredData::Dictionary()); 4065 StructuredData::ArraySP addresses(new StructuredData::Array); 4066 4067 for (auto addr : load_addresses) { 4068 StructuredData::ObjectSP addr_sp(new StructuredData::Integer(addr)); 4069 addresses->AddItem(addr_sp); 4070 } 4071 4072 args_dict->GetAsDictionary()->AddItem("solib_addresses", addresses); 4073 4074 return GetLoadedDynamicLibrariesInfos_sender(args_dict); 4075 } 4076 4077 StructuredData::ObjectSP 4078 ProcessGDBRemote::GetLoadedDynamicLibrariesInfos_sender( 4079 StructuredData::ObjectSP args_dict) { 4080 StructuredData::ObjectSP object_sp; 4081 4082 if (m_gdb_comm.GetLoadedDynamicLibrariesInfosSupported()) { 4083 // Scope for the scoped timeout object 4084 GDBRemoteCommunication::ScopedTimeout timeout(m_gdb_comm, 4085 std::chrono::seconds(10)); 4086 4087 StreamString packet; 4088 packet << "jGetLoadedDynamicLibrariesInfos:"; 4089 args_dict->Dump(packet, false); 4090 4091 // FIXME the final character of a JSON dictionary, '}', is the escape 4092 // character in gdb-remote binary mode. lldb currently doesn't escape 4093 // these characters in its packet output -- so we add the quoted version of 4094 // the } character here manually in case we talk to a debugserver which un- 4095 // escapes the characters at packet read time. 4096 packet << (char)(0x7d ^ 0x20); 4097 4098 StringExtractorGDBRemote response; 4099 response.SetResponseValidatorToJSON(); 4100 if (m_gdb_comm.SendPacketAndWaitForResponse(packet.GetString(), response, 4101 false) == 4102 GDBRemoteCommunication::PacketResult::Success) { 4103 StringExtractorGDBRemote::ResponseType response_type = 4104 response.GetResponseType(); 4105 if (response_type == StringExtractorGDBRemote::eResponse) { 4106 if (!response.Empty()) { 4107 object_sp = 4108 StructuredData::ParseJSON(std::string(response.GetStringRef())); 4109 } 4110 } 4111 } 4112 } 4113 return object_sp; 4114 } 4115 4116 StructuredData::ObjectSP ProcessGDBRemote::GetSharedCacheInfo() { 4117 StructuredData::ObjectSP object_sp; 4118 StructuredData::ObjectSP args_dict(new StructuredData::Dictionary()); 4119 4120 if (m_gdb_comm.GetSharedCacheInfoSupported()) { 4121 StreamString packet; 4122 packet << "jGetSharedCacheInfo:"; 4123 args_dict->Dump(packet, false); 4124 4125 // FIXME the final character of a JSON dictionary, '}', is the escape 4126 // character in gdb-remote binary mode. lldb currently doesn't escape 4127 // these characters in its packet output -- so we add the quoted version of 4128 // the } character here manually in case we talk to a debugserver which un- 4129 // escapes the characters at packet read time. 4130 packet << (char)(0x7d ^ 0x20); 4131 4132 StringExtractorGDBRemote response; 4133 response.SetResponseValidatorToJSON(); 4134 if (m_gdb_comm.SendPacketAndWaitForResponse(packet.GetString(), response, 4135 false) == 4136 GDBRemoteCommunication::PacketResult::Success) { 4137 StringExtractorGDBRemote::ResponseType response_type = 4138 response.GetResponseType(); 4139 if (response_type == StringExtractorGDBRemote::eResponse) { 4140 if (!response.Empty()) { 4141 object_sp = 4142 StructuredData::ParseJSON(std::string(response.GetStringRef())); 4143 } 4144 } 4145 } 4146 } 4147 return object_sp; 4148 } 4149 4150 Status ProcessGDBRemote::ConfigureStructuredData( 4151 ConstString type_name, const StructuredData::ObjectSP &config_sp) { 4152 return m_gdb_comm.ConfigureRemoteStructuredData(type_name, config_sp); 4153 } 4154 4155 // Establish the largest memory read/write payloads we should use. If the 4156 // remote stub has a max packet size, stay under that size. 4157 // 4158 // If the remote stub's max packet size is crazy large, use a reasonable 4159 // largeish default. 4160 // 4161 // If the remote stub doesn't advertise a max packet size, use a conservative 4162 // default. 4163 4164 void ProcessGDBRemote::GetMaxMemorySize() { 4165 const uint64_t reasonable_largeish_default = 128 * 1024; 4166 const uint64_t conservative_default = 512; 4167 4168 if (m_max_memory_size == 0) { 4169 uint64_t stub_max_size = m_gdb_comm.GetRemoteMaxPacketSize(); 4170 if (stub_max_size != UINT64_MAX && stub_max_size != 0) { 4171 // Save the stub's claimed maximum packet size 4172 m_remote_stub_max_memory_size = stub_max_size; 4173 4174 // Even if the stub says it can support ginormous packets, don't exceed 4175 // our reasonable largeish default packet size. 4176 if (stub_max_size > reasonable_largeish_default) { 4177 stub_max_size = reasonable_largeish_default; 4178 } 4179 4180 // Memory packet have other overheads too like Maddr,size:#NN Instead of 4181 // calculating the bytes taken by size and addr every time, we take a 4182 // maximum guess here. 4183 if (stub_max_size > 70) 4184 stub_max_size -= 32 + 32 + 6; 4185 else { 4186 // In unlikely scenario that max packet size is less then 70, we will 4187 // hope that data being written is small enough to fit. 4188 Log *log(ProcessGDBRemoteLog::GetLogIfAnyCategoryIsSet( 4189 GDBR_LOG_COMM | GDBR_LOG_MEMORY)); 4190 if (log) 4191 log->Warning("Packet size is too small. " 4192 "LLDB may face problems while writing memory"); 4193 } 4194 4195 m_max_memory_size = stub_max_size; 4196 } else { 4197 m_max_memory_size = conservative_default; 4198 } 4199 } 4200 } 4201 4202 void ProcessGDBRemote::SetUserSpecifiedMaxMemoryTransferSize( 4203 uint64_t user_specified_max) { 4204 if (user_specified_max != 0) { 4205 GetMaxMemorySize(); 4206 4207 if (m_remote_stub_max_memory_size != 0) { 4208 if (m_remote_stub_max_memory_size < user_specified_max) { 4209 m_max_memory_size = m_remote_stub_max_memory_size; // user specified a 4210 // packet size too 4211 // big, go as big 4212 // as the remote stub says we can go. 4213 } else { 4214 m_max_memory_size = user_specified_max; // user's packet size is good 4215 } 4216 } else { 4217 m_max_memory_size = 4218 user_specified_max; // user's packet size is probably fine 4219 } 4220 } 4221 } 4222 4223 bool ProcessGDBRemote::GetModuleSpec(const FileSpec &module_file_spec, 4224 const ArchSpec &arch, 4225 ModuleSpec &module_spec) { 4226 Log *log = GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PLATFORM); 4227 4228 const ModuleCacheKey key(module_file_spec.GetPath(), 4229 arch.GetTriple().getTriple()); 4230 auto cached = m_cached_module_specs.find(key); 4231 if (cached != m_cached_module_specs.end()) { 4232 module_spec = cached->second; 4233 return bool(module_spec); 4234 } 4235 4236 if (!m_gdb_comm.GetModuleInfo(module_file_spec, arch, module_spec)) { 4237 LLDB_LOGF(log, "ProcessGDBRemote::%s - failed to get module info for %s:%s", 4238 __FUNCTION__, module_file_spec.GetPath().c_str(), 4239 arch.GetTriple().getTriple().c_str()); 4240 return false; 4241 } 4242 4243 if (log) { 4244 StreamString stream; 4245 module_spec.Dump(stream); 4246 LLDB_LOGF(log, "ProcessGDBRemote::%s - got module info for (%s:%s) : %s", 4247 __FUNCTION__, module_file_spec.GetPath().c_str(), 4248 arch.GetTriple().getTriple().c_str(), stream.GetData()); 4249 } 4250 4251 m_cached_module_specs[key] = module_spec; 4252 return true; 4253 } 4254 4255 void ProcessGDBRemote::PrefetchModuleSpecs( 4256 llvm::ArrayRef<FileSpec> module_file_specs, const llvm::Triple &triple) { 4257 auto module_specs = m_gdb_comm.GetModulesInfo(module_file_specs, triple); 4258 if (module_specs) { 4259 for (const FileSpec &spec : module_file_specs) 4260 m_cached_module_specs[ModuleCacheKey(spec.GetPath(), 4261 triple.getTriple())] = ModuleSpec(); 4262 for (const ModuleSpec &spec : *module_specs) 4263 m_cached_module_specs[ModuleCacheKey(spec.GetFileSpec().GetPath(), 4264 triple.getTriple())] = spec; 4265 } 4266 } 4267 4268 llvm::VersionTuple ProcessGDBRemote::GetHostOSVersion() { 4269 return m_gdb_comm.GetOSVersion(); 4270 } 4271 4272 llvm::VersionTuple ProcessGDBRemote::GetHostMacCatalystVersion() { 4273 return m_gdb_comm.GetMacCatalystVersion(); 4274 } 4275 4276 namespace { 4277 4278 typedef std::vector<std::string> stringVec; 4279 4280 typedef std::vector<struct GdbServerRegisterInfo> GDBServerRegisterVec; 4281 struct RegisterSetInfo { 4282 ConstString name; 4283 }; 4284 4285 typedef std::map<uint32_t, RegisterSetInfo> RegisterSetMap; 4286 4287 struct GdbServerTargetInfo { 4288 std::string arch; 4289 std::string osabi; 4290 stringVec includes; 4291 RegisterSetMap reg_set_map; 4292 }; 4293 4294 bool ParseRegisters(XMLNode feature_node, GdbServerTargetInfo &target_info, 4295 GDBRemoteDynamicRegisterInfo &dyn_reg_info, ABISP abi_sp, 4296 uint32_t ®_num_remote, uint32_t ®_num_local) { 4297 if (!feature_node) 4298 return false; 4299 4300 uint32_t reg_offset = LLDB_INVALID_INDEX32; 4301 feature_node.ForEachChildElementWithName( 4302 "reg", [&target_info, &dyn_reg_info, ®_num_remote, ®_num_local, 4303 ®_offset, &abi_sp](const XMLNode ®_node) -> bool { 4304 std::string gdb_group; 4305 std::string gdb_type; 4306 ConstString reg_name; 4307 ConstString alt_name; 4308 ConstString set_name; 4309 std::vector<uint32_t> value_regs; 4310 std::vector<uint32_t> invalidate_regs; 4311 std::vector<uint8_t> dwarf_opcode_bytes; 4312 bool encoding_set = false; 4313 bool format_set = false; 4314 RegisterInfo reg_info = { 4315 nullptr, // Name 4316 nullptr, // Alt name 4317 0, // byte size 4318 reg_offset, // offset 4319 eEncodingUint, // encoding 4320 eFormatHex, // format 4321 { 4322 LLDB_INVALID_REGNUM, // eh_frame reg num 4323 LLDB_INVALID_REGNUM, // DWARF reg num 4324 LLDB_INVALID_REGNUM, // generic reg num 4325 reg_num_remote, // process plugin reg num 4326 reg_num_local // native register number 4327 }, 4328 nullptr, 4329 nullptr, 4330 nullptr, // Dwarf Expression opcode bytes pointer 4331 0 // Dwarf Expression opcode bytes length 4332 }; 4333 4334 reg_node.ForEachAttribute([&target_info, &gdb_group, &gdb_type, 4335 ®_name, &alt_name, &set_name, &value_regs, 4336 &invalidate_regs, &encoding_set, &format_set, 4337 ®_info, ®_offset, &dwarf_opcode_bytes]( 4338 const llvm::StringRef &name, 4339 const llvm::StringRef &value) -> bool { 4340 if (name == "name") { 4341 reg_name.SetString(value); 4342 } else if (name == "bitsize") { 4343 reg_info.byte_size = 4344 StringConvert::ToUInt32(value.data(), 0, 0) / CHAR_BIT; 4345 } else if (name == "type") { 4346 gdb_type = value.str(); 4347 } else if (name == "group") { 4348 gdb_group = value.str(); 4349 } else if (name == "regnum") { 4350 const uint32_t regnum = 4351 StringConvert::ToUInt32(value.data(), LLDB_INVALID_REGNUM, 0); 4352 if (regnum != LLDB_INVALID_REGNUM) { 4353 reg_info.kinds[eRegisterKindProcessPlugin] = regnum; 4354 } 4355 } else if (name == "offset") { 4356 reg_offset = StringConvert::ToUInt32(value.data(), UINT32_MAX, 0); 4357 } else if (name == "altname") { 4358 alt_name.SetString(value); 4359 } else if (name == "encoding") { 4360 encoding_set = true; 4361 reg_info.encoding = Args::StringToEncoding(value, eEncodingUint); 4362 } else if (name == "format") { 4363 format_set = true; 4364 Format format = eFormatInvalid; 4365 if (OptionArgParser::ToFormat(value.data(), format, nullptr) 4366 .Success()) 4367 reg_info.format = format; 4368 else if (value == "vector-sint8") 4369 reg_info.format = eFormatVectorOfSInt8; 4370 else if (value == "vector-uint8") 4371 reg_info.format = eFormatVectorOfUInt8; 4372 else if (value == "vector-sint16") 4373 reg_info.format = eFormatVectorOfSInt16; 4374 else if (value == "vector-uint16") 4375 reg_info.format = eFormatVectorOfUInt16; 4376 else if (value == "vector-sint32") 4377 reg_info.format = eFormatVectorOfSInt32; 4378 else if (value == "vector-uint32") 4379 reg_info.format = eFormatVectorOfUInt32; 4380 else if (value == "vector-float32") 4381 reg_info.format = eFormatVectorOfFloat32; 4382 else if (value == "vector-uint64") 4383 reg_info.format = eFormatVectorOfUInt64; 4384 else if (value == "vector-uint128") 4385 reg_info.format = eFormatVectorOfUInt128; 4386 } else if (name == "group_id") { 4387 const uint32_t set_id = 4388 StringConvert::ToUInt32(value.data(), UINT32_MAX, 0); 4389 RegisterSetMap::const_iterator pos = 4390 target_info.reg_set_map.find(set_id); 4391 if (pos != target_info.reg_set_map.end()) 4392 set_name = pos->second.name; 4393 } else if (name == "gcc_regnum" || name == "ehframe_regnum") { 4394 reg_info.kinds[eRegisterKindEHFrame] = 4395 StringConvert::ToUInt32(value.data(), LLDB_INVALID_REGNUM, 0); 4396 } else if (name == "dwarf_regnum") { 4397 reg_info.kinds[eRegisterKindDWARF] = 4398 StringConvert::ToUInt32(value.data(), LLDB_INVALID_REGNUM, 0); 4399 } else if (name == "generic") { 4400 reg_info.kinds[eRegisterKindGeneric] = 4401 Args::StringToGenericRegister(value); 4402 } else if (name == "value_regnums") { 4403 SplitCommaSeparatedRegisterNumberString(value, value_regs, 0); 4404 } else if (name == "invalidate_regnums") { 4405 SplitCommaSeparatedRegisterNumberString(value, invalidate_regs, 0); 4406 } else if (name == "dynamic_size_dwarf_expr_bytes") { 4407 std::string opcode_string = value.str(); 4408 size_t dwarf_opcode_len = opcode_string.length() / 2; 4409 assert(dwarf_opcode_len > 0); 4410 4411 dwarf_opcode_bytes.resize(dwarf_opcode_len); 4412 reg_info.dynamic_size_dwarf_len = dwarf_opcode_len; 4413 StringExtractor opcode_extractor(opcode_string); 4414 uint32_t ret_val = 4415 opcode_extractor.GetHexBytesAvail(dwarf_opcode_bytes); 4416 assert(dwarf_opcode_len == ret_val); 4417 UNUSED_IF_ASSERT_DISABLED(ret_val); 4418 reg_info.dynamic_size_dwarf_expr_bytes = dwarf_opcode_bytes.data(); 4419 } else { 4420 printf("unhandled attribute %s = %s\n", name.data(), value.data()); 4421 } 4422 return true; // Keep iterating through all attributes 4423 }); 4424 4425 if (!gdb_type.empty() && !(encoding_set || format_set)) { 4426 if (llvm::StringRef(gdb_type).startswith("int")) { 4427 reg_info.format = eFormatHex; 4428 reg_info.encoding = eEncodingUint; 4429 } else if (gdb_type == "data_ptr" || gdb_type == "code_ptr") { 4430 reg_info.format = eFormatAddressInfo; 4431 reg_info.encoding = eEncodingUint; 4432 } else if (gdb_type == "i387_ext" || gdb_type == "float") { 4433 reg_info.format = eFormatFloat; 4434 reg_info.encoding = eEncodingIEEE754; 4435 } 4436 } 4437 4438 // Only update the register set name if we didn't get a "reg_set" 4439 // attribute. "set_name" will be empty if we didn't have a "reg_set" 4440 // attribute. 4441 if (!set_name) { 4442 if (!gdb_group.empty()) { 4443 set_name.SetCString(gdb_group.c_str()); 4444 } else { 4445 // If no register group name provided anywhere, 4446 // we'll create a 'general' register set 4447 set_name.SetCString("general"); 4448 } 4449 } 4450 4451 reg_info.byte_offset = reg_offset; 4452 assert(reg_info.byte_size != 0); 4453 reg_offset = LLDB_INVALID_INDEX32; 4454 if (!value_regs.empty()) { 4455 value_regs.push_back(LLDB_INVALID_REGNUM); 4456 reg_info.value_regs = value_regs.data(); 4457 } 4458 if (!invalidate_regs.empty()) { 4459 invalidate_regs.push_back(LLDB_INVALID_REGNUM); 4460 reg_info.invalidate_regs = invalidate_regs.data(); 4461 } 4462 4463 reg_num_remote = reg_info.kinds[eRegisterKindProcessPlugin] + 1; 4464 ++reg_num_local; 4465 reg_info.name = reg_name.AsCString(); 4466 if (abi_sp) 4467 abi_sp->AugmentRegisterInfo(reg_info); 4468 dyn_reg_info.AddRegister(reg_info, reg_name, alt_name, set_name); 4469 4470 return true; // Keep iterating through all "reg" elements 4471 }); 4472 return true; 4473 } 4474 4475 } // namespace 4476 4477 // This method fetches a register description feature xml file from 4478 // the remote stub and adds registers/register groupsets/architecture 4479 // information to the current process. It will call itself recursively 4480 // for nested register definition files. It returns true if it was able 4481 // to fetch and parse an xml file. 4482 bool ProcessGDBRemote::GetGDBServerRegisterInfoXMLAndProcess( 4483 ArchSpec &arch_to_use, std::string xml_filename, uint32_t ®_num_remote, 4484 uint32_t ®_num_local) { 4485 // request the target xml file 4486 std::string raw; 4487 lldb_private::Status lldberr; 4488 if (!m_gdb_comm.ReadExtFeature(ConstString("features"), 4489 ConstString(xml_filename.c_str()), raw, 4490 lldberr)) { 4491 return false; 4492 } 4493 4494 XMLDocument xml_document; 4495 4496 if (xml_document.ParseMemory(raw.c_str(), raw.size(), xml_filename.c_str())) { 4497 GdbServerTargetInfo target_info; 4498 std::vector<XMLNode> feature_nodes; 4499 4500 // The top level feature XML file will start with a <target> tag. 4501 XMLNode target_node = xml_document.GetRootElement("target"); 4502 if (target_node) { 4503 target_node.ForEachChildElement([&target_info, &feature_nodes]( 4504 const XMLNode &node) -> bool { 4505 llvm::StringRef name = node.GetName(); 4506 if (name == "architecture") { 4507 node.GetElementText(target_info.arch); 4508 } else if (name == "osabi") { 4509 node.GetElementText(target_info.osabi); 4510 } else if (name == "xi:include" || name == "include") { 4511 llvm::StringRef href = node.GetAttributeValue("href"); 4512 if (!href.empty()) 4513 target_info.includes.push_back(href.str()); 4514 } else if (name == "feature") { 4515 feature_nodes.push_back(node); 4516 } else if (name == "groups") { 4517 node.ForEachChildElementWithName( 4518 "group", [&target_info](const XMLNode &node) -> bool { 4519 uint32_t set_id = UINT32_MAX; 4520 RegisterSetInfo set_info; 4521 4522 node.ForEachAttribute( 4523 [&set_id, &set_info](const llvm::StringRef &name, 4524 const llvm::StringRef &value) -> bool { 4525 if (name == "id") 4526 set_id = StringConvert::ToUInt32(value.data(), 4527 UINT32_MAX, 0); 4528 if (name == "name") 4529 set_info.name = ConstString(value); 4530 return true; // Keep iterating through all attributes 4531 }); 4532 4533 if (set_id != UINT32_MAX) 4534 target_info.reg_set_map[set_id] = set_info; 4535 return true; // Keep iterating through all "group" elements 4536 }); 4537 } 4538 return true; // Keep iterating through all children of the target_node 4539 }); 4540 } else { 4541 // In an included XML feature file, we're already "inside" the <target> 4542 // tag of the initial XML file; this included file will likely only have 4543 // a <feature> tag. Need to check for any more included files in this 4544 // <feature> element. 4545 XMLNode feature_node = xml_document.GetRootElement("feature"); 4546 if (feature_node) { 4547 feature_nodes.push_back(feature_node); 4548 feature_node.ForEachChildElement([&target_info]( 4549 const XMLNode &node) -> bool { 4550 llvm::StringRef name = node.GetName(); 4551 if (name == "xi:include" || name == "include") { 4552 llvm::StringRef href = node.GetAttributeValue("href"); 4553 if (!href.empty()) 4554 target_info.includes.push_back(href.str()); 4555 } 4556 return true; 4557 }); 4558 } 4559 } 4560 4561 // If the target.xml includes an architecture entry like 4562 // <architecture>i386:x86-64</architecture> (seen from VMWare ESXi) 4563 // <architecture>arm</architecture> (seen from Segger JLink on unspecified arm board) 4564 // use that if we don't have anything better. 4565 if (!arch_to_use.IsValid() && !target_info.arch.empty()) { 4566 if (target_info.arch == "i386:x86-64") { 4567 // We don't have any information about vendor or OS. 4568 arch_to_use.SetTriple("x86_64--"); 4569 GetTarget().MergeArchitecture(arch_to_use); 4570 } 4571 4572 // SEGGER J-Link jtag boards send this very-generic arch name, 4573 // we'll need to use this if we have absolutely nothing better 4574 // to work with or the register definitions won't be accepted. 4575 if (target_info.arch == "arm") { 4576 arch_to_use.SetTriple("arm--"); 4577 GetTarget().MergeArchitecture(arch_to_use); 4578 } 4579 } 4580 4581 if (arch_to_use.IsValid()) { 4582 // Don't use Process::GetABI, this code gets called from DidAttach, and 4583 // in that context we haven't set the Target's architecture yet, so the 4584 // ABI is also potentially incorrect. 4585 ABISP abi_to_use_sp = ABI::FindPlugin(shared_from_this(), arch_to_use); 4586 for (auto &feature_node : feature_nodes) { 4587 ParseRegisters(feature_node, target_info, *this->m_register_info_sp, 4588 abi_to_use_sp, reg_num_remote, reg_num_local); 4589 } 4590 4591 for (const auto &include : target_info.includes) { 4592 GetGDBServerRegisterInfoXMLAndProcess(arch_to_use, include, 4593 reg_num_remote, reg_num_local); 4594 } 4595 } 4596 } else { 4597 return false; 4598 } 4599 return true; 4600 } 4601 4602 // query the target of gdb-remote for extended target information returns 4603 // true on success (got register definitions), false on failure (did not). 4604 bool ProcessGDBRemote::GetGDBServerRegisterInfo(ArchSpec &arch_to_use) { 4605 // Make sure LLDB has an XML parser it can use first 4606 if (!XMLDocument::XMLEnabled()) 4607 return false; 4608 4609 // check that we have extended feature read support 4610 if (!m_gdb_comm.GetQXferFeaturesReadSupported()) 4611 return false; 4612 4613 uint32_t reg_num_remote = 0; 4614 uint32_t reg_num_local = 0; 4615 if (GetGDBServerRegisterInfoXMLAndProcess(arch_to_use, "target.xml", 4616 reg_num_remote, reg_num_local)) 4617 this->m_register_info_sp->Finalize(arch_to_use); 4618 4619 return m_register_info_sp->GetNumRegisters() > 0; 4620 } 4621 4622 llvm::Expected<LoadedModuleInfoList> ProcessGDBRemote::GetLoadedModuleList() { 4623 // Make sure LLDB has an XML parser it can use first 4624 if (!XMLDocument::XMLEnabled()) 4625 return llvm::createStringError(llvm::inconvertibleErrorCode(), 4626 "XML parsing not available"); 4627 4628 Log *log = GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS); 4629 LLDB_LOGF(log, "ProcessGDBRemote::%s", __FUNCTION__); 4630 4631 LoadedModuleInfoList list; 4632 GDBRemoteCommunicationClient &comm = m_gdb_comm; 4633 bool can_use_svr4 = GetGlobalPluginProperties()->GetUseSVR4(); 4634 4635 // check that we have extended feature read support 4636 if (can_use_svr4 && comm.GetQXferLibrariesSVR4ReadSupported()) { 4637 // request the loaded library list 4638 std::string raw; 4639 lldb_private::Status lldberr; 4640 4641 if (!comm.ReadExtFeature(ConstString("libraries-svr4"), ConstString(""), 4642 raw, lldberr)) 4643 return llvm::createStringError(llvm::inconvertibleErrorCode(), 4644 "Error in libraries-svr4 packet"); 4645 4646 // parse the xml file in memory 4647 LLDB_LOGF(log, "parsing: %s", raw.c_str()); 4648 XMLDocument doc; 4649 4650 if (!doc.ParseMemory(raw.c_str(), raw.size(), "noname.xml")) 4651 return llvm::createStringError(llvm::inconvertibleErrorCode(), 4652 "Error reading noname.xml"); 4653 4654 XMLNode root_element = doc.GetRootElement("library-list-svr4"); 4655 if (!root_element) 4656 return llvm::createStringError( 4657 llvm::inconvertibleErrorCode(), 4658 "Error finding library-list-svr4 xml element"); 4659 4660 // main link map structure 4661 llvm::StringRef main_lm = root_element.GetAttributeValue("main-lm"); 4662 if (!main_lm.empty()) { 4663 list.m_link_map = 4664 StringConvert::ToUInt64(main_lm.data(), LLDB_INVALID_ADDRESS, 0); 4665 } 4666 4667 root_element.ForEachChildElementWithName( 4668 "library", [log, &list](const XMLNode &library) -> bool { 4669 4670 LoadedModuleInfoList::LoadedModuleInfo module; 4671 4672 library.ForEachAttribute( 4673 [&module](const llvm::StringRef &name, 4674 const llvm::StringRef &value) -> bool { 4675 4676 if (name == "name") 4677 module.set_name(value.str()); 4678 else if (name == "lm") { 4679 // the address of the link_map struct. 4680 module.set_link_map(StringConvert::ToUInt64( 4681 value.data(), LLDB_INVALID_ADDRESS, 0)); 4682 } else if (name == "l_addr") { 4683 // the displacement as read from the field 'l_addr' of the 4684 // link_map struct. 4685 module.set_base(StringConvert::ToUInt64( 4686 value.data(), LLDB_INVALID_ADDRESS, 0)); 4687 // base address is always a displacement, not an absolute 4688 // value. 4689 module.set_base_is_offset(true); 4690 } else if (name == "l_ld") { 4691 // the memory address of the libraries PT_DYNAMIC section. 4692 module.set_dynamic(StringConvert::ToUInt64( 4693 value.data(), LLDB_INVALID_ADDRESS, 0)); 4694 } 4695 4696 return true; // Keep iterating over all properties of "library" 4697 }); 4698 4699 if (log) { 4700 std::string name; 4701 lldb::addr_t lm = 0, base = 0, ld = 0; 4702 bool base_is_offset; 4703 4704 module.get_name(name); 4705 module.get_link_map(lm); 4706 module.get_base(base); 4707 module.get_base_is_offset(base_is_offset); 4708 module.get_dynamic(ld); 4709 4710 LLDB_LOGF(log, 4711 "found (link_map:0x%08" PRIx64 ", base:0x%08" PRIx64 4712 "[%s], ld:0x%08" PRIx64 ", name:'%s')", 4713 lm, base, (base_is_offset ? "offset" : "absolute"), ld, 4714 name.c_str()); 4715 } 4716 4717 list.add(module); 4718 return true; // Keep iterating over all "library" elements in the root 4719 // node 4720 }); 4721 4722 if (log) 4723 LLDB_LOGF(log, "found %" PRId32 " modules in total", 4724 (int)list.m_list.size()); 4725 return list; 4726 } else if (comm.GetQXferLibrariesReadSupported()) { 4727 // request the loaded library list 4728 std::string raw; 4729 lldb_private::Status lldberr; 4730 4731 if (!comm.ReadExtFeature(ConstString("libraries"), ConstString(""), raw, 4732 lldberr)) 4733 return llvm::createStringError(llvm::inconvertibleErrorCode(), 4734 "Error in libraries packet"); 4735 4736 LLDB_LOGF(log, "parsing: %s", raw.c_str()); 4737 XMLDocument doc; 4738 4739 if (!doc.ParseMemory(raw.c_str(), raw.size(), "noname.xml")) 4740 return llvm::createStringError(llvm::inconvertibleErrorCode(), 4741 "Error reading noname.xml"); 4742 4743 XMLNode root_element = doc.GetRootElement("library-list"); 4744 if (!root_element) 4745 return llvm::createStringError(llvm::inconvertibleErrorCode(), 4746 "Error finding library-list xml element"); 4747 4748 root_element.ForEachChildElementWithName( 4749 "library", [log, &list](const XMLNode &library) -> bool { 4750 LoadedModuleInfoList::LoadedModuleInfo module; 4751 4752 llvm::StringRef name = library.GetAttributeValue("name"); 4753 module.set_name(name.str()); 4754 4755 // The base address of a given library will be the address of its 4756 // first section. Most remotes send only one section for Windows 4757 // targets for example. 4758 const XMLNode §ion = 4759 library.FindFirstChildElementWithName("section"); 4760 llvm::StringRef address = section.GetAttributeValue("address"); 4761 module.set_base( 4762 StringConvert::ToUInt64(address.data(), LLDB_INVALID_ADDRESS, 0)); 4763 // These addresses are absolute values. 4764 module.set_base_is_offset(false); 4765 4766 if (log) { 4767 std::string name; 4768 lldb::addr_t base = 0; 4769 bool base_is_offset; 4770 module.get_name(name); 4771 module.get_base(base); 4772 module.get_base_is_offset(base_is_offset); 4773 4774 LLDB_LOGF(log, "found (base:0x%08" PRIx64 "[%s], name:'%s')", base, 4775 (base_is_offset ? "offset" : "absolute"), name.c_str()); 4776 } 4777 4778 list.add(module); 4779 return true; // Keep iterating over all "library" elements in the root 4780 // node 4781 }); 4782 4783 if (log) 4784 LLDB_LOGF(log, "found %" PRId32 " modules in total", 4785 (int)list.m_list.size()); 4786 return list; 4787 } else { 4788 return llvm::createStringError(llvm::inconvertibleErrorCode(), 4789 "Remote libraries not supported"); 4790 } 4791 } 4792 4793 lldb::ModuleSP ProcessGDBRemote::LoadModuleAtAddress(const FileSpec &file, 4794 lldb::addr_t link_map, 4795 lldb::addr_t base_addr, 4796 bool value_is_offset) { 4797 DynamicLoader *loader = GetDynamicLoader(); 4798 if (!loader) 4799 return nullptr; 4800 4801 return loader->LoadModuleAtAddress(file, link_map, base_addr, 4802 value_is_offset); 4803 } 4804 4805 llvm::Error ProcessGDBRemote::LoadModules() { 4806 using lldb_private::process_gdb_remote::ProcessGDBRemote; 4807 4808 // request a list of loaded libraries from GDBServer 4809 llvm::Expected<LoadedModuleInfoList> module_list = GetLoadedModuleList(); 4810 if (!module_list) 4811 return module_list.takeError(); 4812 4813 // get a list of all the modules 4814 ModuleList new_modules; 4815 4816 for (LoadedModuleInfoList::LoadedModuleInfo &modInfo : module_list->m_list) { 4817 std::string mod_name; 4818 lldb::addr_t mod_base; 4819 lldb::addr_t link_map; 4820 bool mod_base_is_offset; 4821 4822 bool valid = true; 4823 valid &= modInfo.get_name(mod_name); 4824 valid &= modInfo.get_base(mod_base); 4825 valid &= modInfo.get_base_is_offset(mod_base_is_offset); 4826 if (!valid) 4827 continue; 4828 4829 if (!modInfo.get_link_map(link_map)) 4830 link_map = LLDB_INVALID_ADDRESS; 4831 4832 FileSpec file(mod_name); 4833 FileSystem::Instance().Resolve(file); 4834 lldb::ModuleSP module_sp = 4835 LoadModuleAtAddress(file, link_map, mod_base, mod_base_is_offset); 4836 4837 if (module_sp.get()) 4838 new_modules.Append(module_sp); 4839 } 4840 4841 if (new_modules.GetSize() > 0) { 4842 ModuleList removed_modules; 4843 Target &target = GetTarget(); 4844 ModuleList &loaded_modules = m_process->GetTarget().GetImages(); 4845 4846 for (size_t i = 0; i < loaded_modules.GetSize(); ++i) { 4847 const lldb::ModuleSP loaded_module = loaded_modules.GetModuleAtIndex(i); 4848 4849 bool found = false; 4850 for (size_t j = 0; j < new_modules.GetSize(); ++j) { 4851 if (new_modules.GetModuleAtIndex(j).get() == loaded_module.get()) 4852 found = true; 4853 } 4854 4855 // The main executable will never be included in libraries-svr4, don't 4856 // remove it 4857 if (!found && 4858 loaded_module.get() != target.GetExecutableModulePointer()) { 4859 removed_modules.Append(loaded_module); 4860 } 4861 } 4862 4863 loaded_modules.Remove(removed_modules); 4864 m_process->GetTarget().ModulesDidUnload(removed_modules, false); 4865 4866 new_modules.ForEach([&target](const lldb::ModuleSP module_sp) -> bool { 4867 lldb_private::ObjectFile *obj = module_sp->GetObjectFile(); 4868 if (!obj) 4869 return true; 4870 4871 if (obj->GetType() != ObjectFile::Type::eTypeExecutable) 4872 return true; 4873 4874 lldb::ModuleSP module_copy_sp = module_sp; 4875 target.SetExecutableModule(module_copy_sp, eLoadDependentsNo); 4876 return false; 4877 }); 4878 4879 loaded_modules.AppendIfNeeded(new_modules); 4880 m_process->GetTarget().ModulesDidLoad(new_modules); 4881 } 4882 4883 return llvm::ErrorSuccess(); 4884 } 4885 4886 Status ProcessGDBRemote::GetFileLoadAddress(const FileSpec &file, 4887 bool &is_loaded, 4888 lldb::addr_t &load_addr) { 4889 is_loaded = false; 4890 load_addr = LLDB_INVALID_ADDRESS; 4891 4892 std::string file_path = file.GetPath(false); 4893 if (file_path.empty()) 4894 return Status("Empty file name specified"); 4895 4896 StreamString packet; 4897 packet.PutCString("qFileLoadAddress:"); 4898 packet.PutStringAsRawHex8(file_path); 4899 4900 StringExtractorGDBRemote response; 4901 if (m_gdb_comm.SendPacketAndWaitForResponse(packet.GetString(), response, 4902 false) != 4903 GDBRemoteCommunication::PacketResult::Success) 4904 return Status("Sending qFileLoadAddress packet failed"); 4905 4906 if (response.IsErrorResponse()) { 4907 if (response.GetError() == 1) { 4908 // The file is not loaded into the inferior 4909 is_loaded = false; 4910 load_addr = LLDB_INVALID_ADDRESS; 4911 return Status(); 4912 } 4913 4914 return Status( 4915 "Fetching file load address from remote server returned an error"); 4916 } 4917 4918 if (response.IsNormalResponse()) { 4919 is_loaded = true; 4920 load_addr = response.GetHexMaxU64(false, LLDB_INVALID_ADDRESS); 4921 return Status(); 4922 } 4923 4924 return Status( 4925 "Unknown error happened during sending the load address packet"); 4926 } 4927 4928 void ProcessGDBRemote::ModulesDidLoad(ModuleList &module_list) { 4929 // We must call the lldb_private::Process::ModulesDidLoad () first before we 4930 // do anything 4931 Process::ModulesDidLoad(module_list); 4932 4933 // After loading shared libraries, we can ask our remote GDB server if it 4934 // needs any symbols. 4935 m_gdb_comm.ServeSymbolLookups(this); 4936 } 4937 4938 void ProcessGDBRemote::HandleAsyncStdout(llvm::StringRef out) { 4939 AppendSTDOUT(out.data(), out.size()); 4940 } 4941 4942 static const char *end_delimiter = "--end--;"; 4943 static const int end_delimiter_len = 8; 4944 4945 void ProcessGDBRemote::HandleAsyncMisc(llvm::StringRef data) { 4946 std::string input = data.str(); // '1' to move beyond 'A' 4947 if (m_partial_profile_data.length() > 0) { 4948 m_partial_profile_data.append(input); 4949 input = m_partial_profile_data; 4950 m_partial_profile_data.clear(); 4951 } 4952 4953 size_t found, pos = 0, len = input.length(); 4954 while ((found = input.find(end_delimiter, pos)) != std::string::npos) { 4955 StringExtractorGDBRemote profileDataExtractor( 4956 input.substr(pos, found).c_str()); 4957 std::string profile_data = 4958 HarmonizeThreadIdsForProfileData(profileDataExtractor); 4959 BroadcastAsyncProfileData(profile_data); 4960 4961 pos = found + end_delimiter_len; 4962 } 4963 4964 if (pos < len) { 4965 // Last incomplete chunk. 4966 m_partial_profile_data = input.substr(pos); 4967 } 4968 } 4969 4970 std::string ProcessGDBRemote::HarmonizeThreadIdsForProfileData( 4971 StringExtractorGDBRemote &profileDataExtractor) { 4972 std::map<uint64_t, uint32_t> new_thread_id_to_used_usec_map; 4973 std::string output; 4974 llvm::raw_string_ostream output_stream(output); 4975 llvm::StringRef name, value; 4976 4977 // Going to assuming thread_used_usec comes first, else bail out. 4978 while (profileDataExtractor.GetNameColonValue(name, value)) { 4979 if (name.compare("thread_used_id") == 0) { 4980 StringExtractor threadIDHexExtractor(value); 4981 uint64_t thread_id = threadIDHexExtractor.GetHexMaxU64(false, 0); 4982 4983 bool has_used_usec = false; 4984 uint32_t curr_used_usec = 0; 4985 llvm::StringRef usec_name, usec_value; 4986 uint32_t input_file_pos = profileDataExtractor.GetFilePos(); 4987 if (profileDataExtractor.GetNameColonValue(usec_name, usec_value)) { 4988 if (usec_name.equals("thread_used_usec")) { 4989 has_used_usec = true; 4990 usec_value.getAsInteger(0, curr_used_usec); 4991 } else { 4992 // We didn't find what we want, it is probably an older version. Bail 4993 // out. 4994 profileDataExtractor.SetFilePos(input_file_pos); 4995 } 4996 } 4997 4998 if (has_used_usec) { 4999 uint32_t prev_used_usec = 0; 5000 std::map<uint64_t, uint32_t>::iterator iterator = 5001 m_thread_id_to_used_usec_map.find(thread_id); 5002 if (iterator != m_thread_id_to_used_usec_map.end()) { 5003 prev_used_usec = m_thread_id_to_used_usec_map[thread_id]; 5004 } 5005 5006 uint32_t real_used_usec = curr_used_usec - prev_used_usec; 5007 // A good first time record is one that runs for at least 0.25 sec 5008 bool good_first_time = 5009 (prev_used_usec == 0) && (real_used_usec > 250000); 5010 bool good_subsequent_time = 5011 (prev_used_usec > 0) && 5012 ((real_used_usec > 0) || (HasAssignedIndexIDToThread(thread_id))); 5013 5014 if (good_first_time || good_subsequent_time) { 5015 // We try to avoid doing too many index id reservation, resulting in 5016 // fast increase of index ids. 5017 5018 output_stream << name << ":"; 5019 int32_t index_id = AssignIndexIDToThread(thread_id); 5020 output_stream << index_id << ";"; 5021 5022 output_stream << usec_name << ":" << usec_value << ";"; 5023 } else { 5024 // Skip past 'thread_used_name'. 5025 llvm::StringRef local_name, local_value; 5026 profileDataExtractor.GetNameColonValue(local_name, local_value); 5027 } 5028 5029 // Store current time as previous time so that they can be compared 5030 // later. 5031 new_thread_id_to_used_usec_map[thread_id] = curr_used_usec; 5032 } else { 5033 // Bail out and use old string. 5034 output_stream << name << ":" << value << ";"; 5035 } 5036 } else { 5037 output_stream << name << ":" << value << ";"; 5038 } 5039 } 5040 output_stream << end_delimiter; 5041 m_thread_id_to_used_usec_map = new_thread_id_to_used_usec_map; 5042 5043 return output_stream.str(); 5044 } 5045 5046 void ProcessGDBRemote::HandleStopReply() { 5047 if (GetStopID() != 0) 5048 return; 5049 5050 if (GetID() == LLDB_INVALID_PROCESS_ID) { 5051 lldb::pid_t pid = m_gdb_comm.GetCurrentProcessID(); 5052 if (pid != LLDB_INVALID_PROCESS_ID) 5053 SetID(pid); 5054 } 5055 BuildDynamicRegisterInfo(true); 5056 } 5057 5058 static const char *const s_async_json_packet_prefix = "JSON-async:"; 5059 5060 static StructuredData::ObjectSP 5061 ParseStructuredDataPacket(llvm::StringRef packet) { 5062 Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS)); 5063 5064 if (!packet.consume_front(s_async_json_packet_prefix)) { 5065 if (log) { 5066 LLDB_LOGF( 5067 log, 5068 "GDBRemoteCommunicationClientBase::%s() received $J packet " 5069 "but was not a StructuredData packet: packet starts with " 5070 "%s", 5071 __FUNCTION__, 5072 packet.slice(0, strlen(s_async_json_packet_prefix)).str().c_str()); 5073 } 5074 return StructuredData::ObjectSP(); 5075 } 5076 5077 // This is an asynchronous JSON packet, destined for a StructuredDataPlugin. 5078 StructuredData::ObjectSP json_sp = 5079 StructuredData::ParseJSON(std::string(packet)); 5080 if (log) { 5081 if (json_sp) { 5082 StreamString json_str; 5083 json_sp->Dump(json_str, true); 5084 json_str.Flush(); 5085 LLDB_LOGF(log, 5086 "ProcessGDBRemote::%s() " 5087 "received Async StructuredData packet: %s", 5088 __FUNCTION__, json_str.GetData()); 5089 } else { 5090 LLDB_LOGF(log, 5091 "ProcessGDBRemote::%s" 5092 "() received StructuredData packet:" 5093 " parse failure", 5094 __FUNCTION__); 5095 } 5096 } 5097 return json_sp; 5098 } 5099 5100 void ProcessGDBRemote::HandleAsyncStructuredDataPacket(llvm::StringRef data) { 5101 auto structured_data_sp = ParseStructuredDataPacket(data); 5102 if (structured_data_sp) 5103 RouteAsyncStructuredData(structured_data_sp); 5104 } 5105 5106 class CommandObjectProcessGDBRemoteSpeedTest : public CommandObjectParsed { 5107 public: 5108 CommandObjectProcessGDBRemoteSpeedTest(CommandInterpreter &interpreter) 5109 : CommandObjectParsed(interpreter, "process plugin packet speed-test", 5110 "Tests packet speeds of various sizes to determine " 5111 "the performance characteristics of the GDB remote " 5112 "connection. ", 5113 nullptr), 5114 m_option_group(), 5115 m_num_packets(LLDB_OPT_SET_1, false, "count", 'c', 0, eArgTypeCount, 5116 "The number of packets to send of each varying size " 5117 "(default is 1000).", 5118 1000), 5119 m_max_send(LLDB_OPT_SET_1, false, "max-send", 's', 0, eArgTypeCount, 5120 "The maximum number of bytes to send in a packet. Sizes " 5121 "increase in powers of 2 while the size is less than or " 5122 "equal to this option value. (default 1024).", 5123 1024), 5124 m_max_recv(LLDB_OPT_SET_1, false, "max-receive", 'r', 0, eArgTypeCount, 5125 "The maximum number of bytes to receive in a packet. Sizes " 5126 "increase in powers of 2 while the size is less than or " 5127 "equal to this option value. (default 1024).", 5128 1024), 5129 m_json(LLDB_OPT_SET_1, false, "json", 'j', 5130 "Print the output as JSON data for easy parsing.", false, true) { 5131 m_option_group.Append(&m_num_packets, LLDB_OPT_SET_ALL, LLDB_OPT_SET_1); 5132 m_option_group.Append(&m_max_send, LLDB_OPT_SET_ALL, LLDB_OPT_SET_1); 5133 m_option_group.Append(&m_max_recv, LLDB_OPT_SET_ALL, LLDB_OPT_SET_1); 5134 m_option_group.Append(&m_json, LLDB_OPT_SET_ALL, LLDB_OPT_SET_1); 5135 m_option_group.Finalize(); 5136 } 5137 5138 ~CommandObjectProcessGDBRemoteSpeedTest() override {} 5139 5140 Options *GetOptions() override { return &m_option_group; } 5141 5142 bool DoExecute(Args &command, CommandReturnObject &result) override { 5143 const size_t argc = command.GetArgumentCount(); 5144 if (argc == 0) { 5145 ProcessGDBRemote *process = 5146 (ProcessGDBRemote *)m_interpreter.GetExecutionContext() 5147 .GetProcessPtr(); 5148 if (process) { 5149 StreamSP output_stream_sp( 5150 m_interpreter.GetDebugger().GetAsyncOutputStream()); 5151 result.SetImmediateOutputStream(output_stream_sp); 5152 5153 const uint32_t num_packets = 5154 (uint32_t)m_num_packets.GetOptionValue().GetCurrentValue(); 5155 const uint64_t max_send = m_max_send.GetOptionValue().GetCurrentValue(); 5156 const uint64_t max_recv = m_max_recv.GetOptionValue().GetCurrentValue(); 5157 const bool json = m_json.GetOptionValue().GetCurrentValue(); 5158 const uint64_t k_recv_amount = 5159 4 * 1024 * 1024; // Receive amount in bytes 5160 process->GetGDBRemote().TestPacketSpeed( 5161 num_packets, max_send, max_recv, k_recv_amount, json, 5162 output_stream_sp ? *output_stream_sp : result.GetOutputStream()); 5163 result.SetStatus(eReturnStatusSuccessFinishResult); 5164 return true; 5165 } 5166 } else { 5167 result.AppendErrorWithFormat("'%s' takes no arguments", 5168 m_cmd_name.c_str()); 5169 } 5170 result.SetStatus(eReturnStatusFailed); 5171 return false; 5172 } 5173 5174 protected: 5175 OptionGroupOptions m_option_group; 5176 OptionGroupUInt64 m_num_packets; 5177 OptionGroupUInt64 m_max_send; 5178 OptionGroupUInt64 m_max_recv; 5179 OptionGroupBoolean m_json; 5180 }; 5181 5182 class CommandObjectProcessGDBRemotePacketHistory : public CommandObjectParsed { 5183 private: 5184 public: 5185 CommandObjectProcessGDBRemotePacketHistory(CommandInterpreter &interpreter) 5186 : CommandObjectParsed(interpreter, "process plugin packet history", 5187 "Dumps the packet history buffer. ", nullptr) {} 5188 5189 ~CommandObjectProcessGDBRemotePacketHistory() override {} 5190 5191 bool DoExecute(Args &command, CommandReturnObject &result) override { 5192 const size_t argc = command.GetArgumentCount(); 5193 if (argc == 0) { 5194 ProcessGDBRemote *process = 5195 (ProcessGDBRemote *)m_interpreter.GetExecutionContext() 5196 .GetProcessPtr(); 5197 if (process) { 5198 process->GetGDBRemote().DumpHistory(result.GetOutputStream()); 5199 result.SetStatus(eReturnStatusSuccessFinishResult); 5200 return true; 5201 } 5202 } else { 5203 result.AppendErrorWithFormat("'%s' takes no arguments", 5204 m_cmd_name.c_str()); 5205 } 5206 result.SetStatus(eReturnStatusFailed); 5207 return false; 5208 } 5209 }; 5210 5211 class CommandObjectProcessGDBRemotePacketXferSize : public CommandObjectParsed { 5212 private: 5213 public: 5214 CommandObjectProcessGDBRemotePacketXferSize(CommandInterpreter &interpreter) 5215 : CommandObjectParsed( 5216 interpreter, "process plugin packet xfer-size", 5217 "Maximum size that lldb will try to read/write one one chunk.", 5218 nullptr) {} 5219 5220 ~CommandObjectProcessGDBRemotePacketXferSize() override {} 5221 5222 bool DoExecute(Args &command, CommandReturnObject &result) override { 5223 const size_t argc = command.GetArgumentCount(); 5224 if (argc == 0) { 5225 result.AppendErrorWithFormat("'%s' takes an argument to specify the max " 5226 "amount to be transferred when " 5227 "reading/writing", 5228 m_cmd_name.c_str()); 5229 result.SetStatus(eReturnStatusFailed); 5230 return false; 5231 } 5232 5233 ProcessGDBRemote *process = 5234 (ProcessGDBRemote *)m_interpreter.GetExecutionContext().GetProcessPtr(); 5235 if (process) { 5236 const char *packet_size = command.GetArgumentAtIndex(0); 5237 errno = 0; 5238 uint64_t user_specified_max = strtoul(packet_size, nullptr, 10); 5239 if (errno == 0 && user_specified_max != 0) { 5240 process->SetUserSpecifiedMaxMemoryTransferSize(user_specified_max); 5241 result.SetStatus(eReturnStatusSuccessFinishResult); 5242 return true; 5243 } 5244 } 5245 result.SetStatus(eReturnStatusFailed); 5246 return false; 5247 } 5248 }; 5249 5250 class CommandObjectProcessGDBRemotePacketSend : public CommandObjectParsed { 5251 private: 5252 public: 5253 CommandObjectProcessGDBRemotePacketSend(CommandInterpreter &interpreter) 5254 : CommandObjectParsed(interpreter, "process plugin packet send", 5255 "Send a custom packet through the GDB remote " 5256 "protocol and print the answer. " 5257 "The packet header and footer will automatically " 5258 "be added to the packet prior to sending and " 5259 "stripped from the result.", 5260 nullptr) {} 5261 5262 ~CommandObjectProcessGDBRemotePacketSend() override {} 5263 5264 bool DoExecute(Args &command, CommandReturnObject &result) override { 5265 const size_t argc = command.GetArgumentCount(); 5266 if (argc == 0) { 5267 result.AppendErrorWithFormat( 5268 "'%s' takes a one or more packet content arguments", 5269 m_cmd_name.c_str()); 5270 result.SetStatus(eReturnStatusFailed); 5271 return false; 5272 } 5273 5274 ProcessGDBRemote *process = 5275 (ProcessGDBRemote *)m_interpreter.GetExecutionContext().GetProcessPtr(); 5276 if (process) { 5277 for (size_t i = 0; i < argc; ++i) { 5278 const char *packet_cstr = command.GetArgumentAtIndex(0); 5279 bool send_async = true; 5280 StringExtractorGDBRemote response; 5281 process->GetGDBRemote().SendPacketAndWaitForResponse( 5282 packet_cstr, response, send_async); 5283 result.SetStatus(eReturnStatusSuccessFinishResult); 5284 Stream &output_strm = result.GetOutputStream(); 5285 output_strm.Printf(" packet: %s\n", packet_cstr); 5286 std::string response_str = std::string(response.GetStringRef()); 5287 5288 if (strstr(packet_cstr, "qGetProfileData") != nullptr) { 5289 response_str = process->HarmonizeThreadIdsForProfileData(response); 5290 } 5291 5292 if (response_str.empty()) 5293 output_strm.PutCString("response: \nerror: UNIMPLEMENTED\n"); 5294 else 5295 output_strm.Printf("response: %s\n", response.GetStringRef().data()); 5296 } 5297 } 5298 return true; 5299 } 5300 }; 5301 5302 class CommandObjectProcessGDBRemotePacketMonitor : public CommandObjectRaw { 5303 private: 5304 public: 5305 CommandObjectProcessGDBRemotePacketMonitor(CommandInterpreter &interpreter) 5306 : CommandObjectRaw(interpreter, "process plugin packet monitor", 5307 "Send a qRcmd packet through the GDB remote protocol " 5308 "and print the response." 5309 "The argument passed to this command will be hex " 5310 "encoded into a valid 'qRcmd' packet, sent and the " 5311 "response will be printed.") {} 5312 5313 ~CommandObjectProcessGDBRemotePacketMonitor() override {} 5314 5315 bool DoExecute(llvm::StringRef command, 5316 CommandReturnObject &result) override { 5317 if (command.empty()) { 5318 result.AppendErrorWithFormat("'%s' takes a command string argument", 5319 m_cmd_name.c_str()); 5320 result.SetStatus(eReturnStatusFailed); 5321 return false; 5322 } 5323 5324 ProcessGDBRemote *process = 5325 (ProcessGDBRemote *)m_interpreter.GetExecutionContext().GetProcessPtr(); 5326 if (process) { 5327 StreamString packet; 5328 packet.PutCString("qRcmd,"); 5329 packet.PutBytesAsRawHex8(command.data(), command.size()); 5330 5331 bool send_async = true; 5332 StringExtractorGDBRemote response; 5333 Stream &output_strm = result.GetOutputStream(); 5334 process->GetGDBRemote().SendPacketAndReceiveResponseWithOutputSupport( 5335 packet.GetString(), response, send_async, 5336 [&output_strm](llvm::StringRef output) { output_strm << output; }); 5337 result.SetStatus(eReturnStatusSuccessFinishResult); 5338 output_strm.Printf(" packet: %s\n", packet.GetData()); 5339 const std::string &response_str = std::string(response.GetStringRef()); 5340 5341 if (response_str.empty()) 5342 output_strm.PutCString("response: \nerror: UNIMPLEMENTED\n"); 5343 else 5344 output_strm.Printf("response: %s\n", response.GetStringRef().data()); 5345 } 5346 return true; 5347 } 5348 }; 5349 5350 class CommandObjectProcessGDBRemotePacket : public CommandObjectMultiword { 5351 private: 5352 public: 5353 CommandObjectProcessGDBRemotePacket(CommandInterpreter &interpreter) 5354 : CommandObjectMultiword(interpreter, "process plugin packet", 5355 "Commands that deal with GDB remote packets.", 5356 nullptr) { 5357 LoadSubCommand( 5358 "history", 5359 CommandObjectSP( 5360 new CommandObjectProcessGDBRemotePacketHistory(interpreter))); 5361 LoadSubCommand( 5362 "send", CommandObjectSP( 5363 new CommandObjectProcessGDBRemotePacketSend(interpreter))); 5364 LoadSubCommand( 5365 "monitor", 5366 CommandObjectSP( 5367 new CommandObjectProcessGDBRemotePacketMonitor(interpreter))); 5368 LoadSubCommand( 5369 "xfer-size", 5370 CommandObjectSP( 5371 new CommandObjectProcessGDBRemotePacketXferSize(interpreter))); 5372 LoadSubCommand("speed-test", 5373 CommandObjectSP(new CommandObjectProcessGDBRemoteSpeedTest( 5374 interpreter))); 5375 } 5376 5377 ~CommandObjectProcessGDBRemotePacket() override {} 5378 }; 5379 5380 class CommandObjectMultiwordProcessGDBRemote : public CommandObjectMultiword { 5381 public: 5382 CommandObjectMultiwordProcessGDBRemote(CommandInterpreter &interpreter) 5383 : CommandObjectMultiword( 5384 interpreter, "process plugin", 5385 "Commands for operating on a ProcessGDBRemote process.", 5386 "process plugin <subcommand> [<subcommand-options>]") { 5387 LoadSubCommand( 5388 "packet", 5389 CommandObjectSP(new CommandObjectProcessGDBRemotePacket(interpreter))); 5390 } 5391 5392 ~CommandObjectMultiwordProcessGDBRemote() override {} 5393 }; 5394 5395 CommandObject *ProcessGDBRemote::GetPluginCommandObject() { 5396 if (!m_command_sp) 5397 m_command_sp = std::make_shared<CommandObjectMultiwordProcessGDBRemote>( 5398 GetTarget().GetDebugger().GetCommandInterpreter()); 5399 return m_command_sp.get(); 5400 } 5401