Wednesday 12 June 2013

TNDJG:0003 Hello World x86_64 assembly language program for linux


 What is the shortest Hello World program on linux?

$ cat syscall.s
# Minimal program on linux x86_64
# (C) 2004 DJ Greaves.
# Compile and run with: as -o a.o syscall.s;ld -o a.out a.o; ./a.out

#int main()
#{
#  char *s = "Hello Worldly\n";
#  write(1, s, strlen(s));
#  exit(0);
#}


# Calling convention uses %rdi, %rsi, %rdx, %rcx, %r8 and %r9 in order.
# Low syscall function numbers are 0=read,1=write,2=open,3=close,4=stat


      
        .global _start
_start:
        mov    $14,%rdx
        mov    $message,%rsi
        mov    $1,%rdi # stdout file description number is 1
        mov    $1,%rax # Kernel function number for write is 1
        syscall

        movq   $0,%rdi # Zero return code
        mov    $60,%rax # Kernel function number for _exit is 60
        syscall

        ret

message:
        .string "Hello Worldly\n"


$
as -o a.o syscall.s
ld -o a.out a.o
./a.out
Hello Worldly
$
strace ./a.out
execve("./a.out", ["./a.out"], [/* 60 vars */]) = 0
write(1, "Hello Worldly\n", 14Hello Worldly
)         = 14
_exit(0)                                = ?
$

No comments:

Post a Comment