1 //===-- DynamicLoaderHexagonDYLD.cpp --------------------------------------===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 9 #include "lldb/Breakpoint/BreakpointLocation.h" 10 #include "lldb/Core/Module.h" 11 #include "lldb/Core/ModuleSpec.h" 12 #include "lldb/Core/PluginManager.h" 13 #include "lldb/Core/Section.h" 14 #include "lldb/Symbol/ObjectFile.h" 15 #include "lldb/Target/Process.h" 16 #include "lldb/Target/Target.h" 17 #include "lldb/Target/Thread.h" 18 #include "lldb/Target/ThreadPlanRunToAddress.h" 19 #include "lldb/Utility/Log.h" 20 21 #include "DynamicLoaderHexagonDYLD.h" 22 23 #include <memory> 24 25 using namespace lldb; 26 using namespace lldb_private; 27 28 LLDB_PLUGIN_DEFINE(DynamicLoaderHexagonDYLD) 29 30 // Aidan 21/05/2014 31 // 32 // Notes about hexagon dynamic loading: 33 // 34 // When we connect to a target we find the dyld breakpoint address. We put 35 // a 36 // breakpoint there with a callback 'RendezvousBreakpointHit()'. 37 // 38 // It is possible to find the dyld structure address from the ELF symbol 39 // table, 40 // but in the case of the simulator it has not been initialized before the 41 // target calls dlinit(). 42 // 43 // We can only safely parse the dyld structure after we hit the dyld 44 // breakpoint 45 // since at that time we know dlinit() must have been called. 46 // 47 48 // Find the load address of a symbol 49 static lldb::addr_t findSymbolAddress(Process *proc, ConstString findName) { 50 assert(proc != nullptr); 51 52 ModuleSP module = proc->GetTarget().GetExecutableModule(); 53 assert(module.get() != nullptr); 54 55 ObjectFile *exe = module->GetObjectFile(); 56 assert(exe != nullptr); 57 58 lldb_private::Symtab *symtab = exe->GetSymtab(); 59 assert(symtab != nullptr); 60 61 for (size_t i = 0; i < symtab->GetNumSymbols(); i++) { 62 const Symbol *sym = symtab->SymbolAtIndex(i); 63 assert(sym != nullptr); 64 ConstString symName = sym->GetName(); 65 66 if (ConstString::Compare(findName, symName) == 0) { 67 Address addr = sym->GetAddress(); 68 return addr.GetLoadAddress(&proc->GetTarget()); 69 } 70 } 71 return LLDB_INVALID_ADDRESS; 72 } 73 74 void DynamicLoaderHexagonDYLD::Initialize() { 75 PluginManager::RegisterPlugin(GetPluginNameStatic(), 76 GetPluginDescriptionStatic(), CreateInstance); 77 } 78 79 void DynamicLoaderHexagonDYLD::Terminate() {} 80 81 lldb_private::ConstString DynamicLoaderHexagonDYLD::GetPluginName() { 82 return GetPluginNameStatic(); 83 } 84 85 lldb_private::ConstString DynamicLoaderHexagonDYLD::GetPluginNameStatic() { 86 static ConstString g_name("hexagon-dyld"); 87 return g_name; 88 } 89 90 const char *DynamicLoaderHexagonDYLD::GetPluginDescriptionStatic() { 91 return "Dynamic loader plug-in that watches for shared library " 92 "loads/unloads in Hexagon processes."; 93 } 94 95 uint32_t DynamicLoaderHexagonDYLD::GetPluginVersion() { return 1; } 96 97 DynamicLoader *DynamicLoaderHexagonDYLD::CreateInstance(Process *process, 98 bool force) { 99 bool create = force; 100 if (!create) { 101 const llvm::Triple &triple_ref = 102 process->GetTarget().GetArchitecture().GetTriple(); 103 if (triple_ref.getArch() == llvm::Triple::hexagon) 104 create = true; 105 } 106 107 if (create) 108 return new DynamicLoaderHexagonDYLD(process); 109 return nullptr; 110 } 111 112 DynamicLoaderHexagonDYLD::DynamicLoaderHexagonDYLD(Process *process) 113 : DynamicLoader(process), m_rendezvous(process), 114 m_load_offset(LLDB_INVALID_ADDRESS), m_entry_point(LLDB_INVALID_ADDRESS), 115 m_dyld_bid(LLDB_INVALID_BREAK_ID) {} 116 117 DynamicLoaderHexagonDYLD::~DynamicLoaderHexagonDYLD() { 118 if (m_dyld_bid != LLDB_INVALID_BREAK_ID) { 119 m_process->GetTarget().RemoveBreakpointByID(m_dyld_bid); 120 m_dyld_bid = LLDB_INVALID_BREAK_ID; 121 } 122 } 123 124 void DynamicLoaderHexagonDYLD::DidAttach() { 125 ModuleSP executable; 126 addr_t load_offset; 127 128 executable = GetTargetExecutable(); 129 130 // Find the difference between the desired load address in the elf file and 131 // the real load address in memory 132 load_offset = ComputeLoadOffset(); 133 134 // Check that there is a valid executable 135 if (executable.get() == nullptr) 136 return; 137 138 // Disable JIT for hexagon targets because its not supported 139 m_process->SetCanJIT(false); 140 141 // Enable Interpreting of function call expressions 142 m_process->SetCanInterpretFunctionCalls(true); 143 144 // Add the current executable to the module list 145 ModuleList module_list; 146 module_list.Append(executable); 147 148 // Map the loaded sections of this executable 149 if (load_offset != LLDB_INVALID_ADDRESS) 150 UpdateLoadedSections(executable, LLDB_INVALID_ADDRESS, load_offset, true); 151 152 // AD: confirm this? 153 // Load into LLDB all of the currently loaded executables in the stub 154 LoadAllCurrentModules(); 155 156 // AD: confirm this? 157 // Callback for the target to give it the loaded module list 158 m_process->GetTarget().ModulesDidLoad(module_list); 159 160 // Try to set a breakpoint at the rendezvous breakpoint. DidLaunch uses 161 // ProbeEntry() instead. That sets a breakpoint, at the dyld breakpoint 162 // address, with a callback so that when hit, the dyld structure can be 163 // parsed. 164 if (!SetRendezvousBreakpoint()) { 165 // fail 166 } 167 } 168 169 void DynamicLoaderHexagonDYLD::DidLaunch() {} 170 171 /// Checks to see if the target module has changed, updates the target 172 /// accordingly and returns the target executable module. 173 ModuleSP DynamicLoaderHexagonDYLD::GetTargetExecutable() { 174 Target &target = m_process->GetTarget(); 175 ModuleSP executable = target.GetExecutableModule(); 176 177 // There is no executable 178 if (!executable.get()) 179 return executable; 180 181 // The target executable file does not exits 182 if (!FileSystem::Instance().Exists(executable->GetFileSpec())) 183 return executable; 184 185 // Prep module for loading 186 ModuleSpec module_spec(executable->GetFileSpec(), 187 executable->GetArchitecture()); 188 ModuleSP module_sp(new Module(module_spec)); 189 190 // Check if the executable has changed and set it to the target executable if 191 // they differ. 192 if (module_sp.get() && module_sp->GetUUID().IsValid() && 193 executable->GetUUID().IsValid()) { 194 // if the executable has changed ?? 195 if (module_sp->GetUUID() != executable->GetUUID()) 196 executable.reset(); 197 } else if (executable->FileHasChanged()) 198 executable.reset(); 199 200 if (executable.get()) 201 return executable; 202 203 // TODO: What case is this code used? 204 executable = target.GetOrCreateModule(module_spec, true /* notify */); 205 if (executable.get() != target.GetExecutableModulePointer()) { 206 // Don't load dependent images since we are in dyld where we will know and 207 // find out about all images that are loaded 208 target.SetExecutableModule(executable, eLoadDependentsNo); 209 } 210 211 return executable; 212 } 213 214 // AD: Needs to be updated? 215 Status DynamicLoaderHexagonDYLD::CanLoadImage() { return Status(); } 216 217 void DynamicLoaderHexagonDYLD::UpdateLoadedSections(ModuleSP module, 218 addr_t link_map_addr, 219 addr_t base_addr, 220 bool base_addr_is_offset) { 221 Target &target = m_process->GetTarget(); 222 const SectionList *sections = GetSectionListFromModule(module); 223 224 assert(sections && "SectionList missing from loaded module."); 225 226 m_loaded_modules[module] = link_map_addr; 227 228 const size_t num_sections = sections->GetSize(); 229 230 for (unsigned i = 0; i < num_sections; ++i) { 231 SectionSP section_sp(sections->GetSectionAtIndex(i)); 232 lldb::addr_t new_load_addr = section_sp->GetFileAddress() + base_addr; 233 234 // AD: 02/05/14 235 // since our memory map starts from address 0, we must not ignore 236 // sections that load to address 0. This violates the reference 237 // ELF spec, however is used for Hexagon. 238 239 // If the file address of the section is zero then this is not an 240 // allocatable/loadable section (property of ELF sh_addr). Skip it. 241 // if (new_load_addr == base_addr) 242 // continue; 243 244 target.SetSectionLoadAddress(section_sp, new_load_addr); 245 } 246 } 247 248 /// Removes the loaded sections from the target in \p module. 249 /// 250 /// \param module The module to traverse. 251 void DynamicLoaderHexagonDYLD::UnloadSections(const ModuleSP module) { 252 Target &target = m_process->GetTarget(); 253 const SectionList *sections = GetSectionListFromModule(module); 254 255 assert(sections && "SectionList missing from unloaded module."); 256 257 m_loaded_modules.erase(module); 258 259 const size_t num_sections = sections->GetSize(); 260 for (size_t i = 0; i < num_sections; ++i) { 261 SectionSP section_sp(sections->GetSectionAtIndex(i)); 262 target.SetSectionUnloaded(section_sp); 263 } 264 } 265 266 // Place a breakpoint on <_rtld_debug_state> 267 bool DynamicLoaderHexagonDYLD::SetRendezvousBreakpoint() { 268 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_DYNAMIC_LOADER)); 269 270 // This is the original code, which want to look in the rendezvous structure 271 // to find the breakpoint address. Its backwards for us, since we can easily 272 // find the breakpoint address, since it is exported in our executable. We 273 // however know that we cant read the Rendezvous structure until we have hit 274 // the breakpoint once. 275 const ConstString dyldBpName("_rtld_debug_state"); 276 addr_t break_addr = findSymbolAddress(m_process, dyldBpName); 277 278 Target &target = m_process->GetTarget(); 279 280 // Do not try to set the breakpoint if we don't know where to put it 281 if (break_addr == LLDB_INVALID_ADDRESS) { 282 LLDB_LOGF(log, "Unable to locate _rtld_debug_state breakpoint address"); 283 284 return false; 285 } 286 287 // Save the address of the rendezvous structure 288 m_rendezvous.SetBreakAddress(break_addr); 289 290 // If we haven't set the breakpoint before then set it 291 if (m_dyld_bid == LLDB_INVALID_BREAK_ID) { 292 Breakpoint *dyld_break = 293 target.CreateBreakpoint(break_addr, true, false).get(); 294 dyld_break->SetCallback(RendezvousBreakpointHit, this, true); 295 dyld_break->SetBreakpointKind("shared-library-event"); 296 m_dyld_bid = dyld_break->GetID(); 297 298 // Make sure our breakpoint is at the right address. 299 assert(target.GetBreakpointByID(m_dyld_bid) 300 ->FindLocationByAddress(break_addr) 301 ->GetBreakpoint() 302 .GetID() == m_dyld_bid); 303 304 if (log && dyld_break == nullptr) 305 LLDB_LOGF(log, "Failed to create _rtld_debug_state breakpoint"); 306 307 // check we have successfully set bp 308 return (dyld_break != nullptr); 309 } else 310 // rendezvous already set 311 return true; 312 } 313 314 // We have just hit our breakpoint at <_rtld_debug_state> 315 bool DynamicLoaderHexagonDYLD::RendezvousBreakpointHit( 316 void *baton, StoppointCallbackContext *context, user_id_t break_id, 317 user_id_t break_loc_id) { 318 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_DYNAMIC_LOADER)); 319 320 LLDB_LOGF(log, "Rendezvous breakpoint hit!"); 321 322 DynamicLoaderHexagonDYLD *dyld_instance = nullptr; 323 dyld_instance = static_cast<DynamicLoaderHexagonDYLD *>(baton); 324 325 // if the dyld_instance is still not valid then try to locate it on the 326 // symbol table 327 if (!dyld_instance->m_rendezvous.IsValid()) { 328 Process *proc = dyld_instance->m_process; 329 330 const ConstString dyldStructName("_rtld_debug"); 331 addr_t structAddr = findSymbolAddress(proc, dyldStructName); 332 333 if (structAddr != LLDB_INVALID_ADDRESS) { 334 dyld_instance->m_rendezvous.SetRendezvousAddress(structAddr); 335 336 LLDB_LOGF(log, "Found _rtld_debug structure @ 0x%08" PRIx64, structAddr); 337 } else { 338 LLDB_LOGF(log, "Unable to resolve the _rtld_debug structure"); 339 } 340 } 341 342 dyld_instance->RefreshModules(); 343 344 // Return true to stop the target, false to just let the target run. 345 return dyld_instance->GetStopWhenImagesChange(); 346 } 347 348 /// Helper method for RendezvousBreakpointHit. Updates LLDB's current set 349 /// of loaded modules. 350 void DynamicLoaderHexagonDYLD::RefreshModules() { 351 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_DYNAMIC_LOADER)); 352 353 if (!m_rendezvous.Resolve()) 354 return; 355 356 HexagonDYLDRendezvous::iterator I; 357 HexagonDYLDRendezvous::iterator E; 358 359 ModuleList &loaded_modules = m_process->GetTarget().GetImages(); 360 361 if (m_rendezvous.ModulesDidLoad()) { 362 ModuleList new_modules; 363 364 E = m_rendezvous.loaded_end(); 365 for (I = m_rendezvous.loaded_begin(); I != E; ++I) { 366 FileSpec file(I->path); 367 FileSystem::Instance().Resolve(file); 368 ModuleSP module_sp = 369 LoadModuleAtAddress(file, I->link_addr, I->base_addr, true); 370 if (module_sp.get()) { 371 loaded_modules.AppendIfNeeded(module_sp); 372 new_modules.Append(module_sp); 373 } 374 375 if (log) { 376 LLDB_LOGF(log, "Target is loading '%s'", I->path.c_str()); 377 if (!module_sp.get()) 378 LLDB_LOGF(log, "LLDB failed to load '%s'", I->path.c_str()); 379 else 380 LLDB_LOGF(log, "LLDB successfully loaded '%s'", I->path.c_str()); 381 } 382 } 383 m_process->GetTarget().ModulesDidLoad(new_modules); 384 } 385 386 if (m_rendezvous.ModulesDidUnload()) { 387 ModuleList old_modules; 388 389 E = m_rendezvous.unloaded_end(); 390 for (I = m_rendezvous.unloaded_begin(); I != E; ++I) { 391 FileSpec file(I->path); 392 FileSystem::Instance().Resolve(file); 393 ModuleSpec module_spec(file); 394 ModuleSP module_sp = loaded_modules.FindFirstModule(module_spec); 395 396 if (module_sp.get()) { 397 old_modules.Append(module_sp); 398 UnloadSections(module_sp); 399 } 400 401 LLDB_LOGF(log, "Target is unloading '%s'", I->path.c_str()); 402 } 403 loaded_modules.Remove(old_modules); 404 m_process->GetTarget().ModulesDidUnload(old_modules, false); 405 } 406 } 407 408 // AD: This is very different to the Static Loader code. 409 // It may be wise to look over this and its relation to stack 410 // unwinding. 411 ThreadPlanSP 412 DynamicLoaderHexagonDYLD::GetStepThroughTrampolinePlan(Thread &thread, 413 bool stop) { 414 ThreadPlanSP thread_plan_sp; 415 416 StackFrame *frame = thread.GetStackFrameAtIndex(0).get(); 417 const SymbolContext &context = frame->GetSymbolContext(eSymbolContextSymbol); 418 Symbol *sym = context.symbol; 419 420 if (sym == nullptr || !sym->IsTrampoline()) 421 return thread_plan_sp; 422 423 const ConstString sym_name = 424 sym->GetMangled().GetName(Mangled::ePreferMangled); 425 if (!sym_name) 426 return thread_plan_sp; 427 428 SymbolContextList target_symbols; 429 Target &target = thread.GetProcess()->GetTarget(); 430 const ModuleList &images = target.GetImages(); 431 432 images.FindSymbolsWithNameAndType(sym_name, eSymbolTypeCode, target_symbols); 433 size_t num_targets = target_symbols.GetSize(); 434 if (!num_targets) 435 return thread_plan_sp; 436 437 typedef std::vector<lldb::addr_t> AddressVector; 438 AddressVector addrs; 439 for (size_t i = 0; i < num_targets; ++i) { 440 SymbolContext context; 441 AddressRange range; 442 if (target_symbols.GetContextAtIndex(i, context)) { 443 context.GetAddressRange(eSymbolContextEverything, 0, false, range); 444 lldb::addr_t addr = range.GetBaseAddress().GetLoadAddress(&target); 445 if (addr != LLDB_INVALID_ADDRESS) 446 addrs.push_back(addr); 447 } 448 } 449 450 if (addrs.size() > 0) { 451 AddressVector::iterator start = addrs.begin(); 452 AddressVector::iterator end = addrs.end(); 453 454 llvm::sort(start, end); 455 addrs.erase(std::unique(start, end), end); 456 thread_plan_sp = 457 std::make_shared<ThreadPlanRunToAddress>(thread, addrs, stop); 458 } 459 460 return thread_plan_sp; 461 } 462 463 /// Helper for the entry breakpoint callback. Resolves the load addresses 464 /// of all dependent modules. 465 void DynamicLoaderHexagonDYLD::LoadAllCurrentModules() { 466 HexagonDYLDRendezvous::iterator I; 467 HexagonDYLDRendezvous::iterator E; 468 ModuleList module_list; 469 470 if (!m_rendezvous.Resolve()) { 471 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_DYNAMIC_LOADER)); 472 LLDB_LOGF( 473 log, 474 "DynamicLoaderHexagonDYLD::%s unable to resolve rendezvous address", 475 __FUNCTION__); 476 return; 477 } 478 479 // The rendezvous class doesn't enumerate the main module, so track that 480 // ourselves here. 481 ModuleSP executable = GetTargetExecutable(); 482 m_loaded_modules[executable] = m_rendezvous.GetLinkMapAddress(); 483 484 for (I = m_rendezvous.begin(), E = m_rendezvous.end(); I != E; ++I) { 485 const char *module_path = I->path.c_str(); 486 FileSpec file(module_path); 487 ModuleSP module_sp = 488 LoadModuleAtAddress(file, I->link_addr, I->base_addr, true); 489 if (module_sp.get()) { 490 module_list.Append(module_sp); 491 } else { 492 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_DYNAMIC_LOADER)); 493 LLDB_LOGF(log, 494 "DynamicLoaderHexagonDYLD::%s failed loading module %s at " 495 "0x%" PRIx64, 496 __FUNCTION__, module_path, I->base_addr); 497 } 498 } 499 500 m_process->GetTarget().ModulesDidLoad(module_list); 501 } 502 503 /// Computes a value for m_load_offset returning the computed address on 504 /// success and LLDB_INVALID_ADDRESS on failure. 505 addr_t DynamicLoaderHexagonDYLD::ComputeLoadOffset() { 506 // Here we could send a GDB packet to know the load offset 507 // 508 // send: $qOffsets#4b 509 // get: Text=0;Data=0;Bss=0 510 // 511 // Currently qOffsets is not supported by pluginProcessGDBRemote 512 // 513 return 0; 514 } 515 516 // Here we must try to read the entry point directly from the elf header. This 517 // is possible if the process is not relocatable or dynamically linked. 518 // 519 // an alternative is to look at the PC if we can be sure that we have connected 520 // when the process is at the entry point. 521 // I dont think that is reliable for us. 522 addr_t DynamicLoaderHexagonDYLD::GetEntryPoint() { 523 if (m_entry_point != LLDB_INVALID_ADDRESS) 524 return m_entry_point; 525 // check we have a valid process 526 if (m_process == nullptr) 527 return LLDB_INVALID_ADDRESS; 528 // Get the current executable module 529 Module &module = *(m_process->GetTarget().GetExecutableModule().get()); 530 // Get the object file (elf file) for this module 531 lldb_private::ObjectFile &object = *(module.GetObjectFile()); 532 // Check if the file is executable (ie, not shared object or relocatable) 533 if (object.IsExecutable()) { 534 // Get the entry point address for this object 535 lldb_private::Address entry = object.GetEntryPointAddress(); 536 // Return the entry point address 537 return entry.GetFileAddress(); 538 } 539 // No idea so back out 540 return LLDB_INVALID_ADDRESS; 541 } 542 543 const SectionList *DynamicLoaderHexagonDYLD::GetSectionListFromModule( 544 const ModuleSP module) const { 545 SectionList *sections = nullptr; 546 if (module.get()) { 547 ObjectFile *obj_file = module->GetObjectFile(); 548 if (obj_file) { 549 sections = obj_file->GetSectionList(); 550 } 551 } 552 return sections; 553 } 554 555 static int ReadInt(Process *process, addr_t addr) { 556 Status error; 557 int value = (int)process->ReadUnsignedIntegerFromMemory( 558 addr, sizeof(uint32_t), 0, error); 559 if (error.Fail()) 560 return -1; 561 else 562 return value; 563 } 564 565 lldb::addr_t 566 DynamicLoaderHexagonDYLD::GetThreadLocalData(const lldb::ModuleSP module, 567 const lldb::ThreadSP thread, 568 lldb::addr_t tls_file_addr) { 569 auto it = m_loaded_modules.find(module); 570 if (it == m_loaded_modules.end()) 571 return LLDB_INVALID_ADDRESS; 572 573 addr_t link_map = it->second; 574 if (link_map == LLDB_INVALID_ADDRESS) 575 return LLDB_INVALID_ADDRESS; 576 577 const HexagonDYLDRendezvous::ThreadInfo &metadata = 578 m_rendezvous.GetThreadInfo(); 579 if (!metadata.valid) 580 return LLDB_INVALID_ADDRESS; 581 582 // Get the thread pointer. 583 addr_t tp = thread->GetThreadPointer(); 584 if (tp == LLDB_INVALID_ADDRESS) 585 return LLDB_INVALID_ADDRESS; 586 587 // Find the module's modid. 588 int modid = ReadInt(m_process, link_map + metadata.modid_offset); 589 if (modid == -1) 590 return LLDB_INVALID_ADDRESS; 591 592 // Lookup the DTV structure for this thread. 593 addr_t dtv_ptr = tp + metadata.dtv_offset; 594 addr_t dtv = ReadPointer(dtv_ptr); 595 if (dtv == LLDB_INVALID_ADDRESS) 596 return LLDB_INVALID_ADDRESS; 597 598 // Find the TLS block for this module. 599 addr_t dtv_slot = dtv + metadata.dtv_slot_size * modid; 600 addr_t tls_block = ReadPointer(dtv_slot + metadata.tls_offset); 601 602 Module *mod = module.get(); 603 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_DYNAMIC_LOADER)); 604 LLDB_LOGF(log, 605 "DynamicLoaderHexagonDYLD::Performed TLS lookup: " 606 "module=%s, link_map=0x%" PRIx64 ", tp=0x%" PRIx64 607 ", modid=%i, tls_block=0x%" PRIx64, 608 mod->GetObjectName().AsCString(""), link_map, tp, modid, tls_block); 609 610 if (tls_block == LLDB_INVALID_ADDRESS) 611 return LLDB_INVALID_ADDRESS; 612 else 613 return tls_block + tls_file_addr; 614 } 615