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