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 #include "lldb/Breakpoint/BreakpointLocation.h"
24 
25 #include "AuxVector.h"
26 #include "DynamicLoaderPOSIXDYLD.h"
27 
28 using namespace lldb;
29 using namespace lldb_private;
30 
31 void
32 DynamicLoaderPOSIXDYLD::Initialize()
33 {
34     PluginManager::RegisterPlugin(GetPluginNameStatic(),
35                                   GetPluginDescriptionStatic(),
36                                   CreateInstance);
37 }
38 
39 void
40 DynamicLoaderPOSIXDYLD::Terminate()
41 {
42 }
43 
44 lldb_private::ConstString
45 DynamicLoaderPOSIXDYLD::GetPluginName()
46 {
47     return GetPluginNameStatic();
48 }
49 
50 lldb_private::ConstString
51 DynamicLoaderPOSIXDYLD::GetPluginNameStatic()
52 {
53     static ConstString g_name("linux-dyld");
54     return g_name;
55 }
56 
57 const char *
58 DynamicLoaderPOSIXDYLD::GetPluginDescriptionStatic()
59 {
60     return "Dynamic loader plug-in that watches for shared library "
61            "loads/unloads in POSIX processes.";
62 }
63 
64 void
65 DynamicLoaderPOSIXDYLD::GetPluginCommandHelp(const char *command, Stream *strm)
66 {
67 }
68 
69 uint32_t
70 DynamicLoaderPOSIXDYLD::GetPluginVersion()
71 {
72     return 1;
73 }
74 
75 DynamicLoader *
76 DynamicLoaderPOSIXDYLD::CreateInstance(Process *process, bool force)
77 {
78     bool create = force;
79     if (!create)
80     {
81         const llvm::Triple &triple_ref = process->GetTarget().GetArchitecture().GetTriple();
82         if (triple_ref.getOS() == llvm::Triple::Linux ||
83             triple_ref.getOS() == llvm::Triple::FreeBSD)
84             create = true;
85     }
86 
87     if (create)
88         return new DynamicLoaderPOSIXDYLD (process);
89     return NULL;
90 }
91 
92 DynamicLoaderPOSIXDYLD::DynamicLoaderPOSIXDYLD(Process *process)
93     : DynamicLoader(process),
94       m_rendezvous(process),
95       m_load_offset(LLDB_INVALID_ADDRESS),
96       m_entry_point(LLDB_INVALID_ADDRESS),
97       m_auxv(),
98       m_dyld_bid(LLDB_INVALID_BREAK_ID)
99 {
100 }
101 
102 DynamicLoaderPOSIXDYLD::~DynamicLoaderPOSIXDYLD()
103 {
104     if (m_dyld_bid != LLDB_INVALID_BREAK_ID)
105     {
106         m_process->GetTarget().RemoveBreakpointByID (m_dyld_bid);
107         m_dyld_bid = LLDB_INVALID_BREAK_ID;
108     }
109 }
110 
111 void
112 DynamicLoaderPOSIXDYLD::DidAttach()
113 {
114     Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_DYNAMIC_LOADER));
115     ModuleSP executable_sp;
116     addr_t load_offset;
117 
118     if (log)
119         log->Printf ("DynamicLoaderPOSIXDYLD::%s() pid %" PRIu64, __FUNCTION__, m_process ? m_process->GetID () : LLDB_INVALID_PROCESS_ID);
120 
121     m_auxv.reset(new AuxVector(m_process));
122     if (log)
123         log->Printf ("DynamicLoaderPOSIXDYLD::%s pid %" PRIu64 " reloaded auxv data", __FUNCTION__, m_process ? m_process->GetID () : LLDB_INVALID_PROCESS_ID);
124 
125     executable_sp = GetTargetExecutable();
126     load_offset = ComputeLoadOffset();
127     if (log)
128         log->Printf ("DynamicLoaderPOSIXDYLD::%s pid %" PRIu64 " executable '%s', load_offset 0x%" PRIx64, __FUNCTION__, m_process ? m_process->GetID () : LLDB_INVALID_PROCESS_ID, executable_sp ? executable_sp->GetFileSpec().GetPath().c_str () : "<null executable>", load_offset);
129 
130 
131     if (executable_sp && load_offset != LLDB_INVALID_ADDRESS)
132     {
133         ModuleList module_list;
134 
135         module_list.Append(executable_sp);
136         if (log)
137             log->Printf ("DynamicLoaderPOSIXDYLD::%s pid %" PRIu64 " added executable '%s' to module load list",
138                          __FUNCTION__,
139                          m_process ? m_process->GetID () : LLDB_INVALID_PROCESS_ID,
140                          executable_sp->GetFileSpec().GetPath().c_str ());
141 
142         UpdateLoadedSections(executable_sp, LLDB_INVALID_ADDRESS, load_offset);
143 
144         // When attaching to a target, there are two possible states:
145         // (1) We already crossed the entry point and therefore the rendezvous
146         //     structure is ready to be used and we can load the list of modules
147         //     and place the rendezvous breakpoint.
148         // (2) We didn't cross the entry point yet, so these structures are not
149         //     ready; we should behave as if we just launched the target and
150         //     call ProbeEntry(). This will place a breakpoint on the entry
151         //     point which itself will be hit after the rendezvous structure is
152         //     set up and will perform actions described in (1).
153         if (m_rendezvous.Resolve())
154         {
155             if (log)
156                 log->Printf ("DynamicLoaderPOSIXDYLD::%s() pid %" PRIu64 " rendezvous could resolve: attach assuming dynamic loader info is available now", __FUNCTION__, m_process ? m_process->GetID () : LLDB_INVALID_PROCESS_ID);
157             LoadAllCurrentModules();
158             SetRendezvousBreakpoint();
159         }
160         else
161         {
162             if (log)
163                 log->Printf ("DynamicLoaderPOSIXDYLD::%s() pid %" PRIu64 " rendezvous could not yet resolve: adding breakpoint to catch future rendezvous setup", __FUNCTION__, m_process ? m_process->GetID () : LLDB_INVALID_PROCESS_ID);
164             ProbeEntry();
165         }
166 
167         m_process->GetTarget().ModulesDidLoad(module_list);
168         if (log)
169         {
170             log->Printf ("DynamicLoaderPOSIXDYLD::%s told the target about the modules that loaded:", __FUNCTION__);
171             for (auto module_sp : module_list.Modules ())
172             {
173                 log->Printf ("-- [module] %s (pid %" PRIu64 ")",
174                              module_sp ? module_sp->GetFileSpec().GetPath().c_str () : "<null>",
175                              m_process ? m_process->GetID () : LLDB_INVALID_PROCESS_ID);
176             }
177         }
178     }
179 }
180 
181 void
182 DynamicLoaderPOSIXDYLD::DidLaunch()
183 {
184     ModuleSP executable;
185     addr_t load_offset;
186 
187     m_auxv.reset(new AuxVector(m_process));
188 
189     executable = GetTargetExecutable();
190     load_offset = ComputeLoadOffset();
191 
192     if (executable.get() && load_offset != LLDB_INVALID_ADDRESS)
193     {
194         ModuleList module_list;
195         module_list.Append(executable);
196         UpdateLoadedSections(executable, LLDB_INVALID_ADDRESS, load_offset);
197         ProbeEntry();
198         m_process->GetTarget().ModulesDidLoad(module_list);
199     }
200 }
201 
202 Error
203 DynamicLoaderPOSIXDYLD::ExecutePluginCommand(Args &command, Stream *strm)
204 {
205     return Error();
206 }
207 
208 Log *
209 DynamicLoaderPOSIXDYLD::EnablePluginLogging(Stream *strm, Args &command)
210 {
211     return NULL;
212 }
213 
214 Error
215 DynamicLoaderPOSIXDYLD::CanLoadImage()
216 {
217     return Error();
218 }
219 
220 void
221 DynamicLoaderPOSIXDYLD::UpdateLoadedSections(ModuleSP module, addr_t link_map_addr, addr_t base_addr)
222 {
223     m_loaded_modules[module] = link_map_addr;
224 
225     UpdateLoadedSectionsCommon(module, base_addr);
226 }
227 
228 void
229 DynamicLoaderPOSIXDYLD::UnloadSections(const ModuleSP module)
230 {
231     m_loaded_modules.erase(module);
232 
233     UnloadSectionsCommon(module);
234 }
235 
236 void
237 DynamicLoaderPOSIXDYLD::ProbeEntry()
238 {
239     Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_DYNAMIC_LOADER));
240 
241     const addr_t entry = GetEntryPoint();
242     if (entry == LLDB_INVALID_ADDRESS)
243     {
244         if (log)
245             log->Printf ("DynamicLoaderPOSIXDYLD::%s pid %" PRIu64 " GetEntryPoint() returned no address, not setting entry breakpoint", __FUNCTION__, m_process ? m_process->GetID () : LLDB_INVALID_PROCESS_ID);
246         return;
247     }
248 
249     if (log)
250         if (log)
251             log->Printf ("DynamicLoaderPOSIXDYLD::%s pid %" PRIu64 " GetEntryPoint() returned address 0x%" PRIx64 ", setting entry breakpoint", __FUNCTION__, m_process ? m_process->GetID () : LLDB_INVALID_PROCESS_ID, entry);
252 
253 
254     Breakpoint *const entry_break = m_process->GetTarget().CreateBreakpoint(entry, true, false).get();
255     entry_break->SetCallback(EntryBreakpointHit, this, true);
256     entry_break->SetBreakpointKind("shared-library-event");
257 }
258 
259 // The runtime linker has run and initialized the rendezvous structure once the
260 // process has hit its entry point.  When we hit the corresponding breakpoint we
261 // interrogate the rendezvous structure to get the load addresses of all
262 // dependent modules for the process.  Similarly, we can discover the runtime
263 // linker function and setup a breakpoint to notify us of any dynamically loaded
264 // modules (via dlopen).
265 bool
266 DynamicLoaderPOSIXDYLD::EntryBreakpointHit(void *baton,
267                                            StoppointCallbackContext *context,
268                                            user_id_t break_id,
269                                            user_id_t break_loc_id)
270 {
271     assert(baton && "null baton");
272     if (!baton)
273         return false;
274 
275     Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_DYNAMIC_LOADER));
276     DynamicLoaderPOSIXDYLD *const dyld_instance = static_cast<DynamicLoaderPOSIXDYLD*>(baton);
277     if (log)
278         log->Printf ("DynamicLoaderPOSIXDYLD::%s called for pid %" PRIu64, __FUNCTION__, dyld_instance->m_process ? dyld_instance->m_process->GetID () : LLDB_INVALID_PROCESS_ID);
279 
280     dyld_instance->LoadAllCurrentModules();
281     dyld_instance->SetRendezvousBreakpoint();
282     return false; // Continue running.
283 }
284 
285 void
286 DynamicLoaderPOSIXDYLD::SetRendezvousBreakpoint()
287 {
288     Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_DYNAMIC_LOADER));
289 
290     addr_t break_addr = m_rendezvous.GetBreakAddress();
291     Target &target = m_process->GetTarget();
292 
293     if (m_dyld_bid == LLDB_INVALID_BREAK_ID)
294     {
295         if (log)
296             log->Printf ("DynamicLoaderPOSIXDYLD::%s pid %" PRIu64 " setting rendezvous break address at 0x%" PRIx64, __FUNCTION__, m_process ? m_process->GetID () : LLDB_INVALID_PROCESS_ID, break_addr);
297         Breakpoint *dyld_break = target.CreateBreakpoint (break_addr, true, false).get();
298         dyld_break->SetCallback(RendezvousBreakpointHit, this, true);
299         dyld_break->SetBreakpointKind ("shared-library-event");
300         m_dyld_bid = dyld_break->GetID();
301     }
302     else
303     {
304         if (log)
305             log->Printf ("DynamicLoaderPOSIXDYLD::%s pid %" PRIu64 " reusing break id %" PRIu32 ", address at 0x%" PRIx64, __FUNCTION__, m_process ? m_process->GetID () : LLDB_INVALID_PROCESS_ID, m_dyld_bid, break_addr);
306     }
307 
308     // Make sure our breakpoint is at the right address.
309     assert (target.GetBreakpointByID(m_dyld_bid)->FindLocationByAddress(break_addr)->GetBreakpoint().GetID() == m_dyld_bid);
310 }
311 
312 bool
313 DynamicLoaderPOSIXDYLD::RendezvousBreakpointHit(void *baton,
314                                                 StoppointCallbackContext *context,
315                                                 user_id_t break_id,
316                                                 user_id_t break_loc_id)
317 {
318     assert (baton && "null baton");
319     if (!baton)
320         return false;
321 
322     Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_DYNAMIC_LOADER));
323     DynamicLoaderPOSIXDYLD *const dyld_instance = static_cast<DynamicLoaderPOSIXDYLD*>(baton);
324     if (log)
325         log->Printf ("DynamicLoaderPOSIXDYLD::%s called for pid %" PRIu64, __FUNCTION__, dyld_instance->m_process ? dyld_instance->m_process->GetID () : LLDB_INVALID_PROCESS_ID);
326 
327     dyld_instance->RefreshModules();
328 
329     // Return true to stop the target, false to just let the target run.
330     const bool stop_when_images_change = dyld_instance->GetStopWhenImagesChange();
331     if (log)
332         log->Printf ("DynamicLoaderPOSIXDYLD::%s pid %" PRIu64 " stop_when_images_change=%s", __FUNCTION__, dyld_instance->m_process ? dyld_instance->m_process->GetID () : LLDB_INVALID_PROCESS_ID, stop_when_images_change ? "true" : "false");
333     return stop_when_images_change;
334 }
335 
336 void
337 DynamicLoaderPOSIXDYLD::RefreshModules()
338 {
339     if (!m_rendezvous.Resolve())
340         return;
341 
342     DYLDRendezvous::iterator I;
343     DYLDRendezvous::iterator E;
344 
345     ModuleList &loaded_modules = m_process->GetTarget().GetImages();
346 
347     if (m_rendezvous.ModulesDidLoad())
348     {
349         ModuleList new_modules;
350 
351         E = m_rendezvous.loaded_end();
352         for (I = m_rendezvous.loaded_begin(); I != E; ++I)
353         {
354             FileSpec file(I->path.c_str(), true);
355             ModuleSP module_sp = LoadModuleAtAddress(file, I->link_addr, I->base_addr);
356             if (module_sp.get())
357             {
358                 loaded_modules.AppendIfNeeded(module_sp);
359                 new_modules.Append(module_sp);
360             }
361         }
362         m_process->GetTarget().ModulesDidLoad(new_modules);
363     }
364 
365     if (m_rendezvous.ModulesDidUnload())
366     {
367         ModuleList old_modules;
368 
369         E = m_rendezvous.unloaded_end();
370         for (I = m_rendezvous.unloaded_begin(); I != E; ++I)
371         {
372             FileSpec file(I->path.c_str(), true);
373             ModuleSpec module_spec (file);
374             ModuleSP module_sp =
375                 loaded_modules.FindFirstModule (module_spec);
376 
377             if (module_sp.get())
378             {
379                 old_modules.Append(module_sp);
380                 UnloadSections(module_sp);
381             }
382         }
383         loaded_modules.Remove(old_modules);
384         m_process->GetTarget().ModulesDidUnload(old_modules, false);
385     }
386 }
387 
388 ThreadPlanSP
389 DynamicLoaderPOSIXDYLD::GetStepThroughTrampolinePlan(Thread &thread, bool stop)
390 {
391     ThreadPlanSP thread_plan_sp;
392 
393     StackFrame *frame = thread.GetStackFrameAtIndex(0).get();
394     const SymbolContext &context = frame->GetSymbolContext(eSymbolContextSymbol);
395     Symbol *sym = context.symbol;
396 
397     if (sym == NULL || !sym->IsTrampoline())
398         return thread_plan_sp;
399 
400     const ConstString &sym_name = sym->GetMangled().GetName(Mangled::ePreferMangled);
401     if (!sym_name)
402         return thread_plan_sp;
403 
404     SymbolContextList target_symbols;
405     Target &target = thread.GetProcess()->GetTarget();
406     const ModuleList &images = target.GetImages();
407 
408     images.FindSymbolsWithNameAndType(sym_name, eSymbolTypeCode, target_symbols);
409     size_t num_targets = target_symbols.GetSize();
410     if (!num_targets)
411         return thread_plan_sp;
412 
413     typedef std::vector<lldb::addr_t> AddressVector;
414     AddressVector addrs;
415     for (size_t i = 0; i < num_targets; ++i)
416     {
417         SymbolContext context;
418         AddressRange range;
419         if (target_symbols.GetContextAtIndex(i, context))
420         {
421             context.GetAddressRange(eSymbolContextEverything, 0, false, range);
422             lldb::addr_t addr = range.GetBaseAddress().GetLoadAddress(&target);
423             if (addr != LLDB_INVALID_ADDRESS)
424                 addrs.push_back(addr);
425         }
426     }
427 
428     if (addrs.size() > 0)
429     {
430         AddressVector::iterator start = addrs.begin();
431         AddressVector::iterator end = addrs.end();
432 
433         std::sort(start, end);
434         addrs.erase(std::unique(start, end), end);
435         thread_plan_sp.reset(new ThreadPlanRunToAddress(thread, addrs, stop));
436     }
437 
438     return thread_plan_sp;
439 }
440 
441 void
442 DynamicLoaderPOSIXDYLD::LoadAllCurrentModules()
443 {
444     DYLDRendezvous::iterator I;
445     DYLDRendezvous::iterator E;
446     ModuleList module_list;
447 
448     if (!m_rendezvous.Resolve())
449     {
450         Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_DYNAMIC_LOADER));
451         if (log)
452             log->Printf("DynamicLoaderPOSIXDYLD::%s unable to resolve POSIX DYLD rendezvous address",
453                         __FUNCTION__);
454         return;
455     }
456 
457     // The rendezvous class doesn't enumerate the main module, so track
458     // that ourselves here.
459     ModuleSP executable = GetTargetExecutable();
460     m_loaded_modules[executable] = m_rendezvous.GetLinkMapAddress();
461 
462 
463     for (I = m_rendezvous.begin(), E = m_rendezvous.end(); I != E; ++I)
464     {
465         const char *module_path = I->path.c_str();
466         FileSpec file(module_path, false);
467         ModuleSP module_sp = LoadModuleAtAddress(file, I->link_addr, I->base_addr);
468         if (module_sp.get())
469         {
470             module_list.Append(module_sp);
471         }
472         else
473         {
474             Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_DYNAMIC_LOADER));
475             if (log)
476                 log->Printf("DynamicLoaderPOSIXDYLD::%s failed loading module %s at 0x%" PRIx64,
477                             __FUNCTION__, module_path, I->base_addr);
478         }
479     }
480 
481     m_process->GetTarget().ModulesDidLoad(module_list);
482 }
483 
484 addr_t
485 DynamicLoaderPOSIXDYLD::ComputeLoadOffset()
486 {
487     addr_t virt_entry;
488 
489     if (m_load_offset != LLDB_INVALID_ADDRESS)
490         return m_load_offset;
491 
492     if ((virt_entry = GetEntryPoint()) == LLDB_INVALID_ADDRESS)
493         return LLDB_INVALID_ADDRESS;
494 
495     ModuleSP module = m_process->GetTarget().GetExecutableModule();
496     if (!module)
497         return LLDB_INVALID_ADDRESS;
498 
499     ObjectFile *exe = module->GetObjectFile();
500     Address file_entry = exe->GetEntryPointAddress();
501 
502     if (!file_entry.IsValid())
503         return LLDB_INVALID_ADDRESS;
504 
505     m_load_offset = virt_entry - file_entry.GetFileAddress();
506     return m_load_offset;
507 }
508 
509 addr_t
510 DynamicLoaderPOSIXDYLD::GetEntryPoint()
511 {
512     if (m_entry_point != LLDB_INVALID_ADDRESS)
513         return m_entry_point;
514 
515     if (m_auxv.get() == NULL)
516         return LLDB_INVALID_ADDRESS;
517 
518     AuxVector::iterator I = m_auxv->FindEntry(AuxVector::AT_ENTRY);
519 
520     if (I == m_auxv->end())
521         return LLDB_INVALID_ADDRESS;
522 
523     m_entry_point = static_cast<addr_t>(I->value);
524     return m_entry_point;
525 }
526 
527 lldb::addr_t
528 DynamicLoaderPOSIXDYLD::GetThreadLocalData (const lldb::ModuleSP module, const lldb::ThreadSP thread)
529 {
530     auto it = m_loaded_modules.find (module);
531     if (it == m_loaded_modules.end())
532         return LLDB_INVALID_ADDRESS;
533 
534     addr_t link_map = it->second;
535     if (link_map == LLDB_INVALID_ADDRESS)
536         return LLDB_INVALID_ADDRESS;
537 
538     const DYLDRendezvous::ThreadInfo &metadata = m_rendezvous.GetThreadInfo();
539     if (!metadata.valid)
540         return LLDB_INVALID_ADDRESS;
541 
542     // Get the thread pointer.
543     addr_t tp = thread->GetThreadPointer ();
544     if (tp == LLDB_INVALID_ADDRESS)
545         return LLDB_INVALID_ADDRESS;
546 
547     // Find the module's modid.
548     int modid_size = 4;  // FIXME(spucci): This isn't right for big-endian 64-bit
549     int64_t modid = ReadUnsignedIntWithSizeInBytes (link_map + metadata.modid_offset, modid_size);
550     if (modid == -1)
551         return LLDB_INVALID_ADDRESS;
552 
553     // Lookup the DTV structure for this thread.
554     addr_t dtv_ptr = tp + metadata.dtv_offset;
555     addr_t dtv = ReadPointer (dtv_ptr);
556     if (dtv == LLDB_INVALID_ADDRESS)
557         return LLDB_INVALID_ADDRESS;
558 
559     // Find the TLS block for this module.
560     addr_t dtv_slot = dtv + metadata.dtv_slot_size*modid;
561     addr_t tls_block = ReadPointer (dtv_slot + metadata.tls_offset);
562 
563     Module *mod = module.get();
564     Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_DYNAMIC_LOADER));
565     if (log)
566         log->Printf("DynamicLoaderPOSIXDYLD::Performed TLS lookup: "
567                     "module=%s, link_map=0x%" PRIx64 ", tp=0x%" PRIx64 ", modid=%" PRId64 ", tls_block=0x%" PRIx64 "\n",
568                     mod->GetObjectName().AsCString(""), link_map, tp, (int64_t)modid, tls_block);
569 
570     return tls_block;
571 }
572