x86-64 TUTORIAL: HELLO WORLD!


x86-64 TUTORIAL: CPUID  |  x86-64 TUTORIAL: INPUT OUTPUT FUNCTIONS

Below is a program that prints "Hello World!" on screen followed by a newline character. In the data section we first store the string "Hello World!", followed by the newline character which has an ASCII value of 10 and the NULL character or the value 0. The NULL character is used here because of the way we calculate the string length. There are other ways to calculate the string length as well, by using NASM’s directives like equ, but we shall use that in another sample program.

We use the SCASB instruction which checks if every byte, at the address given by register RDI, matches the byte in register AL, and hence in AL we place the byte 0x00 by using the XOR instruction. Then we use the REPNZ instruction on the SCASB instruction, which repeats the SCASB instruction until the zero flag ZF is set in the RFLAGS register. This will happen when the byte scanned by SCASB and the byte in register AL are equal or if RCX is zero. We use the CLD instruction to clear the direction flag DF in the RFLAGS register, thus incrementing the value in RCX everytime the SCASB instruction is called. We place the decimal number -1 into RCX, and once the counting has been done and the null character encountered, we can calculate the length of the string, by subtracting RCX from the decimal number -2. The reason we use -2 and not -1 is because SCASB counts the null character as well and increments RCX. The final length is placed in RDX.

We then call the write() system call with the file descriptor as 0x1 for stdout, and the string followed by its length as arguments. After this we call exit().

section .data
    string1 db  "Hello World!",10,0

section .text
    global _start

    _start:
        ; calculate the length of string
        mov     rdi, dword string1
        mov     rcx, dword -1
        xor     al,al
        cld
        repnz scasb

        ; place the length of the string in RDX
        mov     rdx, dword -2
        sub     rdx, rcx

        ; print the string using write() system call 
        mov     rsi, dword string1
        push    0x1
        pop     rax
        mov     rdi,rax
        syscall

        ; exit from the application here
        xor     rdi,rdi
        push    0x3c
        pop     rax
        syscall

Download helloworld.asm.

The command to compile the above code is as follows:

$ yasm -f elf64 helloworld.asm 
$ ld -o helloworld.out helloworld.o  

x86-64 TUTORIAL: CPUID  |  x86-64 TUTORIAL: INPUT OUTPUT FUNCTIONS
SUPPORT THIS SITE
Donate DOGECOIN to DBevjMg3fd8C5oxZbV8sFpAffo6Tas1s8Q. DBevjMg3fd8C5oxZbV8sFpAffo6Tas1s8Q Donate BITCOIN to 19hrWWw1dPvBE1wVPfCnH8LqnUwsT3NsHW. 19hrWWw1dPvBE1wVPfCnH8LqnUwsT3NsHW
As an Amazon Associate I earn from qualifying purchases.