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