[PATCH v4 1/1] firmware: Initialize stack guard via Zkr

Xiang W wxjstz at 126.com
Sat Jan 3 21:18:10 PST 2026


Try to initialize stack protection guard via the zkr extension.

Signed-off-by: Xiang W <wxjstz at 126.com>
---
 firmware/fw_base.S           | 24 ++++++++++++++++++++++++
 include/sbi/riscv_encoding.h | 10 ++++++++++
 2 files changed, 34 insertions(+)

diff --git a/firmware/fw_base.S b/firmware/fw_base.S
index bce9e226..63bb4473 100644
--- a/firmware/fw_base.S
+++ b/firmware/fw_base.S
@@ -107,6 +107,30 @@ _bss_zero:
 	add	s4, s4, __SIZEOF_POINTER__
 	blt	s4, s5, _bss_zero
 
+	/* Trying to initialize the stack guard via the Zkr extension */
+	lla	t0, __stack_chk_guard_done
+	csrw	CSR_MTVEC, t0
+	li	t0, 0
+	li	t3, SEED_OPTS_ES16
+	li	t4, SEED_ENTROPY_MASK
+	li	t5, __SIZEOF_POINTER__
+__stack_chk_guard_loop:
+	csrrw	t1, CSR_SEED, x0
+	li	t2, SEED_OPTS_MASK
+	and	t2, t2, t1
+	bgtu	t2, t3, __stack_chk_guard_done
+	bltu	t2, t3, __stack_chk_guard_loop
+	and	t1, t1, t4
+	slli	t0, t0, 16
+	or	t0, t0, t1
+	addi	t5, t5, -2
+	bgtz	t5, __stack_chk_guard_loop
+	lla	t1, __stack_chk_guard
+	REG_S	t0, 0(t1)
+	j	__stack_chk_guard_done
+	.align 3
+__stack_chk_guard_done:
+
 	/* Setup temporary trap handler */
 	lla	s4, _start_hang
 	csrw	CSR_MTVEC, s4
diff --git a/include/sbi/riscv_encoding.h b/include/sbi/riscv_encoding.h
index b5a4ce81..3c1d5256 100644
--- a/include/sbi/riscv_encoding.h
+++ b/include/sbi/riscv_encoding.h
@@ -261,6 +261,16 @@
 #define CSR_FRM				0x002
 #define CSR_FCSR			0x003
 
+/* User entropy source */
+#define CSR_SEED			0x015
+#define SEED_OPTS_SHIFT			30
+#define SEED_OPTS_MASK			(_UL(3) << SEED_OPTS_SHIFT)
+#define SEED_OPTS_BIST			(_UL(0) << SEED_OPTS_SHIFT)
+#define SEED_OPTS_WAIT			(_UL(1) << SEED_OPTS_SHIFT)
+#define SEED_OPTS_ES16			(_UL(2) << SEED_OPTS_SHIFT)
+#define SEED_OPTS_DEAD			(_UL(3) << SEED_OPTS_SHIFT)
+#define SEED_ENTROPY_MASK		0xffff
+
 /* User Counters/Timers */
 #define CSR_CYCLE			0xc00
 #define CSR_TIME			0xc01
-- 
2.47.3




More information about the opensbi mailing list