Re: [PATCH] bpftool: Fix JSON writer resource leak in version command
From: Andrii Nakryiko
Date: Mon Jun 16 2025 - 17:19:35 EST
On Mon, Jun 16, 2025 at 8:30 AM Yuan Chen <chenyuan_fl@xxxxxxx> wrote:
>
> From: Yuan Chen <chenyuan@xxxxxxxxxx>
>
> When using `bpftool --version -j/-p`, the JSON writer object
> created in do_version() was not properly destroyed after use.
> This caused a memory leak each time the version command was
> executed with JSON output.
>
> Fix: 004b45c0e51a (tools: bpftool: provide JSON output for all possible commands)
> Signed-off-by: Yuan Chen <chenyuan@xxxxxxxxxx>
> Suggested-by: Quentin Monnet <qmo@xxxxxxxxxx>
> ---
> tools/bpf/bpftool/main.c | 8 ++++++--
> 1 file changed, 6 insertions(+), 2 deletions(-)
>
> diff --git a/tools/bpf/bpftool/main.c b/tools/bpf/bpftool/main.c
> index cd5963cb6058..33c68eccd2c3 100644
> --- a/tools/bpf/bpftool/main.c
> +++ b/tools/bpf/bpftool/main.c
> @@ -533,8 +533,12 @@ int main(int argc, char **argv)
> if (argc < 0)
> usage();
>
> - if (version_requested)
> - return do_version(argc, argv);
> + if (version_requested) {
> + ret = do_version(argc, argv);
> + if (json_output)
> + jsonw_destroy(&json_wtr);
> + return ret;
> + }
there is also btf__free(base_btf), so instead of jsonw_destroy copy,
let's maybe just do
if (version_requested)
ret = do_version(...);
else
ret = cmd_select(...);
jsonw_destroy, btf__free...
return ret;
pw-bot: cr
>
> ret = cmd_select(commands, argc, argv, do_help);
>
> --
> 2.44.0
>
>