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