67 lines
1.8 KiB
Go
Raw Normal View History

2023-10-17 18:29:36 +00:00
package elf
import (
"encoding/binary"
"io"
)
const (
2023-10-19 08:14:52 +00:00
minAddress = 0x10000
baseAddress = 0x40 * minAddress
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
2023-10-18 15:03:31 +00:00
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,
2023-10-18 15:03:31 +00:00
Flags: ProgramFlagsExecutable | ProgramFlagsReadable,
2023-10-17 20:08:40 +00:00
Offset: 0x80,
VirtualAddress: baseAddress + 0x80,
PhysicalAddress: baseAddress + 0x80,
SizeInFile: int64(len(code)),
SizeInMemory: int64(len(code)),
Align: Align,
},
2023-10-18 15:03:31 +00:00
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)
2023-10-18 15:03:31 +00:00
writer.Write([]byte{0, 0, 0, 0, 0, 0, 0, 0})
2023-10-17 20:08:40 +00:00
writer.Write(elf.Code)
2023-10-17 18:29:36 +00:00
}