最小C程序(264字节), 最小ELF程序(45字节)

极小C程序

tiny.c:

void start()
{
 __asm__(
"movl $1,  %eax;\n\t"
     
   "movl $42, %ebx;\n\t"
    
   "int $0x80");
}

 

ld链接脚本,tiny.lds:

ENTRY(start)
SECTIONS
{
         . 
= 0x08048000 + SIZEOF_HEADERS;
        
t : { *(.text) }
         
/DISCARD/ : { *(.bss) *(.data) *(.rodata) *(.note.GNU-stack) }
         
/DISCARD/ : { *(.comment) }
}


 t 段名更短,  /DISCARD/ 丢弃不需要的段。

 

Makefile:

tiny:tiny.o
   ld 
-static --T tiny.lds -o tiny tiny.o
   strip tiny
 
tiny.o:tiny.c 
   gcc 
-fomit-frame-pointer --o tiny.o tiny.c
 
clean:
   rm 
-f tiny tiny.o


-fomit-frame-pointer 可以省略掉 ebp 操作。

 

$objdump -d tiny

tiny:     file format elf32-i386

Disassembly of section t:

08048074 <t>:
 
8048074:       b8 01 00 00 00          mov    $0x1,%eax
 
8048079:       bb 2a 00 00 00          mov    $0x2a,%ebx
 804807e:       cd 
80                   int    $0x80
 
8048080:       c3                      ret    


shell执行

$make clean;make
$./tiny
$echo $?
42
$wc -c tiny
      264 tiny

 


极小ELF程序

 来至:http://www.muppetlabs.com/~breadbox/software/tiny/teensy.html

tiny.asm

代码
BITS 32 
    org     
0x08048000 
    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     $ 
- $$



标准ELF头部就有52字节, 这个ELF其实是不标准的,只是可以运行(readelf, objdump, gdb都不能识别这个程序)。 

 

shell

  $ nasm -f bin -o tiny tiny.asm
  $ chmod +x tiny
  $ ./tiny ; echo $?
  
42
  $ wc -c tiny
       
45 tiny


 

 

 

posted @ 2010-10-29 16:29  napoleon_liu  阅读(739)  评论(0编辑  收藏  举报