Subject: [PATCH AUTOSEL 5.16 012/217] selftests/bpf: Fix memory leaks in btf_type_c_dump() helper

From: Sasha Levin <[email-masked]>
Date: Mon, 17 Jan 2022 21:16:15 -0500

From: Andrii Nakryiko <[email-masked]>

[ Upstream commit 8ba285874913da21ca39a46376e9cc5ce0f45f94 ]

Free up memory and resources used by temporary allocated memstream and
btf_dump instance.

Signed-off-by: Andrii Nakryiko <[email-masked]>
Signed-off-by: Alexei Starovoitov <[email-masked]>
Reviewed-by: Hengqi Chen <[email-masked]>
Link: https://lore.kernel.org/bpf/[email-masked]
Signed-off-by: Sasha Levin <[email-masked]>
---
 tools/testing/selftests/bpf/btf_helpers.c | 9 +++++++--
 1 file changed, 7 insertions(+), 2 deletions(-)

diff --git a/tools/testing/selftests/bpf/btf_helpers.c b/tools/testing/selftests/bpf/btf_helpers.c
index b5b6b013a245e..3d1a748d09d81 100644
--- a/tools/testing/selftests/bpf/btf_helpers.c
+++ b/tools/testing/selftests/bpf/btf_helpers.c
@@ -251,18 +251,23 @@ const char *btf_type_c_dump(const struct btf *btf)
 	d = btf_dump__new(btf, NULL, &opts, btf_dump_printf);
 	if (libbpf_get_error(d)) {
 		fprintf(stderr, "Failed to create btf_dump instance: %ld\n", libbpf_get_error(d));
-		return NULL;
+		goto err_out;
 	}
 
 	for (i = 1; i < btf__type_cnt(btf); i++) {
 		err = btf_dump__dump_type(d, i);
 		if (err) {
 			fprintf(stderr, "Failed to dump type [%d]: %d\n", i, err);
-			return NULL;
+			goto err_out;
 		}
 	}
 
+	btf_dump__free(d);
 	fflush(buf_file);
 	fclose(buf_file);
 	return buf;
+err_out:
+	btf_dump__free(d);
+	fclose(buf_file);
+	return NULL;
 }
-- 
2.34.1