---
# System prepended metadata

title: How To Ass(embly)

---

# How To Assembly
###### By Sebastian Wojciechowski (490631)


### Chapter 1 - Introduction:
In this report I will explore some of the basics of Assembly and provide a few Step by Step guides in helping to  create basic programs in assembly.

### Step 1: Instalation of the compilers
The first step is instlling a compiler. There are a various options available and if you really want to you can pick any of them, however for the sake of simplicity I will be using the NASM compiler for this tutorial.

If you are on Linux you can simply type in the following command in your command line.

```
sudo apt install nasm yasm 
```

If you are on Mac, the procees is a bit more involved however here is a decent tutorial on how to do it:
https://medium.com/@thisura1998/hello-world-assembly-program-on-macos-mojave-d5d65f0ce7c6

*The latest version of NASM can be downloaded here:*
https://www.nasm.us/


### Step 2: Assembly basics and the first program 
With use of a text editor of your choice, it's time to create the program. It's good to start with someting simple to get the idea of how the code is structured and how you write basic instructions. 

```
        global    _start

        section   .text
_start:
        mov       rax, 1                  ; system call for write
        mov       rdi, 1                  ; file handle 1 is stdout
        mov       rsi, message            ; address of string to output
        mov       rdx, 13                 ; number of bytes
        syscall                           ; invoke operating system to do the write
        mov       rax, 60                 ; system call for exit
        xor       rdi, rdi                ; exit code 0
        syscall                           ; invoke operating system to exit

        section   .data
message:  db        "Hello, World", 10      ; note the newline at the end
```

*global* directive is NASM specific. It is for exporting symbols in your code to where it points in the object code generated. Here you mark _start symbol global so its name is added in the object code.

*.text* section is used for keeping the actual code. This section must begin with the declaration global _start, which tells the kernel where the program execution begins.

*.data* section is used for declaring initialized data or constants. This data does not change at runtime. You can declare various constant values, file names, or buffer size, etc., in this section.

*db* is a pseudo-instruction that declares bytes that will be in memory when the program runs

*mov* instruction copies the data item referred to by its second operand  into the location referred to by its first operand (i.e. a register or memory).

