Skip to content
LumenaryAcademy
Foundations 50 min

First steps in assembly

What assembly language is, why people still learn it, and a first x86-64 program that talks to Linux with no library at all.

Code tested · 3AI-draftedAwaiting review by a computer scientist

Your guides: Chloe · The Designer, Margaret · The Profiler, Gideon · The Language Lawyer

MotivationH

Why learn the processor's own language?

Every program you have ever run, whether written in Python, JavaScript, Rust or Java, ends up as a sequence of very small instructions that a processor carries out one after another: copy this number here, add these two numbers, compare, jump to a different instruction if the comparison came out a certain way. Those instructions are stored as bytes, called machine code. An assembly language is a way of writing machine code that people can read: each line names one instruction, with words such as mov and add instead of bytes such as b8 01 00 00 00.

Almost nobody writes large programs in assembly any more, and this course will not pretend otherwise. Compilers produce excellent machine code, and code written in a high-level language is far easier to read, test and change. So why spend nine lessons here? Because a surprising number of working programmers read assembly regularly, and a few write it:

  • Understanding compilers. When you know what for loops and function calls become, you can predict what code is cheap and what is expensive, and you can check what the compiler actually did instead of guessing. Tools such as Compiler Explorer make this a daily habit for many C, C++ and Rust developers.
  • Performance. The innermost loops of video codecs, cryptography libraries, compression tools and numerical libraries are still sometimes written or hand-tuned in assembly, or in "intrinsics" that map one-to-one onto instructions. Even when you never write it, reading it tells you why a loop is slow.
  • Security. Malware analysts, people who find and fix vulnerabilities, and anyone studying how a buffer overflow becomes an attack reads disassembled machine code, because that is all a compiled program contains.
  • Embedded systems and operating systems. The first instructions a computer runs after power-on, the code that switches a processor into a new mode, interrupt handlers and context switches all need a few dozen lines of assembly, because no high-level language can express them.
  • Debugging. When a program crashes in a library you have no source for, a debugger shows you the instruction that failed. Being able to read it turns a mystery into a bug report.

There is also a quieter reason. Assembly removes the last layer of mystery between your code and the machine. After this course, a "variable" will mean a register or a few bytes at an address, a "function call" will mean a jump that remembers where to come back, and "printing" will mean asking the operating system to copy bytes to a file. Those pictures stay with you in every language you use afterwards.

History & global context

From Kathleen Booth to x86-64

The first computers were programmed in raw numbers. Each instruction was a pattern of bits, worked out by hand from a table and entered with switches, punched tape or cards. Mistakes were easy to make and very hard to find.

Assembly languages appeared in the late 1940s as the obvious improvement: let people write short names for operations and let a program translate them. In 1947, Kathleen Booth, working with Andrew Booth on the ARC machine at Birkbeck College in London, described a symbolic notation for its instructions in a report titled Coding for A.R.C.; she is widely credited with the first assembly language. In 1949 at the University of Cambridge, David Wheeler wrote the "initial orders" for the EDSAC computer: a short program, wired permanently into the machine, that read instructions punched as a letter for the operation and a decimal number for the address, and converted them into binary as it loaded them. That is the job an assembler still does today.

The idea spread with every new machine, and that is the key to understanding the subject: there is no single assembly language. Each processor family has its own instruction set, its own registers and its own encodings, and so its own assembly language. A program written for one family will not run on another. The families you are most likely to meet today are:

FamilyWhere you find it
x86-64 (also called AMD64 or Intel 64)most laptops, desktops and cloud servers
ARM64 (AArch64)phones, tablets, Apple's Macs since 2020, Raspberry Pi, a growing share of servers
RISC-Vmicrocontrollers, research chips, and a fast-growing open ecosystem
others8- and 32-bit microcontrollers (AVR, ARM Cortex-M), DSPs, GPUs, mainframes

This course teaches x86-64. Its ancestor is Intel's 16-bit 8086 from 1978; it grew to 32 bits with the 80386 in 1985, and AMD extended it to 64 bits in the early 2000s (the first AMD64 processors shipped in 2003, and Intel adopted the same design soon after). Because each generation kept running the previous generation's code, x86-64 carries a lot of history: odd register names, several ways to do the same thing, and instructions nobody uses. We will use the clean, modern subset that compilers use. Lesson 8, ARM64 and RISC-V, shows how two younger designs made different choices.

