1 //===-- DYLDRendezvous.cpp --------------------------------------*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
12 // Other libraries and framework includes
13 #include "lldb/Core/ArchSpec.h"
14 #include "lldb/Core/Error.h"
15 #include "lldb/Core/Log.h"
16 #include "lldb/Core/Module.h"
17 #include "lldb/Symbol/ObjectFile.h"
18 #include "lldb/Symbol/Symbol.h"
19 #include "lldb/Symbol/SymbolContext.h"
20 #include "lldb/Target/Platform.h"
21 #include "lldb/Target/Process.h"
22 #include "lldb/Target/Target.h"
24 #include "llvm/Support/Path.h"
26 #include "DYLDRendezvous.h"
29 using namespace lldb_private;
31 /// Locates the address of the rendezvous structure. Returns the address on
32 /// success and LLDB_INVALID_ADDRESS on failure.
33 static addr_t ResolveRendezvousAddress(Process *process) {
34 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_DYNAMIC_LOADER));
41 log->Printf("%s null process provided", __FUNCTION__);
42 return LLDB_INVALID_ADDRESS;
45 // Try to get it from our process. This might be a remote process and might
46 // grab it via some remote-specific mechanism.
47 info_location = process->GetImageInfoAddress();
49 log->Printf("%s info_location = 0x%" PRIx64, __FUNCTION__, info_location);
51 // If the process fails to return an address, fall back to seeing if the local
52 // object file can help us find it.
53 if (info_location == LLDB_INVALID_ADDRESS) {
54 Target *target = &process->GetTarget();
56 ObjectFile *obj_file = target->GetExecutableModule()->GetObjectFile();
57 Address addr = obj_file->GetImageInfoAddress(target);
60 info_location = addr.GetLoadAddress(target);
63 "%s resolved via direct object file approach to 0x%" PRIx64,
64 __FUNCTION__, info_location);
67 log->Printf("%s FAILED - direct object file approach did not yield a "
74 if (info_location == LLDB_INVALID_ADDRESS) {
76 log->Printf("%s FAILED - invalid info address", __FUNCTION__);
77 return LLDB_INVALID_ADDRESS;
81 log->Printf("%s reading pointer (%" PRIu32 " bytes) from 0x%" PRIx64,
82 __FUNCTION__, process->GetAddressByteSize(), info_location);
84 info_addr = process->ReadPointerFromMemory(info_location, error);
87 log->Printf("%s FAILED - could not read from the info location: %s",
88 __FUNCTION__, error.AsCString());
89 return LLDB_INVALID_ADDRESS;
94 log->Printf("%s FAILED - the rendezvous address contained at 0x%" PRIx64
95 " returned a null value",
96 __FUNCTION__, info_location);
97 return LLDB_INVALID_ADDRESS;
103 DYLDRendezvous::DYLDRendezvous(Process *process)
104 : m_process(process), m_rendezvous_addr(LLDB_INVALID_ADDRESS), m_current(),
105 m_previous(), m_loaded_modules(), m_soentries(), m_added_soentries(),
106 m_removed_soentries() {
107 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_DYNAMIC_LOADER));
109 m_thread_info.valid = false;
111 // Cache a copy of the executable path
113 Module *exe_mod = m_process->GetTarget().GetExecutableModulePointer();
115 m_exe_file_spec = exe_mod->GetPlatformFileSpec();
117 log->Printf("DYLDRendezvous::%s exe module executable path set: '%s'",
118 __FUNCTION__, m_exe_file_spec.GetCString());
121 log->Printf("DYLDRendezvous::%s cannot cache exe module path: null "
122 "executable module pointer",
128 bool DYLDRendezvous::Resolve() {
129 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_DYNAMIC_LOADER));
131 const size_t word_size = 4;
138 address_size = m_process->GetAddressByteSize();
139 padding = address_size - word_size;
141 log->Printf("DYLDRendezvous::%s address size: %" PRIu64
142 ", padding %" PRIu64,
143 __FUNCTION__, uint64_t(address_size), uint64_t(padding));
145 if (m_rendezvous_addr == LLDB_INVALID_ADDRESS)
146 cursor = info_addr = ResolveRendezvousAddress(m_process);
148 cursor = info_addr = m_rendezvous_addr;
150 log->Printf("DYLDRendezvous::%s cursor = 0x%" PRIx64, __FUNCTION__, cursor);
152 if (cursor == LLDB_INVALID_ADDRESS)
155 if (!(cursor = ReadWord(cursor, &info.version, word_size)))
158 if (!(cursor = ReadPointer(cursor + padding, &info.map_addr)))
161 if (!(cursor = ReadPointer(cursor, &info.brk)))
164 if (!(cursor = ReadWord(cursor, &info.state, word_size)))
167 if (!(cursor = ReadPointer(cursor + padding, &info.ldbase)))
170 // The rendezvous was successfully read. Update our internal state.
171 m_rendezvous_addr = info_addr;
172 m_previous = m_current;
175 if (UpdateSOEntries(true))
178 return UpdateSOEntries();
181 bool DYLDRendezvous::IsValid() {
182 return m_rendezvous_addr != LLDB_INVALID_ADDRESS;
185 bool DYLDRendezvous::UpdateSOEntries(bool fromRemote) {
187 LoadedModuleInfoList module_list;
189 // If we can't get the SO info from the remote, return failure.
190 if (fromRemote && m_process->LoadModules(module_list) == 0)
193 if (!fromRemote && m_current.map_addr == 0)
196 // When the previous and current states are consistent this is the first
197 // time we have been asked to update. Just take a snapshot of the currently
199 if (m_previous.state == eConsistent && m_current.state == eConsistent)
200 return fromRemote ? SaveSOEntriesFromRemote(module_list)
201 : TakeSnapshot(m_soentries);
203 // If we are about to add or remove a shared object clear out the current
204 // state and take a snapshot of the currently loaded images.
205 if (m_current.state == eAdd || m_current.state == eDelete) {
206 // Some versions of the android dynamic linker might send two
207 // notifications with state == eAdd back to back. Ignore them
208 // until we get an eConsistent notification.
209 if (!(m_previous.state == eConsistent ||
210 (m_previous.state == eAdd && m_current.state == eDelete)))
215 return SaveSOEntriesFromRemote(module_list);
217 m_added_soentries.clear();
218 m_removed_soentries.clear();
219 return TakeSnapshot(m_soentries);
221 assert(m_current.state == eConsistent);
223 // Otherwise check the previous state to determine what to expect and update
225 if (m_previous.state == eAdd)
226 return fromRemote ? AddSOEntriesFromRemote(module_list) : AddSOEntries();
227 else if (m_previous.state == eDelete)
228 return fromRemote ? RemoveSOEntriesFromRemote(module_list)
234 bool DYLDRendezvous::FillSOEntryFromModuleInfo(
235 LoadedModuleInfoList::LoadedModuleInfo const &modInfo, SOEntry &entry) {
236 addr_t link_map_addr;
241 if (!modInfo.get_link_map(link_map_addr) || !modInfo.get_base(base_addr) ||
242 !modInfo.get_dynamic(dyn_addr) || !modInfo.get_name(name))
245 entry.link_addr = link_map_addr;
246 entry.base_addr = base_addr;
247 entry.dyn_addr = dyn_addr;
249 entry.file_spec.SetFile(name, false);
251 UpdateBaseAddrIfNecessary(entry, name);
253 // not needed if we're using ModuleInfos
261 bool DYLDRendezvous::SaveSOEntriesFromRemote(
262 LoadedModuleInfoList &module_list) {
263 for (auto const &modInfo : module_list.m_list) {
265 if (!FillSOEntryFromModuleInfo(modInfo, entry))
268 // Only add shared libraries and not the executable.
269 if (!SOEntryIsMainExecutable(entry))
270 m_soentries.push_back(entry);
273 m_loaded_modules = module_list;
277 bool DYLDRendezvous::AddSOEntriesFromRemote(LoadedModuleInfoList &module_list) {
278 for (auto const &modInfo : module_list.m_list) {
280 for (auto const &existing : m_loaded_modules.m_list) {
281 if (modInfo == existing) {
291 if (!FillSOEntryFromModuleInfo(modInfo, entry))
294 // Only add shared libraries and not the executable.
295 if (!SOEntryIsMainExecutable(entry))
296 m_soentries.push_back(entry);
299 m_loaded_modules = module_list;
303 bool DYLDRendezvous::RemoveSOEntriesFromRemote(
304 LoadedModuleInfoList &module_list) {
305 for (auto const &existing : m_loaded_modules.m_list) {
307 for (auto const &modInfo : module_list.m_list) {
308 if (modInfo == existing) {
318 if (!FillSOEntryFromModuleInfo(existing, entry))
321 // Only add shared libraries and not the executable.
322 if (!SOEntryIsMainExecutable(entry)) {
323 auto pos = std::find(m_soentries.begin(), m_soentries.end(), entry);
324 if (pos == m_soentries.end())
327 m_soentries.erase(pos);
331 m_loaded_modules = module_list;
335 bool DYLDRendezvous::AddSOEntries() {
339 assert(m_previous.state == eAdd);
341 if (m_current.map_addr == 0)
344 for (addr_t cursor = m_current.map_addr; cursor != 0; cursor = entry.next) {
345 if (!ReadSOEntryFromMemory(cursor, entry))
348 // Only add shared libraries and not the executable.
349 if (SOEntryIsMainExecutable(entry))
352 pos = std::find(m_soentries.begin(), m_soentries.end(), entry);
353 if (pos == m_soentries.end()) {
354 m_soentries.push_back(entry);
355 m_added_soentries.push_back(entry);
362 bool DYLDRendezvous::RemoveSOEntries() {
363 SOEntryList entry_list;
366 assert(m_previous.state == eDelete);
368 if (!TakeSnapshot(entry_list))
371 for (iterator I = begin(); I != end(); ++I) {
372 pos = std::find(entry_list.begin(), entry_list.end(), *I);
373 if (pos == entry_list.end())
374 m_removed_soentries.push_back(*I);
377 m_soentries = entry_list;
381 bool DYLDRendezvous::SOEntryIsMainExecutable(const SOEntry &entry) {
382 // On Linux the executable is indicated by an empty path in the entry. On
383 // FreeBSD and on Android it is the full path to the executable.
385 auto triple = m_process->GetTarget().GetArchitecture().GetTriple();
386 switch (triple.getOS()) {
387 case llvm::Triple::FreeBSD:
388 return entry.file_spec == m_exe_file_spec;
389 case llvm::Triple::Linux:
390 if (triple.isAndroid())
391 return entry.file_spec == m_exe_file_spec;
392 return !entry.file_spec;
398 bool DYLDRendezvous::TakeSnapshot(SOEntryList &entry_list) {
401 if (m_current.map_addr == 0)
404 // Clear previous entries since we are about to obtain an up to date list.
407 for (addr_t cursor = m_current.map_addr; cursor != 0; cursor = entry.next) {
408 if (!ReadSOEntryFromMemory(cursor, entry))
411 // Only add shared libraries and not the executable.
412 if (SOEntryIsMainExecutable(entry))
415 entry_list.push_back(entry);
421 addr_t DYLDRendezvous::ReadWord(addr_t addr, uint64_t *dst, size_t size) {
424 *dst = m_process->ReadUnsignedIntegerFromMemory(addr, size, 0, error);
431 addr_t DYLDRendezvous::ReadPointer(addr_t addr, addr_t *dst) {
434 *dst = m_process->ReadPointerFromMemory(addr, error);
438 return addr + m_process->GetAddressByteSize();
441 std::string DYLDRendezvous::ReadStringFromMemory(addr_t addr) {
445 if (addr == LLDB_INVALID_ADDRESS)
446 return std::string();
448 m_process->ReadCStringFromMemory(addr, str, error);
453 // Returns true if the load bias reported by the linker is incorrect for the
455 // function is used to handle cases where we want to work around a bug in the
457 static bool isLoadBiasIncorrect(Target &target, const std::string &file_path) {
458 // On Android L (API 21, 22) the load address of the "/system/bin/linker"
461 uint32_t os_major = 0, os_minor = 0, os_update = 0;
462 if (target.GetArchitecture().GetTriple().isAndroid() &&
463 target.GetPlatform()->GetOSVersion(os_major, os_minor, os_update) &&
464 (os_major == 21 || os_major == 22) &&
465 (file_path == "/system/bin/linker" ||
466 file_path == "/system/bin/linker64")) {
473 void DYLDRendezvous::UpdateBaseAddrIfNecessary(SOEntry &entry,
474 std::string const &file_path) {
475 // If the load bias reported by the linker is incorrect then fetch the load
476 // address of the file
477 // from the proc file system.
478 if (isLoadBiasIncorrect(m_process->GetTarget(), file_path)) {
479 lldb::addr_t load_addr = LLDB_INVALID_ADDRESS;
480 bool is_loaded = false;
482 m_process->GetFileLoadAddress(entry.file_spec, is_loaded, load_addr);
483 if (error.Success() && is_loaded)
484 entry.base_addr = load_addr;
488 bool DYLDRendezvous::ReadSOEntryFromMemory(lldb::addr_t addr, SOEntry &entry) {
491 entry.link_addr = addr;
493 if (!(addr = ReadPointer(addr, &entry.base_addr)))
496 // mips adds an extra load offset field to the link map struct on
497 // FreeBSD and NetBSD (need to validate other OSes).
498 // http://svnweb.freebsd.org/base/head/sys/sys/link_elf.h?revision=217153&view=markup#l57
499 const ArchSpec &arch = m_process->GetTarget().GetArchitecture();
500 if ((arch.GetTriple().getOS() == llvm::Triple::FreeBSD ||
501 arch.GetTriple().getOS() == llvm::Triple::NetBSD) &&
502 (arch.GetMachine() == llvm::Triple::mips ||
503 arch.GetMachine() == llvm::Triple::mipsel ||
504 arch.GetMachine() == llvm::Triple::mips64 ||
505 arch.GetMachine() == llvm::Triple::mips64el)) {
507 if (!(addr = ReadPointer(addr, &mips_l_offs)))
509 if (mips_l_offs != 0 && mips_l_offs != entry.base_addr)
513 if (!(addr = ReadPointer(addr, &entry.path_addr)))
516 if (!(addr = ReadPointer(addr, &entry.dyn_addr)))
519 if (!(addr = ReadPointer(addr, &entry.next)))
522 if (!(addr = ReadPointer(addr, &entry.prev)))
525 std::string file_path = ReadStringFromMemory(entry.path_addr);
526 entry.file_spec.SetFile(file_path, false);
528 UpdateBaseAddrIfNecessary(entry, file_path);
533 bool DYLDRendezvous::FindMetadata(const char *name, PThreadField field,
535 Target &target = m_process->GetTarget();
537 SymbolContextList list;
538 if (!target.GetImages().FindSymbolsWithNameAndType(ConstString(name),
539 eSymbolTypeAny, list))
542 Address address = list[0].symbol->GetAddress();
543 addr_t addr = address.GetLoadAddress(&target);
544 if (addr == LLDB_INVALID_ADDRESS)
548 value = (uint32_t)m_process->ReadUnsignedIntegerFromMemory(
549 addr + field * sizeof(uint32_t), sizeof(uint32_t), 0, error);
554 value /= 8; // convert bits to bytes
559 const DYLDRendezvous::ThreadInfo &DYLDRendezvous::GetThreadInfo() {
560 if (!m_thread_info.valid) {
563 ok &= FindMetadata("_thread_db_pthread_dtvp", eOffset,
564 m_thread_info.dtv_offset);
566 FindMetadata("_thread_db_dtv_dtv", eSize, m_thread_info.dtv_slot_size);
567 ok &= FindMetadata("_thread_db_link_map_l_tls_modid", eOffset,
568 m_thread_info.modid_offset);
569 ok &= FindMetadata("_thread_db_dtv_t_pointer_val", eOffset,
570 m_thread_info.tls_offset);
573 m_thread_info.valid = true;
576 return m_thread_info;
579 void DYLDRendezvous::DumpToLog(Log *log) const {
580 int state = GetState();
585 log->PutCString("DYLDRendezvous:");
586 log->Printf(" Address: %" PRIx64, GetRendezvousAddress());
587 log->Printf(" Version: %" PRIu64, GetVersion());
588 log->Printf(" Link : %" PRIx64, GetLinkMapAddress());
589 log->Printf(" Break : %" PRIx64, GetBreakAddress());
590 log->Printf(" LDBase : %" PRIx64, GetLDBase());
591 log->Printf(" State : %s",
592 (state == eConsistent)
594 : (state == eAdd) ? "add" : (state == eDelete) ? "delete"
597 iterator I = begin();
601 log->PutCString("DYLDRendezvous SOEntries:");
603 for (int i = 1; I != E; ++I, ++i) {
604 log->Printf("\n SOEntry [%d] %s", i, I->file_spec.GetCString());
605 log->Printf(" Base : %" PRIx64, I->base_addr);
606 log->Printf(" Path : %" PRIx64, I->path_addr);
607 log->Printf(" Dyn : %" PRIx64, I->dyn_addr);
608 log->Printf(" Next : %" PRIx64, I->next);
609 log->Printf(" Prev : %" PRIx64, I->prev);