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