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