Skip to contentSkip to conversation

kexec: Use BPF lskel to enable kexec to load PE format boot image

PATCH Superseded Pingfan Liu 4 participants 30 messages Jan 19 – Feb 27

Subsystems (8)

v6 of 7 Superseded Latest is v7 →

lore
Share & tools
lore
#0 lore raw

v6 cover kexec: Use BPF lskel to enable kexec to load PE format boot image

*** The history ***

Nowadays, UEFI PE bootable images are becoming increasingly popular among distributions. Currently, we have several kinds of image format parsers in user space (kexec-tools). However, this approach breaks the integrity protection of the images. To address this integrity protection concern, several approaches have been proposed to resolve this issue, but none of them have been accepted upstream yet.

The summary of those approaches:
-1. UEFI service emulator for UEFI stub
-2. PE format parser in kernel
-3. Signing the arm64/boot/Image

For the first approach, I tried a purgatory-style emulator [1], but it encounters hardware scaling issues. For the second approach, both zboot-format [2] and UKI-format [3] parsers were rejected due to concerns that variant format parsers would bloat the kernel code. Additionally, for example in arm64, both UKI and zboot format parsers would need to be introduced and chained together to handle image loading. For the third approach, I attempted [4], but since zboot or UKI images already have signatures, upstream maintainers dislike the additional signature on the Image. Moreover, for secure boot UKI, this method cannot use signatures to protect the initramfs.

*** The approach in this series ***

This series introduces an approach that allows image formats to be parsed by BPF programs. As a result, the kexec kernel code can remain relatively stable without introducing new parsers for different architectures. This approach introduces a dedicated '.bpf' section in the PE file, which stores BPF bytecode. The integrity of all components -- kernel, initramfs, cmdline, and even the BPF bytecode itself is protected by the PE file's signature. After signature verification, the BPF bytecode is loaded and executed from within the kernel using BPF lskel. Therefore, the bytecode itself is protected from malicious attacks on the BPF loader in user space.

When a .bpf section is extracted from the current image file, its bytecode is attached to the kexec kernel function kexec_image_parser_anchor(). After the bytecode parses the image, the next-stage image is prepared, and the bytecode in the new .bpf section can be attached to kexec_image_parser_anchor(). In this way, nested image format issues (e.g., zboot image within UKI on arm64) can be resolved. (Theoretically not yet tested.)

*** Thanks ***
I would like to thank Philipp Rudo, whose insights inspired this approach and who dedicated significant time to evaluating its practicality. I am also grateful to Viktor Malik for his guidance on using BPF light skeleton to prevent malicious attacks from user space.

*** Test approach ***
-1. compile kernel
-2. get the zboot image with bpf-prog by 'make -C tools/kexec zboot' -3. compile kexec-tools from https://github.com/pfliu/kexec-tools/tree/pe_bpf

The rest test process is the common convention to use kexec.

[1]: https://lore.kernel.org/lkml/[email protected]/T/
[2]: https://lore.kernel.org/kexec/[email protected]/
[3]: https://lore.kernel.org/lkml/[email protected]/
[4]: https://lore.kernel.org/linux-efi/[email protected]/

*** Changes ***
v5 -> v6
- Re-organize the layers in kexec_file_load into two layers: format-parsing and kernel boot protocol handling.
- Simplify the bpf kfunc interface.
- rebased onto Linux 6.19-rc2

v4 -> v5
- rebased onto Linux 6.17-rc2
- [1/12], use a separate CONFIG_KEEP_COMPRESSOR to decide the section of decompressor method
- [10/12], add Catalin's acked-by (Thanks Catalin!)

v3 -> v4
- Use dynamic allocator in decompression ([4/12])
- Fix issue caused by Identical Code Folding ([5/12])
- Integrate the image generator tool in the kernel tree ([11,12/12])
- Address the issue according to Philipp's comments in v3 reviewing. Thanks Philipp!

RFCv2 -> v3
- move the introduced bpf kfuncs to kernel/bpf/* and mark them sleepable
- use listener and publisher model to implement bpf_copy_to_kernel()
- keep each introduced kfunc under the control of memcg

RFCv1 -> RFCv2
- Use bpf kfunc instead of helper
- Use C source code to generate the light skeleton file

---
Pingfan Liu (13):
bpf: Introduce kfuncs to parser buffer content
kexec_file: Move signature validation ahead
kexec_file: Introduce routines to parse PE file
kexec_file: Use bpf-prog to decompose image lib/decompress: Keep decompressor when CONFIG_KEEP_DECOMPRESSOR
kexec_file: Implement decompress method for parser
kexec_file: Implement copy method for parser
kexec_file: Introduce a bpf-prog lskel to parse PE file
kexec_file: Factor out routine to find a symbol in ELF
kexec_file: Integrate bpf light skeleton to load image with bpf-prog arm64/kexec: Select KEXEC_BPF to support UEFI-style kernel image tools/kexec: Introduce a bpf-prog to parse zboot image format tools/kexec: Add a zboot image building tool

 arch/arm64/Kconfig                           |   1 +
 include/linux/bpf.h                          |  19 +
 include/linux/decompress/mm.h                |   8 +
 kernel/Kconfig.kexec                         |   8 +
 kernel/Makefile                              |   2 +
 kernel/bpf/Makefile                          |   3 +
 kernel/bpf/bpf_buffer_parser.c               | 170 +++++++
 kernel/kexec_bpf/Makefile                    |  70 +++
 kernel/kexec_bpf/kexec_pe_parser_bpf.c       |  12 +
 kernel/kexec_bpf/kexec_pe_parser_bpf.lskel.h | 130 ++++++
 kernel/kexec_bpf/template.c                  |  68 +++
 kernel/kexec_bpf_loader.c                    | 439 +++++++++++++++++++
 kernel/kexec_file.c                          | 106 +++--
 kernel/kexec_internal.h                      |   5 +
 kernel/kexec_uefi_app.c                      |  81 ++++
 lib/Kconfig                                  |   6 +
 lib/decompress.c                             |   6 +-
 tools/kexec/Makefile                         |  91 ++++
 tools/kexec/pe.h                             | 177 ++++++++
 tools/kexec/template.c                       |  68 +++
 tools/kexec/zboot_image_builder.c            | 278 ++++++++++++
 tools/kexec/zboot_parser_bpf.c               | 114 +++++
 22 files changed, 1813 insertions(+), 49 deletions(-)
 create mode 100644 kernel/bpf/bpf_buffer_parser.c
 create mode 100644 kernel/kexec_bpf/Makefile
 create mode 100644 kernel/kexec_bpf/kexec_pe_parser_bpf.c
 create mode 100644 kernel/kexec_bpf/kexec_pe_parser_bpf.lskel.h
 create mode 100644 kernel/kexec_bpf/template.c
 create mode 100644 kernel/kexec_bpf_loader.c
 create mode 100644 kernel/kexec_uefi_app.c
 create mode 100644 tools/kexec/Makefile
 create mode 100644 tools/kexec/pe.h
 create mode 100644 tools/kexec/template.c
 create mode 100644 tools/kexec/zboot_image_builder.c
 create mode 100644 tools/kexec/zboot_parser_bpf.c
Signature · 1 line
2.49.0
#1 lore raw

PATCH v6 1/13 bpf: Introduce kfuncs to parser buffer content

In the security kexec_file_load case, the buffer holding the kernel image should not be accessible from userspace.

Typically, BPF data flow occurs between user space and kernel space in either direction. However, the above case presents a unique scenario where the kernel, instead of a user task, reads data from a file, passes it to a BPF program for parsing, and finally stores the parsed result.

This requires a mechanism to channel the intermediate data from the BPF program directly to the kernel. BPF buffer parser kfuncs are introduced to serve this purpose:

BTF_ID_FLAGS(func, bpf_get_parser_context, KF_ACQUIRE | KF_RET_NULL) BTF_ID_FLAGS(func, bpf_put_parser_context, KF_RELEASE) BTF_ID_FLAGS(func, bpf_buffer_parser, KF_TRUSTED_ARGS | KF_SLEEPABLE)

where bpf_get_parser_context() and bpf_put_parser_context() manage the trusted argument, and bpf_buffer_parser() forwards data to a callback that processes the structured buffer constructed by the BPF program.

Cc Alexei Starovoitov <[email protected]>
Cc Daniel Borkmann <[email protected]>
Cc David S. Miller <[email protected]>
Cc John Fastabend <[email protected]>
Cc Andrii Nakryiko <[email protected]>
Cc Martin KaFai Lau <[email protected]>
Cc Eduard Zingerman <[email protected]>
Cc Song Liu <[email protected]>
Cc Yonghong Song <[email protected]>
Cc KP Singh <[email protected]>
Cc Stanislav Fomichev <[email protected]>
Cc Hao Luo <[email protected]>
Cc Jiri Olsa <[email protected]>

To: [email protected]

---
 include/linux/bpf.h            |  19 ++++
 kernel/bpf/Makefile            |   3 +
 kernel/bpf/bpf_buffer_parser.c | 170 +++++++++++++++++++++++++++++++++
 3 files changed, 192 insertions(+)
 create mode 100644 kernel/bpf/bpf_buffer_parser.c
include/linux/bpf.h +19 -0
index e5be698256d15..25bc1b6b8a600 100644
@@ -3843,4 +3843,23 @@ static inline int bpf_map_check_op_flags(struct bpf_map *map, u64 flags, u64 all
 	return 0;
 }
 
+struct bpf_parser_buf {
+	char *buf;
+	int size;
+};
+
+struct bpf_parser_context;
+typedef int (*bpf_parser_handler_t)(struct bpf_parser_context *ctx);
+
+struct bpf_parser_context {
+	struct kref ref;
+	struct hlist_node hash_node;
+	bpf_parser_handler_t func;
+	struct bpf_parser_buf *buf;
+	void *data;
+};
+
+struct bpf_parser_context *alloc_bpf_parser_context(bpf_parser_handler_t func,
+			void *data);
+void put_bpf_parser_context(struct bpf_parser_context *ctx);
 #endif /* _LINUX_BPF_H */
kernel/bpf/Makefile +3 -0
index 232cbc97434db..309b905a81736 100644
@@ -56,6 +56,9 @@ obj-$(CONFIG_BPF_SYSCALL) += kmem_cache_iter.o
 ifeq ($(CONFIG_DMA_SHARED_BUFFER),y)
 obj-$(CONFIG_BPF_SYSCALL) += dmabuf_iter.o
 endif
+ifeq ($(CONFIG_KEXEC_BPF),y)
+obj-$(CONFIG_BPF_SYSCALL) += bpf_buffer_parser.o
+endif
 
 CFLAGS_REMOVE_percpu_freelist.o = $(CC_FLAGS_FTRACE)
 CFLAGS_REMOVE_bpf_lru_list.o = $(CC_FLAGS_FTRACE)
kernel/bpf/bpf_buffer_parser.c new file +170 -0

170 lines not on this page · raw message

Signature · 1 line
2.49.0
#2 lore raw

Re: [PATCHv6 01/13] bpf: Introduce kfuncs to parser buffer content

ctx->buf is NULL here from kzalloc.
Quoted 5 lines
kernel/bpf/bpf_buffer_parser.c new file +0 -0
new file mode 100644
index 000000000000..6acb4b5da71b

[ ... ]

