x86 Assembly Tutorial
x86 Assembly Tutorial
Flags types:
- Status
- Control
- System
5
● Important Flags
○ CF: Carry flag
6
Instruction Syntax Conventions
7
source: http://flint.cs.yale.edu/cs422/doc/pc-arch.html
Memory Addressing
● Memory addressing modes:
1. Real address (unprotected) 2. Protected 3. System Management
○ 16-bit segment add. [times 16, i.e., +4 bits] + 16-bit offset add.
8
Memory Addressing (Real Mode)
● Format (AT&T syntax):
○ segment:displacement(base,index,scale)
● Displacement: Constant
9
Data Types
10
Instructions: Arithmetic & Logic
● Arithmetic, such as:
○ add/sub{l,w,b} source,dest
○ inc/dec/neg{l,w,b} dest
○ cmp{l,w,b} source,dest
● Logic, such as:
○ and/or/xor{l,w,b} source,dest ...
● Restrictions
○ No more than one memory operand 11
Instructions: Data Transfer
● mov{l,w,b} source, dest
● xchg{l,w,b} source, dest (exchange)
● movsb/movsw (move byte/word)
○ %es:(%di) ← %ds:(%si)
○ Often used with %cx to move a number of bytes
■ movw $0x10,%cx
■ rep movsw (repeat)
12
Stack Layout
...
● Grows from high to low (function arg. n …)
function arg. 1
○ Lowest address = “top” of stack %bp + 8
return address
%bp + 4
old %ebp
● %sp points to top of the stack local var. 1
%bp
%bp - 4
(local var. n …)
○ Used to reference temporary variables
(callee-save regs)
● %bp points to bottom of stack frame
callee-save reg 1
(callee-save regs)
○ dest ← %ss:(%sp)
callee-save reg 1
○ %sp ← %sp + 4 (temp var. n …)
%sp + 4
temp var. 1
%sp 15
Instructions: Control Flow
● jmp label ● call label
○ %eip ← label ○ push %eip
○ %eip ← label
● ljmp NEW_CS, offset
○ %cs ← NEW_CS ● ret
○ %eip ← offset ○ pop %eip
16
Instructions: Conditional Jump
● Relies on %eflags bits
○ Most arithmetic operations change %eflags
● j{e,ne,l,le,g,ge}
○ Jump to label if {=,!=,<,<=,>,>=}
17
Assembler Directives
● Commands that speak directly to the assembler
○ Are not instructions
● Examples:
○ .globl - defines a list of symbols as global
○ .equ - defines a constant (like #define)
○ .bytes, .word, .asciz - reserve space in memory
https://docs.oracle.com/cd/E26502_01/html/E28388/eoiyg.html
18
Assembler Segments
● Organize memory by data properties
○ .text - holds executable instructions
○ .bss - holds zero-initialized data (e.g. static int i;)
○ .data - holds initialized data (e.g. char c = ‘a’;)
○ .rodata - holds read-only data
● Stack / Heap - Set up by linker / loader / programmer
19
Basic Input/Output System (BIOS) Services
22