IntuitionH

Machine code with names

A processor is a machine with a small number of very fast storage slots called registers, a connection to a large memory, and a fixed menu of instructions. It keeps the address of the next instruction in a special register, fetches the bytes there, decodes them, carries them out, and moves on.

Here is one x86-64 instruction in three forms:

FormWhat it looks like
machine code (hexadecimal bytes)b8 01 00 00 00
assembly, Intel syntaxmov eax, 1
meaningput the number 1 into the register eax

An assembler turns the middle column into the first. The translation is almost one-to-one: one line of assembly becomes one instruction. That is what separates assembly from every other language in this catalogue, where one line can become dozens or thousands of instructions.

Three kinds of line appear in an assembly file:

  • Instructions such as mov eax, 1 become machine code.
  • Directives start with a dot, such as .section .rodata or .ascii "Hi\n". They are orders to the assembler itself: put the following bytes in this section, reserve this much space, define this constant.
  • Labels end with a colon, such as msg: or _start:. A label gives a name to the address where the next byte will go, so that other lines can refer to it.

Text after # is a comment (the GNU assembler on x86 also accepts /* … */).

Note

x86-64 assembly has two syntaxes. The GNU tools default to AT&T syntax, which writes movl $1, %eax with the destination last and % and $ marks. Intel's manuals, Windows tools and most security tools use Intel syntax, mov eax, 1, with the destination first. Both describe exactly the same machine code. This course uses Intel syntax, switched on by the first line of every program: .intel_syntax noprefix. You will meet AT&T syntax in older tutorials and in GCC's default output; lesson 7 shows how to ask GCC for Intel syntax instead.

ComputationC

Your first program

Installing the tools

You need three things: an x86-64 processor, Linux, and GNU Binutils, which contains the assembler as and the linker ld.

  • On Debian or Ubuntu: sudo apt install binutils (it is already there if you have installed gcc or build-essential).
  • On Fedora: sudo dnf install binutils.
  • On Windows: install WSL 2 with a Ubuntu distribution, then use the line above inside it.
  • On a Mac: macOS uses a different executable format and different system calls, and recent Macs have ARM64 processors. Use a Linux virtual machine or a container built for linux/amd64.

Check with as --version. This course was tested with GNU Binutils 2.38; anything from the last decade behaves the same for everything here.

Hello, assembly

Save this as hello.s:

asm
        .intel_syntax noprefix

        .section .rodata
msg:    .ascii "Hello, assembly!\n"
        .equ msg_len, . - msg

        .text
        .globl _start
_start:
        # write(1, msg, msg_len)
        mov     eax, 1              # system call number 1 is write
        mov     edi, 1              # argument 1: file descriptor 1, standard output
        lea     rsi, [rip + msg]    # argument 2: the address of the bytes
        mov     edx, msg_len        # argument 3: how many bytes
        syscall

        # exit(0)
        mov     eax, 60             # system call number 60 is exit
        xor     edi, edi            # argument 1: status 0 (a register XORed with itself is 0)
        syscall

Then assemble, link and run it:

bash
as --64 -o hello.o hello.s     # assemble: text to an object file of machine code
ld -o hello hello.o            # link: object file(s) to an executable
./hello
echo "exit status: $?"

It prints:

text
Hello, assembly!
exit status: 0

Reading it line by line

.intel_syntax noprefix selects Intel syntax without % before register names.

.section .rodata says the following bytes belong in the read-only data section. An executable is divided into sections: .text holds instructions, .rodata constants, .data variables with initial values, and .bss zero-filled space. The operating system maps each with the right permissions, so a stray write into .rodata crashes instead of silently changing your message.

msg: .ascii "Hello, assembly!\n" puts 17 bytes into memory (the 16 visible characters and the newline byte, 10) and names the address of the first one msg. .ascii adds no terminating zero; .asciz would.

.equ msg_len, . - msg defines a constant. The dot means "the current address", just after the last byte of the string, so . - msg is the string's length, 17. The assembler computes it; it costs nothing at run time.

