]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - contrib/llvm/tools/lldb/source/Plugins/DynamicLoader/Hexagon-DYLD/DynamicLoaderHexagonDYLD.cpp
Merge clang 7.0.1 and several follow-up changes
[FreeBSD/FreeBSD.git] / contrib / llvm / tools / lldb / source / Plugins / DynamicLoader / Hexagon-DYLD / DynamicLoaderHexagonDYLD.cpp
1 //===-- DynamicLoaderHexagonDYLD.cpp ----------------------------*- C++ -*-===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9
10 // C Includes
11 // C++ Includes
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"
24
25 #include "DynamicLoaderHexagonDYLD.h"
26
27 using namespace lldb;
28 using namespace lldb_private;
29
30 // Aidan 21/05/2014
31 //
32 // Notes about hexagon dynamic loading:
33 //
34 //      When we connect to a target we find the dyld breakpoint address.  We put
35 //      a
36 //      breakpoint there with a callback 'RendezvousBreakpointHit()'.
37 //
38 //      It is possible to find the dyld structure address from the ELF symbol
39 //      table,
40 //      but in the case of the simulator it has not been initialized before the
41 //      target calls dlinit().
42 //
43 //      We can only safely parse the dyld structure after we hit the dyld
44 //      breakpoint
45 //      since at that time we know dlinit() must have been called.
46 //
47
48 // Find the load address of a symbol
49 static lldb::addr_t findSymbolAddress(Process *proc, ConstString findName) {
50   assert(proc != nullptr);
51
52   ModuleSP module = proc->GetTarget().GetExecutableModule();
53   assert(module.get() != nullptr);
54
55   ObjectFile *exe = module->GetObjectFile();
56   assert(exe != nullptr);
57
58   lldb_private::Symtab *symtab = exe->GetSymtab();
59   assert(symtab != nullptr);
60
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();
65
66     if (ConstString::Compare(findName, symName) == 0) {
67       Address addr = sym->GetAddress();
68       return addr.GetLoadAddress(&proc->GetTarget());
69     }
70   }
71   return LLDB_INVALID_ADDRESS;
72 }
73
74 void DynamicLoaderHexagonDYLD::Initialize() {
75   PluginManager::RegisterPlugin(GetPluginNameStatic(),
76                                 GetPluginDescriptionStatic(), CreateInstance);
77 }
78
79 void DynamicLoaderHexagonDYLD::Terminate() {}
80
81 lldb_private::ConstString DynamicLoaderHexagonDYLD::GetPluginName() {
82   return GetPluginNameStatic();
83 }
84
85 lldb_private::ConstString DynamicLoaderHexagonDYLD::GetPluginNameStatic() {
86   static ConstString g_name("hexagon-dyld");
87   return g_name;
88 }
89
90 const char *DynamicLoaderHexagonDYLD::GetPluginDescriptionStatic() {
91   return "Dynamic loader plug-in that watches for shared library "
92          "loads/unloads in Hexagon processes.";
93 }
94
95 uint32_t DynamicLoaderHexagonDYLD::GetPluginVersion() { return 1; }
96
97 DynamicLoader *DynamicLoaderHexagonDYLD::CreateInstance(Process *process,
98                                                         bool force) {
99   bool create = force;
100   if (!create) {
101     const llvm::Triple &triple_ref =
102         process->GetTarget().GetArchitecture().GetTriple();
103     if (triple_ref.getArch() == llvm::Triple::hexagon)
104       create = true;
105   }
106
107   if (create)
108     return new DynamicLoaderHexagonDYLD(process);
109   return NULL;
110 }
111
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) {}
116
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;
121   }
122 }
123
124 void DynamicLoaderHexagonDYLD::DidAttach() {
125   ModuleSP executable;
126   addr_t load_offset;
127
128   executable = GetTargetExecutable();
129
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();
133
134   // Check that there is a valid executable
135   if (executable.get() == nullptr)
136     return;
137
138   // Disable JIT for hexagon targets because its not supported
139   m_process->SetCanJIT(false);
140
141   // Enable Interpreting of function call expressions
142   m_process->SetCanInterpretFunctionCalls(true);
143
144   // Add the current executable to the module list
145   ModuleList module_list;
146   module_list.Append(executable);
147
148   // Map the loaded sections of this executable
149   if (load_offset != LLDB_INVALID_ADDRESS)
150     UpdateLoadedSections(executable, LLDB_INVALID_ADDRESS, load_offset, true);
151
152   // AD: confirm this?
153   // Load into LLDB all of the currently loaded executables in the stub
154   LoadAllCurrentModules();
155
156   // AD: confirm this?
157   // Callback for the target to give it the loaded module list
158   m_process->GetTarget().ModulesDidLoad(module_list);
159
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
163   // parsed.
164   if (!SetRendezvousBreakpoint()) {
165     // fail
166   }
167 }
168
169 void DynamicLoaderHexagonDYLD::DidLaunch() {}
170
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();
176
177   // There is no executable
178   if (!executable.get())
179     return executable;
180
181   // The target executable file does not exits
182   if (!executable->GetFileSpec().Exists())
183     return executable;
184
185   // Prep module for loading
186   ModuleSpec module_spec(executable->GetFileSpec(),
187                          executable->GetArchitecture());
188   ModuleSP module_sp(new Module(module_spec));
189
190   // Check if the executable has changed and set it to the target executable if
191   // they differ.
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())
196       executable.reset();
197   } else if (executable->FileHasChanged())
198     executable.reset();
199
200   if (executable.get())
201     return executable;
202
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);
210   }
211
212   return executable;
213 }
214
215 // AD: Needs to be updated?
216 Status DynamicLoaderHexagonDYLD::CanLoadImage() { return Status(); }
217
218 void DynamicLoaderHexagonDYLD::UpdateLoadedSections(ModuleSP module,
219                                                     addr_t link_map_addr,
220                                                     addr_t base_addr,
221                                                     bool base_addr_is_offset) {
222   Target &target = m_process->GetTarget();
223   const SectionList *sections = GetSectionListFromModule(module);
224
225   assert(sections && "SectionList missing from loaded module.");
226
227   m_loaded_modules[module] = link_map_addr;
228
229   const size_t num_sections = sections->GetSize();
230
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;
234
235     // AD: 02/05/14
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.
239
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)
243     //          continue;
244
245     target.SetSectionLoadAddress(section_sp, new_load_addr);
246   }
247 }
248
249 /// Removes the loaded sections from the target in @p module.
250 ///
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);
255
256   assert(sections && "SectionList missing from unloaded module.");
257
258   m_loaded_modules.erase(module);
259
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);
264   }
265 }
266
267 // Place a breakpoint on <_rtld_debug_state>
268 bool DynamicLoaderHexagonDYLD::SetRendezvousBreakpoint() {
269   Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_DYNAMIC_LOADER));
270
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);
278
279   Target &target = m_process->GetTarget();
280
281   // Do not try to set the breakpoint if we don't know where to put it
282   if (break_addr == LLDB_INVALID_ADDRESS) {
283     if (log)
284       log->Printf("Unable to locate _rtld_debug_state breakpoint address");
285
286     return false;
287   }
288
289   // Save the address of the rendezvous structure
290   m_rendezvous.SetBreakAddress(break_addr);
291
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();
299
300     // Make sure our breakpoint is at the right address.
301     assert(target.GetBreakpointByID(m_dyld_bid)
302                ->FindLocationByAddress(break_addr)
303                ->GetBreakpoint()
304                .GetID() == m_dyld_bid);
305
306     if (log && dyld_break == nullptr)
307       log->Printf("Failed to create _rtld_debug_state breakpoint");
308
309     // check we have successfully set bp
310     return (dyld_break != nullptr);
311   } else
312     // rendezvous already set
313     return true;
314 }
315
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));
321
322   if (log)
323     log->Printf("Rendezvous breakpoint hit!");
324
325   DynamicLoaderHexagonDYLD *dyld_instance = nullptr;
326   dyld_instance = static_cast<DynamicLoaderHexagonDYLD *>(baton);
327
328   // if the dyld_instance is still not valid then try to locate it on the
329   // symbol table
330   if (!dyld_instance->m_rendezvous.IsValid()) {
331     Process *proc = dyld_instance->m_process;
332
333     const ConstString dyldStructName("_rtld_debug");
334     addr_t structAddr = findSymbolAddress(proc, dyldStructName);
335
336     if (structAddr != LLDB_INVALID_ADDRESS) {
337       dyld_instance->m_rendezvous.SetRendezvousAddress(structAddr);
338
339       if (log)
340         log->Printf("Found _rtld_debug structure @ 0x%08" PRIx64, structAddr);
341     } else {
342       if (log)
343         log->Printf("Unable to resolve the _rtld_debug structure");
344     }
345   }
346
347   dyld_instance->RefreshModules();
348
349   // Return true to stop the target, false to just let the target run.
350   return dyld_instance->GetStopWhenImagesChange();
351 }
352
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));
357
358   if (!m_rendezvous.Resolve())
359     return;
360
361   HexagonDYLDRendezvous::iterator I;
362   HexagonDYLDRendezvous::iterator E;
363
364   ModuleList &loaded_modules = m_process->GetTarget().GetImages();
365
366   if (m_rendezvous.ModulesDidLoad()) {
367     ModuleList new_modules;
368
369     E = m_rendezvous.loaded_end();
370     for (I = m_rendezvous.loaded_begin(); I != E; ++I) {
371       FileSpec file(I->path, true);
372       ModuleSP module_sp =
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);
377       }
378
379       if (log) {
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());
383         else
384           log->Printf("LLDB successfully loaded '%s'", I->path.c_str());
385       }
386     }
387     m_process->GetTarget().ModulesDidLoad(new_modules);
388   }
389
390   if (m_rendezvous.ModulesDidUnload()) {
391     ModuleList old_modules;
392
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);
398
399       if (module_sp.get()) {
400         old_modules.Append(module_sp);
401         UnloadSections(module_sp);
402       }
403
404       if (log)
405         log->Printf("Target is unloading '%s'", I->path.c_str());
406     }
407     loaded_modules.Remove(old_modules);
408     m_process->GetTarget().ModulesDidUnload(old_modules, false);
409   }
410 }
411
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
414 //              unwinding.
415 ThreadPlanSP
416 DynamicLoaderHexagonDYLD::GetStepThroughTrampolinePlan(Thread &thread,
417                                                        bool stop) {
418   ThreadPlanSP thread_plan_sp;
419
420   StackFrame *frame = thread.GetStackFrameAtIndex(0).get();
421   const SymbolContext &context = frame->GetSymbolContext(eSymbolContextSymbol);
422   Symbol *sym = context.symbol;
423
424   if (sym == NULL || !sym->IsTrampoline())
425     return thread_plan_sp;
426
427   const ConstString sym_name = sym->GetMangled().GetName(
428       lldb::eLanguageTypeUnknown, Mangled::ePreferMangled);
429   if (!sym_name)
430     return thread_plan_sp;
431
432   SymbolContextList target_symbols;
433   Target &target = thread.GetProcess()->GetTarget();
434   const ModuleList &images = target.GetImages();
435
436   images.FindSymbolsWithNameAndType(sym_name, eSymbolTypeCode, target_symbols);
437   size_t num_targets = target_symbols.GetSize();
438   if (!num_targets)
439     return thread_plan_sp;
440
441   typedef std::vector<lldb::addr_t> AddressVector;
442   AddressVector addrs;
443   for (size_t i = 0; i < num_targets; ++i) {
444     SymbolContext context;
445     AddressRange range;
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);
451     }
452   }
453
454   if (addrs.size() > 0) {
455     AddressVector::iterator start = addrs.begin();
456     AddressVector::iterator end = addrs.end();
457
458     std::sort(start, end);
459     addrs.erase(std::unique(start, end), end);
460     thread_plan_sp.reset(new ThreadPlanRunToAddress(thread, addrs, stop));
461   }
462
463   return thread_plan_sp;
464 }
465
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;
472
473   if (!m_rendezvous.Resolve()) {
474     Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_DYNAMIC_LOADER));
475     if (log)
476       log->Printf(
477           "DynamicLoaderHexagonDYLD::%s unable to resolve rendezvous address",
478           __FUNCTION__);
479     return;
480   }
481
482   // The rendezvous class doesn't enumerate the main module, so track that
483   // ourselves here.
484   ModuleSP executable = GetTargetExecutable();
485   m_loaded_modules[executable] = m_rendezvous.GetLinkMapAddress();
486
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);
490     ModuleSP module_sp =
491         LoadModuleAtAddress(file, I->link_addr, I->base_addr, true);
492     if (module_sp.get()) {
493       module_list.Append(module_sp);
494     } else {
495       Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_DYNAMIC_LOADER));
496       if (log)
497         log->Printf("DynamicLoaderHexagonDYLD::%s failed loading module %s at "
498                     "0x%" PRIx64,
499                     __FUNCTION__, module_path, I->base_addr);
500     }
501   }
502
503   m_process->GetTarget().ModulesDidLoad(module_list);
504 }
505
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
510   //
511   // send:    $qOffsets#4b
512   // get:     Text=0;Data=0;Bss=0
513   //
514   // Currently qOffsets is not supported by pluginProcessGDBRemote
515   //
516   return 0;
517 }
518
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.
521 //
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();
541   }
542   // No idea so back out
543   return LLDB_INVALID_ADDRESS;
544 }
545
546 const SectionList *DynamicLoaderHexagonDYLD::GetSectionListFromModule(
547     const ModuleSP module) const {
548   SectionList *sections = nullptr;
549   if (module.get()) {
550     ObjectFile *obj_file = module->GetObjectFile();
551     if (obj_file) {
552       sections = obj_file->GetSectionList();
553     }
554   }
555   return sections;
556 }
557
558 static int ReadInt(Process *process, addr_t addr) {
559   Status error;
560   int value = (int)process->ReadUnsignedIntegerFromMemory(
561       addr, sizeof(uint32_t), 0, error);
562   if (error.Fail())
563     return -1;
564   else
565     return value;
566 }
567
568 lldb::addr_t
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;
575
576   addr_t link_map = it->second;
577   if (link_map == LLDB_INVALID_ADDRESS)
578     return LLDB_INVALID_ADDRESS;
579
580   const HexagonDYLDRendezvous::ThreadInfo &metadata =
581       m_rendezvous.GetThreadInfo();
582   if (!metadata.valid)
583     return LLDB_INVALID_ADDRESS;
584
585   // Get the thread pointer.
586   addr_t tp = thread->GetThreadPointer();
587   if (tp == LLDB_INVALID_ADDRESS)
588     return LLDB_INVALID_ADDRESS;
589
590   // Find the module's modid.
591   int modid = ReadInt(m_process, link_map + metadata.modid_offset);
592   if (modid == -1)
593     return LLDB_INVALID_ADDRESS;
594
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;
600
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);
604
605   Module *mod = module.get();
606   Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_DYNAMIC_LOADER));
607   if (log)
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,
612                 tls_block);
613
614   if (tls_block == LLDB_INVALID_ADDRESS)
615     return LLDB_INVALID_ADDRESS;
616   else
617     return tls_block + tls_file_addr;
618 }