// These all need to be static to avoid emitting // RELATIVE relocations for the part of the code running // before linker links itself.
/** The head of the list of all objects (including the executable and the linker itself), used for iteration. */ static soinfo* solist_head; /** The tail of the list of all objects (including the executable and the linker itself), used for insertion. */ static soinfo* solist_tail;
/** The main executable. */ static soinfo* somain; /** The linker. */ static soinfo* solinker; /** The vdso (can be null). */ static soinfo* vdso;
bool solist_remove_soinfo(soinfo* si) {
soinfo *prev = nullptr, *it; for (it = solist_get_head(); it != nullptr; it = it->next) { if (it == si) { break;
}
prev = it;
}
if (it == nullptr) {
DL_WARN("name \"%s\"@%p is not in solist!", si->get_realpath(), si); returnfalse;
}
// prev will never be null, nor the head of the list, // because the main executable and linker are first, // and they can't be removed.
CHECK(prev != nullptr);
CHECK(prev != solist_head);
prev->next = si->next; if (solist_tail == si) {
solist_tail = prev;
}
// Initializes an soinfo's link_map_head field using other fields from the // soinfo (phdr, phnum, load_bias). The soinfo's realpath must not change after // this function is called. staticvoid init_link_map_head(soinfo& info) { auto& map = info.link_map_head;
map.l_addr = info.load_bias;
map.l_name = const_cast<char*>(info.get_realpath());
phdr_table_get_dynamic_section(info.phdr, info.phnum, info.load_bias, &map.l_ld, nullptr);
}
// Stat "/proc/self/exe" instead of executable_path because // the executable could be unlinked by this point and it should // not cause a crash (see http://b/31084669) if (TEMP_FAILURE_RETRY(stat(exe_path, &result.file_stat)) == -1) { // Fallback to argv[0] for the case where /proc isn't available if (TEMP_FAILURE_RETRY(stat(arg_path, &result.file_stat)) == -1) {
async_safe_fatal("unable to stat either \"/proc/self/exe\" or \"%s\": %m", arg_path);
}
exe_path = arg_path;
}
// Path might be a symlink; we need the target so that we get the right // linker configuration later. char sym_path[PATH_MAX];
result.path = std::string(realpath(exe_path, sym_path) != nullptr ? sym_path : exe_path);
// Load an executable. Normally the kernel has already loaded the executable when the linker // starts. The linker can be invoked directly on an executable, though, and then the linker must // load it. This function doesn't load dependencies or resolve relocations. static ExecutableInfo load_executable(constchar* orig_path) {
ExecutableInfo result = {};
// These should have been sanitized by __libc_init_AT_SECURE, but the test // doesn't cost us anything. constchar* ldpath_env = nullptr; constchar* ldpreload_env = nullptr; if (!getauxval(AT_SECURE)) {
ldpath_env = getenv("LD_LIBRARY_PATH"); if (ldpath_env != nullptr) {
LD_DEBUG(any, "[ LD_LIBRARY_PATH set to \"%s\" ]", ldpath_env);
}
ldpreload_env = getenv("LD_PRELOAD"); if (ldpreload_env != nullptr) {
LD_DEBUG(any, "[ LD_PRELOAD set to \"%s\" ]", ldpreload_env);
}
}
// Initialize the main exe's soinfo. // TODO: lose `si` and go straight to somain for clarity.
soinfo* si = soinfo_alloc(&g_default_namespace,
exe_info.path.c_str(), &exe_info.file_stat, 0, RTLD_GLOBAL);
somain = si;
si->phdr = exe_info.phdr;
si->phnum = exe_info.phdr_count;
si->set_should_pad_segments(exe_info.should_pad_segments);
get_elf_base_from_phdr(si->phdr, si->phnum, &si->base, &si->load_bias);
si->size = phdr_table_get_load_size(si->phdr, si->phnum);
si->dynamic = nullptr;
si->set_main_executable();
init_link_map_head(*si);
set_bss_vma_name(si);
// Add the linker's soinfo. // We need to do this manually because it's placement-new'ed by get_libdl_info(), // not created by soinfo_alloc() like everything else. // We do it here because we want it to come after the executable in solist.
solist_add_soinfo(solinker);
// Use the executable's PT_INTERP string as the solinker filename in the // dynamic linker's module list. gdb reads both PT_INTERP and the module list, // and if the paths for the linker are different, gdb will report that the // PT_INTERP linker path was unloaded once the module list is initialized. // There are three situations to handle: // - the APEX linker (/system/bin/linker[64] -> /apex/.../linker[64]) // - the ASAN linker (/system/bin/linker_asan[64] -> /apex/.../linker[64]) // - the bootstrap linker (/system/bin/bootstrap/linker[64]) constchar *interp = phdr_table_get_interpreter_name(somain->phdr, somain->phnum,
somain->load_bias); if (interp == nullptr) { // This case can happen if the linker attempts to execute itself // (e.g. "linker64 /system/bin/linker64"). #ifdefined(__LP64__) #define DEFAULT_INTERP "/system/bin/linker64" #else #define DEFAULT_INTERP "/system/bin/linker" #endif
interp = DEFAULT_INTERP;
}
solinker->set_realpath(interp);
init_link_map_head(*solinker);
init_sanitizer_mode(interp);
if (exe_to_load == nullptr) { // Kernel does not add PROT_BTI to executable pages of the loaded ELF. // Apply appropriate protections here if it is needed. auto note_gnu_property = GnuPropertySection(somain); if (note_gnu_property.IsBTICompatible() &&
(phdr_table_protect_segments(
somain->phdr, somain->phnum, somain->load_bias, somain->should_pad_segments(),
somain->should_use_16kib_app_compat(), ¬e_gnu_property) < 0)) {
__linker_error("error: can't protect segments for \"%s\": %m", exe_info.path.c_str());
}
} #endif
// Register the main executable and the linker upfront to have // gdb aware of them before loading the rest of the dependency // tree. // // gdb expects the linker to be in the debug shared object list. // Without this, gdb has trouble locating the linker's ".text" // and ".plt" sections. Gdb could also potentially use this to // relocate the offset of our exported 'rtld_db_dlactivity' symbol. //
insert_link_map_into_debug_map(&somain->link_map_head);
insert_link_map_into_debug_map(&solinker->link_map_head);
// For security reasons we dropped non-PIE support in API level 21, // and the NDK no longer supports earlier API levels. if (elf_hdr->e_type != ET_DYN) {
__linker_error("error: %s: Android only supports position-independent " "executables (-fPIE)", exe_info.path.c_str());
}
// Use LD_LIBRARY_PATH and LD_PRELOAD (but only if we aren't setuid/setgid).
parse_LD_LIBRARY_PATH(ldpath_env);
parse_LD_PRELOAD(ldpreload_env);
if (!si->prelink_image()) __linker_cannot_link(g_argv[0]);
// add somain to global group
si->set_dt_flags_1(si->get_dt_flags_1() | DF_1_GLOBAL); // ... and add it to all other linked namespaces for (auto linked_ns : namespaces) { if (linked_ns != &g_default_namespace) {
linked_ns->add_soinfo(somain);
somain->add_secondary_namespace(linked_ns);
}
}
// Exit early for ldd. We don't want to run the code that was loaded, so skip // the constructor calls. Skip CFI setup because it would call __cfi_init in // libdl.so. if (g_is_ldd) _exit(EXIT_SUCCESS);
#ifdefined(__aarch64__) // This has to happen after the find_libraries, which will have collected any possible // libraries that request memtag_stack in the dynamic section.
__libc_init_mte_stack(args.argv); #endif
// Magic linker-provided pointer to the ELF header. // Hidden so it's accessible before linker relocations have been processed. extern"C"const ElfW(Ehdr) __ehdr_start __attribute__((__visibility__("hidden")));
staticvoid relocate_linker() { // The linker should only have relative relocations (in RELR) and IRELATIVE // relocations. Find the IRELATIVE relocations using the DT_JMPREL and // DT_PLTRELSZ, or DT_RELA/DT_RELASZ (DT_REL/DT_RELSZ on ILP32). auto ehdr = reinterpret_cast<ElfW(Addr)>(&__ehdr_start); auto* phdr = reinterpret_cast<ElfW(Phdr)*>(ehdr + __ehdr_start.e_phoff); for (size_t i = 0; i != __ehdr_start.e_phnum; ++i) { if (phdr[i].p_type != PT_DYNAMIC) { continue;
} auto *dyn = reinterpret_cast<ElfW(Dyn)*>(ehdr + phdr[i].p_vaddr);
ElfW(Addr) relr = 0, relrsz = 0, pltrel = 0, pltrelsz = 0, rel = 0, relsz = 0; for (size_t j = 0, size = phdr[i].p_filesz / sizeof(ElfW(Dyn)); j != size; ++j) { constauto tag = dyn[j].d_tag; constauto val = dyn[j].d_un.d_ptr; // We don't currently handle IRELATIVE relocations in DT_ANDROID_REL[A]. // We disabled DT_ANDROID_REL[A] at build time; verify that it was actually disabled.
CHECK(tag != DT_ANDROID_REL && tag != DT_ANDROID_RELA); if (tag == DT_RELR || tag == DT_ANDROID_RELR) {
relr = val;
} elseif (tag == DT_RELRSZ || tag == DT_ANDROID_RELRSZ) {
relrsz = val;
} elseif (tag == DT_JMPREL) {
pltrel = val;
} elseif (tag == DT_PLTRELSZ) {
pltrelsz = val;
} elseif (tag == kRelTag) {
rel = val;
} elseif (tag == kRelSzTag) {
relsz = val;
}
} // Apply RELR relocations first so that the GOT is initialized for ifunc // resolvers. if (relr && relrsz) { // Nothing has tagged the memtag globals here, so it is pointless either // way to handle them, the tags will be zero anyway. // That is moot though, because the linker does not use memtag_globals // in the first place.
relocate_relr(reinterpret_cast<ElfW(Relr*)>(ehdr + relr), reinterpret_cast<ElfW(Relr*)>(ehdr + relr + relrsz), ehdr, /*has_memtag_globals=*/ false);
} if (pltrel && pltrelsz) {
call_ifunc_resolvers_for_section(reinterpret_cast<RelType*>(ehdr + pltrel), reinterpret_cast<RelType*>(ehdr + pltrel + pltrelsz));
} if (rel && relsz) {
call_ifunc_resolvers_for_section(reinterpret_cast<RelType*>(ehdr + rel), reinterpret_cast<RelType*>(ehdr + rel + relsz));
}
}
}
// Usable before ifunc resolvers have been called. This function is compiled with -ffreestanding. staticvoid linker_memclr(void* dst, size_t cnt) { for (size_t i = 0; i < cnt; ++i) { reinterpret_cast<char*>(dst)[i] = '\0';
}
}
// Remapping MTE globals segments happens before the linker relocates itself, and so can't use // memcpy() from string.h. This function is compiled with -ffreestanding. void linker_memcpy(void* dst, constvoid* src, size_t n) { char* dst_bytes = reinterpret_cast<char*>(dst); constchar* src_bytes = reinterpret_cast<constchar*>(src); for (size_t i = 0; i < n; ++i) {
dst_bytes[i] = src_bytes[i];
}
}
// Detect an attempt to run the linker on itself. e.g.: // /system/bin/linker64 /system/bin/linker64 // Use priority-1 to run this constructor before other constructors.
__attribute__((constructor(1))) staticvoid detect_self_exec() { // Normally, the linker initializes the auxv global before calling its // constructors. If the linker loads itself, though, the first loader calls // the second loader's constructors before calling __linker_init. if (__libc_shared_globals()->auxv != nullptr) { return;
} #ifdefined(__i386__) // We don't have access to the auxv struct from here, so use the int 0x80 // fallback.
__libc_sysinfo = reinterpret_cast<void*>(__libc_int0x80); #endif
__linker_error("error: linker cannot load itself");
}
/* *Thisistheentrypointforthelinker,calledfrombegin.S.This *methodisresponsibleforfixingthelinker'sownrelocations,and *thencalling__linker_init_post_relocation(). * *Becausethismethodiscalledbeforethelinkerhasfixedit'sown *relocations,anyattempttoreferenceanexternvariable,extern *function,orotherGOTreferencewillgenerateasegfault.
*/ extern"C" ElfW(Addr) __linker_init(void* raw_args) { // Unlock the loader mutex immediately before transferring to the executable's // entry point. This must happen after destructors are called in this function // (e.g. ~soinfo), so declare this variable very early. struct DlMutexUnlocker {
~DlMutexUnlocker() { pthread_mutex_unlock(&g_dl_mutex); }
} unlocker;
// Initialize TLS early so system calls and errno work.
KernelArgumentBlock args(raw_args);
bionic_tcb temp_tcb __attribute__((uninitialized));
linker_memclr(&temp_tcb, sizeof(temp_tcb));
__libc_init_main_thread_early(args, &temp_tcb);
// When the linker is run by itself (rather than as an interpreter for // another program), AT_BASE is 0.
ElfW(Addr) linker_addr = getauxval(AT_BASE); if (linker_addr == 0) { // The AT_PHDR and AT_PHNUM aux values describe this linker instance, so use // the phdr to find the linker's base address.
ElfW(Addr) load_bias;
get_elf_base_from_phdr( reinterpret_cast<ElfW(Phdr)*>(getauxval(AT_PHDR)), getauxval(AT_PHNUM),
&linker_addr, &load_bias);
}
// Relocate the linker. This step will initialize the GOT, which is needed for // accessing non-hidden global variables. (On some targets, the stack // protector uses GOT accesses rather than TLS.) Relocating the linker will // also call the linker's ifunc resolvers so that string.h functions can be // used.
relocate_linker();
if (!tmp_linker_so.prelink_image()) __linker_cannot_link(args.argv[0]); // There is special logic in soinfo::relocate to avoid duplicating the // relocations we did in relocate_linker(). if (!tmp_linker_so.link_image(SymbolLookupList(&tmp_linker_so), &tmp_linker_so, nullptr, nullptr)) __linker_cannot_link(args.argv[0]);
// We didn't protect the linker's RELRO pages in link_image because we // couldn't make system calls on x86 at that point, but we can now... if (!tmp_linker_so.protect_relro()) __linker_cannot_link(args.argv[0]);
// And we can set VMA name for the bss section now
set_bss_vma_name(&tmp_linker_so);
// Initialize the linker's static libc's globals
__libc_init_globals();
// A constructor could spawn a thread that calls into the loader, so as soon // as we've called a constructor, we need to hold the lock until transferring // to the entry point.
pthread_mutex_lock(&g_dl_mutex);
// Initialize the linker's own global variables
tmp_linker_so.call_constructors();
// Setting the linker soinfo's soname can allocate heap memory, so delay it until here. for (const ElfW(Dyn)* d = tmp_linker_so.dynamic; d->d_tag != DT_NULL; ++d) { if (d->d_tag == DT_SONAME) {
tmp_linker_so.set_soname(tmp_linker_so.get_string(d->d_un.d_val));
}
}
// When the linker is run directly rather than acting as PT_INTERP, parse // arguments and determine the executable to load. When it's instead acting // as PT_INTERP, AT_ENTRY will refer to the loaded executable rather than the // linker's _start. constchar* exe_to_load = nullptr; if (getauxval(AT_ENTRY) == reinterpret_cast<uintptr_t>(&_start)) { if (args.argc == 3 && !strcmp(args.argv[1], "--list")) { // We're being asked to behave like ldd(1).
g_is_ldd = true;
exe_to_load = args.argv[2];
} elseif (args.argc <= 1 || !strcmp(args.argv[1], "--help")) {
async_safe_format_fd(STDOUT_FILENO, "Usage: %s [--list] PROGRAM [ARGS-FOR-PROGRAM...]\n" " %s [--list] path.zip!/PROGRAM [ARGS-FOR-PROGRAM...]\n" "\n" "A helper program for linking dynamic executables. Typically, the kernel loads\n" "this program because it's the PT_INTERP of a dynamic executable.\n" "\n" "This program can also be run directly to load and run a dynamic executable. The\n" "executable can be inside a zip file if it's stored uncompressed and at a\n" "page-aligned offset.\n" "\n" "The --list option gives behavior equivalent to ldd(1) on other systems.\n",
args.argv[0], args.argv[0]);
_exit(EXIT_SUCCESS);
} else {
exe_to_load = args.argv[1];
__libc_shared_globals()->initial_linker_arg_count = 1;
}
}
// Store argc/argv/envp to use them for calling constructors.
g_argc = args.argc - __libc_shared_globals()->initial_linker_arg_count;
g_argv = args.argv + __libc_shared_globals()->initial_linker_arg_count;
g_envp = args.envp;
__libc_shared_globals()->init_progname = g_argv[0];
// Return the address that the calling assembly stub should jump to.
LD_DEBUG(any, "[ Jumping to _start (%p)... ]", reinterpret_cast<void*>(start_address)); return start_address;
}
Messung V0.5 in Prozent
¤ Dauer der Verarbeitung: 0.15 Sekunden
(vorverarbeitet am 2026-06-28)
¤
Die Informationen auf dieser Webseite wurden
nach bestem Wissen sorgfältig zusammengestellt. Es wird jedoch weder Vollständigkeit, noch Richtigkeit,
noch Qualität der bereit gestellten Informationen zugesichert.
Bemerkung:
Die farbliche Syntaxdarstellung und die Messung sind noch experimentell.