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