[PATCH v3] perf parse-events: Prevent null pointer dereference in __add_event()

zhaoguohan@kylinos.cn posted 1 patch 3 weeks, 3 days ago
tools/perf/util/parse-events.c | 14 ++++++++------
1 file changed, 8 insertions(+), 6 deletions(-)
[PATCH v3] perf parse-events: Prevent null pointer dereference in __add_event()
Posted by zhaoguohan@kylinos.cn 3 weeks, 3 days ago
From: GuoHan Zhao <zhaoguohan@kylinos.cn>

In the error handling path of __add_event(), if evsel__new_idx() fails
and returns NULL, the subsequent calls to zfree(&evsel->name) and
zfree(&evsel->metric_id) will cause null pointer dereference.

Extend the goto chain to properly handle the case where evsel allocation
fails, avoiding unnecessary cleanup operations on a NULL pointer.

Fixes: cd63c2216825 ("perf parse-events: Minor __add_event refactoring")
Reviewed-by: Markus Elfring <Markus.Elfring@web.de>
Reviewed-by: Ian Rogers <irogers@google.com>
Signed-off-by: GuoHan Zhao <zhaoguohan@kylinos.cn>

---
V2 -> V3:
- Replaced `out_free_cpus` with `out_put_cpus`
- moved the patch version descriptions behind the marker line
V1 -> V2:
- Extended the goto chain with separate error handling labels instead of using null pointer check
- Reordered jump targets to avoid accessing NULL evsel members
- Added Fixes tag
- Updated commit subject to use "Prevent" instead of "Fix"
---
 tools/perf/util/parse-events.c | 14 ++++++++------
 1 file changed, 8 insertions(+), 6 deletions(-)

diff --git a/tools/perf/util/parse-events.c b/tools/perf/util/parse-events.c
index 8282ddf68b98..2ffdd0d13c45 100644
--- a/tools/perf/util/parse-events.c
+++ b/tools/perf/util/parse-events.c
@@ -277,18 +277,18 @@ __add_event(struct list_head *list, int *idx,
 
 	evsel = evsel__new_idx(attr, *idx);
 	if (!evsel)
-		goto out_err;
+		goto out_put_cpus;
 
 	if (name) {
 		evsel->name = strdup(name);
 		if (!evsel->name)
-			goto out_err;
+			goto out_free_evsel;
 	}
 
 	if (metric_id) {
 		evsel->metric_id = strdup(metric_id);
 		if (!evsel->metric_id)
-			goto out_err;
+			goto out_free_evsel;
 	}
 
 	(*idx)++;
@@ -310,12 +310,14 @@ __add_event(struct list_head *list, int *idx,
 		evsel__warn_user_requested_cpus(evsel, user_cpus);
 
 	return evsel;
-out_err:
-	perf_cpu_map__put(cpus);
-	perf_cpu_map__put(pmu_cpus);
+out_free_evsel:
 	zfree(&evsel->name);
 	zfree(&evsel->metric_id);
 	free(evsel);
+out_put_cpus:
+	perf_cpu_map__put(cpus);
+	perf_cpu_map__put(pmu_cpus);
+
 	return NULL;
 }
 
-- 
2.43.0