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