[PATCH v4] riscv: Prevent NULL pointer dereference in machine_kexec_prepare

From: Tao Liu

Date: Fri Jul 03 2026 - 07:28:03 EST


A NULL pointer dereference issue is noticed in riscv's machine_kexec_prepare(),
where image->segment[i].buf might be NULL and copied unchecked.

The NULL buf comes from ima_add_kexec_buffer(), where kbuf is added by
kexec_add_buffer(), but kbuf.buffer is NULL, then it is copied without
a check in machine_kexec_prepare().

Relevant path:

kexec_file_load
-> kimage_file_alloc_init()
-> kimage_file_prepare_segments()
-> ima_add_kexec_buffer()
-> kexec_add_buffer()
-> machine_kexec_prepare()
-> memcpy()

Address this by adding a check before the data copy attempt.

Fixes: b7fb4d78a6ad ("RISC-V: use memcpy for kexec_file mode")
Cc: stable@xxxxxxxxxxxxxxx
Closes: https://lore.kernel.org/kexec/CAO7dBbVftLUhd2qrh7hmijTB3PEPfZAhykCGqEfrPoOcSrrj-w@xxxxxxxxxxxxxx/
Acked-by: Baoquan He <bhe@xxxxxxxxxx>
Acked-by: Pratyush Yadav <pratyush@xxxxxxxxxx>
Reviewed-by: Nutty Liu <nutty.liu@xxxxxxxxxxx>
Signed-off-by: Tao Liu <ltao@xxxxxxxxxx>
---
v4 -> v3: 1) Remove code comment.
2) Replace (buf == NULL) to (!buf).
3) Reword commit message.

link to v1: https://lore.kernel.org/linux-riscv/20260529032739.13264-2-ltao@xxxxxxxxxx/
link to v2: https://lore.kernel.org/linux-riscv/20260627222602.23594-2-ltao@xxxxxxxxxx/
link to v3: https://lore.kernel.org/linux-riscv/20260701025732.66330-2-ltao@xxxxxxxxxx/
---
arch/riscv/kernel/machine_kexec.c | 3 +++
1 file changed, 3 insertions(+)

diff --git a/arch/riscv/kernel/machine_kexec.c b/arch/riscv/kernel/machine_kexec.c
index 2306ce3e5f22..738df176ff6f 100644
--- a/arch/riscv/kernel/machine_kexec.c
+++ b/arch/riscv/kernel/machine_kexec.c
@@ -41,6 +41,9 @@ machine_kexec_prepare(struct kimage *image)
if (image->segment[i].memsz <= sizeof(fdt))
continue;

+ if (!image->segment[i].buf)
+ continue;
+
if (image->file_mode)
memcpy(&fdt, image->segment[i].buf, sizeof(fdt));
else if (copy_from_user(&fdt, image->segment[i].buf, sizeof(fdt)))
--
2.54.0