Quoted 8 lines
kernel/bpf/bpf_buffer_parser.c new file +8 -0
+static void release_bpf_parser_context(struct kref *kref)
+{
+	struct bpf_parser_context *ctx = container_of(kref, struct bpf_parser_context, ref);
+
+	if (!!ctx->buf) {
+		vfree(ctx->buf->buf);
+		kfree(ctx->buf);
+	}

[ ... ]

kernel/bpf/bpf_buffer_parser.c line 40

Quoted 7 lines
kernel/bpf/bpf_buffer_parser.c new file +7 -0
+struct bpf_parser_context *alloc_bpf_parser_context(bpf_parser_handler_t func,
+		void *data)
+{
+	struct bpf_parser_context *ctx;
+	unsigned int key;
+
+	ctx = kzalloc(sizeof(*ctx), GFP_KERNEL);

ctx->buf is NULL here from kzalloc.

[ ... ]

Quoted 17 lines
kernel/bpf/bpf_buffer_parser.c new file +17 -0
+__bpf_kfunc int bpf_buffer_parser(char *buf, int buf_sz,
+		struct bpf_parser_context *context)
+{
+	struct bpf_parser_buf *parser_buf;
+	int ret;
+	char *b;
+
+	if (unlikely(context->func == NULL))
+		return -EINVAL;
+
+	b = __vmalloc(buf_sz, GFP_KERNEL_ACCOUNT | __GFP_ZERO);
+	if (!b)
+		return -ENOMEM;
+	ret = copy_from_kernel_nofault(b, buf, buf_sz);
+	if (!!ret) {
+		vfree(b);
+		return ret;

kernel/bpf/bpf_buffer_parser.c line 131

Quoted 10 lines
kernel/bpf/bpf_buffer_parser.c new file +10 -0
+	}
+
+	parser_buf = kmalloc(sizeof(struct bpf_parser_buf), GFP_KERNEL);
+	if (!parser_buf) {
+		vfree(b);
+		return -ENOMEM;
+	}
+	parser_buf->buf = b;
+	parser_buf->size = buf_sz;
+	context->buf = parser_buf;

If bpf_buffer_parser() is called multiple times on the same context, does this leak the previous parser_buf and its backing vmalloc buffer? The assignment to context->buf overwrites any existing pointer without first freeing it.

release_bpf_parser_context() will only free the final context->buf value when the context is destroyed, so any intermediate buffers from prior calls would be lost.

Should there be a check here to either return an error if context->buf is already set, or free the old buffer before assigning the new one?

kernel/bpf/bpf_buffer_parser.c line 135

Quoted 4 lines
kernel/bpf/bpf_buffer_parser.c new file +4 -0
+	ret = context->func(context);
+
+	return ret;
+}

[ ... ]

---
AI reviewed your patch. Please fix the bug or email reply why it's not a bug.
See: https://github.com/kernel-patches/vmtest/blob/master/ci/claude/README.md

CI run summary: https://github.com/kernel-patches/bpf/actions/runs/21147860407

#3 lore raw

PATCH v6 2/13 kexec_file: Move signature validation ahead

In reply to Pingfan Liu

Move the signature validation at the head of the function, so the image can be unfold and handled later.

Cc Baoquan He <[email protected]>
Cc Dave Young <[email protected]>
Cc Andrew Morton <[email protected]>
Cc Philipp Rudo <[email protected]>

To: [email protected]

---
 kernel/kexec_file.c | 13 +++++++------
 1 file changed, 7 insertions(+), 6 deletions(-)
kernel/kexec_file.c +7 -6
index eb62a97942428..0222d17072d40 100644
@@ -231,18 +231,19 @@ kimage_file_prepare_segments(struct kimage *image, int kernel_fd, int initrd_fd,
 	kexec_dprintk("kernel: %p kernel_size: %#lx\n",
 		      image->kernel_buf, image->kernel_buf_len);
 
-	/* Call arch image probe handlers */
-	ret = arch_kexec_kernel_image_probe(image, image->kernel_buf,
-					    image->kernel_buf_len);
-	if (ret)
-		goto out;
-
 #ifdef CONFIG_KEXEC_SIG
 	ret = kimage_validate_signature(image);
 
 	if (ret)
 		goto out;
 #endif
+
+	/* Call arch image probe handlers */
+	ret = arch_kexec_kernel_image_probe(image, image->kernel_buf,
+					    image->kernel_buf_len);
+	if (ret)
+		goto out;
+
 	/* It is possible that there no initramfs is being loaded */
 	if (!(flags & KEXEC_FILE_NO_INITRAMFS)) {
 		ret = kernel_read_file_from_fd(initrd_fd, 0, &image->initrd_buf,
Signature · 1 line
2.49.0
#4 lore raw

Re: [PATCHv6 02/13] kexec_file: Move signature validation ahead

Does this reordering break signature verification? The kimage_validate_signature() function calls kexec_image_verify_sig(), which accesses image->fops->verify_sig:
Quoted 10 lines
kernel/kexec_file.c +0 -2
index eb62a9794242..0222d17072d4 100644
@@ -231,18 +231,19 @@ kimage_file_prepare_segments(struct kimage *image, int kernel_fd, int initrd_fd,
 	kexec_dprintk("kernel: %p kernel_size: %#lx\n",
 		      image->kernel_buf, image->kernel_buf_len);
 
-	/* Call arch image probe handlers */
-	ret = arch_kexec_kernel_image_probe(image, image->kernel_buf,

kernel/kexec_file.c kimage_file_prepare_segments(struct kimage *image, int kernel_fd, int initrd_fd, · line 239

Quoted 10 lines
kernel/kexec_file.c +0 -4
-					    image->kernel_buf_len);
-	if (ret)
-		goto out;
-
 #ifdef CONFIG_KEXEC_SIG
 	ret = kimage_validate_signature(image);
 
 	if (ret)
 		goto out;
 #endif

Does this reordering break signature verification? The kimage_validate_signature() function calls kexec_image_verify_sig(), which accesses image->fops->verify_sig:

  static int kexec_image_verify_sig(struct kimage *image, void *buf,
                                    unsigned long buf_len)
  {
      if (!image->fops || !image->fops->verify_sig) {
          pr_debug("kernel loader does not support signature verification.\n");
          return -EKEYREJECTED;
      }
      return image->fops->verify_sig(buf, buf_len);
  }

However, image->fops is set by arch_kexec_kernel_image_probe() via kexec_image_probe_default(), which now runs after kimage_validate_signature(). Since the kimage struct is zero-initialized by do_kimage_alloc_init(), image->fops will be NULL when kexec_image_verify_sig() is called.

With this ordering, kexec_image_verify_sig() will always return -EKEYREJECTED. When CONFIG_KEXEC_SIG_FORCE is enabled (sig_enforce = true), this causes kimage_validate_signature() to return the error and kexec_file_load() fails.

Is this intentional, or should arch_kexec_kernel_image_probe() remain before the signature validation call?

kernel/kexec_file.c kimage_file_prepare_segments(struct kimage *image, int kernel_fd, int initrd_fd, · line 246

Quoted 7 lines
kernel/kexec_file.c +7 -0
+
+	/* Call arch image probe handlers */
+	ret = arch_kexec_kernel_image_probe(image, image->kernel_buf,
+					    image->kernel_buf_len);
+	if (ret)
+		goto out;
+

[ ... ]

---
AI reviewed your patch. Please fix the bug or email reply why it's not a bug.
See: https://github.com/kernel-patches/vmtest/blob/master/ci/claude/README.md

CI run summary: https://github.com/kernel-patches/bpf/actions/runs/21147860407

#5 lore raw

Re: [PATCHv6 02/13] kexec_file: Move signature validation ahead

In reply to Pingfan Liu

Hi Pingfan,

Quoted 2 lines · On Mon, 19 Jan 2026 11:24:13 +0800 Pingfan Liu <[email protected]> wrote:

Move the signature validation at the head of the function, so the image can be unfold and handled later.

besides what the bpf-bot already mentioned.

What do you want to achieve by moving signature verification in front of probing the image? Do you want to avoid calling arch_kexec_kernel_image_probe twice? It would be great if you could add the reasoning why the change is needed to the commit message in the future. Not only to make review easier but also to document it for the future.

Thanks
Philipp

Quoted 40 lines
Cc Baoquan He <[email protected]>
Cc Dave Young <[email protected]>
Cc Andrew Morton <[email protected]>
Cc Philipp Rudo <[email protected]>

To: [email protected]

---
 kernel/kexec_file.c | 13 +++++++------
 1 file changed, 7 insertions(+), 6 deletions(-)
kernel/kexec_file.c +7 -6
index eb62a97942428..0222d17072d40 100644
@@ -231,18 +231,19 @@ kimage_file_prepare_segments(struct kimage *image, int kernel_fd, int initrd_fd,
 	kexec_dprintk("kernel: %p kernel_size: %#lx\n",
 		      image->kernel_buf, image->kernel_buf_len);
 
-	/* Call arch image probe handlers */
-	ret = arch_kexec_kernel_image_probe(image, image->kernel_buf,
-					    image->kernel_buf_len);
-	if (ret)
-		goto out;
-
 #ifdef CONFIG_KEXEC_SIG
 	ret = kimage_validate_signature(image);
 
 	if (ret)
 		goto out;
 #endif
+
+	/* Call arch image probe handlers */
+	ret = arch_kexec_kernel_image_probe(image, image->kernel_buf,
+					    image->kernel_buf_len);
+	if (ret)
+		goto out;
+
 	/* It is possible that there no initramfs is being loaded */
 	if (!(flags & KEXEC_FILE_NO_INITRAMFS)) {
 		ret = kernel_read_file_from_fd(initrd_fd, 0, &image->initrd_buf,
#6 lore raw

Re: [PATCHv6 02/13] kexec_file: Move signature validation ahead

Quoted 9 lines · Philipp Rudo

Hi Pingfan,

Quoted 2 lines · On Mon, 19 Jan 2026 11:24:13 +0800 Pingfan Liu <[email protected]> wrote:

Move the signature validation at the head of the function, so the image can be unfold and handled later.

Quoted 9 lines

besides what the bpf-bot already mentioned.

What do you want to achieve by moving signature verification in front of probing the image? Do you want to avoid calling arch_kexec_kernel_image_probe twice? It would be great if you could add the reasoning why the change is needed to the commit message in the future. Not only to make review easier but also to document it for the future.

Here I made a mistake. I think the UKI case and the convention case should be handled separately. For the UKI case, signature verification should be applied to the UKI envelope but skipped for the unpacked kernel image since it has no signature.

Thanks,

Pingfan

Quoted 44 lines

Thanks
Philipp

Quoted 40 lines
Cc Baoquan He <[email protected]>
Cc Dave Young <[email protected]>
Cc Andrew Morton <[email protected]>
Cc Philipp Rudo <[email protected]>

To: [email protected]

---
 kernel/kexec_file.c | 13 +++++++------
 1 file changed, 7 insertions(+), 6 deletions(-)
kernel/kexec_file.c +7 -6
index eb62a97942428..0222d17072d40 100644
@@ -231,18 +231,19 @@ kimage_file_prepare_segments(struct kimage *image, int kernel_fd, int initrd_fd,
      kexec_dprintk("kernel: %p kernel_size: %#lx\n",
                    image->kernel_buf, image->kernel_buf_len);
 
-     /* Call arch image probe handlers */
-     ret = arch_kexec_kernel_image_probe(image, image->kernel_buf,
-                                         image->kernel_buf_len);
-     if (ret)
-             goto out;
-
 #ifdef CONFIG_KEXEC_SIG
      ret = kimage_validate_signature(image);
 
      if (ret)
              goto out;
 #endif
+
+     /* Call arch image probe handlers */
+     ret = arch_kexec_kernel_image_probe(image, image->kernel_buf,
+                                         image->kernel_buf_len);
+     if (ret)
+             goto out;
+
      /* It is possible that there no initramfs is being loaded */
      if (!(flags & KEXEC_FILE_NO_INITRAMFS)) {
              ret = kernel_read_file_from_fd(initrd_fd, 0, &image->initrd_buf,
#7 lore raw

PATCH v6 3/13 kexec_file: Introduce routines to parse PE file

In reply to Pingfan Liu

The incoming patches need to handle UEFI format image, which is in PE format. Hence introducing some routines here.

Cc Baoquan He <[email protected]>
Cc Dave Young <[email protected]>
Cc Andrew Morton <[email protected]>
Cc Philipp Rudo <[email protected]>

To: [email protected]

---
 kernel/Makefile         |  1 +
 kernel/kexec_internal.h |  3 ++
 kernel/kexec_uefi_app.c | 81 +++++++++++++++++++++++++++++++++++++++++
 3 files changed, 85 insertions(+)
 create mode 100644 kernel/kexec_uefi_app.c
kernel/Makefile +1 -0
index e83669841b8cc..f9e85c4a0622b 100644
@@ -83,6 +83,7 @@ obj-$(CONFIG_CRASH_DUMP_KUNIT_TEST) += crash_core_test.o
 obj-$(CONFIG_KEXEC) += kexec.o
 obj-$(CONFIG_KEXEC_FILE) += kexec_file.o
 obj-$(CONFIG_KEXEC_ELF) += kexec_elf.o
+obj-$(CONFIG_KEXEC_BPF) += kexec_uefi_app.o
 obj-$(CONFIG_BACKTRACE_SELF_TEST) += backtracetest.o
 obj-$(CONFIG_COMPAT) += compat.o
 obj-$(CONFIG_CGROUPS) += cgroup/
kernel/kexec_internal.h +3 -0
index 228bb88c018bc..8e5e5c1237732 100644
@@ -36,6 +36,9 @@ static inline void kexec_unlock(void)
 void kimage_file_post_load_cleanup(struct kimage *image);
 extern char kexec_purgatory[];
 extern size_t kexec_purgatory_size;
+extern bool pe_has_bpf_section(const char *file_buf, unsigned long pe_sz);
+extern int pe_get_section(const char *file_buf, const char *sect_name,
+		char **sect_start, unsigned long *sect_sz);
 #else /* CONFIG_KEXEC_FILE */
 static inline void kimage_file_post_load_cleanup(struct kimage *image) { }
 #endif /* CONFIG_KEXEC_FILE */
kernel/kexec_uefi_app.c new file +81 -0

81 lines not on this page · raw message

Signature · 1 line
2.49.0
#8 lore raw

Re: [PATCHv6 03/13] kexec_file: Introduce routines to parse PE file

The kernel_len parameter is declared but never used in this function. Should this validate that mz->peaddr is within bounds of kernel_len before accessing pe->magic? If mz->peaddr is larger than the…
Quoted 5 lines
kernel/kexec_uefi_app.c new file +0 -0
new file mode 100644
index 000000000000..dbe6d76d47ff

[ ... ]

kernel/kexec_uefi_app.c line 29

Quoted 11 lines
kernel/kexec_uefi_app.c new file +11 -0
+static bool is_valid_pe(const char *kernel_buf, unsigned long kernel_len)
+{
+	struct mz_hdr *mz;
+	struct pe_hdr *pe;
+
+	if (!kernel_buf)
+		return false;
+	mz = (struct mz_hdr *)kernel_buf;
+	if (mz->magic != IMAGE_DOS_SIGNATURE)
+		return false;
+	pe = (struct pe_hdr *)(kernel_buf + mz->peaddr);

The kernel_len parameter is declared but never used in this function. Should this validate that mz->peaddr is within bounds of kernel_len before accessing pe->magic? If mz->peaddr is larger than the buffer size, this would read out of bounds.

Quoted 8 lines
kernel/kexec_uefi_app.c new file +8 -0
+	if (pe->magic != IMAGE_NT_SIGNATURE)
+		return false;
+	if (pe->opt_hdr_size == 0) {
+		pr_err("optional header is missing\n");
+		return false;
+	}
+	return true;
+}

[ ... ]

Quoted 9 lines
kernel/kexec_uefi_app.c new file +9 -0
+int pe_get_section(const char *file_buf, const char *sect_name,
+		char **sect_start, unsigned long *sect_sz)
+{
+	struct pe_hdr *pe_hdr;
+	struct pe32plus_opt_hdr *opt_hdr;
+	struct section_header *sect_hdr;
+	int section_nr, i;
+	struct mz_hdr *mz = (struct mz_hdr *)file_buf;
+

kernel/kexec_uefi_app.c line 71

Quoted 10 lines
kernel/kexec_uefi_app.c new file +10 -0
+	*sect_start = NULL;
+	*sect_sz = 0;
+	pe_hdr = (struct pe_hdr *)(file_buf + mz->peaddr);
+	section_nr = pe_hdr->sections;
+	opt_hdr = (struct pe32plus_opt_hdr *)(file_buf + mz->peaddr +
+				sizeof(struct pe_hdr));
+	sect_hdr = (struct section_header *)((char *)opt_hdr +
+				pe_hdr->opt_hdr_size);
+
+	for (i = 0; i < section_nr; i++) {

pe_get_section() has no buffer size parameter. The values of mz->peaddr, pe_hdr->sections, and pe_hdr->opt_hdr_size are all read from the PE file content. If the file is malformed or crafted, section_nr could be set to an arbitrarily large value, causing sect_hdr to iterate past the end of file_buf. Is there a way to validate these offsets against the actual buffer size?

kernel/kexec_uefi_app.c line 81

Quoted 10 lines
kernel/kexec_uefi_app.c new file +10 -0
+		if (strcmp(sect_hdr->name, sect_name) == 0) {
+			*sect_start = (char *)file_buf + sect_hdr->data_addr;
+			*sect_sz = sect_hdr->raw_data_size;
+			return 0;
+		}
+		sect_hdr++;
+	}
+
+	return -1;
+}

---
AI reviewed your patch. Please fix the bug or email reply why it's not a bug.
See: https://github.com/kernel-patches/vmtest/blob/master/ci/claude/README.md

CI run summary: https://github.com/kernel-patches/bpf/actions/runs/21147860407

#9 lore raw

PATCH v6 4/13 kexec_file: Use bpf-prog to decompose image

In reply to Pingfan Liu

As UEFI becomes popular, a few architectures support to boot a PE format kernel image directly. But the internal of PE format varies, which means each parser for each format.

This patch (with the rest in this series) introduces a common skeleton to all parsers, and leave the format parsing in
bpf-prog, so the kernel code can keep relative stable.

History, the syscall
SYSCALL_DEFINE5(kexec_file_load, int, kernel_fd, int, initrd_fd,
unsigned long, cmdline_len, const char __user *, cmdline_ptr, unsigned long, flags)
complies with the kernel protocol: bootable kernel, initramfs, cmdline.

But the occurrence of UKI images challenges the traditional model. The image itself contains the kernel, initrd, and cmdline. To be compatible with both the old and new models, kexec_file_load can be reorganized into two stages. In the first stage, "decompose_kexec_image()" breaks down the passed-in image into the components required by the kernel boot protocol. In the second stage, the traditional image loader "arch_kexec_kernel_image_load()" prepares the switch to the next kernel.

During the decomposition stage, the decomposition process can be nested. In each sub-process, BPF bytecode is extracted from the '.bpf' section to parse the current PE file. If the data section in the PE file contains another PE file, the sub-process is repeated. This is designed to handle the zboot format embedded in UKI format on the arm64 platform.

There are some placeholder functions in this patch. (They will take effect after the introduction of kexec BPF light skeleton and BPF helpers.)

Cc Baoquan He <[email protected]>
Cc Dave Young <[email protected]>
Cc Andrew Morton <[email protected]>
Cc Philipp Rudo <[email protected]>

To: [email protected]

---
 kernel/Kconfig.kexec      |   8 ++
 kernel/Makefile           |   2 +-
 kernel/kexec_bpf_loader.c | 161 ++++++++++++++++++++++++++++++++++++++
 kernel/kexec_file.c       |   9 ++-
 kernel/kexec_internal.h   |   1 +
 5 files changed, 179 insertions(+), 2 deletions(-)
 create mode 100644 kernel/kexec_bpf_loader.c
kernel/Kconfig.kexec +8 -0
index 15632358bcf71..0c5d619820bcd 100644
@@ -46,6 +46,14 @@ config KEXEC_FILE
 	  for kernel and initramfs as opposed to list of segments as
 	  accepted by kexec system call.
 
+config KEXEC_BPF
+	bool "Enable bpf-prog to parse the kexec image"
+	depends on KEXEC_FILE
+	depends on DEBUG_INFO_BTF && BPF_SYSCALL
+	help
+	  This is a feature to run bpf section inside a kexec image file, which
+	  parses the image properly and help kernel set up kexec boot protocol
+
 config KEXEC_SIG
 	bool "Verify kernel signature during kexec_file_load() syscall"
 	depends on ARCH_SUPPORTS_KEXEC_SIG
kernel/Makefile +1 -1
index f9e85c4a0622b..05177a867690d 100644
@@ -83,7 +83,7 @@ obj-$(CONFIG_CRASH_DUMP_KUNIT_TEST) += crash_core_test.o
 obj-$(CONFIG_KEXEC) += kexec.o
 obj-$(CONFIG_KEXEC_FILE) += kexec_file.o
 obj-$(CONFIG_KEXEC_ELF) += kexec_elf.o
-obj-$(CONFIG_KEXEC_BPF) += kexec_uefi_app.o
+obj-$(CONFIG_KEXEC_BPF) += kexec_bpf_loader.o kexec_uefi_app.o
 obj-$(CONFIG_BACKTRACE_SELF_TEST) += backtracetest.o
 obj-$(CONFIG_COMPAT) += compat.o
 obj-$(CONFIG_CGROUPS) += cgroup/
kernel/kexec_bpf_loader.c new file +161 -0

161 lines not on this page · raw message

kernel/kexec_file.c +8 -1
index 0222d17072d40..f9674bb5bd8db 100644
@@ -238,7 +238,14 @@ kimage_file_prepare_segments(struct kimage *image, int kernel_fd, int initrd_fd,
 		goto out;
 #endif
 
-	/* Call arch image probe handlers */
+	if (IS_ENABLED(CONFIG_KEXEC_BPF))
+		decompose_kexec_image(image, initrd_fd);
+
+	/*
+	 * From this point, the kexec subsystem handle the kernel boot protocol.
+	 *
+	 * Call arch image probe handlers
+	 */
 	ret = arch_kexec_kernel_image_probe(image, image->kernel_buf,
 					    image->kernel_buf_len);
 	if (ret)
kernel/kexec_internal.h +1 -0
index 8e5e5c1237732..ee01d0c8bb377 100644
@@ -39,6 +39,7 @@ extern size_t kexec_purgatory_size;
 extern bool pe_has_bpf_section(const char *file_buf, unsigned long pe_sz);
 extern int pe_get_section(const char *file_buf, const char *sect_name,
 		char **sect_start, unsigned long *sect_sz);
+extern int decompose_kexec_image(struct kimage *image, int extended_fd);
 #else /* CONFIG_KEXEC_FILE */
 static inline void kimage_file_post_load_cleanup(struct kimage *image) { }
 #endif /* CONFIG_KEXEC_FILE */
Signature · 1 line
2.49.0
#10 lore raw

Re: [PATCHv6 04/13] kexec_file: Use bpf-prog to decompose image

The *_sz fields here are int, but image->kernel_buf_len and related fields are unsigned long. Could this cause truncation issues for buffers larger than INT_MAX?
Quoted 5 lines
kernel/kexec_bpf_loader.c new file +0 -0
new file mode 100644
index 000000000000..dc59e1389da9

[ ... ]

kernel/kexec_bpf_loader.c line 43

Quoted 9 lines
kernel/kexec_bpf_loader.c new file +9 -0
+struct kexec_context {
+	bool kdump;
+	char *kernel;
+	int kernel_sz;
+	char *initrd;
+	int initrd_sz;
+	char *cmdline;
+	int cmdline_sz;
+};

The *_sz fields here are int, but image->kernel_buf_len and related fields are unsigned long. Could this cause truncation issues for buffers larger than INT_MAX?

[ ... ]

Quoted 7 lines
kernel/kexec_bpf_loader.c new file +7 -0
+int decompose_kexec_image(struct kimage *image, int extended_fd)
+{
+	struct kexec_context context = { 0 };
+	struct bpf_parser_context *bpf;
+	unsigned long kernel_sz, bpf_sz;
+	char *kernel_start, *bpf_start;
+	int ret = 0;

kernel/kexec_bpf_loader.c line 108

Quoted 10 lines
kernel/kexec_bpf_loader.c new file +10 -0
+
+	if (image->type != KEXEC_TYPE_CRASH)
+	        context.kdump = false;
+	else
+	        context.kdump = true;
+
+	kernel_start = image->kernel_buf;
+	kernel_sz = image->kernel_buf_len;
+
+	while (file_has_bpf_section(kernel_start, kernel_sz)) {

With the placeholder arm_bpf_prog/disarm_bpf_prog functions that do nothing, if an image has a .bpf section, won't this loop iterate forever? The BPF program is supposed to modify context.kernel to point to the inner content, but without a real implementation, context.kernel stays unchanged after kexec_image_parser_anchor() returns.

Note: commit 59dbdff4e55b ("kexec_file: Integrate bpf light skeleton to load image with bpf-prog") later in the series fills in these placeholders.

Quoted 3 lines
kernel/kexec_bpf_loader.c new file +3 -0
+		bpf = alloc_bpf_parser_context(kexec_buff_parser, &context);
+		if (!bpf)
+			return -ENOMEM;

[ ... ]

Quoted 10 lines
kernel/kexec_bpf_loader.c new file +10 -0
+		kernel_start = context.kernel;
+		kernel_sz = context.kernel_sz;
+
+		/*
+		 * detach the current bpf-prog from their attachment points.
+		 */
+		disarm_bpf_prog();
+		put_bpf_parser_context(bpf);
+	}
+

kernel/kexec_bpf_loader.c line 152

Quoted 10 lines
kernel/kexec_bpf_loader.c new file +10 -0
+	/*
+	 * image's kernel_buf, initrd_buf, cmdline_buf are set. Now they should
+	 * be updated to the new content.
+	 */
+	image->kernel_buf = context.kernel;
+	image->kernel_buf_len = context.kernel_sz;
+	image->initrd_buf = context.initrd;
+	image->initrd_buf_len = context.initrd_sz;
+	image->cmdline_buf = context.cmdline;
+	image->cmdline_buf_len = context.cmdline_sz;

When the kernel image has no .bpf section, the while loop never executes. In that case, context.kernel remains NULL (from the zero initializer), and these lines set image->kernel_buf = NULL, image->kernel_buf_len = 0.

This appears to leak the original image->kernel_buf that was allocated by kernel_read_file_from_fd() in kimage_file_prepare_segments(). The subsequent arch_kexec_kernel_image_probe() call then receives NULL instead of the valid kernel buffer.

Should there be a check to preserve the original buffers when no decomposition occurred?

Quoted 2 lines
kernel/kexec_bpf_loader.c new file +2 -0
+
+	return 0;

[ ... ]

kernel/kexec_file.c kimage_file_prepare_segments(struct kimage *image, int kernel_fd, int initrd_fd, · line 242

Quoted 10 lines
kernel/kexec_file.c +2 -0
index 0222d17072d4..f9674bb5bd8d 100644
@@ -238,7 +238,14 @@ kimage_file_prepare_segments(struct kimage *image, int kernel_fd, int initrd_fd,
 		goto out;
 #endif
 
+	if (IS_ENABLED(CONFIG_KEXEC_BPF))
+		decompose_kexec_image(image, initrd_fd);

The return value of decompose_kexec_image() is ignored here. If it returns an error (e.g., -ENOMEM from alloc_bpf_parser_context()), the function continues with potentially corrupted state instead of propagating the error.

Should this check the return value and goto out on failure?

kernel/kexec_file.c kimage_file_prepare_segments(struct kimage *image, int kernel_fd, int initrd_fd, · line 250

Quoted 8 lines
kernel/kexec_file.c +6 -0
+
+	/*
+	 * From this point, the kexec subsystem handle the kernel boot protocol.
+	 *
+	 * Call arch image probe handlers
+	 */
 	ret = arch_kexec_kernel_image_probe(image, image->kernel_buf,
 					    image->kernel_buf_len);

---
AI reviewed your patch. Please fix the bug or email reply why it's not a bug.
See: https://github.com/kernel-patches/vmtest/blob/master/ci/claude/README.md

CI run summary: https://github.com/kernel-patches/bpf/actions/runs/21147860407

#11 lore raw

Re: [PATCHv6 04/13] kexec_file: Use bpf-prog to decompose image

In reply to Pingfan Liu

Hi Pingfan,

On Mon, 19 Jan 2026 11:24:15 +0800
Pingfan Liu <[email protected]> wrote:

[...]

Quoted 118 lines
kernel/kexec_bpf_loader.c new file +112 -0
new file mode 100644
index 0000000000000..dc59e1389da94
@@ -0,0 +1,161 @@
+// SPDX-License-Identifier: GPL-2.0
+/*
+ * Kexec image bpf section helpers
+ *
+ * Copyright (C) 2025, 2026 Red Hat, Inc
+ */
+
+#define pr_fmt(fmt)	"kexec_file(Image): " fmt
+
+#include <linux/err.h>
+#include <linux/errno.h>
+#include <linux/list.h>
+#include <linux/kernel.h>
+#include <linux/vmalloc.h>
+#include <linux/kexec.h>
+#include <linux/elf.h>
+#include <linux/string.h>
+#include <linux/bpf.h>
+#include <linux/filter.h>
+#include <asm/byteorder.h>
+#include <asm/image.h>
+#include <asm/memory.h>
+#include "kexec_internal.h"
+
+/* Load a ELF */
+static int arm_bpf_prog(char *bpf_elf, unsigned long sz)
+{
+	return 0;
+}
+
+static void disarm_bpf_prog(void)
+{
+}
+
+struct kexec_context {
+	bool kdump;
+	char *kernel;
+	int kernel_sz;
+	char *initrd;
+	int initrd_sz;
+	char *cmdline;
+	int cmdline_sz;
+};
+
+void kexec_image_parser_anchor(struct kexec_context *context,
+		unsigned long parser_id);
+
+/*
+ * optimize("O0") prevents inline, compiler constant propagation
+ *
+ * Let bpf be the program context pointer so that it will not be spilled into
+ * stack.
+ */
+__attribute__((used, optimize("O0"))) void kexec_image_parser_anchor(
+		struct kexec_context *context,
+		unsigned long parser_id)
+{
+	/*
+	 * To prevent linker from Identical Code Folding (ICF) with kexec_image_parser_anchor,
+	 * making them have different code.
+	 */
+	volatile int dummy = 0;
+
+	dummy += 1;
+}
+
+
+BTF_KFUNCS_START(kexec_modify_return_ids)
+BTF_ID_FLAGS(func, kexec_image_parser_anchor, KF_SLEEPABLE)
+BTF_KFUNCS_END(kexec_modify_return_ids)
+
+static const struct btf_kfunc_id_set kexec_modify_return_set = {
+	.owner = THIS_MODULE,
+	.set = &kexec_modify_return_ids,
+};
+
+static int __init kexec_bpf_prog_run_init(void)
+{
+	return register_btf_fmodret_id_set(&kexec_modify_return_set);
+}
+late_initcall(kexec_bpf_prog_run_init);
+
+static int kexec_buff_parser(struct bpf_parser_context *parser)
+{
+	return 0;
+}
+
+/* At present, only PE format file with .bpf section is supported */
+#define file_has_bpf_section	pe_has_bpf_section
+#define file_get_section	pe_get_section
+
+int decompose_kexec_image(struct kimage *image, int extended_fd)
+{
+	struct kexec_context context = { 0 };
+	struct bpf_parser_context *bpf;
+	unsigned long kernel_sz, bpf_sz;
+	char *kernel_start, *bpf_start;
+	int ret = 0;
+
+	if (image->type != KEXEC_TYPE_CRASH)
+	        context.kdump = false;
+	else
+	        context.kdump = true;
+
+	kernel_start = image->kernel_buf;
+	kernel_sz = image->kernel_buf_len;
+
+	while (file_has_bpf_section(kernel_start, kernel_sz)) {
+
+		bpf = alloc_bpf_parser_context(kexec_buff_parser, &context);
+		if (!bpf)
+			return -ENOMEM;

kernel/kexec_bpf_loader.c line 122

Quoted 10 lines
kernel/kexec_bpf_loader.c new file +10 -0
+		file_get_section((const char *)kernel_start, ".bpf", &bpf_start, &bpf_sz);
+		if (!!bpf_sz) {
+			/* load and attach bpf-prog */
+			ret = arm_bpf_prog(bpf_start, bpf_sz);
+			if (ret) {
+				put_bpf_parser_context(bpf);
+				pr_err("Fail to load .bpf section\n");
+				goto err;
+			}
+		}

I'm not sure this works as intended. In case a .bpf section exists but bpf_sz is 0, the function will skip arming the bpf-prog but still continue. That doesn't look right to me. IIUC a zero size bpf-prog should be an error. Or am I missing something?

Thanks
Philipp

Quoted 71 lines
kernel/kexec_bpf_loader.c new file +39 -0
+		context.kernel = kernel_start;
+		context.kernel_sz = kernel_sz;
+		/* bpf-prog fentry, which handle above buffers. */
+		kexec_image_parser_anchor(&context, (unsigned long)bpf);
+
+		/*
+		 * Container may be nested and should be unfold one by one.
+		 * The former bpf-prog should prepare 'kernel', 'initrd',
+		 * 'cmdline' for the next phase by calling kexec_buff_parser()
+		 */
+		kernel_start = context.kernel;
+		kernel_sz = context.kernel_sz;
+
+		/*
+		 * detach the current bpf-prog from their attachment points.
+		 */
+		disarm_bpf_prog();
+		put_bpf_parser_context(bpf);
+	}
+
+	/*
+	 * image's kernel_buf, initrd_buf, cmdline_buf are set. Now they should
+	 * be updated to the new content.
+	 */
+	image->kernel_buf = context.kernel;
+	image->kernel_buf_len = context.kernel_sz;
+	image->initrd_buf = context.initrd;
+	image->initrd_buf_len = context.initrd_sz;
+	image->cmdline_buf = context.cmdline;
+	image->cmdline_buf_len = context.cmdline_sz;
+
+	return 0;
+err:
+	vfree(context.kernel);
+	vfree(context.initrd);
+	vfree(context.cmdline);
+	return ret;
+}
+
kernel/kexec_file.c +8 -1
index 0222d17072d40..f9674bb5bd8db 100644
@@ -238,7 +238,14 @@ kimage_file_prepare_segments(struct kimage *image, int kernel_fd, int initrd_fd,
 		goto out;
 #endif
 
-	/* Call arch image probe handlers */
+	if (IS_ENABLED(CONFIG_KEXEC_BPF))
+		decompose_kexec_image(image, initrd_fd);
+
+	/*
+	 * From this point, the kexec subsystem handle the kernel boot protocol.
+	 *
+	 * Call arch image probe handlers
+	 */
 	ret = arch_kexec_kernel_image_probe(image, image->kernel_buf,
 					    image->kernel_buf_len);
 	if (ret)
kernel/kexec_internal.h +1 -0
index 8e5e5c1237732..ee01d0c8bb377 100644
@@ -39,6 +39,7 @@ extern size_t kexec_purgatory_size;
 extern bool pe_has_bpf_section(const char *file_buf, unsigned long pe_sz);
 extern int pe_get_section(const char *file_buf, const char *sect_name,
 		char **sect_start, unsigned long *sect_sz);
+extern int decompose_kexec_image(struct kimage *image, int extended_fd);
 #else /* CONFIG_KEXEC_FILE */
 static inline void kimage_file_post_load_cleanup(struct kimage *image) { }
 #endif /* CONFIG_KEXEC_FILE */
#12 lore raw

Re: [PATCHv6 04/13] kexec_file: Use bpf-prog to decompose image

Quoted 133 lines · Philipp Rudo

Hi Pingfan,

On Mon, 19 Jan 2026 11:24:15 +0800
Pingfan Liu <[email protected]> wrote:

[...]

Quoted 125 lines
kernel/kexec_bpf_loader.c new file +119 -0
new file mode 100644
index 0000000000000..dc59e1389da94
@@ -0,0 +1,161 @@
+// SPDX-License-Identifier: GPL-2.0
+/*
+ * Kexec image bpf section helpers
+ *
+ * Copyright (C) 2025, 2026 Red Hat, Inc
+ */
+
+#define pr_fmt(fmt)  "kexec_file(Image): " fmt
+
+#include <linux/err.h>
+#include <linux/errno.h>
+#include <linux/list.h>
+#include <linux/kernel.h>
+#include <linux/vmalloc.h>
+#include <linux/kexec.h>
+#include <linux/elf.h>
+#include <linux/string.h>
+#include <linux/bpf.h>
+#include <linux/filter.h>
+#include <asm/byteorder.h>
+#include <asm/image.h>
+#include <asm/memory.h>
+#include "kexec_internal.h"
+
+/* Load a ELF */
+static int arm_bpf_prog(char *bpf_elf, unsigned long sz)
+{
+     return 0;
+}
+
+static void disarm_bpf_prog(void)
+{
+}
+
+struct kexec_context {
+     bool kdump;
+     char *kernel;
+     int kernel_sz;
+     char *initrd;
+     int initrd_sz;
+     char *cmdline;
+     int cmdline_sz;
+};
+
+void kexec_image_parser_anchor(struct kexec_context *context,
+             unsigned long parser_id);
+
+/*
+ * optimize("O0") prevents inline, compiler constant propagation
+ *
+ * Let bpf be the program context pointer so that it will not be spilled into
+ * stack.
+ */
+__attribute__((used, optimize("O0"))) void kexec_image_parser_anchor(
+             struct kexec_context *context,
+             unsigned long parser_id)
+{
+     /*
+      * To prevent linker from Identical Code Folding (ICF) with kexec_image_parser_anchor,
+      * making them have different code.
+      */
+     volatile int dummy = 0;
+
+     dummy += 1;
+}
+
+
+BTF_KFUNCS_START(kexec_modify_return_ids)
+BTF_ID_FLAGS(func, kexec_image_parser_anchor, KF_SLEEPABLE)
+BTF_KFUNCS_END(kexec_modify_return_ids)
+
+static const struct btf_kfunc_id_set kexec_modify_return_set = {
+     .owner = THIS_MODULE,
+     .set = &kexec_modify_return_ids,
+};
+
+static int __init kexec_bpf_prog_run_init(void)
+{
+     return register_btf_fmodret_id_set(&kexec_modify_return_set);
+}
+late_initcall(kexec_bpf_prog_run_init);
+
+static int kexec_buff_parser(struct bpf_parser_context *parser)
+{
+     return 0;
+}
+
+/* At present, only PE format file with .bpf section is supported */
+#define file_has_bpf_section pe_has_bpf_section
+#define file_get_section     pe_get_section
+
+int decompose_kexec_image(struct kimage *image, int extended_fd)
+{
+     struct kexec_context context = { 0 };
+     struct bpf_parser_context *bpf;
+     unsigned long kernel_sz, bpf_sz;
+     char *kernel_start, *bpf_start;
+     int ret = 0;
+
+     if (image->type != KEXEC_TYPE_CRASH)
+             context.kdump = false;
+     else
+             context.kdump = true;
+
+     kernel_start = image->kernel_buf;
+     kernel_sz = image->kernel_buf_len;
+
+     while (file_has_bpf_section(kernel_start, kernel_sz)) {
+
+             bpf = alloc_bpf_parser_context(kexec_buff_parser, &context);
+             if (!bpf)
+                     return -ENOMEM;
+             file_get_section((const char *)kernel_start, ".bpf", &bpf_start, &bpf_sz);
+             if (!!bpf_sz) {
+                     /* load and attach bpf-prog */
+                     ret = arm_bpf_prog(bpf_start, bpf_sz);
+                     if (ret) {
+                             put_bpf_parser_context(bpf);
+                             pr_err("Fail to load .bpf section\n");
Quoted 9 lines

kernel/kexec_bpf_loader.c line 122

Quoted 3 lines
kernel/kexec_bpf_loader.c new file +3 -0
+                             goto err;
+                     }
+             }

I'm not sure this works as intended. In case a .bpf section exists but bpf_sz is 0, the function will skip arming the bpf-prog but still continue. That doesn't look right to me. IIUC a zero size bpf-prog should be an error. Or am I missing something?

Yes, you are right. It's better to treat a zero bpf_sz as an invalid format.

Thanks,

Pingfan

#13 lore raw

PATCH v6 5/13 lib/decompress: Keep decompressor when CONFIG_KEEP_DECOMPRESSOR

In reply to Pingfan Liu

The KEXE PE format parser needs the kernel built-in decompressor to decompress the kernel image. So moving the decompressor out of __init sections.

To: [email protected]

---
 include/linux/decompress/mm.h | 8 ++++++++
 lib/Kconfig                   | 6 ++++++
 lib/decompress.c              | 6 +++---
 3 files changed, 17 insertions(+), 3 deletions(-)
include/linux/decompress/mm.h +8 -0
index ac862422df158..39df02bcbc661 100644
@@ -81,6 +81,7 @@ MALLOC_VISIBLE void free(void *where)
 #include <linux/string.h>
 #include <linux/slab.h>
 #include <linux/vmalloc.h>
+#include <generated/autoconf.h>
 
 /* Use defines rather than static inline in order to avoid spurious
  * warnings when not needed (indeed large_malloc / large_free are not
@@ -92,7 +93,14 @@ MALLOC_VISIBLE void free(void *where)
 #define large_malloc(a) vmalloc(a)
 #define large_free(a) vfree(a)
 
+#ifdef CONFIG_KEEP_DECOMPRESSOR
+#define INIT
+#define INITCONST
+#else
 #define INIT __init
+#define INITCONST __initconst
+#endif
+
 #define STATIC
 
 #include <linux/init.h>
lib/Kconfig +6 -0
index 2923924bea78c..4424ae14dcf12 100644
@@ -165,6 +165,12 @@ config RANDOM32_SELFTEST
 #
 # compression support is select'ed if needed
 #
+config KEEP_DECOMPRESSOR
+	bool "keeps the decompress routines after kernel initialization"
+	default n
+	help
+	  This option keeps the decompress routines after kernel initialization
+
 config 842_COMPRESS
 	select CRC32
 	tristate
lib/decompress.c +3 -3
index 7785471586c62..29d4c749f1fc4 100644
@@ -6,7 +6,7 @@
  */
 
 #include <linux/decompress/generic.h>
-
+#include <linux/decompress/mm.h>
 #include <linux/decompress/bunzip2.h>
 #include <linux/decompress/unlzma.h>
 #include <linux/decompress/unxz.h>
@@ -48,7 +48,7 @@ struct compress_format {
 	decompress_fn decompressor;
 };
 
-static const struct compress_format compressed_formats[] __initconst = {
+static const struct compress_format compressed_formats[] INITCONST = {
 	{ .magic = {0x1f, 0x8b}, .name = "gzip", .decompressor = gunzip },
 	{ .magic = {0x1f, 0x9e}, .name = "gzip", .decompressor = gunzip },
 	{ .magic = {0x42, 0x5a}, .name = "bzip2", .decompressor = bunzip2 },
@@ -60,7 +60,7 @@ static const struct compress_format compressed_formats[] __initconst = {
 	{ /* sentinel */ }
 };
 
-decompress_fn __init decompress_method(const unsigned char *inbuf, long len,
+decompress_fn INIT decompress_method(const unsigned char *inbuf, long len,
 				const char **name)
 {
 	const struct compress_format *cf;
Signature · 1 line
2.49.0
#14 lore raw

PATCH v6 6/13 kexec_file: Implement decompress method for parser

In reply to Pingfan Liu

On arm64, there is no boot-time decompression for the kernel image. Therefore, when a compressed kernel image is loaded, it must be decompressed.

It is impractical to implement the complex decompression methods in BPF bytecode. However, decompression routines exist in the kernel. This patch bridges the compressed data with the kernel's decompression methods.

Cc Baoquan He <[email protected]>
Cc Dave Young <[email protected]>
Cc Andrew Morton <[email protected]>
Cc Philipp Rudo <[email protected]>

To: [email protected]

---
 kernel/Kconfig.kexec      |   2 +-
 kernel/kexec_bpf_loader.c | 203 ++++++++++++++++++++++++++++++++++++++
 2 files changed, 204 insertions(+), 1 deletion(-)
kernel/Kconfig.kexec +1 -1
index 0c5d619820bcd..dbfdf34a78aa0 100644
@@ -49,7 +49,7 @@ config KEXEC_FILE
 config KEXEC_BPF
 	bool "Enable bpf-prog to parse the kexec image"
 	depends on KEXEC_FILE
-	depends on DEBUG_INFO_BTF && BPF_SYSCALL
+	depends on DEBUG_INFO_BTF && BPF_SYSCALL && KEEP_DECOMPRESSOR
 	help
 	  This is a feature to run bpf section inside a kexec image file, which
 	  parses the image properly and help kernel set up kexec boot protocol
kernel/kexec_bpf_loader.c +203 -0

217 lines not on this page · raw message

Signature · 1 line
2.49.0
#15 lore raw

Re: [PATCHv6 06/13] kexec_file: Implement decompress method for parser

Should decompress_mem_allocator_fini() also free the individual chunks stored in chunk_base_addr[0..next_idx-1]? On the success path, merge_decompressed_data() frees them, but on error paths…
Quoted 4 lines
kernel/kexec_bpf_loader.c +0 -0
index dc59e1389da9..bd6a47fc53ed 100644

[ ... ]

kernel/kexec_bpf_loader.c static int __init kexec_bpf_prog_run_init(void) · line 188

Quoted 4 lines
kernel/kexec_bpf_loader.c +4 -0
+static void decompress_mem_allocator_fini(struct decompress_mem_allocator *a)
+{
+	vfree(a->chunk_base_addr);
+}

Should decompress_mem_allocator_fini() also free the individual chunks stored in chunk_base_addr[0..next_idx-1]? On the success path, merge_decompressed_data() frees them, but on error paths (decompressor failure or merge failure), the chunks appear to be leaked since only the array pointer is freed here.

[ ... ]

kernel/kexec_bpf_loader.c static int __init kexec_bpf_prog_run_init(void) · line 234

Quoted 9 lines
kernel/kexec_bpf_loader.c +9 -0
+static int parser_cmd_decompress(char *compressed_data, int image_gz_sz,
+		char **out_buf, int *out_sz, struct kexec_context *ctx)
+{
+	struct decompress_mem_allocator *a = &dcmpr_allocator;
+	decompress_fn decompressor;
+	const char *name;
+	int ret;
+
+	decompress_mem_allocator_init(a, CHUNK_SIZE);

Is the return value from decompress_mem_allocator_init() intentionally ignored? If vmalloc fails inside that function, chunk_base_addr and the other fields remain uninitialized, and subsequent code will use garbage values when accessing the allocator.

kernel/kexec_bpf_loader.c static int __init kexec_bpf_prog_run_init(void) · line 239

Quoted 5 lines
kernel/kexec_bpf_loader.c +5 -0
+	decompressor = decompress_method(compressed_data, image_gz_sz, &name);
+	if (!decompressor) {
+		pr_err("Can not find decompress method\n");
+		return -1;
+	}

When decompress_method() returns NULL, should decompress_mem_allocator_fini() be called before returning? The allocator was initialized above and allocated both chunk_base_addr and the first chunk, which appear to leak on this path.

Quoted 13 lines
kernel/kexec_bpf_loader.c +13 -0
+	pr_debug("Find decompressing method: %s, compressed sz:0x%x\n",
+			name, image_gz_sz);
+	ret = decompressor(compressed_data, image_gz_sz, NULL, flush,
+				NULL, NULL, NULL);
+	if (!!ret)
+		goto err;
+	ret = merge_decompressed_data(a, out_buf, out_sz);
+
+err:
+	decompress_mem_allocator_fini(a);
+
+	return ret;
+}

[ ... ]

kernel/kexec_bpf_loader.c static int __init kexec_bpf_prog_run_init(void) · line 280

Quoted 13 lines
kernel/kexec_bpf_loader.c +13 -0
+	switch (cmd->cmd) {
+	case KEXEC_BPF_CMD_DECOMPRESS:
+		ret = parser_cmd_decompress(buf, cmd->payload_len, &decompressed_buf,
+					&decompressed_sz, ctx);
+		if (!ret) {
+			switch (cmd->subcmd) {
+			case KEXEC_BPF_SUBCMD_KERNEL:
+				vfree(ctx->kernel);
+				ctx->kernel = decompressed_buf;
+				ctx->kernel_sz = decompressed_sz;
+				break;
+			default:
+				break;

When decompression succeeds but subcmd is not KEXEC_BPF_SUBCMD_KERNEL (for example INITRD or CMDLINE), decompressed_buf is allocated by merge_decompressed_data() but not stored or freed. Is this intentional, or should decompressed_buf be freed in the default case?

kernel/kexec_bpf_loader.c static int __init kexec_bpf_prog_run_init(void)

Quoted 9 lines
kernel/kexec_bpf_loader.c +9 -0
+			}
+		}
+		break;
+	default:
+		break;
+	}
+
+	return 0;
+}

---
AI reviewed your patch. Please fix the bug or email reply why it's not a bug.
See: https://github.com/kernel-patches/vmtest/blob/master/ci/claude/README.md

CI run summary: https://github.com/kernel-patches/bpf/actions/runs/21147860407

#16 lore raw

PATCH v6 7/13 kexec_file: Implement copy method for parser

In reply to Pingfan Liu

Copying the bpf code parsing result to the proper place:
image->kernel_buf, initrd_buf, cmdline_buf.

Cc Baoquan He <[email protected]>
Cc Dave Young <[email protected]>
Cc Andrew Morton <[email protected]>
Cc Philipp Rudo <[email protected]>

To: [email protected]

---
 kernel/kexec_bpf_loader.c | 27 +++++++++++++++++++++++++++
 1 file changed, 27 insertions(+)
kernel/kexec_bpf_loader.c +27 -0
index bd6a47fc53ed3..5ad67672dead1 100644
@@ -82,6 +82,7 @@ static int __init kexec_bpf_prog_run_init(void)
 late_initcall(kexec_bpf_prog_run_init);
 
 #define KEXEC_BPF_CMD_DECOMPRESS	0x1
+#define KEXEC_BPF_CMD_COPY		0x2
 
 #define KEXEC_BPF_SUBCMD_KERNEL		0x1
 #define KEXEC_BPF_SUBCMD_INITRD		0x2
@@ -281,6 +282,32 @@ static int kexec_buff_parser(struct bpf_parser_context *parser)
 			}
 		}
 		break;
+	case KEXEC_BPF_CMD_COPY:
+		p = __vmalloc(cmd->payload_len, GFP_KERNEL | __GFP_ACCOUNT);
+		if (!p)
+			return -ENOMEM;
+		memcpy(p, buf, cmd->payload_len);
+		switch (cmd->subcmd) {
+		case KEXEC_BPF_SUBCMD_KERNEL:
+			vfree(ctx->kernel);
+			ctx->kernel = p;
+			ctx->kernel_sz = cmd->payload_len;
+			break;
+		case KEXEC_BPF_SUBCMD_INITRD:
+			vfree(ctx->initrd);
+			ctx->initrd = p;
+			ctx->initrd_sz = cmd->payload_len;
+			break;
+		case KEXEC_BPF_SUBCMD_CMDLINE:
+			vfree(ctx->cmdline);
+			ctx->cmdline = p;
+			ctx->cmdline_sz = cmd->payload_len;
+			break;
+		default:
+			vfree(p);
+			break;
+		}
+		break;
 	default:
 		break;
 	}
Signature · 1 line
2.49.0
#17 lore raw

PATCH v6 8/13 kexec_file: Introduce a bpf-prog lskel to parse PE file

In reply to Pingfan Liu

Analague to kernel/bpf/preload/iterators/Makefile,
this Makefile is not invoked by the Kbuild system. It needs to be invoked manually when kexec_pe_parser_bpf.c is changed so that kexec_pe_parser_bpf.lskel.h can be re-generated by the command "bpftool gen skeleton -L kexec_pe_parser_bpf.o".

kexec_pe_parser_bpf.lskel.h is used directly by the kernel kexec code in later patch. For this patch, there are bpf bytecode contained in opts_data[] and opts_insn[] in kexec_pe_parser_bpf.lskel.h, but in the following patch, they will be removed and only the function API in kexec_pe_parser_bpf.lskel.h left.

As exposed in kexec_pe_parser_bpf.lskel.h, the interface between bpf-prog and the kernel are constituted by:

four maps:

                struct bpf_map_desc ringbuf_1;
                struct bpf_map_desc ringbuf_2;
                struct bpf_map_desc ringbuf_3;
                struct bpf_map_desc ringbuf_4;
four sections:
                struct bpf_map_desc rodata;
                struct bpf_map_desc data;
                struct bpf_map_desc rodata_str1_1;
                struct bpf_map_desc bss;

one prog:
SEC("fentry.s/kexec_image_parser_anchor")

The interface of maps and sections are extracted in template.c, which should be included by any bpf-prog to interact with kexec_bpf component

Cc Alexei Starovoitov <[email protected]>
Cc Baoquan He <[email protected]>
Cc Dave Young <[email protected]>
Cc Andrew Morton <[email protected]>
Cc Philipp Rudo <[email protected]>

To: [email protected]

---
 kernel/kexec_bpf/Makefile                    |  62 ++++
 kernel/kexec_bpf/kexec_pe_parser_bpf.c       |  12 +
 kernel/kexec_bpf/kexec_pe_parser_bpf.lskel.h | 372 +++++++++++++++++++
 kernel/kexec_bpf/template.c                  |  68 ++++
 4 files changed, 514 insertions(+)
 create mode 100644 kernel/kexec_bpf/Makefile
 create mode 100644 kernel/kexec_bpf/kexec_pe_parser_bpf.c
 create mode 100644 kernel/kexec_bpf/kexec_pe_parser_bpf.lskel.h
 create mode 100644 kernel/kexec_bpf/template.c
kernel/kexec_bpf/Makefile new file +62 -0
new file mode 100644
index 0000000000000..45d45cc0855a3
@@ -0,0 +1,62 @@
+# SPDX-License-Identifier: GPL-2.0
+OUTPUT := .output
+CLANG ?= clang
+LLC ?= llc
+LLVM_STRIP ?= llvm-strip
+DEFAULT_BPFTOOL := $(OUTPUT)/sbin/bpftool
+BPFTOOL ?= $(DEFAULT_BPFTOOL)
+LIBBPF_SRC := $(abspath ../../tools/lib/bpf)
+BPFOBJ := $(OUTPUT)/libbpf.a
+BPF_INCLUDE := $(OUTPUT)
+INCLUDES := -I$(OUTPUT) -I$(BPF_INCLUDE) -I$(abspath ../../tools/lib)        \
+       -I$(abspath ../../tools/include/uapi)
+CFLAGS := -g -Wall
+
+srctree := $(patsubst %/kernel/kexec_bpf,%,$(CURDIR))
+VMLINUX = $(srctree)/vmlinux
+
+abs_out := $(abspath $(OUTPUT))
+ifeq ($(V),1)
+Q =
+msg =
+else
+Q = @
+msg = @printf '  %-8s %s%s\n' "$(1)" "$(notdir $(2))" "$(if $(3), $(3))";
+MAKEFLAGS += --no-print-directory
+submake_extras := feature_display=0
+endif
+
+.DELETE_ON_ERROR:
+
+.PHONY: all clean
+
+all: $(OUTPUT) kexec_pe_parser_bpf.lskel.h
+
+clean:
+	$(call msg,CLEAN)
+	$(Q)rm -rf $(OUTPUT) kexec_pe_parser_bpf.lskel.h
+
+kexec_pe_parser_bpf.lskel.h: $(OUTPUT)/kexec_pe_parser_bpf.o | $(BPFTOOL)
+	$(call msg,GEN-SKEL,$@)
+	$(Q)$(BPFTOOL) gen skeleton -L $< > $@
+
+$(OUTPUT)/vmlinux.h: $(VMLINUX) $(DEFAULT_BPFTOOL) $(BPFOBJ) | $(OUTPUT)
+	@$(BPFTOOL) btf dump file $(VMLINUX) format c > $(OUTPUT)/vmlinux.h
+
+$(OUTPUT)/kexec_pe_parser_bpf.o: kexec_pe_parser_bpf.c $(OUTPUT)/vmlinux.h $(BPFOBJ) | $(OUTPUT)
+	$(call msg,BPF,$@)
+	$(Q)$(CLANG) -g -O2 -target bpf $(INCLUDES)			      \
+		 -c $(filter %.c,$^) -o $@ &&				      \
+	$(LLVM_STRIP) -g $@
+
+$(OUTPUT):
+	$(call msg,MKDIR,$@)
+	$(Q)mkdir -p $(OUTPUT)
+
+$(BPFOBJ): $(wildcard $(LIBBPF_SRC)/*.[ch] $(LIBBPF_SRC)/Makefile) | $(OUTPUT)
+	$(Q)$(MAKE) $(submake_extras) -C $(LIBBPF_SRC)			       \
+		    OUTPUT=$(abspath $(dir $@))/ $(abspath $@)
+
+$(DEFAULT_BPFTOOL):
+	$(Q)$(MAKE) $(submake_extras) -C ../../tools/bpf/bpftool			      \
+		    prefix= OUTPUT=$(abs_out)/ DESTDIR=$(abs_out) install
kernel/kexec_bpf/kexec_pe_parser_bpf.c new file +12 -0
new file mode 100644
index 0000000000000..e4a2419240673
@@ -0,0 +1,12 @@
+// SPDX-License-Identifier: GPL-2.0
+//
+// Copyright (C) 2025, 2026 Red Hat, Inc
+
+#include "template.c"
+
+SEC("fentry.s/kexec_image_parser_anchor")
+__attribute__((used)) int BPF_PROG(parse_pe, struct kexec_context *context,
+				unsigned long parser_id)
+{
+	return 0;
+}
kernel/kexec_bpf/kexec_pe_parser_bpf.lskel.h new file +372 -0

372 lines not on this page · raw message

kernel/kexec_bpf/template.c new file +68 -0

68 lines not on this page · raw message

Signature · 1 line
2.49.0
#18 lore raw

PATCH v6 9/13 kexec_file: Factor out routine to find a symbol in ELF

In reply to Pingfan Liu

The routine to search a symbol in ELF can be shared, so split it out.

Cc Baoquan He <[email protected]>
Cc Dave Young <[email protected]>
Cc Andrew Morton <[email protected]>
Cc Philipp Rudo <[email protected]>

To: [email protected]

---
 kernel/kexec_file.c     | 86 ++++++++++++++++++++++-------------------
 kernel/kexec_internal.h |  1 +
 2 files changed, 47 insertions(+), 40 deletions(-)
kernel/kexec_file.c +46 -40
index f9674bb5bd8db..9731019ba2a1a 100644
@@ -889,6 +889,51 @@ static int kexec_calculate_store_digests(struct kimage *image)
 	return ret;
 }
 
+#if defined(CONFIG_ARCH_SUPPORTS_KEXEC_PURGATORY) || defined(CONFIG_KEXEC_BPF)
+const Elf_Sym *elf_find_symbol(const Elf_Ehdr *ehdr, const char *name)
+{
+	const Elf_Shdr *sechdrs;
+	const Elf_Sym *syms;
+	const char *strtab;
+	int i, k;
+
+	sechdrs = (void *)ehdr + ehdr->e_shoff;
+
+	for (i = 0; i < ehdr->e_shnum; i++) {
+		if (sechdrs[i].sh_type != SHT_SYMTAB)
+			continue;
+
+		if (sechdrs[i].sh_link >= ehdr->e_shnum)
+			/* Invalid strtab section number */
+			continue;
+		strtab = (void *)ehdr + sechdrs[sechdrs[i].sh_link].sh_offset;
+		syms = (void *)ehdr + sechdrs[i].sh_offset;
+
+		/* Go through symbols for a match */
+		for (k = 0; k < sechdrs[i].sh_size/sizeof(Elf_Sym); k++) {
+			if (ELF_ST_BIND(syms[k].st_info) != STB_GLOBAL)
+				continue;
+
+			if (strcmp(strtab + syms[k].st_name, name) != 0)
+				continue;
+
+			if (syms[k].st_shndx == SHN_UNDEF ||
+			    syms[k].st_shndx >= ehdr->e_shnum) {
+				pr_debug("Symbol: %s has bad section index %d.\n",
+						name, syms[k].st_shndx);
+				return NULL;
+			}
+
+			/* Found the symbol we are looking for */
+			return &syms[k];
+		}
+	}
+
+	return NULL;
+}
+
+#endif
+
 #ifdef CONFIG_ARCH_SUPPORTS_KEXEC_PURGATORY
 /*
  * kexec_purgatory_setup_kbuf - prepare buffer to load purgatory.
@@ -1146,49 +1191,10 @@ int kexec_load_purgatory(struct kimage *image, struct kexec_buf *kbuf)
 static const Elf_Sym *kexec_purgatory_find_symbol(struct purgatory_info *pi,
 						  const char *name)
 {
-	const Elf_Shdr *sechdrs;
-	const Elf_Ehdr *ehdr;
-	const Elf_Sym *syms;
-	const char *strtab;
-	int i, k;
-
 	if (!pi->ehdr)
 		return NULL;
 
-	ehdr = pi->ehdr;
-	sechdrs = (void *)ehdr + ehdr->e_shoff;
-
-	for (i = 0; i < ehdr->e_shnum; i++) {
-		if (sechdrs[i].sh_type != SHT_SYMTAB)
-			continue;
-
-		if (sechdrs[i].sh_link >= ehdr->e_shnum)
-			/* Invalid strtab section number */
-			continue;
-		strtab = (void *)ehdr + sechdrs[sechdrs[i].sh_link].sh_offset;
-		syms = (void *)ehdr + sechdrs[i].sh_offset;
-
-		/* Go through symbols for a match */
-		for (k = 0; k < sechdrs[i].sh_size/sizeof(Elf_Sym); k++) {
-			if (ELF_ST_BIND(syms[k].st_info) != STB_GLOBAL)
-				continue;
-
-			if (strcmp(strtab + syms[k].st_name, name) != 0)
-				continue;
-
-			if (syms[k].st_shndx == SHN_UNDEF ||
-			    syms[k].st_shndx >= ehdr->e_shnum) {
-				pr_debug("Symbol: %s has bad section index %d.\n",
-						name, syms[k].st_shndx);
-				return NULL;
-			}
-
-			/* Found the symbol we are looking for */
-			return &syms[k];
-		}
-	}
-
-	return NULL;
+	return elf_find_symbol(pi->ehdr, name);
 }
 
 void *kexec_purgatory_get_symbol_addr(struct kimage *image, const char *name)
kernel/kexec_internal.h +1 -0
index ee01d0c8bb377..2e8e0fedbe2a9 100644
@@ -40,6 +40,7 @@ extern bool pe_has_bpf_section(const char *file_buf, unsigned long pe_sz);
 extern int pe_get_section(const char *file_buf, const char *sect_name,
 		char **sect_start, unsigned long *sect_sz);
 extern int decompose_kexec_image(struct kimage *image, int extended_fd);
+extern const Elf_Sym *elf_find_symbol(const Elf_Ehdr *ehdr, const char *name);
 #else /* CONFIG_KEXEC_FILE */
 static inline void kimage_file_post_load_cleanup(struct kimage *image) { }
 #endif /* CONFIG_KEXEC_FILE */
Signature · 1 line
2.49.0
#19 lore raw

PATCH v6 10/13 kexec_file: Integrate bpf light skeleton to load image with bpf-prog

In reply to Pingfan Liu

All kexec PE bpf prog should align with the interface exposed by the light skeleton

    four maps:
                    struct bpf_map_desc ringbuf_1;
                    struct bpf_map_desc ringbuf_2;
                    struct bpf_map_desc ringbuf_3;
                    struct bpf_map_desc ringbuf_4;
    four sections:
                    struct bpf_map_desc rodata;
                    struct bpf_map_desc data;
                    struct bpf_map_desc rodata_str1_1;
                    struct bpf_map_desc bss;
    one prog:
            SEC("fentry.s/kexec_image_parser_anchor")

With the above presumption, the integration consists of two parts:
-1. Call API exposed by light skeleton from kexec
-2. The opts_insn[] and opts_data[] are bpf-prog dependent and
can be extracted and passed in from the user space. In the kexec_file_load design, a PE file has a .bpf section, which data content is a ELF, and the ELF contains opts_insn[] opts_data[]. As a bonus, BPF bytecode can be placed under the protection of the entire PE signature.
(Note, since opts_insn[] contains the information of the ringbuf
size, the bpf-prog writer can change its proper size according to the kernel image size without modifying the kernel code)

Cc Alexei Starovoitov <[email protected]>
Cc Baoquan He <[email protected]>
Cc Dave Young <[email protected]>
Cc Andrew Morton <[email protected]>
Cc Philipp Rudo <[email protected]>

To: [email protected]

---
 kernel/Makefile                              |   1 +
 kernel/kexec_bpf/Makefile                    |   8 +
 kernel/kexec_bpf/kexec_pe_parser_bpf.lskel.h | 254 +------------------
 kernel/kexec_bpf_loader.c                    |  48 ++++
 4 files changed, 63 insertions(+), 248 deletions(-)
kernel/Makefile +1 -0
index 05177a867690d..a1c5f5fb02770 100644
@@ -143,6 +143,7 @@ obj-$(CONFIG_SYSCTL_KUNIT_TEST) += sysctl-test.o
 
 CFLAGS_kstack_erase.o += $(DISABLE_KSTACK_ERASE)
 CFLAGS_kstack_erase.o += $(call cc-option,-mgeneral-regs-only)
+CFLAGS_kexec_bpf_loader.o += -I$(srctree)/tools/lib
 obj-$(CONFIG_KSTACK_ERASE) += kstack_erase.o
 KASAN_SANITIZE_kstack_erase.o := n
 KCSAN_SANITIZE_kstack_erase.o := n
kernel/kexec_bpf/Makefile +8 -0
index 45d45cc0855a3..88e92eb910f64 100644
@@ -39,6 +39,14 @@ clean:
 kexec_pe_parser_bpf.lskel.h: $(OUTPUT)/kexec_pe_parser_bpf.o | $(BPFTOOL)
 	$(call msg,GEN-SKEL,$@)
 	$(Q)$(BPFTOOL) gen skeleton -L $< > $@
+	@# The following sed commands make opts_data[] and opts_insn[] visible in a file instead of only in a function.
+	@# And it removes the bytecode
+	$(Q) sed -i '/static const char opts_data\[\].*=/,/";$$/d' $@
+	$(Q) sed -i '/static const char opts_insn\[\].*=/,/";$$/d' $@
+	$(Q) sed -i \
+		-e 's/opts\.data_sz = sizeof(opts_data) - 1;/opts.data_sz = opts_data_sz;/' \
+		-e 's/opts\.insns_sz = sizeof(opts_insn) - 1;/opts.insns_sz = opts_insn_sz;/' $@
+	$(Q) sed -i '7i static char *opts_data, *opts_insn;\nstatic unsigned int opts_data_sz, opts_insn_sz;' $@
 
 $(OUTPUT)/vmlinux.h: $(VMLINUX) $(DEFAULT_BPFTOOL) $(BPFOBJ) | $(OUTPUT)
 	@$(BPFTOOL) btf dump file $(VMLINUX) format c > $(OUTPUT)/vmlinux.h
kernel/kexec_bpf/kexec_pe_parser_bpf.lskel.h +6 -248

282 lines not on this page · raw message

kernel/kexec_bpf_loader.c +48 -0

62 lines not on this page · raw message

Signature · 1 line
2.49.0
#20 lore raw

Re: [PATCHv6 10/13] kexec_file: Integrate bpf light skeleton to load image with bpf-prog

The elf_size parameter is declared but never used in this function. The pointer calculations at ehdr->e_shoff, shdr[sym->st_shndx], and dst_shdr->sh_offset + sym->st_value could all access memory…
Quoted 4 lines
kernel/kexec_bpf_loader.c +0 -0
index 5ad67672dead..9f1c5aede42e 100644

[ ... ]

Quoted 9 lines
kernel/kexec_bpf_loader.c +9 -0
+static void *get_symbol_from_elf(const char *elf_data, size_t elf_size,
+		const char *symbol_name, unsigned int *symbol_size)
+{
+	Elf_Ehdr *ehdr = (Elf_Ehdr *)elf_data;
+	Elf_Shdr *shdr, *dst_shdr;
+	const Elf_Sym *sym;
+	void *symbol_data;
+
+	if (memcmp(ehdr->e_ident, ELFMAG, SELFMAG) != 0) {

kernel/kexec_bpf_loader.c line 48

Quoted 10 lines
kernel/kexec_bpf_loader.c +10 -0
+		pr_err("Not a valid ELF file\n");
+		return NULL;
+	}
+
+	sym = elf_find_symbol(ehdr, symbol_name);
+	if (!sym)
+		return NULL;
+	shdr = (struct elf_shdr *)(elf_data + ehdr->e_shoff);
+	dst_shdr = &shdr[sym->st_shndx];
+	symbol_data = (void *)(elf_data + dst_shdr->sh_offset + sym->st_value);
                                         ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

The elf_size parameter is declared but never used in this function. The pointer calculations at ehdr->e_shoff, shdr[sym->st_shndx], and dst_shdr->sh_offset + sym->st_value could all access memory beyond the ELF buffer if the ELF data is malformed. Should there be bounds checking against elf_size to prevent out-of-bounds reads?

Quoted 8 lines
kernel/kexec_bpf_loader.c +5 -0
+	*symbol_size = sym->st_size;
+
+	return symbol_data;
+}
+
 /* Load a ELF */
 static int arm_bpf_prog(char *bpf_elf, unsigned long sz)
 {

kernel/kexec_bpf_loader.c line 66

Quoted 10 lines
kernel/kexec_bpf_loader.c +10 -0
+	opts_data = get_symbol_from_elf(bpf_elf, sz, "opts_data", &opts_data_sz);
+	opts_insn = get_symbol_from_elf(bpf_elf, sz, "opts_insn", &opts_insn_sz);
+	if (!opts_data || !opts_insn)
+		return -1;
+	/*
+	 * When light skeleton generates opts_data[] and opts_insn[], it appends a
+	 * NULL terminator at the end of string
+	 */
+	opts_data_sz = opts_data_sz - 1;
+	opts_insn_sz = opts_insn_sz - 1;
                      ^^^^^^^^^^^^^^^^^^

If sym->st_size is 0 for either opts_data or opts_insn symbols in the ELF, then opts_data_sz or opts_insn_sz would be 0 after get_symbol_from_elf() returns. Subtracting 1 from an unsigned int with value 0 would cause an integer underflow to UINT_MAX. This large value would then be passed to bpf_load_and_run() via the opts structure. Would it make sense to check that opts_data_sz and opts_insn_sz are non-zero before the subtraction?

kernel/kexec_bpf_loader.c line 74

Quoted 8 lines
kernel/kexec_bpf_loader.c +7 -0
+
+	pe_parser = kexec_pe_parser_bpf__open_and_load();
+	if (!pe_parser)
+		return -1;
+	kexec_pe_parser_bpf__attach(pe_parser);
+
+	return 0;
 }

[ ... ]

---
AI reviewed your patch. Please fix the bug or email reply why it's not a bug.
See: https://github.com/kernel-patches/vmtest/blob/master/ci/claude/README.md

CI run summary: https://github.com/kernel-patches/bpf/actions/runs/21147860407

#21 lore raw

PATCH v6 11/13 arm64/kexec: Select KEXEC_BPF to support UEFI-style kernel image

In reply to Pingfan Liu

Now everything is ready for kexec PE image parser. Select it on arm64 for zboot and UKI image support.

Cc Catalin Marinas <[email protected]>
Cc Will Deacon <[email protected]>

To: [email protected]

---
 arch/arm64/Kconfig | 1 +
 1 file changed, 1 insertion(+)
arch/arm64/Kconfig +1 -0
index 93173f0a09c7d..922d58abbbd67 100644
@@ -1587,6 +1587,7 @@ config ARCH_SELECTS_KEXEC_FILE
 	def_bool y
 	depends on KEXEC_FILE
 	select HAVE_IMA_KEXEC if IMA
+	select KEXEC_BPF if DEBUG_INFO_BTF && BPF_SYSCALL
 
 config ARCH_SUPPORTS_KEXEC_SIG
 	def_bool y
Signature · 1 line
2.49.0
#22 lore raw

Re: [PATCHv6 11/13] arm64/kexec: Select KEXEC_BPF to support UEFI-style kernel image

kernel test robot noticed the following build warnings:

Hi Pingfan,

kernel test robot noticed the following build warnings:

[auto build test WARNING on bpf-next/net]
[also build test WARNING on bpf-next/master bpf/master akpm-mm/mm-nonmm-unstable linus/master v6.19-rc6 next-20260116] [If your patch is applied to the wrong git tree, kindly drop us a note.
And when submitting patch, we suggest to use '--base' as documented in
https://git-scm.com/docs/git-format-patch#_base_tree_information]

url:    https://github.com/intel-lab-lkp/linux/commits/Pingfan-Liu/bpf-Introduce-kfuncs-to-parser-buffer-content/20260119-112939
base:   https://git.kernel.org/pub/scm/linux/kernel/git/bpf/bpf-next.git net
patch link:    https://lore.kernel.org/r/20260119032424.10781-12-piliu%40redhat.com
patch subject: [PATCHv6 11/13] arm64/kexec: Select KEXEC_BPF to support UEFI-style kernel image
config: arm64-randconfig-004-20260119 (https://download.01.org/0day-ci/archive/20260119/[email protected]/config)
compiler: clang version 20.1.8 (https://github.com/llvm/llvm-project 87f0227cb60147a26a1eeb4fb06e3b505e9c7261)
reproduce (this is a W=1 build): (https://download.01.org/0day-ci/archive/20260119/[email protected]/reproduce)

If you fix the issue in a separate patch/commit (i.e. not just a new version of the same patch/commit), kindly add following tags
| Reported-by: kernel test robot <[email protected]>
| Closes: https://lore.kernel.org/oe-kbuild-all/[email protected]/

All warnings (new ones prefixed by >>):

>> kernel/kexec_bpf_loader.c:103:22: warning: unknown attribute 'optimize' ignored [-Wunknown-attributes]
     103 | __attribute__((used, optimize("O0"))) void kexec_image_parser_anchor(
         |                      ^~~~~~~~~~~~~~

1 warning generated.

Kconfig warnings: (for reference only)
WARNING: unmet direct dependencies detected for KEXEC_BPF
Depends on [n]: KEXEC_FILE [=y] && DEBUG_INFO_BTF [=y] && BPF_SYSCALL [=y] && KEEP_DECOMPRESSOR [=n] Selected by [y]:
- ARCH_SELECTS_KEXEC_FILE [=y] && KEXEC_FILE [=y] && DEBUG_INFO_BTF [=y] && BPF_SYSCALL [=y]

vim +/optimize +103 kernel/kexec_bpf_loader.c

e683ae405ea0458 Pingfan Liu 2026-01-19   93  
e683ae405ea0458 Pingfan Liu 2026-01-19   94  void kexec_image_parser_anchor(struct kexec_context *context,
e683ae405ea0458 Pingfan Liu 2026-01-19   95  		unsigned long parser_id);
e683ae405ea0458 Pingfan Liu 2026-01-19   96  
e683ae405ea0458 Pingfan Liu 2026-01-19   97  /*
e683ae405ea0458 Pingfan Liu 2026-01-19   98   * optimize("O0") prevents inline, compiler constant propagation
e683ae405ea0458 Pingfan Liu 2026-01-19   99   *
e683ae405ea0458 Pingfan Liu 2026-01-19  100   * Let bpf be the program context pointer so that it will not be spilled into
e683ae405ea0458 Pingfan Liu 2026-01-19  101   * stack.
e683ae405ea0458 Pingfan Liu 2026-01-19  102   */
e683ae405ea0458 Pingfan Liu 2026-01-19 @103  __attribute__((used, optimize("O0"))) void kexec_image_parser_anchor(
e683ae405ea0458 Pingfan Liu 2026-01-19  104  		struct kexec_context *context,
e683ae405ea0458 Pingfan Liu 2026-01-19  105  		unsigned long parser_id)
e683ae405ea0458 Pingfan Liu 2026-01-19  106  {
e683ae405ea0458 Pingfan Liu 2026-01-19  107  	/*
e683ae405ea0458 Pingfan Liu 2026-01-19  108  	 * To prevent linker from Identical Code Folding (ICF) with kexec_image_parser_anchor,
e683ae405ea0458 Pingfan Liu 2026-01-19  109  	 * making them have different code.
e683ae405ea0458 Pingfan Liu 2026-01-19  110  	 */
e683ae405ea0458 Pingfan Liu 2026-01-19  111  	volatile int dummy = 0;
e683ae405ea0458 Pingfan Liu 2026-01-19  112  
e683ae405ea0458 Pingfan Liu 2026-01-19  113  	dummy += 1;
e683ae405ea0458 Pingfan Liu 2026-01-19  114  }
e683ae405ea0458 Pingfan Liu 2026-01-19  115  
Signature · 2 lines
0-DAY CI Kernel Test Service
https://github.com/intel/lkp-tests/wiki
#23 lore raw

Re: [PATCHv6 11/13] arm64/kexec: Select KEXEC_BPF to support UEFI-style kernel image

In reply to Pingfan Liu
Should this condition also include KEEP_DECOMPRESSOR?

arch/arm64/Kconfig config ARCH_SELECTS_KEXEC_FILE · line 1590

Quoted 9 lines
arch/arm64/Kconfig +1 -0
index 93173f0a09c7..922d58abbbd6 100644
@@ -1587,6 +1587,7 @@ config ARCH_SELECTS_KEXEC_FILE
 	def_bool y
 	depends on KEXEC_FILE
 	select HAVE_IMA_KEXEC if IMA
+	select KEXEC_BPF if DEBUG_INFO_BTF && BPF_SYSCALL
                          ^^^

Should this condition also include KEEP_DECOMPRESSOR?

In kernel/Kconfig.kexec, KEXEC_BPF has:

    depends on DEBUG_INFO_BTF && BPF_SYSCALL && KEEP_DECOMPRESSOR

Since Kconfig's select statement forces a symbol's value without visiting the dependencies, this select will enable KEXEC_BPF even when KEEP_DECOMPRESSOR is not set, creating an inconsistent configuration.

KEEP_DECOMPRESSOR defaults to n and nothing selects it, so this appears to be a missing condition in the select statement.

---
AI reviewed your patch. Please fix the bug or email reply why it's not a bug.
See: https://github.com/kernel-patches/vmtest/blob/master/ci/claude/README.md

CI run summary: https://github.com/kernel-patches/bpf/actions/runs/21147860407

#24 lore raw

PATCH v6 12/13 tools/kexec: Introduce a bpf-prog to parse zboot image format

In reply to Pingfan Liu

This BPF program aligns with the convention defined in the kernel file kexec_pe_parser_bpf.lskel.h. This can be easily achieved by include "template.c", which includes:

    four maps:
                    struct bpf_map_desc ringbuf_1;
                    struct bpf_map_desc ringbuf_2;
                    struct bpf_map_desc ringbuf_3;
                    struct bpf_map_desc ringbuf_4;
    four sections:
                    struct bpf_map_desc rodata;
                    struct bpf_map_desc data;
                    struct bpf_map_desc bss;
                    struct bpf_map_desc rodata_str1_1;

The only left thing is to implement a prog SEC("fentry.s/kexec_image_parser_anchor")
int BPF_PROG(parse_pe, struct kexec_context *context, unsigned long parser_id)

This BPF program only uses ringbuf_1, so it minimizes the size of the other three ringbufs to one byte. The size of ringbuf_1 is derived from the size of the uncompressed file 'vmlinux.bin', which is usually less than 64MB. With the help of the BPF kfunc bpf_buffer_parser(), the BPF program passes instructions to the kexec BPF component to perform the appropriate actions.

Cc Alexei Starovoitov <[email protected]>
Cc Baoquan He <[email protected]>
Cc Dave Young <[email protected]>
Cc Andrew Morton <[email protected]>
Cc Philipp Rudo <[email protected]>

To: [email protected]

---
 tools/kexec/Makefile           |  83 ++++++++++++++++++++++++
 tools/kexec/template.c         |  68 ++++++++++++++++++++
 tools/kexec/zboot_parser_bpf.c | 114 +++++++++++++++++++++++++++++++++
 3 files changed, 265 insertions(+)
 create mode 100644 tools/kexec/Makefile
 create mode 100644 tools/kexec/template.c
 create mode 100644 tools/kexec/zboot_parser_bpf.c
tools/kexec/Makefile new file +83 -0
new file mode 100644
index 0000000000000..88db6d11bde61
@@ -0,0 +1,83 @@
+# SPDX-License-Identifier: GPL-2.0
+
+# Ensure Kbuild variables are available
+include ../scripts/Makefile.include
+
+srctree := $(patsubst %/tools/kexec,%,$(CURDIR))
+VMLINUX = $(srctree)/vmlinux
+TOOLSDIR := $(srctree)/tools
+LIBDIR := $(TOOLSDIR)/lib
+BPFDIR := $(LIBDIR)/bpf
+ARCH ?= $(shell uname -m | sed -e s/i.86/x86/ -e s/x86_64/x86/ -e s/aarch64.*/arm64/ -e s/riscv64/riscv/ -e s/loongarch.*/loongarch/)
+# At present, zboot image format is used by arm64, riscv, loongarch
+# And arch/$(ARCH)/boot/vmlinux.bin is the uncompressed file instead of arch/$(ARCH)/boot/Image
+ifeq ($(ARCH),$(filter $(ARCH),arm64 riscv loongarch))
+	EFI_IMAGE := $(srctree)/arch/$(ARCH)/boot/vmlinuz.efi
+	KERNEL_IMAGE := $(srctree)/arch/$(ARCH)/boot/vmlinux.bin
+else
+	@echo "Unsupported architecture: $(ARCH)"
+	@exit 1
+endif
+
+
+CC = clang
+CFLAGS = -O2
+BPF_PROG_CFLAGS = -g -O2 -target bpf -Wall -I $(BPFDIR) -I .
+BPFTOOL = bpftool
+
+# List of generated target files
+HEADERS = vmlinux.h bpf_helper_defs.h image_size.h
+ZBOOT_TARGETS = zboot_parser_bpf.o zboot_parser_bpf.lskel.h bytecode.c bytecode.o
+
+
+# Targets
+zboot: $(HEADERS) $(ZBOOT_TARGETS)
+
+# Rule to generate vmlinux.h from vmlinux
+vmlinux.h: $(VMLINUX)
+	@command -v $(BPFTOOL) >/dev/null 2>&1 || { echo >&2 "$(BPFTOOL) is required but not found. Please install it."; exit 1; }
+	@$(BPFTOOL) btf dump file $(VMLINUX) format c > vmlinux.h
+
+bpf_helper_defs.h: $(srctree)/tools/include/uapi/linux/bpf.h
+	@$(QUIET_GEN)$(srctree)/scripts/bpf_doc.py --header \
+		--file $(srctree)/tools/include/uapi/linux/bpf.h > bpf_helper_defs.h
+
+image_size.h: $(KERNEL_IMAGE)
+	@{ \
+		if [ ! -f "$(KERNEL_IMAGE)" ]; then \
+			echo "Error: File '$(KERNEL_IMAGE)' does not exist"; \
+			exit 1; \
+		fi; \
+		FILE_SIZE=$$(stat -c '%s' "$(KERNEL_IMAGE)" 2>/dev/null); \
+		POWER=4096; \
+		while [ $$POWER -le $$FILE_SIZE ]; do \
+			POWER=$$((POWER * 2)); \
+		done; \
+		RINGBUF_SIZE=$$POWER; \
+		echo "#define IMAGE_SIZE_POWER2_ALIGN $$RINGBUF_SIZE" > $@; \
+		echo "#define IMAGE_SIZE $$FILE_SIZE" >> $@; \
+	}
+
+
+# Rule to generate zboot_parser_bpf.o, depends on vmlinux.h
+zboot_parser_bpf.o: zboot_parser_bpf.c vmlinux.h bpf_helper_defs.h
+	@$(CC) $(BPF_PROG_CFLAGS) -c zboot_parser_bpf.c -o zboot_parser_bpf.o
+
+# Generate zboot_parser_bpf.lskel.h using bpftool
+zboot_parser_bpf.lskel.h: zboot_parser_bpf.o
+	@$(BPFTOOL) gen skeleton -L zboot_parser_bpf.o > zboot_parser_bpf.lskel.h
+
+# Then, extract the opts_data[] and opts_insn[] arrays and remove 'static'
+# keywords to avoid being optimized away.
+bytecode.c: zboot_parser_bpf.lskel.h
+	@sed -n '/static const char opts_data\[\]/,/;/p' zboot_parser_bpf.lskel.h | sed 's/static const/const/' > $@
+	@sed -n '/static const char opts_insn\[\]/,/;/p' zboot_parser_bpf.lskel.h | sed 's/static const/const/' >> $@
+
+bytecode.o: bytecode.c
+	@$(CC) -c $< -o $@
+
+# Clean up generated files
+clean:
+	@rm -f $(HEADERS) $(ZBOOT_TARGETS)
+
+.PHONY: all clean
tools/kexec/template.c new file +68 -0

68 lines not on this page · raw message

tools/kexec/zboot_parser_bpf.c new file +114 -0

114 lines not on this page · raw message

Signature · 1 line
2.49.0
#25 lore raw

Re: [PATCHv6 12/13] tools/kexec: Introduce a bpf-prog to parse zboot image format

Should this bounds check also verify that payload_offset + payload_size does not exceed image_sz? The current check only validates that payload_size fits, but if payload_offset is large (e.g., near…
Quoted 5 lines
tools/kexec/zboot_parser_bpf.c new file +0 -0
new file mode 100644
index 000000000000..54c4b762b332

[ ... ]

Quoted 11 lines
tools/kexec/zboot_parser_bpf.c new file +11 -0
+/* see drivers/firmware/efi/libstub/zboot-header.S */
+struct linux_pe_zboot_header {
+	unsigned int mz_magic;
+	char image_type[4];
+	unsigned int payload_offset;
+	unsigned int payload_size;
+	unsigned int reserved[2];
+	char comp_type[4];
+	unsigned int linux_pe_magic;
+	unsigned int pe_header_offset;
+} __attribute__((packed));

[ ... ]

tools/kexec/zboot_parser_bpf.c line 77

Quoted 9 lines
tools/kexec/zboot_parser_bpf.c new file +9 -0
+	unsigned int payload_offset = zboot_header->payload_offset;
+	unsigned int payload_size = zboot_header->payload_size;
+	bpf_printk("zboot image payload offset=0x%x, size=0x%x\n", payload_offset, payload_size);
+	/* sane check */
+	if (payload_size > image_sz) {
+		bpf_ringbuf_discard(buf, BPF_RB_NO_WAKEUP);
+		bpf_printk("Invalid zboot image payload offset and size\n");
+		return 0;
+	}

Should this bounds check also verify that payload_offset + payload_size does not exceed image_sz? The current check only validates that payload_size fits, but if payload_offset is large (e.g., near image_sz), the read below could extend past the end of the kernel buffer.

For example, with payload_offset = image_sz - 10 and payload_size = 100, the check "payload_size > image_sz" passes, but the bpf_probe_read below would read 90 bytes past the valid buffer boundary.

Quoted 4 lines
tools/kexec/zboot_parser_bpf.c new file +4 -0
+	unsigned int max_payload = MAX_RECORD_SIZE - sizeof(struct cmd_hdr);
+	if (payload_size >= max_payload) {
+		bpf_ringbuf_discard(buf, BPF_RB_NO_WAKEUP);
+		bpf_printk("Err: payload_size > MAX_RECORD_SIZE\n");

tools/kexec/zboot_parser_bpf.c line 91

Quoted 10 lines
tools/kexec/zboot_parser_bpf.c new file +10 -0
+		return 0;
+	}
+	void *dst = (void *)buf + sizeof(struct cmd_hdr);
+	/* Overwrite buf */
+	struct cmd_hdr *cmd = (struct cmd_hdr *)buf;
+	cmd->cmd = KEXEC_BPF_CMD_DECOMPRESS;
+	cmd->subcmd = KEXEC_BPF_SUBCMD_KERNEL;
+	/* 4 bytes original size is appended after vmlinuz.bin */
+	cmd->payload_len = payload_size - 4;
+	bpf_probe_read(dst, payload_size, context->kernel + payload_offset);
                                                           ^^^^^^^^^^^^^^^

This is where the out-of-bounds read could occur if payload_offset + payload_size > image_sz. While bpf_probe_read is safe and will not crash (it uses copy_from_kernel_nofault internally), it could read from adjacent kernel memory if the zboot header contains invalid offset/size values.

---
AI reviewed your patch. Please fix the bug or email reply why it's not a bug.
See: https://github.com/kernel-patches/vmtest/blob/master/ci/claude/README.md

CI run summary: https://github.com/kernel-patches/bpf/actions/runs/21147860407

#26 lore raw

PATCH v6 13/13 tools/kexec: Add a zboot image building tool

In reply to Pingfan Liu

The objcopy binary can append a section to a PE file, but it disregards the DOS header. However, the zboot format carries important information in the DOS header: payload offset and size.

To track this information and append a new PE section, here a dedicated binary tool is introduced to build zboot images. The payload's relative offset within the .data section remains unchanged. Therefore, the .data section offset in the new PE file, plus the payload offset within that section, yields the payload offset within the new PE file.

Finally, the new PE file 'zboot.efi', with a .bpf section, can be got by the command:
make -C tools/kexec zboot

Cc Alexei Starovoitov <[email protected]>
Cc Baoquan He <[email protected]>
Cc Dave Young <[email protected]>
Cc Andrew Morton <[email protected]>
Cc Philipp Rudo <[email protected]>

To: [email protected]

---
 tools/kexec/Makefile              |  10 +-
 tools/kexec/pe.h                  | 177 +++++++++++++++++++
 tools/kexec/zboot_image_builder.c | 278 ++++++++++++++++++++++++++++++
 3 files changed, 464 insertions(+), 1 deletion(-)
 create mode 100644 tools/kexec/pe.h
 create mode 100644 tools/kexec/zboot_image_builder.c
tools/kexec/Makefile +9 -1
index 88db6d11bde61..acb045367adfa 100644
@@ -27,7 +27,7 @@ BPFTOOL = bpftool
 
 # List of generated target files
 HEADERS = vmlinux.h bpf_helper_defs.h image_size.h
-ZBOOT_TARGETS = zboot_parser_bpf.o zboot_parser_bpf.lskel.h bytecode.c bytecode.o
+ZBOOT_TARGETS = zboot_parser_bpf.o zboot_parser_bpf.lskel.h bytecode.c bytecode.o zboot_image_builder zboot.efi
 
 
 # Targets
@@ -76,6 +76,14 @@ bytecode.c: zboot_parser_bpf.lskel.h
 bytecode.o: bytecode.c
 	@$(CC) -c $< -o $@
 
+# Rule to build zboot_image_builder executable
+zboot_image_builder: zboot_image_builder.c
+	@$(CC) $(CFLAGS) $< -o $@
+
+zboot.efi: zboot_image_builder bytecode.o
+	@chmod +x zboot_image_builder
+	@./zboot_image_builder $(EFI_IMAGE) bytecode.o $@
+
 # Clean up generated files
 clean:
 	@rm -f $(HEADERS) $(ZBOOT_TARGETS)
tools/kexec/pe.h new file +177 -0

177 lines not on this page · raw message

tools/kexec/zboot_image_builder.c new file +278 -0

278 lines not on this page · raw message

Signature · 1 line
2.49.0
#27 lore raw

Re: [PATCHv6 13/13] tools/kexec: Add a zboot image building tool

This function returns int and can return -1 on error, but the caller stores the result in a uint32_t without checking for errors (see below).
Quoted 5 lines
tools/kexec/pe.h new file +0 -0
new file mode 100644
index 000000000000..c2273d3fc3bb

[ ... ]

Quoted 6 lines
tools/kexec/pe.h new file +6 -0
+/*
+ * Return -1 if not PE, else offset of the PE header
+ */
+static int get_pehdr_offset(const char *buf)
+{
+	int pe_hdr_offset;

tools/kexec/pe.h line 175

Quoted 10 lines
tools/kexec/pe.h new file +10 -0
+
+	pe_hdr_offset = *((int *)(buf + 0x3c));
+	buf += pe_hdr_offset;
+	if (!!memcmp(buf, "PE\0\0", 4)) {
+		printf("Not a PE file\n");
+		return -1;
+	}
+
+	return pe_hdr_offset;
+}

This function returns int and can return -1 on error, but the caller stores the result in a uint32_t without checking for errors (see below).

Quoted 5 lines
tools/kexec/zboot_image_builder.c new file +0 -0
new file mode 100644
index 000000000000..c0a785074970

[ ... ]

tools/kexec/zboot_image_builder.c line 50

Quoted 5 lines
tools/kexec/zboot_image_builder.c new file +5 -0
+int main(int argc, char **argv)
+{
+	uint32_t payload_new_offset, payload_sect_off;
+	uint32_t payload_size;
+	uint32_t payload_sect_idx;
                 ^^^^^^^^^^^^^^^^

Are payload_sect_idx and payload_sect_off intentionally left uninitialized here? If the loop below never finds a matching section, these variables will contain garbage values.

[ ... ]

tools/kexec/zboot_image_builder.c line 112

Quoted 2 lines
tools/kexec/zboot_image_builder.c new file +2 -0
+	uint32_t pe_hdr_offset = get_pehdr_offset((const char *)base_start_addr);
+	base_cur = base_start_addr + pe_hdr_offset;

Is there a missing check for the return value of get_pehdr_offset()? The function returns -1 on error (printing "Not a PE file"), but this code stores it in a uint32_t and uses it directly. If get_pehdr_offset() returns -1, pe_hdr_offset becomes 0xFFFFFFFF, and base_cur will point far past the mapped region.

[ ... ]

tools/kexec/zboot_image_builder.c line 136

Quoted 9 lines
tools/kexec/zboot_image_builder.c new file +9 -0
+	/* Decide the section idx and the payload offset within the section */
+	for (i = 0; i < num_sections; i++) {
+	    sect = &base_sections[i];
+	    if (zheader->payload_offset >= sect->data_addr &&
+		zheader->payload_offset < (sect->data_addr + sect->raw_data_size)) {
+		    payload_sect_idx = i;
+		    payload_sect_off = zheader->payload_offset - sect->data_addr;
+	    }
+	}

If the condition is never true (payload_offset not within any section), payload_sect_idx and payload_sect_off remain uninitialized. They are used later in:

    payload_new_offset = new_sections[payload_sect_idx].data_addr + payload_sect_off;

Could this cause undefined behavior with a malformed input file?

---
AI reviewed your patch. Please fix the bug or email reply why it's not a bug.
See: https://github.com/kernel-patches/vmtest/blob/master/ci/claude/README.md

CI run summary: https://github.com/kernel-patches/bpf/actions/runs/21147860407

#28 lore raw
In reply to Pingfan Liu

Hi Pingfan,

please excuse my late reply. I've looked through the series and all in all it looks fine to me. I've got two comments/questions in addition to what the bpf-bot found. In general the findings from the bpf-bot look valid to me. But fixing them should be rather straight forward. Only for the first finding, where it "complains" that ctx->buf is NULL, I don't understand what it is wants to tell us.

In my opinion the next step we should take is to implement an example bpf-prog for UKIs. I expect it to be much more complex compared to the zboot one. So having a example bpf-prog will show us if we run into any limitations with bpf or need to adjust the interfaces.

Thanks
Philipp

Quoted 151 lines · On Mon, 19 Jan 2026 11:24:11 +0800 Pingfan Liu <[email protected]> wrote:

*** The history ***

Nowadays, UEFI PE bootable images are becoming increasingly popular among distributions. Currently, we have several kinds of image format parsers in user space (kexec-tools). However, this approach breaks the integrity protection of the images. To address this integrity protection concern, several approaches have been proposed to resolve this issue, but none of them have been accepted upstream yet.

The summary of those approaches:
-1. UEFI service emulator for UEFI stub
-2. PE format parser in kernel
-3. Signing the arm64/boot/Image

For the first approach, I tried a purgatory-style emulator [1], but it encounters hardware scaling issues. For the second approach, both zboot-format [2] and UKI-format [3] parsers were rejected due to concerns that variant format parsers would bloat the kernel code. Additionally, for example in arm64, both UKI and zboot format parsers would need to be introduced and chained together to handle image loading. For the third approach, I attempted [4], but since zboot or UKI images already have signatures, upstream maintainers dislike the additional signature on the Image. Moreover, for secure boot UKI, this method cannot use signatures to protect the initramfs.

*** The approach in this series ***

This series introduces an approach that allows image formats to be parsed by BPF programs. As a result, the kexec kernel code can remain relatively stable without introducing new parsers for different architectures. This approach introduces a dedicated '.bpf' section in the PE file, which stores BPF bytecode. The integrity of all components -- kernel, initramfs, cmdline, and even the BPF bytecode itself is protected by the PE file's signature. After signature verification, the BPF bytecode is loaded and executed from within the kernel using BPF lskel. Therefore, the bytecode itself is protected from malicious attacks on the BPF loader in user space.

When a .bpf section is extracted from the current image file, its bytecode is attached to the kexec kernel function kexec_image_parser_anchor(). After the bytecode parses the image, the next-stage image is prepared, and the bytecode in the new .bpf section can be attached to kexec_image_parser_anchor(). In this way, nested image format issues (e.g., zboot image within UKI on arm64) can be resolved. (Theoretically not yet tested.)

*** Thanks ***
I would like to thank Philipp Rudo, whose insights inspired this approach and who dedicated significant time to evaluating its practicality. I am also grateful to Viktor Malik for his guidance on using BPF light skeleton to prevent malicious attacks from user space.

*** Test approach ***
-1. compile kernel
-2. get the zboot image with bpf-prog by 'make -C tools/kexec zboot' -3. compile kexec-tools from https://github.com/pfliu/kexec-tools/tree/pe_bpf

The rest test process is the common convention to use kexec.

[1]: https://lore.kernel.org/lkml/[email protected]/T/
[2]: https://lore.kernel.org/kexec/[email protected]/
[3]: https://lore.kernel.org/lkml/[email protected]/
[4]: https://lore.kernel.org/linux-efi/[email protected]/

*** Changes ***
v5 -> v6
- Re-organize the layers in kexec_file_load into two layers: format-parsing and kernel boot protocol handling.
- Simplify the bpf kfunc interface.
- rebased onto Linux 6.19-rc2

v4 -> v5
- rebased onto Linux 6.17-rc2
- [1/12], use a separate CONFIG_KEEP_COMPRESSOR to decide the section of decompressor method
- [10/12], add Catalin's acked-by (Thanks Catalin!)

v3 -> v4
- Use dynamic allocator in decompression ([4/12])
- Fix issue caused by Identical Code Folding ([5/12])
- Integrate the image generator tool in the kernel tree ([11,12/12])
- Address the issue according to Philipp's comments in v3 reviewing. Thanks Philipp!

RFCv2 -> v3
- move the introduced bpf kfuncs to kernel/bpf/* and mark them sleepable
- use listener and publisher model to implement bpf_copy_to_kernel()
- keep each introduced kfunc under the control of memcg

RFCv1 -> RFCv2
- Use bpf kfunc instead of helper
- Use C source code to generate the light skeleton file

---
Pingfan Liu (13):
bpf: Introduce kfuncs to parser buffer content
kexec_file: Move signature validation ahead
kexec_file: Introduce routines to parse PE file
kexec_file: Use bpf-prog to decompose image lib/decompress: Keep decompressor when CONFIG_KEEP_DECOMPRESSOR
kexec_file: Implement decompress method for parser
kexec_file: Implement copy method for parser
kexec_file: Introduce a bpf-prog lskel to parse PE file
kexec_file: Factor out routine to find a symbol in ELF
kexec_file: Integrate bpf light skeleton to load image with bpf-prog arm64/kexec: Select KEXEC_BPF to support UEFI-style kernel image tools/kexec: Introduce a bpf-prog to parse zboot image format tools/kexec: Add a zboot image building tool

 arch/arm64/Kconfig                           |   1 +
 include/linux/bpf.h                          |  19 +
 include/linux/decompress/mm.h                |   8 +
 kernel/Kconfig.kexec                         |   8 +
 kernel/Makefile                              |   2 +
 kernel/bpf/Makefile                          |   3 +
 kernel/bpf/bpf_buffer_parser.c               | 170 +++++++
 kernel/kexec_bpf/Makefile                    |  70 +++
 kernel/kexec_bpf/kexec_pe_parser_bpf.c       |  12 +
 kernel/kexec_bpf/kexec_pe_parser_bpf.lskel.h | 130 ++++++
 kernel/kexec_bpf/template.c                  |  68 +++
 kernel/kexec_bpf_loader.c                    | 439 +++++++++++++++++++
 kernel/kexec_file.c                          | 106 +++--
 kernel/kexec_internal.h                      |   5 +
 kernel/kexec_uefi_app.c                      |  81 ++++
 lib/Kconfig                                  |   6 +
 lib/decompress.c                             |   6 +-
 tools/kexec/Makefile                         |  91 ++++
 tools/kexec/pe.h                             | 177 ++++++++
 tools/kexec/template.c                       |  68 +++
 tools/kexec/zboot_image_builder.c            | 278 ++++++++++++
 tools/kexec/zboot_parser_bpf.c               | 114 +++++
 22 files changed, 1813 insertions(+), 49 deletions(-)
 create mode 100644 kernel/bpf/bpf_buffer_parser.c
 create mode 100644 kernel/kexec_bpf/Makefile
 create mode 100644 kernel/kexec_bpf/kexec_pe_parser_bpf.c
 create mode 100644 kernel/kexec_bpf/kexec_pe_parser_bpf.lskel.h
 create mode 100644 kernel/kexec_bpf/template.c
 create mode 100644 kernel/kexec_bpf_loader.c
 create mode 100644 kernel/kexec_uefi_app.c
 create mode 100644 tools/kexec/Makefile
 create mode 100644 tools/kexec/pe.h
 create mode 100644 tools/kexec/template.c
 create mode 100644 tools/kexec/zboot_image_builder.c
 create mode 100644 tools/kexec/zboot_parser_bpf.c
#29 lore raw

Hi Philipp,

Thank you for taking the time to look into this.

Quoted 10 lines · Philipp Rudo

Hi Pingfan,

please excuse my late reply. I've looked through the series and all in all it looks fine to me. I've got two comments/questions in addition to what the bpf-bot found. In general the findings from the bpf-bot look valid to me. But fixing them should be rather straight forward. Only for the first finding, where it "complains" that ctx->buf is NULL, I don't understand what it is wants to tell us.

A race condition exists: when bpf_buffer_parser() is called multiple times on ctx, later calls overwrite the previous ctx->buf without releasing it. While re-entrancy is uncommon in this design, it still needs to be addressed.

Quoted 5 lines

In my opinion the next step we should take is to implement an example bpf-prog for UKIs. I expect it to be much more complex compared to the zboot one. So having a example bpf-prog will show us if we run into any limitations with bpf or need to adjust the interfaces.

Yeah, it's a little challenge. The traditional kexec_file_load syscall interface was tailored for the kernel boot protocol. However, with the emergence of Zboot and UKI images, it fails to automatically accommodate these new formats.

Now, with the introduction of decompose_kexec_kimage() to kexec_file_load, the design takes a different approach. It decomposes these complex modern images and then reassembles them into the kernel boot protocol. Consequently, the fds parameter in kexec_file_load() can have more flexible meanings, no longer limited to kernel or initrd file descriptors.

I'm considering two alternative approaches. The first is to introduce an fd array to pass the file descriptors for UKI and cmdline add-ons. The second option is to reuse the current interface but reinterpret the meaning of fds. The first approach requires not just an fd array but also metadata describing the purpose of each file descriptor. In contrast, the second option avoids this complexity.
In the second option, the first fd in kexec_file_load can be used to ship the bpf parsers. the second fd can be used to ship a temporary file, which holds UKI and all addons. Inside the kernel, the bpf parser can extract the PE files embeded inside the temporary file, verify their signature, decide their role and reassemble them. So all details are kept inside the bpf parser without changing the kernel API.

To implement this, the design in this series requires some adjustments. Rather than embedding BPF parsers in PE-based formats like Zboot or UKI, this approach improves the design by keeping the kernel image unmodified.

What is your opinion?

Thanks,

Pingfan

Quoted 158 lines

Thanks
Philipp

Quoted 151 lines · On Mon, 19 Jan 2026 11:24:11 +0800 Pingfan Liu <[email protected]> wrote:

*** The history ***

Nowadays, UEFI PE bootable images are becoming increasingly popular among distributions. Currently, we have several kinds of image format parsers in user space (kexec-tools). However, this approach breaks the integrity protection of the images. To address this integrity protection concern, several approaches have been proposed to resolve this issue, but none of them have been accepted upstream yet.

The summary of those approaches:
-1. UEFI service emulator for UEFI stub
-2. PE format parser in kernel
-3. Signing the arm64/boot/Image

For the first approach, I tried a purgatory-style emulator [1], but it encounters hardware scaling issues. For the second approach, both zboot-format [2] and UKI-format [3] parsers were rejected due to concerns that variant format parsers would bloat the kernel code. Additionally, for example in arm64, both UKI and zboot format parsers would need to be introduced and chained together to handle image loading. For the third approach, I attempted [4], but since zboot or UKI images already have signatures, upstream maintainers dislike the additional signature on the Image. Moreover, for secure boot UKI, this method cannot use signatures to protect the initramfs.

*** The approach in this series ***

This series introduces an approach that allows image formats to be parsed by BPF programs. As a result, the kexec kernel code can remain relatively stable without introducing new parsers for different architectures. This approach introduces a dedicated '.bpf' section in the PE file, which stores BPF bytecode. The integrity of all components -- kernel, initramfs, cmdline, and even the BPF bytecode itself is protected by the PE file's signature. After signature verification, the BPF bytecode is loaded and executed from within the kernel using BPF lskel. Therefore, the bytecode itself is protected from malicious attacks on the BPF loader in user space.

When a .bpf section is extracted from the current image file, its bytecode is attached to the kexec kernel function kexec_image_parser_anchor(). After the bytecode parses the image, the next-stage image is prepared, and the bytecode in the new .bpf section can be attached to kexec_image_parser_anchor(). In this way, nested image format issues (e.g., zboot image within UKI on arm64) can be resolved. (Theoretically not yet tested.)

*** Thanks ***
I would like to thank Philipp Rudo, whose insights inspired this approach and who dedicated significant time to evaluating its practicality. I am also grateful to Viktor Malik for his guidance on using BPF light skeleton to prevent malicious attacks from user space.

*** Test approach ***
-1. compile kernel
-2. get the zboot image with bpf-prog by 'make -C tools/kexec zboot' -3. compile kexec-tools from https://github.com/pfliu/kexec-tools/tree/pe_bpf

The rest test process is the common convention to use kexec.

[1]: https://lore.kernel.org/lkml/[email protected]/T/
[2]: https://lore.kernel.org/kexec/[email protected]/
[3]: https://lore.kernel.org/lkml/[email protected]/
[4]: https://lore.kernel.org/linux-efi/[email protected]/

*** Changes ***
v5 -> v6
- Re-organize the layers in kexec_file_load into two layers: format-parsing and kernel boot protocol handling.
- Simplify the bpf kfunc interface.
- rebased onto Linux 6.19-rc2

v4 -> v5
- rebased onto Linux 6.17-rc2
- [1/12], use a separate CONFIG_KEEP_COMPRESSOR to decide the section of decompressor method
- [10/12], add Catalin's acked-by (Thanks Catalin!)

v3 -> v4
- Use dynamic allocator in decompression ([4/12])
- Fix issue caused by Identical Code Folding ([5/12])
- Integrate the image generator tool in the kernel tree ([11,12/12])
- Address the issue according to Philipp's comments in v3 reviewing. Thanks Philipp!

RFCv2 -> v3
- move the introduced bpf kfuncs to kernel/bpf/* and mark them sleepable
- use listener and publisher model to implement bpf_copy_to_kernel()
- keep each introduced kfunc under the control of memcg

RFCv1 -> RFCv2
- Use bpf kfunc instead of helper
- Use C source code to generate the light skeleton file

---
Pingfan Liu (13):
bpf: Introduce kfuncs to parser buffer content
kexec_file: Move signature validation ahead
kexec_file: Introduce routines to parse PE file
kexec_file: Use bpf-prog to decompose image lib/decompress: Keep decompressor when CONFIG_KEEP_DECOMPRESSOR
kexec_file: Implement decompress method for parser
kexec_file: Implement copy method for parser
kexec_file: Introduce a bpf-prog lskel to parse PE file
kexec_file: Factor out routine to find a symbol in ELF
kexec_file: Integrate bpf light skeleton to load image with bpf-prog arm64/kexec: Select KEXEC_BPF to support UEFI-style kernel image tools/kexec: Introduce a bpf-prog to parse zboot image format tools/kexec: Add a zboot image building tool

 arch/arm64/Kconfig                           |   1 +
 include/linux/bpf.h                          |  19 +
 include/linux/decompress/mm.h                |   8 +
 kernel/Kconfig.kexec                         |   8 +
 kernel/Makefile                              |   2 +
 kernel/bpf/Makefile                          |   3 +
 kernel/bpf/bpf_buffer_parser.c               | 170 +++++++
 kernel/kexec_bpf/Makefile                    |  70 +++
 kernel/kexec_bpf/kexec_pe_parser_bpf.c       |  12 +
 kernel/kexec_bpf/kexec_pe_parser_bpf.lskel.h | 130 ++++++
 kernel/kexec_bpf/template.c                  |  68 +++
 kernel/kexec_bpf_loader.c                    | 439 +++++++++++++++++++
 kernel/kexec_file.c                          | 106 +++--
 kernel/kexec_internal.h                      |   5 +
 kernel/kexec_uefi_app.c                      |  81 ++++
 lib/Kconfig                                  |   6 +
 lib/decompress.c                             |   6 +-
 tools/kexec/Makefile                         |  91 ++++
 tools/kexec/pe.h                             | 177 ++++++++
 tools/kexec/template.c                       |  68 +++
 tools/kexec/zboot_image_builder.c            | 278 ++++++++++++
 tools/kexec/zboot_parser_bpf.c               | 114 +++++
 22 files changed, 1813 insertions(+), 49 deletions(-)
 create mode 100644 kernel/bpf/bpf_buffer_parser.c
 create mode 100644 kernel/kexec_bpf/Makefile
 create mode 100644 kernel/kexec_bpf/kexec_pe_parser_bpf.c
 create mode 100644 kernel/kexec_bpf/kexec_pe_parser_bpf.lskel.h
 create mode 100644 kernel/kexec_bpf/template.c
 create mode 100644 kernel/kexec_bpf_loader.c
 create mode 100644 kernel/kexec_uefi_app.c
 create mode 100644 tools/kexec/Makefile
 create mode 100644 tools/kexec/pe.h
 create mode 100644 tools/kexec/template.c
 create mode 100644 tools/kexec/zboot_image_builder.c
 create mode 100644 tools/kexec/zboot_parser_bpf.c