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>( 183 history_file.GetPath(), EC, sys::fs::OpenFlags::OF_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 std::this_thread::sleep_for(std::chrono::milliseconds(100)); 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 std::this_thread::sleep_for(std::chrono::milliseconds(500)); 3595 3596 // If our process hasn't yet exited, debugserver might have died. If the 3597 // process did exit, then we are reaping it. 3598 const StateType state = process_sp->GetState(); 3599 3600 if (state != eStateInvalid && state != eStateUnloaded && 3601 state != eStateExited && state != eStateDetached) { 3602 char error_str[1024]; 3603 if (signo) { 3604 const char *signal_cstr = 3605 process_sp->GetUnixSignals()->GetSignalAsCString(signo); 3606 if (signal_cstr) 3607 ::snprintf(error_str, sizeof(error_str), 3608 DEBUGSERVER_BASENAME " died with signal %s", signal_cstr); 3609 else 3610 ::snprintf(error_str, sizeof(error_str), 3611 DEBUGSERVER_BASENAME " died with signal %i", signo); 3612 } else { 3613 ::snprintf(error_str, sizeof(error_str), 3614 DEBUGSERVER_BASENAME " died with an exit status of 0x%8.8x", 3615 exit_status); 3616 } 3617 3618 process_sp->SetExitStatus(-1, error_str); 3619 } 3620 // Debugserver has exited we need to let our ProcessGDBRemote know that it no 3621 // longer has a debugserver instance 3622 process_sp->m_debugserver_pid = LLDB_INVALID_PROCESS_ID; 3623 return handled; 3624 } 3625 3626 void ProcessGDBRemote::KillDebugserverProcess() { 3627 m_gdb_comm.Disconnect(); 3628 if (m_debugserver_pid != LLDB_INVALID_PROCESS_ID) { 3629 Host::Kill(m_debugserver_pid, SIGINT); 3630 m_debugserver_pid = LLDB_INVALID_PROCESS_ID; 3631 } 3632 } 3633 3634 void ProcessGDBRemote::Initialize() { 3635 static llvm::once_flag g_once_flag; 3636 3637 llvm::call_once(g_once_flag, []() { 3638 PluginManager::RegisterPlugin(GetPluginNameStatic(), 3639 GetPluginDescriptionStatic(), CreateInstance, 3640 DebuggerInitialize); 3641 }); 3642 } 3643 3644 void ProcessGDBRemote::DebuggerInitialize(Debugger &debugger) { 3645 if (!PluginManager::GetSettingForProcessPlugin( 3646 debugger, PluginProperties::GetSettingName())) { 3647 const bool is_global_setting = true; 3648 PluginManager::CreateSettingForProcessPlugin( 3649 debugger, GetGlobalPluginProperties()->GetValueProperties(), 3650 ConstString("Properties for the gdb-remote process plug-in."), 3651 is_global_setting); 3652 } 3653 } 3654 3655 bool ProcessGDBRemote::StartAsyncThread() { 3656 Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS)); 3657 3658 LLDB_LOGF(log, "ProcessGDBRemote::%s ()", __FUNCTION__); 3659 3660 std::lock_guard<std::recursive_mutex> guard(m_async_thread_state_mutex); 3661 if (!m_async_thread.IsJoinable()) { 3662 // Create a thread that watches our internal state and controls which 3663 // events make it to clients (into the DCProcess event queue). 3664 3665 llvm::Expected<HostThread> async_thread = ThreadLauncher::LaunchThread( 3666 "<lldb.process.gdb-remote.async>", ProcessGDBRemote::AsyncThread, this); 3667 if (!async_thread) { 3668 LLDB_LOG(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_HOST), 3669 "failed to launch host thread: {}", 3670 llvm::toString(async_thread.takeError())); 3671 return false; 3672 } 3673 m_async_thread = *async_thread; 3674 } else 3675 LLDB_LOGF(log, 3676 "ProcessGDBRemote::%s () - Called when Async thread was " 3677 "already running.", 3678 __FUNCTION__); 3679 3680 return m_async_thread.IsJoinable(); 3681 } 3682 3683 void ProcessGDBRemote::StopAsyncThread() { 3684 Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS)); 3685 3686 LLDB_LOGF(log, "ProcessGDBRemote::%s ()", __FUNCTION__); 3687 3688 std::lock_guard<std::recursive_mutex> guard(m_async_thread_state_mutex); 3689 if (m_async_thread.IsJoinable()) { 3690 m_async_broadcaster.BroadcastEvent(eBroadcastBitAsyncThreadShouldExit); 3691 3692 // This will shut down the async thread. 3693 m_gdb_comm.Disconnect(); // Disconnect from the debug server. 3694 3695 // Stop the stdio thread 3696 m_async_thread.Join(nullptr); 3697 m_async_thread.Reset(); 3698 } else 3699 LLDB_LOGF( 3700 log, 3701 "ProcessGDBRemote::%s () - Called when Async thread was not running.", 3702 __FUNCTION__); 3703 } 3704 3705 bool ProcessGDBRemote::HandleNotifyPacket(StringExtractorGDBRemote &packet) { 3706 // get the packet at a string 3707 const std::string &pkt = packet.GetStringRef(); 3708 // skip %stop: 3709 StringExtractorGDBRemote stop_info(pkt.c_str() + 5); 3710 3711 // pass as a thread stop info packet 3712 SetLastStopPacket(stop_info); 3713 3714 // check for more stop reasons 3715 HandleStopReplySequence(); 3716 3717 // if the process is stopped then we need to fake a resume so that we can 3718 // stop properly with the new break. This is possible due to 3719 // SetPrivateState() broadcasting the state change as a side effect. 3720 if (GetPrivateState() == lldb::StateType::eStateStopped) { 3721 SetPrivateState(lldb::StateType::eStateRunning); 3722 } 3723 3724 // since we have some stopped packets we can halt the process 3725 SetPrivateState(lldb::StateType::eStateStopped); 3726 3727 return true; 3728 } 3729 3730 thread_result_t ProcessGDBRemote::AsyncThread(void *arg) { 3731 ProcessGDBRemote *process = (ProcessGDBRemote *)arg; 3732 3733 Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS)); 3734 LLDB_LOGF(log, 3735 "ProcessGDBRemote::%s (arg = %p, pid = %" PRIu64 3736 ") thread starting...", 3737 __FUNCTION__, arg, process->GetID()); 3738 3739 EventSP event_sp; 3740 bool done = false; 3741 while (!done) { 3742 LLDB_LOGF(log, 3743 "ProcessGDBRemote::%s (arg = %p, pid = %" PRIu64 3744 ") listener.WaitForEvent (NULL, event_sp)...", 3745 __FUNCTION__, arg, process->GetID()); 3746 if (process->m_async_listener_sp->GetEvent(event_sp, llvm::None)) { 3747 const uint32_t event_type = event_sp->GetType(); 3748 if (event_sp->BroadcasterIs(&process->m_async_broadcaster)) { 3749 LLDB_LOGF(log, 3750 "ProcessGDBRemote::%s (arg = %p, pid = %" PRIu64 3751 ") Got an event of type: %d...", 3752 __FUNCTION__, arg, process->GetID(), event_type); 3753 3754 switch (event_type) { 3755 case eBroadcastBitAsyncContinue: { 3756 const EventDataBytes *continue_packet = 3757 EventDataBytes::GetEventDataFromEvent(event_sp.get()); 3758 3759 if (continue_packet) { 3760 const char *continue_cstr = 3761 (const char *)continue_packet->GetBytes(); 3762 const size_t continue_cstr_len = continue_packet->GetByteSize(); 3763 LLDB_LOGF(log, 3764 "ProcessGDBRemote::%s (arg = %p, pid = %" PRIu64 3765 ") got eBroadcastBitAsyncContinue: %s", 3766 __FUNCTION__, arg, process->GetID(), continue_cstr); 3767 3768 if (::strstr(continue_cstr, "vAttach") == nullptr) 3769 process->SetPrivateState(eStateRunning); 3770 StringExtractorGDBRemote response; 3771 3772 // If in Non-Stop-Mode 3773 if (process->GetTarget().GetNonStopModeEnabled()) { 3774 // send the vCont packet 3775 if (!process->GetGDBRemote().SendvContPacket( 3776 llvm::StringRef(continue_cstr, continue_cstr_len), 3777 response)) { 3778 // Something went wrong 3779 done = true; 3780 break; 3781 } 3782 } 3783 // If in All-Stop-Mode 3784 else { 3785 StateType stop_state = 3786 process->GetGDBRemote().SendContinuePacketAndWaitForResponse( 3787 *process, *process->GetUnixSignals(), 3788 llvm::StringRef(continue_cstr, continue_cstr_len), 3789 response); 3790 3791 // We need to immediately clear the thread ID list so we are sure 3792 // to get a valid list of threads. The thread ID list might be 3793 // contained within the "response", or the stop reply packet that 3794 // caused the stop. So clear it now before we give the stop reply 3795 // packet to the process using the 3796 // process->SetLastStopPacket()... 3797 process->ClearThreadIDList(); 3798 3799 switch (stop_state) { 3800 case eStateStopped: 3801 case eStateCrashed: 3802 case eStateSuspended: 3803 process->SetLastStopPacket(response); 3804 process->SetPrivateState(stop_state); 3805 break; 3806 3807 case eStateExited: { 3808 process->SetLastStopPacket(response); 3809 process->ClearThreadIDList(); 3810 response.SetFilePos(1); 3811 3812 int exit_status = response.GetHexU8(); 3813 std::string desc_string; 3814 if (response.GetBytesLeft() > 0 && 3815 response.GetChar('-') == ';') { 3816 llvm::StringRef desc_str; 3817 llvm::StringRef desc_token; 3818 while (response.GetNameColonValue(desc_token, desc_str)) { 3819 if (desc_token != "description") 3820 continue; 3821 StringExtractor extractor(desc_str); 3822 extractor.GetHexByteString(desc_string); 3823 } 3824 } 3825 process->SetExitStatus(exit_status, desc_string.c_str()); 3826 done = true; 3827 break; 3828 } 3829 case eStateInvalid: { 3830 // Check to see if we were trying to attach and if we got back 3831 // the "E87" error code from debugserver -- this indicates that 3832 // the process is not debuggable. Return a slightly more 3833 // helpful error message about why the attach failed. 3834 if (::strstr(continue_cstr, "vAttach") != nullptr && 3835 response.GetError() == 0x87) { 3836 process->SetExitStatus(-1, "cannot attach to process due to " 3837 "System Integrity Protection"); 3838 } else if (::strstr(continue_cstr, "vAttach") != nullptr && 3839 response.GetStatus().Fail()) { 3840 process->SetExitStatus(-1, response.GetStatus().AsCString()); 3841 } else { 3842 process->SetExitStatus(-1, "lost connection"); 3843 } 3844 break; 3845 } 3846 3847 default: 3848 process->SetPrivateState(stop_state); 3849 break; 3850 } // switch(stop_state) 3851 } // else // if in All-stop-mode 3852 } // if (continue_packet) 3853 } // case eBroadcastBitAysncContinue 3854 break; 3855 3856 case eBroadcastBitAsyncThreadShouldExit: 3857 LLDB_LOGF(log, 3858 "ProcessGDBRemote::%s (arg = %p, pid = %" PRIu64 3859 ") got eBroadcastBitAsyncThreadShouldExit...", 3860 __FUNCTION__, arg, process->GetID()); 3861 done = true; 3862 break; 3863 3864 default: 3865 LLDB_LOGF(log, 3866 "ProcessGDBRemote::%s (arg = %p, pid = %" PRIu64 3867 ") got unknown event 0x%8.8x", 3868 __FUNCTION__, arg, process->GetID(), event_type); 3869 done = true; 3870 break; 3871 } 3872 } else if (event_sp->BroadcasterIs(&process->m_gdb_comm)) { 3873 switch (event_type) { 3874 case Communication::eBroadcastBitReadThreadDidExit: 3875 process->SetExitStatus(-1, "lost connection"); 3876 done = true; 3877 break; 3878 3879 case GDBRemoteCommunication::eBroadcastBitGdbReadThreadGotNotify: { 3880 lldb_private::Event *event = event_sp.get(); 3881 const EventDataBytes *continue_packet = 3882 EventDataBytes::GetEventDataFromEvent(event); 3883 StringExtractorGDBRemote notify( 3884 (const char *)continue_packet->GetBytes()); 3885 // Hand this over to the process to handle 3886 process->HandleNotifyPacket(notify); 3887 break; 3888 } 3889 3890 default: 3891 LLDB_LOGF(log, 3892 "ProcessGDBRemote::%s (arg = %p, pid = %" PRIu64 3893 ") got unknown event 0x%8.8x", 3894 __FUNCTION__, arg, process->GetID(), event_type); 3895 done = true; 3896 break; 3897 } 3898 } 3899 } else { 3900 LLDB_LOGF(log, 3901 "ProcessGDBRemote::%s (arg = %p, pid = %" PRIu64 3902 ") listener.WaitForEvent (NULL, event_sp) => false", 3903 __FUNCTION__, arg, process->GetID()); 3904 done = true; 3905 } 3906 } 3907 3908 LLDB_LOGF(log, 3909 "ProcessGDBRemote::%s (arg = %p, pid = %" PRIu64 3910 ") thread exiting...", 3911 __FUNCTION__, arg, process->GetID()); 3912 3913 return {}; 3914 } 3915 3916 // uint32_t 3917 // ProcessGDBRemote::ListProcessesMatchingName (const char *name, StringList 3918 // &matches, std::vector<lldb::pid_t> &pids) 3919 //{ 3920 // // If we are planning to launch the debugserver remotely, then we need to 3921 // fire up a debugserver 3922 // // process and ask it for the list of processes. But if we are local, we 3923 // can let the Host do it. 3924 // if (m_local_debugserver) 3925 // { 3926 // return Host::ListProcessesMatchingName (name, matches, pids); 3927 // } 3928 // else 3929 // { 3930 // // FIXME: Implement talking to the remote debugserver. 3931 // return 0; 3932 // } 3933 // 3934 //} 3935 // 3936 bool ProcessGDBRemote::NewThreadNotifyBreakpointHit( 3937 void *baton, StoppointCallbackContext *context, lldb::user_id_t break_id, 3938 lldb::user_id_t break_loc_id) { 3939 // I don't think I have to do anything here, just make sure I notice the new 3940 // thread when it starts to 3941 // run so I can stop it if that's what I want to do. 3942 Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_STEP)); 3943 LLDB_LOGF(log, "Hit New Thread Notification breakpoint."); 3944 return false; 3945 } 3946 3947 Status ProcessGDBRemote::UpdateAutomaticSignalFiltering() { 3948 Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS)); 3949 LLDB_LOG(log, "Check if need to update ignored signals"); 3950 3951 // QPassSignals package is not supported by the server, there is no way we 3952 // can ignore any signals on server side. 3953 if (!m_gdb_comm.GetQPassSignalsSupported()) 3954 return Status(); 3955 3956 // No signals, nothing to send. 3957 if (m_unix_signals_sp == nullptr) 3958 return Status(); 3959 3960 // Signals' version hasn't changed, no need to send anything. 3961 uint64_t new_signals_version = m_unix_signals_sp->GetVersion(); 3962 if (new_signals_version == m_last_signals_version) { 3963 LLDB_LOG(log, "Signals' version hasn't changed. version={0}", 3964 m_last_signals_version); 3965 return Status(); 3966 } 3967 3968 auto signals_to_ignore = 3969 m_unix_signals_sp->GetFilteredSignals(false, false, false); 3970 Status error = m_gdb_comm.SendSignalsToIgnore(signals_to_ignore); 3971 3972 LLDB_LOG(log, 3973 "Signals' version changed. old version={0}, new version={1}, " 3974 "signals ignored={2}, update result={3}", 3975 m_last_signals_version, new_signals_version, 3976 signals_to_ignore.size(), error); 3977 3978 if (error.Success()) 3979 m_last_signals_version = new_signals_version; 3980 3981 return error; 3982 } 3983 3984 bool ProcessGDBRemote::StartNoticingNewThreads() { 3985 Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_STEP)); 3986 if (m_thread_create_bp_sp) { 3987 if (log && log->GetVerbose()) 3988 LLDB_LOGF(log, "Enabled noticing new thread breakpoint."); 3989 m_thread_create_bp_sp->SetEnabled(true); 3990 } else { 3991 PlatformSP platform_sp(GetTarget().GetPlatform()); 3992 if (platform_sp) { 3993 m_thread_create_bp_sp = 3994 platform_sp->SetThreadCreationBreakpoint(GetTarget()); 3995 if (m_thread_create_bp_sp) { 3996 if (log && log->GetVerbose()) 3997 LLDB_LOGF( 3998 log, "Successfully created new thread notification breakpoint %i", 3999 m_thread_create_bp_sp->GetID()); 4000 m_thread_create_bp_sp->SetCallback( 4001 ProcessGDBRemote::NewThreadNotifyBreakpointHit, this, true); 4002 } else { 4003 LLDB_LOGF(log, "Failed to create new thread notification breakpoint."); 4004 } 4005 } 4006 } 4007 return m_thread_create_bp_sp.get() != nullptr; 4008 } 4009 4010 bool ProcessGDBRemote::StopNoticingNewThreads() { 4011 Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_STEP)); 4012 if (log && log->GetVerbose()) 4013 LLDB_LOGF(log, "Disabling new thread notification breakpoint."); 4014 4015 if (m_thread_create_bp_sp) 4016 m_thread_create_bp_sp->SetEnabled(false); 4017 4018 return true; 4019 } 4020 4021 DynamicLoader *ProcessGDBRemote::GetDynamicLoader() { 4022 if (m_dyld_up.get() == nullptr) 4023 m_dyld_up.reset(DynamicLoader::FindPlugin(this, nullptr)); 4024 return m_dyld_up.get(); 4025 } 4026 4027 Status ProcessGDBRemote::SendEventData(const char *data) { 4028 int return_value; 4029 bool was_supported; 4030 4031 Status error; 4032 4033 return_value = m_gdb_comm.SendLaunchEventDataPacket(data, &was_supported); 4034 if (return_value != 0) { 4035 if (!was_supported) 4036 error.SetErrorString("Sending events is not supported for this process."); 4037 else 4038 error.SetErrorStringWithFormat("Error sending event data: %d.", 4039 return_value); 4040 } 4041 return error; 4042 } 4043 4044 DataExtractor ProcessGDBRemote::GetAuxvData() { 4045 DataBufferSP buf; 4046 if (m_gdb_comm.GetQXferAuxvReadSupported()) { 4047 std::string response_string; 4048 if (m_gdb_comm.SendPacketsAndConcatenateResponses("qXfer:auxv:read::", 4049 response_string) == 4050 GDBRemoteCommunication::PacketResult::Success) 4051 buf = std::make_shared<DataBufferHeap>(response_string.c_str(), 4052 response_string.length()); 4053 } 4054 return DataExtractor(buf, GetByteOrder(), GetAddressByteSize()); 4055 } 4056 4057 StructuredData::ObjectSP 4058 ProcessGDBRemote::GetExtendedInfoForThread(lldb::tid_t tid) { 4059 StructuredData::ObjectSP object_sp; 4060 4061 if (m_gdb_comm.GetThreadExtendedInfoSupported()) { 4062 StructuredData::ObjectSP args_dict(new StructuredData::Dictionary()); 4063 SystemRuntime *runtime = GetSystemRuntime(); 4064 if (runtime) { 4065 runtime->AddThreadExtendedInfoPacketHints(args_dict); 4066 } 4067 args_dict->GetAsDictionary()->AddIntegerItem("thread", tid); 4068 4069 StreamString packet; 4070 packet << "jThreadExtendedInfo:"; 4071 args_dict->Dump(packet, false); 4072 4073 // FIXME the final character of a JSON dictionary, '}', is the escape 4074 // character in gdb-remote binary mode. lldb currently doesn't escape 4075 // these characters in its packet output -- so we add the quoted version of 4076 // the } character here manually in case we talk to a debugserver which un- 4077 // escapes the characters at packet read time. 4078 packet << (char)(0x7d ^ 0x20); 4079 4080 StringExtractorGDBRemote response; 4081 response.SetResponseValidatorToJSON(); 4082 if (m_gdb_comm.SendPacketAndWaitForResponse(packet.GetString(), response, 4083 false) == 4084 GDBRemoteCommunication::PacketResult::Success) { 4085 StringExtractorGDBRemote::ResponseType response_type = 4086 response.GetResponseType(); 4087 if (response_type == StringExtractorGDBRemote::eResponse) { 4088 if (!response.Empty()) { 4089 object_sp = StructuredData::ParseJSON(response.GetStringRef()); 4090 } 4091 } 4092 } 4093 } 4094 return object_sp; 4095 } 4096 4097 StructuredData::ObjectSP ProcessGDBRemote::GetLoadedDynamicLibrariesInfos( 4098 lldb::addr_t image_list_address, lldb::addr_t image_count) { 4099 4100 StructuredData::ObjectSP args_dict(new StructuredData::Dictionary()); 4101 args_dict->GetAsDictionary()->AddIntegerItem("image_list_address", 4102 image_list_address); 4103 args_dict->GetAsDictionary()->AddIntegerItem("image_count", image_count); 4104 4105 return GetLoadedDynamicLibrariesInfos_sender(args_dict); 4106 } 4107 4108 StructuredData::ObjectSP ProcessGDBRemote::GetLoadedDynamicLibrariesInfos() { 4109 StructuredData::ObjectSP args_dict(new StructuredData::Dictionary()); 4110 4111 args_dict->GetAsDictionary()->AddBooleanItem("fetch_all_solibs", true); 4112 4113 return GetLoadedDynamicLibrariesInfos_sender(args_dict); 4114 } 4115 4116 StructuredData::ObjectSP ProcessGDBRemote::GetLoadedDynamicLibrariesInfos( 4117 const std::vector<lldb::addr_t> &load_addresses) { 4118 StructuredData::ObjectSP args_dict(new StructuredData::Dictionary()); 4119 StructuredData::ArraySP addresses(new StructuredData::Array); 4120 4121 for (auto addr : load_addresses) { 4122 StructuredData::ObjectSP addr_sp(new StructuredData::Integer(addr)); 4123 addresses->AddItem(addr_sp); 4124 } 4125 4126 args_dict->GetAsDictionary()->AddItem("solib_addresses", addresses); 4127 4128 return GetLoadedDynamicLibrariesInfos_sender(args_dict); 4129 } 4130 4131 StructuredData::ObjectSP 4132 ProcessGDBRemote::GetLoadedDynamicLibrariesInfos_sender( 4133 StructuredData::ObjectSP args_dict) { 4134 StructuredData::ObjectSP object_sp; 4135 4136 if (m_gdb_comm.GetLoadedDynamicLibrariesInfosSupported()) { 4137 // Scope for the scoped timeout object 4138 GDBRemoteCommunication::ScopedTimeout timeout(m_gdb_comm, 4139 std::chrono::seconds(10)); 4140 4141 StreamString packet; 4142 packet << "jGetLoadedDynamicLibrariesInfos:"; 4143 args_dict->Dump(packet, false); 4144 4145 // FIXME the final character of a JSON dictionary, '}', is the escape 4146 // character in gdb-remote binary mode. lldb currently doesn't escape 4147 // these characters in its packet output -- so we add the quoted version of 4148 // the } character here manually in case we talk to a debugserver which un- 4149 // escapes the characters at packet read time. 4150 packet << (char)(0x7d ^ 0x20); 4151 4152 StringExtractorGDBRemote response; 4153 response.SetResponseValidatorToJSON(); 4154 if (m_gdb_comm.SendPacketAndWaitForResponse(packet.GetString(), response, 4155 false) == 4156 GDBRemoteCommunication::PacketResult::Success) { 4157 StringExtractorGDBRemote::ResponseType response_type = 4158 response.GetResponseType(); 4159 if (response_type == StringExtractorGDBRemote::eResponse) { 4160 if (!response.Empty()) { 4161 object_sp = StructuredData::ParseJSON(response.GetStringRef()); 4162 } 4163 } 4164 } 4165 } 4166 return object_sp; 4167 } 4168 4169 StructuredData::ObjectSP ProcessGDBRemote::GetSharedCacheInfo() { 4170 StructuredData::ObjectSP object_sp; 4171 StructuredData::ObjectSP args_dict(new StructuredData::Dictionary()); 4172 4173 if (m_gdb_comm.GetSharedCacheInfoSupported()) { 4174 StreamString packet; 4175 packet << "jGetSharedCacheInfo:"; 4176 args_dict->Dump(packet, false); 4177 4178 // FIXME the final character of a JSON dictionary, '}', is the escape 4179 // character in gdb-remote binary mode. lldb currently doesn't escape 4180 // these characters in its packet output -- so we add the quoted version of 4181 // the } character here manually in case we talk to a debugserver which un- 4182 // escapes the characters at packet read time. 4183 packet << (char)(0x7d ^ 0x20); 4184 4185 StringExtractorGDBRemote response; 4186 response.SetResponseValidatorToJSON(); 4187 if (m_gdb_comm.SendPacketAndWaitForResponse(packet.GetString(), response, 4188 false) == 4189 GDBRemoteCommunication::PacketResult::Success) { 4190 StringExtractorGDBRemote::ResponseType response_type = 4191 response.GetResponseType(); 4192 if (response_type == StringExtractorGDBRemote::eResponse) { 4193 if (!response.Empty()) { 4194 object_sp = StructuredData::ParseJSON(response.GetStringRef()); 4195 } 4196 } 4197 } 4198 } 4199 return object_sp; 4200 } 4201 4202 Status ProcessGDBRemote::ConfigureStructuredData( 4203 ConstString type_name, const StructuredData::ObjectSP &config_sp) { 4204 return m_gdb_comm.ConfigureRemoteStructuredData(type_name, config_sp); 4205 } 4206 4207 // Establish the largest memory read/write payloads we should use. If the 4208 // remote stub has a max packet size, stay under that size. 4209 // 4210 // If the remote stub's max packet size is crazy large, use a reasonable 4211 // largeish default. 4212 // 4213 // If the remote stub doesn't advertise a max packet size, use a conservative 4214 // default. 4215 4216 void ProcessGDBRemote::GetMaxMemorySize() { 4217 const uint64_t reasonable_largeish_default = 128 * 1024; 4218 const uint64_t conservative_default = 512; 4219 4220 if (m_max_memory_size == 0) { 4221 uint64_t stub_max_size = m_gdb_comm.GetRemoteMaxPacketSize(); 4222 if (stub_max_size != UINT64_MAX && stub_max_size != 0) { 4223 // Save the stub's claimed maximum packet size 4224 m_remote_stub_max_memory_size = stub_max_size; 4225 4226 // Even if the stub says it can support ginormous packets, don't exceed 4227 // our reasonable largeish default packet size. 4228 if (stub_max_size > reasonable_largeish_default) { 4229 stub_max_size = reasonable_largeish_default; 4230 } 4231 4232 // Memory packet have other overheads too like Maddr,size:#NN Instead of 4233 // calculating the bytes taken by size and addr every time, we take a 4234 // maximum guess here. 4235 if (stub_max_size > 70) 4236 stub_max_size -= 32 + 32 + 6; 4237 else { 4238 // In unlikely scenario that max packet size is less then 70, we will 4239 // hope that data being written is small enough to fit. 4240 Log *log(ProcessGDBRemoteLog::GetLogIfAnyCategoryIsSet( 4241 GDBR_LOG_COMM | GDBR_LOG_MEMORY)); 4242 if (log) 4243 log->Warning("Packet size is too small. " 4244 "LLDB may face problems while writing memory"); 4245 } 4246 4247 m_max_memory_size = stub_max_size; 4248 } else { 4249 m_max_memory_size = conservative_default; 4250 } 4251 } 4252 } 4253 4254 void ProcessGDBRemote::SetUserSpecifiedMaxMemoryTransferSize( 4255 uint64_t user_specified_max) { 4256 if (user_specified_max != 0) { 4257 GetMaxMemorySize(); 4258 4259 if (m_remote_stub_max_memory_size != 0) { 4260 if (m_remote_stub_max_memory_size < user_specified_max) { 4261 m_max_memory_size = m_remote_stub_max_memory_size; // user specified a 4262 // packet size too 4263 // big, go as big 4264 // as the remote stub says we can go. 4265 } else { 4266 m_max_memory_size = user_specified_max; // user's packet size is good 4267 } 4268 } else { 4269 m_max_memory_size = 4270 user_specified_max; // user's packet size is probably fine 4271 } 4272 } 4273 } 4274 4275 bool ProcessGDBRemote::GetModuleSpec(const FileSpec &module_file_spec, 4276 const ArchSpec &arch, 4277 ModuleSpec &module_spec) { 4278 Log *log = GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PLATFORM); 4279 4280 const ModuleCacheKey key(module_file_spec.GetPath(), 4281 arch.GetTriple().getTriple()); 4282 auto cached = m_cached_module_specs.find(key); 4283 if (cached != m_cached_module_specs.end()) { 4284 module_spec = cached->second; 4285 return bool(module_spec); 4286 } 4287 4288 if (!m_gdb_comm.GetModuleInfo(module_file_spec, arch, module_spec)) { 4289 LLDB_LOGF(log, "ProcessGDBRemote::%s - failed to get module info for %s:%s", 4290 __FUNCTION__, module_file_spec.GetPath().c_str(), 4291 arch.GetTriple().getTriple().c_str()); 4292 return false; 4293 } 4294 4295 if (log) { 4296 StreamString stream; 4297 module_spec.Dump(stream); 4298 LLDB_LOGF(log, "ProcessGDBRemote::%s - got module info for (%s:%s) : %s", 4299 __FUNCTION__, module_file_spec.GetPath().c_str(), 4300 arch.GetTriple().getTriple().c_str(), stream.GetData()); 4301 } 4302 4303 m_cached_module_specs[key] = module_spec; 4304 return true; 4305 } 4306 4307 void ProcessGDBRemote::PrefetchModuleSpecs( 4308 llvm::ArrayRef<FileSpec> module_file_specs, const llvm::Triple &triple) { 4309 auto module_specs = m_gdb_comm.GetModulesInfo(module_file_specs, triple); 4310 if (module_specs) { 4311 for (const FileSpec &spec : module_file_specs) 4312 m_cached_module_specs[ModuleCacheKey(spec.GetPath(), 4313 triple.getTriple())] = ModuleSpec(); 4314 for (const ModuleSpec &spec : *module_specs) 4315 m_cached_module_specs[ModuleCacheKey(spec.GetFileSpec().GetPath(), 4316 triple.getTriple())] = spec; 4317 } 4318 } 4319 4320 llvm::VersionTuple ProcessGDBRemote::GetHostOSVersion() { 4321 return m_gdb_comm.GetOSVersion(); 4322 } 4323 4324 namespace { 4325 4326 typedef std::vector<std::string> stringVec; 4327 4328 typedef std::vector<struct GdbServerRegisterInfo> GDBServerRegisterVec; 4329 struct RegisterSetInfo { 4330 ConstString name; 4331 }; 4332 4333 typedef std::map<uint32_t, RegisterSetInfo> RegisterSetMap; 4334 4335 struct GdbServerTargetInfo { 4336 std::string arch; 4337 std::string osabi; 4338 stringVec includes; 4339 RegisterSetMap reg_set_map; 4340 }; 4341 4342 bool ParseRegisters(XMLNode feature_node, GdbServerTargetInfo &target_info, 4343 GDBRemoteDynamicRegisterInfo &dyn_reg_info, ABISP abi_sp, 4344 uint32_t &cur_reg_num, uint32_t ®_offset) { 4345 if (!feature_node) 4346 return false; 4347 4348 feature_node.ForEachChildElementWithName( 4349 "reg", 4350 [&target_info, &dyn_reg_info, &cur_reg_num, ®_offset, 4351 &abi_sp](const XMLNode ®_node) -> bool { 4352 std::string gdb_group; 4353 std::string gdb_type; 4354 ConstString reg_name; 4355 ConstString alt_name; 4356 ConstString set_name; 4357 std::vector<uint32_t> value_regs; 4358 std::vector<uint32_t> invalidate_regs; 4359 std::vector<uint8_t> dwarf_opcode_bytes; 4360 bool encoding_set = false; 4361 bool format_set = false; 4362 RegisterInfo reg_info = { 4363 nullptr, // Name 4364 nullptr, // Alt name 4365 0, // byte size 4366 reg_offset, // offset 4367 eEncodingUint, // encoding 4368 eFormatHex, // format 4369 { 4370 LLDB_INVALID_REGNUM, // eh_frame reg num 4371 LLDB_INVALID_REGNUM, // DWARF reg num 4372 LLDB_INVALID_REGNUM, // generic reg num 4373 cur_reg_num, // process plugin reg num 4374 cur_reg_num // native register number 4375 }, 4376 nullptr, 4377 nullptr, 4378 nullptr, // Dwarf Expression opcode bytes pointer 4379 0 // Dwarf Expression opcode bytes length 4380 }; 4381 4382 reg_node.ForEachAttribute([&target_info, &gdb_group, &gdb_type, 4383 ®_name, &alt_name, &set_name, &value_regs, 4384 &invalidate_regs, &encoding_set, &format_set, 4385 ®_info, ®_offset, &dwarf_opcode_bytes]( 4386 const llvm::StringRef &name, 4387 const llvm::StringRef &value) -> bool { 4388 if (name == "name") { 4389 reg_name.SetString(value); 4390 } else if (name == "bitsize") { 4391 reg_info.byte_size = 4392 StringConvert::ToUInt32(value.data(), 0, 0) / CHAR_BIT; 4393 } else if (name == "type") { 4394 gdb_type = value.str(); 4395 } else if (name == "group") { 4396 gdb_group = value.str(); 4397 } else if (name == "regnum") { 4398 const uint32_t regnum = 4399 StringConvert::ToUInt32(value.data(), LLDB_INVALID_REGNUM, 0); 4400 if (regnum != LLDB_INVALID_REGNUM) { 4401 reg_info.kinds[eRegisterKindProcessPlugin] = regnum; 4402 } 4403 } else if (name == "offset") { 4404 reg_offset = StringConvert::ToUInt32(value.data(), UINT32_MAX, 0); 4405 } else if (name == "altname") { 4406 alt_name.SetString(value); 4407 } else if (name == "encoding") { 4408 encoding_set = true; 4409 reg_info.encoding = Args::StringToEncoding(value, eEncodingUint); 4410 } else if (name == "format") { 4411 format_set = true; 4412 Format format = eFormatInvalid; 4413 if (OptionArgParser::ToFormat(value.data(), format, nullptr) 4414 .Success()) 4415 reg_info.format = format; 4416 else if (value == "vector-sint8") 4417 reg_info.format = eFormatVectorOfSInt8; 4418 else if (value == "vector-uint8") 4419 reg_info.format = eFormatVectorOfUInt8; 4420 else if (value == "vector-sint16") 4421 reg_info.format = eFormatVectorOfSInt16; 4422 else if (value == "vector-uint16") 4423 reg_info.format = eFormatVectorOfUInt16; 4424 else if (value == "vector-sint32") 4425 reg_info.format = eFormatVectorOfSInt32; 4426 else if (value == "vector-uint32") 4427 reg_info.format = eFormatVectorOfUInt32; 4428 else if (value == "vector-float32") 4429 reg_info.format = eFormatVectorOfFloat32; 4430 else if (value == "vector-uint64") 4431 reg_info.format = eFormatVectorOfUInt64; 4432 else if (value == "vector-uint128") 4433 reg_info.format = eFormatVectorOfUInt128; 4434 } else if (name == "group_id") { 4435 const uint32_t set_id = 4436 StringConvert::ToUInt32(value.data(), UINT32_MAX, 0); 4437 RegisterSetMap::const_iterator pos = 4438 target_info.reg_set_map.find(set_id); 4439 if (pos != target_info.reg_set_map.end()) 4440 set_name = pos->second.name; 4441 } else if (name == "gcc_regnum" || name == "ehframe_regnum") { 4442 reg_info.kinds[eRegisterKindEHFrame] = 4443 StringConvert::ToUInt32(value.data(), LLDB_INVALID_REGNUM, 0); 4444 } else if (name == "dwarf_regnum") { 4445 reg_info.kinds[eRegisterKindDWARF] = 4446 StringConvert::ToUInt32(value.data(), LLDB_INVALID_REGNUM, 0); 4447 } else if (name == "generic") { 4448 reg_info.kinds[eRegisterKindGeneric] = 4449 Args::StringToGenericRegister(value); 4450 } else if (name == "value_regnums") { 4451 SplitCommaSeparatedRegisterNumberString(value, value_regs, 0); 4452 } else if (name == "invalidate_regnums") { 4453 SplitCommaSeparatedRegisterNumberString(value, invalidate_regs, 0); 4454 } else if (name == "dynamic_size_dwarf_expr_bytes") { 4455 StringExtractor opcode_extractor; 4456 std::string opcode_string = value.str(); 4457 size_t dwarf_opcode_len = opcode_string.length() / 2; 4458 assert(dwarf_opcode_len > 0); 4459 4460 dwarf_opcode_bytes.resize(dwarf_opcode_len); 4461 reg_info.dynamic_size_dwarf_len = dwarf_opcode_len; 4462 opcode_extractor.GetStringRef().swap(opcode_string); 4463 uint32_t ret_val = 4464 opcode_extractor.GetHexBytesAvail(dwarf_opcode_bytes); 4465 assert(dwarf_opcode_len == ret_val); 4466 UNUSED_IF_ASSERT_DISABLED(ret_val); 4467 reg_info.dynamic_size_dwarf_expr_bytes = dwarf_opcode_bytes.data(); 4468 } else { 4469 printf("unhandled attribute %s = %s\n", name.data(), value.data()); 4470 } 4471 return true; // Keep iterating through all attributes 4472 }); 4473 4474 if (!gdb_type.empty() && !(encoding_set || format_set)) { 4475 if (gdb_type.find("int") == 0) { 4476 reg_info.format = eFormatHex; 4477 reg_info.encoding = eEncodingUint; 4478 } else if (gdb_type == "data_ptr" || gdb_type == "code_ptr") { 4479 reg_info.format = eFormatAddressInfo; 4480 reg_info.encoding = eEncodingUint; 4481 } else if (gdb_type == "i387_ext" || gdb_type == "float") { 4482 reg_info.format = eFormatFloat; 4483 reg_info.encoding = eEncodingIEEE754; 4484 } 4485 } 4486 4487 // Only update the register set name if we didn't get a "reg_set" 4488 // attribute. "set_name" will be empty if we didn't have a "reg_set" 4489 // attribute. 4490 if (!set_name) { 4491 if (!gdb_group.empty()) { 4492 set_name.SetCString(gdb_group.c_str()); 4493 } else { 4494 // If no register group name provided anywhere, 4495 // we'll create a 'general' register set 4496 set_name.SetCString("general"); 4497 } 4498 } 4499 4500 reg_info.byte_offset = reg_offset; 4501 assert(reg_info.byte_size != 0); 4502 reg_offset += reg_info.byte_size; 4503 if (!value_regs.empty()) { 4504 value_regs.push_back(LLDB_INVALID_REGNUM); 4505 reg_info.value_regs = value_regs.data(); 4506 } 4507 if (!invalidate_regs.empty()) { 4508 invalidate_regs.push_back(LLDB_INVALID_REGNUM); 4509 reg_info.invalidate_regs = invalidate_regs.data(); 4510 } 4511 4512 ++cur_reg_num; 4513 AugmentRegisterInfoViaABI(reg_info, reg_name, abi_sp); 4514 dyn_reg_info.AddRegister(reg_info, reg_name, alt_name, set_name); 4515 4516 return true; // Keep iterating through all "reg" elements 4517 }); 4518 return true; 4519 } 4520 4521 } // namespace 4522 4523 // This method fetches a register description feature xml file from 4524 // the remote stub and adds registers/register groupsets/architecture 4525 // information to the current process. It will call itself recursively 4526 // for nested register definition files. It returns true if it was able 4527 // to fetch and parse an xml file. 4528 bool ProcessGDBRemote::GetGDBServerRegisterInfoXMLAndProcess( 4529 ArchSpec &arch_to_use, std::string xml_filename, uint32_t &cur_reg_num, 4530 uint32_t ®_offset) { 4531 // request the target xml file 4532 std::string raw; 4533 lldb_private::Status lldberr; 4534 if (!m_gdb_comm.ReadExtFeature(ConstString("features"), 4535 ConstString(xml_filename.c_str()), raw, 4536 lldberr)) { 4537 return false; 4538 } 4539 4540 XMLDocument xml_document; 4541 4542 if (xml_document.ParseMemory(raw.c_str(), raw.size(), xml_filename.c_str())) { 4543 GdbServerTargetInfo target_info; 4544 std::vector<XMLNode> feature_nodes; 4545 4546 // The top level feature XML file will start with a <target> tag. 4547 XMLNode target_node = xml_document.GetRootElement("target"); 4548 if (target_node) { 4549 target_node.ForEachChildElement([&target_info, &feature_nodes]( 4550 const XMLNode &node) -> bool { 4551 llvm::StringRef name = node.GetName(); 4552 if (name == "architecture") { 4553 node.GetElementText(target_info.arch); 4554 } else if (name == "osabi") { 4555 node.GetElementText(target_info.osabi); 4556 } else if (name == "xi:include" || name == "include") { 4557 llvm::StringRef href = node.GetAttributeValue("href"); 4558 if (!href.empty()) 4559 target_info.includes.push_back(href.str()); 4560 } else if (name == "feature") { 4561 feature_nodes.push_back(node); 4562 } else if (name == "groups") { 4563 node.ForEachChildElementWithName( 4564 "group", [&target_info](const XMLNode &node) -> bool { 4565 uint32_t set_id = UINT32_MAX; 4566 RegisterSetInfo set_info; 4567 4568 node.ForEachAttribute( 4569 [&set_id, &set_info](const llvm::StringRef &name, 4570 const llvm::StringRef &value) -> bool { 4571 if (name == "id") 4572 set_id = StringConvert::ToUInt32(value.data(), 4573 UINT32_MAX, 0); 4574 if (name == "name") 4575 set_info.name = ConstString(value); 4576 return true; // Keep iterating through all attributes 4577 }); 4578 4579 if (set_id != UINT32_MAX) 4580 target_info.reg_set_map[set_id] = set_info; 4581 return true; // Keep iterating through all "group" elements 4582 }); 4583 } 4584 return true; // Keep iterating through all children of the target_node 4585 }); 4586 } else { 4587 // In an included XML feature file, we're already "inside" the <target> 4588 // tag of the initial XML file; this included file will likely only have 4589 // a <feature> tag. Need to check for any more included files in this 4590 // <feature> element. 4591 XMLNode feature_node = xml_document.GetRootElement("feature"); 4592 if (feature_node) { 4593 feature_nodes.push_back(feature_node); 4594 feature_node.ForEachChildElement([&target_info]( 4595 const XMLNode &node) -> bool { 4596 llvm::StringRef name = node.GetName(); 4597 if (name == "xi:include" || name == "include") { 4598 llvm::StringRef href = node.GetAttributeValue("href"); 4599 if (!href.empty()) 4600 target_info.includes.push_back(href.str()); 4601 } 4602 return true; 4603 }); 4604 } 4605 } 4606 4607 // If the target.xml includes an architecture entry like 4608 // <architecture>i386:x86-64</architecture> (seen from VMWare ESXi) 4609 // <architecture>arm</architecture> (seen from Segger JLink on unspecified arm board) 4610 // use that if we don't have anything better. 4611 if (!arch_to_use.IsValid() && !target_info.arch.empty()) { 4612 if (target_info.arch == "i386:x86-64") { 4613 // We don't have any information about vendor or OS. 4614 arch_to_use.SetTriple("x86_64--"); 4615 GetTarget().MergeArchitecture(arch_to_use); 4616 } 4617 4618 // SEGGER J-Link jtag boards send this very-generic arch name, 4619 // we'll need to use this if we have absolutely nothing better 4620 // to work with or the register definitions won't be accepted. 4621 if (target_info.arch == "arm") { 4622 arch_to_use.SetTriple("arm--"); 4623 GetTarget().MergeArchitecture(arch_to_use); 4624 } 4625 } 4626 4627 if (arch_to_use.IsValid()) { 4628 // Don't use Process::GetABI, this code gets called from DidAttach, and 4629 // in that context we haven't set the Target's architecture yet, so the 4630 // ABI is also potentially incorrect. 4631 ABISP abi_to_use_sp = ABI::FindPlugin(shared_from_this(), arch_to_use); 4632 for (auto &feature_node : feature_nodes) { 4633 ParseRegisters(feature_node, target_info, this->m_register_info, 4634 abi_to_use_sp, cur_reg_num, reg_offset); 4635 } 4636 4637 for (const auto &include : target_info.includes) { 4638 GetGDBServerRegisterInfoXMLAndProcess(arch_to_use, include, cur_reg_num, 4639 reg_offset); 4640 } 4641 } 4642 } else { 4643 return false; 4644 } 4645 return true; 4646 } 4647 4648 // query the target of gdb-remote for extended target information returns 4649 // true on success (got register definitions), false on failure (did not). 4650 bool ProcessGDBRemote::GetGDBServerRegisterInfo(ArchSpec &arch_to_use) { 4651 // Make sure LLDB has an XML parser it can use first 4652 if (!XMLDocument::XMLEnabled()) 4653 return false; 4654 4655 // check that we have extended feature read support 4656 if (!m_gdb_comm.GetQXferFeaturesReadSupported()) 4657 return false; 4658 4659 uint32_t cur_reg_num = 0; 4660 uint32_t reg_offset = 0; 4661 if (GetGDBServerRegisterInfoXMLAndProcess (arch_to_use, "target.xml", cur_reg_num, reg_offset)) 4662 this->m_register_info.Finalize(arch_to_use); 4663 4664 return m_register_info.GetNumRegisters() > 0; 4665 } 4666 4667 llvm::Expected<LoadedModuleInfoList> ProcessGDBRemote::GetLoadedModuleList() { 4668 // Make sure LLDB has an XML parser it can use first 4669 if (!XMLDocument::XMLEnabled()) 4670 return llvm::createStringError(llvm::inconvertibleErrorCode(), 4671 "XML parsing not available"); 4672 4673 Log *log = GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS); 4674 LLDB_LOGF(log, "ProcessGDBRemote::%s", __FUNCTION__); 4675 4676 LoadedModuleInfoList list; 4677 GDBRemoteCommunicationClient &comm = m_gdb_comm; 4678 bool can_use_svr4 = GetGlobalPluginProperties()->GetUseSVR4(); 4679 4680 // check that we have extended feature read support 4681 if (can_use_svr4 && comm.GetQXferLibrariesSVR4ReadSupported()) { 4682 // request the loaded library list 4683 std::string raw; 4684 lldb_private::Status lldberr; 4685 4686 if (!comm.ReadExtFeature(ConstString("libraries-svr4"), ConstString(""), 4687 raw, lldberr)) 4688 return llvm::createStringError(llvm::inconvertibleErrorCode(), 4689 "Error in libraries-svr4 packet"); 4690 4691 // parse the xml file in memory 4692 LLDB_LOGF(log, "parsing: %s", raw.c_str()); 4693 XMLDocument doc; 4694 4695 if (!doc.ParseMemory(raw.c_str(), raw.size(), "noname.xml")) 4696 return llvm::createStringError(llvm::inconvertibleErrorCode(), 4697 "Error reading noname.xml"); 4698 4699 XMLNode root_element = doc.GetRootElement("library-list-svr4"); 4700 if (!root_element) 4701 return llvm::createStringError( 4702 llvm::inconvertibleErrorCode(), 4703 "Error finding library-list-svr4 xml element"); 4704 4705 // main link map structure 4706 llvm::StringRef main_lm = root_element.GetAttributeValue("main-lm"); 4707 if (!main_lm.empty()) { 4708 list.m_link_map = 4709 StringConvert::ToUInt64(main_lm.data(), LLDB_INVALID_ADDRESS, 0); 4710 } 4711 4712 root_element.ForEachChildElementWithName( 4713 "library", [log, &list](const XMLNode &library) -> bool { 4714 4715 LoadedModuleInfoList::LoadedModuleInfo module; 4716 4717 library.ForEachAttribute( 4718 [&module](const llvm::StringRef &name, 4719 const llvm::StringRef &value) -> bool { 4720 4721 if (name == "name") 4722 module.set_name(value.str()); 4723 else if (name == "lm") { 4724 // the address of the link_map struct. 4725 module.set_link_map(StringConvert::ToUInt64( 4726 value.data(), LLDB_INVALID_ADDRESS, 0)); 4727 } else if (name == "l_addr") { 4728 // the displacement as read from the field 'l_addr' of the 4729 // link_map struct. 4730 module.set_base(StringConvert::ToUInt64( 4731 value.data(), LLDB_INVALID_ADDRESS, 0)); 4732 // base address is always a displacement, not an absolute 4733 // value. 4734 module.set_base_is_offset(true); 4735 } else if (name == "l_ld") { 4736 // the memory address of the libraries PT_DYAMIC section. 4737 module.set_dynamic(StringConvert::ToUInt64( 4738 value.data(), LLDB_INVALID_ADDRESS, 0)); 4739 } 4740 4741 return true; // Keep iterating over all properties of "library" 4742 }); 4743 4744 if (log) { 4745 std::string name; 4746 lldb::addr_t lm = 0, base = 0, ld = 0; 4747 bool base_is_offset; 4748 4749 module.get_name(name); 4750 module.get_link_map(lm); 4751 module.get_base(base); 4752 module.get_base_is_offset(base_is_offset); 4753 module.get_dynamic(ld); 4754 4755 LLDB_LOGF(log, 4756 "found (link_map:0x%08" PRIx64 ", base:0x%08" PRIx64 4757 "[%s], ld:0x%08" PRIx64 ", name:'%s')", 4758 lm, base, (base_is_offset ? "offset" : "absolute"), ld, 4759 name.c_str()); 4760 } 4761 4762 list.add(module); 4763 return true; // Keep iterating over all "library" elements in the root 4764 // node 4765 }); 4766 4767 if (log) 4768 LLDB_LOGF(log, "found %" PRId32 " modules in total", 4769 (int)list.m_list.size()); 4770 return list; 4771 } else if (comm.GetQXferLibrariesReadSupported()) { 4772 // request the loaded library list 4773 std::string raw; 4774 lldb_private::Status lldberr; 4775 4776 if (!comm.ReadExtFeature(ConstString("libraries"), ConstString(""), raw, 4777 lldberr)) 4778 return llvm::createStringError(llvm::inconvertibleErrorCode(), 4779 "Error in libraries packet"); 4780 4781 LLDB_LOGF(log, "parsing: %s", raw.c_str()); 4782 XMLDocument doc; 4783 4784 if (!doc.ParseMemory(raw.c_str(), raw.size(), "noname.xml")) 4785 return llvm::createStringError(llvm::inconvertibleErrorCode(), 4786 "Error reading noname.xml"); 4787 4788 XMLNode root_element = doc.GetRootElement("library-list"); 4789 if (!root_element) 4790 return llvm::createStringError(llvm::inconvertibleErrorCode(), 4791 "Error finding library-list xml element"); 4792 4793 root_element.ForEachChildElementWithName( 4794 "library", [log, &list](const XMLNode &library) -> bool { 4795 LoadedModuleInfoList::LoadedModuleInfo module; 4796 4797 llvm::StringRef name = library.GetAttributeValue("name"); 4798 module.set_name(name.str()); 4799 4800 // The base address of a given library will be the address of its 4801 // first section. Most remotes send only one section for Windows 4802 // targets for example. 4803 const XMLNode §ion = 4804 library.FindFirstChildElementWithName("section"); 4805 llvm::StringRef address = section.GetAttributeValue("address"); 4806 module.set_base( 4807 StringConvert::ToUInt64(address.data(), LLDB_INVALID_ADDRESS, 0)); 4808 // These addresses are absolute values. 4809 module.set_base_is_offset(false); 4810 4811 if (log) { 4812 std::string name; 4813 lldb::addr_t base = 0; 4814 bool base_is_offset; 4815 module.get_name(name); 4816 module.get_base(base); 4817 module.get_base_is_offset(base_is_offset); 4818 4819 LLDB_LOGF(log, "found (base:0x%08" PRIx64 "[%s], name:'%s')", base, 4820 (base_is_offset ? "offset" : "absolute"), name.c_str()); 4821 } 4822 4823 list.add(module); 4824 return true; // Keep iterating over all "library" elements in the root 4825 // node 4826 }); 4827 4828 if (log) 4829 LLDB_LOGF(log, "found %" PRId32 " modules in total", 4830 (int)list.m_list.size()); 4831 return list; 4832 } else { 4833 return llvm::createStringError(llvm::inconvertibleErrorCode(), 4834 "Remote libraries not supported"); 4835 } 4836 } 4837 4838 lldb::ModuleSP ProcessGDBRemote::LoadModuleAtAddress(const FileSpec &file, 4839 lldb::addr_t link_map, 4840 lldb::addr_t base_addr, 4841 bool value_is_offset) { 4842 DynamicLoader *loader = GetDynamicLoader(); 4843 if (!loader) 4844 return nullptr; 4845 4846 return loader->LoadModuleAtAddress(file, link_map, base_addr, 4847 value_is_offset); 4848 } 4849 4850 llvm::Error ProcessGDBRemote::LoadModules() { 4851 using lldb_private::process_gdb_remote::ProcessGDBRemote; 4852 4853 // request a list of loaded libraries from GDBServer 4854 llvm::Expected<LoadedModuleInfoList> module_list = GetLoadedModuleList(); 4855 if (!module_list) 4856 return module_list.takeError(); 4857 4858 // get a list of all the modules 4859 ModuleList new_modules; 4860 4861 for (LoadedModuleInfoList::LoadedModuleInfo &modInfo : module_list->m_list) { 4862 std::string mod_name; 4863 lldb::addr_t mod_base; 4864 lldb::addr_t link_map; 4865 bool mod_base_is_offset; 4866 4867 bool valid = true; 4868 valid &= modInfo.get_name(mod_name); 4869 valid &= modInfo.get_base(mod_base); 4870 valid &= modInfo.get_base_is_offset(mod_base_is_offset); 4871 if (!valid) 4872 continue; 4873 4874 if (!modInfo.get_link_map(link_map)) 4875 link_map = LLDB_INVALID_ADDRESS; 4876 4877 FileSpec file(mod_name); 4878 FileSystem::Instance().Resolve(file); 4879 lldb::ModuleSP module_sp = 4880 LoadModuleAtAddress(file, link_map, mod_base, mod_base_is_offset); 4881 4882 if (module_sp.get()) 4883 new_modules.Append(module_sp); 4884 } 4885 4886 if (new_modules.GetSize() > 0) { 4887 ModuleList removed_modules; 4888 Target &target = GetTarget(); 4889 ModuleList &loaded_modules = m_process->GetTarget().GetImages(); 4890 4891 for (size_t i = 0; i < loaded_modules.GetSize(); ++i) { 4892 const lldb::ModuleSP loaded_module = loaded_modules.GetModuleAtIndex(i); 4893 4894 bool found = false; 4895 for (size_t j = 0; j < new_modules.GetSize(); ++j) { 4896 if (new_modules.GetModuleAtIndex(j).get() == loaded_module.get()) 4897 found = true; 4898 } 4899 4900 // The main executable will never be included in libraries-svr4, don't 4901 // remove it 4902 if (!found && 4903 loaded_module.get() != target.GetExecutableModulePointer()) { 4904 removed_modules.Append(loaded_module); 4905 } 4906 } 4907 4908 loaded_modules.Remove(removed_modules); 4909 m_process->GetTarget().ModulesDidUnload(removed_modules, false); 4910 4911 new_modules.ForEach([&target](const lldb::ModuleSP module_sp) -> bool { 4912 lldb_private::ObjectFile *obj = module_sp->GetObjectFile(); 4913 if (!obj) 4914 return true; 4915 4916 if (obj->GetType() != ObjectFile::Type::eTypeExecutable) 4917 return true; 4918 4919 lldb::ModuleSP module_copy_sp = module_sp; 4920 target.SetExecutableModule(module_copy_sp, eLoadDependentsNo); 4921 return false; 4922 }); 4923 4924 loaded_modules.AppendIfNeeded(new_modules); 4925 m_process->GetTarget().ModulesDidLoad(new_modules); 4926 } 4927 4928 return llvm::ErrorSuccess(); 4929 } 4930 4931 Status ProcessGDBRemote::GetFileLoadAddress(const FileSpec &file, 4932 bool &is_loaded, 4933 lldb::addr_t &load_addr) { 4934 is_loaded = false; 4935 load_addr = LLDB_INVALID_ADDRESS; 4936 4937 std::string file_path = file.GetPath(false); 4938 if (file_path.empty()) 4939 return Status("Empty file name specified"); 4940 4941 StreamString packet; 4942 packet.PutCString("qFileLoadAddress:"); 4943 packet.PutStringAsRawHex8(file_path); 4944 4945 StringExtractorGDBRemote response; 4946 if (m_gdb_comm.SendPacketAndWaitForResponse(packet.GetString(), response, 4947 false) != 4948 GDBRemoteCommunication::PacketResult::Success) 4949 return Status("Sending qFileLoadAddress packet failed"); 4950 4951 if (response.IsErrorResponse()) { 4952 if (response.GetError() == 1) { 4953 // The file is not loaded into the inferior 4954 is_loaded = false; 4955 load_addr = LLDB_INVALID_ADDRESS; 4956 return Status(); 4957 } 4958 4959 return Status( 4960 "Fetching file load address from remote server returned an error"); 4961 } 4962 4963 if (response.IsNormalResponse()) { 4964 is_loaded = true; 4965 load_addr = response.GetHexMaxU64(false, LLDB_INVALID_ADDRESS); 4966 return Status(); 4967 } 4968 4969 return Status( 4970 "Unknown error happened during sending the load address packet"); 4971 } 4972 4973 void ProcessGDBRemote::ModulesDidLoad(ModuleList &module_list) { 4974 // We must call the lldb_private::Process::ModulesDidLoad () first before we 4975 // do anything 4976 Process::ModulesDidLoad(module_list); 4977 4978 // After loading shared libraries, we can ask our remote GDB server if it 4979 // needs any symbols. 4980 m_gdb_comm.ServeSymbolLookups(this); 4981 } 4982 4983 void ProcessGDBRemote::HandleAsyncStdout(llvm::StringRef out) { 4984 AppendSTDOUT(out.data(), out.size()); 4985 } 4986 4987 static const char *end_delimiter = "--end--;"; 4988 static const int end_delimiter_len = 8; 4989 4990 void ProcessGDBRemote::HandleAsyncMisc(llvm::StringRef data) { 4991 std::string input = data.str(); // '1' to move beyond 'A' 4992 if (m_partial_profile_data.length() > 0) { 4993 m_partial_profile_data.append(input); 4994 input = m_partial_profile_data; 4995 m_partial_profile_data.clear(); 4996 } 4997 4998 size_t found, pos = 0, len = input.length(); 4999 while ((found = input.find(end_delimiter, pos)) != std::string::npos) { 5000 StringExtractorGDBRemote profileDataExtractor( 5001 input.substr(pos, found).c_str()); 5002 std::string profile_data = 5003 HarmonizeThreadIdsForProfileData(profileDataExtractor); 5004 BroadcastAsyncProfileData(profile_data); 5005 5006 pos = found + end_delimiter_len; 5007 } 5008 5009 if (pos < len) { 5010 // Last incomplete chunk. 5011 m_partial_profile_data = input.substr(pos); 5012 } 5013 } 5014 5015 std::string ProcessGDBRemote::HarmonizeThreadIdsForProfileData( 5016 StringExtractorGDBRemote &profileDataExtractor) { 5017 std::map<uint64_t, uint32_t> new_thread_id_to_used_usec_map; 5018 std::string output; 5019 llvm::raw_string_ostream output_stream(output); 5020 llvm::StringRef name, value; 5021 5022 // Going to assuming thread_used_usec comes first, else bail out. 5023 while (profileDataExtractor.GetNameColonValue(name, value)) { 5024 if (name.compare("thread_used_id") == 0) { 5025 StringExtractor threadIDHexExtractor(value); 5026 uint64_t thread_id = threadIDHexExtractor.GetHexMaxU64(false, 0); 5027 5028 bool has_used_usec = false; 5029 uint32_t curr_used_usec = 0; 5030 llvm::StringRef usec_name, usec_value; 5031 uint32_t input_file_pos = profileDataExtractor.GetFilePos(); 5032 if (profileDataExtractor.GetNameColonValue(usec_name, usec_value)) { 5033 if (usec_name.equals("thread_used_usec")) { 5034 has_used_usec = true; 5035 usec_value.getAsInteger(0, curr_used_usec); 5036 } else { 5037 // We didn't find what we want, it is probably an older version. Bail 5038 // out. 5039 profileDataExtractor.SetFilePos(input_file_pos); 5040 } 5041 } 5042 5043 if (has_used_usec) { 5044 uint32_t prev_used_usec = 0; 5045 std::map<uint64_t, uint32_t>::iterator iterator = 5046 m_thread_id_to_used_usec_map.find(thread_id); 5047 if (iterator != m_thread_id_to_used_usec_map.end()) { 5048 prev_used_usec = m_thread_id_to_used_usec_map[thread_id]; 5049 } 5050 5051 uint32_t real_used_usec = curr_used_usec - prev_used_usec; 5052 // A good first time record is one that runs for at least 0.25 sec 5053 bool good_first_time = 5054 (prev_used_usec == 0) && (real_used_usec > 250000); 5055 bool good_subsequent_time = 5056 (prev_used_usec > 0) && 5057 ((real_used_usec > 0) || (HasAssignedIndexIDToThread(thread_id))); 5058 5059 if (good_first_time || good_subsequent_time) { 5060 // We try to avoid doing too many index id reservation, resulting in 5061 // fast increase of index ids. 5062 5063 output_stream << name << ":"; 5064 int32_t index_id = AssignIndexIDToThread(thread_id); 5065 output_stream << index_id << ";"; 5066 5067 output_stream << usec_name << ":" << usec_value << ";"; 5068 } else { 5069 // Skip past 'thread_used_name'. 5070 llvm::StringRef local_name, local_value; 5071 profileDataExtractor.GetNameColonValue(local_name, local_value); 5072 } 5073 5074 // Store current time as previous time so that they can be compared 5075 // later. 5076 new_thread_id_to_used_usec_map[thread_id] = curr_used_usec; 5077 } else { 5078 // Bail out and use old string. 5079 output_stream << name << ":" << value << ";"; 5080 } 5081 } else { 5082 output_stream << name << ":" << value << ";"; 5083 } 5084 } 5085 output_stream << end_delimiter; 5086 m_thread_id_to_used_usec_map = new_thread_id_to_used_usec_map; 5087 5088 return output_stream.str(); 5089 } 5090 5091 void ProcessGDBRemote::HandleStopReply() { 5092 if (GetStopID() != 0) 5093 return; 5094 5095 if (GetID() == LLDB_INVALID_PROCESS_ID) { 5096 lldb::pid_t pid = m_gdb_comm.GetCurrentProcessID(); 5097 if (pid != LLDB_INVALID_PROCESS_ID) 5098 SetID(pid); 5099 } 5100 BuildDynamicRegisterInfo(true); 5101 } 5102 5103 static const char *const s_async_json_packet_prefix = "JSON-async:"; 5104 5105 static StructuredData::ObjectSP 5106 ParseStructuredDataPacket(llvm::StringRef packet) { 5107 Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS)); 5108 5109 if (!packet.consume_front(s_async_json_packet_prefix)) { 5110 if (log) { 5111 LLDB_LOGF( 5112 log, 5113 "GDBRemoteCommunicationClientBase::%s() received $J packet " 5114 "but was not a StructuredData packet: packet starts with " 5115 "%s", 5116 __FUNCTION__, 5117 packet.slice(0, strlen(s_async_json_packet_prefix)).str().c_str()); 5118 } 5119 return StructuredData::ObjectSP(); 5120 } 5121 5122 // This is an asynchronous JSON packet, destined for a StructuredDataPlugin. 5123 StructuredData::ObjectSP json_sp = StructuredData::ParseJSON(packet); 5124 if (log) { 5125 if (json_sp) { 5126 StreamString json_str; 5127 json_sp->Dump(json_str); 5128 json_str.Flush(); 5129 LLDB_LOGF(log, 5130 "ProcessGDBRemote::%s() " 5131 "received Async StructuredData packet: %s", 5132 __FUNCTION__, json_str.GetData()); 5133 } else { 5134 LLDB_LOGF(log, 5135 "ProcessGDBRemote::%s" 5136 "() received StructuredData packet:" 5137 " parse failure", 5138 __FUNCTION__); 5139 } 5140 } 5141 return json_sp; 5142 } 5143 5144 void ProcessGDBRemote::HandleAsyncStructuredDataPacket(llvm::StringRef data) { 5145 auto structured_data_sp = ParseStructuredDataPacket(data); 5146 if (structured_data_sp) 5147 RouteAsyncStructuredData(structured_data_sp); 5148 } 5149 5150 class CommandObjectProcessGDBRemoteSpeedTest : public CommandObjectParsed { 5151 public: 5152 CommandObjectProcessGDBRemoteSpeedTest(CommandInterpreter &interpreter) 5153 : CommandObjectParsed(interpreter, "process plugin packet speed-test", 5154 "Tests packet speeds of various sizes to determine " 5155 "the performance characteristics of the GDB remote " 5156 "connection. ", 5157 nullptr), 5158 m_option_group(), 5159 m_num_packets(LLDB_OPT_SET_1, false, "count", 'c', 0, eArgTypeCount, 5160 "The number of packets to send of each varying size " 5161 "(default is 1000).", 5162 1000), 5163 m_max_send(LLDB_OPT_SET_1, false, "max-send", 's', 0, eArgTypeCount, 5164 "The maximum number of bytes to send in a packet. Sizes " 5165 "increase in powers of 2 while the size is less than or " 5166 "equal to this option value. (default 1024).", 5167 1024), 5168 m_max_recv(LLDB_OPT_SET_1, false, "max-receive", 'r', 0, eArgTypeCount, 5169 "The maximum number of bytes to receive in a packet. Sizes " 5170 "increase in powers of 2 while the size is less than or " 5171 "equal to this option value. (default 1024).", 5172 1024), 5173 m_json(LLDB_OPT_SET_1, false, "json", 'j', 5174 "Print the output as JSON data for easy parsing.", false, true) { 5175 m_option_group.Append(&m_num_packets, LLDB_OPT_SET_ALL, LLDB_OPT_SET_1); 5176 m_option_group.Append(&m_max_send, LLDB_OPT_SET_ALL, LLDB_OPT_SET_1); 5177 m_option_group.Append(&m_max_recv, LLDB_OPT_SET_ALL, LLDB_OPT_SET_1); 5178 m_option_group.Append(&m_json, LLDB_OPT_SET_ALL, LLDB_OPT_SET_1); 5179 m_option_group.Finalize(); 5180 } 5181 5182 ~CommandObjectProcessGDBRemoteSpeedTest() override {} 5183 5184 Options *GetOptions() override { return &m_option_group; } 5185 5186 bool DoExecute(Args &command, CommandReturnObject &result) override { 5187 const size_t argc = command.GetArgumentCount(); 5188 if (argc == 0) { 5189 ProcessGDBRemote *process = 5190 (ProcessGDBRemote *)m_interpreter.GetExecutionContext() 5191 .GetProcessPtr(); 5192 if (process) { 5193 StreamSP output_stream_sp( 5194 m_interpreter.GetDebugger().GetAsyncOutputStream()); 5195 result.SetImmediateOutputStream(output_stream_sp); 5196 5197 const uint32_t num_packets = 5198 (uint32_t)m_num_packets.GetOptionValue().GetCurrentValue(); 5199 const uint64_t max_send = m_max_send.GetOptionValue().GetCurrentValue(); 5200 const uint64_t max_recv = m_max_recv.GetOptionValue().GetCurrentValue(); 5201 const bool json = m_json.GetOptionValue().GetCurrentValue(); 5202 const uint64_t k_recv_amount = 5203 4 * 1024 * 1024; // Receive amount in bytes 5204 process->GetGDBRemote().TestPacketSpeed( 5205 num_packets, max_send, max_recv, k_recv_amount, json, 5206 output_stream_sp ? *output_stream_sp : result.GetOutputStream()); 5207 result.SetStatus(eReturnStatusSuccessFinishResult); 5208 return true; 5209 } 5210 } else { 5211 result.AppendErrorWithFormat("'%s' takes no arguments", 5212 m_cmd_name.c_str()); 5213 } 5214 result.SetStatus(eReturnStatusFailed); 5215 return false; 5216 } 5217 5218 protected: 5219 OptionGroupOptions m_option_group; 5220 OptionGroupUInt64 m_num_packets; 5221 OptionGroupUInt64 m_max_send; 5222 OptionGroupUInt64 m_max_recv; 5223 OptionGroupBoolean m_json; 5224 }; 5225 5226 class CommandObjectProcessGDBRemotePacketHistory : public CommandObjectParsed { 5227 private: 5228 public: 5229 CommandObjectProcessGDBRemotePacketHistory(CommandInterpreter &interpreter) 5230 : CommandObjectParsed(interpreter, "process plugin packet history", 5231 "Dumps the packet history buffer. ", nullptr) {} 5232 5233 ~CommandObjectProcessGDBRemotePacketHistory() override {} 5234 5235 bool DoExecute(Args &command, CommandReturnObject &result) override { 5236 const size_t argc = command.GetArgumentCount(); 5237 if (argc == 0) { 5238 ProcessGDBRemote *process = 5239 (ProcessGDBRemote *)m_interpreter.GetExecutionContext() 5240 .GetProcessPtr(); 5241 if (process) { 5242 process->GetGDBRemote().DumpHistory(result.GetOutputStream()); 5243 result.SetStatus(eReturnStatusSuccessFinishResult); 5244 return true; 5245 } 5246 } else { 5247 result.AppendErrorWithFormat("'%s' takes no arguments", 5248 m_cmd_name.c_str()); 5249 } 5250 result.SetStatus(eReturnStatusFailed); 5251 return false; 5252 } 5253 }; 5254 5255 class CommandObjectProcessGDBRemotePacketXferSize : public CommandObjectParsed { 5256 private: 5257 public: 5258 CommandObjectProcessGDBRemotePacketXferSize(CommandInterpreter &interpreter) 5259 : CommandObjectParsed( 5260 interpreter, "process plugin packet xfer-size", 5261 "Maximum size that lldb will try to read/write one one chunk.", 5262 nullptr) {} 5263 5264 ~CommandObjectProcessGDBRemotePacketXferSize() override {} 5265 5266 bool DoExecute(Args &command, CommandReturnObject &result) override { 5267 const size_t argc = command.GetArgumentCount(); 5268 if (argc == 0) { 5269 result.AppendErrorWithFormat("'%s' takes an argument to specify the max " 5270 "amount to be transferred when " 5271 "reading/writing", 5272 m_cmd_name.c_str()); 5273 result.SetStatus(eReturnStatusFailed); 5274 return false; 5275 } 5276 5277 ProcessGDBRemote *process = 5278 (ProcessGDBRemote *)m_interpreter.GetExecutionContext().GetProcessPtr(); 5279 if (process) { 5280 const char *packet_size = command.GetArgumentAtIndex(0); 5281 errno = 0; 5282 uint64_t user_specified_max = strtoul(packet_size, nullptr, 10); 5283 if (errno == 0 && user_specified_max != 0) { 5284 process->SetUserSpecifiedMaxMemoryTransferSize(user_specified_max); 5285 result.SetStatus(eReturnStatusSuccessFinishResult); 5286 return true; 5287 } 5288 } 5289 result.SetStatus(eReturnStatusFailed); 5290 return false; 5291 } 5292 }; 5293 5294 class CommandObjectProcessGDBRemotePacketSend : public CommandObjectParsed { 5295 private: 5296 public: 5297 CommandObjectProcessGDBRemotePacketSend(CommandInterpreter &interpreter) 5298 : CommandObjectParsed(interpreter, "process plugin packet send", 5299 "Send a custom packet through the GDB remote " 5300 "protocol and print the answer. " 5301 "The packet header and footer will automatically " 5302 "be added to the packet prior to sending and " 5303 "stripped from the result.", 5304 nullptr) {} 5305 5306 ~CommandObjectProcessGDBRemotePacketSend() override {} 5307 5308 bool DoExecute(Args &command, CommandReturnObject &result) override { 5309 const size_t argc = command.GetArgumentCount(); 5310 if (argc == 0) { 5311 result.AppendErrorWithFormat( 5312 "'%s' takes a one or more packet content arguments", 5313 m_cmd_name.c_str()); 5314 result.SetStatus(eReturnStatusFailed); 5315 return false; 5316 } 5317 5318 ProcessGDBRemote *process = 5319 (ProcessGDBRemote *)m_interpreter.GetExecutionContext().GetProcessPtr(); 5320 if (process) { 5321 for (size_t i = 0; i < argc; ++i) { 5322 const char *packet_cstr = command.GetArgumentAtIndex(0); 5323 bool send_async = true; 5324 StringExtractorGDBRemote response; 5325 process->GetGDBRemote().SendPacketAndWaitForResponse( 5326 packet_cstr, response, send_async); 5327 result.SetStatus(eReturnStatusSuccessFinishResult); 5328 Stream &output_strm = result.GetOutputStream(); 5329 output_strm.Printf(" packet: %s\n", packet_cstr); 5330 std::string &response_str = response.GetStringRef(); 5331 5332 if (strstr(packet_cstr, "qGetProfileData") != nullptr) { 5333 response_str = process->HarmonizeThreadIdsForProfileData(response); 5334 } 5335 5336 if (response_str.empty()) 5337 output_strm.PutCString("response: \nerror: UNIMPLEMENTED\n"); 5338 else 5339 output_strm.Printf("response: %s\n", response.GetStringRef().c_str()); 5340 } 5341 } 5342 return true; 5343 } 5344 }; 5345 5346 class CommandObjectProcessGDBRemotePacketMonitor : public CommandObjectRaw { 5347 private: 5348 public: 5349 CommandObjectProcessGDBRemotePacketMonitor(CommandInterpreter &interpreter) 5350 : CommandObjectRaw(interpreter, "process plugin packet monitor", 5351 "Send a qRcmd packet through the GDB remote protocol " 5352 "and print the response." 5353 "The argument passed to this command will be hex " 5354 "encoded into a valid 'qRcmd' packet, sent and the " 5355 "response will be printed.") {} 5356 5357 ~CommandObjectProcessGDBRemotePacketMonitor() override {} 5358 5359 bool DoExecute(llvm::StringRef command, 5360 CommandReturnObject &result) override { 5361 if (command.empty()) { 5362 result.AppendErrorWithFormat("'%s' takes a command string argument", 5363 m_cmd_name.c_str()); 5364 result.SetStatus(eReturnStatusFailed); 5365 return false; 5366 } 5367 5368 ProcessGDBRemote *process = 5369 (ProcessGDBRemote *)m_interpreter.GetExecutionContext().GetProcessPtr(); 5370 if (process) { 5371 StreamString packet; 5372 packet.PutCString("qRcmd,"); 5373 packet.PutBytesAsRawHex8(command.data(), command.size()); 5374 5375 bool send_async = true; 5376 StringExtractorGDBRemote response; 5377 Stream &output_strm = result.GetOutputStream(); 5378 process->GetGDBRemote().SendPacketAndReceiveResponseWithOutputSupport( 5379 packet.GetString(), response, send_async, 5380 [&output_strm](llvm::StringRef output) { output_strm << output; }); 5381 result.SetStatus(eReturnStatusSuccessFinishResult); 5382 output_strm.Printf(" packet: %s\n", packet.GetData()); 5383 const std::string &response_str = response.GetStringRef(); 5384 5385 if (response_str.empty()) 5386 output_strm.PutCString("response: \nerror: UNIMPLEMENTED\n"); 5387 else 5388 output_strm.Printf("response: %s\n", response.GetStringRef().c_str()); 5389 } 5390 return true; 5391 } 5392 }; 5393 5394 class CommandObjectProcessGDBRemotePacket : public CommandObjectMultiword { 5395 private: 5396 public: 5397 CommandObjectProcessGDBRemotePacket(CommandInterpreter &interpreter) 5398 : CommandObjectMultiword(interpreter, "process plugin packet", 5399 "Commands that deal with GDB remote packets.", 5400 nullptr) { 5401 LoadSubCommand( 5402 "history", 5403 CommandObjectSP( 5404 new CommandObjectProcessGDBRemotePacketHistory(interpreter))); 5405 LoadSubCommand( 5406 "send", CommandObjectSP( 5407 new CommandObjectProcessGDBRemotePacketSend(interpreter))); 5408 LoadSubCommand( 5409 "monitor", 5410 CommandObjectSP( 5411 new CommandObjectProcessGDBRemotePacketMonitor(interpreter))); 5412 LoadSubCommand( 5413 "xfer-size", 5414 CommandObjectSP( 5415 new CommandObjectProcessGDBRemotePacketXferSize(interpreter))); 5416 LoadSubCommand("speed-test", 5417 CommandObjectSP(new CommandObjectProcessGDBRemoteSpeedTest( 5418 interpreter))); 5419 } 5420 5421 ~CommandObjectProcessGDBRemotePacket() override {} 5422 }; 5423 5424 class CommandObjectMultiwordProcessGDBRemote : public CommandObjectMultiword { 5425 public: 5426 CommandObjectMultiwordProcessGDBRemote(CommandInterpreter &interpreter) 5427 : CommandObjectMultiword( 5428 interpreter, "process plugin", 5429 "Commands for operating on a ProcessGDBRemote process.", 5430 "process plugin <subcommand> [<subcommand-options>]") { 5431 LoadSubCommand( 5432 "packet", 5433 CommandObjectSP(new CommandObjectProcessGDBRemotePacket(interpreter))); 5434 } 5435 5436 ~CommandObjectMultiwordProcessGDBRemote() override {} 5437 }; 5438 5439 CommandObject *ProcessGDBRemote::GetPluginCommandObject() { 5440 if (!m_command_sp) 5441 m_command_sp = std::make_shared<CommandObjectMultiwordProcessGDBRemote>( 5442 GetTarget().GetDebugger().GetCommandInterpreter()); 5443 return m_command_sp.get(); 5444 } 5445