Path: blob/main/contrib/llvm-project/lldb/source/Plugins/DynamicLoader/Hexagon-DYLD/DynamicLoaderHexagonDYLD.cpp
39653 views
//===-- DynamicLoaderHexagonDYLD.cpp --------------------------------------===//1//2// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.3// See https://llvm.org/LICENSE.txt for license information.4// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception5//6//===----------------------------------------------------------------------===//78#include "lldb/Breakpoint/BreakpointLocation.h"9#include "lldb/Core/Module.h"10#include "lldb/Core/ModuleSpec.h"11#include "lldb/Core/PluginManager.h"12#include "lldb/Core/Section.h"13#include "lldb/Symbol/ObjectFile.h"14#include "lldb/Target/Process.h"15#include "lldb/Target/Target.h"16#include "lldb/Target/Thread.h"17#include "lldb/Target/ThreadPlanRunToAddress.h"18#include "lldb/Utility/LLDBLog.h"19#include "lldb/Utility/Log.h"2021#include "DynamicLoaderHexagonDYLD.h"2223#include <memory>2425using namespace lldb;26using namespace lldb_private;2728LLDB_PLUGIN_DEFINE(DynamicLoaderHexagonDYLD)2930// Aidan 21/05/201431//32// Notes about hexagon dynamic loading:33//34// When we connect to a target we find the dyld breakpoint address. We put35// a36// breakpoint there with a callback 'RendezvousBreakpointHit()'.37//38// It is possible to find the dyld structure address from the ELF symbol39// table,40// but in the case of the simulator it has not been initialized before the41// target calls dlinit().42//43// We can only safely parse the dyld structure after we hit the dyld44// breakpoint45// since at that time we know dlinit() must have been called.46//4748// Find the load address of a symbol49static lldb::addr_t findSymbolAddress(Process *proc, ConstString findName) {50assert(proc != nullptr);5152ModuleSP module = proc->GetTarget().GetExecutableModule();53assert(module.get() != nullptr);5455ObjectFile *exe = module->GetObjectFile();56assert(exe != nullptr);5758lldb_private::Symtab *symtab = exe->GetSymtab();59assert(symtab != nullptr);6061for (size_t i = 0; i < symtab->GetNumSymbols(); i++) {62const Symbol *sym = symtab->SymbolAtIndex(i);63assert(sym != nullptr);64ConstString symName = sym->GetName();6566if (ConstString::Compare(findName, symName) == 0) {67Address addr = sym->GetAddress();68return addr.GetLoadAddress(&proc->GetTarget());69}70}71return LLDB_INVALID_ADDRESS;72}7374void DynamicLoaderHexagonDYLD::Initialize() {75PluginManager::RegisterPlugin(GetPluginNameStatic(),76GetPluginDescriptionStatic(), CreateInstance);77}7879void DynamicLoaderHexagonDYLD::Terminate() {}8081llvm::StringRef DynamicLoaderHexagonDYLD::GetPluginDescriptionStatic() {82return "Dynamic loader plug-in that watches for shared library "83"loads/unloads in Hexagon processes.";84}8586DynamicLoader *DynamicLoaderHexagonDYLD::CreateInstance(Process *process,87bool force) {88bool create = force;89if (!create) {90const llvm::Triple &triple_ref =91process->GetTarget().GetArchitecture().GetTriple();92if (triple_ref.getArch() == llvm::Triple::hexagon)93create = true;94}9596if (create)97return new DynamicLoaderHexagonDYLD(process);98return nullptr;99}100101DynamicLoaderHexagonDYLD::DynamicLoaderHexagonDYLD(Process *process)102: DynamicLoader(process), m_rendezvous(process),103m_load_offset(LLDB_INVALID_ADDRESS), m_entry_point(LLDB_INVALID_ADDRESS),104m_dyld_bid(LLDB_INVALID_BREAK_ID) {}105106DynamicLoaderHexagonDYLD::~DynamicLoaderHexagonDYLD() {107if (m_dyld_bid != LLDB_INVALID_BREAK_ID) {108m_process->GetTarget().RemoveBreakpointByID(m_dyld_bid);109m_dyld_bid = LLDB_INVALID_BREAK_ID;110}111}112113void DynamicLoaderHexagonDYLD::DidAttach() {114ModuleSP executable;115addr_t load_offset;116117executable = GetTargetExecutable();118119// Find the difference between the desired load address in the elf file and120// the real load address in memory121load_offset = ComputeLoadOffset();122123// Check that there is a valid executable124if (executable.get() == nullptr)125return;126127// Disable JIT for hexagon targets because its not supported128m_process->SetCanJIT(false);129130// Enable Interpreting of function call expressions131m_process->SetCanInterpretFunctionCalls(true);132133// Add the current executable to the module list134ModuleList module_list;135module_list.Append(executable);136137// Map the loaded sections of this executable138if (load_offset != LLDB_INVALID_ADDRESS)139UpdateLoadedSections(executable, LLDB_INVALID_ADDRESS, load_offset, true);140141// AD: confirm this?142// Load into LLDB all of the currently loaded executables in the stub143LoadAllCurrentModules();144145// AD: confirm this?146// Callback for the target to give it the loaded module list147m_process->GetTarget().ModulesDidLoad(module_list);148149// Try to set a breakpoint at the rendezvous breakpoint. DidLaunch uses150// ProbeEntry() instead. That sets a breakpoint, at the dyld breakpoint151// address, with a callback so that when hit, the dyld structure can be152// parsed.153if (!SetRendezvousBreakpoint()) {154// fail155}156}157158void DynamicLoaderHexagonDYLD::DidLaunch() {}159160/// Checks to see if the target module has changed, updates the target161/// accordingly and returns the target executable module.162ModuleSP DynamicLoaderHexagonDYLD::GetTargetExecutable() {163Target &target = m_process->GetTarget();164ModuleSP executable = target.GetExecutableModule();165166// There is no executable167if (!executable.get())168return executable;169170// The target executable file does not exits171if (!FileSystem::Instance().Exists(executable->GetFileSpec()))172return executable;173174// Prep module for loading175ModuleSpec module_spec(executable->GetFileSpec(),176executable->GetArchitecture());177ModuleSP module_sp(new Module(module_spec));178179// Check if the executable has changed and set it to the target executable if180// they differ.181if (module_sp.get() && module_sp->GetUUID().IsValid() &&182executable->GetUUID().IsValid()) {183// if the executable has changed ??184if (module_sp->GetUUID() != executable->GetUUID())185executable.reset();186} else if (executable->FileHasChanged())187executable.reset();188189if (executable.get())190return executable;191192// TODO: What case is this code used?193executable = target.GetOrCreateModule(module_spec, true /* notify */);194if (executable.get() != target.GetExecutableModulePointer()) {195// Don't load dependent images since we are in dyld where we will know and196// find out about all images that are loaded197target.SetExecutableModule(executable, eLoadDependentsNo);198}199200return executable;201}202203// AD: Needs to be updated?204Status DynamicLoaderHexagonDYLD::CanLoadImage() { return Status(); }205206void DynamicLoaderHexagonDYLD::UpdateLoadedSections(ModuleSP module,207addr_t link_map_addr,208addr_t base_addr,209bool base_addr_is_offset) {210Target &target = m_process->GetTarget();211const SectionList *sections = GetSectionListFromModule(module);212213assert(sections && "SectionList missing from loaded module.");214215m_loaded_modules[module] = link_map_addr;216217const size_t num_sections = sections->GetSize();218219for (unsigned i = 0; i < num_sections; ++i) {220SectionSP section_sp(sections->GetSectionAtIndex(i));221lldb::addr_t new_load_addr = section_sp->GetFileAddress() + base_addr;222223// AD: 02/05/14224// since our memory map starts from address 0, we must not ignore225// sections that load to address 0. This violates the reference226// ELF spec, however is used for Hexagon.227228// If the file address of the section is zero then this is not an229// allocatable/loadable section (property of ELF sh_addr). Skip it.230// if (new_load_addr == base_addr)231// continue;232233target.SetSectionLoadAddress(section_sp, new_load_addr);234}235}236237/// Removes the loaded sections from the target in \p module.238///239/// \param module The module to traverse.240void DynamicLoaderHexagonDYLD::UnloadSections(const ModuleSP module) {241Target &target = m_process->GetTarget();242const SectionList *sections = GetSectionListFromModule(module);243244assert(sections && "SectionList missing from unloaded module.");245246m_loaded_modules.erase(module);247248const size_t num_sections = sections->GetSize();249for (size_t i = 0; i < num_sections; ++i) {250SectionSP section_sp(sections->GetSectionAtIndex(i));251target.SetSectionUnloaded(section_sp);252}253}254255// Place a breakpoint on <_rtld_debug_state>256bool DynamicLoaderHexagonDYLD::SetRendezvousBreakpoint() {257Log *log = GetLog(LLDBLog::DynamicLoader);258259// This is the original code, which want to look in the rendezvous structure260// to find the breakpoint address. Its backwards for us, since we can easily261// find the breakpoint address, since it is exported in our executable. We262// however know that we cant read the Rendezvous structure until we have hit263// the breakpoint once.264const ConstString dyldBpName("_rtld_debug_state");265addr_t break_addr = findSymbolAddress(m_process, dyldBpName);266267Target &target = m_process->GetTarget();268269// Do not try to set the breakpoint if we don't know where to put it270if (break_addr == LLDB_INVALID_ADDRESS) {271LLDB_LOGF(log, "Unable to locate _rtld_debug_state breakpoint address");272273return false;274}275276// Save the address of the rendezvous structure277m_rendezvous.SetBreakAddress(break_addr);278279// If we haven't set the breakpoint before then set it280if (m_dyld_bid == LLDB_INVALID_BREAK_ID) {281Breakpoint *dyld_break =282target.CreateBreakpoint(break_addr, true, false).get();283dyld_break->SetCallback(RendezvousBreakpointHit, this, true);284dyld_break->SetBreakpointKind("shared-library-event");285m_dyld_bid = dyld_break->GetID();286287// Make sure our breakpoint is at the right address.288assert(target.GetBreakpointByID(m_dyld_bid)289->FindLocationByAddress(break_addr)290->GetBreakpoint()291.GetID() == m_dyld_bid);292293if (log && dyld_break == nullptr)294LLDB_LOGF(log, "Failed to create _rtld_debug_state breakpoint");295296// check we have successfully set bp297return (dyld_break != nullptr);298} else299// rendezvous already set300return true;301}302303// We have just hit our breakpoint at <_rtld_debug_state>304bool DynamicLoaderHexagonDYLD::RendezvousBreakpointHit(305void *baton, StoppointCallbackContext *context, user_id_t break_id,306user_id_t break_loc_id) {307Log *log = GetLog(LLDBLog::DynamicLoader);308309LLDB_LOGF(log, "Rendezvous breakpoint hit!");310311DynamicLoaderHexagonDYLD *dyld_instance = nullptr;312dyld_instance = static_cast<DynamicLoaderHexagonDYLD *>(baton);313314// if the dyld_instance is still not valid then try to locate it on the315// symbol table316if (!dyld_instance->m_rendezvous.IsValid()) {317Process *proc = dyld_instance->m_process;318319const ConstString dyldStructName("_rtld_debug");320addr_t structAddr = findSymbolAddress(proc, dyldStructName);321322if (structAddr != LLDB_INVALID_ADDRESS) {323dyld_instance->m_rendezvous.SetRendezvousAddress(structAddr);324325LLDB_LOGF(log, "Found _rtld_debug structure @ 0x%08" PRIx64, structAddr);326} else {327LLDB_LOGF(log, "Unable to resolve the _rtld_debug structure");328}329}330331dyld_instance->RefreshModules();332333// Return true to stop the target, false to just let the target run.334return dyld_instance->GetStopWhenImagesChange();335}336337/// Helper method for RendezvousBreakpointHit. Updates LLDB's current set338/// of loaded modules.339void DynamicLoaderHexagonDYLD::RefreshModules() {340Log *log = GetLog(LLDBLog::DynamicLoader);341342if (!m_rendezvous.Resolve())343return;344345HexagonDYLDRendezvous::iterator I;346HexagonDYLDRendezvous::iterator E;347348ModuleList &loaded_modules = m_process->GetTarget().GetImages();349350if (m_rendezvous.ModulesDidLoad()) {351ModuleList new_modules;352353E = m_rendezvous.loaded_end();354for (I = m_rendezvous.loaded_begin(); I != E; ++I) {355FileSpec file(I->path);356FileSystem::Instance().Resolve(file);357ModuleSP module_sp =358LoadModuleAtAddress(file, I->link_addr, I->base_addr, true);359if (module_sp.get()) {360loaded_modules.AppendIfNeeded(module_sp);361new_modules.Append(module_sp);362}363364if (log) {365LLDB_LOGF(log, "Target is loading '%s'", I->path.c_str());366if (!module_sp.get())367LLDB_LOGF(log, "LLDB failed to load '%s'", I->path.c_str());368else369LLDB_LOGF(log, "LLDB successfully loaded '%s'", I->path.c_str());370}371}372m_process->GetTarget().ModulesDidLoad(new_modules);373}374375if (m_rendezvous.ModulesDidUnload()) {376ModuleList old_modules;377378E = m_rendezvous.unloaded_end();379for (I = m_rendezvous.unloaded_begin(); I != E; ++I) {380FileSpec file(I->path);381FileSystem::Instance().Resolve(file);382ModuleSpec module_spec(file);383ModuleSP module_sp = loaded_modules.FindFirstModule(module_spec);384385if (module_sp.get()) {386old_modules.Append(module_sp);387UnloadSections(module_sp);388}389390LLDB_LOGF(log, "Target is unloading '%s'", I->path.c_str());391}392loaded_modules.Remove(old_modules);393m_process->GetTarget().ModulesDidUnload(old_modules, false);394}395}396397// AD: This is very different to the Static Loader code.398// It may be wise to look over this and its relation to stack399// unwinding.400ThreadPlanSP401DynamicLoaderHexagonDYLD::GetStepThroughTrampolinePlan(Thread &thread,402bool stop) {403ThreadPlanSP thread_plan_sp;404405StackFrame *frame = thread.GetStackFrameAtIndex(0).get();406const SymbolContext &context = frame->GetSymbolContext(eSymbolContextSymbol);407Symbol *sym = context.symbol;408409if (sym == nullptr || !sym->IsTrampoline())410return thread_plan_sp;411412const ConstString sym_name =413sym->GetMangled().GetName(Mangled::ePreferMangled);414if (!sym_name)415return thread_plan_sp;416417SymbolContextList target_symbols;418Target &target = thread.GetProcess()->GetTarget();419const ModuleList &images = target.GetImages();420421images.FindSymbolsWithNameAndType(sym_name, eSymbolTypeCode, target_symbols);422if (target_symbols.GetSize() == 0)423return thread_plan_sp;424425typedef std::vector<lldb::addr_t> AddressVector;426AddressVector addrs;427for (const SymbolContext &context : target_symbols) {428AddressRange range;429context.GetAddressRange(eSymbolContextEverything, 0, false, range);430lldb::addr_t addr = range.GetBaseAddress().GetLoadAddress(&target);431if (addr != LLDB_INVALID_ADDRESS)432addrs.push_back(addr);433}434435if (addrs.size() > 0) {436AddressVector::iterator start = addrs.begin();437AddressVector::iterator end = addrs.end();438439llvm::sort(start, end);440addrs.erase(std::unique(start, end), end);441thread_plan_sp =442std::make_shared<ThreadPlanRunToAddress>(thread, addrs, stop);443}444445return thread_plan_sp;446}447448/// Helper for the entry breakpoint callback. Resolves the load addresses449/// of all dependent modules.450void DynamicLoaderHexagonDYLD::LoadAllCurrentModules() {451HexagonDYLDRendezvous::iterator I;452HexagonDYLDRendezvous::iterator E;453ModuleList module_list;454455if (!m_rendezvous.Resolve()) {456Log *log = GetLog(LLDBLog::DynamicLoader);457LLDB_LOGF(458log,459"DynamicLoaderHexagonDYLD::%s unable to resolve rendezvous address",460__FUNCTION__);461return;462}463464// The rendezvous class doesn't enumerate the main module, so track that465// ourselves here.466ModuleSP executable = GetTargetExecutable();467m_loaded_modules[executable] = m_rendezvous.GetLinkMapAddress();468469for (I = m_rendezvous.begin(), E = m_rendezvous.end(); I != E; ++I) {470const char *module_path = I->path.c_str();471FileSpec file(module_path);472ModuleSP module_sp =473LoadModuleAtAddress(file, I->link_addr, I->base_addr, true);474if (module_sp.get()) {475module_list.Append(module_sp);476} else {477Log *log = GetLog(LLDBLog::DynamicLoader);478LLDB_LOGF(log,479"DynamicLoaderHexagonDYLD::%s failed loading module %s at "480"0x%" PRIx64,481__FUNCTION__, module_path, I->base_addr);482}483}484485m_process->GetTarget().ModulesDidLoad(module_list);486}487488/// Computes a value for m_load_offset returning the computed address on489/// success and LLDB_INVALID_ADDRESS on failure.490addr_t DynamicLoaderHexagonDYLD::ComputeLoadOffset() {491// Here we could send a GDB packet to know the load offset492//493// send: $qOffsets#4b494// get: Text=0;Data=0;Bss=0495//496// Currently qOffsets is not supported by pluginProcessGDBRemote497//498return 0;499}500501// Here we must try to read the entry point directly from the elf header. This502// is possible if the process is not relocatable or dynamically linked.503//504// an alternative is to look at the PC if we can be sure that we have connected505// when the process is at the entry point.506// I dont think that is reliable for us.507addr_t DynamicLoaderHexagonDYLD::GetEntryPoint() {508if (m_entry_point != LLDB_INVALID_ADDRESS)509return m_entry_point;510// check we have a valid process511if (m_process == nullptr)512return LLDB_INVALID_ADDRESS;513// Get the current executable module514Module &module = *(m_process->GetTarget().GetExecutableModule().get());515// Get the object file (elf file) for this module516lldb_private::ObjectFile &object = *(module.GetObjectFile());517// Check if the file is executable (ie, not shared object or relocatable)518if (object.IsExecutable()) {519// Get the entry point address for this object520lldb_private::Address entry = object.GetEntryPointAddress();521// Return the entry point address522return entry.GetFileAddress();523}524// No idea so back out525return LLDB_INVALID_ADDRESS;526}527528const SectionList *DynamicLoaderHexagonDYLD::GetSectionListFromModule(529const ModuleSP module) const {530SectionList *sections = nullptr;531if (module.get()) {532ObjectFile *obj_file = module->GetObjectFile();533if (obj_file) {534sections = obj_file->GetSectionList();535}536}537return sections;538}539540static int ReadInt(Process *process, addr_t addr) {541Status error;542int value = (int)process->ReadUnsignedIntegerFromMemory(543addr, sizeof(uint32_t), 0, error);544if (error.Fail())545return -1;546else547return value;548}549550lldb::addr_t551DynamicLoaderHexagonDYLD::GetThreadLocalData(const lldb::ModuleSP module,552const lldb::ThreadSP thread,553lldb::addr_t tls_file_addr) {554auto it = m_loaded_modules.find(module);555if (it == m_loaded_modules.end())556return LLDB_INVALID_ADDRESS;557558addr_t link_map = it->second;559if (link_map == LLDB_INVALID_ADDRESS)560return LLDB_INVALID_ADDRESS;561562const HexagonDYLDRendezvous::ThreadInfo &metadata =563m_rendezvous.GetThreadInfo();564if (!metadata.valid)565return LLDB_INVALID_ADDRESS;566567// Get the thread pointer.568addr_t tp = thread->GetThreadPointer();569if (tp == LLDB_INVALID_ADDRESS)570return LLDB_INVALID_ADDRESS;571572// Find the module's modid.573int modid = ReadInt(m_process, link_map + metadata.modid_offset);574if (modid == -1)575return LLDB_INVALID_ADDRESS;576577// Lookup the DTV structure for this thread.578addr_t dtv_ptr = tp + metadata.dtv_offset;579addr_t dtv = ReadPointer(dtv_ptr);580if (dtv == LLDB_INVALID_ADDRESS)581return LLDB_INVALID_ADDRESS;582583// Find the TLS block for this module.584addr_t dtv_slot = dtv + metadata.dtv_slot_size * modid;585addr_t tls_block = ReadPointer(dtv_slot + metadata.tls_offset);586587Module *mod = module.get();588Log *log = GetLog(LLDBLog::DynamicLoader);589LLDB_LOGF(log,590"DynamicLoaderHexagonDYLD::Performed TLS lookup: "591"module=%s, link_map=0x%" PRIx64 ", tp=0x%" PRIx64592", modid=%i, tls_block=0x%" PRIx64,593mod->GetObjectName().AsCString(""), link_map, tp, modid, tls_block);594595if (tls_block == LLDB_INVALID_ADDRESS)596return LLDB_INVALID_ADDRESS;597else598return tls_block + tls_file_addr;599}600601602