PC Assembly Language
Reading notes on x86 registers, memory organization and assembly programming. Covers control flow, indirect addressing, stacks, calling conventions and interoperability with C.
- Written
- Published
- Updated
PC Assembly Language
Chapter 1 Introduction
1.2 Computer Organization
All data in memory is numeric. Characters are stored by using a character code that maps numbers to characters.
1.2.4 8086 16-bit Registers
General purpose registers: AX, BX, CX and DX. Each of these registers could be decomposed into two 8-bit registers. For example, the AX register could be decomposed into the AH and AL registers
Two 16-bit index registers: SI and DI. They are often used as pointers, but can be used for many of the same purposes as the general registers. However, they can not be decomposed into 8-bit registers.
The 16-bit BP and SP registers are used to point to data in the machine language stack and are called the Base Pointer and Stack Pointer, respectively.
Segment registers: CS, DS, SS and ES. CS stands for Code Segment, DS for Data Segment, SS for Stack Segment and ES for Extra Segment.
The Instruction Pointer (IP) register is used with the CS register to keep track of the address of the next instruction to be executed by the CPU.
The FLAGS register stores important information about the results of a previous instruction.
1.2.5 80386 32-bit registers
The 80386 and later processors have extended registers.
For example, the 16-bit AX register is extended to be 32-bits. To be backward compatible, AX still refers to the 16-bit register and EAX is used to refer to the extended 32-bit register. AX is the lower 16-bits of EAX just as AL is the lower 8-bits of AX (and EAX). There is no way to access the upper 16-bits of EAX directly. The other extended registers are EBX, ECX, EDX, ESI and EDI.
Many of the other registers are extended as well. BP becomes EBP; SP becomes ESP; FLAGS becomes EFLAGS and IP becomes EIP.
The segment registers are still 16-bit in the 80386.
1.2.6 Real Mode
In this mode, a program may access any memory address, even the memory of other programs!
In real mode, memory is limited to only one megabyte ( bytes). However one 16bit register can't contain 20bit address. Thus, it uses 2 registers to determine an address i.e., selector:offset and formula is
Thus a single selector value can only reference 64K of memory.
1.2.7 16-bit Protected Mode
Protected mode uses a technique called virtual memory .
1.3 Assembly Language
1.3.1 Machine language
Every type of CPU understands its own machine language.
Each instruction has its own unique numeric code called its operation code or opcode for short.
For example, the instruction that says to add the EAX and EBX registers together and store the result back into EAX is encoded by the following hex codes:
1.3.2 Assembly language
An assembly language program is stored as text (just as a higher level language program).
Each assembly instruction represents exactly one machine instruction. (Essential)
add eax, ebx
mnemonic operand(s)
The word add is a mnemonic for the addition instruction. The general form of an assembly instruction is shown above.
An assembler is a program that reads a text file with assembly instructions and converts the assembly into machine code.
Porting assembly programs between different computer architectures is much more difficult than in a high-level language.
1.3.3 Instruction operands
Machine code instructions have varying number and type of operands;
register, memory, immediate, implie
1.3.4 Basic instructions
mov dest src
The data specified by src is copied to dest. One restriction is that both operands may not be memory operands. The operands must also be the same size.
There are often somewhat arbitrary rules about how the various instructions are used.
The ADD instruction is used to add integers.
add eax, 4 ; eax = eax + 4
add al, ah ; al = al + ah
The SUB instruction subtracts integers.
sub bx, 10 ; bx = bx - 10
sub ebx, edi ; ebx = ebx - edi
The INC and DEC instructions increment or decrement values by one.
inc ecx ; ecx++
dec dl ; dl--
1.3.5 Directives
A directive is an artifact of the assembler not the CPU. They are not translated into machine code.
The equ directive can be used to define a symbol. Symbols are named constants that can be used in the assembly program. Symbol values can not be redefined later. (Like constant in C)
symbol equ value
The %define directive. This directive is similar to C’s #define directive.
%define SIZE 100
mov eax, SIZE
Data directives
Data directives are used in data segments to define room for memory.
There are two ways memory can be reserved. The first way only defines room for data; the second way defines room and an initial value.
The first method uses one of the RESX directives. The X is replaced with a letter that determines the size of the one UNIT (or objects) that will be stored. (B for byte, W for word, D for double word, Q for quad word).
eg:
;db Each unit is one byte
a db 42 ; define one byte, contains the value 42
b db 1, 2, 3 ; define three bytes: b[0]=1, b[1]=2, b[2]=3
The second method (that defines an initial value, too) uses one of the DX directives. The X letters are the same as those in the RESX directives.
It is very common to mark memory locations with labels. Labels allow one to easily refer to memory locations in code. Below are several examples:
L1 db 0 ; byte labeled L1 with initial value 0
L2 dw 1000 ; word labeled L2 with initial value 1000
L3 db 110101b ; byte initialized to binary 110101 (53 in decimal)
L4 db 12h ; byte initialized to hex 12 (18 in decimal)
L5 db 17o ; byte initialized to octal 17 (15 in decimal)
L6 dd 1A92h ; double word initialized to hex 1A92
L7 resb 1 ; 1 uninitialized byte
L8 db "A" ; byte initialized to ASCII code for A (65)
Double quotes and single quotes are treated the same.
L9 db 0, 1, 2, 3 ; defines 4 bytes
L10 db "w", "o", "r", ’d’, 0 ; defines a C string = "word"
L11 db ’word’, 0 ; same as L10
For large sequences, NASM’s TIMES directive is often useful. This directive repeats its operand a specified number of times. For example,
L12 times 100 db 0 ; equivalent to 100 (db 0)’s
L13 resw 100 ; reserves room for 100 words
Remember that labels can be used to refer to data in code. There are two ways that a label can be used. If a plain label is used, it is interpreted as the address (or offset) of the data. If the label is placed inside square brackets ([]), it is interpreted as the data at the address. In other words, one should think of a label as a pointer to the data and the square brackets dereferences the pointer just as the asterisk does in C.
1 mov al, [L1] ; copy byte at L1 into AL
2 mov eax, L1 ; EAX = address of byte at L1
3 mov [L1], ah ; copy AH into byte at L1
4 mov eax, [L6] ; copy double word at L6 into EAX
5 add eax, [L6] ; EAX = EAX + double word at L6
6 add [L6], eax ; double word at L6 += EAX
7 mov al, [L6] ; copy first byte of double word at L6 into AL
Line 7 of the examples shows an important property of NASM. The assembler does not keep track of the type of data that a label refers to. It is up to the programmer to make sure that he (or she) uses a label correctly.
; Error
mov [L6], 1 ; store a 1 at L6
NOTE: This statement produces an operation size not specified error.
Because the assembler does not know whether to store the 1 as a byte, word or double word.
; Accepted
mov dword [L6], 1 ; store a 1 at L6
Other size specifiers are: BYTE, WORD, QWORD and TWORD.
1.3.6 Input and Output
Input and output are very system dependent activities.
1.4 Creating a Program
In Linux and use NASM
asm -f elf64 hello.asm -o hello.o
ld hello.o -o hello
Big and Little Endian Representation
Chapter 2 Basic Assembly Language
MUL
mul source
The source is either a register or a memory reference.
And It multiplies AL, AX, or EAX by operand, depending on operand size. And the result in two EAX = low 32 bits of result and EDX = high 32 bits of result
Be careful — mul always assumes unsigned multiplication and can affect EAX and EDX, not just one register.
If you want signed multiplication
imul ebx ; signed multiply EAX * EBX
2.2 Control Structures
2.2.1 Comparisons
Control structures decide what to do based on comparisons of data. In assembly, the result of a comparison is stored in the FLAGS register to be used later.
cmp vleft, vright
2.2.2 Branch instructions
There are several variations of the jump instruction:
short: This jump is very limited in range. It can only move up or down 128 bytes in memory.
near: This jump is the default type for both unconditional and conditional branches, it can be used to jump to any location in a segment.
far: This jump allows control to move to another code segment.
Note signed and unsigned are not the same:
------------Signed-----------------------------------Unsigned------------
JE branches if vleft = vright JE branches if vleft = vright
JNE branches if vleft = vright JNE branches if vleft = vright
JL, JNGE branches if vleft < vright JB, JNAE branches if vleft < vright
JLE, JNG branches if vleft ≤ vright JBE, JNA branches if vleft ≤ vright
JG, JNLE branches if vleft > vright JA, JNBE branches if vleft > vright
JGE, JNL branches if vleft ≥ vright JAE, JNB branches if vleft ≥ vright
2.2.3 The loop instructions
loop: Decrements ECX, if ECX = 0, branches to label.
eg:
;sum = 0;
;for( i=10; i >0; i−− )
; sum += i;
1 mov eax, 0 ; eax is sum
2 mov ecx, 10 ; ecx is i
3 loop_start:
4 add eax, ecx
5 loop loop_start
Chapter 4 Subprograms
4.1 Indirect Addressing
Indirect addressing allows registers to act like pointer variables.
1 mov ax, [Data] ; normal direct memory addressing of a word
2 mov ebx, Data ; ebx = & Data
3 mov ax, [ebx] ; ax = *ebx
4.3 The Stack
The SS segment register specifies the segment that contains the stack (usually this is the same segment data is stored into). The ESP register contains the address of the data that would be removed from the stack. This data is said to be at the top of the stack.
The PUSH instruction inserts a double word(32 bit machine) on the stack by subtracting 4 from ESP and then stores the double word at [ESP]. The POP instruction reads the double word at [ESP] and then adds 4 to ESP.
1 push dword 1 ; 1 stored at 0FFCh, ESP = 0FFCh
2 push dword 2 ; 2 stored at 0FF8h, ESP = 0FF8h
3 push dword 3 ; 3 stored at 0FF4h, ESP = 0FF4h
4 pop eax ; EAX = 3, ESP = 0FF8h
5 pop ebx ; EBX = 2, ESP = 0FFCh
6 pop ecx ; ECX = 1, ESP = 1000h
The 80x86 also provides a PUSHA instruction that pushes the values of EAX, EBX, ECX, EDX, ESI, EDI and EBP registers (not in this order). The POPA instruction can be used to pop them all back off.
4.4 The CALL and RET Instructions
The CALL instruction makes an unconditional jump to a subprogram and pushes the address of the next instruction on the stack.
The RET instruction pops off an address and jumps to that address.
When using these instructions, it is very important that one manage the stack correctly so that the right number is popped off by the RET instruction!
4.5 Calling Conventions
The calling conventions can differ from compiler to compiler or may vary depending on how the code is compiled (e.g. if optimizations are on or not).
4.5.1 Passing parameters on the stack
Parameters to a subprogram may be passed on the stack. They are pushed onto the stack before the CALL instruction.
Just as in C, if the parameter is to be changed by the subprogram, the address of the data must be passed, not the value. If the parameter’s size is less than a double word, it must be converted to a double word before being pushed.
The parameters on the stack are not popped off by the subprogram, instead they are accessed from the stack itself like (esp + 4 or esp + 8 ...)
After the subprogram is over, the parameters that were pushed on the stack must be removed. The C calling convention specifies that the caller code must do this.
The C calling convention mandates that a subprogram first save the value of EBP on the stack and then set EBP to be equal to ESP. This allows ESP to change as data is pushed or popped off the stack without modifying EBP. At the end of the subprogram, the original value of EBP must be restored (this is why it is saved at the start of the subprogram.)
So final process is following:
; NOTE: section name must begin with '.' and
; These three name are The linker and OS expect
; standard section names
; === [ Code Section ] ===
; for code
section .text
; Tell OS this is the entry point of program.
global _start
_start:
; addNumber(7, 3)
push dword 3
push dword 7
call addNumber ; eax is the result
pop ebx ; clear the argument
pop ebx ; for C convention.
; exit(0)
mov eax, 1 ; syscall: sys_exit
xor ebx, ebx ; status code 0
int 0x80
addNumber:
;----------- preliminary -------------------
push ebp ; save caller stack base
mov ebp, esp ; create a new stack i.e. move
; ebp to esp. Note this means
; each stack base is caller's stack base
;----------- do something -------------------
mov eax, [esp+8] ; 1st argument
mov ebx, [esp+12] ; 2nd argument
add eax, ebx ;eax = eax + ebx
;------------- end -------------------
mov esp, ebp ; restore caller's stack base
pop ebp
ret
[ebp+0] = saved ebp
[ebp+4] = return address (pushed by call)
[ebp+8] = 1st arg
[ebp+12] = 2nd arg
4.5.2 Local variables on the stack
The stack can be used as a convenient location for local variables. This is exactly where C stores normal (or automatic in C lingo) variables.
Local variables are stored right after the saved EBP value in the stack.
This section of the stack that contains the parameters, return information and local variable storage is called a stack frame.
Every invocation of a C function creates a new stack frame on the stack.
; === [ Code Section ] ===
; for code
section .text
; Tell OS this is the entry point of program.
global _start
_start:
call localVariable
; exit(0)
mov eax, 1 ; syscall: sys_exit
xor ebx, ebx ; status code 0
int 0x80
localVariable:
;----------- preliminary -------------------
push ebp ; save caller stack base
mov ebp, esp ; create a new stack falme i.e. move
; ebp to esp. Note this means
; each stack base is caller's stack base
sub esp, 8 ; allocate 2 * 4 byte to store 2 local variable
;----------- do something -------------------
mov dword [ebp-4], 7 ; localVariable1 = 7
mov dword [ebp-8], 3 ; localVariable2 = 3
; localVariable1 = localVariable1 * localVariable2
mov eax, [ebp-4]
mov ebx, [ebp-8]
mul ebx ; Note: It multiplies AL, AX, or EAX by operand,
; depending on operand size. And the result in two
; EAX = low 32 bits of result
; EDX = high 32 bits of result
mov [ebp-4], eax
;------------- end -------------------
mov esp, ebp ; restore caller's stack base
pop ebp
ret
4.6 Multi-Module Programs
A multi-module program is one composed of more than one object file.
Recall that the linker combines the object files into a single executable program.
4.7 Interfacing Assembly with C
Today, very few programs are written completely in assembly.
4.7.1 Saving registers
First, C assumes that a subroutine maintains the values of the following registers: EBX, ESI, EDI, EBP, CS, DS, SS, ES. This does not mean that the subroutine can not change them internally. Instead, it means that if it does change their values, it must restore their original values before the subroutine returns.
4.7.3 Passing parameters
Under the C calling convention, the arguments of a function are pushed on the stack in the reverse order that they appear in the function call.
4.7.4 Calculating addresses of local variables
Finding the address of a label defined in the data or bss segments is simple. Basically, the linker does this. However, calculating the address of a local variable (or parameter) on the stack is not as straightforward.
However, this is a very common need when calling subroutines.
So we use lea to solve that. Lea = Load Effective Address.
lea destination, [address_expression]
Lea put the address of what's inside the brackets into the destination
This is often used to calculate an address (e.g., for indexing arrays), but without actually accessing memory. The LEA instruction never reads memory
eg:
; oneAddress = 0x000000ff
lea eax, [oneAddress + 4] ; This is equal to eax = 0x000000ff + 4;
; if lea a register it will be the same as mov
lea eax, [ebx] ; mov eax, ebx;
4.7.5 Returning values
The C calling conventions specify how this is done. Return values are passed via registers.
All integral types (char, int, enum, etc.) are returned in the EAX register. If they are smaller than 32-bits, they are extended to 32-bits when stored in EAX. (How they are extended depends on if they are signed or unsigned types.) 64-bit values are returned in the EDX:EAX register pair. Pointer values are also stored in EAX. Floating point values are stored in the ST0 register of the math coprocessor. (This register is discussed in the floating point chapter.)
4.8 Reentrant and Recursive Subprograms (Interesting)
In a high level language this would be difficult, but in assembly it is not hard for a program to try to modify its own code. (This is super awesome!!)
We call this Self-modifying code
This code would work in real mode, but in protected mode operating systems the code segment is marked as read only.
Comments
No approved comments yet.
Your display name and plain-text comment become public only after owner approval. No account or email is required.