1 //===-- DynamicLoaderHexagonDYLD.cpp ----------------------------*- 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/Breakpoint/BreakpointLocation.h"
14 #include "lldb/Core/Module.h"
15 #include "lldb/Core/ModuleSpec.h"
16 #include "lldb/Core/PluginManager.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/Utility/Log.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
36 // breakpoint there with a callback 'RendezvousBreakpointHit()'.
38 // It is possible to find the dyld structure address from the ELF symbol
40 // but in the case of the simulator it has not been initialized before the
41 // target calls dlinit().
43 // We can only safely parse the dyld structure after we hit the dyld
45 // since at that time we know dlinit() must have been called.
48 // Find the load address of a symbol
49 static lldb::addr_t findSymbolAddress(Process *proc, ConstString findName) {
50 assert(proc != nullptr);
52 ModuleSP module = proc->GetTarget().GetExecutableModule();
53 assert(module.get() != nullptr);
55 ObjectFile *exe = module->GetObjectFile();
56 assert(exe != nullptr);
58 lldb_private::Symtab *symtab = exe->GetSymtab();
59 assert(symtab != nullptr);
61 for (size_t i = 0; i < symtab->GetNumSymbols(); i++) {
62 const Symbol *sym = symtab->SymbolAtIndex(i);
63 assert(sym != nullptr);
64 const ConstString &symName = sym->GetName();
66 if (ConstString::Compare(findName, symName) == 0) {
67 Address addr = sym->GetAddress();
68 return addr.GetLoadAddress(&proc->GetTarget());
71 return LLDB_INVALID_ADDRESS;
74 void DynamicLoaderHexagonDYLD::Initialize() {
75 PluginManager::RegisterPlugin(GetPluginNameStatic(),
76 GetPluginDescriptionStatic(), CreateInstance);
79 void DynamicLoaderHexagonDYLD::Terminate() {}
81 lldb_private::ConstString DynamicLoaderHexagonDYLD::GetPluginName() {
82 return GetPluginNameStatic();
85 lldb_private::ConstString DynamicLoaderHexagonDYLD::GetPluginNameStatic() {
86 static ConstString g_name("hexagon-dyld");
90 const char *DynamicLoaderHexagonDYLD::GetPluginDescriptionStatic() {
91 return "Dynamic loader plug-in that watches for shared library "
92 "loads/unloads in Hexagon processes.";
95 uint32_t DynamicLoaderHexagonDYLD::GetPluginVersion() { return 1; }
97 DynamicLoader *DynamicLoaderHexagonDYLD::CreateInstance(Process *process,
101 const llvm::Triple &triple_ref =
102 process->GetTarget().GetArchitecture().GetTriple();
103 if (triple_ref.getArch() == llvm::Triple::hexagon)
108 return new DynamicLoaderHexagonDYLD(process);
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) {}
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;
124 void DynamicLoaderHexagonDYLD::DidAttach() {
128 executable = GetTargetExecutable();
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();
134 // Check that there is a valid executable
135 if (executable.get() == nullptr)
138 // Disable JIT for hexagon targets because its not supported
139 m_process->SetCanJIT(false);
141 // Enable Interpreting of function call expressions
142 m_process->SetCanInterpretFunctionCalls(true);
144 // Add the current executable to the module list
145 ModuleList module_list;
146 module_list.Append(executable);
148 // Map the loaded sections of this executable
149 if (load_offset != LLDB_INVALID_ADDRESS)
150 UpdateLoadedSections(executable, LLDB_INVALID_ADDRESS, load_offset, true);
153 // Load into LLDB all of the currently loaded executables in the stub
154 LoadAllCurrentModules();
157 // Callback for the target to give it the loaded module list
158 m_process->GetTarget().ModulesDidLoad(module_list);
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
164 if (!SetRendezvousBreakpoint()) {
169 void DynamicLoaderHexagonDYLD::DidLaunch() {}
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();
177 // There is no executable
178 if (!executable.get())
181 // The target executable file does not exits
182 if (!executable->GetFileSpec().Exists())
185 // Prep module for loading
186 ModuleSpec module_spec(executable->GetFileSpec(),
187 executable->GetArchitecture());
188 ModuleSP module_sp(new Module(module_spec));
190 // Check if the executable has changed and set it to the target executable if
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())
197 } else if (executable->FileHasChanged())
200 if (executable.get())
203 // TODO: What case is this code used?
204 executable = target.GetSharedModule(module_spec);
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 const bool get_dependent_images = false;
209 target.SetExecutableModule(executable, get_dependent_images);
215 // AD: Needs to be updated?
216 Status DynamicLoaderHexagonDYLD::CanLoadImage() { return Status(); }
218 void DynamicLoaderHexagonDYLD::UpdateLoadedSections(ModuleSP module,
219 addr_t link_map_addr,
221 bool base_addr_is_offset) {
222 Target &target = m_process->GetTarget();
223 const SectionList *sections = GetSectionListFromModule(module);
225 assert(sections && "SectionList missing from loaded module.");
227 m_loaded_modules[module] = link_map_addr;
229 const size_t num_sections = sections->GetSize();
231 for (unsigned i = 0; i < num_sections; ++i) {
232 SectionSP section_sp(sections->GetSectionAtIndex(i));
233 lldb::addr_t new_load_addr = section_sp->GetFileAddress() + base_addr;
236 // since our memory map starts from address 0, we must not ignore
237 // sections that load to address 0. This violates the reference
238 // ELF spec, however is used for Hexagon.
240 // If the file address of the section is zero then this is not an
241 // allocatable/loadable section (property of ELF sh_addr). Skip it.
242 // if (new_load_addr == base_addr)
245 target.SetSectionLoadAddress(section_sp, new_load_addr);
249 /// Removes the loaded sections from the target in @p module.
251 /// @param module The module to traverse.
252 void DynamicLoaderHexagonDYLD::UnloadSections(const ModuleSP module) {
253 Target &target = m_process->GetTarget();
254 const SectionList *sections = GetSectionListFromModule(module);
256 assert(sections && "SectionList missing from unloaded module.");
258 m_loaded_modules.erase(module);
260 const size_t num_sections = sections->GetSize();
261 for (size_t i = 0; i < num_sections; ++i) {
262 SectionSP section_sp(sections->GetSectionAtIndex(i));
263 target.SetSectionUnloaded(section_sp);
267 // Place a breakpoint on <_rtld_debug_state>
268 bool DynamicLoaderHexagonDYLD::SetRendezvousBreakpoint() {
269 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_DYNAMIC_LOADER));
271 // This is the original code, which want to look in the rendezvous structure
272 // to find the breakpoint address. Its backwards for us, since we can easily
273 // find the breakpoint address, since it is exported in our executable. We
274 // however know that we cant read the Rendezvous structure until we have hit
275 // the breakpoint once.
276 const ConstString dyldBpName("_rtld_debug_state");
277 addr_t break_addr = findSymbolAddress(m_process, dyldBpName);
279 Target &target = m_process->GetTarget();
281 // Do not try to set the breakpoint if we don't know where to put it
282 if (break_addr == LLDB_INVALID_ADDRESS) {
284 log->Printf("Unable to locate _rtld_debug_state breakpoint address");
289 // Save the address of the rendezvous structure
290 m_rendezvous.SetBreakAddress(break_addr);
292 // If we haven't set the breakpoint before then set it
293 if (m_dyld_bid == LLDB_INVALID_BREAK_ID) {
294 Breakpoint *dyld_break =
295 target.CreateBreakpoint(break_addr, true, false).get();
296 dyld_break->SetCallback(RendezvousBreakpointHit, this, true);
297 dyld_break->SetBreakpointKind("shared-library-event");
298 m_dyld_bid = dyld_break->GetID();
300 // Make sure our breakpoint is at the right address.
301 assert(target.GetBreakpointByID(m_dyld_bid)
302 ->FindLocationByAddress(break_addr)
304 .GetID() == m_dyld_bid);
306 if (log && dyld_break == nullptr)
307 log->Printf("Failed to create _rtld_debug_state breakpoint");
309 // check we have successfully set bp
310 return (dyld_break != nullptr);
312 // rendezvous already set
316 // We have just hit our breakpoint at <_rtld_debug_state>
317 bool DynamicLoaderHexagonDYLD::RendezvousBreakpointHit(
318 void *baton, StoppointCallbackContext *context, user_id_t break_id,
319 user_id_t break_loc_id) {
320 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_DYNAMIC_LOADER));
323 log->Printf("Rendezvous breakpoint hit!");
325 DynamicLoaderHexagonDYLD *dyld_instance = nullptr;
326 dyld_instance = static_cast<DynamicLoaderHexagonDYLD *>(baton);
328 // if the dyld_instance is still not valid then try to locate it on the
330 if (!dyld_instance->m_rendezvous.IsValid()) {
331 Process *proc = dyld_instance->m_process;
333 const ConstString dyldStructName("_rtld_debug");
334 addr_t structAddr = findSymbolAddress(proc, dyldStructName);
336 if (structAddr != LLDB_INVALID_ADDRESS) {
337 dyld_instance->m_rendezvous.SetRendezvousAddress(structAddr);
340 log->Printf("Found _rtld_debug structure @ 0x%08" PRIx64, structAddr);
343 log->Printf("Unable to resolve the _rtld_debug structure");
347 dyld_instance->RefreshModules();
349 // Return true to stop the target, false to just let the target run.
350 return dyld_instance->GetStopWhenImagesChange();
353 /// Helper method for RendezvousBreakpointHit. Updates LLDB's current set
354 /// of loaded modules.
355 void DynamicLoaderHexagonDYLD::RefreshModules() {
356 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_DYNAMIC_LOADER));
358 if (!m_rendezvous.Resolve())
361 HexagonDYLDRendezvous::iterator I;
362 HexagonDYLDRendezvous::iterator E;
364 ModuleList &loaded_modules = m_process->GetTarget().GetImages();
366 if (m_rendezvous.ModulesDidLoad()) {
367 ModuleList new_modules;
369 E = m_rendezvous.loaded_end();
370 for (I = m_rendezvous.loaded_begin(); I != E; ++I) {
371 FileSpec file(I->path, true);
373 LoadModuleAtAddress(file, I->link_addr, I->base_addr, true);
374 if (module_sp.get()) {
375 loaded_modules.AppendIfNeeded(module_sp);
376 new_modules.Append(module_sp);
380 log->Printf("Target is loading '%s'", I->path.c_str());
381 if (!module_sp.get())
382 log->Printf("LLDB failed to load '%s'", I->path.c_str());
384 log->Printf("LLDB successfully loaded '%s'", I->path.c_str());
387 m_process->GetTarget().ModulesDidLoad(new_modules);
390 if (m_rendezvous.ModulesDidUnload()) {
391 ModuleList old_modules;
393 E = m_rendezvous.unloaded_end();
394 for (I = m_rendezvous.unloaded_begin(); I != E; ++I) {
395 FileSpec file(I->path, true);
396 ModuleSpec module_spec(file);
397 ModuleSP module_sp = loaded_modules.FindFirstModule(module_spec);
399 if (module_sp.get()) {
400 old_modules.Append(module_sp);
401 UnloadSections(module_sp);
405 log->Printf("Target is unloading '%s'", I->path.c_str());
407 loaded_modules.Remove(old_modules);
408 m_process->GetTarget().ModulesDidUnload(old_modules, false);
412 // AD: This is very different to the Static Loader code.
413 // It may be wise to look over this and its relation to stack
416 DynamicLoaderHexagonDYLD::GetStepThroughTrampolinePlan(Thread &thread,
418 ThreadPlanSP thread_plan_sp;
420 StackFrame *frame = thread.GetStackFrameAtIndex(0).get();
421 const SymbolContext &context = frame->GetSymbolContext(eSymbolContextSymbol);
422 Symbol *sym = context.symbol;
424 if (sym == NULL || !sym->IsTrampoline())
425 return thread_plan_sp;
427 const ConstString sym_name = sym->GetMangled().GetName(
428 lldb::eLanguageTypeUnknown, Mangled::ePreferMangled);
430 return thread_plan_sp;
432 SymbolContextList target_symbols;
433 Target &target = thread.GetProcess()->GetTarget();
434 const ModuleList &images = target.GetImages();
436 images.FindSymbolsWithNameAndType(sym_name, eSymbolTypeCode, target_symbols);
437 size_t num_targets = target_symbols.GetSize();
439 return thread_plan_sp;
441 typedef std::vector<lldb::addr_t> AddressVector;
443 for (size_t i = 0; i < num_targets; ++i) {
444 SymbolContext context;
446 if (target_symbols.GetContextAtIndex(i, context)) {
447 context.GetAddressRange(eSymbolContextEverything, 0, false, range);
448 lldb::addr_t addr = range.GetBaseAddress().GetLoadAddress(&target);
449 if (addr != LLDB_INVALID_ADDRESS)
450 addrs.push_back(addr);
454 if (addrs.size() > 0) {
455 AddressVector::iterator start = addrs.begin();
456 AddressVector::iterator end = addrs.end();
458 std::sort(start, end);
459 addrs.erase(std::unique(start, end), end);
460 thread_plan_sp.reset(new ThreadPlanRunToAddress(thread, addrs, stop));
463 return thread_plan_sp;
466 /// Helper for the entry breakpoint callback. Resolves the load addresses
467 /// of all dependent modules.
468 void DynamicLoaderHexagonDYLD::LoadAllCurrentModules() {
469 HexagonDYLDRendezvous::iterator I;
470 HexagonDYLDRendezvous::iterator E;
471 ModuleList module_list;
473 if (!m_rendezvous.Resolve()) {
474 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_DYNAMIC_LOADER));
477 "DynamicLoaderHexagonDYLD::%s unable to resolve rendezvous address",
482 // The rendezvous class doesn't enumerate the main module, so track that
484 ModuleSP executable = GetTargetExecutable();
485 m_loaded_modules[executable] = m_rendezvous.GetLinkMapAddress();
487 for (I = m_rendezvous.begin(), E = m_rendezvous.end(); I != E; ++I) {
488 const char *module_path = I->path.c_str();
489 FileSpec file(module_path, false);
491 LoadModuleAtAddress(file, I->link_addr, I->base_addr, true);
492 if (module_sp.get()) {
493 module_list.Append(module_sp);
495 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_DYNAMIC_LOADER));
497 log->Printf("DynamicLoaderHexagonDYLD::%s failed loading module %s at "
499 __FUNCTION__, module_path, I->base_addr);
503 m_process->GetTarget().ModulesDidLoad(module_list);
506 /// Computes a value for m_load_offset returning the computed address on
507 /// success and LLDB_INVALID_ADDRESS on failure.
508 addr_t DynamicLoaderHexagonDYLD::ComputeLoadOffset() {
509 // Here we could send a GDB packet to know the load offset
511 // send: $qOffsets#4b
512 // get: Text=0;Data=0;Bss=0
514 // Currently qOffsets is not supported by pluginProcessGDBRemote
519 // Here we must try to read the entry point directly from the elf header. This
520 // is possible if the process is not relocatable or dynamically linked.
522 // an alternative is to look at the PC if we can be sure that we have connected
523 // when the process is at the entry point.
524 // I dont think that is reliable for us.
525 addr_t DynamicLoaderHexagonDYLD::GetEntryPoint() {
526 if (m_entry_point != LLDB_INVALID_ADDRESS)
527 return m_entry_point;
528 // check we have a valid process
529 if (m_process == nullptr)
530 return LLDB_INVALID_ADDRESS;
531 // Get the current executable module
532 Module &module = *(m_process->GetTarget().GetExecutableModule().get());
533 // Get the object file (elf file) for this module
534 lldb_private::ObjectFile &object = *(module.GetObjectFile());
535 // Check if the file is executable (ie, not shared object or relocatable)
536 if (object.IsExecutable()) {
537 // Get the entry point address for this object
538 lldb_private::Address entry = object.GetEntryPointAddress();
539 // Return the entry point address
540 return entry.GetFileAddress();
542 // No idea so back out
543 return LLDB_INVALID_ADDRESS;
546 const SectionList *DynamicLoaderHexagonDYLD::GetSectionListFromModule(
547 const ModuleSP module) const {
548 SectionList *sections = nullptr;
550 ObjectFile *obj_file = module->GetObjectFile();
552 sections = obj_file->GetSectionList();
558 static int ReadInt(Process *process, addr_t addr) {
560 int value = (int)process->ReadUnsignedIntegerFromMemory(
561 addr, sizeof(uint32_t), 0, error);
569 DynamicLoaderHexagonDYLD::GetThreadLocalData(const lldb::ModuleSP module,
570 const lldb::ThreadSP thread,
571 lldb::addr_t tls_file_addr) {
572 auto it = m_loaded_modules.find(module);
573 if (it == m_loaded_modules.end())
574 return LLDB_INVALID_ADDRESS;
576 addr_t link_map = it->second;
577 if (link_map == LLDB_INVALID_ADDRESS)
578 return LLDB_INVALID_ADDRESS;
580 const HexagonDYLDRendezvous::ThreadInfo &metadata =
581 m_rendezvous.GetThreadInfo();
583 return LLDB_INVALID_ADDRESS;
585 // Get the thread pointer.
586 addr_t tp = thread->GetThreadPointer();
587 if (tp == LLDB_INVALID_ADDRESS)
588 return LLDB_INVALID_ADDRESS;
590 // Find the module's modid.
591 int modid = ReadInt(m_process, link_map + metadata.modid_offset);
593 return LLDB_INVALID_ADDRESS;
595 // Lookup the DTV structure for this thread.
596 addr_t dtv_ptr = tp + metadata.dtv_offset;
597 addr_t dtv = ReadPointer(dtv_ptr);
598 if (dtv == LLDB_INVALID_ADDRESS)
599 return LLDB_INVALID_ADDRESS;
601 // Find the TLS block for this module.
602 addr_t dtv_slot = dtv + metadata.dtv_slot_size * modid;
603 addr_t tls_block = ReadPointer(dtv_slot + metadata.tls_offset);
605 Module *mod = module.get();
606 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_DYNAMIC_LOADER));
608 log->Printf("DynamicLoaderHexagonDYLD::Performed TLS lookup: "
609 "module=%s, link_map=0x%" PRIx64 ", tp=0x%" PRIx64
610 ", modid=%i, tls_block=0x%" PRIx64,
611 mod->GetObjectName().AsCString(""), link_map, tp, modid,
614 if (tls_block == LLDB_INVALID_ADDRESS)
615 return LLDB_INVALID_ADDRESS;
617 return tls_block + tls_file_addr;