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