1 //===-- DynamicLoaderHexagonDYLD.cpp ----------------------------*- C++ -*-===//
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
7 //===----------------------------------------------------------------------===//
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"
21 #include "DynamicLoaderHexagonDYLD.h"
26 using namespace lldb_private;
30 // Notes about hexagon dynamic loading:
32 // When we connect to a target we find the dyld breakpoint address. We put
34 // breakpoint there with a callback 'RendezvousBreakpointHit()'.
36 // It is possible to find the dyld structure address from the ELF symbol
38 // but in the case of the simulator it has not been initialized before the
39 // target calls dlinit().
41 // We can only safely parse the dyld structure after we hit the dyld
43 // since at that time we know dlinit() must have been called.
46 // Find the load address of a symbol
47 static lldb::addr_t findSymbolAddress(Process *proc, ConstString findName) {
48 assert(proc != nullptr);
50 ModuleSP module = proc->GetTarget().GetExecutableModule();
51 assert(module.get() != nullptr);
53 ObjectFile *exe = module->GetObjectFile();
54 assert(exe != nullptr);
56 lldb_private::Symtab *symtab = exe->GetSymtab();
57 assert(symtab != nullptr);
59 for (size_t i = 0; i < symtab->GetNumSymbols(); i++) {
60 const Symbol *sym = symtab->SymbolAtIndex(i);
61 assert(sym != nullptr);
62 ConstString symName = sym->GetName();
64 if (ConstString::Compare(findName, symName) == 0) {
65 Address addr = sym->GetAddress();
66 return addr.GetLoadAddress(&proc->GetTarget());
69 return LLDB_INVALID_ADDRESS;
72 void DynamicLoaderHexagonDYLD::Initialize() {
73 PluginManager::RegisterPlugin(GetPluginNameStatic(),
74 GetPluginDescriptionStatic(), CreateInstance);
77 void DynamicLoaderHexagonDYLD::Terminate() {}
79 lldb_private::ConstString DynamicLoaderHexagonDYLD::GetPluginName() {
80 return GetPluginNameStatic();
83 lldb_private::ConstString DynamicLoaderHexagonDYLD::GetPluginNameStatic() {
84 static ConstString g_name("hexagon-dyld");
88 const char *DynamicLoaderHexagonDYLD::GetPluginDescriptionStatic() {
89 return "Dynamic loader plug-in that watches for shared library "
90 "loads/unloads in Hexagon processes.";
93 uint32_t DynamicLoaderHexagonDYLD::GetPluginVersion() { return 1; }
95 DynamicLoader *DynamicLoaderHexagonDYLD::CreateInstance(Process *process,
99 const llvm::Triple &triple_ref =
100 process->GetTarget().GetArchitecture().GetTriple();
101 if (triple_ref.getArch() == llvm::Triple::hexagon)
106 return new DynamicLoaderHexagonDYLD(process);
110 DynamicLoaderHexagonDYLD::DynamicLoaderHexagonDYLD(Process *process)
111 : DynamicLoader(process), m_rendezvous(process),
112 m_load_offset(LLDB_INVALID_ADDRESS), m_entry_point(LLDB_INVALID_ADDRESS),
113 m_dyld_bid(LLDB_INVALID_BREAK_ID) {}
115 DynamicLoaderHexagonDYLD::~DynamicLoaderHexagonDYLD() {
116 if (m_dyld_bid != LLDB_INVALID_BREAK_ID) {
117 m_process->GetTarget().RemoveBreakpointByID(m_dyld_bid);
118 m_dyld_bid = LLDB_INVALID_BREAK_ID;
122 void DynamicLoaderHexagonDYLD::DidAttach() {
126 executable = GetTargetExecutable();
128 // Find the difference between the desired load address in the elf file and
129 // the real load address in memory
130 load_offset = ComputeLoadOffset();
132 // Check that there is a valid executable
133 if (executable.get() == nullptr)
136 // Disable JIT for hexagon targets because its not supported
137 m_process->SetCanJIT(false);
139 // Enable Interpreting of function call expressions
140 m_process->SetCanInterpretFunctionCalls(true);
142 // Add the current executable to the module list
143 ModuleList module_list;
144 module_list.Append(executable);
146 // Map the loaded sections of this executable
147 if (load_offset != LLDB_INVALID_ADDRESS)
148 UpdateLoadedSections(executable, LLDB_INVALID_ADDRESS, load_offset, true);
151 // Load into LLDB all of the currently loaded executables in the stub
152 LoadAllCurrentModules();
155 // Callback for the target to give it the loaded module list
156 m_process->GetTarget().ModulesDidLoad(module_list);
158 // Try to set a breakpoint at the rendezvous breakpoint. DidLaunch uses
159 // ProbeEntry() instead. That sets a breakpoint, at the dyld breakpoint
160 // address, with a callback so that when hit, the dyld structure can be
162 if (!SetRendezvousBreakpoint()) {
167 void DynamicLoaderHexagonDYLD::DidLaunch() {}
169 /// Checks to see if the target module has changed, updates the target
170 /// accordingly and returns the target executable module.
171 ModuleSP DynamicLoaderHexagonDYLD::GetTargetExecutable() {
172 Target &target = m_process->GetTarget();
173 ModuleSP executable = target.GetExecutableModule();
175 // There is no executable
176 if (!executable.get())
179 // The target executable file does not exits
180 if (!FileSystem::Instance().Exists(executable->GetFileSpec()))
183 // Prep module for loading
184 ModuleSpec module_spec(executable->GetFileSpec(),
185 executable->GetArchitecture());
186 ModuleSP module_sp(new Module(module_spec));
188 // Check if the executable has changed and set it to the target executable if
190 if (module_sp.get() && module_sp->GetUUID().IsValid() &&
191 executable->GetUUID().IsValid()) {
192 // if the executable has changed ??
193 if (module_sp->GetUUID() != executable->GetUUID())
195 } else if (executable->FileHasChanged())
198 if (executable.get())
201 // TODO: What case is this code used?
202 executable = target.GetOrCreateModule(module_spec, true /* notify */);
203 if (executable.get() != target.GetExecutableModulePointer()) {
204 // Don't load dependent images since we are in dyld where we will know and
205 // find out about all images that are loaded
206 target.SetExecutableModule(executable, eLoadDependentsNo);
212 // AD: Needs to be updated?
213 Status DynamicLoaderHexagonDYLD::CanLoadImage() { return Status(); }
215 void DynamicLoaderHexagonDYLD::UpdateLoadedSections(ModuleSP module,
216 addr_t link_map_addr,
218 bool base_addr_is_offset) {
219 Target &target = m_process->GetTarget();
220 const SectionList *sections = GetSectionListFromModule(module);
222 assert(sections && "SectionList missing from loaded module.");
224 m_loaded_modules[module] = link_map_addr;
226 const size_t num_sections = sections->GetSize();
228 for (unsigned i = 0; i < num_sections; ++i) {
229 SectionSP section_sp(sections->GetSectionAtIndex(i));
230 lldb::addr_t new_load_addr = section_sp->GetFileAddress() + base_addr;
233 // since our memory map starts from address 0, we must not ignore
234 // sections that load to address 0. This violates the reference
235 // ELF spec, however is used for Hexagon.
237 // If the file address of the section is zero then this is not an
238 // allocatable/loadable section (property of ELF sh_addr). Skip it.
239 // if (new_load_addr == base_addr)
242 target.SetSectionLoadAddress(section_sp, new_load_addr);
246 /// Removes the loaded sections from the target in \p module.
248 /// \param module The module to traverse.
249 void DynamicLoaderHexagonDYLD::UnloadSections(const ModuleSP module) {
250 Target &target = m_process->GetTarget();
251 const SectionList *sections = GetSectionListFromModule(module);
253 assert(sections && "SectionList missing from unloaded module.");
255 m_loaded_modules.erase(module);
257 const size_t num_sections = sections->GetSize();
258 for (size_t i = 0; i < num_sections; ++i) {
259 SectionSP section_sp(sections->GetSectionAtIndex(i));
260 target.SetSectionUnloaded(section_sp);
264 // Place a breakpoint on <_rtld_debug_state>
265 bool DynamicLoaderHexagonDYLD::SetRendezvousBreakpoint() {
266 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_DYNAMIC_LOADER));
268 // This is the original code, which want to look in the rendezvous structure
269 // to find the breakpoint address. Its backwards for us, since we can easily
270 // find the breakpoint address, since it is exported in our executable. We
271 // however know that we cant read the Rendezvous structure until we have hit
272 // the breakpoint once.
273 const ConstString dyldBpName("_rtld_debug_state");
274 addr_t break_addr = findSymbolAddress(m_process, dyldBpName);
276 Target &target = m_process->GetTarget();
278 // Do not try to set the breakpoint if we don't know where to put it
279 if (break_addr == LLDB_INVALID_ADDRESS) {
280 LLDB_LOGF(log, "Unable to locate _rtld_debug_state breakpoint address");
285 // Save the address of the rendezvous structure
286 m_rendezvous.SetBreakAddress(break_addr);
288 // If we haven't set the breakpoint before then set it
289 if (m_dyld_bid == LLDB_INVALID_BREAK_ID) {
290 Breakpoint *dyld_break =
291 target.CreateBreakpoint(break_addr, true, false).get();
292 dyld_break->SetCallback(RendezvousBreakpointHit, this, true);
293 dyld_break->SetBreakpointKind("shared-library-event");
294 m_dyld_bid = dyld_break->GetID();
296 // Make sure our breakpoint is at the right address.
297 assert(target.GetBreakpointByID(m_dyld_bid)
298 ->FindLocationByAddress(break_addr)
300 .GetID() == m_dyld_bid);
302 if (log && dyld_break == nullptr)
303 LLDB_LOGF(log, "Failed to create _rtld_debug_state breakpoint");
305 // check we have successfully set bp
306 return (dyld_break != nullptr);
308 // rendezvous already set
312 // We have just hit our breakpoint at <_rtld_debug_state>
313 bool DynamicLoaderHexagonDYLD::RendezvousBreakpointHit(
314 void *baton, StoppointCallbackContext *context, user_id_t break_id,
315 user_id_t break_loc_id) {
316 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_DYNAMIC_LOADER));
318 LLDB_LOGF(log, "Rendezvous breakpoint hit!");
320 DynamicLoaderHexagonDYLD *dyld_instance = nullptr;
321 dyld_instance = static_cast<DynamicLoaderHexagonDYLD *>(baton);
323 // if the dyld_instance is still not valid then try to locate it on the
325 if (!dyld_instance->m_rendezvous.IsValid()) {
326 Process *proc = dyld_instance->m_process;
328 const ConstString dyldStructName("_rtld_debug");
329 addr_t structAddr = findSymbolAddress(proc, dyldStructName);
331 if (structAddr != LLDB_INVALID_ADDRESS) {
332 dyld_instance->m_rendezvous.SetRendezvousAddress(structAddr);
334 LLDB_LOGF(log, "Found _rtld_debug structure @ 0x%08" PRIx64, structAddr);
336 LLDB_LOGF(log, "Unable to resolve the _rtld_debug structure");
340 dyld_instance->RefreshModules();
342 // Return true to stop the target, false to just let the target run.
343 return dyld_instance->GetStopWhenImagesChange();
346 /// Helper method for RendezvousBreakpointHit. Updates LLDB's current set
347 /// of loaded modules.
348 void DynamicLoaderHexagonDYLD::RefreshModules() {
349 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_DYNAMIC_LOADER));
351 if (!m_rendezvous.Resolve())
354 HexagonDYLDRendezvous::iterator I;
355 HexagonDYLDRendezvous::iterator E;
357 ModuleList &loaded_modules = m_process->GetTarget().GetImages();
359 if (m_rendezvous.ModulesDidLoad()) {
360 ModuleList new_modules;
362 E = m_rendezvous.loaded_end();
363 for (I = m_rendezvous.loaded_begin(); I != E; ++I) {
364 FileSpec file(I->path);
365 FileSystem::Instance().Resolve(file);
367 LoadModuleAtAddress(file, I->link_addr, I->base_addr, true);
368 if (module_sp.get()) {
369 loaded_modules.AppendIfNeeded(module_sp);
370 new_modules.Append(module_sp);
374 LLDB_LOGF(log, "Target is loading '%s'", I->path.c_str());
375 if (!module_sp.get())
376 LLDB_LOGF(log, "LLDB failed to load '%s'", I->path.c_str());
378 LLDB_LOGF(log, "LLDB successfully loaded '%s'", I->path.c_str());
381 m_process->GetTarget().ModulesDidLoad(new_modules);
384 if (m_rendezvous.ModulesDidUnload()) {
385 ModuleList old_modules;
387 E = m_rendezvous.unloaded_end();
388 for (I = m_rendezvous.unloaded_begin(); I != E; ++I) {
389 FileSpec file(I->path);
390 FileSystem::Instance().Resolve(file);
391 ModuleSpec module_spec(file);
392 ModuleSP module_sp = loaded_modules.FindFirstModule(module_spec);
394 if (module_sp.get()) {
395 old_modules.Append(module_sp);
396 UnloadSections(module_sp);
399 LLDB_LOGF(log, "Target is unloading '%s'", I->path.c_str());
401 loaded_modules.Remove(old_modules);
402 m_process->GetTarget().ModulesDidUnload(old_modules, false);
406 // AD: This is very different to the Static Loader code.
407 // It may be wise to look over this and its relation to stack
410 DynamicLoaderHexagonDYLD::GetStepThroughTrampolinePlan(Thread &thread,
412 ThreadPlanSP thread_plan_sp;
414 StackFrame *frame = thread.GetStackFrameAtIndex(0).get();
415 const SymbolContext &context = frame->GetSymbolContext(eSymbolContextSymbol);
416 Symbol *sym = context.symbol;
418 if (sym == nullptr || !sym->IsTrampoline())
419 return thread_plan_sp;
421 const ConstString sym_name = sym->GetMangled().GetName(
422 lldb::eLanguageTypeUnknown, Mangled::ePreferMangled);
424 return thread_plan_sp;
426 SymbolContextList target_symbols;
427 Target &target = thread.GetProcess()->GetTarget();
428 const ModuleList &images = target.GetImages();
430 images.FindSymbolsWithNameAndType(sym_name, eSymbolTypeCode, target_symbols);
431 size_t num_targets = target_symbols.GetSize();
433 return thread_plan_sp;
435 typedef std::vector<lldb::addr_t> AddressVector;
437 for (size_t i = 0; i < num_targets; ++i) {
438 SymbolContext context;
440 if (target_symbols.GetContextAtIndex(i, context)) {
441 context.GetAddressRange(eSymbolContextEverything, 0, false, range);
442 lldb::addr_t addr = range.GetBaseAddress().GetLoadAddress(&target);
443 if (addr != LLDB_INVALID_ADDRESS)
444 addrs.push_back(addr);
448 if (addrs.size() > 0) {
449 AddressVector::iterator start = addrs.begin();
450 AddressVector::iterator end = addrs.end();
452 llvm::sort(start, end);
453 addrs.erase(std::unique(start, end), end);
455 std::make_shared<ThreadPlanRunToAddress>(thread, addrs, stop);
458 return thread_plan_sp;
461 /// Helper for the entry breakpoint callback. Resolves the load addresses
462 /// of all dependent modules.
463 void DynamicLoaderHexagonDYLD::LoadAllCurrentModules() {
464 HexagonDYLDRendezvous::iterator I;
465 HexagonDYLDRendezvous::iterator E;
466 ModuleList module_list;
468 if (!m_rendezvous.Resolve()) {
469 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_DYNAMIC_LOADER));
472 "DynamicLoaderHexagonDYLD::%s unable to resolve rendezvous address",
477 // The rendezvous class doesn't enumerate the main module, so track that
479 ModuleSP executable = GetTargetExecutable();
480 m_loaded_modules[executable] = m_rendezvous.GetLinkMapAddress();
482 for (I = m_rendezvous.begin(), E = m_rendezvous.end(); I != E; ++I) {
483 const char *module_path = I->path.c_str();
484 FileSpec file(module_path);
486 LoadModuleAtAddress(file, I->link_addr, I->base_addr, true);
487 if (module_sp.get()) {
488 module_list.Append(module_sp);
490 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_DYNAMIC_LOADER));
492 "DynamicLoaderHexagonDYLD::%s failed loading module %s at "
494 __FUNCTION__, module_path, I->base_addr);
498 m_process->GetTarget().ModulesDidLoad(module_list);
501 /// Computes a value for m_load_offset returning the computed address on
502 /// success and LLDB_INVALID_ADDRESS on failure.
503 addr_t DynamicLoaderHexagonDYLD::ComputeLoadOffset() {
504 // Here we could send a GDB packet to know the load offset
506 // send: $qOffsets#4b
507 // get: Text=0;Data=0;Bss=0
509 // Currently qOffsets is not supported by pluginProcessGDBRemote
514 // Here we must try to read the entry point directly from the elf header. This
515 // is possible if the process is not relocatable or dynamically linked.
517 // an alternative is to look at the PC if we can be sure that we have connected
518 // when the process is at the entry point.
519 // I dont think that is reliable for us.
520 addr_t DynamicLoaderHexagonDYLD::GetEntryPoint() {
521 if (m_entry_point != LLDB_INVALID_ADDRESS)
522 return m_entry_point;
523 // check we have a valid process
524 if (m_process == nullptr)
525 return LLDB_INVALID_ADDRESS;
526 // Get the current executable module
527 Module &module = *(m_process->GetTarget().GetExecutableModule().get());
528 // Get the object file (elf file) for this module
529 lldb_private::ObjectFile &object = *(module.GetObjectFile());
530 // Check if the file is executable (ie, not shared object or relocatable)
531 if (object.IsExecutable()) {
532 // Get the entry point address for this object
533 lldb_private::Address entry = object.GetEntryPointAddress();
534 // Return the entry point address
535 return entry.GetFileAddress();
537 // No idea so back out
538 return LLDB_INVALID_ADDRESS;
541 const SectionList *DynamicLoaderHexagonDYLD::GetSectionListFromModule(
542 const ModuleSP module) const {
543 SectionList *sections = nullptr;
545 ObjectFile *obj_file = module->GetObjectFile();
547 sections = obj_file->GetSectionList();
553 static int ReadInt(Process *process, addr_t addr) {
555 int value = (int)process->ReadUnsignedIntegerFromMemory(
556 addr, sizeof(uint32_t), 0, error);
564 DynamicLoaderHexagonDYLD::GetThreadLocalData(const lldb::ModuleSP module,
565 const lldb::ThreadSP thread,
566 lldb::addr_t tls_file_addr) {
567 auto it = m_loaded_modules.find(module);
568 if (it == m_loaded_modules.end())
569 return LLDB_INVALID_ADDRESS;
571 addr_t link_map = it->second;
572 if (link_map == LLDB_INVALID_ADDRESS)
573 return LLDB_INVALID_ADDRESS;
575 const HexagonDYLDRendezvous::ThreadInfo &metadata =
576 m_rendezvous.GetThreadInfo();
578 return LLDB_INVALID_ADDRESS;
580 // Get the thread pointer.
581 addr_t tp = thread->GetThreadPointer();
582 if (tp == LLDB_INVALID_ADDRESS)
583 return LLDB_INVALID_ADDRESS;
585 // Find the module's modid.
586 int modid = ReadInt(m_process, link_map + metadata.modid_offset);
588 return LLDB_INVALID_ADDRESS;
590 // Lookup the DTV structure for this thread.
591 addr_t dtv_ptr = tp + metadata.dtv_offset;
592 addr_t dtv = ReadPointer(dtv_ptr);
593 if (dtv == LLDB_INVALID_ADDRESS)
594 return LLDB_INVALID_ADDRESS;
596 // Find the TLS block for this module.
597 addr_t dtv_slot = dtv + metadata.dtv_slot_size * modid;
598 addr_t tls_block = ReadPointer(dtv_slot + metadata.tls_offset);
600 Module *mod = module.get();
601 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_DYNAMIC_LOADER));
603 "DynamicLoaderHexagonDYLD::Performed TLS lookup: "
604 "module=%s, link_map=0x%" PRIx64 ", tp=0x%" PRIx64
605 ", modid=%i, tls_block=0x%" PRIx64,
606 mod->GetObjectName().AsCString(""), link_map, tp, modid, tls_block);
608 if (tls_block == LLDB_INVALID_ADDRESS)
609 return LLDB_INVALID_ADDRESS;
611 return tls_block + tls_file_addr;