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