Re: [PATCH] params: fix potential memory leak in add_sysfs_param()

Woodhouse, David
2014-08-20T21:36:37Z

[-- Attachment #1: Type: text/plain, Size: 1871 bytes --]

On Thu, 2014-08-21 at 06:19 +0930, Rusty Russell wrote:
> Arjun Sreedharan <arjun024@gmail.com> writes:
> > Do not leak memory when attrs is non NULL and
> > krealloc() fails. Without temporary variable,
> > reference to it is lost.
> >
> > Signed-off-by: Arjun Sreedharan <arjun024@gmail.com>
>
> ...
>
> > }
> > - /* Despite looking like the typical realloc() bug, this is safe.
> > - * We *want* the old 'attrs' to be freed either way, and we'll store
> > - * the new one in the success case. */
> > - attrs = krealloc(attrs, sizeof(new->grp.attrs[0])*(num+2), GFP_KERNEL);
> > - if (!attrs) {
> > +
> > + new_attrs = krealloc(attrs, sizeof(new->grp.attrs[0])*(num+2), GFP_KERNEL);
> > + if (!new_attrs) {
>
> I think that comment you deleted is pretty clear. Is it wrong?

Yes, I think it's wrong.

I think I was under the impression that we shouldn't be freeing the old
'attrs' pointer on failure because it would live on in
{new,mk->mp}->grp.attrs and still be used. (Which I concede isn't
actually what the comment says, making it doubly wrong.)

I may have failed to notice that when this krealloc() fails, we actually
*free* the 'new' pointer and set mk->mp to NULL. Without freeing the
new->grp.attrs pointer. So it is indeed leaked. We *don't* need a
temporary variable for it though; we can find it.

In fact, I wonder if it's better to change the 'goto fail_free_new' in
the failure path here to instead do something like 'mk->mp = new; return
-ENOMEM;'. That way, the existing params would still be present and we'd
just have failed to add the *new* one. (And the leak wouldn't exist
because the 'attrs' pointer would live on as I originally thought.)

--
David Woodhouse Open Source Technology Centre
David.Woodhouse@intel.com Intel Corporation

[-- Attachment #2: smime.p7s --]
[-- Type: application/x-pkcs7-signature, Size: 3437 bytes --]