Hello World in Assembly (x86-64)

Kaamkiya - Dec 12 '23 - - Dev Community

Introduction

Welcome to Assembly x86_64! If you're here, you probably fall in to one of these categories: being forced to learn this for school/a job, or being genuinely interested in learning this. Or maybe you just stumbled across this and you thought "Why not? It can't be that hard."

Well, it is that hard. I'll give you the code, and then explain it after.

The Code

section      .data                     ; this is where variables are initialized
    msg      db   "Hello, World!", 0xa ; 0xa is a newline
    msglen   equ  $ - msg

section      .text                     ; this is the code section
    global   _start                    ; declare entry point
_start:                                ; define entry point
    mov rax, 1                         ; sys_write(
    mov rdi, 1                         ;   STDOUT_FILENO,
    mov rsi, msg                       ;   msg,
    mov rdx, msglen                    ;   sizeof(msg)
    syscall                            ; );

    ; exit
    mov rax, 60                        ; exit
    mov rdi, 0                         ;   exit_status
    syscall                            ; );
Enter fullscreen mode Exit fullscreen mode

I'm hoping you're still here. Although probably not 😁.

Anyway, here's the line-by-line:

  1. This is the section where variables are declared
  2. Declare the msg variable to the size data byte, or 8 bits. ; starts a comment.
  3. Set the msglen variable to a sizeof(msg)
  4. This is the code section.
  5. This line declares the entry point, called _start
  6. This line starts the definition of the _start function
  7. rax is the system call id. So exit is 60, stdout is 1, 2 is stderr, etc.
  8. This line sets the file descriptor (fd) to 1, which is stdout.
  9. "Invoke" the message
  10. "Invoke the message length
  11. syscall means "execute the stuff that I just made."
  12. Set rax to 60, which is sys_exit
  13. This line is the exit status
  14. Call the code.

I'm still learning though, so if I'm wrong, please correct me.

By the way, it's a fantastic idea to align Assembly code to maintain the nearly non-existent readability. Please also use comments (I didn't because I described it afterword).

There are plenty of great books and videos on how to learn Assembly. If you still want to learn it, find one! I recommend this YouTube playlist.

(Also, if you know how to add syntax highlighting for this code block, please tell me in the comments 🙂)

. . . . . . . . . . . .