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
LLDB_PLUGIN_DEFINE_ADV(DynamicLoaderPOSIXDYLD,DynamicLoaderPosixDYLD)33 LLDB_PLUGIN_DEFINE_ADV(DynamicLoaderPOSIXDYLD, DynamicLoaderPosixDYLD)
34
35 void DynamicLoaderPOSIXDYLD::Initialize() {
36 PluginManager::RegisterPlugin(GetPluginNameStatic(),
37 GetPluginDescriptionStatic(), CreateInstance);
38 }
39
Terminate()40 void DynamicLoaderPOSIXDYLD::Terminate() {}
41
GetPluginDescriptionStatic()42 llvm::StringRef DynamicLoaderPOSIXDYLD::GetPluginDescriptionStatic() {
43 return "Dynamic loader plug-in that watches for shared library "
44 "loads/unloads in POSIX processes.";
45 }
46
CreateInstance(Process * process,bool force)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
DynamicLoaderPOSIXDYLD(Process * process)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
~DynamicLoaderPOSIXDYLD()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
DidAttach()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
DidLaunch()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
CanLoadImage()197 Status DynamicLoaderPOSIXDYLD::CanLoadImage() { return Status(); }
198
UpdateLoadedSections(ModuleSP module,addr_t link_map_addr,addr_t base_addr,bool base_addr_is_offset)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
UnloadSections(const ModuleSP module)207 void DynamicLoaderPOSIXDYLD::UnloadSections(const ModuleSP module) {
208 m_loaded_modules.erase(module);
209
210 UnloadSectionsCommon(module);
211 }
212
ProbeEntry()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).
EntryBreakpointHit(void * baton,StoppointCallbackContext * context,user_id_t break_id,user_id_t break_loc_id)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
SetRendezvousBreakpoint()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
RendezvousBreakpointHit(void * baton,StoppointCallbackContext * context,user_id_t break_id,user_id_t break_loc_id)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
RefreshModules()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 continue;
438
439 if (module_sp->GetObjectFile()->GetBaseAddress().GetLoadAddress(
440 &m_process->GetTarget()) == m_interpreter_base) {
441 ModuleSP interpreter_sp = m_interpreter_module.lock();
442 if (m_interpreter_module.lock() == nullptr) {
443 m_interpreter_module = module_sp;
444 } else if (module_sp == interpreter_sp) {
445 // Module already loaded.
446 continue;
447 } else {
448 // If this is a duplicate instance of ld.so, unload it. We may end
449 // up with it if we load it via a different path than before
450 // (symlink vs real path).
451 // TODO: remove this once we either fix library matching or avoid
452 // loading the interpreter when setting the rendezvous breakpoint.
453 UnloadSections(module_sp);
454 loaded_modules.Remove(module_sp);
455 continue;
456 }
457 }
458
459 loaded_modules.AppendIfNeeded(module_sp);
460 new_modules.Append(module_sp);
461 }
462 m_process->GetTarget().ModulesDidLoad(new_modules);
463 }
464
465 if (m_rendezvous.ModulesDidUnload()) {
466 ModuleList old_modules;
467
468 E = m_rendezvous.unloaded_end();
469 for (I = m_rendezvous.unloaded_begin(); I != E; ++I) {
470 ModuleSpec module_spec{I->file_spec};
471 ModuleSP module_sp = loaded_modules.FindFirstModule(module_spec);
472
473 if (module_sp.get()) {
474 old_modules.Append(module_sp);
475 UnloadSections(module_sp);
476 }
477 }
478 loaded_modules.Remove(old_modules);
479 m_process->GetTarget().ModulesDidUnload(old_modules, false);
480 }
481 }
482
483 ThreadPlanSP
GetStepThroughTrampolinePlan(Thread & thread,bool stop)484 DynamicLoaderPOSIXDYLD::GetStepThroughTrampolinePlan(Thread &thread,
485 bool stop) {
486 ThreadPlanSP thread_plan_sp;
487
488 StackFrame *frame = thread.GetStackFrameAtIndex(0).get();
489 const SymbolContext &context = frame->GetSymbolContext(eSymbolContextSymbol);
490 Symbol *sym = context.symbol;
491
492 if (sym == nullptr || !sym->IsTrampoline())
493 return thread_plan_sp;
494
495 ConstString sym_name = sym->GetMangled().GetName(Mangled::ePreferMangled);
496 if (!sym_name)
497 return thread_plan_sp;
498
499 SymbolContextList target_symbols;
500 Target &target = thread.GetProcess()->GetTarget();
501 const ModuleList &images = target.GetImages();
502
503 images.FindSymbolsWithNameAndType(sym_name, eSymbolTypeCode, target_symbols);
504 size_t num_targets = target_symbols.GetSize();
505 if (!num_targets)
506 return thread_plan_sp;
507
508 typedef std::vector<lldb::addr_t> AddressVector;
509 AddressVector addrs;
510 for (size_t i = 0; i < num_targets; ++i) {
511 SymbolContext context;
512 AddressRange range;
513 if (target_symbols.GetContextAtIndex(i, context)) {
514 context.GetAddressRange(eSymbolContextEverything, 0, false, range);
515 lldb::addr_t addr = range.GetBaseAddress().GetLoadAddress(&target);
516 if (addr != LLDB_INVALID_ADDRESS)
517 addrs.push_back(addr);
518 }
519 }
520
521 if (addrs.size() > 0) {
522 AddressVector::iterator start = addrs.begin();
523 AddressVector::iterator end = addrs.end();
524
525 llvm::sort(start, end);
526 addrs.erase(std::unique(start, end), end);
527 thread_plan_sp =
528 std::make_shared<ThreadPlanRunToAddress>(thread, addrs, stop);
529 }
530
531 return thread_plan_sp;
532 }
533
LoadVDSO()534 void DynamicLoaderPOSIXDYLD::LoadVDSO() {
535 if (m_vdso_base == LLDB_INVALID_ADDRESS)
536 return;
537
538 FileSpec file("[vdso]");
539
540 MemoryRegionInfo info;
541 Status status = m_process->GetMemoryRegionInfo(m_vdso_base, info);
542 if (status.Fail()) {
543 Log *log = GetLog(LLDBLog::DynamicLoader);
544 LLDB_LOG(log, "Failed to get vdso region info: {0}", status);
545 return;
546 }
547
548 if (ModuleSP module_sp = m_process->ReadModuleFromMemory(
549 file, m_vdso_base, info.GetRange().GetByteSize())) {
550 UpdateLoadedSections(module_sp, LLDB_INVALID_ADDRESS, m_vdso_base, false);
551 m_process->GetTarget().GetImages().AppendIfNeeded(module_sp);
552 }
553 }
554
LoadInterpreterModule()555 ModuleSP DynamicLoaderPOSIXDYLD::LoadInterpreterModule() {
556 if (m_interpreter_base == LLDB_INVALID_ADDRESS)
557 return nullptr;
558
559 MemoryRegionInfo info;
560 Target &target = m_process->GetTarget();
561 Status status = m_process->GetMemoryRegionInfo(m_interpreter_base, info);
562 if (status.Fail() || info.GetMapped() != MemoryRegionInfo::eYes ||
563 info.GetName().IsEmpty()) {
564 Log *log = GetLog(LLDBLog::DynamicLoader);
565 LLDB_LOG(log, "Failed to get interpreter region info: {0}", status);
566 return nullptr;
567 }
568
569 FileSpec file(info.GetName().GetCString());
570 ModuleSpec module_spec(file, target.GetArchitecture());
571
572 if (ModuleSP module_sp = target.GetOrCreateModule(module_spec,
573 true /* notify */)) {
574 UpdateLoadedSections(module_sp, LLDB_INVALID_ADDRESS, m_interpreter_base,
575 false);
576 m_interpreter_module = module_sp;
577 return module_sp;
578 }
579 return nullptr;
580 }
581
LoadModuleAtAddress(const FileSpec & file,addr_t link_map_addr,addr_t base_addr,bool base_addr_is_offset)582 ModuleSP DynamicLoaderPOSIXDYLD::LoadModuleAtAddress(const FileSpec &file,
583 addr_t link_map_addr,
584 addr_t base_addr,
585 bool base_addr_is_offset) {
586 if (ModuleSP module_sp = DynamicLoader::LoadModuleAtAddress(
587 file, link_map_addr, base_addr, base_addr_is_offset))
588 return module_sp;
589
590 // This works around an dynamic linker "bug" on android <= 23, where the
591 // dynamic linker would report the application name
592 // (e.g. com.example.myapplication) instead of the main process binary
593 // (/system/bin/app_process(32)). The logic is not sound in general (it
594 // assumes base_addr is the real address, even though it actually is a load
595 // bias), but it happens to work on adroid because app_process has a file
596 // address of zero.
597 // This should be removed after we drop support for android-23.
598 if (m_process->GetTarget().GetArchitecture().GetTriple().isAndroid()) {
599 MemoryRegionInfo memory_info;
600 Status error = m_process->GetMemoryRegionInfo(base_addr, memory_info);
601 if (error.Success() && memory_info.GetMapped() &&
602 memory_info.GetRange().GetRangeBase() == base_addr &&
603 !(memory_info.GetName().IsEmpty())) {
604 if (ModuleSP module_sp = DynamicLoader::LoadModuleAtAddress(
605 FileSpec(memory_info.GetName().GetStringRef()), link_map_addr,
606 base_addr, base_addr_is_offset))
607 return module_sp;
608 }
609 }
610
611 return nullptr;
612 }
613
LoadAllCurrentModules()614 void DynamicLoaderPOSIXDYLD::LoadAllCurrentModules() {
615 DYLDRendezvous::iterator I;
616 DYLDRendezvous::iterator E;
617 ModuleList module_list;
618 Log *log = GetLog(LLDBLog::DynamicLoader);
619
620 LoadVDSO();
621
622 if (!m_rendezvous.Resolve()) {
623 LLDB_LOGF(log,
624 "DynamicLoaderPOSIXDYLD::%s unable to resolve POSIX DYLD "
625 "rendezvous address",
626 __FUNCTION__);
627 return;
628 }
629
630 // The rendezvous class doesn't enumerate the main module, so track that
631 // ourselves here.
632 ModuleSP executable = GetTargetExecutable();
633 m_loaded_modules[executable] = m_rendezvous.GetLinkMapAddress();
634
635 std::vector<FileSpec> module_names;
636 for (I = m_rendezvous.begin(), E = m_rendezvous.end(); I != E; ++I)
637 module_names.push_back(I->file_spec);
638 m_process->PrefetchModuleSpecs(
639 module_names, m_process->GetTarget().GetArchitecture().GetTriple());
640
641 for (I = m_rendezvous.begin(), E = m_rendezvous.end(); I != E; ++I) {
642 ModuleSP module_sp =
643 LoadModuleAtAddress(I->file_spec, I->link_addr, I->base_addr, true);
644 if (module_sp.get()) {
645 LLDB_LOG(log, "LoadAllCurrentModules loading module: {0}",
646 I->file_spec.GetFilename());
647 module_list.Append(module_sp);
648 } else {
649 Log *log = GetLog(LLDBLog::DynamicLoader);
650 LLDB_LOGF(
651 log,
652 "DynamicLoaderPOSIXDYLD::%s failed loading module %s at 0x%" PRIx64,
653 __FUNCTION__, I->file_spec.GetCString(), I->base_addr);
654 }
655 }
656
657 m_process->GetTarget().ModulesDidLoad(module_list);
658 m_initial_modules_added = true;
659 }
660
ComputeLoadOffset()661 addr_t DynamicLoaderPOSIXDYLD::ComputeLoadOffset() {
662 addr_t virt_entry;
663
664 if (m_load_offset != LLDB_INVALID_ADDRESS)
665 return m_load_offset;
666
667 if ((virt_entry = GetEntryPoint()) == LLDB_INVALID_ADDRESS)
668 return LLDB_INVALID_ADDRESS;
669
670 ModuleSP module = m_process->GetTarget().GetExecutableModule();
671 if (!module)
672 return LLDB_INVALID_ADDRESS;
673
674 ObjectFile *exe = module->GetObjectFile();
675 if (!exe)
676 return LLDB_INVALID_ADDRESS;
677
678 Address file_entry = exe->GetEntryPointAddress();
679
680 if (!file_entry.IsValid())
681 return LLDB_INVALID_ADDRESS;
682
683 m_load_offset = virt_entry - file_entry.GetFileAddress();
684 return m_load_offset;
685 }
686
EvalSpecialModulesStatus()687 void DynamicLoaderPOSIXDYLD::EvalSpecialModulesStatus() {
688 if (llvm::Optional<uint64_t> vdso_base =
689 m_auxv->GetAuxValue(AuxVector::AUXV_AT_SYSINFO_EHDR))
690 m_vdso_base = *vdso_base;
691
692 if (llvm::Optional<uint64_t> interpreter_base =
693 m_auxv->GetAuxValue(AuxVector::AUXV_AT_BASE))
694 m_interpreter_base = *interpreter_base;
695 }
696
GetEntryPoint()697 addr_t DynamicLoaderPOSIXDYLD::GetEntryPoint() {
698 if (m_entry_point != LLDB_INVALID_ADDRESS)
699 return m_entry_point;
700
701 if (m_auxv == nullptr)
702 return LLDB_INVALID_ADDRESS;
703
704 llvm::Optional<uint64_t> entry_point =
705 m_auxv->GetAuxValue(AuxVector::AUXV_AT_ENTRY);
706 if (!entry_point)
707 return LLDB_INVALID_ADDRESS;
708
709 m_entry_point = static_cast<addr_t>(*entry_point);
710
711 const ArchSpec &arch = m_process->GetTarget().GetArchitecture();
712
713 // On ppc64, the entry point is actually a descriptor. Dereference it.
714 if (arch.GetMachine() == llvm::Triple::ppc64)
715 m_entry_point = ReadUnsignedIntWithSizeInBytes(m_entry_point, 8);
716
717 return m_entry_point;
718 }
719
720 lldb::addr_t
GetThreadLocalData(const lldb::ModuleSP module_sp,const lldb::ThreadSP thread,lldb::addr_t tls_file_addr)721 DynamicLoaderPOSIXDYLD::GetThreadLocalData(const lldb::ModuleSP module_sp,
722 const lldb::ThreadSP thread,
723 lldb::addr_t tls_file_addr) {
724 auto it = m_loaded_modules.find(module_sp);
725 if (it == m_loaded_modules.end())
726 return LLDB_INVALID_ADDRESS;
727
728 addr_t link_map = it->second;
729 if (link_map == LLDB_INVALID_ADDRESS)
730 return LLDB_INVALID_ADDRESS;
731
732 const DYLDRendezvous::ThreadInfo &metadata = m_rendezvous.GetThreadInfo();
733 if (!metadata.valid)
734 return LLDB_INVALID_ADDRESS;
735
736 // Get the thread pointer.
737 addr_t tp = thread->GetThreadPointer();
738 if (tp == LLDB_INVALID_ADDRESS)
739 return LLDB_INVALID_ADDRESS;
740
741 // Find the module's modid.
742 int modid_size = 4; // FIXME(spucci): This isn't right for big-endian 64-bit
743 int64_t modid = ReadUnsignedIntWithSizeInBytes(
744 link_map + metadata.modid_offset, modid_size);
745 if (modid == -1)
746 return LLDB_INVALID_ADDRESS;
747
748 // Lookup the DTV structure for this thread.
749 addr_t dtv_ptr = tp + metadata.dtv_offset;
750 addr_t dtv = ReadPointer(dtv_ptr);
751 if (dtv == LLDB_INVALID_ADDRESS)
752 return LLDB_INVALID_ADDRESS;
753
754 // Find the TLS block for this module.
755 addr_t dtv_slot = dtv + metadata.dtv_slot_size * modid;
756 addr_t tls_block = ReadPointer(dtv_slot + metadata.tls_offset);
757
758 Log *log = GetLog(LLDBLog::DynamicLoader);
759 LLDB_LOGF(log,
760 "DynamicLoaderPOSIXDYLD::Performed TLS lookup: "
761 "module=%s, link_map=0x%" PRIx64 ", tp=0x%" PRIx64
762 ", modid=%" PRId64 ", tls_block=0x%" PRIx64 "\n",
763 module_sp->GetObjectName().AsCString(""), link_map, tp,
764 (int64_t)modid, tls_block);
765
766 if (tls_block == LLDB_INVALID_ADDRESS)
767 return LLDB_INVALID_ADDRESS;
768 else
769 return tls_block + tls_file_addr;
770 }
771
ResolveExecutableModule(lldb::ModuleSP & module_sp)772 void DynamicLoaderPOSIXDYLD::ResolveExecutableModule(
773 lldb::ModuleSP &module_sp) {
774 Log *log = GetLog(LLDBLog::DynamicLoader);
775
776 if (m_process == nullptr)
777 return;
778
779 auto &target = m_process->GetTarget();
780 const auto platform_sp = target.GetPlatform();
781
782 ProcessInstanceInfo process_info;
783 if (!m_process->GetProcessInfo(process_info)) {
784 LLDB_LOGF(log,
785 "DynamicLoaderPOSIXDYLD::%s - failed to get process info for "
786 "pid %" PRIu64,
787 __FUNCTION__, m_process->GetID());
788 return;
789 }
790
791 LLDB_LOGF(
792 log, "DynamicLoaderPOSIXDYLD::%s - got executable by pid %" PRIu64 ": %s",
793 __FUNCTION__, m_process->GetID(),
794 process_info.GetExecutableFile().GetPath().c_str());
795
796 ModuleSpec module_spec(process_info.GetExecutableFile(),
797 process_info.GetArchitecture());
798 if (module_sp && module_sp->MatchesModuleSpec(module_spec))
799 return;
800
801 const auto executable_search_paths(Target::GetDefaultExecutableSearchPaths());
802 auto error = platform_sp->ResolveExecutable(
803 module_spec, module_sp,
804 !executable_search_paths.IsEmpty() ? &executable_search_paths : nullptr);
805 if (error.Fail()) {
806 StreamString stream;
807 module_spec.Dump(stream);
808
809 LLDB_LOGF(log,
810 "DynamicLoaderPOSIXDYLD::%s - failed to resolve executable "
811 "with module spec \"%s\": %s",
812 __FUNCTION__, stream.GetData(), error.AsCString());
813 return;
814 }
815
816 target.SetExecutableModule(module_sp, eLoadDependentsNo);
817 }
818
AlwaysRelyOnEHUnwindInfo(lldb_private::SymbolContext & sym_ctx)819 bool DynamicLoaderPOSIXDYLD::AlwaysRelyOnEHUnwindInfo(
820 lldb_private::SymbolContext &sym_ctx) {
821 ModuleSP module_sp;
822 if (sym_ctx.symbol)
823 module_sp = sym_ctx.symbol->GetAddressRef().GetModule();
824 if (!module_sp && sym_ctx.function)
825 module_sp =
826 sym_ctx.function->GetAddressRange().GetBaseAddress().GetModule();
827 if (!module_sp)
828 return false;
829
830 return module_sp->GetFileSpec().GetPath() == "[vdso]";
831 }
832