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