[llvm] [Object][ELF] Fix section header zero check (PR #181796)
via llvm-commits
llvm-commits at lists.llvm.org
Tue Feb 17 02:16:39 PST 2026
https://github.com/aokblast created https://github.com/llvm/llvm-project/pull/181796
The PN_XUM is a necessary condition for reading shdr0
regardless of the value of e_shoff. Without this,
readShdrZero falsely returns the garbage value in ELF
header instead of emitting warning.
>From 1b2e9ee80ff5991ee1f1cc13f879fb7440bd1a15 Mon Sep 17 00:00:00 2001
From: ShengYi Hung <aokblast at FreeBSD.org>
Date: Tue, 17 Feb 2026 18:11:52 +0800
Subject: [PATCH] [Object][ELF] Fix section header zero check
The PN_XUM is a necessary condition for reading shdr0
regardless of the value of e_shoff. Without this,
readShdrZero falsely returns the garbage value in ELF
header instead of emitting warning.
---
llvm/include/llvm/Object/ELF.h | 12 +++++++++---
1 file changed, 9 insertions(+), 3 deletions(-)
diff --git a/llvm/include/llvm/Object/ELF.h b/llvm/include/llvm/Object/ELF.h
index df16e50dc1c4f..5343c0a360824 100644
--- a/llvm/include/llvm/Object/ELF.h
+++ b/llvm/include/llvm/Object/ELF.h
@@ -935,9 +935,15 @@ template <class ELFT> ELFFile<ELFT>::ELFFile(StringRef Object) : Buf(Object) {}
template <class ELFT> Error ELFFile<ELFT>::readShdrZero() {
const Elf_Ehdr &Header = getHeader();
- if ((Header.e_phnum == ELF::PN_XNUM || Header.e_shnum == 0 ||
- Header.e_shstrndx == ELF::SHN_XINDEX) &&
- Header.e_shoff != 0) {
+ // If e_shnum == 0 && e_shoff == 0, this indicates that there are no sections,
+ // which is valid for an ELF file.
+ //
+ // However, if e_phnum == PN_XNUM or e_shstrndx == SHN_XINDEX while
+ // e_shoff == 0, the file is inconsistent. In that case, an error will be
+ // triggered later when getSection() is called and detects that e_shoff == 0.
+ if ((Header.e_phnum == ELF::PN_XNUM ||
+ (Header.e_shnum == 0 && Header.e_shoff != 0) ||
+ Header.e_shstrndx == ELF::SHN_XINDEX)) {
// Pretend we have section 0 or sections() would call getShNum and thus
// become an infinite recursion.
RealShNum = 1;
More information about the llvm-commits
mailing list