From 252d68ff9f5d155cc4eda331d414d35b2edb4e7e Mon Sep 17 00:00:00 2001 From: Dino Li Date: Tue, 23 May 2023 11:55:43 +0800 Subject: [PATCH] arch/riscv: add support for detecting null pointer exception using PMP This change uses a PMP slot to implement null pointer detection. Signed-off-by: Dino Li --- arch/riscv/Kconfig | 21 +++++++++++++++++++++ arch/riscv/core/pmp.c | 11 +++++++++++ 2 files changed, 32 insertions(+) diff --git a/arch/riscv/Kconfig b/arch/riscv/Kconfig index 7e3eb967957..20faced0ca8 100644 --- a/arch/riscv/Kconfig +++ b/arch/riscv/Kconfig @@ -261,6 +261,27 @@ config PMP_STACK_GUARD_MIN_SIZE wiggle room to accommodate the eventual overflow exception stack usage. +# Implement the null pointer detection using the Physical Memory Protection +# (PMP) Unit. +config NULL_POINTER_EXCEPTION_DETECTION_PMP + bool "Use PMP for null pointer exception detection" + depends on RISCV_PMP + help + Null pointer dereference detection implemented + using PMP functionality. + +if NULL_POINTER_EXCEPTION_DETECTION_PMP + +config NULL_POINTER_EXCEPTION_REGION_SIZE + hex "Inaccessible region to implement null pointer detection" + default 0x10 + help + Use a PMP slot to make region (starting at address 0x0) inaccessible for + detecting null pointer dereferencing (raising a CPU access fault). + Minimum is 4 bytes. + +endif # NULL_POINTER_EXCEPTION_DETECTION_PMP + endmenu config MAIN_STACK_SIZE diff --git a/arch/riscv/core/pmp.c b/arch/riscv/core/pmp.c index 7fbf1fa533f..b8ddd1c3203 100644 --- a/arch/riscv/core/pmp.c +++ b/arch/riscv/core/pmp.c @@ -330,6 +330,17 @@ void z_riscv_pmp_init(void) (size_t)__rom_region_size, pmp_addr, pmp_cfg, ARRAY_SIZE(pmp_addr)); +#ifdef CONFIG_NULL_POINTER_EXCEPTION_DETECTION_PMP + /* + * Use a PMP slot to make region (starting at address 0x0) inaccessible + * for detecting null pointer dereferencing. + */ + set_pmp_entry(&index, PMP_NONE | PMP_L, + 0, + CONFIG_NULL_POINTER_EXCEPTION_REGION_SIZE, + pmp_addr, pmp_cfg, ARRAY_SIZE(pmp_addr)); +#endif + #ifdef CONFIG_PMP_STACK_GUARD /* * Set the stack guard for this CPU's IRQ stack by making the bottom