From 39db1e9e63a78b63de883f3d32ef02c620084bf0 Mon Sep 17 00:00:00 2001 From: diviocity Date: Mon, 30 Nov 2026 03:17:01 +0100 Subject: [PATCH] Check target linker page alignment in program headers --- tools/vinix-elf-pages.v | 57 +++++++++++++++++++++++++++++++++++++++++ 1 file changed, 57 insertions(+) create mode 100644 tools/vinix-elf-pages.v diff --git a/tools/vinix-elf-pages.v b/tools/vinix-elf-pages.v new file mode 100644 index 0000000..d01e861 --- /dev/null +++ b/tools/vinix-elf-pages.v @@ -0,0 +1,57 @@ +// Check the load segments produced by a target compiler or linker. +module main + +import encoding.binary +import os + +fn check(path string, machine u16, page u64) ! { + mut file := os.open(path)! + defer { file.close() } + header := file.read_bytes_at(64, 0) + if header.len != 64 || header[..6] != [u8(127), 69, 76, 70, 2, 1] + || binary.little_endian_u16(header[18..]) != machine { + return error('${path}: expected a target ELF64 little-endian file') + } + if binary.little_endian_u16(header[16..]) !in [u16(2), 3] { + return error('${path}: expected an executable or shared object') + } + offset := binary.little_endian_u64(header[32..]) + size := binary.little_endian_u16(header[54..]) + count := binary.little_endian_u16(header[56..]) + length := os.file_size(path) + if size != 56 || count == 0 || offset > length || u64(count) * size > length - offset { + return error('${path}: invalid program-header table') + } + mut loads := 0 + for i in 0 .. int(count) { + record := file.read_bytes_at(int(size), offset + u64(i) * size) + if record.len != int(size) { + return error('${path}: truncated program header') + } + if binary.little_endian_u32(record) != 1 { continue } + position := binary.little_endian_u64(record[8..]) + address := binary.little_endian_u64(record[16..]) + alignment := binary.little_endian_u64(record[48..]) + if alignment < page || alignment & (alignment - 1) != 0 + || position % alignment != address % alignment { + return error('${path}: PT_LOAD ${i} offset 0x${position:x}, address 0x${address:x}, alignment 0x${alignment:x} incompatible with ${page}-byte pages') + } + loads++ + } + if loads == 0 { return error('${path}: no loadable segments') } + println('${path}: ${loads} PT_LOAD segments support ${page}-byte pages') +} + +fn main() { + if os.args.len < 3 || os.args[1] !in ['x86_64', 'aarch64'] { + eprintln('usage: vinix-elf-pages ARCH ELF ...') + exit(2) + } + arm := os.args[1] == 'aarch64' + for path in os.args[2..] { + check(path, if arm { u16(183) } else { u16(62) }, if arm { u64(16384) } else { u64(4096) }) or { + eprintln(err) + exit(1) + } + } +} -- 2.56.1