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