|
| 1 | +class Caotral::Linker::ELF::Header |
| 2 | + include Caotral::Assembler::ELF::Utils |
| 3 | + IDENT = [0x7f, 0x45, 0x4c, 0x46, 0x02, 0x01, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00].freeze |
| 4 | + ELF_FILE_TYPE = { NONE: 0, REL: 1, EXEC: 2, DYN: 3, CORE: 4 }.freeze |
| 5 | + |
| 6 | + def initialize(endian: :little, type: :rel, arc: :amd64) |
| 7 | + @ident = IDENT |
| 8 | + @type = num2bytes(ELF_FILE_TYPE[elf(type)], 2) |
| 9 | + @arch = arch(arc) |
| 10 | + @version = num2bytes(1, 4) |
| 11 | + @entry = num2bytes(0x00, 8) |
| 12 | + @phoffset = num2bytes(0x00, 8) |
| 13 | + @shoffset = num2bytes(0x00, 8) |
| 14 | + @flags = num2bytes(0x00, 4) |
| 15 | + @ehsize = num2bytes(0x40, 2) |
| 16 | + @phsize = num2bytes(0x00, 2) |
| 17 | + @phnum = num2bytes(0x00, 2) |
| 18 | + @shentsize = num2bytes(0x40, 2) |
| 19 | + @shnum = num2bytes(0x08, 2) |
| 20 | + @shstrndx = num2bytes(0x07, 2) |
| 21 | + end |
| 22 | + |
| 23 | + def build = bytes.flatten.pack("C*") |
| 24 | + |
| 25 | + def set!(entry: nil, phoffset: nil, shoffset: nil, shnum: nil, shstrndx: nil) |
| 26 | + @entry = num2bytes(entry, 8) if check(entry, 8) |
| 27 | + @phoffset = num2bytes(phoffset, 8) if check(phoffset, 8) |
| 28 | + @shoffset = num2bytes(shoffset, 8) if check(shoffset, 8) |
| 29 | + @shnum = num2bytes(shnum, 2) if check(shnum, 2) |
| 30 | + @shstrndx = num2bytes(shstrndx, 2) if check(shstrndx, 2) |
| 31 | + end |
| 32 | + |
| 33 | + private |
| 34 | + |
| 35 | + def bytes = [ |
| 36 | + @ident, @type, @arch, @version, @entry, @phoffset, |
| 37 | + @shoffset, @flags, @ehsize, @phsize, @phnum, @shentsize, |
| 38 | + @shnum, @shstrndx |
| 39 | + ] |
| 40 | + |
| 41 | + def arch(machine) |
| 42 | + case machine.to_s |
| 43 | + in "amd64" | "x86_64" | "x64" |
| 44 | + [0x3e, 0x00] |
| 45 | + end |
| 46 | + end |
| 47 | + |
| 48 | + def elf(type) |
| 49 | + case type.to_s |
| 50 | + in "relocatable" | "rel" |
| 51 | + :REL |
| 52 | + in "exe" | "ex" | "exec" |
| 53 | + :EXEC |
| 54 | + in "shared" | "share" | "dynamic" | "dyn" |
| 55 | + :DYN |
| 56 | + else |
| 57 | + :NONE |
| 58 | + end |
| 59 | + end |
| 60 | +end |
0 commit comments