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