[PATCH] proc/vmcore: fix potential memory leak in vmcore_init()

Jianglei Nie posted 1 patch 3 years, 6 months ago
fs/proc/vmcore.c | 8 +++++---
1 file changed, 5 insertions(+), 3 deletions(-)
[PATCH] proc/vmcore: fix potential memory leak in vmcore_init()
Posted by Jianglei Nie 3 years, 6 months ago
elfcorehdr_alloc() allocates a memory chunk for elfcorehdr_addr with
kzalloc(). If is_vmcore_usable() returns false, elfcorehdr_addr is a
predefined value. If parse_crash_elf_headers() gets some error and
returns a negetive value, the elfcorehdr_addr should be released with
elfcorehdr_free().

Fix it by calling elfcorehdr_free() when parse_crash_elf_headers() fails.

Acked-by: Baoquan He <bhe@redhat.com>
Signed-off-by: Jianglei Nie <niejianglei2021@163.com>
---
 fs/proc/vmcore.c | 8 +++++---
 1 file changed, 5 insertions(+), 3 deletions(-)

diff --git a/fs/proc/vmcore.c b/fs/proc/vmcore.c
index f2aa86c421f2..163cb266f5fd 100644
--- a/fs/proc/vmcore.c
+++ b/fs/proc/vmcore.c
@@ -1568,15 +1568,17 @@ static int __init vmcore_init(void)
 	rc = parse_crash_elf_headers();
 	if (rc) {
 		pr_warn("Kdump: vmcore not initialized\n");
-		return rc;
+		goto fail;
 	}
-	elfcorehdr_free(elfcorehdr_addr);
 	elfcorehdr_addr = ELFCORE_ADDR_ERR;
 
 	proc_vmcore = proc_create("vmcore", S_IRUSR, NULL, &vmcore_proc_ops);
 	if (proc_vmcore)
 		proc_vmcore->size = vmcore_size;
-	return 0;
+
+fail:
+	elfcorehdr_free(elfcorehdr_addr);
+	return rc;
 }
 fs_initcall(vmcore_init);
 
-- 
2.25.1
Re: [PATCH] proc/vmcore: fix potential memory leak in vmcore_init()
Posted by Matthew Wilcox 3 years, 6 months ago
On Tue, Sep 13, 2022 at 02:25:01PM +0800, Jianglei Nie wrote:
>  	}
> -	elfcorehdr_free(elfcorehdr_addr);
>  	elfcorehdr_addr = ELFCORE_ADDR_ERR;
>  
>  	proc_vmcore = proc_create("vmcore", S_IRUSR, NULL, &vmcore_proc_ops);
>  	if (proc_vmcore)
>  		proc_vmcore->size = vmcore_size;
> -	return 0;
> +
> +fail:
> +	elfcorehdr_free(elfcorehdr_addr);
> +	return rc;
>  }

Did you test this?  It looks like you now call
elfcorehdr_free(ELFCORE_ADDR_ERR) if 'rc' is 0.
Re: [PATCH] proc/vmcore: fix potential memory leak in vmcore_init()
Posted by Baoquan He 3 years, 6 months ago
On 09/13/22 at 07:35am, Matthew Wilcox wrote:
> On Tue, Sep 13, 2022 at 02:25:01PM +0800, Jianglei Nie wrote:
> >  	}
> > -	elfcorehdr_free(elfcorehdr_addr);
> >  	elfcorehdr_addr = ELFCORE_ADDR_ERR;
> >  
> >  	proc_vmcore = proc_create("vmcore", S_IRUSR, NULL, &vmcore_proc_ops);
> >  	if (proc_vmcore)
> >  		proc_vmcore->size = vmcore_size;
> > -	return 0;
> > +
> > +fail:
> > +	elfcorehdr_free(elfcorehdr_addr);
> > +	return rc;
> >  }
> 
> Did you test this?  It looks like you now call
> elfcorehdr_free(ELFCORE_ADDR_ERR) if 'rc' is 0.

Right, that will cause problem. It's my fault since I suggested
the current change.

Jianglei, please use your v1 change and post again. Sorry for the
incorrect suggestion.