[PATCH v5 21/21] perf python: Correctly throw IndexError

Ian Rogers posted 21 patches 3 weeks, 4 days ago
There is a newer version of this series
[PATCH v5 21/21] perf python: Correctly throw IndexError
Posted by Ian Rogers 3 weeks, 4 days ago
Correctly throw IndexError for out-of-bound accesses to evlist:
```
Python 3.11.9 (main, Jun 19 2024, 00:38:48) [GCC 13.2.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import sys
>>> sys.path.insert(0, '/tmp/perf/python')
>>> import perf
>>> x=perf.parse_events('cycles')
>>> print(x)
evlist([cycles])
>>> x[2]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
IndexError: Index out of range
```

Signed-off-by: Ian Rogers <irogers@google.com>
---
 tools/perf/util/python.c | 4 +++-
 1 file changed, 3 insertions(+), 1 deletion(-)

diff --git a/tools/perf/util/python.c b/tools/perf/util/python.c
index 0d71ec673aa3..25114dcadd21 100644
--- a/tools/perf/util/python.c
+++ b/tools/perf/util/python.c
@@ -1071,8 +1071,10 @@ static PyObject *pyrf_evlist__item(PyObject *obj, Py_ssize_t i)
 	struct pyrf_evlist *pevlist = (void *)obj;
 	struct evsel *pos;
 
-	if (i >= pevlist->evlist.core.nr_entries)
+	if (i >= pevlist->evlist.core.nr_entries) {
+		PyErr_SetString(PyExc_IndexError, "Index out of range");
 		return NULL;
+	}
 
 	evlist__for_each_entry(&pevlist->evlist, pos) {
 		if (i-- == 0)
-- 
2.47.0.163.g1226f6d8fa-goog
Re: [PATCH v5 21/21] perf python: Correctly throw IndexError
Posted by Arnaldo Carvalho de Melo 3 weeks, 3 days ago
On Wed, Oct 30, 2024 at 06:42:52PM -0700, Ian Rogers wrote:
> Correctly throw IndexError for out-of-bound accesses to evlist:
> ```
> Python 3.11.9 (main, Jun 19 2024, 00:38:48) [GCC 13.2.0] on linux
> Type "help", "copyright", "credits" or "license" for more information.
> >>> import sys
> >>> sys.path.insert(0, '/tmp/perf/python')
> >>> import perf
> >>> x=perf.parse_events('cycles')
> >>> print(x)
> evlist([cycles])
> >>> x[2]
> Traceback (most recent call last):
>   File "<stdin>", line 1, in <module>
> IndexError: Index out of range
> ```

Tested-by: Arnaldo Carvalho de Melo <acme@redhat.com>
 
> Signed-off-by: Ian Rogers <irogers@google.com>
> ---
>  tools/perf/util/python.c | 4 +++-
>  1 file changed, 3 insertions(+), 1 deletion(-)
> 
> diff --git a/tools/perf/util/python.c b/tools/perf/util/python.c
> index 0d71ec673aa3..25114dcadd21 100644
> --- a/tools/perf/util/python.c
> +++ b/tools/perf/util/python.c
> @@ -1071,8 +1071,10 @@ static PyObject *pyrf_evlist__item(PyObject *obj, Py_ssize_t i)
>  	struct pyrf_evlist *pevlist = (void *)obj;
>  	struct evsel *pos;
>  
> -	if (i >= pevlist->evlist.core.nr_entries)
> +	if (i >= pevlist->evlist.core.nr_entries) {
> +		PyErr_SetString(PyExc_IndexError, "Index out of range");
>  		return NULL;
> +	}
>  
>  	evlist__for_each_entry(&pevlist->evlist, pos) {
>  		if (i-- == 0)
> -- 
> 2.47.0.163.g1226f6d8fa-goog