[PATCH v11 27/33] perf synthetic-events: Bound check when synthesizing mmap2 and build_id events

From: Ian Rogers

Date: Sun Apr 12 2026 - 21:30:38 EST


Prompted by Sashiko code review, add bound checks when synthesize
mmap2 and build_id events to make sure the filename doesn't overflow
the event and lead to stack corruption.

Signed-off-by: Ian Rogers <irogers@xxxxxxxxxx>
---
tools/perf/util/synthetic-events.c | 19 ++++++++++++++++---
1 file changed, 16 insertions(+), 3 deletions(-)

diff --git a/tools/perf/util/synthetic-events.c b/tools/perf/util/synthetic-events.c
index de812a2befbc..a7fef7ac3da6 100644
--- a/tools/perf/util/synthetic-events.c
+++ b/tools/perf/util/synthetic-events.c
@@ -2257,14 +2257,20 @@ int perf_event__synthesize_build_id(const struct perf_tool *tool,
const char *filename)
{
union perf_event ev;
- size_t len;
+ size_t len, filename_len = strlen(filename);
u64 sample_type = sample->evsel ? sample->evsel->core.attr.sample_type : 0;
void *array = &ev;
int ret;

- len = sizeof(ev.build_id) + strlen(filename) + 1;
+ if (filename_len >= sizeof(ev.mmap2.filename))
+ return -EINVAL;
+
+ len = sizeof(ev.build_id) + filename_len + 1;
len = PERF_ALIGN(len, sizeof(u64));

+ if (len + MAX_ID_HDR_ENTRIES * sizeof(__u64) > sizeof(ev))
+ return -E2BIG;
+
memset(&ev, 0, len);

ev.build_id.size = bid->size;
@@ -2303,14 +2309,21 @@ int perf_event__synthesize_mmap2_build_id(const struct perf_tool *tool,
const char *filename)
{
union perf_event ev;
+ size_t filename_len = strlen(filename);
size_t ev_len;
u64 sample_type = sample->evsel ? sample->evsel->core.attr.sample_type : 0;
void *array;
int ret;

- ev_len = sizeof(ev.mmap2) - sizeof(ev.mmap2.filename) + strlen(filename) + 1;
+ if (filename_len >= sizeof(ev.mmap2.filename))
+ return -EINVAL;
+
+ ev_len = sizeof(ev.mmap2) - sizeof(ev.mmap2.filename) + filename_len + 1;
ev_len = PERF_ALIGN(ev_len, sizeof(u64));

+ if (ev_len + MAX_ID_HDR_ENTRIES * sizeof(__u64) > sizeof(ev))
+ return -E2BIG;
+
memset(&ev, 0, ev_len);

ev.mmap2.header.type = PERF_RECORD_MMAP2;
--
2.53.0.1213.gd9a14994de-goog