1 //===-- DynamicLoaderPOSIX.h ------------------------------------*- 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/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 
24 #include "AuxVector.h"
25 #include "DynamicLoaderPOSIXDYLD.h"
26 
27 using namespace lldb;
28 using namespace lldb_private;
29 
30 void
31 DynamicLoaderPOSIXDYLD::Initialize()
32 {
33     PluginManager::RegisterPlugin(GetPluginNameStatic(),
34                                   GetPluginDescriptionStatic(),
35                                   CreateInstance);
36 }
37 
38 void
39 DynamicLoaderPOSIXDYLD::Terminate()
40 {
41 }
42 
43 const char *
44 DynamicLoaderPOSIXDYLD::GetPluginName()
45 {
46     return "DynamicLoaderPOSIXDYLD";
47 }
48 
49 const char *
50 DynamicLoaderPOSIXDYLD::GetShortPluginName()
51 {
52     return "linux-dyld";
53 }
54 
55 const char *
56 DynamicLoaderPOSIXDYLD::GetPluginNameStatic()
57 {
58     return "dynamic-loader.linux-dyld";
59 }
60 
61 const char *
62 DynamicLoaderPOSIXDYLD::GetPluginDescriptionStatic()
63 {
64     return "Dynamic loader plug-in that watches for shared library "
65            "loads/unloads in POSIX processes.";
66 }
67 
68 void
69 DynamicLoaderPOSIXDYLD::GetPluginCommandHelp(const char *command, Stream *strm)
70 {
71 }
72 
73 uint32_t
74 DynamicLoaderPOSIXDYLD::GetPluginVersion()
75 {
76     return 1;
77 }
78 
79 DynamicLoader *
80 DynamicLoaderPOSIXDYLD::CreateInstance(Process *process, bool force)
81 {
82     bool create = force;
83     if (!create)
84     {
85         const llvm::Triple &triple_ref = process->GetTarget().GetArchitecture().GetTriple();
86         if (triple_ref.getOS() == llvm::Triple::Linux ||
87             triple_ref.getOS() == llvm::Triple::FreeBSD)
88             create = true;
89     }
90 
91     if (create)
92         return new DynamicLoaderPOSIXDYLD (process);
93     return NULL;
94 }
95 
96 DynamicLoaderPOSIXDYLD::DynamicLoaderPOSIXDYLD(Process *process)
97     : DynamicLoader(process),
98       m_rendezvous(process),
99       m_load_offset(LLDB_INVALID_ADDRESS),
100       m_entry_point(LLDB_INVALID_ADDRESS),
101       m_auxv(NULL)
102 {
103 }
104 
105 DynamicLoaderPOSIXDYLD::~DynamicLoaderPOSIXDYLD()
106 {
107 }
108 
109 void
110 DynamicLoaderPOSIXDYLD::DidAttach()
111 {
112     ModuleSP executable;
113     addr_t load_offset;
114 
115     m_auxv.reset(new AuxVector(m_process));
116 
117     executable = m_process->GetTarget().GetExecutableModule();
118     load_offset = ComputeLoadOffset();
119 
120     if (executable.get() && load_offset != LLDB_INVALID_ADDRESS)
121     {
122         ModuleList module_list;
123         module_list.Append(executable);
124         UpdateLoadedSections(executable, load_offset);
125         LoadAllCurrentModules();
126         m_process->GetTarget().ModulesDidLoad(module_list);
127     }
128 }
129 
130 void
131 DynamicLoaderPOSIXDYLD::DidLaunch()
132 {
133     ModuleSP executable;
134     addr_t load_offset;
135 
136     m_auxv.reset(new AuxVector(m_process));
137 
138     executable = m_process->GetTarget().GetExecutableModule();
139     load_offset = ComputeLoadOffset();
140 
141     if (executable.get() && load_offset != LLDB_INVALID_ADDRESS)
142     {
143         ModuleList module_list;
144         module_list.Append(executable);
145         UpdateLoadedSections(executable, load_offset);
146         ProbeEntry();
147         m_process->GetTarget().ModulesDidLoad(module_list);
148     }
149 }
150 
151 Error
152 DynamicLoaderPOSIXDYLD::ExecutePluginCommand(Args &command, Stream *strm)
153 {
154     return Error();
155 }
156 
157 Log *
158 DynamicLoaderPOSIXDYLD::EnablePluginLogging(Stream *strm, Args &command)
159 {
160     return NULL;
161 }
162 
163 Error
164 DynamicLoaderPOSIXDYLD::CanLoadImage()
165 {
166     return Error();
167 }
168 
169 void
170 DynamicLoaderPOSIXDYLD::UpdateLoadedSections(ModuleSP module, addr_t base_addr)
171 {
172     ObjectFile *obj_file = module->GetObjectFile();
173     SectionList *sections = obj_file->GetSectionList();
174     SectionLoadList &load_list = m_process->GetTarget().GetSectionLoadList();
175     const size_t num_sections = sections->GetSize();
176 
177     for (unsigned i = 0; i < num_sections; ++i)
178     {
179         SectionSP section_sp (sections->GetSectionAtIndex(i));
180         lldb::addr_t new_load_addr = section_sp->GetFileAddress() + base_addr;
181         lldb::addr_t old_load_addr = load_list.GetSectionLoadAddress(section_sp);
182 
183         // If the file address of the section is zero then this is not an
184         // allocatable/loadable section (property of ELF sh_addr).  Skip it.
185         if (new_load_addr == base_addr)
186             continue;
187 
188         if (old_load_addr == LLDB_INVALID_ADDRESS ||
189             old_load_addr != new_load_addr)
190             load_list.SetSectionLoadAddress(section_sp, new_load_addr);
191     }
192 }
193 
194 void
195 DynamicLoaderPOSIXDYLD::ProbeEntry()
196 {
197     Breakpoint *entry_break;
198     addr_t entry;
199 
200     if ((entry = GetEntryPoint()) == LLDB_INVALID_ADDRESS)
201         return;
202 
203     entry_break = m_process->GetTarget().CreateBreakpoint(entry, true).get();
204     entry_break->SetCallback(EntryBreakpointHit, this, true);
205 }
206 
207 // The runtime linker has run and initialized the rendezvous structure once the
208 // process has hit its entry point.  When we hit the corresponding breakpoint we
209 // interrogate the rendezvous structure to get the load addresses of all
210 // dependent modules for the process.  Similarly, we can discover the runtime
211 // linker function and setup a breakpoint to notify us of any dynamically loaded
212 // modules (via dlopen).
213 bool
214 DynamicLoaderPOSIXDYLD::EntryBreakpointHit(void *baton,
215                                            StoppointCallbackContext *context,
216                                            user_id_t break_id,
217                                            user_id_t break_loc_id)
218 {
219     DynamicLoaderPOSIXDYLD* dyld_instance;
220 
221     dyld_instance = static_cast<DynamicLoaderPOSIXDYLD*>(baton);
222     dyld_instance->LoadAllCurrentModules();
223     dyld_instance->SetRendezvousBreakpoint();
224     return false; // Continue running.
225 }
226 
227 void
228 DynamicLoaderPOSIXDYLD::SetRendezvousBreakpoint()
229 {
230     Breakpoint *dyld_break;
231     addr_t break_addr;
232 
233     break_addr = m_rendezvous.GetBreakAddress();
234     dyld_break = m_process->GetTarget().CreateBreakpoint(break_addr, true).get();
235     dyld_break->SetCallback(RendezvousBreakpointHit, this, true);
236 }
237 
238 bool
239 DynamicLoaderPOSIXDYLD::RendezvousBreakpointHit(void *baton,
240                                                 StoppointCallbackContext *context,
241                                                 user_id_t break_id,
242                                                 user_id_t break_loc_id)
243 {
244     DynamicLoaderPOSIXDYLD* dyld_instance;
245 
246     dyld_instance = static_cast<DynamicLoaderPOSIXDYLD*>(baton);
247     dyld_instance->RefreshModules();
248 
249     // Return true to stop the target, false to just let the target run.
250     return dyld_instance->GetStopWhenImagesChange();
251 }
252 
253 void
254 DynamicLoaderPOSIXDYLD::RefreshModules()
255 {
256     if (!m_rendezvous.Resolve())
257         return;
258 
259     DYLDRendezvous::iterator I;
260     DYLDRendezvous::iterator E;
261 
262     ModuleList &loaded_modules = m_process->GetTarget().GetImages();
263 
264     if (m_rendezvous.ModulesDidLoad())
265     {
266         ModuleList new_modules;
267 
268         E = m_rendezvous.loaded_end();
269         for (I = m_rendezvous.loaded_begin(); I != E; ++I)
270         {
271             FileSpec file(I->path.c_str(), true);
272             ModuleSP module_sp = LoadModuleAtAddress(file, I->base_addr);
273             if (module_sp.get())
274                 new_modules.Append(module_sp);
275         }
276         m_process->GetTarget().ModulesDidLoad(new_modules);
277     }
278 
279     if (m_rendezvous.ModulesDidUnload())
280     {
281         ModuleList old_modules;
282 
283         E = m_rendezvous.unloaded_end();
284         for (I = m_rendezvous.unloaded_begin(); I != E; ++I)
285         {
286             FileSpec file(I->path.c_str(), true);
287             ModuleSpec module_spec (file);
288             ModuleSP module_sp =
289                 loaded_modules.FindFirstModule (module_spec);
290             if (module_sp.get())
291                 old_modules.Append(module_sp);
292         }
293         m_process->GetTarget().ModulesDidUnload(old_modules);
294     }
295 }
296 
297 ThreadPlanSP
298 DynamicLoaderPOSIXDYLD::GetStepThroughTrampolinePlan(Thread &thread, bool stop)
299 {
300     ThreadPlanSP thread_plan_sp;
301 
302     StackFrame *frame = thread.GetStackFrameAtIndex(0).get();
303     const SymbolContext &context = frame->GetSymbolContext(eSymbolContextSymbol);
304     Symbol *sym = context.symbol;
305 
306     if (sym == NULL || !sym->IsTrampoline())
307         return thread_plan_sp;
308 
309     const ConstString &sym_name = sym->GetMangled().GetName(Mangled::ePreferMangled);
310     if (!sym_name)
311         return thread_plan_sp;
312 
313     SymbolContextList target_symbols;
314     Target &target = thread.GetProcess()->GetTarget();
315     ModuleList &images = target.GetImages();
316 
317     images.FindSymbolsWithNameAndType(sym_name, eSymbolTypeCode, target_symbols);
318     size_t num_targets = target_symbols.GetSize();
319     if (!num_targets)
320         return thread_plan_sp;
321 
322     typedef std::vector<lldb::addr_t> AddressVector;
323     AddressVector addrs;
324     for (size_t i = 0; i < num_targets; ++i)
325     {
326         SymbolContext context;
327         AddressRange range;
328         if (target_symbols.GetContextAtIndex(i, context))
329         {
330             context.GetAddressRange(eSymbolContextEverything, 0, false, range);
331             lldb::addr_t addr = range.GetBaseAddress().GetLoadAddress(&target);
332             if (addr != LLDB_INVALID_ADDRESS)
333                 addrs.push_back(addr);
334         }
335     }
336 
337     if (addrs.size() > 0)
338     {
339         AddressVector::iterator start = addrs.begin();
340         AddressVector::iterator end = addrs.end();
341 
342         std::sort(start, end);
343         addrs.erase(std::unique(start, end), end);
344         thread_plan_sp.reset(new ThreadPlanRunToAddress(thread, addrs, stop));
345     }
346 
347     return thread_plan_sp;
348 }
349 
350 void
351 DynamicLoaderPOSIXDYLD::LoadAllCurrentModules()
352 {
353     DYLDRendezvous::iterator I;
354     DYLDRendezvous::iterator E;
355     ModuleList module_list;
356 
357     if (!m_rendezvous.Resolve())
358         return;
359 
360     for (I = m_rendezvous.begin(), E = m_rendezvous.end(); I != E; ++I)
361     {
362         FileSpec file(I->path.c_str(), false);
363         ModuleSP module_sp = LoadModuleAtAddress(file, I->base_addr);
364         if (module_sp.get())
365             module_list.Append(module_sp);
366     }
367 
368     m_process->GetTarget().ModulesDidLoad(module_list);
369 }
370 
371 ModuleSP
372 DynamicLoaderPOSIXDYLD::LoadModuleAtAddress(const FileSpec &file, addr_t base_addr)
373 {
374     Target &target = m_process->GetTarget();
375     ModuleList &modules = target.GetImages();
376     ModuleSP module_sp;
377 
378     ModuleSpec module_spec (file, target.GetArchitecture());
379     if ((module_sp = modules.FindFirstModule (module_spec)))
380     {
381         UpdateLoadedSections(module_sp, base_addr);
382     }
383     else if ((module_sp = target.GetSharedModule(module_spec)))
384     {
385         UpdateLoadedSections(module_sp, base_addr);
386         modules.Append(module_sp);
387     }
388 
389     return module_sp;
390 }
391 
392 addr_t
393 DynamicLoaderPOSIXDYLD::ComputeLoadOffset()
394 {
395     addr_t virt_entry;
396 
397     if (m_load_offset != LLDB_INVALID_ADDRESS)
398         return m_load_offset;
399 
400     if ((virt_entry = GetEntryPoint()) == LLDB_INVALID_ADDRESS)
401         return LLDB_INVALID_ADDRESS;
402 
403     ModuleSP module = m_process->GetTarget().GetExecutableModule();
404     ObjectFile *exe = module->GetObjectFile();
405     Address file_entry = exe->GetEntryPointAddress();
406 
407     if (!file_entry.IsValid())
408         return LLDB_INVALID_ADDRESS;
409 
410     m_load_offset = virt_entry - file_entry.GetFileAddress();
411     return m_load_offset;
412 }
413 
414 addr_t
415 DynamicLoaderPOSIXDYLD::GetEntryPoint()
416 {
417     if (m_entry_point != LLDB_INVALID_ADDRESS)
418         return m_entry_point;
419 
420     if (m_auxv.get() == NULL)
421         return LLDB_INVALID_ADDRESS;
422 
423     AuxVector::iterator I = m_auxv->FindEntry(AuxVector::AT_ENTRY);
424 
425     if (I == m_auxv->end())
426         return LLDB_INVALID_ADDRESS;
427 
428     m_entry_point = static_cast<addr_t>(I->value);
429     return m_entry_point;
430 }
431