[PATCH v12 29/33] perf sched: Bounds check CPU in sched switch events

From: Ian Rogers

Date: Mon Apr 13 2026 - 00:27:49 EST


Prompted by Sashiko in code reviews. Ensure the CPU is within expected
bounds to avoid out of bound memory accesses.

Signed-off-by: Ian Rogers <irogers@xxxxxxxxxx>
---
tools/perf/builtin-sched.c | 15 +++++++++++++++
1 file changed, 15 insertions(+)

diff --git a/tools/perf/builtin-sched.c b/tools/perf/builtin-sched.c
index 45439e2af8ff..8b0526d342e3 100644
--- a/tools/perf/builtin-sched.c
+++ b/tools/perf/builtin-sched.c
@@ -1791,6 +1791,11 @@ static int process_sched_switch_event(const struct perf_tool *tool,
u32 prev_pid = perf_sample__intval(sample, "prev_pid"),
next_pid = perf_sample__intval(sample, "next_pid");

+ if (this_cpu < 0 || this_cpu >= MAX_CPUS) {
+ pr_warning("Out-of-bound sample CPU %d. Skipping sample\n", this_cpu);
+ return 0;
+ }
+
if (sched->curr_pid[this_cpu] != (u32)-1) {
/*
* Are we trying to switch away a PID that is
@@ -1813,6 +1818,11 @@ static int process_sched_runtime_event(const struct perf_tool *tool,
{
struct perf_sched *sched = container_of(tool, struct perf_sched, tool);

+ if (sample->cpu >= MAX_CPUS) {
+ pr_warning("Out-of-bound sample CPU %d. Skipping sample\n", sample->cpu);
+ return 0;
+ }
+
if (sched->tp_handler->runtime_event)
return sched->tp_handler->runtime_event(sched, sample, machine);

@@ -2775,6 +2785,11 @@ static int timehist_sched_change_event(const struct perf_tool *tool,
int rc = 0;
const char state = perf_sample__taskstate(sample, "prev_state");

+ if (sample->cpu >= MAX_CPUS) {
+ pr_warning("Out-of-bound sample CPU %d. Skipping sample\n", sample->cpu);
+ return 0;
+ }
+
addr_location__init(&al);
if (machine__resolve(machine, &al, sample) < 0) {
pr_err("problem processing %d event. skipping it\n",
--
2.53.0.1213.gd9a14994de-goog