Re: [PATCH] fix: possible memory leak in unxz()

From: Lasse Collin
Date: Tue Oct 08 2024 - 10:54:15 EST


In short, I dont want this patch to be merged, especially with its
current misleading commit message.

On 2024-10-07 Andrew Morton wrote:
> must_free_in needn't exist - `in' is always non-NULL here.

No, must_free_in is needed. The API (defined in
include/linux/decompress/generic.h) packs three different functions
into a single function:

1. Buffer to buffer (from "in"/"inbuf" to "out"/"outbuf")
2. Buffer ("in"/"inbuf") to callback function (flush)
3. Callback function (fill) to callback function (flush)

The callback functions need input and output buffers. For "flush", the
buffer always has to be allocated.

But, for some reason, generic.h says that "fill" can use the input
buffer provided by the caller when it's non-NULL. Thus, unxz()
allocates "in" conditionally and must_free_in is needed to avoid
freeing "in" when unxz() didn't allocate it.

I don't know if anything actually uses this subvariant where fill !=
NULL && in != NULL. Several other lib/decompress_*.c files support it
too although unlzo and unlz4 don't. So perhaps the feature is an
unneeded complication. Getting rid of this feature could make the code
less confusing. It would also allow making the "in" pointer
const-correct for buffer-to-{buffer,callback} cases.

> And free(NULL) is OK anwyay.

No, it's not. The free() implementation in
include/linux/decompress/mm.h doesn't check for NULL; each free() just
decrements the allocation counter. Thus free(NULL) would desync it.

As I wrote two days ago[1], this patch doesn't fix a memory leak or any
other bugs, and thus the commit message is incorrect. Still, I wasn't
really against the patch two days ago but I am now. I see the code
being misunderstood, and I feel this patch doesn't make it more
understandable.

[1] https://lore.kernel.org/lkml/20241006211720.5d7199b0@kaneli/

--
Lasse Collin