Assembly

Programming can be hard. Programming in assembly is very hard.

A compiler will take your code and output the assembly equivalent. It’s usually very good assembly, which is one reason we don’t usually write code using assembly.

Below is a quick guide to assembly, with some notes and tips that I picked up along the way.

Hello World 🔗︎

Hello World! in assembly.

          global    _start

          section   .text
_start:   mov       rax, 1                  ; system call for write
          mov       rdi, 1                  ; file handle 1 is stdout
          mov       rsi, message            ; address of string to output
          mov       rdx, 13                 ; number of bytes
          syscall                           ; invoke operating system to do the write
          mov       rax, 60                 ; system call for exit
          xor       rdi, rdi                ; exit code 0
          syscall                           ; invoke operating system to exit

          section   .data
message:  db        "Hello, World", 10      ; note the newline at the end

That’s right, probably the most crazy hello world you’ve ever seen.

The Sum From 1 to N 🔗︎

Now, here is something a little more complex. The sum from 1 to n.

section .text
global sum_to_n
sum_to_n:
 xor eax, eax
.loop:
 add eax, edi
 sub edi, 1
 jg .loop 
 ret

Here’s how this works

  • input value n is provided via the %rdi or %edi registers
  • the return value is expected in the %rax or %eax registers
  • jg jumps to argument if %edi equals zero