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