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