[PATCH 2/2] lib: sbi: pmp: do not grant a NAPOT block outside the caller's range
liutong
liutong at iscas.ac.cn
Thu Nov 19 07:55:11 PST 2026
sbi_hart_smepmp_temp_map_range() grows the PMP order until one naturally
aligned block contains the requested range. The block is aligned down,
so it can extend below the range the caller validated, and nothing
checks the result.
The entry has the lowest index, which gives it the highest priority, and
it is programmed with the Smepmp shared-data encoding, which grants
execute permission to no mode. A block that reaches the firmware
therefore takes M-mode's execute permission on its own text away, and
the hart faults on the next instruction fetch. mtvec points into the
same text, so the trap entry faults as well and the hart stops without
a diagnostic.
Both the base and the size come from the caller. A size of zero is a
legal request that makes addr + size - 1 wrap and forces a block below
addr, so return early for it rather than declining it.
Reject a block that is not entirely within what S-mode may access.
Fixes: 6e44ef686a9b ("lib: sbi: Add functions to map/unmap shared memory")
Signed-off-by: liutong <liutong at iscas.ac.cn>
---
lib/sbi/sbi_hart_pmp.c | 19 +++++++++++++++++--
1 file changed, 17 insertions(+), 2 deletions(-)
diff --git a/lib/sbi/sbi_hart_pmp.c b/lib/sbi/sbi_hart_pmp.c
index c530739f..578b13df 100644
--- a/lib/sbi/sbi_hart_pmp.c
+++ b/lib/sbi/sbi_hart_pmp.c
@@ -23,7 +23,7 @@ static int hart_pmp_read(pmp_t *pmp, unsigned int n)
/* check parameters */
if (n >= PMP_COUNT)
- return SBI_EINVAL;
+ return SBI_EFAIL;
/* calculate PMP register and offset */
#if __riscv_xlen == 32
@@ -51,7 +51,7 @@ static int hart_pmp_write(pmp_t *pmp, unsigned int n)
/* check parameters */
if (n >= PMP_COUNT)
- return SBI_EINVAL;
+ return SBI_EFAIL;
/* calculate PMP register and offset */
#if __riscv_xlen == 32
@@ -337,6 +337,10 @@ static int sbi_hart_smepmp_temp_map_range(struct sbi_scratch *scratch,
if (sbi_hart_is_pmp_enabled(SBI_SMEPMP_RESV_ENTRY))
return SBI_ENOSPC;
+ /* An empty range needs no entry, and addr + size - 1 would wrap. */
+ if (!size)
+ return SBI_OK;
+
for (order = MAX(sbi_hart_pmp_log2gran(scratch), log2roundup(size));
order <= __riscv_xlen; order++) {
if (order < __riscv_xlen) {
@@ -351,6 +355,17 @@ static int sbi_hart_smepmp_temp_map_range(struct sbi_scratch *scratch,
}
}
+ /*
+ * The block is aligned down, so it can reach below the range the
+ * caller validated. It is programmed into the lowest numbered PMP
+ * entry and carries no execute permission, so a block that covers
+ * the firmware revokes M-mode's access to its own text.
+ */
+ if (!sbi_domain_check_addr_range(sbi_domain_thishart_ptr(), base,
+ 1UL << order, PRV_S,
+ SBI_DOMAIN_READ | SBI_DOMAIN_WRITE))
+ return SBI_EFAIL;
+
sbi_platform_pmp_set(sbi_platform_ptr(scratch), SBI_SMEPMP_RESV_ENTRY,
SBI_DOMAIN_MEMREGION_SHARED_SURW_MRW,
pmp_flags, base, order);
--
2.34.1
More information about the opensbi
mailing list