From 8b66c9588c5cac219f3785f0e7865f8a351672a8 Mon Sep 17 00:00:00 2001 From: Eduard Urbach Date: Tue, 17 Oct 2023 22:08:40 +0200 Subject: [PATCH] Added ELF program header --- build/Build.go | 2 +- build/elf/Header.go | 1 + build/elf/elf.go | 30 +++++++++++++++++++++++------- 3 files changed, 25 insertions(+), 8 deletions(-) diff --git a/build/Build.go b/build/Build.go index 338c5be..0d0b156 100644 --- a/build/Build.go +++ b/build/Build.go @@ -58,7 +58,7 @@ func writeToDisk(filePath string, code []byte, data []byte) error { } buffer := bufio.NewWriter(file) - executable := elf.New() + executable := elf.New(code) executable.Write(buffer) buffer.Flush() diff --git a/build/elf/Header.go b/build/elf/Header.go index 672f065..bdb7e24 100644 --- a/build/elf/Header.go +++ b/build/elf/Header.go @@ -4,6 +4,7 @@ const ( LittleEndian = 1 TypeExecutable = 2 ArchitectureAMD64 = 0x3E + Align = 16 HeaderSize = 64 ) diff --git a/build/elf/elf.go b/build/elf/elf.go index 68f7bab..740ab77 100644 --- a/build/elf/elf.go +++ b/build/elf/elf.go @@ -6,18 +6,19 @@ import ( ) const ( - baseAddress = 0x400000 - programAlign = 16 - sectionAlign = 16 + baseAddress = 0x10000 ) // ELF64 represents an ELF 64-bit file. type ELF64 struct { Header + ProgramHeader + Padding []byte + Code []byte } // New creates a new 64-bit ELF binary. -func New() *ELF64 { +func New(code []byte) *ELF64 { elf := &ELF64{ Header: Header{ Magic: [4]byte{0x7F, 'E', 'L', 'F'}, @@ -29,17 +30,29 @@ func New() *ELF64 { Type: TypeExecutable, Architecture: ArchitectureAMD64, FileVersion: 1, - EntryPointInMemory: 0, + EntryPointInMemory: baseAddress + 0x80, ProgramHeaderOffset: HeaderSize, - SectionHeaderOffset: 0, // TODO + SectionHeaderOffset: 0, Flags: 0, Size: HeaderSize, ProgramHeaderEntrySize: ProgramHeaderSize, - ProgramHeaderEntryCount: 0, + ProgramHeaderEntryCount: 1, SectionHeaderEntrySize: SectionHeaderSize, SectionHeaderEntryCount: 0, SectionNameStringTableIndex: 0, }, + ProgramHeader: ProgramHeader{ + Type: ProgramTypeLOAD, + Flags: ProgramFlagsExecutable, + Offset: 0x80, + VirtualAddress: baseAddress + 0x80, + PhysicalAddress: baseAddress + 0x80, + SizeInFile: int64(len(code)), + SizeInMemory: int64(len(code)), + Align: Align, + }, + Padding: []byte{0, 0, 0, 0, 0, 0, 0, 0}, + Code: code, } return elf @@ -48,4 +61,7 @@ func New() *ELF64 { // Write writes the ELF64 format to the given writer. func (elf *ELF64) Write(writer io.Writer) { binary.Write(writer, binary.LittleEndian, &elf.Header) + binary.Write(writer, binary.LittleEndian, &elf.ProgramHeader) + writer.Write(elf.Padding) + writer.Write(elf.Code) }