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