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