understanding elf magic : the section header and success
today, i spent the entire day constructing the section header table of my simple program. i also changed some bytes in the elf header to accomodate the section headers and string table index. so without further blabber, here are the additions.
; ----------------------------
; start of segment definitions
; ----------------------------
; program entry
_start:
mov eax, 4
inc ebx
mov ecx, stringy
mov edx, strlen
int 0x80
xor eax, eax
inc eax
xor ebx, ebx
int 0x80
s1 equ $-$$
; data segment
dataseg:
stringy db "I LOVE STEPHANIE!", 10
strlen equ $-stringy
d1 equ $-dataseg
%assign liner (dataseg-$$)
dsegoff equ (liner&-8)+8
p_vadd1 equ $$+(dsegoff)
dseglen equ $-dataseg
%assign multiplier (s1/0x1000)+1
psize equ 0x1000*multiplier
; --------------------
; section header table
; --------------------
null_section:
dd 0 ; sh_name
dd 0 ; sh_type
dd 0 ; sh_flags
dd 0 ; sh_addr
dd 0 ; sh_offset
dd 0 ; sh_size
dd 0 ; sh_link
dd 0 ; sh_info
dd 0 ; sh_addralign
dd 0 ; sh_entsize
shdrsize equ $-null_section
; text header
text_section:
dd 11 ; .text
dd 0x1 ; SHT_PROGBITS
dd 0x6 ; SHF_ALLOC+SHF_EXECINSTR
dd _start ; sh_addr
dd _start-$$
dd s1 ; sh_size
dd 0 ; sh_link
dd 0 ; sh_info
dd 16 ; 16 byte alignment
dd 0 ; sh_entsize
; data header
data_section:
dd 17 ; .data
dd 0x1 ; SHT_PROGBITS
dd 0x3 ; SHF_ALLOC+SHF_WRITE
dd dataseg ; sh_addr
dd dataseg-$$
dd d1 ; sh_size
dd 0 ; sh_link
dd 0 ; sh_info
dd 4 ; 4 byte alignment
dd 0 ; sh_entsize
; string table section header
str_section:
dd 1 ; sh_name
dd 3 ; sh_type
dd 0 ; sh_flags
dd 0 ; sh_addr
dd stab-$$ ; sh_offset
dd stbsz ; sh_size
dd 0 ; sh_link
dd 0 ; sh_info
dd 1 ; sh_addralign
dd 0 ; sh_entsize
; string table
stab:
db 0x0, '.shstrtab',0x0,'.text',0x0,'.data',0x0
stbsz equ $-stab
figuring out the section headers.. especially the section that deals with the string table was confusing at first. the elf specification was written by a sadistic writer i assume. the alignment issues also made me doubt if the progam would even work.
amerei@heaven ~/workdir/elf_magic $ nasm -f bin elfhead.asm amerei@heaven ~/workdir/elf_magic $ chmod +x elfhead amerei@heaven ~/workdir/elf_magic $ file elfhead elfhead: ELF 32-bit LSB executable, Intel 80386, version 1 (SYSV), statically linked, stripped amerei@heaven ~/workdir/elf_magic $ du -b elfhead 342 elfhead amerei@heaven ~/workdir/elf_magic $ ./elfhead I LOVE STEPHANIE!
there you go! a linux elf binary that is truly from scratch.
signing off.
