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