Helloworld

Easiest example to start with.  Just prints a text on a terminal screen.

Pitfalls

- don't forget TABS in the Makefile.
- syscalls in this example are macros (see unistd.inc in helloworld.inc) not the actual opcodes

Source code

; name: helloworld.asm
; description: show hello world in a terminal
; assemble and link: nasm -felf64 helloworld.asm -o helloworld.o
;                    ld -s -melf_x86_64 helloworld.o -o helloworld

bits 64
         
%include "helloworld.inc"
global _start
section .bss
section .udata
    message:    db  "Hello world!", 10
    .length:    equ $-message
section .text
_start:

    syscall write,stdout,message,message.length
    syscall exit,0

 

include file

%ifndef _helloworld_inc_
%define _helloworld_inc_
    %include "unistd.inc"
%endif   ;helloworld_inc_

Makefile


.phony: clean
.phony: release
.phony: debug

NAME= helloworld O = .o ASM = .asm INC = .inc LST = .lst ASFLAGS = "-felf64" LDFLAGS = -s -melf_x86_64 LIBS = OBJS = $(NAME): $(NAME)$(O) ld $(LDFLAGS) $(NAME)$(O) -o $(NAME) $(OBJS) $(LIBS) $(NAME)$(O): $(NAME)$(ASM) nasm $(ASFLAGS) $(NAME)$(ASM) -o $(NAME)$(O) release: touch $(NAME) $(MAKE) $(NAME) debug: touch $(NAME) $(MAKE) $(NAME) ASFLAGS="-felf64 -Fdwarf -g -l $(NAME)$(LST)" LDFLAGS="-g -melf_x86_64" clean: @rm -f $(NAME) $(NAME)$(LST) $(NAME)$(O)

 

Disassembly listing

        22 [1]	    syscall write,stdout,message,message.length
0x400080                  ba 0d 00 00 00                 mov    edx,0xd
0x400085  <+    5>        48 be a5 00 40 00 00 00 00 00  movabs rsi,0x4000a5
0x40008f  <+   15>        bf 01 00 00 00                 mov    edi,0x1
0x400094  <+   20>        b8 01 00 00 00                 mov    eax,0x1
0x400099  <+   25>        0f 05                          syscall
        23 [1]	    syscall exit,0
0x40009b  <+   27>        48 31 ff                       xor    rdi,rdi
0x40009e  <+   30>        b8 3c 00 00 00                 mov    eax,0x3c
0x4000a3  <+   35>        0f 05                          syscall

 

Optimized code

    mov    edx,message.length    ba 0d 00 00 00
    mov    rsi,message           48 be a0 00 40 00 00 00 00 00
    xor    edi,edi               31 ff
    inc    edi                   ff C7
    mov    eax,edi               89 f8
    syscall                      0f 05
    dec    edi                   ff cf
    mov    eax,0x3c              b8 3c 00 00 00
    syscall                      0f 05