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