Re: [PATCH] libtrace: Fix memory leak in tracefs_cpu

Steven Rostedt <[email protected]> Thu, 3 Apr 2025 15:14:04 -0400
Newsgroups org.kernel.vger.linux-trace-devel
Message-ID <[email protected]>
On Mon, 17 Mar 2025 11:24:36 +0000
"Kutzer, Philipp" <[email protected]> wrote:

> From: Philipp Kutzer <[email protected]>
> 
> Hi,
> 
> with the introduction of the interface to allow the tracefs_cpu to handle buffer allocation on their
>  own a memory leak was built in. 
> (Commit 1e1cc549d7e7fa408081e03e4effd3591a131ae5 - libtracefs: Add API to read tracefs_cpu 
> and return a kbuffer)
> 
> We cyclically call the tracefs_iterate_raw_events function from one of our applications and 
> noticed that our application was increasingly allocating memory. 
> 
> With the help of Address Sanitizer the root cause, allocating but not freeing memory 
> for "tcpu->buffer" was found. The fix will free memory during close and cleanup function 
> and has been successfully tested in our environment. The original problem (memory leak) 
> has been resolved.

Note, I cleaned up the change log:

    libtrace: Fix memory leak in tracefs_cpu
    
    The introduction of the interface to allow the tracefs_cpu to handle buffer
    allocation on their own caused a memory leak.  (Commit 1e1cc549d7
    ("libtracefs: Add API to read tracefs_cpu and return a kbuffer")).
    
    The help of Address Sanitizer found the root cause. The "tcpu->buffer" was
    being allocated but not freed. The fix will free memory during close and
    cleanup functions.


> 
> Signed-off-by: Philipp Kutzer mailto:[email protected]

Also, this should be:

 Signed-off-by: Philipp Kutzer <[email protected]>

> ---
> 
> diff --git a/src/tracefs-record.c b/src/tracefs-record.c
> index a2dcfc2..4cd0917 100644
> --- a/src/tracefs-record.c
> +++ b/src/tracefs-record.c
> @@ -293,6 +293,8 @@ void tracefs_cpu_close(struct tracefs_cpu *tcpu)
>         if (!tcpu)
>                 return;
> 
> +       free(tcpu->buffer);
> +       tcpu->buffer = NULL;
>         close(tcpu->fd);
>         tracefs_cpu_free_fd(tcpu);
> }

This also had whitespace issues.

I fixed it up and applied it.

Thanks,

-- Steve