Assembly Language

Reading map

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

Detailed notes - 3: Processor capabilities and assembly language

1

assembly in ordinary software:

  • most code is written in high-level languages, including C
  • kernels and microcontroller firmware still contain small assembly parts

2

assembly remains useful when hardware access or severe resource limits require it

  • example: ATtiny4 has 16 bytes of RAM and 512 bytes for program code
  • such constraints are exceptional, even among microcontrollers

3

main reason to study assembly: understand what high-level operations cost

  • a scalar assignment can take one instruction
  • copying a large array or a complex object can require many instructions
  • identical source notation does not imply identical work

4

professional understanding should connect all levels of the computer

  • electronics, instructions, operating system, application programs
  • the machine contains mechanisms designed by people, not unexplained magic

5

learning one instruction set teaches the way to reason about other processors

  • concrete mnemonics change
  • understanding execution and data representation carries over

6

book uses 32-bit i386 instructions under Unix

  • x86_64 processors can execute compatible 32-bit programs
  • only a useful subset of the instruction set is needed here

7

32-bit examples expose the complete stack frame

  • parameters, return address, local variables
  • register-based parameter passing in x86_64 hides part of this arrangement

8

NASM uses Intel syntax

  • Intel: mov eax, [a+edx]
  • AT&T: movl a(%edx), %eax
  • same operation, different operand notation and ordering
  • NASM and FASM support Intel syntax; this book chooses NASM

Introduction

Detailed notes - 3.1: Introduction

1

review instruction execution and the distinction between assembler and assembly language

2

before systematic instruction study:

  • understand the execution environment
  • review the processor family's history
  • assemble and run a small program

History of the i386 platform

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.

Detailed notes - 3.1.3: History of the i386 platform

1

Intel family before x86:

  • 4004: 4-bit microprocessor, 1971
  • 8008: 8-bit, 1972; 8080: 1974
  • 8086: 16-bit, 1978; 8088: similar CPU with an 8-bit external data bus
  • IBM PC used 8088
  • early compatibility sometimes meant reassembling the same source, not reusing machine code

2

8086, 8088 and 80186:

  • no memory protection or separation of privileged instructions
  • 20-bit address bus -> at most 1 MB directly addressable
  • 80186 improved speed, integrated support circuitry and added instructions

3

80286:

  • protected mode, segment-based virtual memory and four protection rings
  • 24-bit address bus -> 16 MB

4

80386 / i386:

  • 32-bit general-purpose registers and addresses
  • up to 4 GB directly addressable physical memory
  • paging supports multitasking
  • compatibility retains AX as the low 16 bits of EAX, similarly for other registers

5

x86 development and 64-bit extensions:

  • earlier successors mainly increased speed and added instructions
  • Intel Itanium used a different architecture with slow i386 emulation
  • AMD Opteron introduced the compatible x86_64 extension in 2003
  • Intel subsequently adopted x86_64 too

6

author's performance aside:

  • more cores do not remove disk and bus bottlenecks
  • usefulness depends on whether the workload can occupy the cores

7

x86_64 processors can run the book's 32-bit instruction sequences

  • the OS and toolchain also need the corresponding execution support

CPU execution cycle

Instructions and data share memory in the Von Neumann model: programs can also be processed as data.

Detailed notes - 3.1.1: Von Neumann architecture

1-2

computer = CPU + RAM

RAM:

  • linear, uniform memory consisting of equally sized locations
  • each location has its own address
  • CPU can read from / write to locations directly

program:

  • sequence of machine instructions stored in RAM
  • RAM itself does not distinguish code from data

binary representation is customary, but separate from these architectural principles

3

programs can be treated as data

  • one program can process another program
  • self-modifying code is possible in principle; modern protection restricts it

4

general-purpose registers: temporary storage for calculations

  • much faster to access than RAM, but much smaller total capacity
  • hold current operands and intermediate results
  • completed results can be moved to RAM to free registers

5

special-purpose registers include the instruction pointer

  • stores address of the next machine instruction to execute

6-7

CPU execution cycle:

  • fetch instruction using the instruction pointer
  • increase instruction pointer by the instruction's length
  • decode and execute instruction
  • repeat

CPU follows instructions; it does not understand the program's purpose control is at the location currently addressed by the instruction pointer

8

branches and loops explicitly replace the instruction pointer

  • the new address replaces the already advanced sequential address

9

jumps:

  • unconditional: always replace instruction pointer
  • conditional: replace it only when the tested condition holds
  • otherwise execution continues with the next instruction

10

subroutine call:

  • save the already advanced instruction pointer as return address
  • jump to the subroutine
  • return restores that address, continuing after the call

11

transfer of control = explicitly changing the instruction pointer

fetch at instruction pointer -> advance by instruction size -> decode / execute -> repeat

Programs Under a Multitasking OS

Detailed notes - 3.1.2: Programming under multitasking operating systems

1-2

Unix runs several tasks concurrently

  • assembly exposes restrictions also present for other languages
  • reliable multitasking needs hardware support

3

memory protection:

  • prevents a task from damaging another task or the OS
  • a program may access only memory assigned to it

4

CPU modes:

  • privileged / supervisor mode: all instructions available
  • user mode: privileged instructions forbidden

privileged operations include:

  • direct device access
  • configuring memory protection
  • other actions affecting the whole system

user task:

  • transforms data in its assigned memory
  • requests outside services through system calls
  • even termination requires OS work: release memory and stop scheduling

return to privileged mode also transfers control to the OS

5

physical address = number of a real memory location

  • embedding physical addresses would tie a program to one memory region
  • that region might already belong to another running task

6

virtual address = address used by a program

  • i386: 32 bits, 00000000 through ffffffff
  • some addresses are mapped to physical memory; others are not
  • MMU translates virtual addresses according to OS settings

7

each task can have its own address space

  • the same virtual address can refer to different physical memory in different tasks

8

book studies user-mode instructions in Unix's flat memory model

  • unused segmentation features are omitted
  • stud_io.inc temporarily supplies I/O and termination macros
  • macros expand into instruction sequences during assembly

Getting started

%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
Detailed notes - 3.1.4: First assembly program

1

learn instruction notation and assembler syntax together through a working example

2

goal: print Hello followed by a newline five times

  • printing and termination require the OS
  • macros initially hide the system-call details

3

stud_io.inc supplies the example's macros

4

choose the file's OS configuration:

  • Linux: enable %define STUD_IO_LINUX
  • FreeBSD: enable %define STUD_IO_FREEBSD instead
  • semicolon starts a comment; comment out the unused definition

5

assembly source contains:

  • mnemonics: processor instructions
  • directives: instructions to the assembler
  • macro calls: requests to substitute predefined source text

%include "stud_io.inc": insert the macro definitions into the source

  • PRINT prints a literal string
  • PUTCHAR 10 prints a newline
  • FINISH terminates the task

6

include definitions before their first use

  • assembler reads source from top to bottom

7

global _start exports the entry-point label

8

sections in a file become memory regions when the OS loads the program

  • code, initialized data and information about uninitialized storage
  • OS also creates a stack

9

section names:

  • .text: machine code
  • .data: initialized data
  • .bss: reserved uninitialized storage
  • example needs only an explicit .text section

10

mov eax, 0:

  • first operand = destination; second = source
  • EAX becomes the loop counter, initially zero

11-12

_start is a label attached to that instruction

13

mov eax, 0 becomes five bytes: b8 00 00 00 00

  • opcode selects operation and register
  • four following bytes encode the immediate value
  • labels let us refer to instruction addresses without writing numeric addresses

14

label = identifier associated with a number

  • usually an address, but can also be an ordinary constant
  • defining a label records the current address
  • using it as an operand substitutes its value

15

labels belong to assembly/linking information

  • CPU executes machine code containing numeric operands, not label names

16

NASM permits labels with or without a colon

  • usual style: colon on code labels; no colon on data labels

17

_start marks the entry point

  • loader starts execution there even though our program never jumps to it

18

again labels the loop's first operation

  • PRINT "Hello" expands the macro with the literal string as argument

19

PRINT is not a CPU instruction

  • expansion includes real instructions and a write system call
  • expansion depends on the chosen operating system

20

PUTCHAR 10 emits the newline

  • ordinary sequential instructions do not need their own labels

21

inc eax records one more printed line

  • increment instruction adds 1

22

cmp eax, 5 records comparison results in the flags register

jl again:

  • repeat while the signed counter is less than 5
  • jump reads the comparison flags

23

when EAX reaches 5, jl falls through

  • FINISH requests process termination

24

global _start makes entry-point information available to the linker

25

whole algorithm:

  • initialize counter
  • print line, increment counter, compare, repeat if needed
  • finish

26

save assembly source in hello5.asm

27

building has two stages:

  • assembler: source -> object module
  • linker: combine modules/libraries, resolve addresses -> executable

28

even a one-module program still needs linking

  • global causes _start information to be recorded in the object file

29

historical i386 build commands:

  • nasm -f elf hello5.asm -> hello5.o
  • ld hello5.o -o hello5 -> executable
  • on a 64-bit Linux toolchain: ld -m elf_i386 hello5.o -o hello5
  • FreeBSD example uses -m elf_i386_fbsd
  • source and stud_io.inc must both be available

uname -a helps identify the architecture

  • these instruction examples target x86, not ARM or another instruction set

30

-o selects output filename

  • ./hello5 runs the executable and prints five Hello lines
Examples & tests (3 files) - 3.1.4: First assembly program
Book exampleBook example: hello5.asmIn catalog
hello5.asmAssembly / 11 lines
%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
Section test04 (03-01)In catalog
hello5-00.asmAssembly / 14 lines
%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
hello5-01.asmAssembly / 11 lines
%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

Macros in stud_io.inc

PRINT "Hello"/'Hello'
PUTCHAR 10/[a-d][l,h]/[label]
GETCHAR -> al (C-d = -1)
FINISH
Detailed notes - 3.1.5: Macros in stud_io.inc

1

four macros: PRINT, PUTCHAR, GETCHAR and FINISH

2

PRINT:

  • accepts a literal string in single or double quotes
  • does not format arbitrary values

3

PUTCHAR:

  • prints one character
  • accepts character code, quoted character, byte register or memory operand
  • byte registers: AL/AH, BL/BH, CL/CH, DL/DH
  • larger registers are not valid arguments

4

GETCHAR:

  • no arguments; reads one character from standard input
  • character code returned in EAX, with upper bits zero
  • AL therefore contains the character
  • end of input -> EAX = -1 / ffffffff
  • Unix terminal EOF can be entered with Ctrl-D

5

FINISH:

  • terminates the process
  • optional numeric argument specifies the exit status

Formatting assembly code

Detailed notes - 3.1.6: Formatting assembly programs

1

assembly formatting differs from Pascal formatting

2

one source line is the main syntactic unit

  • layout tradition comes partly from early Fortran

3

fixed-format Fortran reflected punched cards

  • separate columns for labels, continuation marker and statement text

4

assembly source describes a linear memory image

  • structural indentation does not represent nested statements here
  • detailed comments explain algorithms and control flow

5

align code in columns:

  • labels at the left
  • instructions after a tab; optional separate comment column
  • long labels can occupy their own line
  • one or two tab stops may be reserved for labels
  • an optional mnemonic column aligns operands too
  • unusually long macro names may require a layout exception

6

general source-formatting principles still apply

7

book's source convention: ASCII characters and English comments

  • comments remain essential even when writing them takes extra effort

8

keep source lines within 79 characters

9

use meaningful labels and sensible decomposition

  • subroutines, modules and subsystems matter in assembly too

Main i386 commands

Detailed notes - 3.2: Basic i386 instructions

1

