Danijel-Korent / RISC-V-emulator

A small exercise to learn RISC-V ISA
MIT License
5 stars 1 forks source link

generate my own linux image and run elf file #1

Open Be997398715 opened 8 months ago

Be997398715 commented 8 months ago

Hi, this is an exciting project. I have two questions:

  1. How do I create my own linux image? Are there any tutorials or materials?
  2. What should I do if I need to use your project to simulate elf files that I wrote and generated from riscv-tool-chain compiler? What should I pay attention to? Hope for you reply.
Danijel-Korent commented 7 months ago

Hi! Sorry for the late reply.

I've generated the image by using another project, the "mini-rv32ima", which also simulates RISC-V, but in C language. That project is in a more advanced stage because it can read the keyboard input, therefore it is interactive! The "mini-rv32ima" could be more helpful to you because it runs much much faster, but I find the code hard to read.

That project builds the image using buildroot + custom config for μClinux

Just clone the repo (https://github.com/cnlohr/mini-rv32ima/) and run "make everything"

You can see more about the image generation process in the Makefile: https://github.com/cnlohr/mini-rv32ima/blob/master/Makefile

I believe the author used another "Buidroot" repo as a baseline for his own: https://github.com/regymm/buildroot

There is also a tutorial on how to make MMU-less Linux for RISC-V: https://popovicu.com/posts/789-kb-linux-without-mmu-riscv/

But in the end, you can just do "make everything" from cnlohr's repo, that's what I have done to have more time for the actual emulator development

About simulating ELF files:

a) With the whole Linux OS

Include the ELF file into the ramdisk/rootfs of the Kernel image. And modify the rootfs's "init" script to automatically run the elf, or just run it manually in the "mini-rv32ima" project).

This probably requires just copying the ELF file into the folder https://github.com/cnlohr/mini-rv32ima/tree/master/configs/rootfsoverlay

b) Without Linux OS

1) You will need to manually parse the ELF file and copy text/data/bss memory segments into the emulator's memory and then start executing from the "Program Entry Point" that is defined in the ELF file

2) You will need to simulate the Linux's OS system calls if you want to have I/O. The "ecall" instruction will need to simulate open/read/write/mmap/brk/fork and similar, instead of jumping somewhere. For example when the ELF binary calls "write" system call to file descriptor 1 (stdout) the emulator should print the buffer content, and on system call "read" on file descriptor 0 (stdin) the emulator should fill it with input from the keyboard

I hope this helps!