[PATCH 06/11] perf sched: Bounds-check prio before test_bit() in timehist
From: Arnaldo Carvalho de Melo
Date: Sun Jun 07 2026 - 19:30:48 EST
From: Arnaldo Carvalho de Melo <acme@xxxxxxxxxx>
timehist_skip_sample() reads prio from untrusted tracepoint data via
perf_sample__intval(sample, "prev_prio") without bounds validation.
A crafted perf.data with prev_prio >= MAX_PRIO (140) causes test_bit()
to read past the end of the prio_bitmap, which is only MAX_PRIO bits.
Add a prio >= 0 && prio < MAX_PRIO check before the test_bit() call.
This also makes the != -1 sentinel check explicit as >= 0.
Fixes: 9b3a48bbe20d9692 ("perf sched timehist: Add --prio option")
Reported-by: sashiko-bot <sashiko-bot@xxxxxxxxxx>
Cc: Yang Jihong <yangjihong@xxxxxxxxxxxxx>
Assisted-by: Claude Opus 4.6 <noreply@xxxxxxxxxxxxx>
Signed-off-by: Arnaldo Carvalho de Melo <acme@xxxxxxxxxx>
---
tools/lib/perf/TODO | 7 +++++++
tools/perf/builtin-sched.c | 4 +++-
2 files changed, 10 insertions(+), 1 deletion(-)
diff --git a/tools/lib/perf/TODO b/tools/lib/perf/TODO
index 486dd95dc57208a8..1a3644aa1f38dde4 100644
--- a/tools/lib/perf/TODO
+++ b/tools/lib/perf/TODO
@@ -11,6 +11,13 @@ together.
(x86_64 max is 8192, arm64 is 4096), but NR_CPUS limits keep
growing. perf clamps to INT16_MAX in set_max_cpu_num() as a
safety net.
+ - Code simplification: the int16_t forces defensive truncation
+ checks at every boundary where a wider CPU index (int from
+ sample->cpu, al->cpu, etc.) is narrowed into struct perf_cpu.
+ Without these checks, values > 32767 silently wrap to small
+ positive numbers, bypassing bounds validation. Widening to int
+ eliminates this entire class of silent truncation bugs and
+ removes the need for the INT16_MAX clamp in set_max_cpu_num().
- Scope: struct perf_cpu is embedded everywhere — perf_cpu_map__cpu(),
perf_cpu_map__min(), perf_cpu_map__max(), perf_cpu_map__has(), the
for_each_cpu macros, and all internal callers. The perf_cpu_map
diff --git a/tools/perf/builtin-sched.c b/tools/perf/builtin-sched.c
index 1ff01f03d2ad1ad3..5f3510f9ca249132 100644
--- a/tools/perf/builtin-sched.c
+++ b/tools/perf/builtin-sched.c
@@ -2645,7 +2645,9 @@ static bool timehist_skip_sample(struct perf_sched *sched,
else if (evsel__name_is(sample->evsel, "sched:sched_switch"))
prio = perf_sample__intval(sample, "prev_prio");
- if (prio != -1 && !test_bit(prio, sched->prio_bitmap)) {
+ /* prio comes from untrusted tracepoint data — skip invalid values */
+ if (prio < 0 || prio >= MAX_PRIO ||
+ !test_bit(prio, sched->prio_bitmap)) {
rc = true;
sched->skipped_samples++;
}
--
2.54.0