basic user-mode instruction set:

  • registers, data movement, integer arithmetic and control flow
  • subroutines and floating-point arithmetic follow separately

2

privileged instructions are outside this introduction

  • ordinary user programs cannot execute them

Other useful instructions

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).

Detailed notes - 3.2.14: Other useful instructions

1

stc / clc set/clear CF

  • can use CF to communicate a condition
  • cli / sti control interrupt enable and are unavailable to ordinary user code

2

lahf copies selected flags into AH

  • CF bit 0; PF bit 2; AF bit 4; ZF bit 6; SF bit 7

3

movsx / movzx combine copying with widening

  • destination is a register; source is a smaller register or memory operand
  • movsx extends the sign; movzx fills upper bits with zero
  • byte -> word/dword and word -> dword forms exist

4

cpuid reports processor identity and supported features

  • available on later members of the family, not the original i386

5

other examples:

  • xlat: byte translation through a lookup table
  • bswap: reverse byte order of a 32-bit register, introduced with i486
  • aaa/aad/aam/aas: decimal-adjust operations

6

xchg exchanges two equal-sized operands

  • one must be a general-purpose register
  • register-memory form performs an atomic exchange
  • useful for coordination between concurrent activities

7

lock prefix makes supported memory read-modify-write instructions atomic

  • examples: lock inc dword [x], lock sub [m],eax
  • stronger coordination can be costly
  • memory xchg already has the required locking semantics

8

nop: no operation

Registers

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

Detailed notes - 3.2.1: Registers

1

register = CPU storage for a fixed number of bits

  • general-purpose, segment and special-purpose registers
  • register names identify hardware storage, not program variables

2

segment registers: CS, DS, SS, ES, FS, GS

  • OS initializes them for the book's flat-address-space examples
  • examples leave them unchanged

3

code/data/stack memory regions are not simply the hardware segments

  • Unix builds its memory organization using other protection mechanisms

4

32-bit general-purpose registers:

  • EAX, EBX, ECX, EDX, ESI, EDI, EBP, ESP
  • low 16 bits accessible as AX, BX, CX, DX, SI, DI, BP, SP
  • these names overlap the same physical storage

5

AX, BX, CX and DX also have byte parts

  • AL/BL/CL/DL: low byte
  • AH/BH/CH/DH: high byte of the low 16 bits
  • SI, DI, BP and SP have no byte-register names in i386 mode

6

EAX / AX: accumulator

  • implicit operand/result register for multiplication and division

7

EBX / BX: base

  • historical role does not prevent ordinary 32-bit use

8

ECX / CX / CL: counter

  • implicit count for several repeated operations and shifts

9

EDX / DX: data

  • upper product or dividend; division remainder

10

ESI and EDI: source and destination indices

  • implicit addresses used by string instructions

11

EBP: base pointer

  • normally anchors a subroutine's stack frame

12

ESP: stack pointer

  • addresses the current stack top
  • arithmetic instructions can use it, but its stack role must be preserved

13

special registers considered here: EIP and the flags register

14

EIP: address of next instruction

  • fetching an instruction advances it by that instruction's length

15

i386 instruction length varies from 1 to 15 bytes

  • optional prefixes are part of the instruction
  • encoding length cannot be inferred just from the mnemonic

16

flags are individual bits, not one ordinary numeric value

  • ZF: result is zero
  • CF: unsigned carry or borrow
  • SF: most significant result bit / sign
  • OF: signed overflow
  • DF: string direction; cld clears it, std sets it
  • PF: parity; AF: auxiliary carry
  • IF and TF concern interrupts/debugging; outside these examples

arithmetic sets status flags; conditional jumps test them

17

EFLAGS is the 32-bit extension of FLAGS

  • this introduction mainly uses the older flag bits

EAX, AX, AH and AL select nested or adjacent portions of one 32-bit register.
Register names overlap the same bits. Open full size - Editable SVG

Memory, Code segments

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
Detailed notes - 3.2.2: Task memory and segments

1

registers hold temporary results; larger and longer-lived data belongs in RAM

2

instructions and data share the virtual address space

  • byte-sized locations; 32-bit addresses in these examples

3

memory protection assigns access rights to regions

  • readable, writable and executable are distinct properties
  • an address can exist without permitting every kind of access

4

principal task regions: code, data and stack

  • loader builds code/data from executable sections
  • initial Unix stack contains arguments and environment information
  • a segment may combine sections; some file sections are not loaded

5

code region:

  • executable and readable; ordinarily not writable
  • physical code pages can be shared by instances of the same program
  • immutable constants can share this region too

6

.text supplies the machine code

  • leading dot is part of the section name

7

data region:

  • readable and writable; ordinarily non-executable
  • .data stores explicit initial values in the executable
  • .bss records required storage size without storing all its bytes
  • dynamic allocation may enlarge data memory or create another region

8

historical Unix examples of requesting memory:

  • Linux brk changes the data-segment boundary
  • mmap creates a mapping; used for the FreeBSD example

9

stack region:

  • writable storage for return addresses and local variables
  • grows as needed within OS limits
  • initial contents depend on arguments and environment
  • created by the OS, without a corresponding stack-data section
  • executable-stack behavior depends on OS/version; book discusses older systems
Tests & experiments (3 files) - 3.2.2: Task memory and segments
Section test02 (03-02)In catalog
brk-00.asmAssembly / 19 lines
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
brk-01.asmAssembly / 97 lines
%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
brk-02.asmAssembly / 98 lines
%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

Memory directives

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
Detailed notes - 3.2.3: Reserving memory

1

storage directives belong to NASM syntax, not the processor instruction set

2

assembling instructions creates a memory image of their machine-code bytes

3

the assembler can also construct an image of data

  • specify required storage and, when needed, initial contents

4

section selects which image subsequent source contributes to

  • .text: instructions; .data: initialized bytes; .bss: required storage size
  • may switch between sections repeatedly
  • linker combines section information into the executable

5

storage directives either reserve uninitialized storage or provide initial values

  • preceding label names the first byte's address

6-7

NASM size terminology preserves the older x86 convention

  • byte = 1 byte
  • word = 2 bytes
  • dword = 4 bytes
  • qword = 8 bytes
  • word in this syntax does not mean the i386 CPU's 32-bit machine word

8

reserve uninitialized elements:

  • resb N: N bytes
  • resw N: N two-byte words
  • resd N: N four-byte double words
  • string resb 20 -> 20 bytes
  • count resw 256 -> 512 bytes
  • x resd 1 -> 4 bytes, enough for a 32-bit integer or address

9

define initialized elements:

  • db, dw, dd: 1, 2, 4 bytes per value
  • comma-separated values determine the number of elements
  • fibon dw 1,1,2,3,5,8,13,21 -> 16 bytes

10

numeric literals:

  • hexadecimal: 2af3h, $2af3 or 0x2af3
  • h/$ notation needs an initial digit: 0a21h, $0f9
  • octal: suffix o or q; binary: suffix b

11

quoted characters stand for their codes

  • db '7' stores 55, the ASCII code for digit 7
  • db accepts a whole string as consecutive bytes
  • single and double quotes are alternatives
  • split the data into adjacent arguments when both quote characters are needed

12

strings can also be supplied to dw/dd

  • packing/padding rules then need additional care

13

usual placement:

  • db/dw/dd initial values in .data
  • resb/resw/resd reservations in .bss
  • large .bss reservations increase memory needs without storing those bytes in the file

14

unchanging data can be placed in the code region

  • permits physical sharing between program instances
  • writing to that protected region causes a fault

15

assembler can accept instructions/directives in inappropriate sections

  • machine code in data remains data unless memory permits execution
  • reservations in .data waste file space
  • initialized values in .bss have nowhere to be stored
  • warnings should prompt correction, even when assembly continues
Section test (1 file) - 3.2.3: Reserving memory
Section testString data directive testIn catalog
str_dd.asmAssembly / 20 lines
%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

The mov Command and Its Parameters

section .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
Detailed notes - 3.2.4: mov and operand kinds

1

mov illustrates copying, operand sizes and addressing

2

mov destination, source:

  • copies bits without converting their meaning
  • mov eax, ebx copies EBX to EAX

3

register operand: names a register

immediate operand: value encoded directly in the instruction

  • mov ecx, 5 places the constant 5 in ECX

4

one mnemonic can describe different machine encodings

  • register-to-register and immediate-to-register mov differ in opcode/length

5

memory operand in NASM always uses square brackets

  • mov [count], eax stores EAX at address count
  • mov edx, [count] reads the value stored there
  • mov edx, count puts the address itself in EDX

label without brackets is a number substituted by the assembler brackets request access to memory at that number

Indirect addressing

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]
Detailed notes - 3.2.5: Indirect addressing and effective addresses

1

array traversal needs a different element address on each iteration

2

indirect addressing:

  • compute an address during execution
  • use the computed value to access memory

3

mov ebx, [eax]: read four bytes from the address held in EAX mov ebx, eax: copy the register value itself

4

fill 256 bytes with '@':

  • ECX = 256 remaining elements
  • EDI = array address; AL = '@'
  • store AL through [EDI]
  • increment EDI; decrement ECX
  • repeat with jnz until ECX becomes zero

5-6

example favors familiar instructions over minimizing registers

  • later size qualifiers allow storing an immediate byte directly
  • a different loop could combine position and count

7

effective address = address actually used by an instruction

  • may be fixed or computed as part of instruction execution

8

i386 address form: displacement + base register + index register * scale

  • scale = 1, 2, 4 or 8; terms may be omitted
  • [array+ebx+2*edi] combines all three terms

9

address expression has hardware limits

  • no three-register sum, register subtraction or arbitrary multiplication
  • ESP may be a base, but cannot be the scaled index

10

NASM can rearrange equivalent expressions

  • constant terms are combined at assembly time
  • [eax*5] becomes [eax+eax*4]
  • [eax+ebx*5] needs three register terms and is invalid

11

matrix example: 10 rows of 15 four-byte elements

  • row N starts at offset N*60
  • with that offset in EAX and column in EBX:
    • [matrix+eax+4*ebx] addresses the element

12

lea destination, [address expression]:

  • computes the effective address and stores it in a register
  • performs no memory read
  • 16-bit destination keeps only the low 16 bits
  • lea eax, [1000+ebx+8*ecx] computes 1000+EBX+8*ECX

13

lea also performs useful ordinary arithmetic

  • multiplication by 3, 5 or 9 can use the addressing hardware
  • same restrictions apply even when the result is not an address
A matrix element address combines its base, row displacement and scaled column index; LEA only computes it.
Effective address combines three terms. Open full size - Editable SVG
Section test (1 file) - 3.2.5: Indirect addressing and effective addresses
Section test05 (03-02)In catalog
lea.asmAssembly / 13 lines
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

Combinations and size of operands

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
Detailed notes - 3.2.6: Operand sizes and combinations

1

operand kinds: immediate, register and memory

2

mov destination must be writable storage

  • immediate destination is impossible
  • two explicit memory operands are not supported
  • copy memory through a register: mov eax,[x]; mov [y],eax

3

valid mov combinations:

  • register -> register; register -> memory; memory -> register
  • immediate -> register; immediate -> memory

both operands describe the same data width

  • a register normally determines the width
  • AL -> CX is not a valid plain mov

memory plus immediate needs an explicit size when otherwise ambiguous

  • mov dword [x], 25 stores four bytes
  • byte / word / dword mean 1 / 2 / 4 bytes

mnemonic alone does not determine the machine encoding

  • mov eax,17 and mov eax,x both use immediate source values

Integer addition and subtraction

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
Detailed notes - 3.2.7: Integer addition and subtraction

1

add / sub destination, source:

  • read destination, add/subtract source, write result to destination
  • operand combinations follow mov rules
  • memory plus immediate needs a size: add dword [x], 12

