GAS (GNU Assembler) Comprehensive Cheatsheet
Installation Instructions
# Using MSYS2
pacman - S mingw- w64- x86_64- gcc
# Or install via MinGW
sudo apt-get update
sudo apt-get install gcc-multilib binutils
# Using Homebrew
brew install gcc
brew install binutils
Essential GAS Assembly Directives and Instructions
Basic Syntax and Directives
Basic Instruction Syntax
instruction source, destination
Define Byte
.byte 42 # 8-bit value
.byte 'A' # Character literal
Define Word (16-bit)
.word 1000 # 16-bit integer
Define Long (32-bit)
.long 65536 # 32-bit integer
Define Quad (64-bit)
.quad 1000000 # 64-bit integer
Reserving Memory Space
.comm buffer, 100 # Reserve 100 bytes of uninitialized memory
Global Symbol Declaration
.globl main # Make symbol visible globally
External Symbol Import
.extern printf # Import external function
64-bit Register Move
movq $42 , %rax # Move immediate to 64-bit register
32-bit Register Move
movl $100 , %eax # Move immediate to 32-bit register
Register to Register Move
movq %rbx , %rax # Copy value from rbx to rax
Memory to Register Move
movq (address), %rax # Move from memory to register
Addition
addq $10 , %rax # Add 10 to rax
Subtraction
subq $5 , %rbx # Subtract 5 from rbx
Multiplication
imulq %rcx # Multiply rax by rcx
Division
idivq %rdx # Divide rax by rdx
Compare Instructions
cmpq %rax , %rbx # Compare rax and rbx
Conditional Jumps
je label # Jump if equal
jne label # Jump if not equal
jg label # Jump if greater
jl label # Jump if less
Push to Stack
pushq %rax # Push rax onto stack
Pop from Stack
popq %rbx # Pop top of stack to rbx
System Calls (Linux x86_64)
Exit System Call
movq $60 , %rax # Exit syscall number
movq $0 , %rdi # Exit status
syscall # Invoke syscall
Write System Call
movq $1 , %rax # Write syscall
movq $1 , %rdi # Stdout
movq $message, %rsi # Buffer
movq $14 , %rdx # Length
syscall
Simple Macro
.macro print_msg
movq $1 , %rax
movq $1 , %rdi
movq $message, %rsi
movq $14 , %rdx
syscall
.endm
Preprocessor Conditionals
#ifdef DEBUG
# Debug-specific code
#endif
Advanced Memory Operations
Indirect Addressing
movq (%rax ), %rbx # Move value pointed by rax to rbx
Base + Displacement Addressing
movq 8 (%rsp ), %rax # Move value 8 bytes above stack pointer
Floating Point Operations
SSE Floating Point Move
movsd x(%rip ), %xmm0 # Move double precision float
String Copy
rep movsb # Repeat move string byte
Shift Left
shlq $2 , %rax # Shift left by 2 bits
Shift Right
shrq $1 , %rbx # Shift right by 1 bit
as -o output.o input.s
ld -o program output.o
gcc -c input.s -o output.o
gcc output.o -o program
Use AT&T syntax consistently
Be mindful of register sizes
Comment your code thoroughly
Handle potential overflow scenarios
Use appropriate addressing modes
Use -g
flag for debugging symbols
Leverage gdb
for step-by-step execution
Check register states during debugging
Understand memory layout and alignment