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