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     entry_break->SetBreakpointKind("shared-library-event");
206 }
207 
208 // The runtime linker has run and initialized the rendezvous structure once the
209 // process has hit its entry point.  When we hit the corresponding breakpoint we
210 // interrogate the rendezvous structure to get the load addresses of all
211 // dependent modules for the process.  Similarly, we can discover the runtime
212 // linker function and setup a breakpoint to notify us of any dynamically loaded
213 // modules (via dlopen).
214 bool
215 DynamicLoaderPOSIXDYLD::EntryBreakpointHit(void *baton,
216                                            StoppointCallbackContext *context,
217                                            user_id_t break_id,
218                                            user_id_t break_loc_id)
219 {
220     DynamicLoaderPOSIXDYLD* dyld_instance;
221 
222     dyld_instance = static_cast<DynamicLoaderPOSIXDYLD*>(baton);
223     dyld_instance->LoadAllCurrentModules();
224     dyld_instance->SetRendezvousBreakpoint();
225     return false; // Continue running.
226 }
227 
228 void
229 DynamicLoaderPOSIXDYLD::SetRendezvousBreakpoint()
230 {
231     Breakpoint *dyld_break;
232     addr_t break_addr;
233 
234     break_addr = m_rendezvous.GetBreakAddress();
235     dyld_break = m_process->GetTarget().CreateBreakpoint(break_addr, true).get();
236     dyld_break->SetCallback(RendezvousBreakpointHit, this, true);
237     dyld_break->SetBreakpointKind ("shared-library-event");
238 }
239 
240 bool
241 DynamicLoaderPOSIXDYLD::RendezvousBreakpointHit(void *baton,
242                                                 StoppointCallbackContext *context,
243                                                 user_id_t break_id,
244                                                 user_id_t break_loc_id)
245 {
246     DynamicLoaderPOSIXDYLD* dyld_instance;
247 
248     dyld_instance = static_cast<DynamicLoaderPOSIXDYLD*>(baton);
249     dyld_instance->RefreshModules();
250 
251     // Return true to stop the target, false to just let the target run.
252     return dyld_instance->GetStopWhenImagesChange();
253 }
254 
255 void
256 DynamicLoaderPOSIXDYLD::RefreshModules()
257 {
258     if (!m_rendezvous.Resolve())
259         return;
260 
261     DYLDRendezvous::iterator I;
262     DYLDRendezvous::iterator E;
263 
264     ModuleList &loaded_modules = m_process->GetTarget().GetImages();
265 
266     if (m_rendezvous.ModulesDidLoad())
267     {
268         ModuleList new_modules;
269 
270         E = m_rendezvous.loaded_end();
271         for (I = m_rendezvous.loaded_begin(); I != E; ++I)
272         {
273             FileSpec file(I->path.c_str(), true);
274             ModuleSP module_sp = LoadModuleAtAddress(file, I->base_addr);
275             if (module_sp.get())
276                 loaded_modules.AppendIfNeeded(module_sp);
277         }
278     }
279 
280     if (m_rendezvous.ModulesDidUnload())
281     {
282         ModuleList old_modules;
283 
284         E = m_rendezvous.unloaded_end();
285         for (I = m_rendezvous.unloaded_begin(); I != E; ++I)
286         {
287             FileSpec file(I->path.c_str(), true);
288             ModuleSpec module_spec (file);
289             ModuleSP module_sp =
290                 loaded_modules.FindFirstModule (module_spec);
291             if (module_sp.get())
292                 old_modules.Append(module_sp);
293         }
294         loaded_modules.Remove(old_modules);
295     }
296 }
297 
298 ThreadPlanSP
299 DynamicLoaderPOSIXDYLD::GetStepThroughTrampolinePlan(Thread &thread, bool stop)
300 {
301     ThreadPlanSP thread_plan_sp;
302 
303     StackFrame *frame = thread.GetStackFrameAtIndex(0).get();
304     const SymbolContext &context = frame->GetSymbolContext(eSymbolContextSymbol);
305     Symbol *sym = context.symbol;
306 
307     if (sym == NULL || !sym->IsTrampoline())
308         return thread_plan_sp;
309 
310     const ConstString &sym_name = sym->GetMangled().GetName(Mangled::ePreferMangled);
311     if (!sym_name)
312         return thread_plan_sp;
313 
314     SymbolContextList target_symbols;
315     Target &target = thread.GetProcess()->GetTarget();
316     const ModuleList &images = target.GetImages();
317 
318     images.FindSymbolsWithNameAndType(sym_name, eSymbolTypeCode, target_symbols);
319     size_t num_targets = target_symbols.GetSize();
320     if (!num_targets)
321         return thread_plan_sp;
322 
323     typedef std::vector<lldb::addr_t> AddressVector;
324     AddressVector addrs;
325     for (size_t i = 0; i < num_targets; ++i)
326     {
327         SymbolContext context;
328         AddressRange range;
329         if (target_symbols.GetContextAtIndex(i, context))
330         {
331             context.GetAddressRange(eSymbolContextEverything, 0, false, range);
332             lldb::addr_t addr = range.GetBaseAddress().GetLoadAddress(&target);
333             if (addr != LLDB_INVALID_ADDRESS)
334                 addrs.push_back(addr);
335         }
336     }
337 
338     if (addrs.size() > 0)
339     {
340         AddressVector::iterator start = addrs.begin();
341         AddressVector::iterator end = addrs.end();
342 
343         std::sort(start, end);
344         addrs.erase(std::unique(start, end), end);
345         thread_plan_sp.reset(new ThreadPlanRunToAddress(thread, addrs, stop));
346     }
347 
348     return thread_plan_sp;
349 }
350 
351 void
352 DynamicLoaderPOSIXDYLD::LoadAllCurrentModules()
353 {
354     DYLDRendezvous::iterator I;
355     DYLDRendezvous::iterator E;
356     ModuleList module_list;
357 
358     if (!m_rendezvous.Resolve())
359         return;
360 
361     for (I = m_rendezvous.begin(), E = m_rendezvous.end(); I != E; ++I)
362     {
363         FileSpec file(I->path.c_str(), false);
364         ModuleSP module_sp = LoadModuleAtAddress(file, I->base_addr);
365         if (module_sp.get())
366             module_list.Append(module_sp);
367     }
368 
369     m_process->GetTarget().ModulesDidLoad(module_list);
370 }
371 
372 ModuleSP
373 DynamicLoaderPOSIXDYLD::LoadModuleAtAddress(const FileSpec &file, addr_t base_addr)
374 {
375     Target &target = m_process->GetTarget();
376     ModuleList &modules = target.GetImages();
377     ModuleSP module_sp;
378 
379     ModuleSpec module_spec (file, target.GetArchitecture());
380     if ((module_sp = modules.FindFirstModule (module_spec)))
381     {
382         UpdateLoadedSections(module_sp, base_addr);
383     }
384     else if ((module_sp = target.GetSharedModule(module_spec)))
385     {
386         UpdateLoadedSections(module_sp, base_addr);
387         modules.Append(module_sp);
388     }
389 
390     return module_sp;
391 }
392 
393 addr_t
394 DynamicLoaderPOSIXDYLD::ComputeLoadOffset()
395 {
396     addr_t virt_entry;
397 
398     if (m_load_offset != LLDB_INVALID_ADDRESS)
399         return m_load_offset;
400 
401     if ((virt_entry = GetEntryPoint()) == LLDB_INVALID_ADDRESS)
402         return LLDB_INVALID_ADDRESS;
403 
404     ModuleSP module = m_process->GetTarget().GetExecutableModule();
405     ObjectFile *exe = module->GetObjectFile();
406     Address file_entry = exe->GetEntryPointAddress();
407 
408     if (!file_entry.IsValid())
409         return LLDB_INVALID_ADDRESS;
410 
411     m_load_offset = virt_entry - file_entry.GetFileAddress();
412     return m_load_offset;
413 }
414 
415 addr_t
416 DynamicLoaderPOSIXDYLD::GetEntryPoint()
417 {
418     if (m_entry_point != LLDB_INVALID_ADDRESS)
419         return m_entry_point;
420 
421     if (m_auxv.get() == NULL)
422         return LLDB_INVALID_ADDRESS;
423 
424     AuxVector::iterator I = m_auxv->FindEntry(AuxVector::AT_ENTRY);
425 
426     if (I == m_auxv->end())
427         return LLDB_INVALID_ADDRESS;
428 
429     m_entry_point = static_cast<addr_t>(I->value);
430     return m_entry_point;
431 }
432