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