me

/

vinix-ports Public
382 commits 0 issues 0 pull requests 1 contributor Discussions Projects Snippets LOC history Platform CI

Check target linker page alignment in program headers

diviocity committed 5 days ago · 39db1e9e63a78b63de883f3d32ef02c620084bf0 View patch
Unverified signature 1 files changed +57 -0
tools/vinix-elf-pages.v new file +57 -0

@@ -0,0 +1,57 @@

1+// Check the load segments produced by a target compiler or linker.

2+module main

3+

4+import encoding.binary

5+import os

6+

7+fn check(path string, machine u16, page u64) ! {

8+ mut file := os.open(path)!

9+ defer { file.close() }

10+ header := file.read_bytes_at(64, 0)

11+ if header.len != 64 || header[..6] != [u8(127), 69, 76, 70, 2, 1]

12+ || binary.little_endian_u16(header[18..]) != machine {

13+ return error('${path}: expected a target ELF64 little-endian file')

14+ }

15+ if binary.little_endian_u16(header[16..]) !in [u16(2), 3] {

16+ return error('${path}: expected an executable or shared object')

17+ }

18+ offset := binary.little_endian_u64(header[32..])

19+ size := binary.little_endian_u16(header[54..])

20+ count := binary.little_endian_u16(header[56..])

21+ length := os.file_size(path)

22+ if size != 56 || count == 0 || offset > length || u64(count) * size > length - offset {

23+ return error('${path}: invalid program-header table')

24+ }

25+ mut loads := 0

26+ for i in 0 .. int(count) {

27+ record := file.read_bytes_at(int(size), offset + u64(i) * size)

28+ if record.len != int(size) {

29+ return error('${path}: truncated program header')

30+ }

31+ if binary.little_endian_u32(record) != 1 { continue }

32+ position := binary.little_endian_u64(record[8..])

33+ address := binary.little_endian_u64(record[16..])

34+ alignment := binary.little_endian_u64(record[48..])

35+ if alignment < page || alignment & (alignment - 1) != 0

36+ || position % alignment != address % alignment {

37+ return error('${path}: PT_LOAD ${i} offset 0x${position:x}, address 0x${address:x}, alignment 0x${alignment:x} incompatible with ${page}-byte pages')

38+ }

39+ loads++

40+ }

41+ if loads == 0 { return error('${path}: no loadable segments') }

42+ println('${path}: ${loads} PT_LOAD segments support ${page}-byte pages')

43+}

44+

45+fn main() {

46+ if os.args.len < 3 || os.args[1] !in ['x86_64', 'aarch64'] {

47+ eprintln('usage: vinix-elf-pages ARCH ELF ...')

48+ exit(2)

49+ }

50+ arm := os.args[1] == 'aarch64'

51+ for path in os.args[2..] {

52+ check(path, if arm { u16(183) } else { u16(62) }, if arm { u64(16384) } else { u64(4096) }) or {

53+ eprintln(err)

54+ exit(1)

55+ }

56+ }

57+}