[PATCH 1/5] perf header: Add section bounds checking to the fd read path

From: Arnaldo Carvalho de Melo

Date: Wed Apr 15 2026 - 20:15:27 EST


From: Arnaldo Carvalho de Melo <acme@xxxxxxxxxx>

__do_read_buf() validates reads against ff->size (section size), but
__do_read_fd() had no such check, so a malformed perf.data with an
understated section size could cause reads past the end of the current
section into the next section's data.

Add the bounds check in __do_read(), the common caller of both helpers,
so it is enforced uniformly for both the fd and buf paths.

This requires two supporting changes:

- perf_file_section__process(): initialize ff->offset to 0 so it
tracks bytes consumed from the section start (consistent with the
buf path), rather than the absolute file position.

- process_build_id(): use lseek(ff->fd, 0, SEEK_CUR) to discover
the current file position instead of reading ff->offset.

Cc: Ian Rogers <irogers@xxxxxxxxxx>
Assisted-by: Claude Code:claude-opus-4-6
Signed-off-by: Arnaldo Carvalho de Melo <acme@xxxxxxxxxx>
---
tools/perf/util/header.c | 17 +++++++++++------
1 file changed, 11 insertions(+), 6 deletions(-)

diff --git a/tools/perf/util/header.c b/tools/perf/util/header.c
index f30e48eb3fc32da2..13bbf8df15f66cab 100644
--- a/tools/perf/util/header.c
+++ b/tools/perf/util/header.c
@@ -213,23 +213,23 @@ static int __do_read_fd(struct feat_fd *ff, void *addr, ssize_t size)

if (ret != size)
return ret < 0 ? (int)ret : -1;
+ ff->offset += size;
return 0;
}

static int __do_read_buf(struct feat_fd *ff, void *addr, ssize_t size)
{
- if (size > (ssize_t)ff->size - ff->offset)
- return -1;
-
memcpy(addr, ff->buf + ff->offset, size);
ff->offset += size;

return 0;
-
}

static int __do_read(struct feat_fd *ff, void *addr, ssize_t size)
{
+ if (size > (ssize_t)ff->size - ff->offset)
+ return -1;
+
if (!ff->buf)
return __do_read_fd(ff, addr, size);
return __do_read_buf(ff, addr, size);
@@ -2713,7 +2713,12 @@ static int process_tracing_data(struct feat_fd *ff __maybe_unused, void *data __

static int process_build_id(struct feat_fd *ff, void *data __maybe_unused)
{
- if (perf_header__read_build_ids(ff->ph, ff->fd, ff->offset, ff->size))
+ off_t offset = lseek(ff->fd, 0, SEEK_CUR);
+
+ if (offset == (off_t)-1)
+ return -1;
+
+ if (perf_header__read_build_ids(ff->ph, ff->fd, offset, ff->size))
pr_debug("Failed to read buildids, continuing...\n");
return 0;
}
@@ -4687,7 +4692,7 @@ static int perf_file_section__process(struct perf_file_section *section,
.fd = fd,
.ph = ph,
.size = section->size,
- .offset = section->offset,
+ .offset = 0,
};

if (lseek(fd, section->offset, SEEK_SET) == (off_t)-1) {
--
2.53.0