We will use the
NASM assembler
to create some small assembler programs on the PC.
Some useful links:
- We are using 386 mainly because it's handy.
The architecture is not very clean.
- We'll be considering the 32-bit architecture. 64-bit systems can
do 32-bit just fine. (16-bit ones, too, for that matter.)
- We'll use the NASM assembler.
- On Linux, just use the package manager, e.g.,
yum install nasm
- For Windows.
- You should have the compilers working from the Windows command
line. If they don't, you might install
MinGW. If you have
CodeBlocks installed, you might try
this
procedure to make the compilers available.
- NASM
download page.
- Nasm is available on Sandbox.
- NASM uses the Intel format, rather than the ATT format. (Some of the
tutorials may refer to these.)
The Stack
- Furniture.
- 32-bit General-purpose registers: EAX, EBX, ECX, EDX, ESI, EDI, EBP, ESP.
- The Program Counter is called EIP.
- The MOV instruction copies between registers, or memory and register.
Covers load and store, and copying between registers.
- Simple math: ADD and SUB. Also INC and DEC.
- MUL and DIV.
- MUL produces a 64-bit product in EDX:EAX pair.
- DIV divides a 64-bit value EDX:EAX.
- For two arguments, the first is the destination.
- Destinations can be registers or memory addresses.
- Sources also can be constants.
- Memory locations can be symbols, or indirect from registers.
[EAX], [ESP+4], [4*EAX+12]
- PUSH and .
- Manipulate the ESP.
- PUSH decrements then stores.
- loads then increments.
- Assorted jumps.
- CALL and RET.
- Calling conventions.
- Conventional register usage allows functions written by different
parties to work together.
- Compiled code generally obeys these rules.
- The values of EBX, ESI, EDI and EBP must survive across calls.
- If you call a function, you can expect it to preserve those registers.
- If you write a function, you must either not use those registers, or
save before use and restore before return.
- Other register may not survive functions you call, and you need not
preserve them in your functions.
- A function's return value is left in EAX.
- Arguments are pushed before calling, and the caller removes them after
return.
- The EBP is used as frame pointer.
- Function form:
push ebp
mov ebp, esp
; Save registers on the stack, several pushes, or pusha
sub esp, N ; Allocate N bytes of local variable space
;
; Get some actual work done.
;
add esp, N ; Free the space
; Pop saved registers off the stack.
mov esp, ebp
pop ebp
ret