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