cmELF: Avoid out-of-bounds access on zero-section ELF binary

Fix commit 615a1c6691 (cmELF: Get correct section count for large ELF
binaries, 2024-02-21, v3.30.0-rc1~354^2) to avoid out-of-bounds access
if both `e_shnum` and the first `sh_size` are zero.

Issue: #24877
This commit is contained in:
Brad King
2026-01-29 10:21:29 -05:00
parent 5954145e0d
commit e47f7c8af4

View File

@@ -2,6 +2,7 @@
file LICENSE.rst or https://cmake.org/licensing for details. */
#include "cmELF.h"
#include <algorithm>
#include <cstddef>
#include <cstdint>
#include <map>
@@ -449,13 +450,15 @@ cmELFInternalImpl<Types>::cmELFInternalImpl(cmELF* external,
this->Machine = this->ELFHeader.e_machine;
// Load the section headers.
this->SectionHeaders.resize(
this->ELFHeader.e_shnum == 0 ? 1 : this->ELFHeader.e_shnum);
std::size_t const minSections = 1;
std::size_t numSections = this->ELFHeader.e_shnum;
this->SectionHeaders.resize(std::max(numSections, minSections));
if (!this->LoadSectionHeader(0)) {
return;
}
this->SectionHeaders.resize(this->GetNumberOfSections());
for (std::size_t i = 1; i < this->GetNumberOfSections(); ++i) {
numSections = this->GetNumberOfSections();
this->SectionHeaders.resize(std::max(numSections, minSections));
for (std::size_t i = 1; i < numSections; ++i) {
if (!this->LoadSectionHeader(i)) {
return;
}