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