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                 loaded_modules.AppendIfNeeded(module_sp);
275         }
276     }
277 
278     if (m_rendezvous.ModulesDidUnload())
279     {
280         ModuleList old_modules;
281 
282         E = m_rendezvous.unloaded_end();
283         for (I = m_rendezvous.unloaded_begin(); I != E; ++I)
284         {
285             FileSpec file(I->path.c_str(), true);
286             ModuleSpec module_spec (file);
287             ModuleSP module_sp =
288                 loaded_modules.FindFirstModule (module_spec);
289             if (module_sp.get())
290                 old_modules.Append(module_sp);
291         }
292         loaded_modules.Remove(old_modules);
293     }
294 }
295 
296 ThreadPlanSP
297 DynamicLoaderPOSIXDYLD::GetStepThroughTrampolinePlan(Thread &thread, bool stop)
298 {
299     ThreadPlanSP thread_plan_sp;
300 
301     StackFrame *frame = thread.GetStackFrameAtIndex(0).get();
302     const SymbolContext &context = frame->GetSymbolContext(eSymbolContextSymbol);
303     Symbol *sym = context.symbol;
304 
305     if (sym == NULL || !sym->IsTrampoline())
306         return thread_plan_sp;
307 
308     const ConstString &sym_name = sym->GetMangled().GetName(Mangled::ePreferMangled);
309     if (!sym_name)
310         return thread_plan_sp;
311 
312     SymbolContextList target_symbols;
313     Target &target = thread.GetProcess()->GetTarget();
314     const ModuleList &images = target.GetImages();
315 
316     images.FindSymbolsWithNameAndType(sym_name, eSymbolTypeCode, target_symbols);
317     size_t num_targets = target_symbols.GetSize();
318     if (!num_targets)
319         return thread_plan_sp;
320 
321     typedef std::vector<lldb::addr_t> AddressVector;
322     AddressVector addrs;
323     for (size_t i = 0; i < num_targets; ++i)
324     {
325         SymbolContext context;
326         AddressRange range;
327         if (target_symbols.GetContextAtIndex(i, context))
328         {
329             context.GetAddressRange(eSymbolContextEverything, 0, false, range);
330             lldb::addr_t addr = range.GetBaseAddress().GetLoadAddress(&target);
331             if (addr != LLDB_INVALID_ADDRESS)
332                 addrs.push_back(addr);
333         }
334     }
335 
336     if (addrs.size() > 0)
337     {
338         AddressVector::iterator start = addrs.begin();
339         AddressVector::iterator end = addrs.end();
340 
341         std::sort(start, end);
342         addrs.erase(std::unique(start, end), end);
343         thread_plan_sp.reset(new ThreadPlanRunToAddress(thread, addrs, stop));
344     }
345 
346     return thread_plan_sp;
347 }
348 
349 void
350 DynamicLoaderPOSIXDYLD::LoadAllCurrentModules()
351 {
352     DYLDRendezvous::iterator I;
353     DYLDRendezvous::iterator E;
354     ModuleList module_list;
355 
356     if (!m_rendezvous.Resolve())
357         return;
358 
359     for (I = m_rendezvous.begin(), E = m_rendezvous.end(); I != E; ++I)
360     {
361         FileSpec file(I->path.c_str(), false);
362         ModuleSP module_sp = LoadModuleAtAddress(file, I->base_addr);
363         if (module_sp.get())
364             module_list.Append(module_sp);
365     }
366 
367     m_process->GetTarget().ModulesDidLoad(module_list);
368 }
369 
370 ModuleSP
371 DynamicLoaderPOSIXDYLD::LoadModuleAtAddress(const FileSpec &file, addr_t base_addr)
372 {
373     Target &target = m_process->GetTarget();
374     ModuleList &modules = target.GetImages();
375     ModuleSP module_sp;
376 
377     ModuleSpec module_spec (file, target.GetArchitecture());
378     if ((module_sp = modules.FindFirstModule (module_spec)))
379     {
380         UpdateLoadedSections(module_sp, base_addr);
381     }
382     else if ((module_sp = target.GetSharedModule(module_spec)))
383     {
384         UpdateLoadedSections(module_sp, base_addr);
385         modules.Append(module_sp);
386     }
387 
388     return module_sp;
389 }
390 
391 addr_t
392 DynamicLoaderPOSIXDYLD::ComputeLoadOffset()
393 {
394     addr_t virt_entry;
395 
396     if (m_load_offset != LLDB_INVALID_ADDRESS)
397         return m_load_offset;
398 
399     if ((virt_entry = GetEntryPoint()) == LLDB_INVALID_ADDRESS)
400         return LLDB_INVALID_ADDRESS;
401 
402     ModuleSP module = m_process->GetTarget().GetExecutableModule();
403     ObjectFile *exe = module->GetObjectFile();
404     Address file_entry = exe->GetEntryPointAddress();
405 
406     if (!file_entry.IsValid())
407         return LLDB_INVALID_ADDRESS;
408 
409     m_load_offset = virt_entry - file_entry.GetFileAddress();
410     return m_load_offset;
411 }
412 
413 addr_t
414 DynamicLoaderPOSIXDYLD::GetEntryPoint()
415 {
416     if (m_entry_point != LLDB_INVALID_ADDRESS)
417         return m_entry_point;
418 
419     if (m_auxv.get() == NULL)
420         return LLDB_INVALID_ADDRESS;
421 
422     AuxVector::iterator I = m_auxv->FindEntry(AuxVector::AT_ENTRY);
423 
424     if (I == m_auxv->end())
425         return LLDB_INVALID_ADDRESS;
426 
427     m_entry_point = static_cast<addr_t>(I->value);
428     return m_entry_point;
429 }
430