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