*xor* - logical exclusive or instruction (it's used here to insert 0 into ldi)
#### General purpose registers 

The x86 architecture has 8 General-Purpose Registers (GPR), 6 Segment Registers, 1 Flags Register and an Instruction Pointer. 64-bit x86 has additional registers. General-Purpose Registers (GPR) - 16-bit naming conventions
The 8 GPRs are as follows:

*Accumulator register (AX)*. Used in arithmetic operations
*Counter register (CX)*. Used in shift/rotate instructions and loops.
*Data register (DX)*. Used in arithmetic operations and I/O operations.
*Base register (BX)*. Used as a pointer to data (located in segment register DS, when in segmented mode).
*Stack Pointer register (SP)*. Pointer to the top of the stack.
*Stack Base Pointer register (BP)*. Used to point to the base of the stack.
*Source Index register (SI)*. Used as a pointer to a source in stream operations.
*Destination Index register (DI)*. Used as a pointer to a destination in stream operations.

You can specify which part of the register you want to use by changing the prefix or the suffix of the register
e.g. for register (AX)

RAX - using 64 bits of the register
EAX - using 32 bits of the register
AX - using 16 bits of the register
AL - using first 8 bits of the register
AH - using second 8 bits of the register


#### Linux System Calls (syscall) 
You can make use of Linux system calls in your assembly programs. You need to take the following steps for using Linux system calls in your program −

Put the system call number in the EAX register.
Store the arguments to the system call in the registers EBX, ECX, etc.
Call the relevant interrupt (80h).
The result is usually returned in the EAX register.
There are six registers that store the arguments of the system call used. These are the EBX, ECX, EDX, ESI, EDI, and EBP. These registers take the consecutive arguments, starting with the EBX register. If there are more than six arguments, then the memory location of the first argument is stored in the EBX register.

*rax* register is used as a designated register for return values from functions

The first six function arguments are passed in registers *%rdi* , *%rsi* , *%rdx* , *%rcx* , *%r8* , and *%r9* (On x86-64 Linux)

#### Types of operands
Three kinds of operands are generally available to the instructions: register, memory, and immediate


#### Direct vs Indirect addressing 

Direct addressing provides the full address of the main memory in the instruction, where the is stored. On the other hand, in indirect addressing mode, the address is stored at the address field of the instruction. 

Key Differences Between Direct and Indirect addressing modes

- Direct addressing provides the full address of the main memory in the instruction, where the is stored. On the other hand, in indirect addressing mode, the address is stored at the address field of the instruction.
 - The number of memory references required in the direct mode is one, but it is two in the indirect mode for executing the instruction.
 - The address space provided in the indirect mode is up to 2N, which is greater than the space provided in the direct addressing mode.
- For executing the instruction using a direct mode, the supplementary calculation is not required. Conversely, the execution of the instruction using indirect addressing mode requires more computations.
- The direct addressing mode is faster than the indirect addressing mode.


#### Reserving space in memory for variables

In assembly we need to specify the size of variables using assembler directives:



| directive | size | 
| -------- | -------- | 
| DB/BYTE     | 1 byte     | 
| DW/WORD    |2 bytes     | 
| DD, DWORD    | 4 bytes     | 
| DQ, QWORD    | 8 bytes     | 
| DT    | 10 bytes    | 

```
section   .data
message:  db        "Hello, World", 10      ; here with db we reserve 1 byte of memory
```
### Chapter 2 - Logical operations 

The processor instruction set provides the instructions AND, OR, XOR, TEST, and NOT Boolean logic, which tests, sets, and clears the bits according to the need of the program.

The format for these instructions:





 | Instruction | Format |
 | -------- | -------- |
 | AND      | AND operand1, operand2     |
| OR     | OR operand1, operand2     |
| XOR      | XOR operand1, operand2     |
| TEST      | TEST operand1, operand2     |
| NOT     | NOT operand1     |

The first operand in all the cases could be either in register or in memory. The second operand could be either in register/memory or an immediate (constant) value. However, memory-to-memory operations are not possible. These instructions compare or match bits of the operands and set the CF, OF, PF, SF and ZF flags.

The TEST Instruction
The TEST instruction works same as the AND operation, but unlike AND instruction, it does not change the first operand. So, if we need to check whether a number in a register is even or odd, we can also do this using the TEST instruction without changing the original number
### Chapter 3 - Arithmetic Instructions

Assembly language provides instructions for multiple arthmetic operations



| Instruction | Opertation | 
| -------- | -------- | 
| INC    | Increments an opperand by 1    |
| DEC     | Decrements an opperand by 1     |
| ADD     | addition of binary data     |
| SUB     | Subtraction of binary data   |
| MUL/IMUL     | Multiplying binary data. The MUL (Multiply) instruction handles unsigned data and the IMUL (Integer Multiply) handles signed data.    |
| DIV/IDIV   | Division operation generates two elements - a quotient and a remainder. The DIV (Divide) instruction is used for unsigned data and the IDIV (Integer Divide) is used for signed data.    |






### Chapter 4 - Conditions
There are two types of conditional instructions, Conditional and Un-conditional instructions.


Conditional execution in assembly language is accomplished by several looping and branching instructions. These instructions can change the flow of control in a program. Conditional execution is observed in two scenarios:


- Unconditional jump: performed by the JMP instruction
- Condiditonal jump: performed by a set of jump instructions j<condition> depending upon the condition

	<br>
***CMP* Instruction**
The *CMP* instruction compares two operands. It is generally used in conditional execution. This instruction basically subtracts one operand from the other for comparing whether the operands are equal or not It is used along with the conditional jump instruction for decision making.
	
	
**Conditional Jump**
If some specified condition is satisfied in conditional jump, the control flow is transferred to a target instruction. There are numerous conditional jump instructions depending upon the condition and data.
Following are the conditional jump instructions used on signed data used for arithmetic operations:

| Instruction | Description  | Flags tested | 
| --------    | --------     | --------     |
| JE/JZ       | Jump Equal or Jump Zero     | ZF     |
| JNE/JNZ     | Jump not Equal or Jump Not Zero     | ZF     |
| JG/JNLE     | Jump Greater or Jump Not Less/Equal     |	OF, SF, ZF     |
| JGE/JNL     | Jump Greater/Equal or Jump Not Less     | OF, SF    |
| JL/JNGE     | Jump Less or Jump Not Greater/Equal     | OF, SF     |
| JLE/JNG     | Jump Less/Equal or Jump Not Greater     | OF, SF, ZF   |
	
Some conditional jump instructions have special uses to check the states like:
	- carry
	- overflow
	- sign
    

### Chapter 5 - The Loops
There are three main types of loops. The "For-Loop", the "While-Loop", and the "Do-While-Loop".
    
    
    
**For-loop in C:**
    
```
    for(int x = 0; x <=3; x++)
    {
        //Do something!
    }
```
The same loop in 8086 assembler:

    xor cx,cx           ; cx-register is the counter, set to 0
    loop1   nop         ; Whatever you wanna do goes here, should not change cx
    inc cx              ; Increment
    cmp cx,3            ; Compare cx to the limit
    jle loop1           ; Loop while less or equal

That is the loop if you need to access your index (cx). If you just wanna to something 0-3=4 times but you do not need the index, this would be easier:

    mov cx,4            ; 4 iterations
    loop1   nop         ; Whatever you wanna do goes here, should not change cx
    loop loop1          ; loop instruction decrements cx and jumps to label if not 0
                        
If you just want to perform a very simple instruction a constant amount of times, you could also use an assembler-directive which will just hardcore that instruction

    times 4 nop

**While-loops**
While-loop in C:

    while(x==1){
        //Do something
    }
The same loop in assembler:

    jmp loop1           ; Jump to condition first
    cloop1  nop         ; Execute the content of the loop
    loop1   cmp ax,1    ; Check the condition
    je cloop1           ; Jump to content of the loop if met


 **Do-while-loops**
Do-while-loop in C:

    int x=1;
    do{
        //Do something!
    }
    while(x==1)
The same loop in assembler:

    mov ax,1
    loop1   nop         ; Whatever you wanna do goes here
    cmp ax,1            ; Check wether cx is 1
    je loop1            ; And loop if equal

### Chapter 6 - Arrays
Just like in any traditional programing language, an array is just a block of memory. In assembly however, it takes a bit more effort to iterate through it. There are many ways to declare and initialize an array.
 Here are some examples:
```
- NUMBERS	DW  34,  45,  56,  67,  75, 89

- INVENTORY DW  0
            DW  0
            DW  0
            DW  0
            DW  0
            DW  0
            DW  0
            DW  0

;Which can be abbreviated as:
- INVENTORY   DW  0, 0 , 0 , 0 , 0 , 0 , 0 , 0

- INVENTORY TIMES 8 DW 0 ;(initializing inventory with 8 zeroes)

```
To iterate through an array you need to add correct amount of bytes to the array pointer to access the next elements of it.

```
- NUMBERS	DW  34,  45,  56,  67,  75, 89

;to get the value at first index we just need to put our array pointer in square brackets (dereference it)

[NUMBERS]

;Since elements in NUMBERS are DW (2 bytes) we need to add 2 to our array pointer to move to the next element

[NUMBERS + 2]

```



### Chapter 7 - Functions
To create a function, first we need to declare it with a label (e.g. _swap:).
Then we implement it by putting code after the label, followed by ***ret***(return) in the end. 
To call a function simply use ***call*** instruction followed by the label name



**Swap Function:**
```
global _start
global _print 
global _swap 
section   .text
_swap: 
        mov     rsi,x_value
        mov     al,[rsi]
        mov     rdi,y_value
        mov     dl,[rdi]
        mov     [rsi],dl
        mov     [rdi],al
        ret
        
_print:
        mov       rax, 1                  ; system call for write
        mov       rdi, 1                  ; file handle 1 is stdout
        mov       rsi, x_value            ; address of string to output
        mov       rdx, 12                 ; number of bytes
        syscall                           ; invoke operating system to do the write
        mov       rax, 60                 ; system call for exit
        xor       rdi, rdi                ; exit code 0
        syscall
        ret 

_start:
        
    
        call _print     ;print x_value
        call _swap      ;call swap function
        call _print     ;print x_value again


section   .data
        x_value: db     "42",10
        y_value: db     "24"


```

### Chapter 8 - File Operations

**Opening a file**

```
mov rax, 2              ; SYS_OPEN syscall number
mov rdi, path           ; File path pointer
mov rsi, O_RDONLY       ; Open for read-only
xor rdx, rdx            ; Mode not needed for read-only
syscall                 ; Perform system call
```

**Reading from a file**

```
mov rax, 0              ; SYS_READ syscall number
mov rdi, fd             ; File descriptor
mov rsi, buffer         ; Buffer pointer
mov rdx, 4096           ; Bytes to read
syscall                 ; Perform system call
```

**Writing to a file**

```
mov rax, 1              ; SYS_WRITE syscall number
mov rdi, fd             ; File descriptor
mov rsi, buffer         ; Buffer pointer
mov rdx, 4096           ; Bytes to write
syscall                 ; Perform system call
```

### Chapter 9 - The Stack in Assembly

The stack is a crucial component in assembly programming for temporary storage and function call management.

**Pushing and Popping**

The push and pop instructions allow data to be added to or removed from the stack:
```
push rax        ; Save the value of rax on the stack
pop rbx         ; Restore the value from the stack into rbx
```
The stack grows downward, meaning each push decreases the stack pointer (rsp) and each pop increases it.

Stack Usage Example
```
push rax        ; Save rax
mov rax, 5      ; Perform some operation
pop rax         ; Restore original value of rax
                                                      
```
### Chapter 10 - Stack Alignment and Stack Frame

Stack alignment is essential for performance and correctness in certain operations, particularly when calling functions.

**Alignment Requirements**

The stack must be 16-byte aligned before making a function call. Use padding if necessary:
```
sub rsp, 8          ; Align stack to 16 bytes
call my_function    ; Call a function
add rsp, 8          ; Restore stack alignment
```
**Creating a Stack Frame**

A stack frame is created for managing local variables and function parameters. The base pointer (rbp) is typically used to reference the frame:                       
```         
push rbp            ; Save base pointer
mov rbp, rsp        ; Set new base pointer
sub rsp, 16         ; Allocate space for local variables
...                 ; Perform operations
mov rsp, rbp        ; Restore stack pointer
pop rbp             ; Restore base pointer
ret                 ; Return from function   
```    
                        
### Chapter 11 - External Functions

Assembly programs can utilize external functions written in other languages like C.

**Declaring External Functions**

Use the extern directive to declare external functions:
``` 
extern printf
``` 
**Declaring Global Symbols**

Use the global directive to expose symbols from your assembly code:
``` 
global my_function
``` 
                        
Example 
```                         
section .data
    message db "Hello, World!", 0

section .text
    extern printf
    global _start

_start:
    mov rdi, message    ; Pass message as first argument to printf
    call printf         ; Call printf
    mov rax, 60         ; Exit system call
    xor rdi, rdi        ; Exit code 0
    syscall        
```                         
### Chapter 12 - Calling Conventions

Calling conventions are standardized ways to pass arguments to and receive return values from functions.

**Argument Passing**
For x86-64 Linux, non-floating-point arguments (e.g., integers and addresses) are passed in the following order:

rdi -> First argument 

rsi -> Second argument

rdx -> Third argument

rcx -> Fourth argument

r8 -> Fifth argument

r9 -> Sixth argument

Floating-point arguments are passed using xmm registers in order, from xmm0 to xmm7.

**Preserving Registers**

Certain registers must be preserved during a function call (callee-saved):

rbx

rsp

rbp

r12

r13

r14

r15

Example   
```     
my_function:
    push rbp        ; Save base pointer
    mov rbp, rsp    ; Establish stack frame
    mov rax, rdi    ; Use first argument
    add rax, rsi    ; Add second argument
    pop rbp         ; Restore base pointer
    ret             ; Return
```  
### Chapter 13 - Compilation and debugging

To compile a nasm assembly program with debug info we can use the following command:

- *nasm -f elf64 -g -F dwarf filename -o filename.o*

-*f elf64* flag select an output format (elf64 in this case)

-*g* flag generates debugging information

-*F dwarf* selects debugging  format (dwarf in this case)

-*o* writes output to an outfile 

To link the *.o* we can use either ld command or gcc 
 
- *ld file.o -o file* 
- *gcc file.o -o file*

those will create an executable called *test*

to debug that executable you can use gdb with
 - *gdb test*

With gdb you can set breakpoints and analyze how variables and registers change with each line of code 