.text switches to the code section. .globl _start makes the label _start visible to the linker, and _start is where ld makes the program begin. (In C programs the C library supplies its own _start, which eventually calls your main. Here there is no C library, so we are the very first code that runs.)

The next five lines make a system call: a request to the Linux kernel. On x86-64 Linux, you put the call's number in rax and its arguments in rdi, rsi and rdx (and r10, r8, r9 for more), then execute syscall. The kernel does the work and puts the result in rax. Call number 1 is write(fd, address, count), which copies count bytes starting at address to the open file fd. File descriptor 1 is standard output, the terminal here.

You may have noticed that we put numbers into eax, edi and edx but an address into rsi. eax is the low 32-bit half of the 64-bit register rax, and writing to it clears the upper half. It is the usual way to load a small number, because the instruction is shorter. Lesson 2 explains register names properly.

lea rsi, [rip + msg] means "load the effective address": compute the address of msg, relative to the current instruction, and put that address (not the bytes stored there) into rsi. Lesson 3 explains why addresses are written relative to rip.

Finally, call number 60 is exit(status). A program written this way must end with an exit call: there is nothing after the last instruction to return to, and if you leave it out the processor runs on into whatever bytes follow and the program crashes with a segmentation fault.

Looking at the machine code

objdump disassembles an executable back into assembly. With -M intel it uses Intel syntax:

bash
objdump -d -M intel hello

On our machine it showed:

text
0000000000401000 <_start>:
  401000:	b8 01 00 00 00       	mov    eax,0x1
  401005:	bf 01 00 00 00       	mov    edi,0x1
  40100a:	48 8d 35 ef 0f 00 00 	lea    rsi,[rip+0xfef]        # 402000 <msg>
  401011:	ba 11 00 00 00       	mov    edx,0x11
  401016:	0f 05                	syscall 
  401018:	b8 3c 00 00 00       	mov    eax,0x3c
  40101d:	31 ff                	xor    edi,edi
  40101f:	0f 05                	syscall 

The left column is each instruction's address, the middle its bytes, the right the instruction again. Notice that msg_len has become the number 0x11 (17) and the label msg has become a distance from the next instruction, 0xfef bytes. Notice too that x86-64 instructions have different lengths: syscall is 2 bytes, lea is 7. The whole program's code is 33 bytes, and the executable file, mostly headers and padding, is under 9 kilobytes. A C "hello world" built with gcc on the same machine came to about 16 kilobytes, and it also loads the shared C library, a file of about two megabytes, every time it runs.

You can also watch the system calls happen with strace ./hello, which prints each call the program makes:

text
execve("./hello", ["./hello"], 0x7ffc31ced0d0 /* 95 vars */) = 0
write(1, "Hello, assembly!\n", 17Hello, assembly!
)      = 17
exit(0)                                 = ?
+++ exited with 0 +++

write returned 17, the number of bytes written. Our program ignored that answer; lesson 6 shows how to check it.

Worked examplesH

Text is bytes, and addresses are numbers

The .ascii directive is only a convenience. Text in memory is nothing but bytes, each holding a character's code, and you can write those bytes as numbers yourself. This program prints a greeting in Swahili using .byte, which emits one byte per value:

asm
        .intel_syntax noprefix

        .section .rodata
greeting:
        .byte 0x4A, 0x61, 0x6D, 0x62, 0x6F, 0x21, 10   # J a m b o ! newline
        .equ greeting_len, . - greeting

        .text
        .globl _start
_start:
        mov     eax, 1
        mov     edi, 1
        lea     rsi, [rip + greeting]
        mov     edx, greeting_len
        syscall

        mov     eax, 60
        xor     edi, edi
        syscall

It prints:

text
Jambo!

0x4A is 74, the ASCII and UTF-8 code for J; 0x61 is a; 10 is the newline. The processor neither knows nor cares that these bytes are letters. The terminal receives them and draws the matching glyphs.

Since a label is just an address, and an address is just a number, you can do arithmetic with it. This program writes only part of its message by starting further in and writing fewer bytes:

asm
        .intel_syntax noprefix

        .section .rodata