2

signed and unsigned addition/subtraction use the same bit operations

  • programmer supplies the interpretation

3

ZF = 1 when the result is zero

  • useful for both signed and unsigned arithmetic

4

signed interpretation:

  • SF copies the result's most significant bit
  • OF reports signed overflow
  • overflow can make SF differ from the mathematical result's sign

5

unsigned interpretation:

  • CF reports a carry beyond the width or a borrow in subtraction

6

CPU sets flags without knowing which interpretation the programmer intends

  • choose the flags appropriate to the data

7

adc / sbb include the old carry flag

  • adc: destination + source + CF
  • sbb: destination - source - CF
  • then update flags from the new result

8

multiword example: EDX:EAX and EBX:ECX

  • add eax,ecx; adc edx,ebx -> propagate carry into upper half
  • sub eax,ecx; sbb edx,ebx -> propagate borrow

inc / dec add or subtract 1

  • set ZF/SF/OF but preserve CF
  • memory operand needs its size specified

9

neg replaces its operand with 0 - operand

  • updates arithmetic flags, including CF

10

cmp performs subtraction only for its flags

  • does not store the subtraction result
  • usually followed by a conditional jump
  • first operand still cannot be immediate
CMP sets flags from subtraction, and signed and unsigned branches interpret them differently.
The comparison is the same; the chosen flags differ. Open full size - Editable SVG

Integer multiplication and division

