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/Log.h"
15 #include "lldb/Core/Module.h"
16 #include "lldb/Core/ModuleSpec.h"
17 #include "lldb/Core/PluginManager.h"
18 #include "lldb/Core/Section.h"
19 #include "lldb/Symbol/ObjectFile.h"
20 #include "lldb/Target/Process.h"
21 #include "lldb/Target/Target.h"
22 #include "lldb/Target/Thread.h"
23 #include "lldb/Target/ThreadPlanRunToAddress.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
131 // and 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.
161 // DidLaunch uses ProbeEntry() instead. That sets a breakpoint,
162 // at the dyld breakpoint address, with a callback so that when hit,
163 // the dyld structure can be parsed.
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
207 // and 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 Error DynamicLoaderHexagonDYLD::CanLoadImage() { return Error(); }
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.
274 // We however know that we cant read the Rendezvous structure until we have
276 // the breakpoint once.
277 const ConstString dyldBpName("_rtld_debug_state");
278 addr_t break_addr = findSymbolAddress(m_process, dyldBpName);
280 Target &target = m_process->GetTarget();
282 // Do not try to set the breakpoint if we don't know where to put it
283 if (break_addr == LLDB_INVALID_ADDRESS) {
285 log->Printf("Unable to locate _rtld_debug_state breakpoint address");
290 // Save the address of the rendezvous structure
291 m_rendezvous.SetBreakAddress(break_addr);
293 // If we haven't set the breakpoint before then set it
294 if (m_dyld_bid == LLDB_INVALID_BREAK_ID) {
295 Breakpoint *dyld_break =
296 target.CreateBreakpoint(break_addr, true, false).get();
297 dyld_break->SetCallback(RendezvousBreakpointHit, this, true);
298 dyld_break->SetBreakpointKind("shared-library-event");
299 m_dyld_bid = dyld_break->GetID();
301 // Make sure our breakpoint is at the right address.
302 assert(target.GetBreakpointByID(m_dyld_bid)
303 ->FindLocationByAddress(break_addr)
305 .GetID() == m_dyld_bid);
307 if (log && dyld_break == nullptr)
308 log->Printf("Failed to create _rtld_debug_state breakpoint");
310 // check we have successfully set bp
311 return (dyld_break != nullptr);
313 // rendezvous already set
317 // We have just hit our breakpoint at <_rtld_debug_state>
318 bool DynamicLoaderHexagonDYLD::RendezvousBreakpointHit(
319 void *baton, StoppointCallbackContext *context, user_id_t break_id,
320 user_id_t break_loc_id) {
321 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_DYNAMIC_LOADER));
324 log->Printf("Rendezvous breakpoint hit!");
326 DynamicLoaderHexagonDYLD *dyld_instance = nullptr;
327 dyld_instance = static_cast<DynamicLoaderHexagonDYLD *>(baton);
329 // if the dyld_instance is still not valid then
330 // try to locate it on the symbol table
331 if (!dyld_instance->m_rendezvous.IsValid()) {
332 Process *proc = dyld_instance->m_process;
334 const ConstString dyldStructName("_rtld_debug");
335 addr_t structAddr = findSymbolAddress(proc, dyldStructName);
337 if (structAddr != LLDB_INVALID_ADDRESS) {
338 dyld_instance->m_rendezvous.SetRendezvousAddress(structAddr);
341 log->Printf("Found _rtld_debug structure @ 0x%08" PRIx64, structAddr);
344 log->Printf("Unable to resolve the _rtld_debug structure");
348 dyld_instance->RefreshModules();
350 // Return true to stop the target, false to just let the target run.
351 return dyld_instance->GetStopWhenImagesChange();
354 /// Helper method for RendezvousBreakpointHit. Updates LLDB's current set
355 /// of loaded modules.
356 void DynamicLoaderHexagonDYLD::RefreshModules() {
357 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_DYNAMIC_LOADER));
359 if (!m_rendezvous.Resolve())
362 HexagonDYLDRendezvous::iterator I;
363 HexagonDYLDRendezvous::iterator E;
365 ModuleList &loaded_modules = m_process->GetTarget().GetImages();
367 if (m_rendezvous.ModulesDidLoad()) {
368 ModuleList new_modules;
370 E = m_rendezvous.loaded_end();
371 for (I = m_rendezvous.loaded_begin(); I != E; ++I) {
372 FileSpec file(I->path, true);
374 LoadModuleAtAddress(file, I->link_addr, I->base_addr, true);
375 if (module_sp.get()) {
376 loaded_modules.AppendIfNeeded(module_sp);
377 new_modules.Append(module_sp);
381 log->Printf("Target is loading '%s'", I->path.c_str());
382 if (!module_sp.get())
383 log->Printf("LLDB failed to load '%s'", I->path.c_str());
385 log->Printf("LLDB successfully loaded '%s'", I->path.c_str());
388 m_process->GetTarget().ModulesDidLoad(new_modules);
391 if (m_rendezvous.ModulesDidUnload()) {
392 ModuleList old_modules;
394 E = m_rendezvous.unloaded_end();
395 for (I = m_rendezvous.unloaded_begin(); I != E; ++I) {
396 FileSpec file(I->path, true);
397 ModuleSpec module_spec(file);
398 ModuleSP module_sp = loaded_modules.FindFirstModule(module_spec);
400 if (module_sp.get()) {
401 old_modules.Append(module_sp);
402 UnloadSections(module_sp);
406 log->Printf("Target is unloading '%s'", I->path.c_str());
408 loaded_modules.Remove(old_modules);
409 m_process->GetTarget().ModulesDidUnload(old_modules, false);
413 // AD: This is very different to the Static Loader code.
414 // It may be wise to look over this and its relation to stack
417 DynamicLoaderHexagonDYLD::GetStepThroughTrampolinePlan(Thread &thread,
419 ThreadPlanSP thread_plan_sp;
421 StackFrame *frame = thread.GetStackFrameAtIndex(0).get();
422 const SymbolContext &context = frame->GetSymbolContext(eSymbolContextSymbol);
423 Symbol *sym = context.symbol;
425 if (sym == NULL || !sym->IsTrampoline())
426 return thread_plan_sp;
428 const ConstString sym_name = sym->GetMangled().GetName(
429 lldb::eLanguageTypeUnknown, Mangled::ePreferMangled);
431 return thread_plan_sp;
433 SymbolContextList target_symbols;
434 Target &target = thread.GetProcess()->GetTarget();
435 const ModuleList &images = target.GetImages();
437 images.FindSymbolsWithNameAndType(sym_name, eSymbolTypeCode, target_symbols);
438 size_t num_targets = target_symbols.GetSize();
440 return thread_plan_sp;
442 typedef std::vector<lldb::addr_t> AddressVector;
444 for (size_t i = 0; i < num_targets; ++i) {
445 SymbolContext context;
447 if (target_symbols.GetContextAtIndex(i, context)) {
448 context.GetAddressRange(eSymbolContextEverything, 0, false, range);
449 lldb::addr_t addr = range.GetBaseAddress().GetLoadAddress(&target);
450 if (addr != LLDB_INVALID_ADDRESS)
451 addrs.push_back(addr);
455 if (addrs.size() > 0) {
456 AddressVector::iterator start = addrs.begin();
457 AddressVector::iterator end = addrs.end();
459 std::sort(start, end);
460 addrs.erase(std::unique(start, end), end);
461 thread_plan_sp.reset(new ThreadPlanRunToAddress(thread, addrs, stop));
464 return thread_plan_sp;
467 /// Helper for the entry breakpoint callback. Resolves the load addresses
468 /// of all dependent modules.
469 void DynamicLoaderHexagonDYLD::LoadAllCurrentModules() {
470 HexagonDYLDRendezvous::iterator I;
471 HexagonDYLDRendezvous::iterator E;
472 ModuleList module_list;
474 if (!m_rendezvous.Resolve()) {
475 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_DYNAMIC_LOADER));
478 "DynamicLoaderHexagonDYLD::%s unable to resolve rendezvous address",
483 // The rendezvous class doesn't enumerate the main module, so track
484 // that ourselves here.
485 ModuleSP executable = GetTargetExecutable();
486 m_loaded_modules[executable] = m_rendezvous.GetLinkMapAddress();
488 for (I = m_rendezvous.begin(), E = m_rendezvous.end(); I != E; ++I) {
489 const char *module_path = I->path.c_str();
490 FileSpec file(module_path, false);
492 LoadModuleAtAddress(file, I->link_addr, I->base_addr, true);
493 if (module_sp.get()) {
494 module_list.Append(module_sp);
496 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_DYNAMIC_LOADER));
498 log->Printf("DynamicLoaderHexagonDYLD::%s failed loading module %s at "
500 __FUNCTION__, module_path, I->base_addr);
504 m_process->GetTarget().ModulesDidLoad(module_list);
507 /// Computes a value for m_load_offset returning the computed address on
508 /// success and LLDB_INVALID_ADDRESS on failure.
509 addr_t DynamicLoaderHexagonDYLD::ComputeLoadOffset() {
510 // Here we could send a GDB packet to know the load offset
512 // send: $qOffsets#4b
513 // get: Text=0;Data=0;Bss=0
515 // Currently qOffsets is not supported by pluginProcessGDBRemote
520 // Here we must try to read the entry point directly from
521 // the elf header. This is possible if the process is not
522 // relocatable or dynamically linked.
524 // an alternative is to look at the PC if we can be sure
525 // that we have connected when the process is at the entry point.
526 // I dont think that is reliable for us.
527 addr_t DynamicLoaderHexagonDYLD::GetEntryPoint() {
528 if (m_entry_point != LLDB_INVALID_ADDRESS)
529 return m_entry_point;
530 // check we have a valid process
531 if (m_process == nullptr)
532 return LLDB_INVALID_ADDRESS;
533 // Get the current executable module
534 Module &module = *(m_process->GetTarget().GetExecutableModule().get());
535 // Get the object file (elf file) for this module
536 lldb_private::ObjectFile &object = *(module.GetObjectFile());
537 // Check if the file is executable (ie, not shared object or relocatable)
538 if (object.IsExecutable()) {
539 // Get the entry point address for this object
540 lldb_private::Address entry = object.GetEntryPointAddress();
541 // Return the entry point address
542 return entry.GetFileAddress();
544 // No idea so back out
545 return LLDB_INVALID_ADDRESS;
548 const SectionList *DynamicLoaderHexagonDYLD::GetSectionListFromModule(
549 const ModuleSP module) const {
550 SectionList *sections = nullptr;
552 ObjectFile *obj_file = module->GetObjectFile();
554 sections = obj_file->GetSectionList();
560 static int ReadInt(Process *process, addr_t addr) {
562 int value = (int)process->ReadUnsignedIntegerFromMemory(
563 addr, sizeof(uint32_t), 0, error);
571 DynamicLoaderHexagonDYLD::GetThreadLocalData(const lldb::ModuleSP module,
572 const lldb::ThreadSP thread,
573 lldb::addr_t tls_file_addr) {
574 auto it = m_loaded_modules.find(module);
575 if (it == m_loaded_modules.end())
576 return LLDB_INVALID_ADDRESS;
578 addr_t link_map = it->second;
579 if (link_map == LLDB_INVALID_ADDRESS)
580 return LLDB_INVALID_ADDRESS;
582 const HexagonDYLDRendezvous::ThreadInfo &metadata =
583 m_rendezvous.GetThreadInfo();
585 return LLDB_INVALID_ADDRESS;
587 // Get the thread pointer.
588 addr_t tp = thread->GetThreadPointer();
589 if (tp == LLDB_INVALID_ADDRESS)
590 return LLDB_INVALID_ADDRESS;
592 // Find the module's modid.
593 int modid = ReadInt(m_process, link_map + metadata.modid_offset);
595 return LLDB_INVALID_ADDRESS;
597 // Lookup the DTV structure for this thread.
598 addr_t dtv_ptr = tp + metadata.dtv_offset;
599 addr_t dtv = ReadPointer(dtv_ptr);
600 if (dtv == LLDB_INVALID_ADDRESS)
601 return LLDB_INVALID_ADDRESS;
603 // Find the TLS block for this module.
604 addr_t dtv_slot = dtv + metadata.dtv_slot_size * modid;
605 addr_t tls_block = ReadPointer(dtv_slot + metadata.tls_offset);
607 Module *mod = module.get();
608 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_DYNAMIC_LOADER));
610 log->Printf("DynamicLoaderHexagonDYLD::Performed TLS lookup: "
611 "module=%s, link_map=0x%" PRIx64 ", tp=0x%" PRIx64
612 ", modid=%i, tls_block=0x%" PRIx64,
613 mod->GetObjectName().AsCString(""), link_map, tp, modid,
616 if (tls_block == LLDB_INVALID_ADDRESS)
617 return LLDB_INVALID_ADDRESS;
619 return tls_block + tls_file_addr;