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