Added optional section headers

This commit is contained in:
Eduard Urbach 2025-03-07 16:55:30 +01:00
parent 0765351891
commit 955461d2de
Signed by: eduard
GPG key ID: 49226B848C78F6C8
6 changed files with 63 additions and 14 deletions

35
src/elf/AddSections.go Normal file
View file

@ -0,0 +1,35 @@
package elf
// AddSections adds section headers to the ELF file.
func (elf *ELF) AddSections() {
elf.StringTable = []byte("\000.text\000.shstrtab\000")
stringTableStart := elf.DataHeader.Offset + elf.DataHeader.SizeInFile
sectionHeaderStart := stringTableStart + int64(len(elf.StringTable))
elf.SectionHeaders = []SectionHeader{
{
Type: SectionTypeNULL,
},
{
NameIndex: 1,
Type: SectionTypePROGBITS,
Flags: SectionFlagsAllocate | SectionFlagsExecutable,
VirtualAddress: elf.CodeHeader.VirtualAddress,
Offset: elf.CodeHeader.Offset,
SizeInFile: elf.CodeHeader.SizeInFile,
Align: elf.CodeHeader.Align,
},
{
NameIndex: 7,
Type: SectionTypeSTRTAB,
Offset: int64(stringTableStart),
SizeInFile: int64(len(elf.StringTable)),
Align: 1,
},
}
elf.SectionHeaderEntrySize = SectionHeaderSize
elf.SectionHeaderEntryCount = int16(len(elf.SectionHeaders))
elf.SectionHeaderOffset = int64(sectionHeaderStart)
elf.SectionNameStringTableIndex = 2
}

View file

@ -14,8 +14,10 @@ const HeaderEnd = HeaderSize + ProgramHeaderSize*2
// ELF represents an ELF file.
type ELF struct {
Header
CodeHeader ProgramHeader
DataHeader ProgramHeader
CodeHeader ProgramHeader
DataHeader ProgramHeader
SectionHeaders []SectionHeader
StringTable []byte
}
// Write writes the ELF64 format to the given writer.
@ -77,14 +79,20 @@ func Write(writer io.Writer, code []byte, data []byte) {
},
}
if config.Sections {
elf.AddSections()
}
binary.Write(writer, binary.LittleEndian, &elf.Header)
binary.Write(writer, binary.LittleEndian, &elf.CodeHeader)
binary.Write(writer, binary.LittleEndian, &elf.DataHeader)
writer.Write(bytes.Repeat([]byte{0x00}, codePadding))
writer.Write(code)
writer.Write(bytes.Repeat([]byte{0x00}, dataPadding))
writer.Write(data)
if len(data) > 0 {
writer.Write(bytes.Repeat([]byte{0x00}, dataPadding))
writer.Write(data)
if config.Sections {
writer.Write(elf.StringTable)
binary.Write(writer, binary.LittleEndian, &elf.SectionHeaders)
}
}