mit-pdos / xv6-riscv

Xv6 for RISC-V
Other
6.63k stars 2.4k forks source link

Exit from start() by restoring the sp correctly, before jumping to main() #63

Open streetdogg opened 3 years ago

streetdogg commented 3 years ago

using asm volatile("mret") in start() leads to a jump to main() before the stack pointer is adjusted back by 16. Result is wasted 16 bytes.

Without the fix:

│   0x800000e6 <start+88>           mv      tp,a5
│   0x800000e8 <start+90>           mret    # jump to main() here
│   0x800000ec <start+94>           ld      ra,8(sp)
│   0x800000ee <start+96>           ld      s0,0(sp)
│   0x800000f0 <start+98>           addi    sp,sp,16
│   0x800000f2 <start+100>          ret

With the fix:

│   0x800000e4 <start+82>           csrr    a5,mhartid
│   0x800000e8 <start+86>           sext.w  a5,a5
│   0x800000ea <start+88>           mv      tp,a5
│   0x800000ec <start+90>           ld      ra,8(sp)
│   0x800000ee <start+92>           ld      s0,0(sp)
│   0x800000f0 <start+94>           addi    sp,sp,16
│   0x800000f2 <start+96>           ret

Return address (ra) when in start()

│ra             0x8000001a       0x8000001a <_entry+26>

Instruction at 0x8000001a

│   0x8000001a <_entry+26>          mret  # jump to main here (from within _entry)

Signed-off-by: Piyush Itankar pitankar@gmail.com