owned this note
owned this note
Published
Linked with GitHub
# Lab2: RISC-V RV32I[MA] emulator with ELF support : pow function
###### tags: `RISC-V`
## Rewrite POW function in C
```cpp
int _start()
{
int base = 5;
int exponent = 3;
int result = 1;
for(exponent; exponent>0;exponent--)
{
result = result * base;
}
int Value = result;
volatile char* tx = (volatile char*) 0x40002000;
int out = Value;
*tx = out;
return 0;
}
```
I got an experience on the other Lab2, therefore, I write in iterative method, which is not functional.
---
using command below to makefile
cf with gcc: gcc produce elf file for c, the other produce elf file for riscv
```
riscv-none-embed-gcc -march=rv32i -mabi=ilp32 -O3 -nostdlib pow.c -o pow
```
### run it
```
dc@dc-VirtualBox:~/rv32emu$ ./emu-rv32i pow
}
>>> Execution time: 3097 ns
>>> Instruction count: 6 (IPS=1937358)
>>> Jumps: 1 (16.67%) - 0 forwards, 1 backwards
>>> Branching T=0 (-nan%) F=0 (-nan%)
```
I was shocked by the NaN message. Then I know, it's because they set it as your count is 0. We don't want anything divided by 0.
---
### objdump
```shell
dc@dc-VirtualBox:~/rv32emu$ riscv-none-embed-objdump -d pow
pow: file format elf32-littleriscv
Disassembly of section .text:
00010054 <_start>:
10054: 400027b7 lui a5,0x40002
10058: 07d00713 li a4,125
1005c: 00e78023 sb a4,0(a5) # 40002000 <__global_pointer$+0x3fff0798>
10060: 00000513 li a0,0
10064: 00008067 ret
```
I was quite surprising that it's only 6 instructions.
Then I figure out it was the optimization by compiler.
---
### readelf
```
dc@dc-VirtualBox:~/rv32emu$ riscv-none-embed-readelf -h pow
ELF Header:
Magic: 7f 45 4c 46 01 01 01 00 00 00 00 00 00 00 00 00
Class: ELF32
Data: 2's complement, little endian
Version: 1 (current)
OS/ABI: UNIX - System V
ABI Version: 0
Type: EXEC (Executable file)
Machine: RISC-V
Version: 0x1
Entry point address: 0x10054
Start of program headers: 52 (bytes into file)
Start of section headers: 484 (bytes into file)
Flags: 0x0
Size of this header: 52 (bytes)
Size of program headers: 32 (bytes)
Number of program headers: 1
Size of section headers: 40 (bytes)
Number of section headers: 6
Section header string table index: 5
```
---
### size
```
dc@dc-VirtualBox:~/rv32emu$ riscv-none-embed-size pow
text data bss dec hex filename
20 0 0 20 14 pow
```
---
### [Assembly code credit to 李佶龍](https://hackmd.io/JJtYOroGRL2UWdjE4LDopw?view)
```
.text
main:
# Load arguments from static data
lw a0, argument1
lw a1, argument2
# Jump-and-link to the 'pow' label
jal ra, pow
# Print the result to console
add a2, a0, zero
lw a0, argument1
lw a1, argument2
jal ra, printResult
#Exit program
li a0, 10
ecall
```
## Note:
### sp = stack pointer
The default of riscv emulator does not allow we change sp(cauz we would ket it lower than 0). In this case, I got a wrong simulation in the oter code.
This problem I do not fix until I check that file and asking others. I think reading that file is quite time consuming.
### Report from this Lab2