68 lines
1.7 KiB
Go
Raw Normal View History

2023-10-17 18:29:36 +00:00
package elf
import (
"encoding/binary"
"io"
)
const (
2023-10-17 20:08:40 +00:00
baseAddress = 0x10000
2023-10-17 18:29:36 +00:00
)
// ELF64 represents an ELF 64-bit file.
type ELF64 struct {
Header
2023-10-17 20:08:40 +00:00
ProgramHeader
Padding []byte
Code []byte
2023-10-17 18:29:36 +00:00
}
// New creates a new 64-bit ELF binary.
2023-10-17 20:08:40 +00:00
func New(code []byte) *ELF64 {
2023-10-17 18:29:36 +00:00
elf := &ELF64{
Header: Header{
Magic: [4]byte{0x7F, 'E', 'L', 'F'},
Class: 2,
Endianness: LittleEndian,
Version: 1,
OSABI: 0,
ABIVersion: 0,
Type: TypeExecutable,
Architecture: ArchitectureAMD64,
FileVersion: 1,
2023-10-17 20:08:40 +00:00
EntryPointInMemory: baseAddress + 0x80,
2023-10-17 18:29:36 +00:00
ProgramHeaderOffset: HeaderSize,
2023-10-17 20:08:40 +00:00
SectionHeaderOffset: 0,
2023-10-17 18:29:36 +00:00
Flags: 0,
Size: HeaderSize,
ProgramHeaderEntrySize: ProgramHeaderSize,
2023-10-17 20:08:40 +00:00
ProgramHeaderEntryCount: 1,
2023-10-17 18:29:36 +00:00
SectionHeaderEntrySize: SectionHeaderSize,
SectionHeaderEntryCount: 0,
SectionNameStringTableIndex: 0,
},
2023-10-17 20:08:40 +00:00
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,
2023-10-17 18:29:36 +00:00
}
return elf
}
// Write writes the ELF64 format to the given writer.
func (elf *ELF64) Write(writer io.Writer) {
binary.Write(writer, binary.LittleEndian, &elf.Header)
2023-10-17 20:08:40 +00:00
binary.Write(writer, binary.LittleEndian, &elf.ProgramHeader)
writer.Write(elf.Padding)
writer.Write(elf.Code)
2023-10-17 18:29:36 +00:00
}