From 8f2593fbbad2a549b854645acde7b11f5e02a924 Mon Sep 17 00:00:00 2001
From: Jerome Marchand <jmarchan@redhat.com>
Date: Thu, 6 Jun 2024 17:38:23 +0200
Subject: [PATCH 09/15] libtracefs: Prevent a memory leak in open_cpu_files()
In open_cpu_files(), if realloc() fails, the latest allocated tcpu
isn't freed. Rearrange the loop to prevent that.
Link: https://lore.kernel.org/linux-trace-devel/20240606153830.2666120-10-jmarchan@redhat.com
Fixes: 564bffddcb117 ("libtracefs: Use tracefs_cpu_read() for tracefs_iterate_raw_events()")
Signed-off-by: Jerome Marchand <jmarchan@redhat.com>
Signed-off-by: Steven Rostedt (Google) <rostedt@goodmis.org>
---
src/tracefs-events.c | 10 +++++-----
1 file changed, 5 insertions(+), 5 deletions(-)
diff --git a/src/tracefs-events.c b/src/tracefs-events.c
index d65837e..88325e1 100644
--- a/src/tracefs-events.c
+++ b/src/tracefs-events.c
@@ -275,9 +275,12 @@ static int open_cpu_files(struct tracefs_instance *instance, cpu_set_t *cpus,
tcpu = tracefs_cpu_snapshot_open(instance, cpu, true);
else
tcpu = tracefs_cpu_open_mapped(instance, cpu, true);
+ if (!tcpu)
+ goto error;
+
tmp = realloc(*all_cpus, (i + 1) * sizeof(*tmp));
if (!tmp) {
- i--;
+ tracefs_cpu_close(tcpu);
goto error;
}
@@ -285,9 +288,6 @@ static int open_cpu_files(struct tracefs_instance *instance, cpu_set_t *cpus,
memset(tmp + i, 0, sizeof(*tmp));
- if (!tcpu)
- goto error;
-
tmp[i].tcpu = tcpu;
tmp[i].cpu = cpu;
i++;
@@ -296,7 +296,7 @@ static int open_cpu_files(struct tracefs_instance *instance, cpu_set_t *cpus,
return 0;
error:
tmp = *all_cpus;
- for (; i >= 0; i--) {
+ for (i--; i >= 0; i--) {
tracefs_cpu_close(tmp[i].tcpu);
}
free(tmp);
--
2.45.2