This guide provides an introduction to x86_64 assembly, including a list of common instructions, an overview of 64-bit CPU registers, and a practical example program.
x86_64 is an extension of the x86 architecture, supporting 64-bit registers, larger memory addressing, and enhanced instruction sets. It is widely used in modern processors, including those from Intel and AMD.
In x86_64, the number of general-purpose registers increases compared to x86, and their sizes expand to 64 bits.
Register | Purpose | Notes |
---|---|---|
RAX |
Accumulator for operands | Used in arithmetic and function returns. |
RBX |
Base register | Used for addressing. |
RCX |
Counter for loops | Iteration purposes. |
RDX |
Data register | I/O and arithmetic. |
RSI |
Source index for string operations | Source address in memory operations. |
RDI |
Destination index for string ops | Destination address in memory operations. |
RSP |
Stack pointer | Tracks the top of the stack. |
RBP |
Base pointer | Points to the base of the stack frame. |
R8 -R15 |
Additional general-purpose regs | Introduced in x86_64. |
Register | Purpose |
---|---|
CS |
Code Segment |
DS |
Data Segment |
SS |
Stack Segment |
The instruction set of x86_64 largely builds upon x86, with additional enhancements for 64-bit operations. Below are some key instructions:
MOV
- Move dataPUSH
- Push data onto the stackPOP
- Pop data off the stackLEA
- Load effective address
ADD
- AddSUB
- SubtractIMUL
- Multiply (signed)IDIV
- Divide (signed)INC
- IncrementDEC
- Decrement
AND
- Bitwise ANDOR
- Bitwise ORXOR
- Bitwise XORSHL
- Shift leftSHR
- Shift right
JMP
- Unconditional jumpJE
/JZ
- Jump if equal/zeroJNE
/JNZ
- Jump if not equal/not zeroCALL
- Call a procedureRET
- Return from a procedure
Below is a basic example that calculates the sum of numbers from 1 to 10 using x86_64 assembly.
section .data ; Data section
result dq 0 ; Allocate space for the result
section .text ; Code section
global _start ; Entry point for the program
_start:
mov rax, 0 ; Accumulator for the sum
mov rcx, 10 ; Counter for the loop
loop_start:
add rax, rcx ; Add the value of RCX to RAX
dec rcx ; Decrement RCX
jnz loop_start ; Repeat until RCX = 0
; Store the result
mov [result], rax ; Move the final sum into memory
; Exit the program
mov rax, 60 ; Syscall for exit
xor rdi, rdi ; Return code 0
syscall ; Exit
- Data Section:
result
is allocated to store the final sum.
- Initialization:
RAX
is cleared to prepare for the sum.RCX
is set to 10 (loop counter).
- Loop:
- The
ADD
instruction accumulates the value ofRCX
intoRAX
. - The
DEC
instruction decrementsRCX
. JNZ
repeats the loop whileRCX
is not zero.
- The
- Store and Exit:
- The final result is stored in
result
. - The program exits using the Linux syscall mechanism.
- The final result is stored in
- Save the code to a file (e.g.,
sum64.asm
). - Assemble the code using NASM:
nasm -f elf64 sum64.asm
- Link the object file using ld:
ld -o sum64 sum64.o
- Run the program:
./sum64