1 //===-- DynamicLoaderHexagon.h ----------------------------------*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
12 // Other libraries and framework includes
13 #include "lldb/Core/PluginManager.h"
14 #include "lldb/Core/Log.h"
15 #include "lldb/Core/Module.h"
16 #include "lldb/Core/ModuleSpec.h"
17 #include "lldb/Core/Section.h"
18 #include "lldb/Symbol/ObjectFile.h"
19 #include "lldb/Target/Process.h"
20 #include "lldb/Target/Target.h"
21 #include "lldb/Target/Thread.h"
22 #include "lldb/Target/ThreadPlanRunToAddress.h"
23 #include "lldb/Breakpoint/BreakpointLocation.h"
25 #include "DynamicLoaderHexagonDYLD.h"
28 using namespace lldb_private;
32 // Notes about hexagon dynamic loading:
34 // When we connect to a target we find the dyld breakpoint address. We put a
35 // breakpoint there with a callback 'RendezvousBreakpointHit()'.
37 // It is possible to find the dyld structure address from the ELF symbol table,
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 breakpoint
42 // since at that time we know dlinit() must have been called.
45 // Find the load address of a symbol
46 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++ )
61 const Symbol* sym = symtab->SymbolAtIndex( i );
62 assert( sym != nullptr );
63 const ConstString &symName = sym->GetName( );
65 if ( ConstString::Compare( findName, symName ) == 0 )
67 Address addr = sym->GetAddress();
68 return addr.GetLoadAddress( & proc->GetTarget() );
71 return LLDB_INVALID_ADDRESS;
75 DynamicLoaderHexagonDYLD::Initialize()
77 PluginManager::RegisterPlugin(GetPluginNameStatic(),
78 GetPluginDescriptionStatic(),
83 DynamicLoaderHexagonDYLD::Terminate()
87 lldb_private::ConstString
88 DynamicLoaderHexagonDYLD::GetPluginName()
90 return GetPluginNameStatic();
93 lldb_private::ConstString
94 DynamicLoaderHexagonDYLD::GetPluginNameStatic()
96 static ConstString g_name("hexagon-dyld");
101 DynamicLoaderHexagonDYLD::GetPluginDescriptionStatic()
103 return "Dynamic loader plug-in that watches for shared library "
104 "loads/unloads in Hexagon processes.";
108 DynamicLoaderHexagonDYLD::GetPluginVersion()
114 DynamicLoaderHexagonDYLD::CreateInstance(Process *process, bool force)
119 const llvm::Triple &triple_ref = process->GetTarget().GetArchitecture().GetTriple();
120 if (triple_ref.getArch() == llvm::Triple::hexagon)
125 return new DynamicLoaderHexagonDYLD(process);
129 DynamicLoaderHexagonDYLD::DynamicLoaderHexagonDYLD(Process *process)
130 : DynamicLoader(process)
131 , m_rendezvous (process)
132 , m_load_offset(LLDB_INVALID_ADDRESS)
133 , m_entry_point(LLDB_INVALID_ADDRESS)
134 , m_dyld_bid (LLDB_INVALID_BREAK_ID)
138 DynamicLoaderHexagonDYLD::~DynamicLoaderHexagonDYLD()
140 if (m_dyld_bid != LLDB_INVALID_BREAK_ID)
142 m_process->GetTarget().RemoveBreakpointByID (m_dyld_bid);
143 m_dyld_bid = LLDB_INVALID_BREAK_ID;
148 DynamicLoaderHexagonDYLD::DidAttach()
153 executable = GetTargetExecutable();
155 // Find the difference between the desired load address in the elf file
156 // and the real load address in memory
157 load_offset = ComputeLoadOffset();
159 // Check that there is a valid executable
160 if ( executable.get( ) == nullptr )
163 // Disable JIT for hexagon targets because its not supported
164 m_process->SetCanJIT(false);
166 // Enable Interpreting of function call expressions
167 m_process->SetCanInterpretFunctionCalls(true);
169 // Add the current executable to the module list
170 ModuleList module_list;
171 module_list.Append(executable);
173 // Map the loaded sections of this executable
174 if ( load_offset != LLDB_INVALID_ADDRESS )
175 UpdateLoadedSections(executable, LLDB_INVALID_ADDRESS, load_offset, true);
178 // Load into LLDB all of the currently loaded executables in the stub
179 LoadAllCurrentModules();
182 // Callback for the target to give it the loaded module list
183 m_process->GetTarget().ModulesDidLoad(module_list);
185 // Try to set a breakpoint at the rendezvous breakpoint.
186 // DidLaunch uses ProbeEntry() instead. That sets a breakpoint,
187 // at the dyld breakpoint address, with a callback so that when hit,
188 // the dyld structure can be parsed.
189 if (! SetRendezvousBreakpoint() )
196 DynamicLoaderHexagonDYLD::DidLaunch()
200 /// Checks to see if the target module has changed, updates the target
201 /// accordingly and returns the target executable module.
203 DynamicLoaderHexagonDYLD::GetTargetExecutable()
205 Target &target = m_process->GetTarget();
206 ModuleSP executable = target.GetExecutableModule();
208 // There is no executable
209 if (! executable.get())
212 // The target executable file does not exits
213 if (! executable->GetFileSpec().Exists())
216 // Prep module for loading
217 ModuleSpec module_spec(executable->GetFileSpec(), executable->GetArchitecture());
218 ModuleSP module_sp (new Module (module_spec));
220 // Check if the executable has changed and set it to the target executable if they differ.
221 if (module_sp.get() && module_sp->GetUUID().IsValid() && executable->GetUUID().IsValid())
223 // if the executable has changed ??
224 if (module_sp->GetUUID() != executable->GetUUID())
227 else if (executable->FileHasChanged())
230 if ( executable.get( ) )
233 // TODO: What case is this code used?
234 executable = target.GetSharedModule(module_spec);
235 if (executable.get() != target.GetExecutableModulePointer())
237 // Don't load dependent images since we are in dyld where we will know
238 // and find out about all images that are loaded
239 const bool get_dependent_images = false;
240 target.SetExecutableModule(executable, get_dependent_images);
246 //AD: Needs to be updated?
248 DynamicLoaderHexagonDYLD::CanLoadImage()
254 DynamicLoaderHexagonDYLD::UpdateLoadedSections(ModuleSP module,
255 addr_t link_map_addr,
257 bool base_addr_is_offset)
259 Target &target = m_process->GetTarget();
260 const SectionList *sections = GetSectionListFromModule(module);
262 assert(sections && "SectionList missing from loaded module.");
264 m_loaded_modules[module] = link_map_addr;
266 const size_t num_sections = sections->GetSize();
268 for (unsigned i = 0; i < num_sections; ++i)
270 SectionSP section_sp (sections->GetSectionAtIndex(i));
271 lldb::addr_t new_load_addr = section_sp->GetFileAddress() + base_addr;
274 // since our memory map starts from address 0, we must not ignore
275 // sections that load to address 0. This violates the reference
276 // ELF spec, however is used for Hexagon.
278 // If the file address of the section is zero then this is not an
279 // allocatable/loadable section (property of ELF sh_addr). Skip it.
280 // if (new_load_addr == base_addr)
283 target.SetSectionLoadAddress(section_sp, new_load_addr);
287 /// Removes the loaded sections from the target in @p module.
289 /// @param module The module to traverse.
291 DynamicLoaderHexagonDYLD::UnloadSections(const ModuleSP module)
293 Target &target = m_process->GetTarget();
294 const SectionList *sections = GetSectionListFromModule(module);
296 assert(sections && "SectionList missing from unloaded module.");
298 m_loaded_modules.erase(module);
300 const size_t num_sections = sections->GetSize();
301 for (size_t i = 0; i < num_sections; ++i)
303 SectionSP section_sp (sections->GetSectionAtIndex(i));
304 target.SetSectionUnloaded(section_sp);
308 // Place a breakpoint on <_rtld_debug_state>
310 DynamicLoaderHexagonDYLD::SetRendezvousBreakpoint()
312 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_DYNAMIC_LOADER));
314 // This is the original code, which want to look in the rendezvous structure
315 // to find the breakpoint address. Its backwards for us, since we can easily
316 // find the breakpoint address, since it is exported in our executable.
317 // We however know that we cant read the Rendezvous structure until we have hit
318 // the breakpoint once.
319 const ConstString dyldBpName( "_rtld_debug_state" );
320 addr_t break_addr = findSymbolAddress( m_process, dyldBpName );
322 Target &target = m_process->GetTarget();
324 // Do not try to set the breakpoint if we don't know where to put it
325 if ( break_addr == LLDB_INVALID_ADDRESS )
328 log->Printf( "Unable to locate _rtld_debug_state breakpoint address" );
333 // Save the address of the rendezvous structure
334 m_rendezvous.SetBreakAddress( break_addr );
336 // If we haven't set the breakpoint before then set it
337 if (m_dyld_bid == LLDB_INVALID_BREAK_ID)
339 Breakpoint *dyld_break = target.CreateBreakpoint (break_addr, true, false).get();
340 dyld_break->SetCallback(RendezvousBreakpointHit, this, true);
341 dyld_break->SetBreakpointKind ("shared-library-event");
342 m_dyld_bid = dyld_break->GetID();
344 // Make sure our breakpoint is at the right address.
347 target.GetBreakpointByID(m_dyld_bid)->
348 FindLocationByAddress(break_addr)->
349 GetBreakpoint().GetID()
353 if ( log && dyld_break == nullptr )
354 log->Printf( "Failed to create _rtld_debug_state breakpoint" );
356 // check we have successfully set bp
357 return (dyld_break != nullptr);
360 // rendezvous already set
364 // We have just hit our breakpoint at <_rtld_debug_state>
366 DynamicLoaderHexagonDYLD::RendezvousBreakpointHit(void *baton,
367 StoppointCallbackContext *context,
369 user_id_t break_loc_id)
371 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_DYNAMIC_LOADER));
374 log->Printf( "Rendezvous breakpoint hit!" );
376 DynamicLoaderHexagonDYLD* dyld_instance = nullptr;
377 dyld_instance = static_cast<DynamicLoaderHexagonDYLD*>(baton);
379 // if the dyld_instance is still not valid then
380 // try to locate it on the symbol table
381 if ( !dyld_instance->m_rendezvous.IsValid( ) )
383 Process *proc = dyld_instance->m_process;
385 const ConstString dyldStructName( "_rtld_debug" );
386 addr_t structAddr = findSymbolAddress( proc, dyldStructName );
388 if ( structAddr != LLDB_INVALID_ADDRESS )
390 dyld_instance->m_rendezvous.SetRendezvousAddress( structAddr );
393 log->Printf( "Found _rtld_debug structure @ 0x%08" PRIx64, structAddr );
398 log->Printf( "Unable to resolve the _rtld_debug structure" );
402 dyld_instance->RefreshModules();
404 // Return true to stop the target, false to just let the target run.
405 return dyld_instance->GetStopWhenImagesChange();
408 /// Helper method for RendezvousBreakpointHit. Updates LLDB's current set
409 /// of loaded modules.
411 DynamicLoaderHexagonDYLD::RefreshModules()
413 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_DYNAMIC_LOADER));
415 if (!m_rendezvous.Resolve())
418 HexagonDYLDRendezvous::iterator I;
419 HexagonDYLDRendezvous::iterator E;
421 ModuleList &loaded_modules = m_process->GetTarget().GetImages();
423 if (m_rendezvous.ModulesDidLoad())
425 ModuleList new_modules;
427 E = m_rendezvous.loaded_end();
428 for (I = m_rendezvous.loaded_begin(); I != E; ++I)
430 FileSpec file(I->path.c_str(), true);
431 ModuleSP module_sp = LoadModuleAtAddress(file, I->link_addr, I->base_addr, true);
434 loaded_modules.AppendIfNeeded( module_sp );
435 new_modules.Append(module_sp);
440 log->Printf( "Target is loading '%s'", I->path.c_str() );
441 if (! module_sp.get() )
442 log->Printf( "LLDB failed to load '%s'", I->path.c_str() );
444 log->Printf( "LLDB successfully loaded '%s'", I->path.c_str() );
448 m_process->GetTarget().ModulesDidLoad(new_modules);
451 if (m_rendezvous.ModulesDidUnload())
453 ModuleList old_modules;
455 E = m_rendezvous.unloaded_end();
456 for (I = m_rendezvous.unloaded_begin(); I != E; ++I)
458 FileSpec file(I->path.c_str(), true);
459 ModuleSpec module_spec(file);
460 ModuleSP module_sp = loaded_modules.FindFirstModule (module_spec);
464 old_modules.Append(module_sp);
465 UnloadSections(module_sp);
469 log->Printf( "Target is unloading '%s'", I->path.c_str() );
472 loaded_modules.Remove(old_modules);
473 m_process->GetTarget().ModulesDidUnload(old_modules, false);
477 //AD: This is very different to the Static Loader code.
478 // It may be wise to look over this and its relation to stack
481 DynamicLoaderHexagonDYLD::GetStepThroughTrampolinePlan(Thread &thread, bool stop)
483 ThreadPlanSP thread_plan_sp;
485 StackFrame *frame = thread.GetStackFrameAtIndex(0).get();
486 const SymbolContext &context = frame->GetSymbolContext(eSymbolContextSymbol);
487 Symbol *sym = context.symbol;
489 if (sym == NULL || !sym->IsTrampoline())
490 return thread_plan_sp;
492 const ConstString sym_name = sym->GetMangled().GetName(lldb::eLanguageTypeUnknown, Mangled::ePreferMangled);
494 return thread_plan_sp;
496 SymbolContextList target_symbols;
497 Target &target = thread.GetProcess()->GetTarget();
498 const ModuleList &images = target.GetImages();
500 images.FindSymbolsWithNameAndType(sym_name, eSymbolTypeCode, target_symbols);
501 size_t num_targets = target_symbols.GetSize();
503 return thread_plan_sp;
505 typedef std::vector<lldb::addr_t> AddressVector;
507 for (size_t i = 0; i < num_targets; ++i)
509 SymbolContext context;
511 if (target_symbols.GetContextAtIndex(i, context))
513 context.GetAddressRange(eSymbolContextEverything, 0, false, range);
514 lldb::addr_t addr = range.GetBaseAddress().GetLoadAddress(&target);
515 if (addr != LLDB_INVALID_ADDRESS)
516 addrs.push_back(addr);
520 if (addrs.size() > 0)
522 AddressVector::iterator start = addrs.begin();
523 AddressVector::iterator end = addrs.end();
525 std::sort(start, end);
526 addrs.erase(std::unique(start, end), end);
527 thread_plan_sp.reset(new ThreadPlanRunToAddress(thread, addrs, stop));
530 return thread_plan_sp;
533 /// Helper for the entry breakpoint callback. Resolves the load addresses
534 /// of all dependent modules.
536 DynamicLoaderHexagonDYLD::LoadAllCurrentModules()
538 HexagonDYLDRendezvous::iterator I;
539 HexagonDYLDRendezvous::iterator E;
540 ModuleList module_list;
542 if (!m_rendezvous.Resolve())
544 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_DYNAMIC_LOADER));
546 log->Printf("DynamicLoaderHexagonDYLD::%s unable to resolve rendezvous address", __FUNCTION__);
550 // The rendezvous class doesn't enumerate the main module, so track
551 // that ourselves here.
552 ModuleSP executable = GetTargetExecutable();
553 m_loaded_modules[executable] = m_rendezvous.GetLinkMapAddress();
556 for (I = m_rendezvous.begin(), E = m_rendezvous.end(); I != E; ++I)
558 const char *module_path = I->path.c_str();
559 FileSpec file(module_path, false);
560 ModuleSP module_sp = LoadModuleAtAddress(file, I->link_addr, I->base_addr, true);
563 module_list.Append(module_sp);
567 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_DYNAMIC_LOADER));
569 log->Printf("DynamicLoaderHexagonDYLD::%s failed loading module %s at 0x%" PRIx64,
570 __FUNCTION__, module_path, I->base_addr);
574 m_process->GetTarget().ModulesDidLoad(module_list);
577 /// Helper for the entry breakpoint callback. Resolves the load addresses
578 /// of all dependent modules.
580 DynamicLoaderHexagonDYLD::LoadModuleAtAddress(const FileSpec &file,
581 addr_t link_map_addr,
583 bool base_addr_is_offset)
585 Target &target = m_process->GetTarget();
586 ModuleList &modules = target.GetImages();
589 ModuleSpec module_spec (file, target.GetArchitecture());
591 // check if module is currently loaded
592 if ((module_sp = modules.FindFirstModule (module_spec)))
594 UpdateLoadedSections(module_sp, link_map_addr, base_addr, true);
596 // try to load this module from disk
597 else if ((module_sp = target.GetSharedModule(module_spec)))
599 UpdateLoadedSections(module_sp, link_map_addr, base_addr, true);
605 /// Computes a value for m_load_offset returning the computed address on
606 /// success and LLDB_INVALID_ADDRESS on failure.
608 DynamicLoaderHexagonDYLD::ComputeLoadOffset()
610 // Here we could send a GDB packet to know the load offset
612 // send: $qOffsets#4b
613 // get: Text=0;Data=0;Bss=0
615 // Currently qOffsets is not supported by pluginProcessGDBRemote
620 // Here we must try to read the entry point directly from
621 // the elf header. This is possible if the process is not
622 // relocatable or dynamically linked.
624 // an alternative is to look at the PC if we can be sure
625 // that we have connected when the process is at the entry point.
626 // I dont think that is reliable for us.
628 DynamicLoaderHexagonDYLD::GetEntryPoint()
630 if (m_entry_point != LLDB_INVALID_ADDRESS)
631 return m_entry_point;
632 // check we have a valid process
633 if ( m_process == nullptr )
634 return LLDB_INVALID_ADDRESS;
635 // Get the current executable module
636 Module & module = *( m_process->GetTarget( ).GetExecutableModule( ).get( ) );
637 // Get the object file (elf file) for this module
638 lldb_private::ObjectFile &object = *( module.GetObjectFile( ) );
639 // Check if the file is executable (ie, not shared object or relocatable)
640 if ( object.IsExecutable() )
642 // Get the entry point address for this object
643 lldb_private::Address entry = object.GetEntryPointAddress( );
644 // Return the entry point address
645 return entry.GetFileAddress( );
647 // No idea so back out
648 return LLDB_INVALID_ADDRESS;
652 DynamicLoaderHexagonDYLD::GetSectionListFromModule(const ModuleSP module) const
654 SectionList *sections = nullptr;
657 ObjectFile *obj_file = module->GetObjectFile();
660 sections = obj_file->GetSectionList();
666 static int ReadInt(Process *process, addr_t addr)
669 int value = (int)process->ReadUnsignedIntegerFromMemory(addr, sizeof(uint32_t), 0, error);
677 DynamicLoaderHexagonDYLD::GetThreadLocalData (const lldb::ModuleSP module, const lldb::ThreadSP thread)
679 auto it = m_loaded_modules.find (module);
680 if (it == m_loaded_modules.end())
681 return LLDB_INVALID_ADDRESS;
683 addr_t link_map = it->second;
684 if (link_map == LLDB_INVALID_ADDRESS)
685 return LLDB_INVALID_ADDRESS;
687 const HexagonDYLDRendezvous::ThreadInfo &metadata = m_rendezvous.GetThreadInfo();
689 return LLDB_INVALID_ADDRESS;
691 // Get the thread pointer.
692 addr_t tp = thread->GetThreadPointer ();
693 if (tp == LLDB_INVALID_ADDRESS)
694 return LLDB_INVALID_ADDRESS;
696 // Find the module's modid.
697 int modid = ReadInt (m_process, link_map + metadata.modid_offset);
699 return LLDB_INVALID_ADDRESS;
701 // Lookup the DTV stucture for this thread.
702 addr_t dtv_ptr = tp + metadata.dtv_offset;
703 addr_t dtv = ReadPointer (dtv_ptr);
704 if (dtv == LLDB_INVALID_ADDRESS)
705 return LLDB_INVALID_ADDRESS;
707 // Find the TLS block for this module.
708 addr_t dtv_slot = dtv + metadata.dtv_slot_size*modid;
709 addr_t tls_block = ReadPointer (dtv_slot + metadata.tls_offset);
711 Module *mod = module.get();
712 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_DYNAMIC_LOADER));
714 log->Printf("DynamicLoaderHexagonDYLD::Performed TLS lookup: "
715 "module=%s, link_map=0x%" PRIx64 ", tp=0x%" PRIx64 ", modid=%i, tls_block=0x%" PRIx64,
716 mod->GetObjectName().AsCString(""), link_map, tp, modid, tls_block);