# Introduction to ARM

### Introduction

ARM stands for Advanced RISC Machines and is a family of CPUs used in various smartphones, IoT devices, Smart gadgets, routers, etc. They are developed by  [Arm Ltd.](https://en.wikipedia.org/wiki/Arm_\(company\)) ARM, initially stood for Acorn RISC Machine, and then it was changed to Advanced RISC Machine. A RISC (Reduced Instruction Set Computer) is a microprocessor that has very optimized instructions.RISC devices might require more instructions when compared to CISC computers because the instruction is simple and are not complex as CISC. CISC is commonly used in PC and laptops.

The ARM machines are smaller in size and are energy efficient that's why it is used in devices like smartphones. ARM is known as a load-store architecture which means that it can't directly perform operations on data in the memory it should be loaded in the appropriate registers before performing any operations.

The RISC Machines use a technique called pipelining to speed up the execution. It is the process of fetching the next instruction while the current instruction is being executed. RISC Machines use more registers compared to CISC Machines. It is much simpler when compared to CISC Machines.

As the usage of smart gadgets, IoT devices, and smartphones is increasing day by day we need to learn about their security aspects too. ARM has a 32-bit architecture and 64-bit architecture. Most of the smartphones manufactured these days are using ARM64.So it's important to learn both.

In this chapter, we will introduce you to ARM32 and its registers, instructions, modes, etc. About 70% of Exploitation is based on ARM32 in this book. But the same can be applied to ARM64.

### Registers

Let's start off with registers.

Registers are high-speed memory areas in the CPU. They can accept, store, and transfer data. A register can hold an instruction,  address, or any data. The number of registers depends on the machine depends on its ARM version.

There are roughly around 37 registers in ARM32. Of these 37 registers, the 11 registers from R0 to R10 are called general purpose registers. The registers from r11 to r15 are called special purpose registers. We should be aware of the general purpose registers and special purpose registers.

| Register | Purpose                                                                                                     |
| -------- | ----------------------------------------------------------------------------------------------------------- |
| R0       | General Purpose, Can be used to store the return value.                                                     |
| R1       | General Purpose.                                                                                            |
| R2       | General Purpose.                                                                                            |
| R3       | General Purpose.                                                                                            |
| R4       | General Purpose.                                                                                            |
| R5       | General Purpose.                                                                                            |
| R6       | General Purpose.                                                                                            |
| R7       | Holds Syscall Number.                                                                                       |
| R8       | General Purpose.                                                                                            |
| R9       | General Purpose.                                                                                            |
| R10      | General Purpose.                                                                                            |
| R11      | FP,Frame pointer, used as a base pointer to local variables on the stack. it holds a fixed value unlike SP. |
| R12      | IP,Intra Procedural Call.                                                                                   |
| R13      | SP, Stack pointer.Points to the top of the stack.                                                           |
| R14      | LR, Link Register. Contains the return address of a subroutine.                                             |
| R15      | PC, Program Counter. Points to the next instruction to be executed.                                         |
| CPSR     |  Current Program Status Register. Contains various bits.                                                    |

We will better understand these registers when we go through the examples.

### Instruction Format

The instruction Format shows the layout of the instructions. The instructions are divided into two parts:

Opcode: Part of the instruction that is executed by the CPU

Operand: The data or memory location used to execute that instruction

<figure><img src="https://3643148735-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FuoH6DVWgxRANBNbHnsUM%2Fuploads%2F3clTdRpg7t6rz7Hn05Ho%2Fimage.png?alt=media&#x26;token=8e20c7f3-0570-4196-9a0d-f9a6705c8523" alt=""><figcaption><p>[Image source : <a href="https://binaryterms.com/addressing-modes-and-its-types.html">https://binaryterms.com/addressing-modes-and-its-types.html</a> ]</p></figcaption></figure>

Instructions are used to perform a specified operation on given data. For example addition, subtraction, etc. In ARM 32 bits are used to represent both Opcode and Operands.

<figure><img src="https://3643148735-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FuoH6DVWgxRANBNbHnsUM%2Fuploads%2F83sI0l0oeZxlgcaxM51F%2Fopcodes.png?alt=media&#x26;token=7057bf03-1e6a-4774-ba48-8f768323c81e" alt=""><figcaption><p>[Source : <a href="https://documentation-service.arm.com/static/5f8db1f7f86e16515cdba287?token=">https://documentation-service.arm.com/static/5f8db1f7f86e16515cdba287?token=</a>]</p></figcaption></figure>

### ARM states

Arm processors can execute instructions in 32-bit mode and 16-bit mode. They are called ARM mode and Thumb mode. The ARM mode instructions are 32-bit in width and the Thumb mode instructions are 16-bit in width. The processor can switch between ARM mode and Thumb mode using the Branch and Exchange instruction. The Thumb bit (T ) indicates in the CPSR determines the processor’s current state: 0 for the ARM state (default) or 1 for Thumb. As the thumb instructions are smaller, it requires more instruction to perform an operation when compared to ARM state instructions. A single instruction to perform a task in the ARM state may require multiple instructions in the Thumb state. Similarly, all the instructions in the ARM state mode won't have support on the Thumb state. The instructions are 2-byte aligned in thumb mode and 4-byte aligned in ARM mode.

### CPSR

The Current Program Status Register (CPSR) contains various flags like the thumb, fast, interrupt, overflow, carry, zero, and negative. These flags represent various bits in the CPSR and are set according to different operations. They can be used in conditional execution, loops, switching states, etc.

<figure><img src="https://3643148735-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FuoH6DVWgxRANBNbHnsUM%2Fuploads%2FrFbSbKq9Hk9CZWGBN4AI%2Fimage.png?alt=media&#x26;token=91e7da27-0895-4568-92e0-5383fcb10115" alt=""><figcaption><p>[Source : <a href="https://azeria-labs.com/arm-data-types-and-registers-part-2/">https://azeria-labs.com/arm-data-types-and-registers-part-2/</a> ]</p></figcaption></figure>



<figure><img src="https://3643148735-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FuoH6DVWgxRANBNbHnsUM%2Fuploads%2F3AtmGdQ29oPCWdTTdLCX%2Fazerialabs.png?alt=media&#x26;token=3c6f16d5-0f4b-410e-b5d7-b2e3b77a6483" alt=""><figcaption><p>[Source : <a href="https://azeria-labs.com/arm-data-types-and-registers-part-2/">https://azeria-labs.com/arm-data-types-and-registers-part-2/</a> ]</p></figcaption></figure>

### Endianness

This refers to the order of bytes represented in the computer memory. ARM can operate either in little-endian, or big-endian. But most implementations of ARM are in little-endian. Little-endian is the default memory format for ARM processors. In little-endian machines, the last byte of the binary representation of the data is stored first. But in Big-endian machines, the first byte of the binary representation of the data is stored in the first location itself.

Let's see an example.

Consider the number hex value 0x01234567 represented in the big-endian and little-endian machines.

<figure><img src="https://3643148735-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FuoH6DVWgxRANBNbHnsUM%2Fuploads%2FYRNNcrv78eQEZe2ZZDud%2Fimage.png?alt=media&#x26;token=e24b444e-9be0-490a-9163-b2c247e5b4ed" alt=""><figcaption><p>[Source: <a href="https://www.geeksforgeeks.org/little-and-big-endian-mystery/">https://www.geeksforgeeks.org/little-and-big-endian-mystery/</a> ]</p></figcaption></figure>

&#x20;As we go over the buffer overflow sections we will be using little endian formats. If you want to read more about this. I recommend going through this link.

{% embed url="https://www.freecodecamp.org/news/what-is-endianness-big-endian-vs-little-endian/" %}

### Instructions&#x20;

Instructions are used to perform a specified operation on given data. There are different types of instructions like arithmetic, logical, etc. we won't be covering all of the instructions because that is not the scope of this book.&#x20;

rd is the destination register and rn is the source register.

| Instruction     | Operation     | Example                           |
| --------------- | ------------- | --------------------------------- |
| `mov rd,rn`     | `rd = rn`     | `mov r0, r2` `; r0 = r2`          |
| `add rd, rn, n` | `rd = rn + n` | `add r0, r2, #2` `; r0 = r2 + 2`  |
| `sub rd, rn, n` | `rd = rn - n` | `sub r0, r0, r1` `; r0 = r0 - r1` |
| `cmp rn, n`     | `rn - n`      | `cmp r0, r2` `; r0 - r2`          |

Let's debug a simple program to get a better understanding.

Boot up your azeria labs vm and login into your emulated raspi using the ssh console. You don't need to write any assembly code here. we just need to learn what these instructions do.

```armasm
.data   @data section where you define data

.text   @text section is where the code is written
.global _start

_start:                @Here is where the program starts
        mov r0, #1
        mov r1, #2
        add r3,r1,r2
        sub r1,r3,r0
        mov r7, #1          @Exit syscall
        swi 0                    



 
```

Assemble and link this program using the 'as' and  'ld' commands.

`as asm.s -o asm.o && ld asm.o -o asm`

Load the program inside gdb.

`gdb ./asm`

Let's do the disassembly of the program to see our instructions.

`disass _start`

<figure><img src="https://3643148735-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FuoH6DVWgxRANBNbHnsUM%2Fuploads%2F6CeywKDP2IZ5xIozmVdC%2Fdisass_start.png?alt=media&#x26;token=5164c143-c5af-4f95-ad2c-4283366c05f8" alt=""><figcaption></figcaption></figure>

Put a break at the first instruction to pause the execution.

`b _start`

The reason we are putting a breakpoint at the "\_start" is that the execution starts from the label "\_start".

Now run the program using the "r" command in gdb.

<figure><img src="https://3643148735-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FuoH6DVWgxRANBNbHnsUM%2Fuploads%2Fsz6c2I8zkmmac6Gwc8gI%2Fbp.png?alt=media&#x26;token=d28d97e9-a7c6-43b3-81c6-9d6a44def94e" alt=""><figcaption></figcaption></figure>

The program hit the breakpoint and the execution paused.

if we look at the registers we can see all the registers except "pc" and "sp" are initialized with zero.

<figure><img src="https://3643148735-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FuoH6DVWgxRANBNbHnsUM%2Fuploads%2FMoMpZKGqykaYqZYfCybN%2Fregisters.png?alt=media&#x26;token=50d663c8-ea41-4dff-b066-82b705f5ef77" alt=""><figcaption></figcaption></figure>

The pc points to the first instruction because it is the instruction to be executed. The stack pointer (sp) points to the top of the stack.

<figure><img src="https://3643148735-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FuoH6DVWgxRANBNbHnsUM%2Fuploads%2F21KcvxsczIjOlWlsfiIy%2Fsp.png?alt=media&#x26;token=6775c4e6-1a23-4c1a-a996-c5792975c0d3" alt=""><figcaption></figcaption></figure>

Let's now execute the instructions one by one. we can use the "si"  (step into) or  "ni" (next instruction for this.

`0x10054 <_start+0> mov r0, #1`

This is the first instruction to be executed. R0 is zero now. The value 1 will be copied to the register r0. After executing this instruction r0 will get the value 1.

<figure><img src="https://3643148735-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FuoH6DVWgxRANBNbHnsUM%2Fuploads%2FAIm8gPcEo4ZBajSV4Rop%2Fone.png?alt=media&#x26;token=6b689933-2b57-44da-868d-c4f877a43a56" alt=""><figcaption></figcaption></figure>

The pc is also updated to point to the next instruction to be executed. Similarly, the pc is incremented by 4 bytes in ARM mode.

Now let's step over the second instruction

`0x10058 <_start+4> mov r1, #2`

This will copy the value #2 into r2.&#x20;

<figure><img src="https://3643148735-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FuoH6DVWgxRANBNbHnsUM%2Fuploads%2F5V9lyXe0QmPvhOCtDZDs%2Fr2.png?alt=media&#x26;token=63394ecc-7f6b-4422-a0a9-c590cc82937a" alt=""><figcaption></figcaption></figure>

`0x1005c <_start+8> add r3, r1, r2`

This will add r1 with r2 and store the result in r3.

So, r3 = r1 + r2 = 2 + 0 = 2.

<figure><img src="https://3643148735-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FuoH6DVWgxRANBNbHnsUM%2Fuploads%2F0fucFVhyAU3GaJVTURkf%2Fr3.png?alt=media&#x26;token=4fbcff5d-239a-49b9-9a78-f2d2c6eb6eee" alt=""><figcaption></figcaption></figure>

`0x10060 <_start+12> sub r1, r3, r0`

The "sub" instruction will subtract r0 from r3 and store the result in r1.

r1 = r3 - r0 = 2 -1  = 1

<figure><img src="https://3643148735-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FuoH6DVWgxRANBNbHnsUM%2Fuploads%2FFMDmqx5j6tQjrjNXQpBj%2Fr1.png?alt=media&#x26;token=9d325e9d-ee2b-40eb-a345-1a05ba763d70" alt=""><figcaption></figcaption></figure>

```
0x10064 <_start+16>      mov    r7,  #1
0x10068 <_start+20>      svc    0x00000000
```

These two instructions are used to exit from the program similar to exit() in c. The r7 contains the syscall number. "1" is used for exit. svc is used for Supervisor Calls (SVC). So that the user can trigger an exception.

if we step over these two instructions, the program will exit gracefully.

### Load and store instructions

As ARM is said to be a load and store architecture, we can't directly operate on data in memory. We need to load the data from the memory to registers for doing operations and store the resultant data back in the memory. This can be done with the help of load and store instructions.

**Load instructions can be used to load the data from the memory.**

```
LDR R1, [R2] 
```

r2: Contains the memory location from which the data is loaded.&#x20;

r1: is the destination register.

\[]: The brackets are used to represent the register which contains the memory address to load the value.

This will load the value from the memory location pointed out by r2 into the r1 register.

**Similarly, store instructions are used to store the data in the memory location from a register.**&#x20;

```
STR R1, [R0]
```

r1: Contains the value that should be stored in the memory location.

r0: Contains the memory location where the data should be stored to. This is the destination.&#x20;

\[]: Represents the register holding the destination memory location.

This stores the value in the r1 register to the memory pointed to by the r0 register.

There are different types of addressing modes used in this instruction. if you want to a detailed explanation I highly recommend going through the azerialabs post. if you this article you can skip the rest of the section and read the next section.

{% embed url="https://azeria-labs.com/memory-instructions-load-and-store-part-4/" %}

Now let's go with a simple example program from the azerialabs.

<pre class="language-armasm"><code class="lang-armasm"><strong>.data          /* the .data section is dynamically created and its addresses cannot be easily predicted */
</strong>var1: .word 3  /* variable 1 in memory */
var2: .word 4  /* variable 2 in memory */

.text          /* start of the text (code) section */ 
.global _start

_start:
    ldr r0, adr_var1  @ load the memory address of var1 via label adr_var1 into R0 
    ldr r1, adr_var2  @ load the memory address of var2 via label adr_var2 into R1 
    ldr r2, [r0]      @ load the value (0x03) at memory address found in R0 to register R2  
    str r2, [r1]      @ store the value found in R2 (0x03) to the memory address found in R1 
    bkpt             

adr_var1: .word var1  /* address to var1 stored here */
adr_var2: .word var2  /* address to var2 stored here */
</code></pre>

Let's assemble and link this using the "as" and "ld" command.

```
pi@raspberrypi:~/practice $ as asm0x2.s -o asm0x2.o
pi@raspberrypi:~/practice $ ld asm0x2.o -o asm0x2
```

&#x20;Load the program into gdb and put a bp at " \_start".

```
gef> b _start
Breakpoint 1 at 0x10074
gef> 
```

Start the execution using the  "r" command.

<figure><img src="https://3643148735-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FuoH6DVWgxRANBNbHnsUM%2Fuploads%2Fyj6BBMWLD3hMjAE52GxL%2Fbp0x1.png?alt=media&#x26;token=8c87a390-c5eb-4a3a-b4d2-01bc47e6f593" alt=""><figcaption></figcaption></figure>

The program has hit the bp. Let's examine the first instruction.

`ldr r0, [pc, #12]`&#x20;

This will copy the value from the memory location : \[pc + 12] into the r0 register. This is called PC-relative addressing. The immediate value should be added to the pc to get the memory address. Gdb shows a comment at the end of the instruction. This represents the memory location \[pc +  12]. So the memory location is 0x10088. Let's examine that memory location using the examine command.

```
gef> x/x 0x10088
0x10088 <adr_var1>:	0x00020090
gef> 
```

The data in the memory location is 0x00020090. it is actually an address.

Let's execute that instruction using the "ni" command.

<figure><img src="https://3643148735-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FuoH6DVWgxRANBNbHnsUM%2Fuploads%2Fl0sS7YKxQSQARgdavaux%2Fr0.png?alt=media&#x26;token=9b6a98e4-744d-4fbd-93dc-f71b283a8e0a" alt=""><figcaption></figcaption></figure>

As expected r0 is loaded with the address 0x0020090 which points to a value of 0x3. gef highlighting is very useful in these situations so that you don't need to examine the location each time to know the data in it, gef will automatically highlight the value in that location.

```
0x10078 <_start+4>       ldr    r1,  [pc,  #12]	; 0x1008c <adr_var2>
```

The second instruction will load a value from \[pc + 12] to the r1 register. we can use the gef highlighting here to determine the location.

<figure><img src="https://3643148735-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FuoH6DVWgxRANBNbHnsUM%2Fuploads%2FCROPaZctMfwBT3iqZbmI%2Fr1.png?alt=media&#x26;token=07bf3bcb-4169-4f98-8f07-68e980796c62" alt=""><figcaption></figcaption></figure>

After stepping over the instruction r1 is filled with the memory address 0x0020094 which points to the value 4.

Now, look at the next two instructions.

```
0x1007c <_start+8>       ldr    r2,  [r0]
0x10080 <_start+12>      str    r2,  [r1]
```

The first instruction will load the value in \[r0] into the r2 register. The memory location in r0 points to the value 3 so 3 will be loaded into the r2 register.

<figure><img src="https://3643148735-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FuoH6DVWgxRANBNbHnsUM%2Fuploads%2Fn6YQNC7Rm6o2UAtmmYuc%2Fr2.png?alt=media&#x26;token=9e5f8be6-85b5-4f64-8841-73cce751f886" alt=""><figcaption></figcaption></figure>

The second instruction will store the value in r2 to the memory location pointed by r1. r2 now contains 0x3 so this will be loaded into the memory location: 0x00020094. So the value 4 will be updated with 3.&#x20;

<figure><img src="https://3643148735-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FuoH6DVWgxRANBNbHnsUM%2Fuploads%2F0FWPnGDfkTbq03eiPbKq%2Fr.png?alt=media&#x26;token=ba1e61ce-52b9-4cc3-9c9b-d91e34406be1" alt=""><figcaption></figcaption></figure>

The final "bkpt" instruction is used to put a breakpoint.

### Stack

Stack is one of the important data structures used in computers. it is a linear data structure that follows the LIFO principle. LIFO stands for "Last In First Out". In LIFO structures, the element that is added first can be removed last and vice versa.&#x20;

A pile of books arranged on top of each other is an example of a stack.

![](https://3643148735-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FuoH6DVWgxRANBNbHnsUM%2Fuploads%2FZ1JPPQwEkqp4KGbtkpqW%2Fimage.png?alt=media\&token=6cd40f4f-7b69-4cc3-96ae-b2eb963ade6b)

**The stack can be used to store local variables, return addresses, arguments, etc.** The topmost element of the stack represents the top of the stack. The stack pointer always points to the top of the stack. Insertion and deletion of elements happen at the top of the stack. Inserting an element in the stack is called a push operation. Deleting an element from the stack is called a pop operation. The stack grows from high memory to low memory.

There is **push and pop i**nstruction in ARM to insert and delete elements from the stack. Let's look at an example

```
push {r1}
pop {r3}
```

In the above example, the push instruction will push the value of the r1 register into the stack. Similarly, the pop instruction removes an element from the top of the stack and copies it to the r3 register.

Let's debug a simple program to understand it better.

```
.data
.text
.global _start
_start:
	mov r1,#1
	mov r2,#2
	mov r3,#3
	mov r4,#4
	push {r1}
	push {r1,r2}
	push {r3}
	pop {r3}
	pop {r3,r4}
	mov r7,#1
	svc 0

```

Let's assemble and link it.

```
as push-pop.s -o push-pop.o && ld push-pop.o -o push-pop
```

Load the program into gdb and put a breakpoint at "\_start" and start the execution.

<figure><img src="https://3643148735-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FuoH6DVWgxRANBNbHnsUM%2Fuploads%2FYSbEk5GGcbv6sB7pXZIh%2Fbp.png?alt=media&#x26;token=26e22306-13c3-4909-8c69-21fdcca6c315" alt=""><figcaption></figcaption></figure>

The first 4 mov instructions will copy the values 1,2,3,4 to the registers r1,r2,r3, and r4.

<figure><img src="https://3643148735-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FuoH6DVWgxRANBNbHnsUM%2Fuploads%2FNIe4o3UvXBiqAToHBjgS%2Fregisters.png?alt=media&#x26;token=6235a8ad-cae2-478f-a9d8-c9d8e06f768d" alt=""><figcaption></figcaption></figure>

Let's also see the stack before the push instructions.

<figure><img src="https://3643148735-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FuoH6DVWgxRANBNbHnsUM%2Fuploads%2FsMFIOSaTVXL3zhpTzTLX%2Fstackbefore.png?alt=media&#x26;token=fd0fe312-6165-4533-9682-55079d69338e" alt=""><figcaption></figcaption></figure>

The  "push {r1}" push the value in r1 into the top of the stack.

Let's step over the instruction using the "si" command.

<figure><img src="https://3643148735-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FuoH6DVWgxRANBNbHnsUM%2Fuploads%2FvGUIWin8UXpvbu9FlsEC%2Fsp.png?alt=media&#x26;token=1e2ee189-aad0-4b66-812d-5cdaf3f9b362" alt=""><figcaption></figcaption></figure>

Now the value 0x1 from the register r1 has been added to the top of the stack. The stack is decremented as the stack grows from a high address to a low address.

The "push {r1, r2}" will insert two values into the top of the stack.

r1 is  0x00000001 and r2 is 0x00000002. Let's see this.

<figure><img src="https://3643148735-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FuoH6DVWgxRANBNbHnsUM%2Fuploads%2FBHgEbWp3KUZV913eeMEp%2Fbarbar.png?alt=media&#x26;token=5dc49318-2f3e-4fac-b696-292375ddae33" alt=""><figcaption></figcaption></figure>

The final "push {r3}" will insert the value in r3 which is 3 into the top of the stack.

<figure><img src="https://3643148735-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FuoH6DVWgxRANBNbHnsUM%2Fuploads%2FoB8s6AYX1j7R5JWpDFbH%2Fr3.png?alt=media&#x26;token=bb8c284e-d1ef-4653-8f78-f10cf9964593" alt=""><figcaption></figcaption></figure>

The "pop {r3}" will remove one value from the top of the stack and copies it to r3.

Look at the stack state before execution.

<figure><img src="https://3643148735-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FuoH6DVWgxRANBNbHnsUM%2Fuploads%2Fg10vH1HVNDpaZopWfcgb%2Fr3state.png?alt=media&#x26;token=8085d126-f877-4d8b-80b6-987994bf8c38" alt=""><figcaption></figcaption></figure>

Let's step over the instruction.

<figure><img src="https://3643148735-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FuoH6DVWgxRANBNbHnsUM%2Fuploads%2FO2uo01wJZ4ddeWo52irn%2Fpopr3.png?alt=media&#x26;token=c5b767f4-44e9-4d28-b49c-e7218bdd29bc" alt=""><figcaption></figcaption></figure>

Now, r3 contains 0x3 and the top of the stack is incremented.

The Final "pop {r3, r4}" will pop the values 0x1 and 0x2 into the r3 and r4 register.

<figure><img src="https://3643148735-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FuoH6DVWgxRANBNbHnsUM%2Fuploads%2FkaDyrWzufYjn4RGMsLRM%2Ffinalstack.png?alt=media&#x26;token=15f94e52-888e-49c4-81de-277a01846ee7" alt=""><figcaption></figcaption></figure>

Now we can use the "c" command to continue to execution to exit the program.

### Functions

Functions contain a group of statements to execute a particular task. In ARM, **the first four arguments to a function are passed from registers r0 to r3. if there are more arguments they are passed through the stack. The return value is usually passed via the r0 register.**

After executing all the instructions in the function/subroutine the program execution should return to the caller to continue its further execution, this is done using a reference to the caller. This reference is called a **return address**. In ARM, the "lr" register is used to hold the return address.

Let's see a simple example of a function.

```c
#include <stdio.h>

int add(a,b){

return a+b;

}
void main(){

int a = 3; 
int b = 3;
add(a,b);

}
```

Compile this using gcc.

`gcc functions.c -o function`

Let's load the program into gdb.

Put a bp at the main and disassemble the main function.

`b main`

<figure><img src="https://3643148735-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FuoH6DVWgxRANBNbHnsUM%2Fuploads%2FOPEPF9UKtRmPf0LJxPYp%2Fdisassas.png?alt=media&#x26;token=270797ef-a11c-4b1a-9f40-06cd88d62587" alt=""><figcaption></figcaption></figure>

The first "push {r11,lr}" instruction will push the values of r11 (frame pointer) and lr into the stack. we will see a "push" instruction almost in all the functions. This is done to save the value of the registers into the stack so that the registers can be reused in the function. These values are restored back at the end of the function.

The "add r11, sp,#4"  instruction updates the frame pointer for the main function. The r11 is set to sp + 4 bytes.

The "sub sp, sp,#8" is used to allocate 8 bytes of space for the two local variables.

These first three instructions are called the **function prologue.**

<pre><code><strong>   0x00010418 &#x3C;+0>:	push	{r11, lr}
</strong>   0x0001041c &#x3C;+4>:	add	r11, sp, #4
   0x00010420 &#x3C;+8>:	sub	sp, sp, #8
</code></pre>

As there are two variables in the program.

```
int a = 3; 
int b = 3;
```

These will be stored in the memory location using the below instructions.

<figure><img src="https://3643148735-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FuoH6DVWgxRANBNbHnsUM%2Fuploads%2Fw3dYC1VFplSPTRVS065W%2Fvariables.png?alt=media&#x26;token=a924df4a-274e-485a-9c68-c833d4391b04" alt=""><figcaption></figcaption></figure>

The first value 3 is copied into the r3 register and is stored in the memory location : \[r11 - 8]. Similarly, the second value 3 is also copied to the r3 register and is stored in the adjacent memory location : \[r11 -12].

We can step over these instructions and confirm these using the examine command.

<figure><img src="https://3643148735-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FuoH6DVWgxRANBNbHnsUM%2Fuploads%2Fs13XutTMJEYH8uMdUG4X%2Fx3.png?alt=media&#x26;token=5ced325e-faf1-4e0a-883a-4853c25d51a2" alt=""><figcaption></figcaption></figure>

Next, we can see two "ldr" instructions. After this "ldr" instruction we can see a "branch" instruction. So these "ldr" instructions are used to load the arguments to the "add" function. These instructions will load our two values from the memory location into r0 and r1 registers. As per the ARM calling convention, the first four arguments will be passed through the registers r0 to r4. So our two values (3) will be passed via r0 and r1.&#x20;

<figure><img src="https://3643148735-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FuoH6DVWgxRANBNbHnsUM%2Fuploads%2F7db5xiYZjw2QaKc3PmaE%2Fsss.png?alt=media&#x26;token=50ede543-250f-4b70-a02c-c81055388417" alt=""><figcaption></figcaption></figure>

Also remember, the arguments are in the same order as in the source program. They are passed from left to right.

For example, Let's consider a function "abc" with three parameters.

<pre class="language-armasm"><code class="lang-armasm"><strong>#include &#x3C;stdio.h>
</strong><strong>int abc(int a,int b, int c){
</strong>return a;
}
void main(){
abc(1,2,3);
}
</code></pre>

So the arguments to the function are 1,2 and 3. This will be passed from left to right meaning that 1  will be passed via r0, 2 via r1, and 3 via r2.

<figure><img src="https://3643148735-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FuoH6DVWgxRANBNbHnsUM%2Fuploads%2F7db5xiYZjw2QaKc3PmaE%2Fsss.png?alt=media&#x26;token=50ede543-250f-4b70-a02c-c81055388417" alt=""><figcaption></figcaption></figure>

Let's focus back on our branch instruction seen in the program.

`0x1043c <main+36> bl 0x103e8`

So what are branch instructions?

Branch instructions are used to change the flow of execution. They can jump from one part of the code into another part of the code. This can be labels, functions, etc.

There are different types of branching instructions like b,blx,bl, etc. You can go through the ARM documentation to learn more about it.

{% embed url="https://developer.arm.com/documentation/ddi0406/c/Application-Level-Architecture/The-Instruction-Sets/Branch-instructions" %}

The "b" instruction will jump to a specified label or location.&#x20;

For example :

`b label`

The "bl" instruction is used to call a subroutine. This will also copy the address of the next instruction into the r14 (LR). So that "lr" will be used to hold the **return address.**

<figure><img src="https://3643148735-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FuoH6DVWgxRANBNbHnsUM%2Fuploads%2FLMS0mTxdhzEokpx9RjGO%2Fbl.png?alt=media&#x26;token=e8593295-ff05-4a25-b7b5-b81ab13c1521" alt=""><figcaption></figcaption></figure>

This branch instruction will copy the address of the next sub-instruction into LR. This is also known as the return address. We can step inside the add function using the "si" command.

Let's do that.

<figure><img src="https://3643148735-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FuoH6DVWgxRANBNbHnsUM%2Fuploads%2FBFwGxILgndIHVUj2wths%2Flr.png?alt=media&#x26;token=c8cade38-921b-4872-95a9-ac3c859c5689" alt=""><figcaption></figcaption></figure>

Now we are inside the "add" function.

If we look at the "lr" register. it is updated with the address of the next instruction after the branching instruction.

The first "push{r11}" will push the value of r11 into the top of the stack so that r11 can be reused without losing its value. The second instructions are the same instructions we saw in the main function. it sets up the frame pointer and allocates the space to store the passed arguments.

```armasm
      0x103f4 <add+12>         str    r0,  [r11,  #-8]
      0x103f8 <add+16>         str    r1,  [r11,  #-12]
      0x103fc <add+20>         ldr    r2,  [r11,  #-8]
      0x10400 <add+24>         ldr    r3,  [r11,  #-12]
```

These above four instructions stores the arguments into the specified locations and loads them again into different registers. After executing these instructions r2 and r3 will contain the value 3.

<figure><img src="https://3643148735-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FuoH6DVWgxRANBNbHnsUM%2Fuploads%2FsLRQWHjJ1rqjEZ9Evz4e%2Fregisters.png?alt=media&#x26;token=6ce7d50c-17f1-4f3a-a7dc-cc0dfd00de98" alt=""><figcaption></figcaption></figure>

The next  "add r3, r2, r3"  will add r2 and r3 stores the result in r3.

So r3 = 3 + 3  = 6

<figure><img src="https://3643148735-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FuoH6DVWgxRANBNbHnsUM%2Fuploads%2FeWdQO7v2E5ZyW7mfI6P0%2Fres.png?alt=media&#x26;token=e1e31e33-882f-421b-9ca2-b8d27b68d79d" alt=""><figcaption></figcaption></figure>

The "mov r0, r3" will copy the result into the r0 register.The r0 register usually holds the return value.

<figure><img src="https://3643148735-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FuoH6DVWgxRANBNbHnsUM%2Fuploads%2F97Waq9Zm6ND5pqDWiBkH%2Fr0.png?alt=media&#x26;token=fff4bd76-2d20-4933-b97c-423a79917d0e" alt=""><figcaption></figcaption></figure>

```armasm
      0x1040c <add+36>         sub    sp,  r11,  #0
      0x10410 <add+40>         pop    {r11}		; (ldr r11,  [sp],  #4)
      0x10414 <add+44>         bx     lr
```

The three instructions are called **function epilogue.**

The "sub rp,r11, #0" will clean up the stack. it clears the allocated space for the function.

<figure><img src="https://3643148735-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FuoH6DVWgxRANBNbHnsUM%2Fuploads%2FYoYhVesUyOVQpvpEctpB%2Fclearedstack.png?alt=media&#x26;token=7d9ee020-594f-4d75-8bc7-16a9e3415ae7" alt=""><figcaption></figcaption></figure>

&#x20;The "pop{11}" will pop the value from the top of the stack which was saved at the beginning of the function.

<figure><img src="https://3643148735-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FuoH6DVWgxRANBNbHnsUM%2Fuploads%2FMdWnl2arpBVpw0gBA3AX%2Fr11.png?alt=media&#x26;token=0bf7394a-50e6-482e-b598-940ae02150f1" alt=""><figcaption></figcaption></figure>

&#x20;Lastly, the "bx lr" instruction will branch to the return address in the link register to return back to the main function. The pc will be updated to point to the next instruction after the branch instruction.&#x20;

Let's step over to return back to the main function.

<figure><img src="https://3643148735-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FuoH6DVWgxRANBNbHnsUM%2Fuploads%2FW6VAc6QcPYINEqwOibXy%2Fblan.png?alt=media&#x26;token=e8c1e80e-8776-4dd1-9fe0-4547aa2cb6ad" alt=""><figcaption></figcaption></figure>

Now we are back at the main function. The pc points to the next instruction to be executed.

The "sub sp, r11, #4" will clean the stack and update the stack pointer.

<figure><img src="https://3643148735-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FuoH6DVWgxRANBNbHnsUM%2Fuploads%2Fwzuh72ok4T6RsP42W3Dt%2Fssss.png?alt=media&#x26;token=63e119f0-a310-4442-8a1d-32e9fa739d46" alt=""><figcaption></figcaption></figure>

The last pop instruction will pop two values from the stack to r11 and pc. The second value that is popped into pc is the exit function.

<figure><img src="https://3643148735-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FuoH6DVWgxRANBNbHnsUM%2Fuploads%2FKSuzh3z1VNIHzDN4vbAs%2Fexit.png?alt=media&#x26;token=63cc1e4d-3d7e-4a3f-aa83-eea1713190a7" alt=""><figcaption></figcaption></figure>

Let's enter the "c"  command to continue the execution to exit the program.

<figure><img src="https://3643148735-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FuoH6DVWgxRANBNbHnsUM%2Fuploads%2FQhXAn3EYq9U4fvDGOIwT%2Fbarbar.png?alt=media&#x26;token=34de46a6-06c2-4e50-8c9e-c0b800c8cdcc" alt=""><figcaption></figcaption></figure>

### Conclusion

This chapter was an introduction to ARM32 architecture. we briefly discussed the Architecture of ARM32. We looked into registers, instructions, Stack, function, etc. From the next chapter onwards we will start our exploitation side. We will highly require the concepts learned in this chapter in the next chapters.
