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