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