perf python: Handle Py_None for thread and cpu maps

The python stubs allow passing None for threads and cpus to the
perf.parse_events() and perf.parse_metrics() bindings. However, PyArg_ParseTuple
parses None into a Py_None object, which is not a NULL pointer.
Because the C code lacked an explicit check for Py_None, it would cast
Py_None to a pyrf_thread_map/pyrf_cpu_map struct pointer and dereference it,
causing a memory corruption crash.

Fix this pre-existing issue by explicitly checking for Py_None alongside NULL
in pyrf__parse_events, pyrf__parse_metrics, and pyrf_evsel__open.

Signed-off-by: Ian Rogers <irogers@google.com>
Cc: Adrian Hunter <adrian.hunter@intel.com>
Cc: Alice Rogers <alice.mei.rogers@gmail.com>
Cc: Dapeng Mi <dapeng1.mi@linux.intel.com>
Cc: Ingo Molnar <mingo@redhat.com>
Cc: James Clark <james.clark@linaro.org>
Cc: Leo Yan <leo.yan@linux.dev>
Cc: Namhyung Kim <namhyung@kernel.org>
Cc: Peter Zijlstra <peterz@infradead.org>
Cc: Thomas Richter <tmricht@linux.ibm.com>
Signed-off-by: Arnaldo Carvalho de Melo <acme@redhat.com>
Signed-off-by: Namhyung Kim <namhyung@kernel.org>
This commit is contained in:
Ian Rogers
2026-06-15 18:15:40 -07:00
committed by Namhyung Kim
parent 44a4bf577d
commit 054d1c7717

View File

@@ -2091,10 +2091,10 @@ static PyObject *pyrf_evsel__open(struct pyrf_evsel *pevsel,
&pcpus, &pthreads, &group, &inherit))
return NULL;
if (pthreads != NULL)
if (pthreads != NULL && pthreads != Py_None)
threads = ((struct pyrf_thread_map *)pthreads)->threads;
if (pcpus != NULL)
if (pcpus != NULL && pcpus != Py_None)
cpus = ((struct pyrf_cpu_map *)pcpus)->cpus;
evsel->core.attr.inherit = inherit;
@@ -3341,8 +3341,10 @@ static PyObject *pyrf__parse_events(PyObject *self, PyObject *args)
return NULL;
}
threads = pthreads ? ((struct pyrf_thread_map *)pthreads)->threads : NULL;
cpus = pcpus ? ((struct pyrf_cpu_map *)pcpus)->cpus : NULL;
threads = (pthreads && pthreads != Py_None) ?
((struct pyrf_thread_map *)pthreads)->threads : NULL;
cpus = (pcpus && pcpus != Py_None) ?
((struct pyrf_cpu_map *)pcpus)->cpus : NULL;
parse_events_error__init(&err);
perf_evlist__set_maps(evlist__core(evlist), cpus, threads);
@@ -3375,8 +3377,10 @@ static PyObject *pyrf__parse_metrics(PyObject *self, PyObject *args)
return NULL;
}
threads = pthreads ? ((struct pyrf_thread_map *)pthreads)->threads : NULL;
cpus = pcpus ? ((struct pyrf_cpu_map *)pcpus)->cpus : NULL;
threads = (pthreads && pthreads != Py_None) ?
((struct pyrf_thread_map *)pthreads)->threads : NULL;
cpus = (pcpus && pcpus != Py_None) ?
((struct pyrf_cpu_map *)pcpus)->cpus : NULL;
perf_evlist__set_maps(evlist__core(evlist), cpus, threads);
ret = metricgroup__parse_groups(evlist, pmu ?: "all", input,