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