From 4e2c5051cf3d0540e7c0612a618271cb8ae7bfdc Mon Sep 17 00:00:00 2001 From: Mark Wielaard Date: Tue, 14 Oct 2025 18:21:54 +0200 Subject: [PATCH] libelf: elf[32|64]_offscn shouldn't return a result for empty sections offscn sets the result before checking the section isn't empty. It assumes the result will be reset for the next section that matches the given offset. But this might not be the case, for example if this was the last section. It will then return that section (and set elf_errno) instead of returning NULL to indicate no non-empty section matched. * libelf/elf32_offscn.c (offscn): Move assignment to result after empty size check. Signed-off-by: Mark Wielaard --- libelf/elf32_offscn.c | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/libelf/elf32_offscn.c b/libelf/elf32_offscn.c index 9e757c840..1a9a3b0a9 100644 --- a/libelf/elf32_offscn.c +++ b/libelf/elf32_offscn.c @@ -73,14 +73,15 @@ elfw2(LIBELFBITS,offscn) (Elf *elf, ElfW2(LIBELFBITS,Off) offset) for (unsigned int i = 0; i < runp->cnt; ++i) if (runp->data[i].shdr.ELFW(e,LIBELFBITS)->sh_offset == offset) { - result = &runp->data[i]; - /* If this section is empty, the following one has the same sh_offset. We presume the caller is looking for a nonempty section, so keep looking if this one is empty. */ if (runp->data[i].shdr.ELFW(e,LIBELFBITS)->sh_size != 0 && runp->data[i].shdr.ELFW(e,LIBELFBITS)->sh_type != SHT_NOBITS) - goto out; + { + result = &runp->data[i]; + goto out; + } } runp = runp->next; -- 2.47.3