riscv-software-src / riscv-tools

RISC-V Tools (ISA Simulator and Tests)
1.14k stars 447 forks source link

How to compile a elf with matched call/ret(shadow stack)? #137

Closed Readm closed 6 years ago

Readm commented 6 years ago

Hello, I'm trying to make a hardware support which fits the shadow stack.

Since in riscv, there is only jalr. I follow the RAS rule in the riscv-spec-v2.2, i.e. when rd = x1/x5, its a call, when rs= x1/x5, its a ret.

Now i want test normal programs in my implementation. But how to compile a c file into an ELF file with matched call and ret?

What should I focus on? riscv-llvm or gcc?

I've tried llvm to compile the c file, but after link step, it seems that the code in libraries is not compiled by llvm(and failed), and I don't know whether the llvm generates the call-ret matched code.

I know it might be unsuitable to ask it here, but I don't know where to get help. Sorry.

Thanks for any suggestions.

palmer-dabbelt commented 6 years ago

This should all just happen by default. Here's a very small example -- note that the program itself doesn't make any sense, it's just the smallest thing I could come up with to generate a function call. The call is the jal at 0x10060, while the return is the jalr at 0x1007c.

$ cat start.c 
int func(int a);

int _start(int b)
{ return 2 + func(b + 3); }
$ cat func.c 
int func(int a)
{ return a + 1; }
$ riscv64-unknown-elf-gcc start.c func.c -o test -O3 -nostartfiles -march=rv32i -mabi=ilp32
$ riscv64-unknown-elf-objdump -d test -M no-aliases

test:     file format elf32-littleriscv

Disassembly of section .text:

00010054 <_start>:
   10054:   ff010113            addi    sp,sp,-16
   10058:   00350513            addi    a0,a0,3
   1005c:   00112623            sw  ra,12(sp)
   10060:   018000ef            jal ra,10078 <func>
   10064:   00c12083            lw  ra,12(sp)
   10068:   00250513            addi    a0,a0,2
   1006c:   01010113            addi    sp,sp,16
   10070:   00008067            jalr    zero,0(ra)

00010078 <func>:
   10078:   00150513            addi    a0,a0,1
   1007c:   00008067            jalr    zero,0(ra)

For future reference, this is probably a better question for something like Stack Overflow, the SiFive forums, or the RISC-V software mailing list.

Readm commented 6 years ago

@palmer-dabbelt Thank you. As far as I've tested, the mismatch seems happens in the default libraries linked by riscv64-unknown-elf-gcc. It's not suitable to compile programs without the libraries, I may study further about the riscv tool chain and try to recompile the libs, maybe. Thank you for your answer.