Previous: Programming in Pascal Reading map Next: C Programming
Volume I: Foundations of Programming (Chapter 3)Code & tests Chapter diagrams Download editable SVGs
The main motivation to learn assembly is not to write real-world programs, but to understand how C programs are executed at the hardware level. Although 64-bit processors are standard today, we study the 32-bit i386 architecture because its limited amount of registers forces a better understanding of the stack.
Chapter Map
assembly in ordinary software:
assembly remains useful when hardware access or severe resource limits require it
main reason to study assembly: understand what high-level operations cost
professional understanding should connect all levels of the computer
learning one instruction set teaches the way to reason about other processors
book uses 32-bit i386 instructions under Unix
32-bit examples expose the complete stack frame
NASM uses Intel syntax
review instruction execution and the distinction between assembler and assembly language
before systematic instruction study:
The Intel processor line evolved from the 4-bit 4004 and 16-bit 8086/8088 through the 80286's protected mode to the 32-bit 80386 (i386) with paging and 4 GB addressing, later extended to 64-bit x86-64 while preserving register compatibility.
Intel family before x86:
8086, 8088 and 80186:
80286:
80386 / i386:
x86 development and 64-bit extensions:
author's performance aside:
x86_64 processors can run the book's 32-bit instruction sequences
Instructions and data share memory in the Von Neumann model: programs can also be processed as data.
computer = CPU + RAM
RAM:
program:
binary representation is customary, but separate from these architectural principles
programs can be treated as data
general-purpose registers: temporary storage for calculations
special-purpose registers include the instruction pointer
CPU execution cycle:
CPU follows instructions; it does not understand the program's purpose control is at the location currently addressed by the instruction pointer
branches and loops explicitly replace the instruction pointer
jumps:
subroutine call:
transfer of control = explicitly changing the instruction pointer
fetch at instruction pointer -> advance by instruction size -> decode / execute -> repeat
0 through
2^32 - 1.Unix runs several tasks concurrently
memory protection:
CPU modes:
privileged operations include:
user task:
return to privileged mode also transfers control to the OS
physical address = number of a real memory location
virtual address = address used by a program
each task can have its own address space
book studies user-mode instructions in Unix's flat memory model
%include "stud_io.inc" ; inserts the macros
global _start ; this label should be seen from outside
; the module
section .text ; code section
_start: ; label _start means that
; we have to start program from here
mov eax, 0 ; counter in eax
again: PRINT "Hello" ; use macro from "stud_io.inc"
PUTCHAR 10 ; next line
inc eax ; increase counter
cmp eax, 5 ; have we printed 5 times already?
jl again ; if not do it again
FINISH ; we need syscall to finish the program
To compile the program above, you have to use stud_io.inc file:
nasm -f elf hello5.asm
ld -m elf_i386 hello5.o -o hello5
./hello5
learn instruction notation and assembler syntax together through a working example
goal: print Hello followed by a newline five times
stud_io.inc supplies the example's macros
choose the file's OS configuration:
assembly source contains:
%include "stud_io.inc": insert the macro definitions into the source
include definitions before their first use
global _start exports the entry-point label
sections in a file become memory regions when the OS loads the program
section names:
mov eax, 0:
_start is a label attached to that instruction
mov eax, 0 becomes five bytes: b8 00 00 00 00
label = identifier associated with a number
labels belong to assembly/linking information
NASM permits labels with or without a colon
_start marks the entry point
again labels the loop's first operation
PRINT is not a CPU instruction
PUTCHAR 10 emits the newline
inc eax records one more printed line
cmp eax, 5 records comparison results in the flags register
jl again:
when EAX reaches 5, jl falls through
global _start makes entry-point information available to the linker
whole algorithm:
save assembly source in hello5.asm
building has two stages:
even a one-module program still needs linking
historical i386 build commands:
uname -a helps identify the architecture
-o selects output filename
%include "stud_io.inc"
global _start
section .text
_start: mov eax, 0
again: PRINT "Hello"
PUTCHAR 10
inc eax
cmp eax, 5
jl again
FINISH
%include "stud_io.inc" ; inserts the macros
global _start ; this label should be seen from outside
; the module
section .text ; code section
_start: ; label _start means that
; we have to start program from here
mov eax, 0 ; counter in eax
again: PRINT "Hello" ; use macro from "stud_io.inc"
PUTCHAR 10 ; next line
inc eax ; increase counter
cmp eax, 5 ; have we printed 5 times already?
jl again ; if not do it again
FINISH ; we need syscall to finish the program
%include "stud_io.inc"
global _start
section .text
_start: mov eax, 0
again: PRINT "Hello"
PUTCHAR 10
inc eax
cmp eax, 5
jl again
FINISH
stud_io.incPRINT "Hello"/'Hello'
PUTCHAR 10/[a-d][l,h]/[label]
GETCHAR -> al (C-d = -1)
FINISH
four macros: PRINT, PUTCHAR, GETCHAR and FINISH
PRINT:
PUTCHAR:
GETCHAR:
FINISH:
assembly formatting differs from Pascal formatting
one source line is the main syntactic unit
fixed-format Fortran reflected punched cards
assembly source describes a linear memory image
align code in columns:
general source-formatting principles still apply
book's source convention: ASCII characters and English comments
keep source lines within 79 characters
use meaningful labels and sensible decomposition
basic user-mode instruction set:
privileged instructions are outside this introduction
Beyond basic moves and arithmetic, x86 provides flag operations
(stc/clc, lahf), sign- and
zero-extending moves (movsx/movzx), processor
identification (cpuid), byte swapping (bswap),
and atomic register-memory exchange (xchg).
stc / clc set/clear CF
lahf copies selected flags into AH
movsx / movzx combine copying with widening
cpuid reports processor identity and supported features
other examples:
xchg exchanges two equal-sized operands
lock prefix makes supported memory read-modify-write instructions atomic
nop: no operation
| ID | Name | Special purpose | Parts |
|---|---|---|---|
eax* |
Accumulator | Result for [i]mul, [i]div |
al, ah, ax |
ebx |
Base | - | bl, bh, bx |
ecx |
Counter | Loop iterations | cl, ch, cx |
edx |
Data | Used with [i]mul, [i]div |
dl, dh, dx |
esi |
Source Index | Address of source array | si |
edi |
Destination Index | Address of destination array | di |
ebp |
Base Pointer | Address of stack frame in procedures | bp |
esp |
Stack Pointer | Current address of stack frame | sp |
eip |
Instruction Pointer | Address of next instruction | ip |
ZF |
Zero Flag | Set when zero | - |
CF |
Carry Flag | Unsigned overflow | - |
SF |
Sign Flag | Negative number | - |
OF |
Overflow Flag | Signed overflow | - |
DF |
Direction Flag | Set with std or clear with cld |
- |
*in e[abcd]x, e and x both stand for extended
register = CPU storage for a fixed number of bits
segment registers: CS, DS, SS, ES, FS, GS
code/data/stack memory regions are not simply the hardware segments
32-bit general-purpose registers:
AX, BX, CX and DX also have byte parts
EAX / AX: accumulator
EBX / BX: base
ECX / CX / CL: counter
EDX / DX: data
ESI and EDI: source and destination indices
EBP: base pointer
ESP: stack pointer
special registers considered here: EIP and the flags register
EIP: address of next instruction
i386 instruction length varies from 1 to 15 bytes
flags are individual bits, not one ordinary numeric value
arithmetic sets status flags; conditional jumps test them
EFLAGS is the 32-bit extension of FLAGS
| Segment | Permission | Contents |
|---|---|---|
.text (Code) |
No write | Shared copies must not modify each other |
.data (Data) |
No execute | Initialized variables |
.bss (Data) |
No execute | Uninitialized vars, heap (only length stored) |
| Stack | - | Params, env vars, locals, return addresses |
registers hold temporary results; larger and longer-lived data belongs in RAM
instructions and data share the virtual address space
memory protection assigns access rights to regions
principal task regions: code, data and stack
code region:
.text supplies the machine code
data region:
historical Unix examples of requesting memory:
stack region:
global _start
section .text
_start:
mov eax, 45
xor ebx, ebx
int 0x80
mov esi, eax
add eax, 4096
mov ebx, eax
mov eax, 45
int 0x80
mov eax, 1
mov ebx, 0
int 0x80
%include "calls.inc"
%define NODE_VALUE 0
%define NODE_NEXT 4
%define NODE_SIZE 8
%define BUF_SIZE 8
global _start
extern sint2str ; sint2str.asm
section .bss
buf resb BUF_SIZE
section .data
newline db 10
space db 32
section .text
malloc:
; < (size) > (old address) : -1
pbegin 0, ebx, esi, edi
mov ebx, [ebp+8] ; size
scall 45, 0
cmp ecx, -1
je .failed
mov esi, eax
lea edi, [esi + ebx]
scall 45, edi
cmp ecx, -1
je .failed
cmp eax, edi
jne .failed
mov eax, esi
jmp .end
.failed:
mov eax, -1
.end:
pend ebx, esi, edi
push:
; < (value) > : -1
pbegin 0, ebx, esi
mov esi, [ebp+8] ; address of header
mov ebx, [ebp+12] ; value
pcall malloc, NODE_SIZE
cmp eax, -1
je .end
mov ecx, [esi]
mov [eax + NODE_VALUE], ebx
mov [eax + NODE_NEXT], ecx
mov [esi], eax
xor eax, eax
.end:
pend ebx, esi
print:
pbegin 0, ebx
mov ebx, [ebp+8]
.loop:
pcall sint2str, [ebx + NODE_VALUE], buf
scall 4, 1, buf, eax
scall 4, 1, space, 1
mov ebx, [ebx + NODE_NEXT]
cmp ebx, 0
jne .loop
pend ebx
_start:
sub esp, 4
mov dword [esp], 0
mov esi, esp
pcall push, esi, 1
pcall push, esi, 2
pcall push, esi, 3
pcall push, esi, 4
pcall print, [esi]
scall 4, 1, newline, 1
jmp .end
.failed:
scall 1, 1
.end:
scall 1, 0
%include "calls.inc"
%define NODE_VALUE 0
%define NODE_NEXT 4
%define NODE_SIZE 8
%define BUF_SIZE 8
global _start
extern sint2str ; sint2str.asm
section .bss
buf resb BUF_SIZE
head resd 1
section .data
newline db 10
space db 32
section .text
malloc:
; < (size) > (old address) : -1
pbegin 0, ebx, esi, edi
mov ebx, [ebp+8] ; size
scall 45, 0
cmp ecx, -1
je .failed
mov esi, eax
lea edi, [esi + ebx]
scall 45, edi
cmp ecx, -1
je .failed
cmp eax, edi
jne .failed
mov eax, esi
jmp .end
.failed:
mov eax, -1
.end:
pend ebx, esi, edi
push:
; < (value) > : -1
pbegin 0, ebx, esi
mov esi, [ebp+8] ; address of header
mov ebx, [ebp+12] ; value
pcall malloc, NODE_SIZE
cmp eax, -1
je .end
mov ecx, [esi]
mov [eax + NODE_VALUE], ebx
mov [eax + NODE_NEXT], ecx
mov [esi], eax
xor eax, eax
.end:
pend ebx, esi
print:
pbegin 0, ebx
mov ebx, [ebp+8]
.loop:
test ebx, ebx
je .end
pcall sint2str, [ebx + NODE_VALUE], buf
scall 4, 1, buf, eax
scall 4, 1, space, 1
mov ebx, [ebx + NODE_NEXT]
jmp .loop
.end:
pend ebx
_start:
pcall push, head, 1
pcall push, head, 2
pcall push, head, 3
pcall push, head, 4
pcall print, [esi]
scall 4, 1, newline, 1
jmp .end
.failed:
scall 1, 1
.end:
scall 1, 0
section .bss
string resb 32
count resw 0e5h ; 229 words = 458 bytes
x resd 0b2h ; 178 dwords = 712 bytes
section .data
fibon dw 1, 1, 2, 3, 5, 8, 13, 21
dig7 db '7' ; char -> ASCII code
welmsg db 'Hello there'
panic db 'Don', "'", 't panic!"'
| size | name | bss | data |
|---|---|---|---|
| 1-byte | byte | resb | db |
| 2-byte | word | resw | dw |
| 4-byte | dword | resd | dd |
| 8-byte | qword | resq | dq |
| 10-byte | tword | rest | dt |
storage directives belong to NASM syntax, not the processor instruction set
assembling instructions creates a memory image of their machine-code bytes
the assembler can also construct an image of data
section selects which image subsequent source contributes to
storage directives either reserve uninitialized storage or provide initial values
NASM size terminology preserves the older x86 convention
reserve uninitialized elements:
define initialized elements:
numeric literals:
quoted characters stand for their codes
strings can also be supplied to dw/dd
usual placement:
unchanging data can be placed in the code region
assembler can accept instructions/directives in inappropriate sections
%include "stud_io.inc"
global _start
section .data
line dd 'a_there_c',0
section .text
_start:
mov ecx, 0
lp:
mov eax, [line+ecx]
PUTCHAR al
add ecx, 1
cmp al, 0
jne lp
end:
PUTCHAR 10
FINISH
mov Command
and Its Parameterssection .data
count dd 0
section .text
mov eax, ebx ; ebx -> eax
mov eax, 5 ; immediate -> eax
mov eax, count ; address of count -> eax
mov eax, 0x25f28a2d ; same if count is at 0x25f28a2d
mov [count], eax ; eax -> memory at count
mov illustrates copying, operand sizes and addressing
mov destination, source:
register operand: names a register
immediate operand: value encoded directly in the instruction
one mnemonic can describe different machine encodings
memory operand in NASM always uses square brackets
label without brackets is a number substituted by the assembler brackets request access to memory at that number
Indirect addressing: mov eax, [ebx] -
memory evaluated at runtime. Useful for arrays:
section .bss
array resb 256
section .text
mov ecx, 256
mov edi, array ; address of array
mov al, '@'
again: mov [edi], al ; '@' into edi
inc edi ; next element of array
dec ecx
jnz again ; again if counter is not zero
Effective address general form:
; constant + address + 1/2/4 * address (not esp)
mov eax, [array+ebx+2*ebi]
Matrix access:
section .bss
matrix resd 10*15
section .text
mov eax, 180 ; 3*15*4 (3rd row)
mov ebx, 5 ; column number
mov edx, [matrix+eax+4*ebx] ; matrix[row + col*4]
lea computes address without memory access - useful for
address arithmetic:
lea eax, [1000+ebx+8*ecx]
array traversal needs a different element address on each iteration
indirect addressing:
mov ebx, [eax]: read four bytes from the address held in EAX mov ebx, eax: copy the register value itself
fill 256 bytes with '@':
example favors familiar instructions over minimizing registers
effective address = address actually used by an instruction
i386 address form: displacement + base register + index register * scale
address expression has hardware limits
NASM can rearrange equivalent expressions
matrix example: 10 rows of 15 four-byte elements
lea destination, [address expression]:
lea also performs useful ordinary arithmetic
global _start
section .text
_start:
mov ebx, 1
mov ecx, 2
lea eax, [1000+ebx+8*ecx]
mov eax, 1
mov ebx, 0
int 80h
5 operand combinations (same for add, sub,
cmp):
mov eax, ebx ; register <- register
mov eax, 5 ; register <- immediate
mov eax, [x] ; register <- memory
mov [x], ebx ; memory <- register
mov dword [x], 5 ; memory <- immediate
Size specifiers:
mov dword [x], 5
mov [x], byte 5
Different machine commands:
mov eax, 2
mov eax, [x]
mov [x], eax
mov [x], al
Same result:
mov eax, 17
mov eax, x
operand kinds: immediate, register and memory
mov destination must be writable storage
valid mov combinations:
both operands describe the same data width
memory plus immediate needs an explicit size when otherwise ambiguous
mnemonic alone does not determine the machine encoding
Same 5 operand combinations as mov:
add eax, ebx ; eax = eax + ebx
add eax, 5 ; eax = eax + 5
add eax, [x] ; eax = eax + *x
add [x], ecx ; *x = *x + ecx
add dword [x], 12 ; *x = *x + 12
Processor does not distinguish signed/unsigned. We have to rely on
ZF, CF, SF, OF:
; multi-register addition (edx:eax + ebx:ecx):
add eax, ecx ; lower parts
adc edx, ebx ; upper parts + carry
; same for subtraction:
sub eax, ecx
sbb edx, ebx
inc eax ; +1 (sets ZF, SF, OF but not CF)
dec ecx ; -1
neg eax ; negate (sets all 4 flags)
cmp eax, ebx ; like sub but result not saved
add / sub destination, source:
signed and unsigned addition/subtraction use the same bit operations
ZF = 1 when the result is zero
signed interpretation:
unsigned interpretation:
CPU sets flags without knowing which interpretation the programmer intends
adc / sbb include the old carry flag
multiword example: EDX:EAX and EBX:ECX
inc / dec add or subtract 1
neg replaces its operand with 0 - operand
cmp performs subtraction only for its flags
[i]mul for unsigned/signed multiplication:
| Size | Command | Operation |
|---|---|---|
| 8-bit | [i]mul cl |
al * cl = ax |
| 16-bit | [i]mul cx |
ax * cx = dx:ax |
| 32-bit | [i]mul ecx |
eax * ecx = edx:eax |
CF=OF=0 when result fits in lower part (al,
ax, eax).
Division (flags unused):
| Size | Command | Quotient | Remainder |
|---|---|---|---|
| 8-bit | [i]div cl |
ax / cl = al |
ax % cl = ah |
| 16-bit | [i]div cx |
dx:ax / cx = ax |
dx:ax % cx = dx |
| 32-bit | [i]div ecx |
edx:eax / ecx = eax |
edx:eax % ecx = edx |
Sign-extension for signed division:
| Conversion | Command | Operation |
|---|---|---|
| 8 -> 16-bit | cbw |
al -> ax |
| 16 -> 32-bit | cwd |
ax -> dx:ax |
| 16 -> 32-bit | cwde |
ax -> eax |
| 32 -> 64-bit | cdq |
eax -> edx:eax |
multiplication/division require more complicated hardware than addition
signed and unsigned versions need different instructions
multiplication can require twice the operand width
division:
one-operand forms use implicit accumulator registers
mul = unsigned; imul = signed
multiplication sets CF and OF together
div = unsigned; idiv = signed
division exception:
signed extension before division:
unsigned extension: clear AH, DX or EDX as appropriate
Jumping is done by changing address in EIP:
jmp cycle ; direct jump to label
jmp eax ; jump to address in eax
jmp [addr] ; jump to address in memory
jmp [eax] ; jump to address from [eax]
With near you can jump anywhere in the code, with
short only +/-127 bytes:
mylabel:
;
; small number of commands
;
jmp short mylabel
| Instruction(s) | Condition | Flags Required |
|---|---|---|
je / jz |
a = b |
ZF = 1 |
jne / jnz |
a != b |
ZF = 0 |
jl / jnge |
a < b |
SF != OF |
jle / jng |
a <= b |
SF != OF or ZF = 1 |
jg / jnle |
a > b |
SF = OF and ZF = 0 |
jge / jnl |
a >= b |
SF = OF |
jb / jnae / jc |
a < b |
CF = 1 |
jbe / jna |
a <= b |
CF = 1 or ZF = 1 |
ja / jnbe |
a > b |
CF = 0 and ZF = 0 |
jae / jnb / jnc |
a >= b |
CF = 0 |
Unconditional: near default. Conditional:
short default, direct only.
cmp eax, ebx
jz are_equal
;
;
;
are_equal:
;
;
;
We can get jl in 2 cases:
| Case | a | b | (a-b) | Flags |
|---|---|---|---|---|
| 1. Standard Less | 5 | 10 | 5 - 10 = -5 | SF=1, OF=0 |
| 2. Overflow Wrap | -100 | 50 | -100 - 50 = 106 | SF=0, OF=1 |
jump explicitly changes EIP
jump forms:
author prefers explicitly chosen encodings over assembler optimization
jmp targets:
direct relative jump encoding stores target minus following-instruction address
short jump can reduce code size
conditional jumps test flags or, for some instructions, a register
ordinary conditional jumps take a direct target
conditional direct jumps also encode relative displacements
single-flag jumps:
cmp eax,ebx followed by jz branches when the two values are equal
ordering needs more than the zero flag
signed a < b: SF differs from OF
unsigned a < b: subtraction needs a borrow
greater-than and less-than-or-equal also need ZF
comparison jump families:
In assembly, the general pattern is to check the opposite condition.
Typical while loop in assembly:
cycle: cmp eax, ebx
jnz cycle_quit
; ...
jmp cycle
cycle_quit:
Typical if, else in assembly:
cmp eax, ebx
jnz else_branch
; ...
jmp if_quit
else_branch:
; ...
if_quit:
usually jump when the source-level condition is false
while loop:
if/else:
true case naturally falls through into its body
negated jump names can make the source condition clearer
Sum of array elements using loop:
.section bss
array resd 1000
.section text
mov ecx, 1000
mov esi, array
mov eax, 0
lp: add eax, [esi]
add esi, 4
loop lp
loop is equivalent to:
dec ecx
jnz lp
Jump is near only.
Fix ecx=0 at start with
jecxz/jcxz:
jecxz lpq
lp: ;
;
loop lp
lpq:
loope/loopz and
loopne/loopnz also check ZF.
ECX has dedicated counter instructions
loop target:
sum 1000 dwords:
dec register / jnz can implement a similar countdown
one-register array traversal:
jecxz / jcxz test ECX / CX directly, without flags
loope/loopz:
loopne/loopnz:
%include "stud_io.inc"
global _start
section .text
_start: mov ecx, 5
lp: PRINT "Hello"
PUTCHAR 10
cmp eax, eax
loopne lp
jnz end
PRINT "ZF"
PUTCHAR 10
end: FINISH
Registers and memory can be treated as independent bit strings, not just integers:
; Bitwise commands:
and al, bl ; per-bit AND, sets ZF, SF
or ax, cx ; per-bit OR
xor edx, edx ; per-bit XOR (usually only ZF)
xor eax, eax ; same as mov eax, 0 (1 byte vs 5)
and eax, 3 ; same as eax % 4
and eax, 0x1f ; same as eax % 32
test eax, eax ; only sets flags, eax=0 -> ZF=1
shl eax, 3 ; left shift = multiply by 2^3
shr eax, 5 ; right shift = divide by 2^5
sar eax, 4 ; arithmetic right shift (sign)
512 items tracked in 16 x 32-bit integers. Item / 32 =
array index, item % 32 = bit position:
; We can achieve this using:
mov edx, ebx ; copy ebx to edx
mov ebx, 11111b ; bit position in bl
shr edx, 5 ; array index in dl
mov bh, dl ; now in bh
; Or even simpler:
shl ebx, 3 ; array index in bh
shr bl, 3 ; bit position in bl
Zero, add, remove, check, count bits:
section .bss
set512 resd 16
; zero all 512 bits:
section .text
xor eax, eax
mov ecx, 16
mov esi, set512
lp: mov [esi+4*ecx-4], eax
loop lp
; if we want to add an item into the array of 512 bits:
; item number is in ebx
mov cl, bl ; only cl for shift count
and cl, 11111b ; bit number is in cl now
mov eax, 1
shl eax, cl ; create bitmask
mov edx, ebx ; 4-byte registers only in indirect addr
shr edx, 5 ; array index in edx
or [set512+4*edx], eax
; if we want to remove an item:
mov cl, bl
mov cl, 11111b
mov eax, 1
shl eax, cl
not eax
mov edx, ebx
shr edx, 5
and [set512+4*edx], eax
; check if there is an item in the array:
test [set512+4*edx], eax
; ZF=0 -> element present
; count set bits:
xor ebx, ebx
mov ecx, 15
lp: mov eax, [set512+4*ecx]
lp2: test eax, 1
jz not_one
inc ebx
not_one:
shr eax, 1
test eax, eax
jnz lp2
jecxz quit
dec ecx
jmp lp
quit:
; now the result is in ebx
register/memory contents can represent independent bits instead of integers
and / or / xor combine corresponding bits
not inverts every bit of its one operand
useful identities:
test performs AND for flags without storing a result
shl / shr destination, count:
logical one-bit shift:
shl / sal multiply by powers of two, subject to finite-width overflow shr divides unsigned values by powers of two
sar copies the sign bit while shifting right
shifts can avoid accumulator setup and expensive
multiplication/division
other bit instructions mentioned:
bitset represents a subset of a finite universe
store the set as 16 dwords
packing index results for 0 <= X < 512:
clear the set:
insert X:
remove X:
test membership:
count present elements:
String operations auto-increment esi/edi by
1, 2 or 4 bytes:
| Command | Description | Register (reg) | Equivalent |
|---|---|---|---|
stos{b,w,d} |
Store | {al,ax,eax} |
mov [edi], reg |
lods{b,w,d} |
Load | {al,ax,eax} |
mov reg, [esi] |
movs{b,w,d} |
Move | - | mov [edi], [esi] |
cmps{b,w,d} |
Compare | - | cmp [edi], [esi] |
scas{b,w,d} |
Scan | {al,ax,eax} |
cmp [edi], reg |
Instead of loop, use repX commands:
| Command | used with Commands | Description |
|---|---|---|
rep |
stosX, loadsX, movsX |
Repeat |
repe/repz |
cmpsX, scasX |
Repeat until ZF=0 |
repne/repnz |
cmpsX, scasX |
Repeat until ZF=1 |
Fill array with zeros:
section .bss
buf resb 1024
section .text
xor al, al
mov edi, buf
mov ecx, 1024
cld ; address will be increasing
lp: stosb ; al -> [edi]
loop lp
; Or with rep:
xor al, al
mov edi, buf
mov ecx, 1024
cld
rep stosb ; handles ecx=0 correctly
Sum of elements:
section .bss
array resd 256
section .text
xor ebx, ebx
mov esi, array
mov ecx, 256
cld
lp: lodsd ; [esi] -> eax
add ebx, eax
loop lp
Increment all elements:
mov esi, array
mov edi, esi
mov ecx, 256
cld
lp: lodsd ; [esi] -> eax
inc eax
stosd ; eax -> [edi]
loop lp
Copy data from one array into another:
section .bss
buff1 resd 1024
buff2 resd 1024
section .text
mov esi, buff1
mov edi, buff2
mov ecx, 1024
cld
rep movsd
Modify string:
section .data
msg db 'This is a string'
lng db 'long '
section .bss
buff resb 32
section .text
cld
mov esi, msg
mov edi, buff
mov ecx, 16
rep movsb
std
mov esi, buff+15
mov edi, buff+15+5 ; 5 more characters for 'long '
mov ecx, 6 ; copy all 'string'
rep movsb
mov esi, lng+4 ; last character of 'long '
mov ecx, 5 ; 5 characters in 'long '
rep movsb
Find a character in a string:
section .data
mystr db 'This is a string'
mystr_len db 16
section .text
mov edi, mystr
mov ecx, mystr_len
mov al, 'a'
cld
repnz scasb ; ZF=1 if found; [edi] = char after match
string instructions operate on contiguous memory
DF controls direction
stosb/stosw/stosd: accumulator -> [EDI], then adjust EDI
lodsb/lodsw/lodsd: [ESI] -> accumulator, then adjust ESI
combine lodsd / inc eax / stosd to increment every array element movsb/movsw/movsd: [ESI] -> [EDI], then adjust both pointers
rep stosX / rep movsX:
rep applies to one instruction, not to a whole lods/process/stos sequence
copy buffer:
overlapping copy:
insert "long " before "string":
scasb/scasw/scasd:
cmpsb/cmpsw/cmpsd:
repe/repz: continue while count remains and comparison is equal repne/repnz: continue while count remains and comparison is unequal
rep and repe share an encoding
find 'a' in a nonempty bounded buffer:
pointer/count updates also occur on the final comparison
When calling a subroutine, stack is mainly used to
Cannot use static memory because of recursion.
stack = last in, first out
hardware stack:
growth direction is architecture-dependent
uses:
We can use push and pop to work with
stack:
mov eax, [esp] ; copy top of stack into eax
; ...
push eax ; remember eax
; ... ; now we can use it
pop eax ; recover eax
To reverse a string we can use:
; esi points to the start of null-terminated string
xor ebx, ebx
xor ecx, ecx
lp: mov bl, [esi+ecx] ; current byte in bl
cmp bl, 0 ; if it the last one,
je lpquit ; we are done
push ebx ; save the whole dword
inc ecx ; with the required byte
jmp lp
lpquit: jecxz done
mov edi, esi ; overwrite with reversed string
lp2: pop ebx ; get the string
mov [edi], bl ; in reverse order
inc edi ; next character
loop lp2
done: ; original zero terminator preserved
push/pop support words and dwords, not individual bytes
ESP points to the most recently pushed value
push source:
pop destination:
[esp] accesses the current top without removing it
other occupied stack locations are ordinary memory too
push eax / pop eax preserve a value across temporary register use
string reversal example:
first pass:
second pass:
pushad saves EAX, ECX, EDX, EBX, original ESP, EBP, ESI, EDI popad restores in reverse order
pushfd / popfd save and restore EFLAGS
16-bit counterparts: pushaw/popaw and pushfw/popfw
call is like jmp but pushes return
address to stack. ret pops it into
EIP.
section .bss
array resb 256
section .text
global _start
; fill memory (edi=address, ecx=length, al=value)
fill_memory:
jecxz fm_q
fm_lp: mov [edi], al
inc edi
loop fm_lp
fm_q: ret
_start:
mov edi array
mov ecx 256
mov al '@'
call fill_memory
subroutine call temporarily transfers control
each call needs storage for return address, parameters and local variables
recursion requires a fresh instance for every active call
stack frame contains information belonging to one invocation
call saves the following instruction's address on the stack, then transfers control
ret pops the return address into EIP
fill_memory example uses register parameters
caller sets EDI=my_array, ECX=256, AL='@' and calls the routine
ESP changes during subroutine calls, so EBP
references the stack frame (must be saved/restored):
subroutine:
push ebp ; save current value in ebp
mov ebp, esp ; use ebp to reference stack
sub esp, 16 ; get 4 bytes in stack (local variable)
;
; main body of subroutine
;
mov esp, ebp ; restore esp
pop ebp ; restore ebp
ret ; pop return address into eip
register parameters alone become inconvenient in larger routines
stack parameters and locals keep each invocation's data together
ESP changes during pushes and nested calls
callee preserves the caller's EBP
prologue:
frame layout:
epilogue reverses frame setup
enter N,0 / leave offer special frame-management instructions
Unix creates the initial stack and supplies backing memory as it grows
push dword param3 ; add parameters to stack
push dword param2
push dword param1
call subroutine ; call subroutine
add esp, 12 ; remove parameters from stack
Subroutines return values either using:
EAX for 4-byte integers or EDX:EAX for
8-byte integersEAX, EDX are modified by arithmetic,
ECX is used as counter. By convention, all three can be
overwritten in subroutines.
calling convention settles choices that the CPU does not decide
classic Pascal convention: push parameters left to right
classic i386 C convention: push parameters right to left
stack cleanup:
C example with three dwords:
ret 12:
returned values in the conventions discussed:
first_proc:
; ... ...
.cycle: ; equivalent to first_proc.cycle
; ... ...
second_proc: ; equivalent to second_proc.cycle
; ... ...
.cycle:
; ... ...
third_proc: ; referring to .cycle after this causes error
subroutine internals should not require remembering other routines' label names
NASM local label starts with a dot
NASM effectively expands .cycle into first_proc.cycle
Given a null-terminated string and pattern
(with ? and *), print yes if
match, no otherwise.
%include "stud_io.inc"
global _start
section .data
string dd 'hello',0 ; dd for 4-byte stack alignment
pattern dd 'he*o',0
section .text
match:
push ebp
mov ebp, esp
sub esp, 4 ; local variable I
push edi ; save edi and esi
push esi
mov esi, [ebp+8] ; use esi for string
mov edi, [ebp+12] ; and edi for pattern
.again:
cmp byte [edi], 0 ; empty pattern?
jne .non_end_pattern
cmp byte [esi], 0 ; only empty string
jne .false ; can match empty pattern
jmp .true
.non_end_pattern:
cmp byte [edi], '*'
jne .not_star
mov dword [ebp-4], 0 ; I=0
.star_loop:
mov eax, edi
inc eax ; substring after '*'
push eax ; use for recursive call
mov eax, esi
add eax, [ebp-4] ; esi+I
push eax
call match
add esp, 8
cmp eax, 1 ; substring matches
je .true ; so we are done
mov eax, esi ; string already empty?
add eax, [ebp-4]
cmp byte [eax], 0
je .false
inc dword [ebp-4] ; I=I+1
jmp .star_loop
.not_star:
cmp byte [esi], 0 ; is the string empty?
jne .not_end_string
jmp .false
.not_end_string:
mov al, [edi] ; '?' character in pattern?
cmp al, '?'
je .next_char
cmp al, [esi] ; characters are the same?
jne .false
.next_char:
inc esi ; reduce substring
inc edi ; by a character and let's see
jmp .again ; if the next substring match
.true:
mov eax, 1
jmp .end
.false:
mov eax, 0
.end:
pop esi ; restore esi and edi
pop edi ; and edi in reverse order
mov esp, ebp
pop ebp
ret
_start:
push pattern ; argument 2
push string ; argument 1
call match
add esp, 8
cmp eax, 1 ; 1 means true
jne false
true:
PRINT 'yes'
jmp end
false:
PRINT 'no'
end:
PUTCHAR 10
FINISH
recursive example: match a string against a wildcard pattern
both inputs are zero-terminated strings
each invocation handles remaining suffixes
empty pattern matches only an empty string
non-star pattern character:
star case:
zero termination permits two pointer arguments
match frame/register layout:
advance a string suffix by incrementing its pointer
recursive calls share physical CPU registers
register-saving convention balances caller and callee work
i386 CDECL convention used here:
match saves EBP, ESI and EDI
implementation:
caller pushes pattern then string and removes both arguments afterwards
long conditional branch to .false needs a near form when short range is exceeded
global _start
section .text
;
; [ebp+8] is pointer to string
; [ebp+12] is pointer to pattern
; returns eax==0 for false, eax==1 for true
;
match:
push ebp
mov ebp, esp
sub esp, 4 ; local I (index) is [ebp-4]
push esi ; we use esi, edi and eax,
push edi ; but eax is changed anyway
mov esi, [ebp+8] ; esi always points to the string
mov edi, [ebp+12] ; edi -------------------- pattern
.again:
cmp byte [edi], 0 ; pattern end?
jne .not_end
cmp byte [esi], 0 ; string end?
jne near .false ; out of range
jmp .true
.not_end:
cmp byte [edi], '*'
jne .not_star
; now the "star cycle" begins
mov dword [ebp-4], 0 ; I := 0
.star_loop:
; prepare the recursive call
mov eax, edi ; second arg of match is pattern+1
inc eax
push eax
mov eax, esi ; first arg of match is string+I
add eax, [ebp-4] ; prepare the recursive call
push eax
call match
add esp, 8 ; remove params from stack
test eax, eax ; what is returned, true or false?
jnz .true ; if 1, then match is found, return 1
add eax, [ebp-4]
cmp byte [esi+eax], 0 ; may be string ended?
je .false ; if so, no more possibilities to try
inc dword [ebp-4] ; I := I + 1
jmp .star_loop ; try the next possibility
.not_star:
mov al, [edi] ; we already know pattern isn't ended
cmp al, '?'
je .quest
cmp al, [esi] ; if the string's over, this cmp fails
jne .false ; as well as if the chars differ
jmp .go_on
.quest:
cmp byte [esi], 0 ; we only need to check for string end
jz .false
.go_on:
inc esi
inc edi
jmp .again
.true:
mov eax, 1
jmp .quit
.false:
xor eax, eax
.quit:
pop edi
pop esi
mov esp, ebp
pop ebp
ret
;
; MAIN PROGRAM
;
_start:
pop eax
cmp eax, 3
jne wrong_args
pop esi ; ignore argv[0]
pop esi ; get argv[1]
pop edi ; get argv[2]
mov [string], esi
mov [pattern], edi
push edi
push esi
call match
add esp, 8
test eax, eax
jz print_no
mov edx, 4 ; print yes
mov ecx, m_yes
mov ebx, 1
mov eax, 4
int 80h
jmp quit
print_no: ; print no
mov edx, 4
mov ecx, m_no
mov ebx, 1
mov eax, 4
int 80h
jmp quit
wrong_args: ; say wrong args
mov edx, m_wrong_len
mov ecx, m_wrong
mov ebx, 1
mov eax, 4
int 80h
jmp quit
quit:
mov ebx, 0
mov eax, 1
int 80h
section .bss
string resd 1
pattern resd 1
section .data
m_yes db "YES", 10
m_no db "NO ", 10
m_wrong db "wrong arguments count, must be 2", 10
m_wrong_len equ $-m_wrong
%include "stud_io.inc"
global _start
section .data
string dd 'hello',0 ; double word because
pattern dd 'he*o',0 ; we are working with
; 4-byte stack
section .text
match:
push ebp
mov ebp, esp
sub esp, 4 ; local variable I
push edi ; save edi and esi
push esi
mov esi, [ebp+8] ; use esi for string
mov edi, [ebp+12] ; and edi for patter
.again:
cmp byte [edi], 0 ; empty pattern?
jne .non_end_pattern
cmp byte [esi], 0 ; only empty string
jne .false ; can match empty pattern
jmp .true
.non_end_pattern:
cmp byte [edi], '*'
jne .not_star
mov dword [ebp-4], 0 ; I=0
.star_loop:
mov eax, edi
inc eax ; substring after '*'
push eax ; use for recursive call
mov eax, esi
add eax, [ebp-4] ; esi+I
push eax
call match
add esp, 8
cmp eax, 1 ; substring matches
je .true ; so we are done
mov eax, esi ; string already empty?
add eax, [ebp-4]
cmp byte [eax], 0
je .false
inc dword [ebp-4] ; I=I+1
jmp .star_loop
.not_star:
cmp byte [esi], 0 ; is the string empty?
jne .not_end_string
jmp .false
.not_end_string:
mov al, [edi] ; '?' character in patter?
cmp al, '?'
je .next_char
cmp al, [esi] ; characters are the same?
jne .false
.next_char:
inc esi ; reduce substring
inc edi ; by a character and let's see
jmp .again ; if the next substring match
.true:
mov eax, 1
jmp .end
.false:
mov eax, 0
.end:
pop esi ; restore esi and edi
pop edi ; and edi in reverse order
mov esp, ebp
pop ebp
ret
_start:
push pattern ; argument 2
push string ; argument 1
call match
add esp, 8
cmp eax, 1 ; 1 means true
jne false
true:
PRINT 'yes'
jmp end
false:
PRINT 'no'
end:
PUTCHAR 10
FINISH
earlier examples introduced only the NASM features needed at each step
now examine command-line options and syntax systematically
| Parameter | Description | Examples | Notes |
|---|---|---|---|
-f |
Format | -f elf |
Default: binary |
-o |
Output file | -o prog.o |
Optional |
-d |
Define macro-symbol | -dSYMBOL |
%define SYMBOL |
-d |
-dSIZE=1024 |
%define SIZE 1024 |
|
-l |
Listing | -l prog.lst |
Addresses, bytes, mnemonics |
-g |
Debug information | For gdb |
|
-e |
Macro-processor output |
nasm takes a source filename and options
-o selects output filename
-d defines a preprocessor symbol from the command line
-l filename creates an assembly listing
-g includes debugging information
-e performs preprocessing only
NASM has further options documented in its reference manual
| Rule | Detail |
|---|---|
| Basic unit | line of text, glue with \ |
| Label characters | letters _ $ # @
~ . ? |
| Label start | letter _ ? . only |
| Label = keyword | prepend with $ |
: after label |
in .text only, not in .data /
.bss |
| Mnemonics | case-insensitive (mov = MOV) |
| User labels | case-sensitive (foo != FOO) |
| Operands | split by ,, memory always in [] |
| Comments | start with ; |
logical source line is the basic syntax unit
backslash at the end of a physical line joins the following line
line fields: label, instruction, operands, comment
label names:
instruction field can contain:
machine mnemonics are case-insensitive; user macro names normally are not
multiple operands are comma-separated
general rule:
memory operands always use square brackets
semicolon starts a comment extending to the end of the line
Pseudo-instructions look like mnemonics but don't map to machine code:
label1 resd 4 ; resb..rest (t=10 bytes, for FPU)
stars times 4096 db '*' ; 4096 bytes filled with stars
four equ 4 ; now four=4
We often use equ to define length of a string:
msg db "Hello there",10,0
msglen equ $-msg ; $ = current address, equ=13
pseudo-instructions look like instructions but direct assembly work
name equ expression binds a label to an explicit constant
$ means the current assembly position
times N repeats the following instruction or pseudo-instruction
incbin includes external binary-file contents in the memory image
| Type | Format | Notes |
|---|---|---|
| Integer | dec / bin / oct / hex | |
| Floating-point | contains . |
e.g. 1.0, 1.0e3 |
| Character | <= 4 bytes in ' ' or " " |
'abcd' = 64636261h |
| String | > 4 bytes in ' ' or " " |
null-terminated in memory |
constant categories: integers, characters, strings and floating-point values
integer notation supports decimal, binary, octal and hexadecimal
short quoted character sequences can act as integer constants
i386 integer byte order is little-endian
floating-point constants have a different bit representation from integers
Assembly evaluates expressions, embedding only the final integer:
| Order | Operation | Notes |
|---|---|---|
| 1 | + - ~ ! SEG |
unary |
| 2 | * / // % %% |
/ % unsigned, // %% signed |
| 3 | + - |
|
| 4 | << <<< >> >>> |
shl, shr, sar |
| 5 | & |
and |
| 6 | ^ |
xor |
| 7 | | | or |
assembler can evaluate an expression before program execution
integer expression operations:
seg operator is irrelevant to these flat-model examples
precedence, highest first:
Assembly reads source twice:
| Pass | Purpose |
|---|---|
| 1 | calculate instruction sizes, assign labels |
| 2 | generate machine code |
times (label-$) db 0 ; uses label
label: db 'Where am I?' ; but label address depends on db size
Critical expressions can only contain:
two-pass model of assembly:
forward references become problematic when they determine layout itself
critical expression = value required when establishing layout
examples: times counts and resb/resw sizes
instruction encodings can also depend on displacement width
%include "stud_io.inc" ; replaced with file content
macro processor transforms source text into new source text
powerful macros compensate for assembly language's limited expressive syntax
macro = transformation rule associated with a macro name
macro definition establishes the name and replacement rule macro call supplies name and arguments
macro expansion substitutes generated text
expansion need not make the text longer
macro directives can act without a macro call
Multi-line macro:
%macro pcall1 2 ; 2 parameters
push %2 ; %2 = second parameter
call %1 ; %0 = number of parameters
add esp, 4
%endmacro
pcall1 proc, eax ; %1 -> proc, %2 -> eax
; expands to:
push eax
call proc
add esp, 4
%macro pcall2 3
push %3
push %2
call %1
add esp, 8
%endmacro
%macro pcall0 1
call %1
%endmacro
%define binds string to a label:
%define arg1 ebp+8 ; arg1 -> ebp+8
%define arg2 ebp+12
%define arg3 ebp+16
%define local1 ebp-4
%define local2 ebp-8
%define local3 ebp-12
mov eax, [arg1]
; more general:
%define arg(n) ebp+(4*n)+4
%define local(n) ebp-(4*n)
mov [arg(7)], edx
pcallN abbreviates a C-style subroutine call
pcall2 / pcall3:
%0 is the number of macro arguments
single-line macros can replace part of an instruction
keep brackets visible at use: mov eax,[arg1]
Lazy define:
%define thenumber 25
%define mkvar dd thenumber
var1 mkvar
; -->
var1 dd thenumber
; -->
var1 dd 25
%define thenumber 36
; -->
var1 dd 36
Eager define:
%define thenumber 25
%xdefine mkvar dd thenumber
var1 mkvar
; -->
var1 dd 25
%define thenumber 36
; -->
var1 dd 25
%assign binds number to a label:
%assign var 25 ; var = 25
%assign var var+1 ; var = 26
single-line macros can be redefined
%define expands nested macro names when the outer macro is used
example: mkvar expands to dd thenumber
%xdefine expands nested names immediately
%assign evaluates an integer expression immediately
%assign names are macro variables
Debug suspicious section:
%ifdef DEBUG_PRINT
PRINT "Entering suspicious section"
PUTCHAR 10
%endif
;
; Here is the suspicious section
;
%ifdef DEBUG_PRINT
PRINT "Leaving suspicious section"
PUTCHAR 10
%endif
Toggle debug print:
%define DEBUG_PRINT
; %define DEBUG_PRINT
Or from command line:
nasm -f elf -dDEBUG_PRINT prog.asm
Use %elifdef and %else for branches:
%ifdef CASE_A
;
; Code for Case A
;
%elifdef CASE_B
;
; Code for Case B
;
%else
; if not A, nor B, output an error:
%error Please define either CASE_A or CASE_B
%endif
%ifndef checks if a variable is not defined.
Other checks:
%if OS_TYPE == 1 ; critical expression, can use:
; = < > >= <= != == && || ^^
%ifidn a, b ; checks if a = b
%ifmacro macroname ; checks if macro exists
%ifid eax ; check if argument is an identifier
%ifstr "hello"
%ifnum 123
with the respective %ifnXXX, %elifXXX,
%elifnXXX forms.
Etude 3.31 extends the macro of etude 3.30 (see string directives
below): a control symbol selects the element size, and
nasm -D_word switches it without editing the source:
%macro str_char_mem 1
char_mem:
%assign i 1
%strlen n %1
%rep n
%substr c %1 i
%ifdef _byte
db c
%elifdef _word
dw c
%else
dd c
%endif
%assign i i+1
%endrep
%endmacro
; %define _word
str_char_mem "Hello there"
$ nasm -f elf -D_word prog.asm # 2-byte elements instead of 4
one source can produce program variants
NASM implements conditional assembly through its preprocessor
%ifdef DEBUG_PRINT ... %endif:
command-line -dDEBUG_PRINT enables the same code without editing source
%elifdef and %else choose alternative configurations
%ifndef tests absence; %elifndef supplies the corresponding alternative branch
%if evaluates a compile-time condition
other tests:
%ifctx checks preprocessor context; outside this introduction
%assign n 50
%rep 100
db n
%assign n n + 1
%endrep
; expands to:
db 50
db 51
db 52
; ...
db 148
db 149
fibonacci ; label link to the
%assign i 1 ; beginning of the
%assign j 1 ; generated memory
%rep 100000
%if j > 100000
%exitrep
%endif
dd j
%assign t j+i
%assign i j
%assign j t
fib_count equ ($-fibonacci)/4 ; how many fibonacci's
%endrep
%assign a 0
%rep
inc word [array+a]
%assign a a + 2
%endrep
Etude 3.28: a macro that fills memory with a sequence, given its
first value, step and length. %assign updates a macro
variable on each repetition:
%macro for_memory 3
%assign n %1
%rep %3
db n
%assign n n+%2
%endrep
%endmacro
mem for_memory 1, 2, 10
nasm -e shows what the assembler receives after macro
expansion:
mem :
db 1
db 3
db 5
db 7
db 9
db 11
db 13
db 15
db 17
db 19
%rep N ... %endrep processes its body N times at preprocessing time
generate initialized bytes 50 through 149:
generate a Fibonacci-like table bounded by 100000:
macro repetition can generate instructions too
%macro zero_memory 2
push dword %2 ; push, pull to not have conflicts
push dword %1 ; with eax, ecx outside macros
pop eax
pop ecx
%%lp: ; %% to not have repeating labels
mov byte [eax], 0 ; if we insert macros more
inc eax ; than once
loop %%lp
%endmacro
a normal label inside a macro is duplicated on every expansion
%%lp is a macro-local label
macro arguments may refer to registers its expansion overwrites
preserve both argument values before assigning working registers
%macro pcall 1-* ; have at least name of subroutine
%rep %0 - 1 ; loop through parameters for subroutine
%rotate -1 ; rotate clockwise
push dword %1 ; push 4-byte parameters
%endrep
%rotate -1 ; now get the name of subroutine
call %1
add esp, (%0 - 1) * 4 ; clean up the stack
%endmacro
pcall myproc, eax, myvar, 27
; expands to:
push dword 27
push myvar
push eax
call myproc
add esp, 12
Etude 3.29: jump to the first, second, ... label when EAX holds 1, 2,
... %0 is the number of arguments, and
%rotate 1 brings the next one to %1:
%macro jmp_labels 1-*
%assign i 1
%rep %0
cmp eax, i
je %1
%assign i i+1
%rotate 1
%endrep
%endmacro
jmp_labels a, b, c, d, e expands to:
cmp eax, 1
je a
cmp eax, 2
je b
cmp eax, 3
je c
cmp eax, 4
je d
cmp eax, 5
je e
%macro mymacro 1-3 accepts one through three arguments %macro mymacro 2-* accepts two or more
%rotate 1 cyclically changes argument positions
%rotate -1 rotates the other way
general pcall macro:
pcall myproc,eax,myvar,27 expands to:
%strlen sl 'my string' ; sl = length of 'my string'
%substr var1 'abcd' 1
%substr var2 'abcd' 2
%substr var3 'abcd' 3
; expands to:
%define var1 'a'
%define var2 'b'
%define var3 'c'
Etude 3.30: %strlen and %substr take a
string literal apart at assembly time, producing one 4-byte element per
character:
%macro str_char_mem 1
char_mem:
%assign i 1
%strlen n %1
%rep n
%substr c %1 i
dd c
%assign i i+1
%endrep
%endmacro
str_char_mem "Hello there" expands to
dd 'H', dd 'e', and so on.
preprocessor can inspect literal strings when generating source
%strlen sl 'my string' assigns 9 to macro variable sl
%substr extracts characters using one-based positions in these examples
all such work happens before assembly and execution
direct system calls replace the temporary stud_io.inc macros
understanding the i386 interface first requires:
In the historical FreeBSD i386 int 80h interface, the
syscall number goes in EAX and arguments are pushed right
to left above a dummy return word, with CF clear on success
and set on error.
historical FreeBSD i386 int 80h interface:
kernel expects the stack layout produced by calling a small wrapper
direct int 80h can supply a dummy dword instead of a wrapper return address
Hello example:
test CF before an instruction such as add destroys it
| Model | How CPU time is used |
|---|---|
| Simple batch model | Run until completion or blocking |
| Time sharing | Preempt tasks after time slices for responsiveness |
| Real time | Prioritize predictable timing and deadlines |
one CPU can support multitasking by switching between programs
tasks execute concurrently when their start-to-finish intervals overlap
at any instant one CPU executes one task, but several tasks can remain in progress
I/O is much slower than CPU computation
multitasking uses that waiting time for other tasks
batch scheduling in the book's model:
interactive work needs prompt responses
time sharing:
priority example:
non-preemptive / cooperative historical systems:
some applications require completion by an external deadline
real-time scheduling focuses on predictable completion
Clarification. The priority formula is an illustrative scheduling policy. Batch systems need not be non-preemptive, and scheduler policies differ between operating systems.
| Mechanism | Purpose |
|---|---|
| Memory protection | Isolate programs and protect OS memory |
| Kernel/user modes | Restrict device access and system-wide operations |
| Interrupts | Notify the kernel of device events without continuous polling |
| Timer | Return control to the OS to track time slices and preempt tasks |
essential starting points: memory protection and CPU privilege modes
memory protection isolates programs from accidental or deliberate corruption
protection settings and direct device access must themselves be protected
kernel / supervisor mode: all relevant instructions available user / restricted mode: cannot perform privileged system-wide actions
user tasks modify their permitted memory and request other work from the OS
busy waiting repeatedly polls a device controller
when another task runs during I/O, OS still needs notification of completion
hardware interrupt:
timer interrupts give the scheduler regular opportunities to run
hardware requirements:
timer-only polling of all other devices is possible in principle
| Event | Origin | Relationship to the task |
|---|---|---|
| Interrupt | Timer or controller | Asynchronous; may concern another task |
| Exception | Current instruction | Synchronous; concerns the current task |
On i386, both use the IDT: up to 256 eight-byte descriptors specifying handler addresses and entry behavior.
interrupt terminology covers mechanisms with different causes
hardware interrupt originates outside the CPU
simplified interrupt sequence:
ordinary user instructions cannot simply enable privileged execution
timer repeatedly generates interrupt requests at configured intervals
integer division by zero cannot produce a valid integer result
CPU reports exceptional situations to OS
exceptions arise inside instruction execution
exception handling has a responsible task and runs in its context
i386 Interrupt Descriptor Table:
x86 terminology sometimes calls exceptions internal interrupts
exception is caused by the task's own execution
event -> save execution state -> enter kernel handler -> resolve event -> resume or stop task
int 0x80 ; traditional Linux i386 syscall entry
system call = request from a user task to the kernel for a service
CPU must change privilege and enter an OS-defined handler
i386 example uses int to enter an interrupt-table handler
three causes in the terminology used here:
software-interrupt name describes the mechanism
privilege increase and entry into a predefined handler are inseparable
syscall numbers, arguments and results depend on OS and architecture
C libraries provide ordinary function wrappers
direct assembly must supply OS-specific numbers and constants
global _start
section .data
msg db "Hello world", 10
msg_len equ $-msg
section .text
_start:
mov eax, 4 ; write
mov ebx, 1 ; to standard output
mov ecx, msg ; our message
mov edx, msg_len ; with its length
int 80h ; system call number in Linux
; (software interrupt)
mov eax, 1 ; _exit
mov ebx, 0 ; with success
int 80h ; same system call number
Results of system calls are returned via EAX. Error if
result is between 0xfffff000 and
0xffffffff.
historical Linux i386 int 80h interface:
write is syscall 4
write to standard output:
_exit is syscall 1
Hello example:
some system calls involve wider/special argument arrangements
| Syscall | EAX |
EBX (Arg 1) |
ECX (Arg 2) |
EDX (Arg 3) |
Ret (EAX) |
|---|---|---|---|---|---|
_exit |
1 | exit code | |||
read |
3 | fd* (0=in) | buf ptr | byte count | bytes to read |
write |
4 | fd (1=out) | buf ptr | byte count | bytes to write |
open |
5 | filename ptr | flags | mode | fd |
close |
6 | fd | 0 success | ||
getpid |
20 | pid | |||
kill |
37 | pid | signal num | 0 success | |
getppid |
64 | ppid |
*fd: file descriptor
File open modes:
| Name | Description | Number |
|---|---|---|
O_RDONLY |
only read | 000h |
O_WRONLY |
only write | 001h |
O_RDWR |
read and write | 002h |
O_CREAT |
allow file creation (it could be old) | 040h |
O_EXCL |
demand file creation (it should be new) | 080h |
O_TRUNC |
overwrite file | 200h |
O_APPEND |
append to file | 400h |
_exit(1) terminates; write(4) sends buffer bytes to a descriptor
read(3): descriptor, destination buffer, maximum byte count
read returning zero for a nonzero request means end of input
always inspect read's result
check error convention after every fallible call
usual initial descriptors:
open(5) creates a new descriptor
i386 examples:
open can fail for reasons outside the program's control
close(6) releases a descriptor
getpid(20) returns current PID
getppid returns parent PID
kill(37) sends a signal to the selected process
Unix provides many more calls
| Common name in C | Description | Location at start of program |
|---|---|---|
| argc | number of arguments | [esp] |
| argv | address of argument array | [esp+4] |
Write a program that prints its parameters.
global _start
section .text
return db 10,0
strlen: ; < (address of string) > (length of string)
push ebp
mov ebp, esp
xor ecx, ecx
mov eax, [ebp+8] ; address of string
.lp: cmp [eax+ecx], byte 0
je .end
inc ecx
jmp short .lp
.end:
mov eax, ecx ; output string length
mov esp, ebp
pop ebp
ret
print_str: ; < (address of string) > (nothing)
push ebp
mov ebp, esp
push ebx
mov ebx, [ebp+8] ; address of string
push ebx
call strlen
add esp, 4
mov edx, eax ; string length in edx for write
mov ecx, ebx ; string address in ecx for write
mov ebx, 1 ; standard output
mov eax, 4 ; write
int 80h
pop ebx
mov esp, ebp
pop ebp
ret
_start:
mov ebx, [esp] ; number of parameters (argc)
mov esi, esp ; address of addresses of
add esi, 4 ; command line parameter (argv)
lp:
push dword [esi] ; current parameter address (argv[i])
call print_str
add esp, 4
push dword return
call print_str
add esp, 4
add esi, 4 ; next parameter
dec ebx
cmp ebx, 0
jne lp
mov ebx, 0 ; success
mov eax, 1 ; _exit
int 80h
Etude 3.35 prints the longest command-line argument, using system
calls directly. At _start the stack holds
argc, then the argument pointers. The program's own
pcall and scall macros push their arguments in
reverse order; scall also sets ECX to -1 when the kernel
returns an error code:
_start:
pop ebx
mov esi, esp
cmp ebx, 2
jl .quit
mov dword [longest_len], 0
.lp:
mov edi, [esi+4*ebx-4]
pcall strlen, edi
cmp [longest_len], eax
ja .next
mov [longest_len], eax
mov [longest], edi
.next:
dec ebx
cmp ebx, 1
jne .lp
scall 4, 1, [longest], [longest_len]
scall 4, 1, return, return_len
.quit:
scall 1, 0
%macro pcall 1-*
; call subroutines
; < (name, param1, param2, param3)
%rep %0 - 1
%rotate -1
push dword %1
%endrep
%rotate -1
call %1
add esp, (%0 - 1)*4
%endmacro
%macro scall 1-4
; system call
; < (interrupt number, param1, param2, param3)
%if %0 > 1
push ebx ; it can only spoid eax, ecx, edx
%endif
%rep %0
%rotate -1
push dword %1 ; push in reverse order
%endrep
pop eax
%if %0 > 1
pop ebx
%if %0 > 2
pop ecx
%if %0 > 3
pop edx
%endif
%endif
%endif
int 80h
cmp eax, 0xfffff000
jb %%ok
mov ecx, -1
jmp short %%quit
%%ok:
xor ecx, ecx
%%quit:
%if %0 > 1
pop ebx
%endif
%endmacro
global _start
section .bss
longest resd 1
longest_len resd 1
section .data
return db 10
return_len equ $-return
section .text
strlen: ; < (string address) > (string length)
push ebp
mov ebp, esp
mov edx, [ebp+8] ; input address
xor eax, eax
.lp:
cmp byte [edx+eax], 0 ; until 0
je .quit
inc eax ; increaes length
jmp short .lp
.quit:
mov esp, ebp
pop ebp
ret
_start:
pop ebx
mov esi, esp
cmp ebx, 2
jl .quit
mov dword [longest_len], 0
.lp:
mov edi, [esi+4*ebx-4]
pcall strlen, edi
cmp [longest_len], eax
ja .next
mov [longest_len], eax
mov [longest], edi
.next:
dec ebx
cmp ebx, 1
jne .lp
scall 4, 1, [longest], [longest_len]
scall 4, 1, return, return_len
.quit:
scall 1, 0
$ nasm -f elf longest.asm && ld -m elf_i386 longest.o -o longest
$ ./longest abc hello xy
hello
command-line arguments are the same interface already used in Pascal examples
initial stack at _start in these i386 examples:
argument-printing example supports both OS conventions
strlen helper:
print_str calls strlen, then write
print newline using the same helper and a two-byte string: 10,0
more efficient output could collect all text and issue fewer syscalls
nlstr can live in .text because it is immutable
main loop:
global _start
section .text
nlstr db 10, 0
strlen: ; arg1 == address of the string
push ebp
mov ebp, esp
xor eax, eax
mov ecx, [ebp+8] ; arg1
.lp: cmp byte [eax+ecx], 0
jz .quit
inc eax
jmp short .lp
.quit: pop ebp
ret
print_str: ; arg1 == address of the string
push ebp
mov ebp, esp
push ebx ; will be spoiled
mov ebx, [ebp+8] ; arg1
push ebx ; (and in ebx, as well)
call strlen
add esp, 4 ; the length is now in eax
%ifdef OS_FREEBSD
push eax ; length
push ebx ; arg1
push dword 1 ; stdout
mov eax, 4 ; write
push eax ; extra dword
int 80h
add esp, 16
%elifdef OS_LINUX
mov edx, eax ; edx now contains the length
mov ecx, ebx ; arg1; was stored in ebx
mov ebx, 1 ; stdout
mov eax, 4 ; write
int 80h
%else
%error please define either OS_FREEBSD or OS_LINUX
%endif
pop ebx
;mov esp, ebp
pop ebp
ret
_start:
mov ebx, [esp] ; argc
mov esi, esp
add esi, 4 ; argv
again: push dword [esi] ; argv[i]
call print_str
add esp, 4
push dword nlstr
call print_str
add esp, 4
add esi, 4
dec ebx
jnz again
%ifdef OS_FREEBSD
push dword 0 ; success
mov eax, 1 ; _exit
push eax ; extra dword
int 80h
%else
mov ebx, 0 ; success
mov eax, 1 ; _exit
int 80h
%endif
Write a program to copy text from one file into another. File names should be given as parameters.
%macro kernel 1-*
%if %0 > 1
push ebx
%endif
%rep %0
%rotate -1
push dword %1
%endrep
pop eax
%if %0 > 1
pop ebx
%if %0 > 2
pop ecx
%if %0 > 3
pop edx
%if %0 > 4
%error "Can't do syscall with more than 4 parameters"
%endif
%endif
%endif
%endif
int 80h
mov ecx, eax
and ecx, 0xfffff000
cmp ecx, 0xfffff000
jne %%ok
mov ecx, eax
neg ecx
mov eax, -1
jmp short %%end
%%ok:
xor ecx, ecx
%%end:
%if %0 > 1
pop ebx
%endif
%endmacro
section .bss
buffer resd 4096
bufsize equ $-buffer
fdsrc resd 1
fddest resd 1
section .data
helpmsg db 'Usage: copy <src> <dest>', 10
helplen equ $-helpmsg
err1msg db "Couldn't open source file for reading", 10
err1len equ $-err1msg
err2msg db "Couldn't open destination file for writing", 10
err2len equ $-err2msg
section .text
global _start
_start:
pop ecx ; number of parameters
mov esi, esp ; address of array
; of parameters
cmp ecx, 3 ; should be name of file
jne .param_error ; and 2 parameters
mov edi, [esi+4] ; address of first parameter
kernel 5, edi, 0 ; open file to read
cmp eax, -1
je .read_error
mov [fdsrc], eax
mov edi, [esi+8] ; address of second parameter
kernel 5, edi, 241h, 664o ; open file to write
cmp eax, -1
je .write_error
mov [fddest], eax
.lp:
; read
kernel 3, [fdsrc], buffer, bufsize
cmp eax, 0
jle .end_of_file
; write
kernel 4, [fddest], buffer, eax
jmp .lp
.param_error:
kernel 4, 2, helpmsg, helplen ; write to error output
kernel 1, 1
.read_error:
kernel 4, 2, err1msg, err1len
kernel 1, 1
.write_error:
kernel 4, 2, err2msg, err2len
kernel 1, 1
.end_of_file:
kernel 6, [fddest]
kernel 6, [fdsrc]
kernel 1, 0
copy source to destination named by two command-line arguments
a kernel macro centralizes Linux/FreeBSD differences
macro follows the CDECL preservation rule
error interfaces differ
normalized macro result:
push argument values before assigning syscall registers
FreeBSD keeps parameters on stack, with syscall number serving as dummy top dword
Linux pops number and parameters into EAX/EBX/ECX/EDX/ESI/EDI/EBP
post-call handling also differs enough to justify separate macro branches
indent preprocessor conditions separately from generated machine instructions
openwr_flags depends on selected OS
.bss storage:
diagnostic messages go to descriptor 2
entry setup:
open source:
open destination:
copy loop:
finish by closing both descriptors and exiting with status 0 internal main-program labels are local to _start
complete example is supplied as copy.asm
%macro kernel 1-*
%ifdef OS_FREEBSD
%rep %0
%rotate -1
push dword %1
%endrep
mov eax, [esp]
int 80h
jnc %%ok
mov ecx, eax
mov eax, -1
jmp short %%q
%%ok:
xor ecx, ecx
%%q:
add esp, %0 * 4
%elifdef OS_LINUX
%if %0 > 1
push ebx
%if %0 > 4
push esi
push edi
push ebp
%endif
%endif
%rep %0
%rotate -1
push dword %1
%endrep
pop eax
%if %0 > 1
pop ebx
%if %0 > 2
pop ecx
%if %0 > 3
pop edx
%if %0 > 4
pop esi
%if %0 > 5
pop edi
%if %0 > 6
pop ebp
%if %0 > 7
%error "Can't handle Linux syscalls for more than 6 params"
%endif
%endif
%endif
%endif
%endif
%endif
%endif
int 80h
mov ecx, eax
and ecx, 0fffff000h
cmp ecx, 0fffff000h
jne %%ok
mov ecx, eax
neg ecx
mov eax, -1
jmp short %%q
%%ok: xor ecx, ecx
%%q:
%if %0 > 1
%if %0 > 4
pop ebp
pop edi
pop esi
%endif
pop ebx
%endif
%else
%error Please define either OS_LINUX or OS_FREEBSD
%endif
%endmacro
%ifdef OS_FREEBSD
openwr_flags equ 601h
%else
openwr_flags equ 241h
%endif
section .bss
buffer resb 4096
bufsize equ $-buffer
argc resd 1
argvp resd 1
fdsrc resd 1
fddest resd 1
section .data
helpmsg db 'Usage: copy <src> <dest>', 10
helplen equ $-helpmsg
err1msg db "Couldn't open source file for reading", 10
err1len equ $-err1msg
err2msg db "Couldn't open destination file for writing", 10
err2len equ $-err2msg
section .text
global _start
_start:
pop dword [argc]
mov [argvp], esp
cmp dword [argc], 3
je .args_count_ok
kernel 4, 2, helpmsg, helplen
kernel 1, 1
.args_count_ok:
; open the source file
mov esi, [argvp]
mov edi, [esi+4]
kernel 5, edi, 0 ; O_RDONLY
cmp eax, -1
jne .source_open_ok
kernel 4, 2, err1msg, err1len
kernel 1, 2
.source_open_ok:
mov [fdsrc], eax
; now open the destination
mov esi, [argvp]
mov edi, [esi+8]
kernel 5, edi, openwr_flags, 0666o
cmp eax, -1
jne .dest_open_ok
kernel 4, 2, err2msg, err2len
kernel 1, 3
.dest_open_ok:
mov [fddest], eax
again:
kernel 3, [fdsrc], buffer, bufsize
cmp eax, 0
jle .end_of_file
kernel 4, [fddest], buffer, eax
jmp again
.end_of_file:
kernel 6, [fdsrc]
kernel 6, [fddest]
kernel 1, 0
compile each module separately, then link object files into an executable
assembly and C toolchains use object-file formats understood by the linker
module owns its internal namespace
encapsulation permits changing internal details without breaking callers
global myproc ; export label to other modules
extern myproc ; import label from another module
Etude 3.34 splits a program into three translation units.
global exports a label from its module; extern
declares one defined elsewhere:
global strlen
section .text
strlen: ; < (string address) > (string length)
push ebp
mov ebp, esp
mov edx, [ebp+8] ; input address
xor eax, eax
.lp:
cmp byte [edx+eax], 0 ; until 0
je .quit
inc eax ; increaes length
jmp short .lp
.quit:
mov esp, ebp
pop ebp
ret
%include "compare.inc"
global _start
extern strlen
extern lastchar
section .text
_start:
pop ebx ; number of paramters
mov esi, esp ; address of array of parameters
cmp ebx, 3
jne .failure
The main module succeeds only for two arguments of equal length that end with the same character:
$ nasm -f elf 03-34.asm && nasm -f elf strlen.asm && nasm -f elf lastchar.asm
$ ld -m elf_i386 03-34.o strlen.o lastchar.o -o same
$ ./same apple grape && echo YES
YES
global myproc exports a definition from this module
extern myproc declares a definition expected from elsewhere
Write a program that asks user for his/her name and uses it to greet him/her. Use multiple modules.
;; kernel.inc ;;
%macro kernel 1-*
%if %0 > 1
push ebx
%endif
%rep %0
%rotate -1
push dword %1
%endrep
pop eax
%if %0 > 1
pop ebx
%if %0 > 2
pop ecx
%if %0 > 3
pop edx
%if %0 > 4
%error "Can't do syscall with more than 4 parameters"
%endif
%endif
%endif
%endif
int 80h
mov ecx, eax
and ecx, 0xfffff000
cmp ecx, 0xfffff000
jne %%ok
mov ecx, eax
neg ecx
mov eax, -1
jmp short %%end
%%ok:
xor ecx, ecx
%%end:
%if %0 > 1
pop ebx
%endif
%endmacro
;; strlen.asm ;;
global strlen
section .text
strlen: ; < (string address) > (string length)
push ebp
mov ebp, esp
mov eax, [ebp+8]
xor ecx, ecx
.lp:
cmp byte [eax+ecx], 0
je .quit
inc ecx
jmp short .lp
.quit:
mov eax, ecx
mov esp, ebp
pop ebp
ret
;; putstr.asm ;;
%include "kernel.inc"
global putstr
extern strlen
section .text
putstr: ; < (string address)
push ebp
mov ebp, esp
push esi
mov esi, [ebp+8]
push esi
call strlen
add esp, 4
kernel 4, 1, esi, eax
pop esi
mov esp, ebp
pop ebp
ret
;; getstr.asm ;;
%include "kernel.inc"
global getstr
section .text
getstr: ; < (buffer address), (buffer length)
push ebp
mov ebp, esp
mov edx, [ebp+8]
xor ecx, ecx
.lp:
inc ecx
cmp ecx, [ebp+12]
jae .quit ; not enough buffer size
push ecx
push edx
kernel 3, 0, edx, 1 ; read one character
pop edx
pop ecx
cmp eax, 1 ; did we actually get
jne .quit ; 1 character?
mov al, [edx]
cmp al, 10 ; we don't need space
je .quit
inc edx ; next byte in the buffer
jmp .lp
.quit:
mov [edx], byte 0 ; add 0 at the end
mov esp, ebp
pop ebp
ret
;; quit.asm ;;
%include "kernel.inc"
global quit
section .text
quit: kernel 1, 0
;; greet.asm ;;
global _start
extern putstr
extern getstr
extern quit
section .data
what db "What is your name?",10,0
hello db "Hello ",0
end db ":)",10,0
section .bss
inp resb 256
inplen equ $-inp
section .text
_start:
push what
call putstr
add esp, 4
push inplen
push inp
call getstr
add esp, 8
push hello
call putstr
add esp, 4
push inp
call putstr
add esp, 4
push end
call putstr
add esp, 4
jmp .quit
.quit:
push dword 0
call quit
nasm -f elf strlen.asm
nasm -f elf putstr.asm
nasm -f elf getstr.asm
nasm -f elf quit.asm
nasm -f elf greet.asm
ld -m elf_i386 greet.o strlen.o getstr.o putstr.o quit.o -o greet
greeting program asks for a name and prints a personalized greeting
separate modules: putstr, getstr, strlen and quit
kernel.inc contains the syscall macro
strlen.asm exports strlen
putstr.asm exports putstr and imports strlen
getstr accepts buffer address and capacity
getstr state:
getstr uses caller-clobbered registers
quit.asm exports quit and invokes _exit(0)
greet.asm:
assemble the five .asm modules separately
OS-selection definition is required where kernel.inc is used
link the five object files with ld
%include "kernel.inc"
global _start
extern transfer
extern msg_help
extern msg_errsrc
extern msg_errdst
extern message_and_quit
extern open_or_die
section .text
_start:
mov ebp, esp
cmp dword [ebp], 3
je .args_ok
mov eax, msg_help
jmp message_and_quit
.args_ok:
; open the source file
mov eax, [ebp+8]
mov ecx, 0 ; O_RDONLY
mov edx, msg_errsrc
call open_or_die
mov esi, eax
; now open the destination
mov eax, [ebp+12]
mov ecx, openwr_flags
mov edx, msg_errdst
call open_or_die
mov edi, eax
; transfer the content
push esi
push edi
call transfer
add esp, 8
; close both files
kernel 6, esi
kernel 6, edi
; quit
kernel 1, 0
%macro kernel 1-*
%ifdef OS_FREEBSD
%rep %0
%rotate -1
push dword %1
%endrep
mov eax, [esp]
int 80h
jnc %%ok
mov ecx, eax
mov eax, -1
jmp short %%q
%%ok:
xor ecx, ecx
%%q:
add esp, (%0-1)*4
%elifdef OS_LINUX
%if %0 > 1
push ebx
%if %0 > 4
push esi
push edi
push ebp
%endif
%endif
%rep %0
%rotate -1
push dword %1
%endrep
pop eax
%if %0 > 1
pop ebx
%if %0 > 2
pop ecx
%if %0 > 3
pop edx
%if %0 > 4
pop esi
%if %0 > 5
pop edi
%if %0 > 6
pop ebp
%if %0 > 7
%error "Can't handle Linux syscalls for more than 6 params"
%endif
%endif
%endif
%endif
%endif
%endif
%endif
int 80h
mov ecx, eax
and ecx, 0fffff000h
cmp ecx, 0fffff000h
jne %%ok
mov ecx, eax
neg ecx
mov eax, -1
jmp short %%q
%%ok: xor ecx, ecx
%%q:
%if %0 > 1
%if %0 > 4
pop ebp
pop edi
pop esi
%endif
pop ebx
%endif
%else
%error Please define either OS_LINUX or OS_FREEBSD
%endif
%endmacro
%ifdef OS_FREEBSD
openwr_flags equ 601h
%else
openwr_flags equ 241h
%endif
%include "kernel.inc"
global msg_help
global msg_errsrc
global msg_errdst
global message_and_quit
section .data
helpmsg db 'Usage: copy <src> <dest>', 10
helplen equ $-helpmsg
err1msg db "Couldn't open source file for reading", 10
err1len equ $-err1msg
err2msg db "Couldn't open destination file for writing", 10
err2len equ $-err2msg
msg_array dd helpmsg, helplen, err1msg, err1len, err2msg, err2len
msg_help equ 0
msg_errsrc equ 1
msg_errdst equ 2
section .text
;; in: eax = message_id
message_and_quit:
mov ecx, [msg_array + eax*8]
mov edx, [msg_array + eax*8 + 4]
kernel 4, 1, ecx, edx
kernel 1, 1
%include "kernel.inc"
global open_or_die
extern message_and_quit
section .text
;; in: eax = file name ptr, ecx = mode, edx = message_id
;; out: eax = file descriptor
open_or_die: push edx
kernel 5, eax, ecx, 0666o
pop edx
cmp eax, -1
jne .open_ok
mov eax, edx
jmp message_and_quit
.open_ok: ret
%include "kernel.inc"
global transfer
bufsize equ 1024
section .text
; [ebp+8] dest. fd; [ebp+12] src. fd; [ebp-bufsize] buffer
transfer: push ebp
mov ebp, esp
sub esp, bufsize
push ebx
mov ebx, ebp
sub ebx, bufsize ; buffer addr. in ebx
.again: kernel 3, [ebp+12], ebx, bufsize
cmp eax, 0
jle .quit
kernel 4, [ebp+8], ebx, eax
jmp .again
.quit: pop ebx
mov esp, ebp
pop ebp
ret
NASM = nasm
NASMFLAGS = -f elf -dOS_LINUX -g
SOURCES = flags.asm hex2num.asm strlen.asm putstr.asm quit.asm \
flagshow.asm num2hex.asm
OBJECTS = $(SOURCES:.asm=.o)
%.o: %.asm
$(NASM) $(NASMFLAGS) $< -o $@
prog: $(OBJECTS)
$(LD) -m elf_i386 $^ -o $@
clean:
rm -f $(OBJECTS) prog a.out core
%include "kernel.inc"
global _start
extern quit
extern putstr
extern hex2num
extern num2hex
extern flagshow
section .text
_start: mov ebp, esp
cmp dword [ebp], 3
je .args_ok
mov eax, msg_help
jmp message_and_quit
.args_ok:
mov eax, [ebp+8]
push eax
call hex2num
add esp, 4
mov esi, eax
mov eax, [ebp+12]
push eax
call hex2num
add esp, 4
mov ecx, esi
mov ch, al ; now CX contains both bytes
mov esi, ecx ; we store them in ESI
mov eax, esi
call num2hex
push eax
call putstr
add esp, 4
push dword newln
call putstr
add esp, 4
%macro OP_AND_PRINT 2 ; %1 = message, %2 = add/sub
push dword %1
call putstr
add esp, 4
mov eax, esi
%2 al, ah
pushfd ;;; used later by flagshow
and eax, 0xff
call num2hex
push eax
call putstr
add esp, 4
push dword spc4
call putstr
add esp, 4
call flagshow
add esp, 4
%endmacro
OP_AND_PRINT msg_doingadd, add
OP_AND_PRINT msg_doingsub, sub
; quit
jmp quit
msg_help db 'Usage: flags <al> <ah> (both in hex)', 10, 0
msg_doingadd db 'doing ADD AL, AH: ', 0
msg_doingsub db 'doing SUB AL, AH: ', 0
newln db 10, 0
spc4 db " ", 0
;; in: eax = message_id
message_and_quit:
push eax
call putstr
jmp quit
global flagshow
extern putstr
section .text
zfmsg db "ZF: ", 0
ofmsg db "OF: ", 0
cfmsg db "CF: ", 0
sfmsg db "SF: ", 0
flgset db "1 ", 0
flgunset db "0 ", 0
newline db 10,0
%macro PRFLAG 2 ; jnX, Xfmsg
push dword %2
call putstr
add esp, 4
push esi
popfd
%1 %%notset
push dword flgset
call putstr
add esp, 4
jmp %%done
%%notset: push dword flgunset
call putstr
add esp, 4
%%done: nop
%endmacro
flagshow: ; arg1 = the flags (pushed by pushf)
push ebp
mov ebp, esp
push esi
mov esi, [ebp+8]
PRFLAG jnz, zfmsg
PRFLAG jns, sfmsg
PRFLAG jno, ofmsg
PRFLAG jnc, cfmsg
push dword newline
call putstr
add esp, 4
pop esi
mov esp, ebp
pop ebp
ret
%include "kernel.inc"
global getstr
section .text
getstr: ; arg1 = address, arg2 = length
push ebp
mov ebp, esp
xor ecx, ecx ; counter
mov edx, [ebp+8] ; addr
.again: inc ecx
cmp ecx, [ebp+12] ; <?> arg2
jae .quit
push ecx
push edx
kernel 3, 0, edx, 1
pop edx
pop ecx
cmp eax, 1
jne .quit
mov al, [edx]
cmp al, 10 ; EOL
je .quit
inc edx
jmp .again
.quit: mov [edx], byte 0
mov esp, ebp
pop ebp
ret
global hex2num
section .text
hex2num: ; arg1 == address of the string
; in case of error, ECX == 0x80..00, CF is set
push ebp
mov ebp, esp
xor eax, eax ; result accumulator
mov ecx, [ebp+8] ; arg1
.lp: mov dl, byte [ecx]
cmp dl, 0
jz .quit_ok
cmp dl, '0'
jl .notdig
cmp dl, '9'
jg .notdig
sub dl, '0' ; it's a digit '0'..'9'
jmp short .addit
.notdig: cmp dl, 'a'
jl .notlower
cmp dl, 'f'
jg .notlower
sub dl, 'a'-10 ; it's a lowercase 'a'..'f'
jmp short .addit
.notlower: cmp dl, 'A'
jl .errchar
cmp dl, 'F'
jg .errchar
sub dl, 'A'-10 ; it's an uppercase 'A'..'F'
.addit: shl eax, 4
and dl, 0fh
or al, dl
inc ecx
jmp short .lp
.errchar: mov eax, 080000000h ; let it be error value
stc
jmp .quit
.quit_ok: clc
.quit: mov esp, ebp
pop ebp
ret
%macro kernel 1-*
%ifdef OS_FREEBSD
%rep %0
%rotate -1
push dword %1
%endrep
mov eax, [esp]
int 80h
jnc %%ok
mov ecx, eax
mov eax, -1
jmp short %%q
%%ok:
xor ecx, ecx
%%q:
add esp, (%0-1)*4
%elifdef OS_LINUX
%if %0 > 1
push ebx
%if %0 > 4
push esi
push edi
push ebp
%endif
%endif
%rep %0
%rotate -1
push dword %1
%endrep
pop eax
%if %0 > 1
pop ebx
%if %0 > 2
pop ecx
%if %0 > 3
pop edx
%if %0 > 4
pop esi
%if %0 > 5
pop edi
%if %0 > 6
pop ebp
%if %0 > 7
%error "Can't handle Linux syscalls for more than 6 params"
%endif
%endif
%endif
%endif
%endif
%endif
%endif
int 80h
mov ecx, eax
and ecx, 0fffff000h
cmp ecx, 0fffff000h
jne %%ok
mov ecx, eax
neg ecx
mov eax, -1
jmp short %%q
%%ok: xor ecx, ecx
%%q:
%if %0 > 1
%if %0 > 4
pop ebp
pop edi
pop esi
%endif
pop ebx
%endif
%else
%error Please define either OS_LINUX or OS_FREEBSD
%endif
%endmacro
%ifdef OS_FREEBSD
openwr_flags equ 601h
%else
openwr_flags equ 241h
%endif
global num2hex
section .bss
buffer resb 16
buflen equ $-buffer
section .text
num2hex: ; in: eax = num
; out: eax = addr. of the string
push ebp
mov ebp, esp
push esi
lea esi, [buffer + buflen - 1]
mov byte [esi], 0
dec esi
cmp eax, 0
jnz .notzero
mov byte [esi], '0' ; zero from the start
jmp short .quit
.notzero:
.lp: mov cl, al
and cl, 0x0f
cmp cl, 9
jg .hexdig ; at least A
add cl, '0' ; arabic dig., turn into dig. code
jmp short .dig_done
.hexdig: add cl, 'A'-10 ; hex dig., turn info letter code
.dig_done: mov [esi], cl
shr eax, 4
cmp eax, 0
je .quit
dec esi
jmp short .lp
.quit: mov eax, esi
pop esi
mov esp, ebp
pop ebp
ret
%include "kernel.inc"
global putstr
extern strlen
section .text
putstr: ; arg1 = address of the string
push ebp
mov ebp, esp
push dword [ebp+8] ; arg1
call strlen
add esp, 4
kernel 4, 1, [ebp+8], eax
mov esp, ebp
pop ebp
ret
global strlen
section .text
strlen: ; arg1 == address of the string
push ebp
mov ebp, esp
xor eax, eax
mov ecx, [ebp+8] ; arg1
.lp: cmp byte [eax+ecx], 0
jz .quit
inc eax
jmp short .lp
.quit: pop ebp
ret
NASM = nasm
NASMFLAGS = -f elf -dOS_LINUX -g
SOURCES = greet.asm strlen.asm getstr.asm putstr.asm quit.asm
OBJECTS = $(SOURCES:.asm=.o)
%.o: %.asm
$(NASM) $(NASMFLAGS) $< -o $@
prog: $(OBJECTS)
$(LD) -m elf_i386 $^ -o $@
clean:
rm -f $(OBJECTS) prog a.out core
%include "kernel.inc"
global getstr
section .text
getstr: ; arg1 = address, arg2 = length
push ebp
mov ebp, esp
xor ecx, ecx ; counter
mov edx, [ebp+8] ; addr
.again: inc ecx
cmp ecx, [ebp+12] ; <?> arg2
jae .quit
push ecx
push edx
kernel 3, 0, edx, 1
pop edx
pop ecx
cmp eax, 1
jne .quit
mov al, [edx]
cmp al, 10 ; EOL
je .quit
inc edx
jmp .again
.quit: mov [edx], byte 0
mov esp, ebp
pop ebp
ret
global _start
extern putstr
extern getstr
extern quit
section .data
nmq db 'Hi, what is your name?', 10, 0
pmy db 'Pleased to meet you, dear ', 0
exc db '!', 10, 0
section .bss
buf resb 512
buflen equ $-buf
section .text
_start:
push dword nmq
call putstr
add esp, 4
push dword buflen
push dword buf
call getstr
add esp, 8
push dword pmy
call putstr
add esp, 4
push dword buf
call putstr
add esp, 4
push dword exc
call putstr
add esp, 4
call quit
%macro kernel 1-*
%ifdef OS_FREEBSD
%rep %0
%rotate -1
push dword %1
%endrep
mov eax, [esp]
int 80h
jnc %%ok
mov ecx, eax
mov eax, -1
jmp short %%q
%%ok:
xor ecx, ecx
%%q:
add esp, (%0-1)*4
%elifdef OS_LINUX
%if %0 > 1
push ebx
%if %0 > 4
push esi
push edi
push ebp
%endif
%endif
%rep %0
%rotate -1
push dword %1
%endrep
pop eax
%if %0 > 1
pop ebx
%if %0 > 2
pop ecx
%if %0 > 3
pop edx
%if %0 > 4
pop esi
%if %0 > 5
pop edi
%if %0 > 6
pop ebp
%if %0 > 7
%error "Can't handle Linux syscalls for more than 6 params"
%endif
%endif
%endif
%endif
%endif
%endif
%endif
int 80h
mov ecx, eax
and ecx, 0fffff000h
cmp ecx, 0fffff000h
jne %%ok
mov ecx, eax
neg ecx
mov eax, -1
jmp short %%q
%%ok: xor ecx, ecx
%%q:
%if %0 > 1
%if %0 > 4
pop ebp
pop edi
pop esi
%endif
pop ebx
%endif
%else
%error Please define either OS_LINUX or OS_FREEBSD
%endif
%endmacro
%ifdef OS_FREEBSD
openwr_flags equ 601h
%else
openwr_flags equ 241h
%endif
%include "kernel.inc"
global putstr
extern strlen
section .text
putstr: ; arg1 = address of the string
push ebp
mov ebp, esp
push dword [ebp+8] ; arg1
call strlen
add esp, 4
kernel 4, 1, [ebp+8], eax
mov esp, ebp
pop ebp
ret
global strlen
section .text
strlen: ; arg1 == address of the string
push ebp
mov ebp, esp
xor eax, eax
mov ecx, [ebp+8] ; arg1
.lp: cmp byte [eax+ecx], 0
jz .quit
inc eax
jmp short .lp
.quit: pop ebp
ret
;; getstr.asm ;;
%include "kernel.inc"
global getstr
section .text
getstr: ; < (buffer address), (buffer length)
push ebp
mov ebp, esp
mov edx, [ebp+8]
xor ecx, ecx
.lp:
inc ecx
cmp ecx, [ebp+12]
jae .quit ; not enough buffer size
push ecx
push edx
kernel 3, 0, edx, 1 ; read one character
pop edx
pop ecx
cmp eax, 1 ; did we actually get
jne .quit ; 1 character?
mov al, [edx]
cmp al, 10 ; we don't need space
je .quit
inc edx ; next byte in the buffer
jmp .lp
.quit:
mov [edx], byte 0 ; add 0 at the end
mov esp, ebp
pop ebp
ret
;; greet.asm ;;
global _start
extern putstr
extern getstr
extern quit
section .data
what db "What is your name?",10,0
hello db "Hello ",0
end db ":)",10,0
section .bss
inp resb 256
inplen equ $-inp
section .text
_start:
push what
call putstr
add esp, 4
push inplen
push inp
call getstr
add esp, 8
push hello
call putstr
add esp, 4
push inp
call putstr
add esp, 4
push end
call putstr
add esp, 4
jmp .quit
.quit:
push dword 0
call quit
%macro kernel 1-*
%if %0 > 1
push ebx
%endif
%rep %0
%rotate -1
push dword %1
%endrep
pop eax
%if %0 > 1
pop ebx
%if %0 > 2
pop ecx
%if %0 > 3
pop edx
%if %0 > 4
%error "Can't do syscall with more than 4 parameters"
%endif
%endif
%endif
%endif
int 80h
mov ecx, eax
and ecx, 0xfffff000
cmp ecx, 0xfffff000
jne %%ok
mov ecx, eax
neg ecx
mov eax, -1
jmp short %%end
%%ok:
xor ecx, ecx
%%end:
%if %0 > 1
pop ebx
%endif
%endmacro
;; putstr.asm ;;
%include "kernel.inc"
global putstr
extern strlen
section .text
putstr: ; < (string address)
push ebp
mov ebp, esp
push esi
mov esi, [ebp+8]
push esi
call strlen
add esp, 4
kernel 4, 1, esi, eax
pop esi
mov esp, ebp
pop ebp
ret
;; quit.asm ;;
%include "kernel.inc"
global quit
section .text
quit: kernel 1, 0
;; strlen.asm ;;
global strlen
section .text
strlen: ; < (string address) > (string length)
push ebp
mov ebp, esp
mov eax, [ebp+8]
xor ecx, ecx
.lp:
cmp byte [eax+ecx], 0
je .quit
inc ecx
jmp short .lp
.quit:
mov eax, ecx
mov esp, ebp
pop ebp
ret
Labels become relative addresses within an object module, then resolved when linking modules into an executable.
object module supplies exported symbols and requests imported symbols
assembler cannot know every final address
object file supplies code plus relocation information
nm displays object-file symbols
# Create library:
ar crs libgreet.a strlen.o getstr.o putstr.o quit.o
# Use library:
ld -m elf_i386 greet.o libgreet.a -o greet
# or:
ld -m elf_i386 greet.o -l greet -L . -o greet
Make sure to specify object modules before libraries.
programs reuse collections of prepared subroutines
static library = archive of object modules with symbol-index information
in the model discussed, object module is the unit of inclusion
ar crs libgreet.a strlen.o getstr.o putstr.o quit.o builds an archive
library remains a collection of selectable modules
Avoid using libraries that depend on other libraries!
Linker can fail in 2 cases:
extern label)global)| Option | Description |
|---|---|
-l |
specify library with just name in
lib(name).a |
-L |
specify location of libraries |
-o |
output name (usually executable) |
-m |
architecture (elf_i386) |
nostdlib |
don't use standard path to search for libraries |
-e |
specify a different entry point than _start |
-static |
use only static libraries |
-s |
strip debug info and symbols |
linker receives an ordered list of objects and libraries
two conceptual symbol sets:
book's linking model begins with entry point _start unresolved
for each ordinary object:
for each static archive:
greet example:
principal errors:
ordinary archive search does not automatically return to earlier archives
dependencies between libraries constrain their order too
linking principles also matter for C/C++ programs
ld also supports detailed options and linker scripts
common options:
additional options:
-static requests static library selection
-s strips symbol/debug information from the result
floating-point values approximate quantities using finite bits
historical x86 floating-point support used separate 8087/80287/80387 chips
Floating-point number:
(-1)s * 2(p-b) * m
s - sign bitp - exponent value (unsigned)b - exponent bias (format-dependent)m - mantissa| Precision name | Size (bits) | Exponent size | Exponent bias | Mantissa (bits) |
|---|---|---|---|---|
| Single precision | 32 | 8 | 127 | 23 |
| Double precision | 64 | 11 | 1023 | 52 |
| Extended precision | 80 | 15 | 16383 | 64 |
FPU Number Classes (Single Precision):
| Class | Exponent | Mantissa | Implicit | Value Formula |
|---|---|---|---|---|
| Zero | 0 |
0 |
0. |
+/- 0.0 |
| Denormal | 0 |
!= 0 |
0. |
+/- 0.M * 2(-126) |
| Normal | 01 - 254 |
Any | 1. |
+/- 1.M * 2(E - 127) |
| Infinity | 255 |
0 |
N/A | +/- Infinity |
| NaN | 255 |
!= 0 |
N/A | NaN |
Notation: 1000.0 = 1.0e3 = 1.0e+3 = 1.0E3.
ordinary normalized value = (-1)^sign * 2^(exponent-bias) * significand
exponent patterns of all zeros/all ones encode special cases
signed zero:
subnormal value:
author's units example illustrates the enormous available exponent range
all-ones exponent represents infinities or NaNs, depending on significand encoding
NASM sizes:
dd/dq distinguish integer and floating initializers by notation
x87 registers hold extended-format values
/*
gcc -S -std=c89 -m32 -masm=intel test_float.c -o test_float.s
with x as float:
fstp DWORD PTR [esp]
call test_float
add esp, 4
with x as double:
fstp QWORD PTR [esp]
call test_float
add esp, 8
*/
void test_float(double x) {
};
int main() {
test_float(3.14f);
return 0;
}
%include "calls.inc"
%assign param_num 2
global _start
extern str2flt ; float.asm
extern flt2str ; float.asm
section .bss
num resd 1
buf resb 12
buf_len equ $-buf
section .data
newline db 10
err_param db "Usage: ./prog <number 1> <number 2>",10
err_param_len equ $-err_param
section .text
terminate:
.wrong_params:
scall 4, 2, err_param, err_param_len
scall 1, 1
_start:
pop ebx ; argc
mov esi, esp ; argv
cmp ebx, param_num
jb terminate.wrong_params
pcall str2flt, [esi+4]
fstp dword [num]
pcall flt2str, [num], buf, buf_len
scall 4, 1, buf, eax
scall 4, 1, newline, 1
.end: scall 1, 0
| Field | Reg | Description |
|---|---|---|
TOP |
SR |
Top of stack pointer (physical register 0-7) |
C0, C3 |
SR |
Condition codes (C0=CF, C3=ZF) |
SF |
SR |
Stack fault exception |
IE .. PE |
SW |
Exceptions (see Exceptions and their handling) |
IM .. PM |
CR |
Exception masks (1: mask/default, 0: throw exception) |
RC |
CR |
Round: 00 near, 01 down, 10
up, 11 zero |
PC |
CR |
Precision: 00 32-bit, 10 64-bit,
11 80-bit |
TAG |
TW |
State: 00 valid, 01 zero, 10
NaN/Inf, 11 empty |
x87 has eight physical 80-bit data registers organized as a circular stack
NASM uses ST0, ST1, ...
control word, status word and tag word contain flags and small fields
status word:
status exception bits:
summary/busy status records pending exceptional work and coprocessor state
control word:
precision-control field selects significand precision for applicable arithmetic
tag word: two bits per physical register
instruction/data pointers retain information useful for exception diagnosis
x87 mnemonics begin with f
| Command | Name | Operands | Description |
|---|---|---|---|
fld |
Load float | stx/mem |
Push param into st0 (mem: 32/64/80) |
fst |
Store float | stx/mem |
Copy st0 to param (mem: 32/64) |
fstp |
Store float & pop | stx/mem |
Copy st0 to param, pop (mem:
32/64/80) |
fild |
Load integer | mem |
Push int as float (mem: 16/32/64) |
fist |
Store integer | mem |
Round st0 to int, store (mem: 16/32) |
fistp |
Store int & pop | mem |
Round st0 to int, store, pop (to 64-bit) |
fxch |
Exchange | none/stx |
Swap st0 with st1 (default) or
stx |
fld1 |
Load 1.0 | none |
Push 1.0 into st0 |
fldz |
Load 0.0 | none |
Push +0.0 into st0 |
fldpi |
Load pi | none |
Push pi into st0 |
fldl2e |
Load log2(e) | none |
Push log_2(e) into st0 |
fldl2t |
Load log2(10) | none |
Push log_2(10) into st0 |
fldln2 |
Load ln(2) | none |
Push ln(2) into st0 |
fldlg2 |
Load log10(2) | none |
Push log_10(2) into st0 |
fld pushes a floating-point value
fst stores ST0 without popping; fstp stores then pops
integer conversion:
fxch stN exchanges ST0 with another occupied stack register
constant-loading instructions push a new value
| Command | Name | Operands | Description |
|---|---|---|---|
fadd |
Add | mem32/64 |
st0 = st0 + mem |
fmul |
Multiply | st0, stx |
st0 = st0 * stx |
fsub |
Subtract | stx, st0 |
stx = stx - st0 |
fsubr |
Sub reverse | mem32/64 |
st0 = mem - st0 |
fdiv |
Divide | st0, stx |
st0 = st0 / stx |
fdivr |
Div reverse | st0, stx |
st0 = stx / st0 |
faddp |
Add & pop | stx = stx + st0; pop st0 |
|
fsubp |
Sub & pop | none | st1 = st1 - st0; pop st0 |
fmulp |
Mul & pop | none | translated directly from |
fdivp |
Div & pop | none | reverse polish notation |
fdivrp |
Div rev & pop | none | st1 = st0 / st1; pop st0 |
fimul |
Int mul | mem16/32 |
st0 = st0 * int(mem) |
fidiv |
Int div | mem16/32 |
st0 = st0 / int(mem) |
fidivr |
Int div rev | mem16/32 |
st0 = int(mem) / st0 |
fabs |
Absolute | none | st0 = abs(st0) |
fchs |
Change sign | none | st0 = -st0 |
frndint |
Round to int | none | st0 = round(st0) (uses RC from
CR) |
Using reverse polish notation: (x+y) * (1-z) converts to x y + 1 z - *, which translates one-to-one in assembly:
; x y + 1 z - *
fld qword [x] ; x
fld qword [y] ; y
faddp ; +
fld1 ; 1
fld qword [z] ; z
fsubp ; -
fmulp ; *
However, it can be written simpler:
; (x+y)*(1-z)
fld qword [x]
fadd qword [y]
fld1
fsub qword [z]
fmulp
memory-source arithmetic uses ST0 and 32/64-bit floating memory
two-register forms require ST0 as one operand
p forms store result in first register, then pop ST0
no-operand p form uses ST1 and ST0
reverse Polish notation evaluates naturally on the register stack
Dijkstra's conversion uses an auxiliary operator stack
conversion rules for the left-associative arithmetic discussed:
example a-b+c*d -> a b - c d * +
mark unary operators distinctly before conversion
avoid ambiguous assembler-specific no-operand ordinary arithmetic forms
fiadd/fisub/fisubr/fimul/fidiv/fidivr:
unary operations on ST0:
fprem/fprem1, fscale and fxtract are mentioned for further study
| Command | Name | Operation / Limits |
|---|---|---|
fsin |
Sine | st0 = sin(st0) |
fcos |
Cosine | st0 = cos(st0) |
fsincos |
Sin & Cos | st1 = sin(st0); push st0 = cos(st0) |
fptan |
Tangent | st1 = tan(st0); push st0 = 1.0 (now fdivrp
for cot) |
fpatan |
Arctangent | st1 = atan2(st1, st0); pop st0 |
fyl2x |
y * log2(x) | st1 = st1 * log2(st0); pop st0 |
fyl2xp1 |
y * log2(x+1) | st1 = st1 * log2(st0 + 1); pop st0 (abs(x) < 1 -
sqrt(2)/2) |
f2xm1 |
2x - 1 | st0 = 2^st0 - 1 (abs(x) < 1) |
fsqrt |
Square root | st0 = sqrt(st0) |
Use fyl2x to compute logarithms of arbitrary bases. Use
fyl2xp1 and f2xm1 to preserve precision for
inputs near zero.
fsin/fcos/fsqrt replace ST0 with sine/cosine/square root fsincos produces two values
fptan leaves 1.0 in ST0 and tangent in ST1
fpatan consumes x=ST0 and y=ST1
f2xm1, fyl2x and fyl2xp1 support numerically useful combined operations
fyl2x computes y*log2(x), consumes both operands and pushes result
fyl2xp1 computes y*log2(1+x)
useful when 1+x would round to 1 before ordinary logarithm evaluation
f2xm1 computes 2^x-1 for -1 <= x <=1
these instructions use implicit stack operands
| Command | Name | Operands | Operation |
|---|---|---|---|
fcom |
Compare | mem/stx |
cmp st0, op |
fcomp |
Compare & Pop | mem/stx |
cmp st0, op; pop st0 |
fcompp |
Compare & Double Pop | none | cmp st0, st1; pop st0, st1 |
ficom |
Compare Integer | mem16/32 |
cmp st0, float(op) |
ftst |
Test | none | cmp st0, 0.0 |
Result FPU flags (C3, C0):
st0 > op : 00st0 < op : 01st0 == op : 10We have to load FPU flags into CPU flags to construct conditions:
; SR -> FLAGS
fstsw ax ; SR -> AX
sahf ; AH -> FLAGS (C3 -> ZF, C0 -> CF)
; now we can use unsigned conditional jumps:
; ja, jb, jae, jbe, jna ...
To get smaller out of a and b in
m:
fld qword [b] ; b -> ST0
fld qword [a] ; a -> ST0 (now b -> ST1)
fcom ; compare
fstsw ax ; SR -> AX
sahf ; AH -> FLAGS
ja lpa ; a > b -> jump
fxch ; swap ST0, ST1
lpa: ; bigger is in ST0
fstp st0 ; remove bigger
fstp qword [m] ; get smaller into m
x87 comparison flags must reach the CPU flags before ordinary conditional jumps
fcom compares ST0 with memory operand/STn; omitted operand means ST1
ordered comparison status:
C2 indicates unordered comparison when applicable
fstsw ax; sahf transfers status bits
minimum example:
ffree st0 plus fincstp can also discard the top
ficom/ficomp compare ST0 with signed word/dword integer memory
The lower 6 bits of both CR and SR map to
the main exceptions:
| Exception | Flag | Description |
|---|---|---|
| Invalid Operation | I |
NaN, sqrt(-1), log(-1), or stack full/empty |
| Denormalized | D |
Denormalized number used or loaded |
| Zero Divide | Z |
Division by zero |
| Overflow | O |
Result too large for destination (e.g. 80-bit to 32/64-bit via
fst) |
| Underflow | U |
Result too small (unlike D, applies to result, not
operand) |
| Precision | P |
Result needed rounding (usually normal) |
| Stack Fault | SF |
(SR only) I was caused by stack error |
These bits control exception handling in CR and
reporting in SR:
| Register | Bit State | Behavior / Description |
|---|---|---|
CR |
0 |
Unmasked: Generates an internal interrupt |
CR |
1 |
Masked: Handled internally (e.g., returns Inf) |
SR |
1 |
Exception occurred. Sticky (use fclex to clear) |
six exception classes may indicate an error or ordinary rounding behavior
invalid operation:
denormal-operand exception concerns a subnormal input
divide-by-zero exception concerns a nonzero finite dividend divided by zero
overflow: result too large for destination format
underflow: result too tiny for normal representation, with relevant precision loss
precision/inexact: exact result does not fit available significand bits
control-word mask bits correspond to status exception bits
status flags are sticky
wait Instructionfimul dword [k] ; Causes exception
mov [k], ecx ; CPU overwrites [k] before
; FPU triggers interrupt!
fsqrt ; Interrupt finally fires here,
; but [k] is lost
Solutions:
mov [k], ecx after
fsqrt.fwait (wait): force pending exceptions
to fire now.fimul dword [k]
fwait ; Forces interrupt here,
; before [k] is overwritten
mov [k], ecx
x87 can defer reporting a pending unmasked exception until a later checking instruction
fwait / wait checks pending unmasked x87 exceptions
some waiting mnemonics represent wait plus a nonwaiting instruction
| Command | Operand | Description |
|---|---|---|
f[n]stcw |
mem |
Stores CR to 16-bit memory |
fldcw |
mem |
Loads CR from 16-bit memory |
f[n]stsw |
m/AX |
Stores SR to memory or AX |
f[n]clex |
- | Clears exception flags in SR |
fincstp |
- | Increments TOP pointer (does not change TW
tags) |
fdecstp |
- | Decrements " |
ffree |
stX |
Marks specified register as empty in the Tag Word |
finit |
- | Resets FPU (CR=037Fh, TOP=0, all
TW=empty) |
f[n]save |
mem |
Saves full FPU state (108 bytes), then runs finit |
frstor |
mem |
Restores full FPU state from memory |
Set rounding mode to "towards zero" (bits 10, 11):
sub esp, 4 ; get memory in stack
fstcw [esp] ; store in this memory CR
or word [esp], 0000110000000000b
; set 11th and 10th bits
;
; Other code
;
fclex ; clears exceptions in SR
; not to trigger interrupt
; by unmasking CR in next command
fldcw [esp] ; load result back in CR
add esp, 4 ; clean up stack
; Remove a value from the top of the stack without saving it:
ffree st0
fincstp
control word sets operating modes; status word reports state; tag word tracks registers
fstcw/fnstcw store control word to 16-bit memory
fldcw loads it from 16-bit memory
set rounding toward zero:
fstsw/fnstsw store status to AX or 16-bit memory
changing masks can expose an already-pending exception
ffree STn marks that physical register empty without moving TOP
finit/fninit establish initial x87 state
fsave/fnsave save complete legacy x87 state
fstenv/fnstenv/fldenv save/load the environment without the data registers
fnop: floating-point no operation
This subset is enough to write working assembly programs and, more importantly, to understand how compiled languages execute on real hardware; deeper x86 details and architectures such as ARM or SPARC can be studied from technical references.
the covered subset is enough to write assembly programs
full i386 architecture includes many additional features and historical complications
other architectures such as ARM or SPARC offer further low-level perspectives
Previous: Programming in Pascal Reading map Next: C Programming
Comments