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