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