[PATCH] bpftool: Fix JSON writer resource leak in version command

Yuan Chen posted 1 patch 3 months, 3 weeks ago
There is a newer version of this series
tools/bpf/bpftool/main.c | 1 +
1 file changed, 1 insertion(+)
[PATCH] bpftool: Fix JSON writer resource leak in version command
Posted by Yuan Chen 3 months, 3 weeks ago
From: chenyuan <chenyuan@kylinos.cn>

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: chenyuan <chenyuan@kylinos.cn>
---
 tools/bpf/bpftool/main.c | 1 +
 1 file changed, 1 insertion(+)

diff --git a/tools/bpf/bpftool/main.c b/tools/bpf/bpftool/main.c
index cd5963cb6058..c8838196a3bd 100644
--- a/tools/bpf/bpftool/main.c
+++ b/tools/bpf/bpftool/main.c
@@ -164,6 +164,7 @@ static int do_version(int argc, char **argv)
 		jsonw_end_object(json_wtr);	/* features */
 
 		jsonw_end_object(json_wtr);	/* root object */
+		jsonw_destroy(&json_wtr);
 	} else {
 		unsigned int nb_features = 0;
 
-- 
2.44.0
Re: [PATCH] bpftool: Fix JSON writer resource leak in version command
Posted by Quentin Monnet 3 months, 3 weeks ago
2025-06-16 09:50 UTC-0400 ~ Yuan Chen <chenyuan_fl@163.com>
> From: chenyuan <chenyuan@kylinos.cn>
> 
> 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: chenyuan <chenyuan@kylinos.cn>
> ---
>  tools/bpf/bpftool/main.c | 1 +
>  1 file changed, 1 insertion(+)
> 
> diff --git a/tools/bpf/bpftool/main.c b/tools/bpf/bpftool/main.c
> index cd5963cb6058..c8838196a3bd 100644
> --- a/tools/bpf/bpftool/main.c
> +++ b/tools/bpf/bpftool/main.c
> @@ -164,6 +164,7 @@ static int do_version(int argc, char **argv)
>  		jsonw_end_object(json_wtr);	/* features */
>  
>  		jsonw_end_object(json_wtr);	/* root object */
> +		jsonw_destroy(&json_wtr);
>  	} else {
>  		unsigned int nb_features = 0;
>  


Good catch, but the fix is not correct:

	$ ./bpftool version -j >/dev/null
	zsh: segmentation fault (core dumped)

This is because we already run jsonw_destroy() at the end of the main()
function when printing the version with "bpftool version", the command
(and not the -V or --version options).

One option would be to add a call at the end of main(), when we call
do_version() because "version_requested" is set:

	if (version_requested) {
		do_version(argc, argv);
		if (json_output)
			jsonw_destroy(&json_wtr);
		return 0;
	}

Thanks,
Quentin

pw-bot: cr