perf python: Add type checking for parse_events/parse_metrics

The threads and cpus parameters in parse_events and parse_metrics
are parsed with the 'O' format specifier but blindly casted in the
C extension. If a user passes an invalid object type, this leads to
memory corruption when dereferencing the expected struct.

Add runtime PyObject_TypeCheck validations in python.c to safely
raise a TypeError if an invalid object is passed.

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:41 -07:00
committed by Namhyung Kim
parent 054d1c7717
commit c52b600dbe

View File

@@ -3341,6 +3341,20 @@ static PyObject *pyrf__parse_events(PyObject *self, PyObject *args)
return NULL;
}
if (pthreads && pthreads != Py_None &&
!PyObject_TypeCheck(pthreads, &pyrf_thread_map__type)) {
PyErr_SetString(PyExc_TypeError, "threads must be a perf.thread_map or None");
evlist__put(evlist);
return NULL;
}
if (pcpus && pcpus != Py_None &&
!PyObject_TypeCheck(pcpus, &pyrf_cpu_map__type)) {
PyErr_SetString(PyExc_TypeError, "cpus must be a perf.cpu_map or None");
evlist__put(evlist);
return NULL;
}
threads = (pthreads && pthreads != Py_None) ?
((struct pyrf_thread_map *)pthreads)->threads : NULL;
cpus = (pcpus && pcpus != Py_None) ?
@@ -3377,6 +3391,20 @@ static PyObject *pyrf__parse_metrics(PyObject *self, PyObject *args)
return NULL;
}
if (pthreads && pthreads != Py_None &&
!PyObject_TypeCheck(pthreads, &pyrf_thread_map__type)) {
PyErr_SetString(PyExc_TypeError, "threads must be a perf.thread_map or None");
evlist__put(evlist);
return NULL;
}
if (pcpus && pcpus != Py_None &&
!PyObject_TypeCheck(pcpus, &pyrf_cpu_map__type)) {
PyErr_SetString(PyExc_TypeError, "cpus must be a perf.cpu_map or None");
evlist__put(evlist);
return NULL;
}
threads = (pthreads && pthreads != Py_None) ?
((struct pyrf_thread_map *)pthreads)->threads : NULL;
cpus = (pcpus && pcpus != Py_None) ?