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 //===----------------------------------------------------------------------===//
10 #include "lldb/Breakpoint/BreakpointLocation.h"
11 #include "lldb/Core/Module.h"
12 #include "lldb/Core/ModuleSpec.h"
13 #include "lldb/Core/PluginManager.h"
14 #include "lldb/Core/Section.h"
15 #include "lldb/Symbol/ObjectFile.h"
16 #include "lldb/Target/Process.h"
17 #include "lldb/Target/Target.h"
18 #include "lldb/Target/Thread.h"
19 #include "lldb/Target/ThreadPlanRunToAddress.h"
20 #include "lldb/Utility/Log.h"
22 #include "DynamicLoaderHexagonDYLD.h"
25 using namespace lldb_private;
29 // Notes about hexagon dynamic loading:
31 // When we connect to a target we find the dyld breakpoint address. We put
33 // breakpoint there with a callback 'RendezvousBreakpointHit()'.
35 // It is possible to find the dyld structure address from the ELF symbol
37 // but in the case of the simulator it has not been initialized before the
38 // target calls dlinit().
40 // We can only safely parse the dyld structure after we hit the dyld
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) {
47 assert(proc != nullptr);
49 ModuleSP module = proc->GetTarget().GetExecutableModule();
50 assert(module.get() != nullptr);
52 ObjectFile *exe = module->GetObjectFile();
53 assert(exe != nullptr);
55 lldb_private::Symtab *symtab = exe->GetSymtab();
56 assert(symtab != nullptr);
58 for (size_t i = 0; i < symtab->GetNumSymbols(); i++) {
59 const Symbol *sym = symtab->SymbolAtIndex(i);
60 assert(sym != nullptr);
61 const ConstString &symName = sym->GetName();
63 if (ConstString::Compare(findName, symName) == 0) {
64 Address addr = sym->GetAddress();
65 return addr.GetLoadAddress(&proc->GetTarget());
68 return LLDB_INVALID_ADDRESS;
71 void DynamicLoaderHexagonDYLD::Initialize() {
72 PluginManager::RegisterPlugin(GetPluginNameStatic(),
73 GetPluginDescriptionStatic(), CreateInstance);
76 void DynamicLoaderHexagonDYLD::Terminate() {}
78 lldb_private::ConstString DynamicLoaderHexagonDYLD::GetPluginName() {
79 return GetPluginNameStatic();
82 lldb_private::ConstString DynamicLoaderHexagonDYLD::GetPluginNameStatic() {
83 static ConstString g_name("hexagon-dyld");
87 const char *DynamicLoaderHexagonDYLD::GetPluginDescriptionStatic() {
88 return "Dynamic loader plug-in that watches for shared library "
89 "loads/unloads in Hexagon processes.";
92 uint32_t DynamicLoaderHexagonDYLD::GetPluginVersion() { return 1; }
94 DynamicLoader *DynamicLoaderHexagonDYLD::CreateInstance(Process *process,
98 const llvm::Triple &triple_ref =
99 process->GetTarget().GetArchitecture().GetTriple();
100 if (triple_ref.getArch() == llvm::Triple::hexagon)
105 return new DynamicLoaderHexagonDYLD(process);
109 DynamicLoaderHexagonDYLD::DynamicLoaderHexagonDYLD(Process *process)
110 : DynamicLoader(process), m_rendezvous(process),
111 m_load_offset(LLDB_INVALID_ADDRESS), m_entry_point(LLDB_INVALID_ADDRESS),
112 m_dyld_bid(LLDB_INVALID_BREAK_ID) {}
114 DynamicLoaderHexagonDYLD::~DynamicLoaderHexagonDYLD() {
115 if (m_dyld_bid != LLDB_INVALID_BREAK_ID) {
116 m_process->GetTarget().RemoveBreakpointByID(m_dyld_bid);
117 m_dyld_bid = LLDB_INVALID_BREAK_ID;
121 void DynamicLoaderHexagonDYLD::DidAttach() {
125 executable = GetTargetExecutable();
127 // Find the difference between the desired load address in the elf file and
128 // the real load address in memory
129 load_offset = ComputeLoadOffset();
131 // Check that there is a valid executable
132 if (executable.get() == nullptr)
135 // Disable JIT for hexagon targets because its not supported
136 m_process->SetCanJIT(false);
138 // Enable Interpreting of function call expressions
139 m_process->SetCanInterpretFunctionCalls(true);
141 // Add the current executable to the module list
142 ModuleList module_list;
143 module_list.Append(executable);
145 // Map the loaded sections of this executable
146 if (load_offset != LLDB_INVALID_ADDRESS)
147 UpdateLoadedSections(executable, LLDB_INVALID_ADDRESS, load_offset, true);
150 // Load into LLDB all of the currently loaded executables in the stub
151 LoadAllCurrentModules();
154 // Callback for the target to give it the loaded module list
155 m_process->GetTarget().ModulesDidLoad(module_list);
157 // Try to set a breakpoint at the rendezvous breakpoint. DidLaunch uses
158 // ProbeEntry() instead. That sets a breakpoint, at the dyld breakpoint
159 // address, with a callback so that when hit, the dyld structure can be
161 if (!SetRendezvousBreakpoint()) {
166 void DynamicLoaderHexagonDYLD::DidLaunch() {}
168 /// Checks to see if the target module has changed, updates the target
169 /// accordingly and returns the target executable module.
170 ModuleSP DynamicLoaderHexagonDYLD::GetTargetExecutable() {
171 Target &target = m_process->GetTarget();
172 ModuleSP executable = target.GetExecutableModule();
174 // There is no executable
175 if (!executable.get())
178 // The target executable file does not exits
179 if (!FileSystem::Instance().Exists(executable->GetFileSpec()))
182 // Prep module for loading
183 ModuleSpec module_spec(executable->GetFileSpec(),
184 executable->GetArchitecture());
185 ModuleSP module_sp(new Module(module_spec));
187 // Check if the executable has changed and set it to the target executable if
189 if (module_sp.get() && module_sp->GetUUID().IsValid() &&
190 executable->GetUUID().IsValid()) {
191 // if the executable has changed ??
192 if (module_sp->GetUUID() != executable->GetUUID())
194 } else if (executable->FileHasChanged())
197 if (executable.get())
200 // TODO: What case is this code used?
201 executable = target.GetSharedModule(module_spec);
202 if (executable.get() != target.GetExecutableModulePointer()) {
203 // Don't load dependent images since we are in dyld where we will know and
204 // find out about all images that are loaded
205 target.SetExecutableModule(executable, eLoadDependentsNo);
211 // AD: Needs to be updated?
212 Status DynamicLoaderHexagonDYLD::CanLoadImage() { return Status(); }
214 void DynamicLoaderHexagonDYLD::UpdateLoadedSections(ModuleSP module,
215 addr_t link_map_addr,
217 bool base_addr_is_offset) {
218 Target &target = m_process->GetTarget();
219 const SectionList *sections = GetSectionListFromModule(module);
221 assert(sections && "SectionList missing from loaded module.");
223 m_loaded_modules[module] = link_map_addr;
225 const size_t num_sections = sections->GetSize();
227 for (unsigned i = 0; i < num_sections; ++i) {
228 SectionSP section_sp(sections->GetSectionAtIndex(i));
229 lldb::addr_t new_load_addr = section_sp->GetFileAddress() + base_addr;
232 // since our memory map starts from address 0, we must not ignore
233 // sections that load to address 0. This violates the reference
234 // ELF spec, however is used for Hexagon.
236 // If the file address of the section is zero then this is not an
237 // allocatable/loadable section (property of ELF sh_addr). Skip it.
238 // if (new_load_addr == base_addr)
241 target.SetSectionLoadAddress(section_sp, new_load_addr);
245 /// Removes the loaded sections from the target in @p module.
247 /// @param module The module to traverse.
248 void DynamicLoaderHexagonDYLD::UnloadSections(const ModuleSP module) {
249 Target &target = m_process->GetTarget();
250 const SectionList *sections = GetSectionListFromModule(module);
252 assert(sections && "SectionList missing from unloaded module.");
254 m_loaded_modules.erase(module);
256 const size_t num_sections = sections->GetSize();
257 for (size_t i = 0; i < num_sections; ++i) {
258 SectionSP section_sp(sections->GetSectionAtIndex(i));
259 target.SetSectionUnloaded(section_sp);
263 // Place a breakpoint on <_rtld_debug_state>
264 bool DynamicLoaderHexagonDYLD::SetRendezvousBreakpoint() {
265 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_DYNAMIC_LOADER));
267 // This is the original code, which want to look in the rendezvous structure
268 // to find the breakpoint address. Its backwards for us, since we can easily
269 // find the breakpoint address, since it is exported in our executable. We
270 // however know that we cant read the Rendezvous structure until we have hit
271 // the breakpoint once.
272 const ConstString dyldBpName("_rtld_debug_state");
273 addr_t break_addr = findSymbolAddress(m_process, dyldBpName);
275 Target &target = m_process->GetTarget();
277 // Do not try to set the breakpoint if we don't know where to put it
278 if (break_addr == LLDB_INVALID_ADDRESS) {
280 log->Printf("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 log->Printf("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));
319 log->Printf("Rendezvous breakpoint hit!");
321 DynamicLoaderHexagonDYLD *dyld_instance = nullptr;
322 dyld_instance = static_cast<DynamicLoaderHexagonDYLD *>(baton);
324 // if the dyld_instance is still not valid then try to locate it on the
326 if (!dyld_instance->m_rendezvous.IsValid()) {
327 Process *proc = dyld_instance->m_process;
329 const ConstString dyldStructName("_rtld_debug");
330 addr_t structAddr = findSymbolAddress(proc, dyldStructName);
332 if (structAddr != LLDB_INVALID_ADDRESS) {
333 dyld_instance->m_rendezvous.SetRendezvousAddress(structAddr);
336 log->Printf("Found _rtld_debug structure @ 0x%08" PRIx64, structAddr);
339 log->Printf("Unable to resolve the _rtld_debug structure");
343 dyld_instance->RefreshModules();
345 // Return true to stop the target, false to just let the target run.
346 return dyld_instance->GetStopWhenImagesChange();
349 /// Helper method for RendezvousBreakpointHit. Updates LLDB's current set
350 /// of loaded modules.
351 void DynamicLoaderHexagonDYLD::RefreshModules() {
352 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_DYNAMIC_LOADER));
354 if (!m_rendezvous.Resolve())
357 HexagonDYLDRendezvous::iterator I;
358 HexagonDYLDRendezvous::iterator E;
360 ModuleList &loaded_modules = m_process->GetTarget().GetImages();
362 if (m_rendezvous.ModulesDidLoad()) {
363 ModuleList new_modules;
365 E = m_rendezvous.loaded_end();
366 for (I = m_rendezvous.loaded_begin(); I != E; ++I) {
367 FileSpec file(I->path);
368 FileSystem::Instance().Resolve(file);
370 LoadModuleAtAddress(file, I->link_addr, I->base_addr, true);
371 if (module_sp.get()) {
372 loaded_modules.AppendIfNeeded(module_sp);
373 new_modules.Append(module_sp);
377 log->Printf("Target is loading '%s'", I->path.c_str());
378 if (!module_sp.get())
379 log->Printf("LLDB failed to load '%s'", I->path.c_str());
381 log->Printf("LLDB successfully loaded '%s'", I->path.c_str());
384 m_process->GetTarget().ModulesDidLoad(new_modules);
387 if (m_rendezvous.ModulesDidUnload()) {
388 ModuleList old_modules;
390 E = m_rendezvous.unloaded_end();
391 for (I = m_rendezvous.unloaded_begin(); I != E; ++I) {
392 FileSpec file(I->path);
393 FileSystem::Instance().Resolve(file);
394 ModuleSpec module_spec(file);
395 ModuleSP module_sp = loaded_modules.FindFirstModule(module_spec);
397 if (module_sp.get()) {
398 old_modules.Append(module_sp);
399 UnloadSections(module_sp);
403 log->Printf("Target is unloading '%s'", I->path.c_str());
405 loaded_modules.Remove(old_modules);
406 m_process->GetTarget().ModulesDidUnload(old_modules, false);
410 // AD: This is very different to the Static Loader code.
411 // It may be wise to look over this and its relation to stack
414 DynamicLoaderHexagonDYLD::GetStepThroughTrampolinePlan(Thread &thread,
416 ThreadPlanSP thread_plan_sp;
418 StackFrame *frame = thread.GetStackFrameAtIndex(0).get();
419 const SymbolContext &context = frame->GetSymbolContext(eSymbolContextSymbol);
420 Symbol *sym = context.symbol;
422 if (sym == NULL || !sym->IsTrampoline())
423 return thread_plan_sp;
425 const ConstString sym_name = sym->GetMangled().GetName(
426 lldb::eLanguageTypeUnknown, Mangled::ePreferMangled);
428 return thread_plan_sp;
430 SymbolContextList target_symbols;
431 Target &target = thread.GetProcess()->GetTarget();
432 const ModuleList &images = target.GetImages();
434 images.FindSymbolsWithNameAndType(sym_name, eSymbolTypeCode, target_symbols);
435 size_t num_targets = target_symbols.GetSize();
437 return thread_plan_sp;
439 typedef std::vector<lldb::addr_t> AddressVector;
441 for (size_t i = 0; i < num_targets; ++i) {
442 SymbolContext context;
444 if (target_symbols.GetContextAtIndex(i, context)) {
445 context.GetAddressRange(eSymbolContextEverything, 0, false, range);
446 lldb::addr_t addr = range.GetBaseAddress().GetLoadAddress(&target);
447 if (addr != LLDB_INVALID_ADDRESS)
448 addrs.push_back(addr);
452 if (addrs.size() > 0) {
453 AddressVector::iterator start = addrs.begin();
454 AddressVector::iterator end = addrs.end();
456 llvm::sort(start, end);
457 addrs.erase(std::unique(start, end), end);
458 thread_plan_sp.reset(new ThreadPlanRunToAddress(thread, addrs, stop));
461 return thread_plan_sp;
464 /// Helper for the entry breakpoint callback. Resolves the load addresses
465 /// of all dependent modules.
466 void DynamicLoaderHexagonDYLD::LoadAllCurrentModules() {
467 HexagonDYLDRendezvous::iterator I;
468 HexagonDYLDRendezvous::iterator E;
469 ModuleList module_list;
471 if (!m_rendezvous.Resolve()) {
472 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_DYNAMIC_LOADER));
475 "DynamicLoaderHexagonDYLD::%s unable to resolve rendezvous address",
480 // The rendezvous class doesn't enumerate the main module, so track that
482 ModuleSP executable = GetTargetExecutable();
483 m_loaded_modules[executable] = m_rendezvous.GetLinkMapAddress();
485 for (I = m_rendezvous.begin(), E = m_rendezvous.end(); I != E; ++I) {
486 const char *module_path = I->path.c_str();
487 FileSpec file(module_path);
489 LoadModuleAtAddress(file, I->link_addr, I->base_addr, true);
490 if (module_sp.get()) {
491 module_list.Append(module_sp);
493 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_DYNAMIC_LOADER));
495 log->Printf("DynamicLoaderHexagonDYLD::%s failed loading module %s at "
497 __FUNCTION__, module_path, I->base_addr);
501 m_process->GetTarget().ModulesDidLoad(module_list);
504 /// Computes a value for m_load_offset returning the computed address on
505 /// success and LLDB_INVALID_ADDRESS on failure.
506 addr_t DynamicLoaderHexagonDYLD::ComputeLoadOffset() {
507 // Here we could send a GDB packet to know the load offset
509 // send: $qOffsets#4b
510 // get: Text=0;Data=0;Bss=0
512 // Currently qOffsets is not supported by pluginProcessGDBRemote
517 // Here we must try to read the entry point directly from the elf header. This
518 // is possible if the process is not relocatable or dynamically linked.
520 // an alternative is to look at the PC if we can be sure that we have connected
521 // when the process is at the entry point.
522 // I dont think that is reliable for us.
523 addr_t DynamicLoaderHexagonDYLD::GetEntryPoint() {
524 if (m_entry_point != LLDB_INVALID_ADDRESS)
525 return m_entry_point;
526 // check we have a valid process
527 if (m_process == nullptr)
528 return LLDB_INVALID_ADDRESS;
529 // Get the current executable module
530 Module &module = *(m_process->GetTarget().GetExecutableModule().get());
531 // Get the object file (elf file) for this module
532 lldb_private::ObjectFile &object = *(module.GetObjectFile());
533 // Check if the file is executable (ie, not shared object or relocatable)
534 if (object.IsExecutable()) {
535 // Get the entry point address for this object
536 lldb_private::Address entry = object.GetEntryPointAddress();
537 // Return the entry point address
538 return entry.GetFileAddress();
540 // No idea so back out
541 return LLDB_INVALID_ADDRESS;
544 const SectionList *DynamicLoaderHexagonDYLD::GetSectionListFromModule(
545 const ModuleSP module) const {
546 SectionList *sections = nullptr;
548 ObjectFile *obj_file = module->GetObjectFile();
550 sections = obj_file->GetSectionList();
556 static int ReadInt(Process *process, addr_t addr) {
558 int value = (int)process->ReadUnsignedIntegerFromMemory(
559 addr, sizeof(uint32_t), 0, error);
567 DynamicLoaderHexagonDYLD::GetThreadLocalData(const lldb::ModuleSP module,
568 const lldb::ThreadSP thread,
569 lldb::addr_t tls_file_addr) {
570 auto it = m_loaded_modules.find(module);
571 if (it == m_loaded_modules.end())
572 return LLDB_INVALID_ADDRESS;
574 addr_t link_map = it->second;
575 if (link_map == LLDB_INVALID_ADDRESS)
576 return LLDB_INVALID_ADDRESS;
578 const HexagonDYLDRendezvous::ThreadInfo &metadata =
579 m_rendezvous.GetThreadInfo();
581 return LLDB_INVALID_ADDRESS;
583 // Get the thread pointer.
584 addr_t tp = thread->GetThreadPointer();
585 if (tp == LLDB_INVALID_ADDRESS)
586 return LLDB_INVALID_ADDRESS;
588 // Find the module's modid.
589 int modid = ReadInt(m_process, link_map + metadata.modid_offset);
591 return LLDB_INVALID_ADDRESS;
593 // Lookup the DTV structure for this thread.
594 addr_t dtv_ptr = tp + metadata.dtv_offset;
595 addr_t dtv = ReadPointer(dtv_ptr);
596 if (dtv == LLDB_INVALID_ADDRESS)
597 return LLDB_INVALID_ADDRESS;
599 // Find the TLS block for this module.
600 addr_t dtv_slot = dtv + metadata.dtv_slot_size * modid;
601 addr_t tls_block = ReadPointer(dtv_slot + metadata.tls_offset);
603 Module *mod = module.get();
604 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_DYNAMIC_LOADER));
606 log->Printf("DynamicLoaderHexagonDYLD::Performed TLS lookup: "
607 "module=%s, link_map=0x%" PRIx64 ", tp=0x%" PRIx64
608 ", modid=%i, tls_block=0x%" PRIx64,
609 mod->GetObjectName().AsCString(""), link_map, tp, modid,
612 if (tls_block == LLDB_INVALID_ADDRESS)
613 return LLDB_INVALID_ADDRESS;
615 return tls_block + tls_file_addr;