[PATCH] tools/sched_ext: scx_simple/scx_cpu0: fix potential stack overflow from VLA in read_stats

From: David Carlier

Date: Sun Mar 01 2026 - 00:48:16 EST


read_stats() in both scx_simple and scx_cpu0 had a VLA allocating
2 * nr_cpus * 8 bytes on the stack, risking stack overflow on large
CPU counts.

Apply the same fix as commit cabd76bbc036 ("tools/sched_ext:
scx_flatcg: fix potential stack overflow from VLA in fcg_read_stats"):
use a single heap allocation, reuse it across all stat indices, and
free it at the end.

Signed-off-by: David Carlier <devnexen@xxxxxxxxx>
---
tools/sched_ext/scx_cpu0.c | 12 +++++++++---
tools/sched_ext/scx_simple.c | 12 +++++++++---
2 files changed, 18 insertions(+), 6 deletions(-)

diff --git a/tools/sched_ext/scx_cpu0.c b/tools/sched_ext/scx_cpu0.c
index a6fba9978b9c..0b412d2eb3f0 100644
--- a/tools/sched_ext/scx_cpu0.c
+++ b/tools/sched_ext/scx_cpu0.c
@@ -41,21 +41,27 @@ static void read_stats(struct scx_cpu0 *skel, __u64 *stats)
{
int nr_cpus = libbpf_num_possible_cpus();
assert(nr_cpus > 0);
- __u64 cnts[2][nr_cpus];
+ __u64 *cnts;
__u32 idx;

+ cnts = calloc(nr_cpus, sizeof(__u64));
+ if (!cnts)
+ return;
+
memset(stats, 0, sizeof(stats[0]) * 2);

for (idx = 0; idx < 2; idx++) {
int ret, cpu;

ret = bpf_map_lookup_elem(bpf_map__fd(skel->maps.stats),
- &idx, cnts[idx]);
+ &idx, cnts);
if (ret < 0)
continue;
for (cpu = 0; cpu < nr_cpus; cpu++)
- stats[idx] += cnts[idx][cpu];
+ stats[idx] += cnts[cpu];
}
+
+ free(cnts);
}

int main(int argc, char **argv)
diff --git a/tools/sched_ext/scx_simple.c b/tools/sched_ext/scx_simple.c
index c3b48611712b..b6ef4cca425a 100644
--- a/tools/sched_ext/scx_simple.c
+++ b/tools/sched_ext/scx_simple.c
@@ -43,21 +43,27 @@ static void read_stats(struct scx_simple *skel, __u64 *stats)
{
int nr_cpus = libbpf_num_possible_cpus();
assert(nr_cpus > 0);
- __u64 cnts[2][nr_cpus];
+ __u64 *cnts;
__u32 idx;

+ cnts = calloc(nr_cpus, sizeof(__u64));
+ if (!cnts)
+ return;
+
memset(stats, 0, sizeof(stats[0]) * 2);

for (idx = 0; idx < 2; idx++) {
int ret, cpu;

ret = bpf_map_lookup_elem(bpf_map__fd(skel->maps.stats),
- &idx, cnts[idx]);
+ &idx, cnts);
if (ret < 0)
continue;
for (cpu = 0; cpu < nr_cpus; cpu++)
- stats[idx] += cnts[idx][cpu];
+ stats[idx] += cnts[cpu];
}
+
+ free(cnts);
}

int main(int argc, char **argv)
--
2.51.0