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