[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
Detailed notes - 3.2.8: Integer multiplication and division

1

multiplication/division require more complicated hardware than addition

2

signed and unsigned versions need different instructions

3

multiplication can require twice the operand width

division:

  • accepts a double-width dividend
  • produces both quotient and remainder

4

one-operand forms use implicit accumulator registers

  • explicit operand supplies multiplier/divisor
  • explicit operand must be register or memory, not an immediate
  • imul also has other forms, outside this discussion

5

mul = unsigned; imul = signed

  • byte operand: AL * operand -> AX
  • word operand: AX * operand -> DX:AX
  • dword operand: EAX * operand -> EDX:EAX

6

multiplication sets CF and OF together

  • clear when the low half contains the complete result
  • unsigned: upper half is zero
  • signed: upper half is sign extension of the lower half
  • other flags are undefined; do not test them for a result

7

div = unsigned; idiv = signed

  • byte divisor: AX -> quotient AL, remainder AH
  • word divisor: DX:AX -> quotient AX, remainder DX
  • dword divisor: EDX:EAX -> quotient EAX, remainder EDX
  • quotient rounds toward zero
  • nonzero signed remainder has the dividend's sign
  • absolute remainder is smaller than absolute divisor
  • arithmetic flags are undefined afterwards

8

division exception:

  • divisor is zero, or quotient does not fit its destination
  • OS receives control and normally terminates the erroneous task
  • clearing/preparing the upper dividend half is essential

9

signed extension before division:

  • cbw: AL -> AX
  • cwd: AX -> DX:AX
  • cwde: AX -> EAX
  • cdq: EAX -> EDX:EAX
  • added bits copy the original sign bit
  • instructions have fixed implicit operands

10

unsigned extension: clear AH, DX or EDX as appropriate

The one-operand i386 forms use EDX:EAX as a double-width product or dividend.
Multiply widens; divide splits the result. Open full size - Editable SVG

[Un]conditional jumps

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
Detailed notes - 3.2.9: Conditional and unconditional jumps

1

jump explicitly changes EIP

  • conditional jump falls through when its condition is false

2

jump forms:

  • far: changes hardware segment; unused in these flat-model examples
  • near: arbitrary location within current segment
  • short: signed byte displacement, -128 through +127 from following instruction
  • short / near qualifiers select the intended form
  • default selection depends on assembler/version

3

author prefers explicitly chosen encodings over assembler optimization

4

jmp targets:

  • jmp cycle: direct jump to label
  • jmp eax: address held in EAX
  • jmp [addr]: address read from memory at addr
  • jmp [eax]: address read from memory at the address held in EAX

5

direct relative jump encoding stores target minus following-instruction address

  • indirect jump instead takes the absolute destination from register/memory

6

short jump can reduce code size

  • macros may expand to more bytes than expected
  • out-of-range short displacement is an assembly error

7

conditional jumps test flags or, for some instructions, a register

8

ordinary conditional jumps take a direct target

  • register/memory indirect targets are not supported
  • conditional indirect transfer: invert condition to skip an ordinary indirect jmp
  • older x86/NASM defaults explain the book's emphasis on short versus near

9

conditional direct jumps also encode relative displacements

10

single-flag jumps:

  • jz/jnz: ZF set/clear
  • js/jns: SF set/clear
  • jc/jnc: CF set/clear
  • jo/jno: OF set/clear
  • jp/jnp: PF set/clear

11

cmp eax,ebx followed by jz branches when the two values are equal

12

ordering needs more than the zero flag

  • cmp a,b sets flags from a-b

13

signed a < b: SF differs from OF

  • jl / jnge test this combination
  • testing SF alone fails when subtraction overflows

14

unsigned a < b: subtraction needs a borrow

  • CF = 1; jb / jnae / jc are equivalent

15

greater-than and less-than-or-equal also need ZF

16

comparison jump families:

  • equal: je/jz; unequal: jne/jnz
  • signed: jl, jle, jg, jge
  • unsigned: jb, jbe, ja, jae
  • signed <=: SF != OF or ZF = 1
  • signed >: SF = OF and ZF = 0
  • unsigned <=: CF = 1 or ZF = 1
  • unsigned >: CF = 0 and ZF = 0
  • corresponding negated mnemonics express the complementary condition

Constructing conditions and loops

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:
Detailed notes - 3.2.10: Building branches and loops

1

usually jump when the source-level condition is false

  • while a=0: compare with zero, then jnz to exit

2

while loop:

  • condition -> jump to exit if false
  • body -> unconditional jump back to condition

if/else:

  • condition -> jump to else if false
  • then branch -> jump over else to end
  • else branch -> end

true case naturally falls through into its body

3

negated jump names can make the source condition clearer

  • jnb, jna, jnge, jnle emphasize skipping when the condition fails

Loops with ecx

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.

Detailed notes - 3.2.11: ECX and counted loops

1

ECX has dedicated counter instructions

2

loop target:

  • decrement ECX
  • jump if the new value is nonzero
  • target must fit a short displacement

3

sum 1000 dwords:

  • ECX = 1000; ESI = array; EAX = 0
  • add [ESI] to EAX; advance ESI by 4; loop

4

dec register / jnz can implement a similar countdown

  • loop has a smaller encoding, but is not necessarily faster
  • loop preserves flags; dec changes arithmetic flags except CF

5

one-register array traversal:

  • start ECX at 1000
  • add [array+4*ecx-4]
  • visits indices 999 down to 0
  • assembler combines array-4 into one constant displacement

6

jecxz / jcxz test ECX / CX directly, without flags

  • short jumps only
  • guard a counted loop when initial count may be zero
  • otherwise first loop decrement wraps zero to ffffffff

loope/loopz:

  • decrement ECX, then jump if ECX != 0 and ZF = 1

loopne/loopnz:

  • decrement ECX, then jump if ECX != 0 and ZF = 0
  • decrement happens regardless of ZF
Section test (1 file) - 3.2.11: ECX and counted loops
Section test11 (03-02)In catalog
loopne.asmAssembly / 13 lines
%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

Bitwise operations

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
Detailed notes - 3.2.12: Bitwise operations

1

register/memory contents can represent independent bits instead of integers

2

and / or / xor combine corresponding bits

  • result replaces first operand; ordinary two-operand restrictions apply
  • set ZF/SF/PF from result; clear CF/OF

not inverts every bit of its one operand

  • unlike and/or/xor, not leaves flags unchanged

3

useful identities:

  • xor eax,eax clears EAX with a compact instruction
  • not of zero produces all ones
  • unsigned x AND (2^n-1) = x modulo 2^n
  • and eax,3 -> remainder modulo 4

4

test performs AND for flags without storing a result

  • test eax,eax checks for zero
  • test value,mask checks whether any masked bit is set

5

shl / shr destination, count:

  • count is immediate or CL; no other register may supply it
  • i386 uses only the low five count bits
  • memory destination needs a size qualifier

6

logical one-bit shift:

  • shl: highest bit -> CF; insert zero at low end
  • shr: lowest bit -> CF; insert zero at high end

7

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

  • rounds negative results toward minus infinity
  • therefore differs from idiv's rounding toward zero for negative odd values

8

shifts can avoid accumulator setup and expensive

multiplication/division

  • valid substitution still depends on signedness and rounding

9

other bit instructions mentioned:

  • shld/shrd: double-width shifts
  • rol/ror: rotations; rcl/rcr: rotate through carry
  • bt/bts/btr/btc: test or alter a bit
  • bsf/bsr: locate a set bit

10

bitset represents a subset of a finite universe

  • one bit per possible element: 1 = present, 0 = absent
  • 512 possible elements need 512 bits / 64 bytes

11

store the set as 16 dwords

  • object X belongs to word X/32, bit X mod 32
  • X >> 5 gives word index; X AND 31 gives bit index
  • object 37 -> word 1, bit 5; object 510 -> word 15, bit 30

packing index results for 0 <= X < 512:

  • shl ebx,3; shr bl,3 leaves word index in BH and bit index in BL

clear the set:

  • EAX = 0; ECX = 16
  • store EAX at [set512+4*ecx-4], repeat with loop

12

insert X:

  • CL = X AND 31
  • mask = 1 << CL
  • EDX = X >> 5
  • OR mask into [set512+4*edx]

remove X:

  • invert the mask; AND it into the same word

test membership:

  • TEST the word with the one-bit mask
  • ZF = 1: absent; ZF = 0: present

count present elements:

  • EBX = total, initially 0; ECX = word index, initially 15
  • load word into EAX
  • test lowest bit; increment EBX when set; shift EAX right
  • repeat inner loop until EAX = 0
  • jecxz finishes after word 0; otherwise decrement index and repeat

String operations

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
Detailed notes - 3.2.13: String instructions

1

string instructions operate on contiguous memory

  • ESI: source; EDI: destination
  • AL/AX/EAX: implicit byte/word/dword accumulator
  • addresses advance by the element size after each operation

2

DF controls direction

  • cld -> increasing addresses
  • std -> decreasing addresses

3

stosb/stosw/stosd: accumulator -> [EDI], then adjust EDI

  • clear AL, set EDI to buffer, repeat stosb to zero byte storage

lodsb/lodsw/lodsd: [ESI] -> accumulator, then adjust ESI

  • lodsd plus add ebx,eax can sum dwords

combine lodsd / inc eax / stosd to increment every array element movsb/movsw/movsd: [ESI] -> [EDI], then adjust both pointers

4

rep stosX / rep movsX:

  • repeat ECX times, decrementing ECX
  • initial ECX = 0 performs no operation
  • rep stosb replaces an explicit zero-fill loop

5

rep applies to one instruction, not to a whole lods/process/stos sequence

copy buffer:

  • set ESI, EDI, ECX and DF; use rep movsb

overlapping copy:

  • when moving data to higher overlapping addresses, copy backwards
  • otherwise early writes destroy bytes still needed as input

insert "long " before "string":

  • set DF; move the six bytes of "string" five places right, starting at the end
  • EDI then points at the last insertion position
  • copy the five inserted bytes backwards from their source too

6

scasb/scasw/scasd:

  • compare accumulator with [EDI]; set comparison flags; adjust EDI

cmpsb/cmpsw/cmpsd:

  • compare [ESI] with [EDI]; set flags; adjust both pointers

7

repe/repz: continue while count remains and comparison is equal repne/repnz: continue while count remains and comparison is unequal

8

rep and repe share an encoding

  • instruction determines whether ZF matters
  • repne has a separate encoding

9

find 'a' in a nonempty bounded buffer:

  • AL = 'a'; EDI = start; ECX = length; cld
  • repne scasb stops on match or exhausted count
  • test ZF afterwards to distinguish those cases
  • handle a zero initial length separately because no comparison then sets ZF

10

pointer/count updates also occur on the final comparison

  • after a forward successful scan, EDI points one byte past the match
A forward overlapping copy destroys unread input; backward order preserves it.
Copy backward when the destination overlaps above. Open full size - Editable SVG

Stack, subroutine, recursion

Stack and Its Purpose

When calling a subroutine, stack is mainly used to

Cannot use static memory because of recursion.

Detailed notes - 3.3.1: The stack and its purpose

1

stack = last in, first out

  • push adds; pop removes the most recently added value

hardware stack:

  • contiguous memory with a stack-pointer register
  • on i386, occupied space extends from current top toward higher addresses
  • push moves top toward lower addresses; pop moves it back

2

growth direction is architecture-dependent

  • downward growth is common, but not universal

3

uses:

  • temporary register saves
  • return addresses
  • subroutine parameters and local variables
  • separate storage for each recursive invocation

Stack in i386 processor

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
Detailed notes - 3.3.2: The i386 stack

1

push/pop support words and dwords, not individual bytes

  • use dwords in these 32-bit examples to preserve alignment

2

ESP points to the most recently pushed value

  • decreases on push; increases on pop

3

push source:

  • register, memory or immediate

pop destination:

  • register or memory
  • use explicit word/dword size when required

4

[esp] accesses the current top without removing it

  • mov eax,[esp] copies the top dword but does not change ESP

5

other occupied stack locations are ordinary memory too

  • do not store live data below ESP in these i386 programs
  • asynchronous signal handling can use that unreserved space

6

push eax / pop eax preserve a value across temporary register use

string reversal example:

  • input ESI points at a zero-terminated string
  • push its characters, then pop them back into the string
  • terminating zero stays in place

7

first pass:

  • clear EBX and ECX
  • read [ESI+ECX] into BL
  • stop at zero; otherwise push EBX and increment ECX
  • each character occupies one stack dword
  • ECX becomes the string length

8

second pass:

  • jecxz skips an empty string
  • EDI starts at ESI
  • pop EBX; store BL through EDI; increment EDI
  • loop exactly ECX times
  • LIFO order reverses characters and restores the original stack depth
Detailed notes - 3.3.3: More stack instructions

1

pushad saves EAX, ECX, EDX, EBX, original ESP, EBP, ESI, EDI popad restores in reverse order

  • skips the saved ESP slot instead of loading ESP from it

2

pushfd / popfd save and restore EFLAGS

  • user mode cannot thereby change protected flag bits

3

16-bit counterparts: pushaw/popaw and pushfw/popfw

  • historical compatibility forms
  • avoid mixing two-byte stack entries into these dword-based frames

Calling subroutines

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
Detailed notes - 3.3.4: Subroutine principles

1

subroutine call temporarily transfers control

  • subroutine later returns to the instruction following the call

2

each call needs storage for return address, parameters and local variables

  • one fixed storage area per subroutine would suffice only without overlapping calls

3

recursion requires a fresh instance for every active call

  • later calls finish first -> natural LIFO lifetime

4

stack frame contains information belonging to one invocation

  • caller places parameters
  • call saves return address
  • callee reserves local storage
Detailed notes - 3.3.5: Calling and returning

1

call saves the following instruction's address on the stack, then transfers control

  • direct label, register target or target read from memory
  • direct form uses a relative displacement
  • these examples use near calls; no short-call form

2

ret pops the return address into EIP

  • before ret, ESP must again point at that address

3

fill_memory example uses register parameters

  • EDI = buffer; ECX = byte count; AL = fill byte
  • jecxz returns immediately for zero length
  • store AL, advance EDI, repeat with loop, then ret

caller sets EDI=my_array, ECX=256, AL='@' and calls the routine

  • routine changes EDI and ECX; this simple interface explicitly relies on that
Arguments, return address, saved frame pointer and locals occupy fixed offsets in an i386 frame.
EBP anchors one invocation while ESP moves. Open full size - Editable SVG

Stack frame

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
Detailed notes - 3.3.6: Stack frames

1

register parameters alone become inconvenient in larger routines

  • limited registers; parameters may stay live for a long time
  • nested calls need the same registers

2

stack parameters and locals keep each invocation's data together

  • on entry: [ESP] = return address
  • first nearby argument slot is [ESP+4]
  • local space must be reserved below the entry ESP before use

3

ESP changes during pushes and nested calls

  • a stable frame pointer gives fixed offsets to arguments and locals

4

callee preserves the caller's EBP

prologue:

  • push ebp
  • mov ebp,esp
  • sub esp,N to reserve N local bytes

frame layout:

  • [EBP]: saved EBP
  • [EBP+4]: return address
  • [EBP+8], [EBP+12], ...: argument slots
  • [EBP-4], [EBP-8], ...: local dwords

5

epilogue reverses frame setup

  • mov esp,ebp discards local storage
  • pop ebp restores caller's frame pointer
  • ret consumes return address

enter N,0 / leave offer special frame-management instructions

  • book favors explicit instructions; performance depends on processor and instruction

6

Unix creates the initial stack and supplies backing memory as it grows

  • growth still has configured limits
  • book's 8 MB example is a historical/common limit, not a universal fixed size

Passing parameters and returning values

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, EDX are modified by arithmetic, ECX is used as counter. By convention, all three can be overwritten in subroutines.

Detailed notes - 3.3.7: Calling conventions

1

calling convention settles choices that the CPU does not decide

  • parameter order, cleanup and returned values

2

classic Pascal convention: push parameters left to right

  • last parameter is nearest the return address
  • first parameter's offset depends on total parameter count
  • fixed-arity routines fit this arrangement

3

classic i386 C convention: push parameters right to left

  • first parameter always at [EBP+8] with the standard prologue
  • later fixed offsets permit variadic interfaces
  • argument-count knowledge comes from the interface, e.g. format string

4

stack cleanup:

  • Pascal-style fixed arguments: callee can discard them
  • C-style: caller discards its own arguments

C example with three dwords:

  • push a3, a2, a1; call proc1; add esp,12

ret 12:

  • pops return address, then discards another 12 argument bytes
  • immediate operand specifies byte count, not number of arguments

5

returned values in the conventions discussed:

  • small integer: EAX
  • 64-bit integer: EDX:EAX
  • floating point: top arithmetic-coprocessor register
  • larger aggregate may use caller-provided memory and a hidden pointer argument

Local labels

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
Detailed notes - 3.3.8: Local labels

1

subroutine internals should not require remembering other routines' label names

2

NASM local label starts with a dot

  • belongs to the preceding nonlocal label
  • first_proc's .cycle and second_proc's .cycle do not conflict
  • begin each routine with a nonlocal label; use local labels inside it

3

NASM effectively expands .cycle into first_proc.cycle

  • avoid manually chosen dotted names that collide with this mechanism

Example: Comparing a string with pattern

Given a null-terminated string and pattern (with ? and *), print yes if match, no otherwise.

Show the solution
%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
Detailed notes - 3.3.9: Example: pattern matching

1

recursive example: match a string against a wildcard pattern

2

both inputs are zero-terminated strings

  • '?' matches exactly one arbitrary character
  • '*' matches an arbitrary substring, including empty
  • other characters match themselves
  • entire string must match; return 0 or 1

3

each invocation handles remaining suffixes

  • already-consumed prefixes are assumed matched

4

empty pattern matches only an empty string

5

non-star pattern character:

  • input must be nonempty
  • accept '?' or an equal literal
  • advance both pointers and continue; otherwise return false

6

star case:

  • try assigning 0,1,2,... input characters to '*'
  • recursively match remaining input against pattern after '*'
  • return true as soon as one alternative succeeds
  • after failure, stop only when no longer input suffix remains

7

zero termination permits two pointer arguments

  • earlier Pascal representation needed additional indices

8

match frame/register layout:

  • [EBP+8]: string pointer -> ESI
  • [EBP+12]: pattern pointer -> EDI
  • [EBP-4]: local alternative length I
  • EAX: scratch and Boolean result

9

advance a string suffix by incrementing its pointer

  • no copying of character data is required

10

recursive calls share physical CPU registers

  • each invocation must protect values needed after nested calls

11

register-saving convention balances caller and callee work

  • saving every register at every call wastes work
  • letting every routine destroy all registers burdens every caller

12

i386 CDECL convention used here:

  • EAX, ECX, EDX may be overwritten by the callee
  • EBX, ESI, EDI, EBP must be preserved when used
  • EAX is both frequently needed scratch space and result register

13

match saves EBP, ESI and EDI

  • EAX intentionally changes to return the result
  • choosing ECX/EDX instead would still require saves around recursion

14

implementation:

  • build frame; reserve I; push ESI and EDI
  • ordinary matching advances pointers in a loop, avoiding unnecessary recursive calls
  • star loop pushes pattern+1, then string+I, calls match, removes 8 argument bytes
  • EAX != 0 -> success
  • on failure EAX is zero, so adding I produces the index for the end-of-string check
  • increment local I and try next suffix when possible
  • common exits set EAX to 1/0
  • restore EDI/ESI, discard frame, restore EBP, return

caller pushes pattern then string and removes both arguments afterwards

15

long conditional branch to .false needs a near form when short range is exceeded

Examples & tests (2 files) - 3.3.9: Example: pattern matching
Book exampleBook example: match.asmIn catalog
match.asmAssembly / 132 lines
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
Section test09 (03-03)In catalog
match.asmAssembly / 102 lines
%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

NASM features

Detailed notes - 3.4: NASM features

1

earlier examples introduced only the NASM features needed at each step

  • includes, storage directives and local labels

2

now examine command-line options and syntax systematically

  • macro processing follows in its own chapter

CLI parameters

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
Detailed notes - 3.4.1: Command-line options

1

nasm takes a source filename and options

  • -f selects output format; book uses elf for i386 object files
  • raw binary output lacks the OS executable structure
  • raw output can be appropriate for boot-sector code

2

-o selects output filename

  • usual ELF default replaces .asm with .o

3

-d defines a preprocessor symbol from the command line

  • -dSYMBOL corresponds to %define SYMBOL
  • -dSIZE=1024 supplies a value too

4

-l filename creates an assembly listing

  • source, offsets and generated bytes can be compared
  • nasm -f elf -l prog.lst prog.asm

5

-g includes debugging information

  • allows debugger to relate instructions to source
  • increases file contents without changing the program's algorithm

6

-e performs preprocessing only

  • writes expanded source to standard output
  • useful when diagnosing a macro's generated text

7

NASM has further options documented in its reference manual

Syntax

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 ;
Detailed notes - 3.4.2: Syntax

1

logical source line is the basic syntax unit

2

backslash at the end of a physical line joins the following line

  • permits readable source without exceeding the preferred line width

3

line fields: label, instruction, operands, comment

  • optional fields may be absent
  • operands must match the instruction when one is present
  • empty lines are ignored by the assembler but help readability

4

label names:

  • letters, digits and permitted punctuation
  • cannot start with a digit
  • initial dot makes a local label
  • names are case-sensitive
  • $ prefix can disambiguate an external symbol that resembles a keyword
  • colon is optional; conventional on code labels

5

instruction field can contain:

  • machine mnemonic, possibly with prefix
  • pseudo-instruction
  • multiline macro name

machine mnemonics are case-insensitive; user macro names normally are not

6

multiple operands are comma-separated

  • register names are case-insensitive

7

general rule:

  • NASM's own words ignore case
  • programmer-defined names distinguish case

8

memory operands always use square brackets

9

semicolon starts a comment extending to the end of the line

Pseudo-instructions

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
Detailed notes - 3.4.3: Pseudo-instructions

1

pseudo-instructions look like instructions but direct assembly work

  • db/dw/dd and resb/resw/resd allocate data
  • dq/resq: 8-byte items; dt/rest: 10-byte items
  • dd/dq/dt can encode 4/8/10-byte floating-point values

2

name equ expression binds a label to an explicit constant

  • four equ 4 reserves no storage
  • using four substitutes the number 4

3

$ means the current assembly position

  • msglen equ $-msg computes bytes emitted since msg
  • includes explicitly stored newline/zero bytes in the example

4

times N repeats the following instruction or pseudo-instruction

  • stars times 4096 db '*' emits 4096 initialized bytes

5

incbin includes external binary-file contents in the memory image

Constants

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
Detailed notes - 3.4.4: Constants

1

constant categories: integers, characters, strings and floating-point values

2

integer notation supports decimal, binary, octal and hexadecimal

3

short quoted character sequences can act as integer constants

  • in the book's 32-bit examples, up to four characters fit a dword
  • longer sequences are strings
  • choose single or double quotes to include the other quote character

4

i386 integer byte order is little-endian

  • 'abcd' as an integer corresponds to 64636261h
  • storing it puts 'a' first in memory
  • shorter numeric character constants have zero upper bytes
  • context such as db may treat the same quoted text as a byte string

5

floating-point constants have a different bit representation from integers

  • 1 differs from 1.0
  • single-precision 1.0 has bits 3f800000h
  • exponential notation example: 1.0e-5
  • use an explicit decimal point in the syntax discussed here

Evaluation of expressions at assembly time

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
Detailed notes - 3.4.5: Assembly-time expressions

1

assembler can evaluate an expression before program execution

  • generated code contains the result, not instructions performing that calculation
  • necessary values must be known at assembly time

2

integer expression operations:

  • +, -, *
  • / and %: unsigned division/remainder
  • // and %%: signed division/remainder
  • &, |, ^: bitwise AND/OR/XOR
  • <<, >>: shifts; unary ~: complement
  • unary + and -: retain/change sign
  • whitespace after remainder operators avoids confusion with macro syntax

3

seg operator is irrelevant to these flat-model examples

4

precedence, highest first:

  • unary; multiplication/division/remainder; addition/subtraction
  • shifts; AND; XOR; OR
  • parentheses override the order

Critical expressions

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:

Detailed notes - 3.4.6: Critical expressions

1

two-pass model of assembly:

  • first determine sizes and label values
  • then generate bytes with resolved operands
  • permits ordinary forward references

2

forward references become problematic when they determine layout itself

  • times (label-$) db 0 followed by label leaves its own size undetermined

3

critical expression = value required when establishing layout

  • constants and already-defined values can be used
  • later unresolved labels cannot determine earlier storage sizes

4

examples: times counts and resb/resw sizes

instruction encodings can also depend on displacement width

  • [ebx], [ebx+10], [ebx+10000] need different sizes
  • explicit displacement width fixes the encoding even before value resolution
  • mov eax,[ebx+dword label] requests the long displacement form

Macro processor

Basic concepts

%include "stud_io.inc"          ; replaced with file content
Detailed notes - 3.5.1: Basic concepts

1

macro processor transforms source text into new source text

  • assembler subsequently translates the resulting ordinary source

2

powerful macros compensate for assembly language's limited expressive syntax

  • NASM's preprocessor can perform substantial source generation

3

macro = transformation rule associated with a macro name

  • PRINT and FINISH are earlier examples

4

macro definition establishes the name and replacement rule macro call supplies name and arguments

macro expansion substitutes generated text

5

expansion need not make the text longer

  • a macro may generate a shorter fragment or nothing

6

macro directives can act without a macro call

  • %include replaces itself with a file's contents

A macro call expands to push, call and cleanup instructions; the CPU runs the resulting instructions.
Macro expansion happens before program execution. Open full size - Editable SVG

Simple examples of macros

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
Detailed notes - 3.5.2: Simple macro examples

1

pcallN abbreviates a C-style subroutine call

  • macro arguments: procedure name, then its parameters
  • %macro pcall1 2 ... %endmacro defines a two-argument multiline macro
  • %1 = procedure name; %2 = first procedure argument
  • expansion: push argument, call procedure, add esp,4

pcall2 / pcall3:

  • push parameters in reverse order
  • remove 8 / 12 argument bytes after call
  • pcall0 expands to call alone for uniform notation

%0 is the number of macro arguments

2

single-line macros can replace part of an instruction

  • %define arg1 ebp+8
  • %define arg(n) ebp+(4*n)+4
  • %define local(n) ebp-(4*n)
  • assumes every parameter/local occupies four bytes

keep brackets visible at use: mov eax,[arg1]

  • hiding brackets inside the macro obscures whether an operand accesses memory

Single-line macros and macro variables

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
Detailed notes - 3.5.3: Single-line macros and macro variables

1

single-line macros can be redefined

  • later source uses the most recent definition
  • %undef removes a definition

2

%define expands nested macro names when the outer macro is used

  • nested definitions may change between definition and use

3

example: mkvar expands to dd thenumber

  • thenumber=25 -> first use emits dd 25
  • redefine thenumber=36 -> later use emits dd 36

%xdefine expands nested names immediately

  • freezes dd 25 at definition time
  • later changes to thenumber do not affect that saved replacement

4

%assign evaluates an integer expression immediately

  • %assign var 25 followed by %assign var var+1 -> 26
  • unsuitable expressions produce an error

5

%assign names are macro variables

  • hold state for a program that generates assembly source

Conditional compilation

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
Detailed notes - 3.5.4: Conditional compilation

1

one source can produce program variants

  • avoids maintaining duplicate almost-identical source trees

2

NASM implements conditional assembly through its preprocessor

  • useful for optional debugging output

3

%ifdef DEBUG_PRINT ... %endif:

  • retain enclosed source only if DEBUG_PRINT is defined
  • remove its definition to omit diagnostic code

4

command-line -dDEBUG_PRINT enables the same code without editing source

5

%elifdef and %else choose alternative configurations

  • %error reports an unsupported/missing selection
  • example selects FOR_PETROV or FOR_SIDOROV

6

%ifndef tests absence; %elifndef supplies the corresponding alternative branch

7

%if evaluates a compile-time condition

  • comparisons: =/==, !=/<>, <, >, <=, >=
  • logical &&, ||, ^^
  • values must be known during preprocessing
  • %elif supplies another condition

8

other tests:

  • %ifidn: exact token/string comparison after expansion
  • %ifidni: ignore case
  • %ifmacro: multiline macro exists
  • %ifid / %ifstr / %ifnum: argument kind
  • corresponding negated and %elif forms are available

9

%ifctx checks preprocessor context; outside this introduction

Macro repetitions

%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
Detailed notes - 3.5.5: Macro repetition

1

%rep N ... %endrep processes its body N times at preprocessing time

  • %exitrep stops early
  • generates repeated source, not a runtime loop

2

generate initialized bytes 50 through 149:

  • %assign n 50
  • repeat 100 times: emit db n; assign n=n+1

3

generate a Fibonacci-like table bounded by 100000:

  • maintain i and j; stop before emitting j when it exceeds the limit
  • emit dd j; update k=j+i, i=j, j=k
  • fib_count equ ($-fibonacci)/4 counts emitted dwords
  • as printed, initialization i=j=1 emits 1,2,3,...; emit an extra initial 1 for the usual 1,1,2,... sequence

4

macro repetition can generate instructions too

  • 128 inc word [array+a] instructions, increasing a by 2 each time
  • explicit runtime loop needs much less code space
  • unrolling trades code size for reduced loop-control work

Multi-line macros and local labels

%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
Detailed notes - 3.5.6: Multiline macros and local labels

1

a normal label inside a macro is duplicated on every expansion

  • two zeromem calls would define lp twice

2

%%lp is a macro-local label

  • each expansion receives a unique generated name
  • references within that expansion remain consistent

3

macro arguments may refer to registers its expansion overwrites

  • zeromem ecx,eax with mov ecx,eax; mov eax,ecx loses the original address

4

preserve both argument values before assigning working registers

  • push length; push address; pop eax; pop ecx
  • then use %%lp for the byte-clearing loop
  • the printed loop still requires a positive length; add a zero-count guard if allowing empty regions
  • stack-relative arguments need care because pushes change ESP

Macros with a variable number of parameters

%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
Detailed notes - 3.5.7: Variable-argument macros

1

%macro mymacro 1-3 accepts one through three arguments %macro mymacro 2-* accepts two or more

  • %0 contains actual argument count

2

%rotate 1 cyclically changes argument positions

  • former %2 becomes %1; former %1 moves to the end
  • %0 remains unchanged

3

%rotate -1 rotates the other way

  • last argument becomes %1

4

general pcall macro:

  • first argument = procedure; remaining arguments = dword parameters
  • repeat %0-1 times: rotate -1, emit push dword %1
  • rotate once more to recover procedure name
  • emit call %1; add esp,(%0-1)*4

pcall myproc,eax,myvar,27 expands to:

  • push 27, myvar, eax in that order
  • call myproc
  • remove 12 parameter bytes

Macro directives for string manipulation

%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.

Detailed notes - 3.5.8: String macro directives

1

preprocessor can inspect literal strings when generating source

2

%strlen sl 'my string' assigns 9 to macro variable sl

3

%substr extracts characters using one-based positions in these examples

  • 'abcd',1 -> 'a'; position 2 -> 'b'; position 3 -> 'c'
  • especially useful with macro arguments

4

all such work happens before assembly and execution

  • it cannot examine a string that will only exist at runtime

Interaction with the operating system

Detailed notes - 3.6: Interaction with the operating system

1

direct system calls replace the temporary stud_io.inc macros

2

understanding the i386 interface first requires:

  • multitasking and hardware support
  • interrupts, exceptions and controlled kernel entry
  • then Linux and FreeBSD calling conventions

FreeBSD syscall convention

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.

Detailed notes - 3.6.6: FreeBSD syscall convention

1

historical FreeBSD i386 int 80h interface:

  • EAX = syscall number
  • arguments pushed right to left
  • EAX = result; CF clear indicates success
  • CF set indicates error code in EAX

2

kernel expects the stack layout produced by calling a small wrapper

  • stack top contains wrapper return address
  • first real argument at [ESP+4], then [ESP+8], ...

3

direct int 80h can supply a dummy dword instead of a wrapper return address

  • afterwards discard dummy plus all argument bytes

4

Hello example:

  • push length, message pointer, stdout descriptor, dummy
  • EAX=4; int 80h; discard 16 bytes
  • push exit status and dummy; EAX=1; int 80h
  • _exit does not return, so no later cleanup is needed

test CF before an instruction such as add destroys it

  • ignored write failures are a simplification of the example

Multitasking and its main types

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
Detailed notes - 3.6.1: Multitasking and its main types

1

one CPU can support multitasking by switching between programs

2

tasks execute concurrently when their start-to-finish intervals overlap

3

at any instant one CPU executes one task, but several tasks can remain in progress

4

I/O is much slower than CPU computation

  • waiting for disk mechanics/controller completion can waste CPU time

5

multitasking uses that waiting time for other tasks

  • OS starts or queues requested I/O
  • requester becomes blocked
  • another ready task receives the CPU

6

batch scheduling in the book's model:

  • current task runs until termination or blocking
  • completed I/O makes a task ready, without immediately switching to it
  • reduces switching overhead for long numerical work

7

interactive work needs prompt responses

  • a user should not wait for another task's entire computation

8

time sharing:

  • tasks receive time slices
  • expiry can preempt the current task in favor of another ready task
  • preempted task returns to the ready queue
  • blocked tasks receive no CPU slices until their blocking cause disappears

9

priority example:

  • static priority expresses assigned importance
  • dynamic priority rises while ready/waiting and falls while running
  • scheduler chooses highest combined priority

10

non-preemptive / cooperative historical systems:

  • switch only when the program enters the OS or yields
  • long computation or infinite loop can prevent other programs running

11

some applications require completion by an external deadline

  • delayed control output can be useless even if eventually correct

12

real-time scheduling focuses on predictable completion

  • meeting deadlines matters more than aggregate throughput
  • needs specialized scheduling analysis

Clarification. The priority formula is an illustrative scheduling policy. Batch systems need not be non-preemptive, and scheduler policies differ between operating systems.

Overlapping task lifetimes.

I/O creates waiting periods.

Another task can use the CPU during I/O.

Time sharing alternates tasks through time slices.

Hardware support for multitasking

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
Detailed notes - 3.6.2: Hardware support for multitasking

1

essential starting points: memory protection and CPU privilege modes

2

memory protection isolates programs from accidental or deliberate corruption

  • software-only checking of native instructions would be impractical

3

protection settings and direct device access must themselves be protected

  • otherwise a task could disable restrictions or conflict with other tasks

4

kernel / supervisor mode: all relevant instructions available user / restricted mode: cannot perform privileged system-wide actions

5

user tasks modify their permitted memory and request other work from the OS

  • privilege separation alone is not all the required hardware support

6

busy waiting repeatedly polls a device controller

  • consumes CPU time without doing useful computation

7

when another task runs during I/O, OS still needs notification of completion

  • may need to transfer data, update task state or start queued I/O

8

hardware interrupt:

  • device requests attention
  • CPU transfers control to OS interrupt handler
  • interrupted execution can resume after handling

9

timer interrupts give the scheduler regular opportunities to run

  • needed for enforcing time slices and deadlines

10

hardware requirements:

  • interrupts
  • memory protection
  • privileged and user modes
  • timer for preemption/time tracking
  • only the timer is a separate device in this simplified list

11

timer-only polling of all other devices is possible in principle

  • generally wastes work and complicates timely response

Interrupts and exceptions

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.

Detailed notes - 3.6.3: Interrupts and exceptions

1

interrupt terminology covers mechanisms with different causes

2

hardware interrupt originates outside the CPU

  • notifies it that an independently operating device needs service

3

simplified interrupt sequence:

  • device raises request
  • CPU reaches a resumable point and acknowledges
  • interrupt vector identifies the handler
  • CPU saves instruction pointer and flags
  • switches privilege as required and enters the OS handler
  • handler saves any additional registers it uses

ordinary user instructions cannot simply enable privileged execution

4

timer repeatedly generates interrupt requests at configured intervals

5

integer division by zero cannot produce a valid integer result

  • normal instruction execution cannot simply continue with meaningful data

6

CPU reports exceptional situations to OS

  • division error, invalid instruction, protection violation
  • saves enough execution state for handling/diagnosis
  • OS decides how to treat the responsible task

7

exceptions arise inside instruction execution

  • no external request/acknowledgement exchange is needed
  • handler-entry mechanism resembles interrupts

8

exception handling has a responsible task and runs in its context

  • task may be suspended and later resumed
  • external interrupt need not belong to the interrupted task

9

i386 Interrupt Descriptor Table:

  • 256 numbered entries, 8 bytes each
  • entry identifies handler address/segment and entry behavior
  • configuring handler entry points is privileged

10

x86 terminology sometimes calls exceptions internal interrupts

  • other architectures commonly retain the word exception/trap

11

exception is caused by the task's own execution

  • unlike an asynchronous hardware interruption
  • common handler machinery does not make their execution contexts identical
event -> save execution state -> enter kernel handler -> resolve event -> resume or stop task

System calls and "software interrupts"

int 0x80    ; traditional Linux i386 syscall entry
Detailed notes - 3.6.4: System calls and software interrupts

1

system call = request from a user task to the kernel for a service

  • cannot be an arbitrary jump into kernel memory

2

CPU must change privilege and enter an OS-defined handler

  • architectures provide mechanisms such as trap, svc or syscall

3

i386 example uses int to enter an interrupt-table handler

  • user mode can invoke only entries configured to permit it

4

three causes in the terminology used here:

  • hardware interrupt: external device
  • exception: instruction execution
  • software interrupt: explicit instruction, used here for a syscall

5

software-interrupt name describes the mechanism

  • task deliberately requests the service

6

privilege increase and entry into a predefined handler are inseparable

  • only privileged code configures those entry points
  • user code cannot continue arbitrarily with kernel privileges

7

syscall numbers, arguments and results depend on OS and architecture

  • Linux/i386 and FreeBSD/i386 differ despite using the same CPU

8

C libraries provide ordinary function wrappers

  • wrapper hides syscall number and machine-level calling sequence
  • same function name can map to different syscall numbers

9

direct assembly must supply OS-specific numbers and constants

  • conditional assembly can select the correct implementation
The historical Linux i386 int 80h ABI carries a write request into a privileged handler and returns a result.
A syscall enters through an OS-defined gate. Open full size - Editable SVG

Linux OS system call convention

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.

Detailed notes - 3.6.5: Linux syscall convention

1

historical Linux i386 int 80h interface:

  • EAX = syscall number
  • arguments in EBX, ECX, EDX, ESI, EDI, EBP
  • EAX returns result or negative errno on failure
  • raw errors occupy the high unsigned range; ordinary wrappers translate them

2

write is syscall 4

  • arguments: descriptor, data address, byte count

3

write to standard output:

  • EAX=4; EBX=1; ECX=message address; EDX=message length
  • execute int 80h

4

_exit is syscall 1

  • EBX supplies exit status
  • convention: 0 success; nonzero failure

5

Hello example:

  • message includes newline; length calculated with $-msg
  • perform write, then _exit(0)
  • no stud_io.inc required

6

some system calls involve wider/special argument arrangements

  • general register summary does not replace each syscall's specific interface

Examples of system calls

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
Detailed notes - 3.6.7: System-call examples

1

_exit(1) terminates; write(4) sends buffer bytes to a descriptor

2

read(3): descriptor, destination buffer, maximum byte count

  • standard input normally uses descriptor 0
  • buffer must be large enough
  • successful result is actual bytes read, which may be fewer than requested

3

read returning zero for a nonzero request means end of input

  • terminal Ctrl-D can indicate EOF

4

always inspect read's result

  • only the returned number of buffer bytes contains newly read data

5

check error convention after every fallible call

  • Linux: negative errno in EAX
  • FreeBSD: CF and EAX

6

usual initial descriptors:

  • 0 stdin; 1 stdout; 2 stderr

open(5) creates a new descriptor

  • pathname is zero-terminated
  • flags select access mode and creation/truncation behavior
  • creation mode supplies requested permission bits, subject to process umask

i386 examples:

  • O_RDONLY = 0 on both systems
  • write/create/truncate flags: Linux 241h; FreeBSD 601h
  • 666q requests ordinary read/write permissions; 600q restricts them to owner

7

open can fail for reasons outside the program's control

  • check first; on success save returned descriptor for later read/write

8

close(6) releases a descriptor

  • later open may reuse the same number

9

getpid(20) returns current PID

getppid returns parent PID

  • Linux i386 number 64; FreeBSD i386 number 39
  • no arguments; result in EAX

10

kill(37) sends a signal to the selected process

  • SIGTERM=15 requests termination and can be handled
  • SIGKILL=9 cannot be caught or ignored

11

Unix provides many more calls

  • documentation generally describes C interfaces
  • some library services emulate behavior without a single corresponding kernel call
  • assembly examples are for understanding the mechanism

Access to command line parameters

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.

Show the solution
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
Show the complete program
%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
Detailed notes - 3.6.8: Command-line arguments

1

command-line arguments are the same interface already used in Pascal examples

2

initial stack at _start in these i386 examples:

  • [ESP]: argc, including program name
  • [ESP+4]: pointer to argv[0]
  • [ESP+8]: pointer to argv[1], and so on
  • each argument is a separate zero-terminated string

3

argument-printing example supports both OS conventions

  • select OS_LINUX or OS_FREEBSD with -d

strlen helper:

  • one pointer argument through stack
  • count bytes up to zero; return length in EAX
  • uses EAX/ECX and preserves EBP according to CDECL

4

print_str calls strlen, then write

  • save string pointer in EBX across the nested call
  • preserve caller's EBX on entry/return
  • do not rely on strlen accidentally preserving caller-clobbered registers

5

print newline using the same helper and a two-byte string: 10,0

6

more efficient output could collect all text and issue fewer syscalls

  • example favors a short, understandable implementation

7

nlstr can live in .text because it is immutable

8

main loop:

  • EBX = remaining argument count
  • ESI = pointer to current argv slot
  • print [ESI], then newline
  • add ESI,4; decrement EBX; repeat
  • EBX/ESI survive helper calls under CDECL
  • after loop, perform OS-specific _exit(0)
Book example (1 file) - 3.6.8: Command-line arguments
Book exampleBook example: cmdl.asmIn catalog
cmdl.asmAssembly / 76 lines
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

Example: copying a file

Write a program to copy text from one file into another. File names should be given as parameters.

Show the solution
%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
Detailed notes - 3.6.9: Example: copying a file

1

copy source to destination named by two command-line arguments

  • open input for reading and output for writing
  • read at most 4096 bytes; write the bytes actually received
  • repeat until EOF

2

a kernel macro centralizes Linux/FreeBSD differences

  • first macro argument = syscall number
  • remaining arguments = syscall parameters
  • Linux variant permits at most six parameters

3

macro follows the CDECL preservation rule

  • EAX/ECX/EDX may change
  • Linux version saves EBX and, when needed, ESI/EDI/EBP

4

error interfaces differ

  • FreeBSD CF must be tested before flags are changed
  • Linux result must be checked for encoded negative error

5

normalized macro result:

  • success: EAX = result, ECX = 0
  • failure: EAX = -1, ECX = positive error number

6

push argument values before assigning syscall registers

  • avoids overwriting a register that still supplies another argument
  • %rotate pushes all values in reverse order

7

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

  • nested preprocessor conditions select the required registers

8

post-call handling also differs enough to justify separate macro branches

  • name kernel avoids conflicting with the syscall instruction mnemonic

9

indent preprocessor conditions separately from generated machine instructions

  • FreeBSD branch checks CF, normalizes result, discards stack arguments
  • Linux branch recognizes error, normalizes result, restores saved registers
  • macro-local labels prevent collisions between expansions
  • kernel 4,1,msg,msg_len and kernel 1,0 now express Hello and exit

10

openwr_flags depends on selected OS

  • Linux 241h; FreeBSD 601h
  • both mean write/create/truncate in the book's interfaces

.bss storage:

  • buffer: 4096 bytes; bufsize calculated from labels
  • fdsrc/fddest: descriptors
  • argc/argvp: argument count and pointer-vector address

diagnostic messages go to descriptor 2

  • usage error
  • cannot open source
  • cannot open destination

entry setup:

  • pop argc, then save current ESP as argvp
  • require argc=3: program name plus two filenames
  • bad count -> print usage and exit status 1

open source:

  • [argvp] holds vector address; its +4 slot points to source pathname
  • open with O_RDONLY=0
  • failure -> diagnostic and exit 2
  • success -> save EAX in fdsrc

open destination:

  • pathname pointer at vector +8
  • use openwr_flags and requested mode 666q
  • failure -> diagnostic and exit 3
  • success -> save descriptor in fddest

copy loop:

  • read(fdsrc,buffer,bufsize)
  • printed example exits loop when signed EAX <= 0
  • positive EAX supplies exact byte count to write
  • repeat after write
  • example merges read error with EOF and omits short-write/error recovery
  • therefore demonstrates the mechanism, not a complete reliable cp implementation

finish by closing both descriptors and exiting with status 0 internal main-program labels are local to _start

  • reduces accidental conflicts in larger programs

11

complete example is supplied as copy.asm

Book example (1 file) - 3.6.9: Example: copying a file
Book exampleBook example: copy.asmIn catalog
copy.asmAssembly / 154 lines

%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

Separate compilation

Detailed notes - 3.7: Separate compilation

1

compile each module separately, then link object files into an executable

  • rebuild changed modules; reuse unchanged objects
  • linking is normally cheaper than recompiling all source

2

assembly and C toolchains use object-file formats understood by the linker

  • ld can combine any required number of compatible objects

3

module owns its internal namespace

  • global exports selected labels
  • identical private names in different modules need not conflict
  • only exported names form the externally visible interface

4

encapsulation permits changing internal details without breaking callers

  • private symbols need not become part of the public documentation

Module support in NASM

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
Detailed notes - 3.7.1: Module support in NASM

1

global myproc exports a definition from this module

extern myproc declares a definition expected from elsewhere

  • assembler sees only the current module
  • records an external reference for the linker to resolve

Example

Write a program that asks user for his/her name and uses it to greet him/her. Use multiple modules.

Show the solution
;; 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
Detailed notes - 3.7.2: Example

1

greeting program asks for a name and prints a personalized greeting

  • all strings use terminating zero bytes

2

separate modules: putstr, getstr, strlen and quit

  • putstr depends on strlen
  • main module calls putstr/getstr/quit

3

kernel.inc contains the syscall macro

  • included during preprocessing, not linked as an object module
  • macro definitions must be visible when their calls are expanded

4

strlen.asm exports strlen

  • pointer argument through stack; EAX counts until the first zero byte
  • global/extern declarations near the top make interfaces visible

5

putstr.asm exports putstr and imports strlen

  • calls strlen, removes its argument, then uses kernel macro for write
  • string pointer comes from [EBP+8]

getstr accepts buffer address and capacity

  • reads one byte at a time for simplicity
  • avoids a large I/O implementation, but uses many syscalls

6

getstr state:

  • EDX = next output address; ECX = count
  • increment count before capacity test to reserve one byte for terminating zero
  • read byte; stop on EOF/error or newline
  • overwrite newline with zero; EOF writes zero at the unfilled position
  • caller must provide a positive buffer capacity

7

getstr uses caller-clobbered registers

  • save ECX/EDX around kernel macro because both hold loop state
  • read result must equal 1 before inspecting the character
  • place final zero, dismantle frame, return

quit.asm exports quit and invokes _exit(0)

  • no ret is needed after a nonreturning exit syscall

greet.asm:

  • exports _start; imports putstr/getstr/quit
  • initialized zero-terminated message strings in .data
  • 512-byte input buffer in .bss
  • prompt, read name, print greeting prefix/name/suffix, quit
  • caller removes each helper's stack arguments

assemble the five .asm modules separately

  • kernel.inc is not a sixth module

8

OS-selection definition is required where kernel.inc is used

  • passing it consistently to every module simplifies build commands

9

link the five object files with ld

  • select elf_i386 on the book's 64-bit GNU toolchain
  • resulting greet executable prompts and prints the supplied name
Examples & tests (28 files) - 3.7.2: Example
Book exampleBook example: asmcopy/In catalog
asmcopy/copy.asmAssembly / 43 lines
%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
asmcopy/kernel.incAssembly / 90 lines
%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
asmcopy/message.asmAssembly / 31 lines
%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
asmcopy/openf.asmAssembly / 17 lines
%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
asmcopy/transfer.asmAssembly / 24 lines
%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
Book exampleBook example: asmflags/In catalog
asmflags/MakefileMake / 17 lines
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
asmflags/flags.asmAssembly / 81 lines
%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
asmflags/flagshow.asmAssembly / 50 lines

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
asmflags/getstr.asmAssembly / 28 lines
%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
asmflags/hex2num.asmAssembly / 41 lines
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
asmflags/kernel.incAssembly / 90 lines
%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
asmflags/num2hex.asmAssembly / 44 lines
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
asmflags/putstr.asmAssembly / 16 lines
%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
asmflags/quit.asmAssembly / 7 lines
%include "kernel.inc"

global  quit

section .text
quit:
    kernel 1, 0
asmflags/strlen.asmAssembly / 14 lines
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
Book exampleBook example: asmgreet/In catalog
asmgreet/MakefileMake / 16 lines
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
asmgreet/getstr.asmAssembly / 28 lines
%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
asmgreet/greet.asmAssembly / 38 lines
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
asmgreet/kernel.incAssembly / 90 lines
%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
asmgreet/putstr.asmAssembly / 16 lines
%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
asmgreet/quit.asmAssembly / 7 lines
%include "kernel.inc"

global  quit

section .text
quit:
    kernel 1, 0
asmgreet/strlen.asmAssembly / 14 lines
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
Section test02 (03-07)In catalog
getstr.asmAssembly / 32 lines
;; 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.asmAssembly / 43 lines
;; 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
kernel.incAssembly / 39 lines
%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.asmAssembly / 23 lines
;; 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.asmAssembly / 6 lines
;; quit.asm ;;
%include "kernel.inc"
global quit

section .text
quit:   kernel 1, 0
strlen.asmAssembly / 21 lines
;; 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

Object code and machine code

Labels become relative addresses within an object module, then resolved when linking modules into an executable.

Detailed notes - 3.7.3: Object code and machine code

1

object module supplies exported symbols and requests imported symbols

2

assembler cannot know every final address

  • external definitions are elsewhere
  • placement of this module among others is not yet known

3

object file supplies code plus relocation information

  • linker learns where address-dependent values must be filled in or adjusted
  • linker does not need original source or its programming language

4

nm displays object-file symbols

  • useful for inspecting exports and unresolved references

Libraries

# 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.

Detailed notes - 3.7.4: Libraries

1

programs reuse collections of prepared subroutines

  • linker libraries differ from source-only macro libraries

2

static library = archive of object modules with symbol-index information

3

in the model discussed, object module is the unit of inclusion

  • one required function can pull in other code in the same object
  • small, coherent modules reduce unnecessary inclusion

4

ar crs libgreet.a strlen.o getstr.o putstr.o quit.o builds an archive

  • library name greet -> filename libgreet.a
  • link by filename, or use -l greet with -L .
  • -L adds a library search directory

5

library remains a collection of selectable modules

  • linker extracts required members instead of treating archive as one indivisible object

Linker operation algorithm

Avoid using libraries that depend on other libraries!

Linker can fail in 2 cases:

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
Detailed notes - 3.7.5: How the linker works

1

linker receives an ordered list of objects and libraries

  • objects named directly
  • library may be named directly or selected with -l
  • -L adds directories searched for library files

2

two conceptual symbol sets:

  • resolved: definitions already accepted
  • unresolved: referenced symbols without accepted definitions
  • NASM global supplies exports; extern supplies imports

3

book's linking model begins with entry point _start unresolved

for each ordinary object:

  • include its contents
  • add exports to resolved; remove matching unresolved references
  • add imports still lacking a definition to unresolved

4

for each static archive:

  • extract a member if its exports satisfy current unresolved references
  • update both sets
  • repeat within the archive while another member is needed
  • then advance to next command-line input

greet example:

  • main requires getstr/putstr/quit
  • accepting putstr adds requirement for strlen, also extracted

5

principal errors:

  • undefined reference: required symbol remains unresolved at end
  • duplicate definition: conflicting accepted exports share a name

6

ordinary archive search does not automatically return to earlier archives

  • put referring objects before libraries that satisfy them
  • cyclic library dependencies make this simple order insufficient
  • book recommends restructuring or combining tightly coupled libraries

7

dependencies between libraries constrain their order too

  • prefer clear, limited dependencies and coherent library responsibilities

8

linking principles also matter for C/C++ programs

  • affect program size and organization of reusable code

9

ld also supports detailed options and linker scripts

  • scripts can control layout beyond the introductory examples

10

common options:

  • -l: library name; -L: search directory
  • -o: output filename
  • -m: emulation/platform, e.g. elf_i386

11

additional options:

  • -nostdlib: restrict ordinary default library search
  • -e name: choose an entry symbol other than _start
  • -y name: report references/definitions of a selected symbol

12

-static requests static library selection

-s strips symbol/debug information from the result

  • assembly can also include debugger information with nasm -g
Resolving one reference can introduce another dependency while unused archive members remain excluded.
An unresolved symbol pulls in an archive member. Open full size - Editable SVG

Floating-point arithmetic

Detailed notes - 3.8: Floating-point arithmetic

1

floating-point values approximate quantities using finite bits

  • operations introduce rounding error
  • representation and arithmetic differ from integers

2

historical x86 floating-point support used separate 8087/80287/80387 chips

  • later processors integrated the hardware
  • x87 programming model still has its own registers, flags and instructions

Floating-point number formats

Floating-point number:

(-1)s * 2(p-b) * m

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.

Detailed notes - 3.8.1: Floating-point formats

1

ordinary normalized value = (-1)^sign * 2^(exponent-bias) * significand

  • single: 32 bits, 8 exponent bits, bias 127, 23 stored fraction bits
  • double: 64 bits, 11 exponent bits, bias 1023, 52 stored fraction bits
  • extended: 80 bits, 15 exponent bits, bias 16383, 64 significand bits
  • normalized significand is in [1,2)
  • single/double omit the leading 1; extended stores it explicitly

2

exponent patterns of all zeros/all ones encode special cases

  • zero cannot use an ordinary normalized significand
  • these encodings include useful values as well as exceptional results

3

signed zero:

  • zero exponent/significand with sign bit set represents -0
  • tiny negative results can round to -0
  • signed zero also arises from exact operations; it is not necessarily evidence of an error

4

subnormal value:

  • zero exponent field, nonzero fraction, no implicit leading 1
  • effective exponents -126 / -1022 / -16382 for the discussed formats
  • provides gradual underflow below the normal range
  • scaling quantities can help avoid extreme magnitudes in an algorithm

5

author's units example illustrates the enormous available exponent range

  • even very small physical lengths in very large units may remain normal
  • criticism of subnormal support is the author's view

6

all-ones exponent represents infinities or NaNs, depending on significand encoding

  • sign distinguishes positive/negative infinity
  • NaNs represent invalid/unordered results; signaling and quiet forms differ
  • masked exceptions can continue with such values
  • whether an exception traps depends on control-word masks

7

NASM sizes:

  • qword = 8 bytes; tword = 10 bytes
  • dq/dt initialize; resq/rest reserve corresponding elements

8

dd/dq distinguish integer and floating initializers by notation

  • 1000.0 = 1.0e3; 0.001 = 1.0e-3
  • integer 1 and floating 1.0 do not have the same bits

9

x87 registers hold extended-format values

  • loads/stores convert other memory formats
  • control settings can reduce arithmetic significand precision
Tests & experiments (2 files) - 3.8.1: Floating-point formats
Section testFloat representation assembly comparisonIn catalog
test_float.cC / 20 lines
/*
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;
}
test_float.asmAssembly / 40 lines
%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

Arithmetic coprocessor architecture

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
Detailed notes - 3.8.2: Arithmetic-coprocessor organization

1

x87 has eight physical 80-bit data registers organized as a circular stack

  • names ST0 through ST7 are relative to TOP
  • pushing decrements TOP; old ST0 becomes ST1
  • values stay in their physical registers while logical names change
  • pop advances TOP

2

NASM uses ST0, ST1, ...

  • other assemblers/reference texts may write ST(0), ST(1), ...

3

control word, status word and tag word contain flags and small fields

4

status word:

  • TOP in bits 11-13 identifies physical top register
  • C0/C2/C3 hold condition results used like CF/PF/ZF
  • C1 supplies additional operation-specific status

5

status exception bits:

  • IE invalid, DE denormal operand, ZE divide by zero
  • OE overflow, UE underflow, PE inexact/precision
  • SF identifies a stack fault associated with invalid operation

6

summary/busy status records pending exceptional work and coprocessor state

  • mainly relevant to low-level handling and historical asynchronous operation

7

control word:

  • exception-mask value 1 means masked; value 0 means unmasked
  • RC chooses nearest, downward, upward or toward-zero rounding

8

precision-control field selects significand precision for applicable arithmetic

  • 24, 53 or 64 significant bits
  • default initialized x87 state uses extended precision
  • old IC/IEM fields are not used on later processors

9

tag word: two bits per physical register

  • 00 valid; 01 zero; 10 special; 11 empty
  • tracks occupancy and detects stack overflow/underflow

10

instruction/data pointers retain information useful for exception diagnosis

11

x87 mnemonics begin with f

  • operands are stack registers or memory
  • arbitrary immediate floating-point operands are not encoded in instructions

Physical register contents stay in place while logical ST names rotate with TOP.
x87 pushes change TOP, not every stored value. Open full size - Editable SVG

Data exchange with the coprocessor

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
Detailed notes - 3.8.3: Moving data to and from x87

1

fld pushes a floating-point value

  • memory source: dword/qword/tword
  • register source: STn
  • fld st0 duplicates the top
  • fld qword [matrix+ecx*8] pushes one double-precision array element

2

fst stores ST0 without popping; fstp stores then pops

  • fst memory form supports 32/64-bit formats
  • fstp also supports 80-bit memory storage
  • register destination can receive the copied value
  • fstp st0 discards the top value

3

integer conversion:

  • fild loads signed word/dword/qword integer and converts it to x87 format
  • fist rounds ST0 into word/dword integer memory
  • fistp also supports qword and removes the top
  • rounding follows the control word

4

fxch stN exchanges ST0 with another occupied stack register

  • no-operand fxch means exchange with ST1

5

constant-loading instructions push a new value

  • fld1: 1.0; fldz: +0.0; fldpi: pi
  • fldl2e: log2(e); fldl2t: log2(10)
  • fldln2: ln(2); fldlg2: log10(2)
  • rounding mode affects approximations of irrational constants

Arithmetic instructions

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
Detailed notes - 3.8.4: Arithmetic instructions

1

memory-source arithmetic uses ST0 and 32/64-bit floating memory

  • fadd/fmul: add/multiply
  • fsub: ST0-source; fsubr: source-ST0
  • fdiv: ST0/source; fdivr: source/ST0
  • result remains in ST0

2

two-register forms require ST0 as one operand

  • first operand is destination
  • reversed forms reverse arithmetic order, not destination

3

p forms store result in first register, then pop ST0

  • faddp, fsubp, fsubrp, fmulp, fdivp, fdivrp
  • second operand is ST0
  • fsubp st1,st0 leaves old ST1 minus old ST0 at the new top

4

no-operand p form uses ST1 and ST0

  • consume two values, leave one result
  • ordinary subtraction/division uses old ST1 as left operand and old ST0 as right

5

reverse Polish notation evaluates naturally on the register stack

  • (x+y)*(1-z) -> x y + 1 z - *
  • push x/y, faddp; push 1/z, fsubp; fmulp
  • shorter form can use fadd/fsub with memory operands
  • expression depth must fit available stack space or spill intermediate values

6

Dijkstra's conversion uses an auxiliary operator stack

  • scan infix expression from left to right
  • emit operands directly
  • stack holds operators and opening parentheses

7

conversion rules for the left-associative arithmetic discussed:

  • '(' -> push
  • ')' -> emit operators until matching '('; discard that parenthesis
  • operator -> emit preceding operators of equal/higher precedence, then push it
  • at end, emit remaining operators
  • unmatched parentheses are errors

8

example a-b+c*d -> a b - c d * +

  • '+' first releases preceding '-'
  • '*' stays above '+' until the expression ends

mark unary operators distinctly before conversion

  • postfix position alone cannot distinguish unary minus from binary subtraction
  • account for their higher precedence

9

avoid ambiguous assembler-specific no-operand ordinary arithmetic forms

  • explicit register operands state the intended order

10

fiadd/fisub/fisubr/fimul/fidiv/fidivr:

  • combine ST0 with a signed integer memory operand of word/dword size

11

unary operations on ST0:

  • fabs: absolute value
  • fchs: change sign
  • frndint: round to integer value while retaining floating representation

12

fprem/fprem1, fscale and fxtract are mentioned for further study

Instructions for calculating mathematical functions

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.

Detailed notes - 3.8.5: Mathematical functions

1

fsin/fcos/fsqrt replace ST0 with sine/cosine/square root fsincos produces two values

  • cosine in new ST0; sine in ST1
  • stack depth increases by one

2

fptan leaves 1.0 in ST0 and tangent in ST1

  • fdivrp then computes cotangent
  • fstp st0 discards the extra 1 if tangent is wanted

3

fpatan consumes x=ST0 and y=ST1

  • returns quadrant-aware arctangent of y/x, like atan2(y,x)
  • result in new ST0; stack depth decreases by one

4

f2xm1, fyl2x and fyl2xp1 support numerically useful combined operations

5

fyl2x computes y*log2(x), consumes both operands and pushes result

  • load y=1/log2(a) to compute logarithm base a

6

fyl2xp1 computes y*log2(1+x)

  • intended for a limited interval around zero
  • book gives |x| <= 1-sqrt(2)/2

7

useful when 1+x would round to 1 before ordinary logarithm evaluation

  • x itself can remain representable even when adding it to 1 loses all its bits
  • direct combined operation preserves a meaningful small result

8

f2xm1 computes 2^x-1 for -1 <= x <=1

  • small x gives a result near zero
  • computing the difference directly avoids losing it by first rounding 2^x to 1

9

these instructions use implicit stack operands

Comparison and result processing

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):

We 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
Detailed notes - 3.8.6: Comparisons and their results

1

x87 comparison flags must reach the CPU flags before ordinary conditional jumps

2

fcom compares ST0 with memory operand/STn; omitted operand means ST1

  • fcomp also pops ST0
  • fcompp compares ST0/ST1 and pops both

3

ordered comparison status:

  • equal: C3=1, C0=0
  • less: C3=0, C0=1
  • greater: C3=0, C0=0

4

C2 indicates unordered comparison when applicable

  • NaNs are unordered; equal signed infinities compare equal
  • invalid-operation masking determines whether handling traps

5

fstsw ax; sahf transfers status bits

  • C3 -> ZF; C2 -> PF; C0 -> CF
  • use unsigned-integer-style jumps such as ja/jb/jae/jbe
  • this follows flag placement, not unsigned floating-point semantics

6

minimum example:

  • load b, then a -> ST0=a, ST1=b
  • compare and transfer flags
  • if a>b, leave order; otherwise exchange
  • larger value is now ST0; discard it
  • store/pop remaining minimum into m
  • assumes ordered operands

7

ffree st0 plus fincstp can also discard the top

8

ficom/ficomp compare ST0 with signed word/dword integer memory

  • ficomp pops afterwards
  • ftst compares ST0 with zero

Exceptions and their handling

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)
Detailed notes - 3.8.7: Exceptional situations

1

six exception classes may indicate an error or ordinary rounding behavior

2

invalid operation:

  • invalid mathematical operation, e.g. square root of a negative number
  • invalid operand or empty/full stack misuse
  • SF distinguishes stack fault

3

denormal-operand exception concerns a subnormal input

  • includes loading smaller-format subnormal data into the register stack

4

divide-by-zero exception concerns a nonzero finite dividend divided by zero

  • zero divided by zero is invalid operation instead

5

overflow: result too large for destination format

  • can occur when storing extended value to a smaller format

6

underflow: result too tiny for normal representation, with relevant precision loss

  • concerns result rather than an already-subnormal input

7

precision/inexact: exact result does not fit available significand bits

  • normal for many computations

8

control-word mask bits correspond to status exception bits

  • mask clear: exceptional handling can be raised
  • mask set: continue with defined default result/rounding where possible
  • exceptions include different cases; infinity is not the result of every invalid division

9

status flags are sticky

  • record exceptional situations until explicitly cleared
  • masked exceptions can therefore be checked later
  • fclex clears exception status

Delayed Exceptions and the wait Instruction

fimul dword [k]         ; Causes exception
mov [k], ecx            ; CPU overwrites [k] before
                        ;   FPU triggers interrupt!
fsqrt                   ; Interrupt finally fires here,
                        ;   but [k] is lost

Solutions:

  1. Reorder: Move mov [k], ecx after fsqrt.
  2. Use fwait (wait): force pending exceptions to fire now.
fimul dword [k]
fwait           ; Forces interrupt here,
                ;   before [k] is overwritten
mov [k], ecx
Detailed notes - 3.8.8: Exceptions and wait

1

x87 can defer reporting a pending unmasked exception until a later checking instruction

  • modifying a memory operand in between can destroy diagnostic information
  • example: fimul [k], integer store to k, then fsqrt
  • ordering the next x87 check before modifying k avoids that issue

fwait / wait checks pending unmasked x87 exceptions

  • useful after the final possibly exceptional x87 operation

2

some waiting mnemonics represent wait plus a nonwaiting instruction

  • fstsw = wait + fnstsw
  • fclex = wait + fnclex
  • nonwaiting forms need deliberate use because they bypass the preliminary check

Coprocessor control

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
Detailed notes - 3.8.9: Controlling x87

1

control word sets operating modes; status word reports state; tag word tracks registers

2

fstcw/fnstcw store control word to 16-bit memory

fldcw loads it from 16-bit memory

set rounding toward zero:

  • reserve four stack bytes to preserve alignment
  • store control word; set RC bits 10 and 11
  • reload control word; release temporary stack space

fstsw/fnstsw store status to AX or 16-bit memory

  • no simple load-status-word counterpart
  • fincstp/fdecstp adjust TOP without changing register tags
  • changing TOP alone does not push a value or free an occupied register
  • fclex/fnclex clear exception status

3

changing masks can expose an already-pending exception

  • clear/handle outstanding status deliberately before changing control settings

4

ffree STn marks that physical register empty without moving TOP

  • ffree st0; fincstp discards the current top

finit/fninit establish initial x87 state

  • control word 037fh: nearest rounding, extended precision, all exceptions masked
  • status cleared; TOP=0
  • tags mark every register empty, without erasing their raw data bits
  • use only when no live x87 values need preserving

5

fsave/fnsave save complete legacy x87 state

  • 108-byte area in the discussed 32-bit mode
  • saving also initializes x87 afterwards
  • frstor restores the saved state

6

fstenv/fnstenv/fldenv save/load the environment without the data registers

  • 28-byte area in this mode

7

fnop: floating-point no operation

Concluding remarks

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.

Detailed notes - 3-closing: Concluding remarks

1

the covered subset is enough to write assembly programs

  • main purpose: understand execution beneath high-level languages

2

full i386 architecture includes many additional features and historical complications

  • especially beyond user mode and flat addressing

3

other architectures such as ARM or SPARC offer further low-level perspectives

  • technical references permit deeper study of either them or x86

Previous: Programming in Pascal Reading map Next: C Programming

Comments

Leave a comment Sign in All comments