perf/core: Fix a memory leak in perf_event_parse_addr_filter()

As shown through runtime testing, the "filename" allocation is not
always freed in perf_event_parse_addr_filter().

There are three possible ways that this could happen:

 - It could be allocated twice on subsequent iterations through the loop,
 - or leaked on the success path,
 - or on the failure path.

Clean up the code flow to make it obvious that 'filename' is always
freed in the reallocation path and in the two return paths as well.

We rely on the fact that kfree(NULL) is NOP and filename is initialized
with NULL.

This fixes the leak. No other side effects expected.

[ Dan Carpenter: cleaned up the code flow & added a changelog. ]
[ Ingo Molnar: updated the changelog some more. ]

Fixes: 375637bc52 ("perf/core: Introduce address range filtering")
Signed-off-by: "kiyin(尹亮)" <kiyin@tencent.com>
Signed-off-by: Dan Carpenter <dan.carpenter@oracle.com>
Signed-off-by: Ingo Molnar <mingo@kernel.org>
Cc: "Srivatsa S. Bhat" <srivatsa@csail.mit.edu>
Cc: Anthony Liguori <aliguori@amazon.com>
--
 kernel/events/core.c | 12 +++++-------
 1 file changed, 5 insertions(+), 7 deletions(-)
This commit is contained in:
kiyin(尹亮) 2020-11-04 08:23:22 +03:00 committed by Ingo Molnar
parent 659caaf65d
commit 7bdb157cde

View File

@ -10085,6 +10085,7 @@ perf_event_parse_addr_filter(struct perf_event *event, char *fstr,
if (token == IF_SRC_FILE || token == IF_SRC_FILEADDR) { if (token == IF_SRC_FILE || token == IF_SRC_FILEADDR) {
int fpos = token == IF_SRC_FILE ? 2 : 1; int fpos = token == IF_SRC_FILE ? 2 : 1;
kfree(filename);
filename = match_strdup(&args[fpos]); filename = match_strdup(&args[fpos]);
if (!filename) { if (!filename) {
ret = -ENOMEM; ret = -ENOMEM;
@ -10131,16 +10132,13 @@ perf_event_parse_addr_filter(struct perf_event *event, char *fstr,
*/ */
ret = -EOPNOTSUPP; ret = -EOPNOTSUPP;
if (!event->ctx->task) if (!event->ctx->task)
goto fail_free_name; goto fail;
/* look up the path and grab its inode */ /* look up the path and grab its inode */
ret = kern_path(filename, LOOKUP_FOLLOW, ret = kern_path(filename, LOOKUP_FOLLOW,
&filter->path); &filter->path);
if (ret) if (ret)
goto fail_free_name; goto fail;
kfree(filename);
filename = NULL;
ret = -EINVAL; ret = -EINVAL;
if (!filter->path.dentry || if (!filter->path.dentry ||
@ -10160,13 +10158,13 @@ perf_event_parse_addr_filter(struct perf_event *event, char *fstr,
if (state != IF_STATE_ACTION) if (state != IF_STATE_ACTION)
goto fail; goto fail;
kfree(filename);
kfree(orig); kfree(orig);
return 0; return 0;
fail_free_name:
kfree(filename);
fail: fail:
kfree(filename);
free_filters_list(filters); free_filters_list(filters);
kfree(orig); kfree(orig);