msg:    .ascii "Habari ya asubuhi\n"      # "good morning" in Swahili

        .text
        .globl _start
_start:
        mov     eax, 1
        mov     edi, 1
        lea     rsi, [rip + msg + 7]       # skip "Habari " (7 bytes)
        mov     edx, 2                     # write only "ya"
        syscall

        mov     eax, 1                     # rax held write's result; set the call number again
        mov     edi, 1
        lea     rsi, [rip + msg + 17]      # the newline is the 18th byte, at offset 17
        mov     edx, 1
        syscall

        mov     eax, 60
        xor     edi, edi
        syscall

It prints:

text
ya

Two habits are visible here. First, the second write sets eax to 1 again, because the first syscall replaced rax with its result. Second, offsets count from zero: the first byte is at msg + 0, so the eighteenth byte is at msg + 17. Counting from zero is natural in assembly, since an offset is a distance from the start, and it is why so many languages index their arrays from zero.

Common misconceptionsH

Common misunderstandings

Misconception

"Assembly is one language." It is a family of languages, one (or more) per processor family. x86-64, ARM64 and RISC-V assembly share ideas, such as registers, loads, stores and jumps, but not instructions, registers or syntax. Even for one processor, different assemblers (GNU as, NASM, Microsoft's MASM) spell directives differently. When you read an assembly snippet online, first find out which processor and which assembler it is for.

Misconception

"An assembly program runs on any computer with that processor." Our program also depends on the operating system: the numbers 1 and 60 for write and exit, the registers that carry arguments, and the executable format are Linux's. The same x86-64 processor running Windows or macOS has different system calls, so this exact program will not run there, even though every instruction is valid.

Misconception

"Hand-written assembly is always faster than compiled code." Modern compilers know thousands of tricks about instruction costs, and they never get tired. A beginner's assembly is usually slower than what gcc -O2 writes for the same C. Experts beat the compiler in narrow places (a specific loop, a special instruction the compiler will not use), and they confirm it by measuring. The more common professional skill is reading the compiler's output, not replacing it.

Misconception

"Any name works as a label." In Intel-syntax mode the GNU assembler treats words such as byte, word, dword, qword and offset as keywords. A label called word assembles without an error but [rip + word] does not mean what you expect: in our tests the program printed garbage. Choose descriptive names like reply or greeting.

Exercises

Exercises

Try each question before opening the hints. Where a question shows a program, every answer was checked by running it.

1. First steps in assembly

Warm-upHuman

You run as --64 -o prog.o prog.s and then ld -o prog prog.o. What does each step produce?

Choose one

2. First steps in assembly

Warm-upComputational

On x86-64 Linux, which number goes into rax (or eax) to make the exit system call?

3. First steps in assembly

Warm-upComputational

What value does the assembler give len here?

msg:    .ascii "Salaam\n"
        .equ len, . - msg

4. First steps in assembly

CoreComputational

What does this program print? (Type the visible characters, without the newline.)

        .intel_syntax noprefix
        .section .rodata
msg:    .ascii "Bonjour, monde!\n"

        .text
        .globl _start
_start:
        mov     eax, 1
        mov     edi, 1
        lea     rsi, [rip + msg + 9]
        mov     edx, 7
        syscall

        mov     eax, 60
        xor     edi, edi
        syscall

5. First steps in assembly

CoreComputational

This program's message is written as numbers. What does it print? (Without the newline.)

        .intel_syntax noprefix
        .section .rodata
reply:  .byte 0x4F, 0x6B, 0x21, 10

        .text
        .globl _start
_start:
        mov     eax, 1
        mov     edi, 1
        lea     rsi, [rip + reply]
        mov     edx, 4
        syscall
        mov     eax, 60
        xor     edi, edi
        syscall

Useful codes: 0x41 is A, 0x61 is a, 0x21 is !.

6. First steps in assembly

CoreHuman

A friend copies the hello executable from this lesson to three machines. On which one will it run unchanged?

Choose one

7. First steps in assembly

StretchHuman

You delete the last three lines (the exit system call) from the hello program, then assemble, link and run it. What happens?

Choose one

Further reading and resources