July 20, 2006

符合 ELF32/i386 格式的最小 "Hello World"

之前的 blog [「深入淺出 Hello World」演講 Sample 檔案上線] 公佈了「深入淺出 Hello World」演講所用的 sample files,後續維護的版本可透過 Subversion 取得:
    # svn co https://svn.csie.net/helloworld/samples
    
我新增了 "A5-nasm" 範例,是我目前寫出符合 ELF32/i386 格式的最小 "Hello World" 程式,用 readelf 觀察:
    $ ls -l hello
    -rwxr-xr-x 1 jserv jserv 115 Jul 20 13:19 hello
    $ ./hello 
    Hello World!
    $ readelf -a hello
    ELF Header:
      Magic:   7f 45 4c 46 01 01 01 00 00 00 00 00 00 00 00 00 
      Class:                             ELF32
      Data:                              2's complement, little endian
      Version:                           1 (current)
      OS/ABI:                            UNIX - System V
      ABI Version:                       0
      Type:                              EXEC (Executable file)
      Machine:                           Intel 80386
      Version:                           0x1
      Entry point address:               0x804804c
      Start of program headers:          44 (bytes into file)
      Start of section headers:          0 (bytes into file)
      Flags:                             0x0
      Size of this header:               52 (bytes)
      Size of program headers:           32 (bytes)
      Number of program headers:         1
      Size of section headers:           0 (bytes)
      Number of section headers:         0
      Section header string table index: 0
    
    There are no sections in this file.
    There are no sections in this file.
    
    Program Headers:
      Type           Offset   VirtAddr   PhysAddr   FileSiz MemSiz  Flg Align
      LOAD           0x000000 0x08048000 0x08048000 0x00073 0x00073 RWE 0x1000
    
    There is no dynamic section in this file.
    There are no relocations in this file.
    There are no unwind sections in this file.
    No version information found in this file.
    
程式碼的註解參考了 /usr/include/elf.h 提供的 ELF Header 資訊,並且填入必要的欄位,可對照參考,所以這 115 bytes 就成為具體而微的 "Hello World" 程式了,在依循 ELF32 format 的前提下,應該沒辦法再縮小空間。
由 jserv 發表於 July 20, 2006 01:26 PM
迴響

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

他把 header 折起來了 ... 應該算是偷吃步吧 :p

SBT 發表於 July 20, 2006 03:34 PM

很經典的實驗,但是有相容性的問題,用新一點的 kernel 是無法執行的。

jserv 發表於 July 20, 2006 03:48 PM