if (kPageSize == 16 * 1024 && min_align_ < kPageSize) { // This prop needs to be read on 16KiB devices for each ELF where min_align_ is less than // 16KiB. It cannot be cached since the developer may toggle app compat on/off. This check will // be removed once app compat is made the default on 16KiB devices. auto compat_prop_val =
::android::base::GetProperty("bionic.linker.16kb.app_compat.enabled", "false");
using ::android::base::ParseBool; using ::android::base::ParseBoolResult;
if (rc != sizeof(header_)) {
DL_ERR("\"%s\" is too small to be an ELF executable: only found %zd bytes", name_.c_str(), static_cast<size_t>(rc)); returnfalse;
} returntrue;
}
staticconstchar* EM_to_string(int em) { if (em == EM_386) return"EM_386"; if (em == EM_AARCH64) return"EM_AARCH64"; if (em == EM_ARM) return"EM_ARM"; if (em == EM_RISCV) return"EM_RISCV"; if (em == EM_X86_64) return"EM_X86_64"; return"EM_???";
}
bool ElfReader::VerifyElfHeader() { if (memcmp(header_.e_ident, ELFMAG, SELFMAG) != 0) {
DL_ERR("\"%s\" has bad ELF magic: %02x%02x%02x%02x", name_.c_str(),
header_.e_ident[0], header_.e_ident[1], header_.e_ident[2], header_.e_ident[3]); returnfalse;
}
// Try to give a clear diagnostic for ELF class mismatches, since they're // an easy mistake to make during the 32-bit/64-bit transition period. int elf_class = header_.e_ident[EI_CLASS]; #ifdefined(__LP64__) if (elf_class != ELFCLASS64) { if (elf_class == ELFCLASS32) {
DL_ERR("\"%s\" is 32-bit instead of 64-bit", name_.c_str());
} else {
DL_ERR("\"%s\" has unknown ELF class: %d", name_.c_str(), elf_class);
} returnfalse;
} #else if (elf_class != ELFCLASS32) { if (elf_class == ELFCLASS64) {
DL_ERR("\"%s\" is 64-bit instead of 32-bit", name_.c_str());
} else {
DL_ERR("\"%s\" has unknown ELF class: %d", name_.c_str(), elf_class);
} returnfalse;
} #endif
if (header_.e_ident[EI_DATA] != ELFDATA2LSB) {
DL_ERR("\"%s\" not little-endian: %d", name_.c_str(), header_.e_ident[EI_DATA]); returnfalse;
}
if (header_.e_type != ET_DYN) {
DL_ERR("\"%s\" has unexpected e_type: %d", name_.c_str(), header_.e_type); returnfalse;
}
if (header_.e_version != EV_CURRENT) {
DL_ERR("\"%s\" has unexpected e_version: %d", name_.c_str(), header_.e_version); returnfalse;
}
if (header_.e_machine != GetTargetElfMachine()) {
DL_ERR("\"%s\" is for %s (%d) instead of %s (%d)",
name_.c_str(),
EM_to_string(header_.e_machine), header_.e_machine,
EM_to_string(GetTargetElfMachine()), GetTargetElfMachine()); returnfalse;
}
if (header_.e_shentsize != sizeof(ElfW(Shdr))) { if (DL_ERROR_AFTER(26, "\"%s\" has unsupported e_shentsize: 0x%x (expected 0x%zx)",
name_.c_str(), header_.e_shentsize, sizeof(ElfW(Shdr)))) { returnfalse;
}
add_dlwarning(name_.c_str(), "has invalid ELF header");
}
if (header_.e_shstrndx == 0) { if (DL_ERROR_AFTER(26, "\"%s\" has invalid e_shstrndx", name_.c_str())) { returnfalse;
}
add_dlwarning(name_.c_str(), "has invalid ELF header");
}
// Only header can be located at the 0 offset... This function called to // check DYNSYM and DYNAMIC sections and phdr/shdr - none of them can be // at offset 0.
// Loads the program header table from an ELF file into a read-only private // anonymous mmap-ed block. bool ElfReader::ReadProgramHeaders() {
phdr_num_ = header_.e_phnum;
// Like the kernel, we only accept program header tables that // are smaller than 64KiB. if (phdr_num_ < 1 || phdr_num_ > 65536/sizeof(ElfW(Phdr))) {
DL_ERR("\"%s\" has invalid e_phnum: %zd", name_.c_str(), phdr_num_); returnfalse;
}
if (!CheckFileRange(strtab_shdr->sh_offset, strtab_shdr->sh_size, alignof(constchar))) {
DL_ERR_AND_LOG("\"%s\" has invalid offset/size of the .strtab section linked from .dynamic section",
name_.c_str()); returnfalse;
}
for (size_t i = 0; i < phdr_num_; ++i) { const ElfW(Phdr)* phdr = &phdr_table_[i];
if (phdr->p_type != PT_LOAD) { continue;
}
// For loadable segments, p_align must be 0, 1, // or a positive, integral power of two. // The kernel ignores loadable segments with other values, // so we just warn rather than reject them. if (!powerof2(phdr->p_align)) {
DL_WARN("\"%s\" has invalid p_align %zx in phdr %zu", name_.c_str(), static_cast<size_t>(phdr->p_align), i); continue;
}
if (kPageSize == 16 * 1024) FixMinAlignFor16KiB();
returntrue;
}
// Reserve a virtual address range such that if it's limits were extended to the next 2**align // boundary, it would not overlap with any existing mappings. staticvoid* ReserveWithAlignmentPadding(size_t size, size_t mapping_align, size_t start_align, void** out_gap_start, size_t* out_gap_size) { int mmap_flags = MAP_PRIVATE | MAP_ANONYMOUS; // Reserve enough space to properly align the library's start address.
mapping_align = std::max(mapping_align, start_align); if (mapping_align == page_size()) { void* mmap_ptr = mmap(nullptr, size, PROT_NONE, mmap_flags, -1, 0); if (mmap_ptr == MAP_FAILED) { return nullptr;
} return mmap_ptr;
}
#ifdefined(__LP64__) // Minimum alignment of shared library gap. For efficiency, this should match the second level // page size of the platform.
constexpr size_t kGapAlignment = 2 * 1024 * 1024; // Maximum gap size, in the units of kGapAlignment.
constexpr size_t kMaxGapUnits = 32; #endif // Allocate enough space so that the end of the desired region aligned up is still inside the // mapping.
size_t mmap_size = __builtin_align_up(size, mapping_align) + mapping_align - page_size();
uint8_t* mmap_ptr = reinterpret_cast<uint8_t*>(mmap(nullptr, mmap_size, PROT_NONE, mmap_flags, -1, 0)); if (mmap_ptr == MAP_FAILED) { return nullptr;
}
size_t gap_size = 0; #ifdefined(__LP64__)
size_t first_byte = reinterpret_cast<size_t>(__builtin_align_up(mmap_ptr, mapping_align));
size_t last_byte = reinterpret_cast<size_t>(__builtin_align_down(mmap_ptr + mmap_size, mapping_align) - 1); if (first_byte / kGapAlignment != last_byte / kGapAlignment) { // This library crosses a 2MB boundary and will fragment a new huge page. // Lets take advantage of that and insert a random number of inaccessible huge pages before that // to improve address randomization and make it harder to locate this library code by probing.
munmap(mmap_ptr, mmap_size);
mapping_align = std::max(mapping_align, kGapAlignment);
gap_size = kGapAlignment * (__libc_arc4random_uniform_or_zero(kMaxGapUnits - 1) + 1);
mmap_size = __builtin_align_up(size + gap_size, mapping_align) + mapping_align - page_size();
mmap_ptr = reinterpret_cast<uint8_t*>(mmap(nullptr, mmap_size, PROT_NONE, mmap_flags, -1, 0)); if (mmap_ptr == MAP_FAILED) { return nullptr;
}
} #endif
uint8_t* first = __builtin_align_up(mmap_ptr, mapping_align);
uint8_t* last = __builtin_align_down(gap_start, mapping_align) - size;
size_t n = __libc_arc4random_uniform_or_zero((last - first) / start_align + 1);
uint8_t* start = first + n * start_align; // Unmap the extra space around the allocation. // Keep it mapped PROT_NONE on 64-bit targets where address space is plentiful to make it harder // to defeat ASLR by probing for readable memory mappings.
munmap(mmap_ptr, start - mmap_ptr);
munmap(start + size, gap_start - (start + size)); if (gap_end != mmap_ptr + mmap_size) {
munmap(gap_end, mmap_ptr + mmap_size - gap_end);
}
*out_gap_start = gap_start;
*out_gap_size = gap_size; return start;
}
// Reserve a virtual address range big enough to hold all loadable // segments of a program header table. This is done by creating a // private anonymous mmap() with PROT_NONE. bool ElfReader::ReserveAddressSpace(address_space_params* address_space) {
ElfW(Addr) min_vaddr;
load_size_ = phdr_table_get_load_size(phdr_table_, phdr_num_, &min_vaddr); if (load_size_ == 0) {
DL_ERR("\"%s\" has no loadable segments", name_.c_str()); returnfalse;
}
if (should_use_16kib_app_compat_) { // Reserve additional space for aligning the permission boundary in compat loading // Up to kPageSize-kCompatPageSize additional space is needed, but reservation // is done with mmap which gives kPageSize multiple-sized reservations.
load_size_ += kPageSize;
}
if (load_size_ > address_space->reserved_size) { if (address_space->must_use_address) {
DL_ERR("reserved address space %zd smaller than %zd bytes needed for \"%s\"",
load_size_ - address_space->reserved_size, load_size_, name_.c_str()); returnfalse;
}
size_t start_alignment = page_size(); if (get_transparent_hugepages_supported() && get_application_target_sdk_version() >= 31) { // Limit alignment to PMD size as other alignments reduce the number of // bits available for ASLR for no benefit.
start_alignment = max_align_ == kPmdSize ? kPmdSize : page_size();
}
start = ReserveWithAlignmentPadding(load_size_, kLibraryAlignment, start_alignment, &gap_start_,
&gap_size_); if (start == nullptr) {
DL_ERR("couldn't reserve %zd bytes of address space for \"%s\"", load_size_, name_.c_str()); returnfalse;
}
} else {
start = address_space->start_addr;
gap_start_ = nullptr;
gap_size_ = 0;
mapped_by_caller_ = true;
// Update the reserved address space to subtract the space used by this library.
address_space->start_addr = reinterpret_cast<uint8_t*>(address_space->start_addr) + load_size_;
address_space->reserved_size -= load_size_;
}
if (should_use_16kib_app_compat_) { // In compat mode make the initial mapping RW since the ELF contents will be read // into it; instead of mapped over it.
mprotect(reinterpret_cast<void*>(start), load_size_, PROT_READ | PROT_WRITE);
}
// Find the ELF note of type NT_ANDROID_TYPE_PAD_SEGMENT and check that the desc value is 1. bool ElfReader::ReadPadSegmentNote() { if (!page_size_migration_supported()) { // Don't attempt to read the note, since segment extension isn't // supported; but return true so that loading can continue normally. returntrue;
}
// The ELF can have multiple PT_NOTE's, check them all for (size_t i = 0; i < phdr_num_; ++i) { const ElfW(Phdr)* phdr = &phdr_table_[i];
if (phdr->p_type != PT_NOTE) { continue;
}
// Some obfuscated ELFs may contain "empty" PT_NOTE program headers that don't // point to any part of the ELF (p_memsz == 0). Skip these since there is // nothing to decode. See: b/324468126 if (phdr->p_memsz == 0) { continue;
}
// Reject notes that claim to extend past the end of the file.
off64_t note_end_off = file_offset_; if (__builtin_add_overflow(note_end_off, phdr->p_offset, ¬e_end_off) ||
__builtin_add_overflow(note_end_off, phdr->p_filesz, ¬e_end_off) ||
phdr->p_filesz != phdr->p_memsz ||
note_end_off > file_size_) {
if (get_application_target_sdk_version() < 37) { // Some in-market apps have invalid ELF notes (http://b/390328213), // so ignore them until/unless they bump their target sdk version. continue;
}
DL_ERR_AND_LOG("\"%s\": ELF note (phdr %zu) runs off end of file", name_.c_str(), i); returnfalse;
}
// We scope note_fragment to within the loop so that there is // at most one PT_NOTE mapped at any time.
MappedFileFragment note_fragment; if (!note_fragment.Map(fd_, file_offset_, phdr->p_offset, phdr->p_filesz)) {
DL_ERR("\"%s\": PT_NOTE mmap(nullptr, %p, PROT_READ, MAP_PRIVATE, %d, %p) failed: %m",
name_.c_str(), reinterpret_cast<void*>(phdr->p_filesz), fd_, reinterpret_cast<void*>(page_start(file_offset_ + phdr->p_offset))); returnfalse;
}
// Don't do segment extension for p_align > 64KiB, such ELFs already existed in the // field e.g. 2MiB p_align for THPs and are relatively small in number. // // The kernel can only represent padding for p_align up to 64KiB. This is because // the kernel uses 4 available bits in the vm_area_struct to represent padding // extent; and so cannot enable mitigations to avoid breaking app compatibility for // p_aligns > 64KiB. // // Don't perform segment extension on these to avoid app compatibility issues. if (phdr->p_align <= kPageSize || phdr->p_align > 64*1024 || !should_pad_segments) { return;
}
if (next_idx < phdr_count && phdr_table[next_idx].p_type == PT_LOAD) {
next = &phdr_table[next_idx];
}
// If this is the last LOAD segment, no extension is needed if (!next || *p_memsz != *p_filesz) { return;
}
// If adjacent segment mappings overlap, no extension is needed. if (curr_end >= next_start) { return;
}
// Extend the LOAD segment mapping to be contiguous with that of // the next LOAD segment.
ElfW(Addr) extend = next_start - curr_end;
*p_memsz += extend;
*p_filesz += extend;
}
// The ELF could be being loaded directly from a zipped APK, // the zip offset must be added to find the segment offset. const ElfW(Addr) offset = file_offset_ + page_start(phdr->p_offset);
// Mark segments as huge page eligible if they meet the requirements if ((phdr->p_flags & PF_X) && phdr->p_align == kPmdSize &&
get_transparent_hugepages_supported()) {
madvise(seg_addr, len, MADV_HUGEPAGE);
}
returntrue;
}
void ElfReader::ZeroFillSegment(const ElfW(Phdr)* phdr) { // NOTE: In 16KiB app compat mode, the ELF mapping is anonymous, meaning that // RW segments are COW-ed from the kernel's zero page. So there is no need to // explicitly zero-fill until the last page's limit. if (should_use_16kib_app_compat_) { return;
}
// If the segment is writable, and does not end on a page boundary, // zero-fill it until the page limit. // // Do not attempt to zero the extended region past the first partial page, // since doing so may: // 1) Result in a SIGBUS, as the region is not backed by the underlying // file. // 2) Break the COW backing, faulting in new anon pages for a region // that will not be used. if ((phdr->p_flags & PF_W) != 0 && page_offset(unextended_seg_file_end) > 0) {
memset(reinterpret_cast<void*>(unextended_seg_file_end), 0,
kPageSize - page_offset(unextended_seg_file_end));
}
}
void ElfReader::DropPaddingPages(const ElfW(Phdr)* phdr, uint64_t seg_file_end) { // NOTE: Padding pages are only applicable where the ELF's max-page-size > runtime page size; // 16KiB compat mode is the exact opposite scenario. if (should_use_16kib_app_compat_) { return;
}
// Pages may be brought in due to readahead. // Drop the padding (zero) pages, to avoid reclaim work later. // // NOTE: The madvise() here is special, as it also serves to hint to the // kernel the portion of the LOAD segment that is padding. // // See: [1] https://android-review.googlesource.com/c/kernel/common/+/3032411 // [2] https://android-review.googlesource.com/c/kernel/common/+/3048835 if (madvise(reinterpret_cast<void*>(pad_start), pad_len, MADV_DONTNEED)) {
DL_WARN("\"%s\": madvise(0x%" PRIx64 ", 0x%" PRIx64 ", MADV_DONTNEED) failed: %m",
name_.c_str(), pad_start, pad_len);
}
}
bool ElfReader::MapBssSection(const ElfW(Phdr)* phdr, ElfW(Addr) seg_page_end,
ElfW(Addr) seg_file_end) { // NOTE: We do not need to handle .bss in 16KiB compat mode since the mapping // reservation is anonymous and RW to begin with. if (should_use_16kib_app_compat_) { returntrue;
}
// seg_file_end is now the first page address after the file content.
seg_file_end = page_end(seg_file_end);
if (seg_page_end <= seg_file_end) { returntrue;
}
// If seg_page_end is larger than seg_file_end, we need to zero // anything between them. This is done by using a private anonymous // map for all extra pages
size_t zeromap_size = seg_page_end - seg_file_end; void* zeromap =
mmap(reinterpret_cast<void*>(seg_file_end), zeromap_size, PFLAGS_TO_PROT(phdr->p_flags),
MAP_FIXED | MAP_ANONYMOUS | MAP_PRIVATE, -1, 0); if (zeromap == MAP_FAILED) {
DL_ERR("couldn't map .bss section for \"%s\": %m", name_.c_str()); returnfalse;
}
// Set the VMA name using prctl
prctl(PR_SET_VMA, PR_SET_VMA_ANON_NAME, zeromap, zeromap_size, ".bss");
returntrue;
}
bool ElfReader::LoadSegments() { // NOTE: The compat(legacy) page size (4096) must be used when aligning // the 4KiB segments for loading in compat mode. The larger 16KiB page size // will lead to overwriting adjacent segments since the ELF's segment(s) // are not 16KiB aligned.
size_t seg_align = should_use_16kib_app_compat_ ? kCompatPageSize : kPageSize;
// Only enforce this on 16 KB systems with app compat disabled. // Apps may rely on undefined behavior here on 4 KB systems, // which is the norm before this change is introduced if (kPageSize >= 16384 && min_align_ < kPageSize && !should_use_16kib_app_compat_) {
std::string err_msg = android::base::StringPrintf( "\"%s\" program alignment (%zu) cannot be smaller than system page size (%zu)",
name_.c_str(), min_align_, kPageSize);
DL_ERR_AND_LOG("%s", err_msg.c_str());
if (dlopen_16kib_err_is_fatal_) {
android_set_abort_message(err_msg.c_str());
inline_raise(SIGABRT);
}
returnfalse;
}
if (!Setup16KiBAppCompat()) returnfalse;
for (size_t i = 0; i < phdr_num_; ++i) { const ElfW(Phdr)* phdr = &phdr_table_[i];
if (file_start + phdr->p_filesz > static_cast<size_t>(file_size_)) {
DL_ERR("invalid ELF file \"%s\" load segment[%zd]:" " p_offset (%p) + p_filesz (%p) ( = %p) past end of file (0x%" PRIx64 ")",
name_.c_str(), i, reinterpret_cast<void*>(phdr->p_offset), reinterpret_cast<void*>(phdr->p_filesz), reinterpret_cast<void*>(file_start + phdr->p_filesz), file_size_); returnfalse;
}
if (file_length != 0) { int prot = PFLAGS_TO_PROT(phdr->p_flags); if ((prot & (PROT_EXEC | PROT_WRITE)) == (PROT_EXEC | PROT_WRITE)) { if (DL_ERROR_AFTER(26, "\"%s\" has load segments that are both writable and executable",
name_.c_str())) { returnfalse;
}
add_dlwarning(name_.c_str(), "W+E load segments");
}
// Pass the file_length, since it may have been extended by _extend_load_segment_vma(). if (should_use_16kib_app_compat_) { if (!CompatMapSegment(i, file_length)) { returnfalse;
}
} else { if (!MapSegment(i, file_length)) { returnfalse;
}
}
}
ZeroFillSegment(phdr);
DropPaddingPages(phdr, seg_file_end);
if (!MapBssSection(phdr, seg_page_end, seg_file_end)) { returnfalse;
}
} returntrue;
}
/* Used internally. Used to set the protection bits of all loaded segments *withoptionalextraflags(i.e.reallyPROT_WRITE).Usedby *phdr_table_protect_segmentsandphdr_table_unprotect_segments.
*/ staticint _phdr_table_set_load_prot(const ElfW(Phdr)* phdr_table, size_t phdr_count,
ElfW(Addr) load_bias, int extra_prot_flags, bool should_pad_segments) { for (size_t i = 0; i < phdr_count; ++i) { const ElfW(Phdr)* phdr = &phdr_table[i];
int prot = PFLAGS_TO_PROT(phdr->p_flags) | extra_prot_flags; if ((prot & PROT_WRITE) != 0) { // make sure we're never simultaneously writable / executable
prot &= ~PROT_EXEC;
} #ifdefined(__aarch64__) if ((prot & PROT_EXEC) == 0) { // Though it is not specified don't add PROT_BTI if segment is not // executable.
prot &= ~PROT_BTI;
} #endif
int ret =
mprotect(reinterpret_cast<void*>(seg_page_start), seg_page_end - seg_page_start, prot); if (ret < 0) { return -1;
}
} return0;
}
/* Restore the original protection modes for all loadable segments. *Youshouldonlycallthisafterphdr_table_unprotect_segmentsand *applyingallrelocations. * *AArch64:alsocalledfromlinker_mainandElfReader::Loadtoapply *PROT_BTIforloadedmainsoandotherso-s. * *Input: *phdr_table->programheadertable *phdr_count->numberofentriesintables *load_bias->loadbias *should_pad_segments->Aresegmentsextendedtoavoidgapsinthememorymap *should_use_16kib_app_compat->IstheELFbeingloadedin16KiBappcompatmode. *prop->GnuPropertySectionornullptr *Return: *0onsuccess,-1onfailure(errorcodeinerrno).
*/ int phdr_table_protect_segments(const ElfW(Phdr)* phdr_table, size_t phdr_count,
ElfW(Addr) load_bias, bool should_pad_segments, bool should_use_16kib_app_compat, const GnuPropertySection* prop __unused) { // Segment permissions are handled separately in 16KiB compatibility mode. if (should_use_16kib_app_compat) { return0;
}
staticbool segment_needs_memtag_globals_remapping(const ElfW(Phdr) * phdr) { // For now, MTE globals is only supported on writeable data segments. return phdr->p_type == PT_LOAD && !(phdr->p_flags & PF_X) && (phdr->p_flags & PF_W);
}
/* When MTE globals are requested by the binary, and when the hardware supports *it,remaptheexecutable'sPT_LOADdatapagestohavePROT_MTE. * *Returns0onsuccess,-1onfailure(errorcodeinerrno).
*/ int remap_memtag_globals_segments(const ElfW(Phdr) * phdr_table __unused,
size_t phdr_count __unused, ElfW(Addr) load_bias __unused) { #ifdefined(__aarch64__) for (const ElfW(Phdr)* phdr = phdr_table; phdr < phdr_table + phdr_count; phdr++) { if (!segment_needs_memtag_globals_remapping(phdr)) { continue;
}
int prot = PFLAGS_TO_PROT(phdr->p_flags); // For anonymous private mappings, it may be possible to simply mprotect() // the PROT_MTE flag over the top. For file-based mappings, this will fail, // and we'll need to fall back. We also allow PROT_WRITE here to allow // writing memory tags (in `soinfo::tag_globals()`), and set these sections // back to read-only after tags are applied (similar to RELRO).
prot |= PROT_MTE; if (mprotect(reinterpret_cast<void*>(seg_page_start), seg_page_aligned_size,
prot | PROT_WRITE) == 0) { continue;
}
// For file-based mappings that we're now forcing to be anonymous mappings, set the VMA name to // make debugging easier. // Once we are targeting only devices that run kernel 5.10 or newer (and thus include // https://android-review.git.corp.google.com/c/kernel/common/+/1934723 which causes the // VMA_ANON_NAME to be copied into the kernel), we can get rid of the storage here. // For now, that is not the case: // https://source.android.com/docs/core/architecture/kernel/android-common#compatibility-matrix
std::string& vma_name = vma_names->emplace_back(kVmaNameLimit, '\0'); // 18 characters are enough for the '+' prefix, 16 hex digits, and the null terminator. char suffix_buffer[18] = {};
async_safe_format_buffer(suffix_buffer, sizeof(suffix_buffer), "+%" PRIxPTR,
page_start(phdr->p_vaddr));
format_left_truncated_vma_anon_name(vma_name.data(), vma_name.size(), "mt:", soname,
suffix_buffer); if (prctl(PR_SET_VMA, PR_SET_VMA_ANON_NAME, reinterpret_cast<void*>(seg_page_start),
seg_page_aligned_size, vma_name.data()) != 0) {
DL_WARN("Failed to rename memtag global segment: %m");
}
}
}
/* Change the protection of all loaded segments in memory to writable. *Thisisusefulbeforeperformingrelocations.Oncecompleted,you *willhavetocallphdr_table_protect_segmentstorestoretheoriginal *protectionflagsonallsegments. * *Notethatsomewritablesegmentscanalsohavetheircontentturned *toread-onlybycallingphdr_table_protect_gnu_relro.Thisisno *performedhere. * *Input: *phdr_table->programheadertable *phdr_count->numberofentriesintables *load_bias->loadbias *should_pad_segments->Aresegmentsextendedtoavoidgapsinthememorymap *should_use_16kib_app_compat->IstheELFbeingloadedin16KiBappcompatmode. *Return: *0onsuccess,-1onfailure(errorcodeinerrno).
*/ int phdr_table_unprotect_segments(const ElfW(Phdr)* phdr_table, size_t phdr_count,
ElfW(Addr) load_bias, bool should_pad_segments, bool should_use_16kib_app_compat) { // Segment permissions are handled separately in 16KiB compatibility mode. Also in this case // binaries are mapped entirely RW until relro protection is applied, so they don't need to be // unprotected before performing dynamic relocations. if (should_use_16kib_app_compat) { return0;
}
staticinlinevoid _extend_gnu_relro_prot_end(const ElfW(Phdr)* relro_phdr, const ElfW(Phdr)* phdr_table, size_t phdr_count,
ElfW(Addr) load_bias, ElfW(Addr)* seg_page_end, bool should_pad_segments) { // Find the index and phdr of the LOAD containing the GNU_RELRO segment for (size_t index = 0; index < phdr_count; ++index) { const ElfW(Phdr)* phdr = &phdr_table[index];
if (phdr->p_type == PT_LOAD && phdr->p_vaddr == relro_phdr->p_vaddr) { // If the PT_GNU_RELRO mem size is not at least as large as the corresponding // LOAD segment mem size, we need to protect only a partial region of the // LOAD segment and therefore cannot avoid a VMA split. // // Note: Don't check the page-aligned mem sizes since the extended protection // may incorrectly write protect non-relocation data. // // Example: // // |---- 3K ----|-- 1K --|---- 3K ---- |-- 1K --| // ---------------------------------------------------------------- // | | | | | // SEG X | RO | RO | RW | | SEG Y // | | | | | // ---------------------------------------------------------------- // | | | // | | | // | | | // relro_vaddr relro_vaddr relro_vaddr // (load_vaddr) + + // relro_memsz load_memsz // // ---------------------------------------------------------------- // | PAGE | PAGE | // ---------------------------------------------------------------- // | Potential | // |----- Extended RO ----| // | Protection | // // If the check below uses page aligned mem sizes it will cause incorrect write // protection of the 3K RW part of the LOAD segment containing the GNU_RELRO. if (relro_phdr->p_memsz < phdr->p_memsz) { return;
}
// Attempt extending the VMA (mprotect range). Without extending the range, // mprotect will only RO protect a part of the extended RW LOAD segment, which // will leave an extra split RW VMA (the gap).
_extend_load_segment_vma(phdr_table, phdr_count, index, &p_memsz, &p_filesz,
should_pad_segments, /*should_use_16kib_app_compat=*/false);
/* Used internally by phdr_table_protect_gnu_relro and *phdr_table_unprotect_gnu_relro.
*/ staticint _phdr_table_set_gnu_relro_prot(const ElfW(Phdr)* phdr_table, size_t phdr_count,
ElfW(Addr) load_bias, int prot_flags, bool should_pad_segments) { const ElfW(Phdr)* phdr = phdr_table; const ElfW(Phdr)* phdr_limit = phdr + phdr_count;
for (phdr = phdr_table; phdr < phdr_limit; phdr++) { if (phdr->p_type != PT_GNU_RELRO) { continue;
}
// Tricky: what happens when the relro segment does not start // or end at page boundaries? We're going to be over-protective // here and put every page touched by the segment as read-only.
// Extract: // Note that the current dynamic linker code will only work // correctly if the PT_GNU_RELRO segment starts on a page // boundary. This is because the dynamic linker rounds the // p_vaddr field down to the previous page boundary. If // there is anything on the page which should not be read-only, // the program is likely to fail at runtime. So in effect the // linker must only emit a PT_GNU_RELRO segment if it ensures // that it starts on a page boundary.
ElfW(Addr) seg_page_start = page_start(phdr->p_vaddr) + load_bias;
ElfW(Addr) seg_page_end = page_end(phdr->p_vaddr + phdr->p_memsz) + load_bias;
_extend_gnu_relro_prot_end(phdr, phdr_table, phdr_count, load_bias, &seg_page_end,
should_pad_segments);
int ret = mprotect(reinterpret_cast<void*>(seg_page_start),
seg_page_end - seg_page_start,
prot_flags); if (ret < 0) { return -1;
}
} return0;
}
/* Apply GNU relro protection if specified by the program header. This will *turnsomeofthepagesofawritablePT_LOADsegmenttoread-only,as *specifiedbyoneormorePT_GNU_RELROsegments.Thismustbealways *performedafterrelocations. * *Theareastypicallycoveredare.gotand.data.rel.ro,theseare *read-onlyfromtheprogram'sPOV,butcontainabsoluteaddresses *thatneedtoberelocatedbeforeuse. * *Input: *phdr_table->programheadertable *phdr_count->numberofentriesintables *load_bias->loadbias *should_pad_segments->Weresegmentsextendedtoavoidgapsinthememorymap *should_use_16kib_app_compat->IstheELFbeingloadedin16KiBappcompatmode. *Return: *0onsuccess,-1onfailure(errorcodeinerrno).
*/ int phdr_table_protect_gnu_relro(const ElfW(Phdr)* phdr_table, size_t phdr_count,
ElfW(Addr) load_bias, bool should_pad_segments) { return _phdr_table_set_gnu_relro_prot(phdr_table, phdr_count, load_bias, PROT_READ,
should_pad_segments);
}
/* Serialize the GNU relro segments to the given file descriptor. This can be *performedafterrelocationstoallowanotherprocesstolatersharethe *relocatedsegment,ifitwasloadedatthesameaddress. * *Input: *phdr_table->programheadertable *phdr_count->numberofentriesintables *load_bias->loadbias *fd->writablefiledescriptortouse *file_offset->pointertooffsetintofiledescriptortouse/update *Return: *0onsuccess,-1onfailure(errorcodeinerrno).
*/ int phdr_table_serialize_gnu_relro(const ElfW(Phdr)* phdr_table,
size_t phdr_count,
ElfW(Addr) load_bias, int fd,
size_t* file_offset) { const ElfW(Phdr)* phdr = phdr_table; const ElfW(Phdr)* phdr_limit = phdr + phdr_count;
for (phdr = phdr_table; phdr < phdr_limit; phdr++) { if (phdr->p_type != PT_GNU_RELRO) { continue;
}
/* Where possible, replace the GNU relro segments with mappings of the given *filedescriptor.Thiscanbeperformedafterrelocationstoallowafile *previouslycreatedbyphdr_table_serialize_gnu_relroinanotherprocessto *replacethedirtyrelocatedpages,savingmemory,ifitwasloadedatthe *sameaddress.Wehavetocomparethedatabeforewemapoverit,sincesome *partsoftherelrosegmentmaynotbeidenticalduetootherlibrariesin *theprocessbeingloadedatdifferentaddresses. * *Input: *phdr_table->programheadertable *phdr_count->numberofentriesintables *load_bias->loadbias *fd->readablefiledescriptortouse *file_offset->pointertooffsetintofiledescriptortouse/update *Return: *0onsuccess,-1onfailure(errorcodeinerrno).
*/ int phdr_table_map_gnu_relro(const ElfW(Phdr)* phdr_table,
size_t phdr_count,
ElfW(Addr) load_bias, int fd,
size_t* file_offset) { // Map the file at a temporary location so we can compare its contents. struct stat file_stat; if (TEMP_FAILURE_RETRY(fstat(fd, &file_stat)) != 0) { return -1;
}
off_t file_size = file_stat.st_size; void* temp_mapping = nullptr; if (file_size > 0) {
temp_mapping = mmap(nullptr, file_size, PROT_READ, MAP_PRIVATE, fd, 0); if (temp_mapping == MAP_FAILED) { return -1;
}
}
// Iterate over the relro segments and compare/remap the pages. const ElfW(Phdr)* phdr = phdr_table; const ElfW(Phdr)* phdr_limit = phdr + phdr_count;
for (phdr = phdr_table; phdr < phdr_limit; phdr++) { if (phdr->p_type != PT_GNU_RELRO) { continue;
}
if (file_size - *file_offset < size) { // File is too short to compare to this segment. The contents are likely // different as well (it's probably for a different library version) so // just don't bother checking. break;
}
while (match_offset < size) { // Skip over dissimilar pages. while (match_offset < size &&
memcmp(mem_base + match_offset, file_base + match_offset, page_size()) != 0) {
match_offset += page_size();
}
/* Return the address and size of the ELF file's .dynamic section in memory, *ornullifmissing. * *Input: *phdr_table->programheadertable *phdr_count->numberofentriesintables *load_bias->loadbias *Output: *dynamic->addressoftableinmemory(nullonfailure). *dynamic_flags->protectionflagsforsection(unsetonfailure) *Return: *void
*/ void phdr_table_get_dynamic_section(const ElfW(Phdr)* phdr_table, size_t phdr_count,
ElfW(Addr) load_bias, ElfW(Dyn)** dynamic,
ElfW(Word)* dynamic_flags) {
*dynamic = nullptr; for (size_t i = 0; i<phdr_count; ++i) { const ElfW(Phdr)& phdr = phdr_table[i]; if (phdr.p_type == PT_DYNAMIC) {
*dynamic = reinterpret_cast<ElfW(Dyn)*>(load_bias + phdr.p_vaddr); if (dynamic_flags) {
*dynamic_flags = phdr.p_flags;
} return;
}
}
}
/* Return the program interpreter string, or nullptr if missing. * *Input: *phdr_table->programheadertable *phdr_count->numberofentriesintables *load_bias->loadbias *Return: *pointertotheprograminterpreterstring.
*/ constchar* phdr_table_get_interpreter_name(const ElfW(Phdr)* phdr_table, size_t phdr_count,
ElfW(Addr) load_bias) { for (size_t i = 0; i<phdr_count; ++i) { const ElfW(Phdr)& phdr = phdr_table[i]; if (phdr.p_type == PT_INTERP) { returnreinterpret_cast<constchar*>(load_bias + phdr.p_vaddr);
}
} return nullptr;
}
// Sets loaded_phdr_ to the address of the program header table as it appears // in the loaded segments in memory. This is in contrast with phdr_table_, // which is temporary and will be released before the library is relocated. bool ElfReader::FindPhdr() { const ElfW(Phdr)* phdr_limit = phdr_table_ + phdr_num_;
// If there is a PT_PHDR, use it directly. for (const ElfW(Phdr)* phdr = phdr_table_; phdr < phdr_limit; ++phdr) { if (phdr->p_type == PT_PHDR) { return CheckPhdr(load_bias_ + phdr->p_vaddr);
}
}
// Otherwise, check the first loadable segment. If its file offset // is 0, it starts with the ELF header, and we can trivially find the // loaded program header from it. for (const ElfW(Phdr)* phdr = phdr_table_; phdr < phdr_limit; ++phdr) { if (phdr->p_type == PT_LOAD) { if (phdr->p_offset == 0) {
ElfW(Addr) elf_addr = load_bias_ + phdr->p_vaddr; const ElfW(Ehdr)* ehdr = reinterpret_cast<const ElfW(Ehdr)*>(elf_addr);
ElfW(Addr) offset = ehdr->e_phoff; return CheckPhdr(reinterpret_cast<ElfW(Addr)>(ehdr) + offset);
} break;
}
}
DL_ERR("can't find loaded phdr for \"%s\"", name_.c_str()); returnfalse;
}
// Tries to find .note.gnu.property section. // It is not considered an error if such section is missing. bool ElfReader::FindGnuPropertySection() { #ifdefined(__aarch64__)
note_gnu_property_ = std::make_shared<GnuPropertySection>(phdr_table_, phdr_num_,
load_bias_, name_.c_str()); #endif returntrue;
}
// Ensures that our program header is actually within a loadable // segment. This should help catch badly-formed ELF files that // would cause the linker to crash later when trying to access it. bool ElfReader::CheckPhdr(ElfW(Addr) loaded) { const ElfW(Phdr)* phdr_limit = phdr_table_ + phdr_num_;
ElfW(Addr) loaded_end = loaded + (phdr_num_ * sizeof(ElfW(Phdr))); for (const ElfW(Phdr)* phdr = phdr_table_; phdr < phdr_limit; ++phdr) { if (phdr->p_type != PT_LOAD) { continue;
}
ElfW(Addr) seg_start = phdr->p_vaddr + load_bias_;
ElfW(Addr) seg_end = phdr->p_filesz + seg_start; if (seg_start <= loaded && loaded_end <= seg_end) {
loaded_phdr_ = reinterpret_cast<const ElfW(Phdr)*>(loaded); returntrue;
}
}
DL_ERR("\"%s\" loaded phdr %p not in loadable segment",
name_.c_str(), reinterpret_cast<void*>(loaded)); returnfalse;
}
Messung V0.5 in Prozent
¤ Diese beiden folgenden Angebotsgruppen bietet das Unternehmen0.42Angebot
(Wie Sie bei der Firma Beratungs- und Dienstleistungen beauftragen können 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.