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