I'm making a RISC-V 64bit emulator and I'm adding ELF file support to it. I read somewhere that you're supposed to allocate a stack and set a pointer to it in the SP register, along with setting the GP register to where the .data section was allocated. However when making some test C++ files to run, I've found that sometimes g++ doesn't include a .data section in the output ELF file, while also trying to access the GP register for reading/writing. I tried looking at the RISCV ABI and linker documentation and for any default value that it could be set to, but I've found nothing. What should it be set to?
Asked
Active
Viewed 26 times
1
Ari
- 31
- 4
-
I'd expect `0` (nullptr) would be a valid choice, if you want to avoid leaving uninitialized garbage there. Presumably programs with no `.data` or `.bss` won't use that register to access static data at all? Have you tried running such files in existing RISC-V emulators like QEMU? QEMU can act as a GDB remote, or you could write a program that stores that reg to the stack and makes a `write` system call to output the bytes (pipe into hexdump). – Peter Cordes Aug 31 '23 at 22:20
-
Also note that *running* a program should only depend on the ELF *program* headers (which define segments that don't have names), not the ELF *section* headers. [What's the difference of section and segment in ELF file format](https://stackoverflow.com/q/14361248) I hope you actually mean a read+write segment with non-zero virtual size, backed by zero or more bytes of the executable file. (vsize > filesz is BSS space). Unless RISC-V is different and executables do need a section header for kernels to set `GP` for them? Or is that something that `_start` CRT startup code normally does? – Peter Cordes Aug 31 '23 at 22:22
-
[The ABI](https://github.com/riscv-non-isa/riscv-elf-psabi-doc/blob/30746d44ed68b83c37a1d19fc088c40bc3b6636a/riscv-elf.adoc?plain=1#L497) says it gets set to the value of the `__global_pointer$` symbol. You could read your linker scripts to determine how that is set if there's no `.data`. – Nate Eldredge Sep 02 '23 at 20:08