My question is general, but to have an example to work with, let us take one from Whirlwind Tutorial.
; tiny.asm BITS 32 org 0x00010000 db 0x7F, "ELF" ; e_ident dd 1 ; p_type dd 0 ; p_offset dd $$ ; p_vaddr dw 2 ; e_type ; p_paddr dw 3 ; e_machine dd _start ; e_version ; p_filesz dd _start ; e_entry ; p_memsz dd 4 ; e_phoff ; p_flags _start: mov bl, 42 ; e_shoff ; p_align xor eax, eax inc eax ; e_flags int 0x80 db 0 dw 0x34 ; e_ehsize dw 0x20 ; e_phentsize db 1 ; e_phnum ; e_shentsize ; e_shnum ; e_shstrndx filesize equ $ - $$ ; tiny.asm
To get a binary compile with
nasm -f bin -o tiny nasm.asm;chmod +x tiny. Executable in it self, is a bit of tiny monster. It is smaller than ELF header, yet contains ELF header, program header and program code - yet Linux (at least on my 64 Debian) runs it.
I would like to be able to debug this types files that have (intentionally or not) damaged/incorrect elf header. Is there a tool to fix elf header? Is there debugger that will manage to run this file?
What I tried is to get entry point:
readelf -h tiny but
readelf refuses even to look at the file:
readelf: Error: tiny: Failed to read file header.
objdump is no better.
rabin2 -e tiny we get entry address (with some warnings):
[Entrypoints] vaddr=0x00010020 paddr=0x00010020 baddr=0x00000000 laddr=0x00000000 haddr=0x00000018 type=program
I managed to get some dissasembly using
radare2 tiny and
[0x00010020]> pd ;-- entry0: 0x00010020 b32a mov bl, 0x2a ; '*' ; 42 0x00010022 31c0 xor eax, eax 0x00010024 40 inc eax 0x00010025 cd80 int 0x80 0x00010027 003400 add byte [eax + eax], dh 0x0001002a 2000 and byte [eax], al ;-- section_end.uphdr: 0x0001002c ~ 01ff add edi, edi
Next I tried
lldb tiny but neither worked. Free version 5.0 of IDA stops at infinite loop.
So is there a way to repair elf in automatic/semi-automatic way? Or maybe some other trick that would allow debugging this (or similar) binary? One idea that comes to my mind is to patch entry point with instruction that loops and attach
gdb. Would that work?
If no tool for repairing elf exists, which files in kernel source contain code responsible for loading binary?