mirror of https://lore.kernel.org/lkml/
 help / color / mirror / Atom feed
* [PATCH] perf kmem: Fix memory leak in __cmd_record()
@ 2019-10-28  6:46 Yunfeng Ye
  0 siblings, 0 replies; only message in thread
From: Yunfeng Ye @ 2019-10-28  6:46 UTC (permalink / raw)
  To: peterz, mingo, acme, mark.rutland, alexander.shishkin, jolsa, namhyung
  Cc: linux-kernel, hushiyuan, linfeilong

There are memory leaks in __cmd_record() found by visual inspection.
calloc() and strdup() are used to allocate memory for rec_argv pointer
array and argv, which should be freed before the function returns.

In addition, checking whether strdup() is success or not, if failure,
then go to the failure path to free memory and return the function.

Fixes: ba77c9e11111 ("perf: Add 'perf kmem' tool")
Signed-off-by: Yunfeng Ye <yeyunfeng@huawei.com>
---
 tools/perf/builtin-kmem.c | 17 ++++++++++++++---
 1 file changed, 14 insertions(+), 3 deletions(-)

diff --git a/tools/perf/builtin-kmem.c b/tools/perf/builtin-kmem.c
index 9661671cc26e..6a62acfc9470 100644
--- a/tools/perf/builtin-kmem.c
+++ b/tools/perf/builtin-kmem.c
@@ -1847,6 +1847,7 @@ static int __cmd_record(int argc, const char **argv)
 	};
 	unsigned int rec_argc, i, j;
 	const char **rec_argv;
+	int ret = -ENOMEM;

 	rec_argc = ARRAY_SIZE(record_args) + argc - 1;
 	if (kmem_slab)
@@ -1873,10 +1874,20 @@ static int __cmd_record(int argc, const char **argv)
 			rec_argv[i] = strdup(page_events[j]);
 	}

-	for (j = 1; j < (unsigned int)argc; j++, i++)
-		rec_argv[i] = argv[j];
+	for (j = 0; j < i; j++)
+		if (!rec_argv[j]) /* check strdup success or not */
+			goto out;
+
+	rec_argc = i;
+	for (j = 1; j < (unsigned int)argc; j++, rec_argc++)
+		rec_argv[rec_argc] = argv[j];

-	return cmd_record(i, rec_argv);
+	ret = cmd_record(rec_argc, rec_argv);
+out:
+	for (i--; (int)i >= 0; i--)
+		free((void *)rec_argv[i]);
+	free(rec_argv);
+	return ret;
 }

 static int kmem_config(const char *var, const char *value, void *cb __maybe_unused)
-- 
2.7.4


^ permalink raw reply	[flat|nested] only message in thread

only message in thread, other threads:[~2019-10-28  6:47 UTC | newest]

Thread overview: (only message) (download: mbox.gz / follow: Atom feed)
-- links below jump to the message on this page --
2019-10-28  6:46 [PATCH] perf kmem: Fix memory leak in __cmd_record() Yunfeng Ye

This is a public inbox, see mirroring instructions
for how to clone and mirror all data and code used for this inbox

all inboxes | Powered by JetHome®