[PATCH 06/31] ctf_loader, libctf: Fix error path resource leaks

Arnaldo Carvalho de Melo <[email protected]> Wed, 29 Jul 2026 16:07:06 -0300
Newsgroups org.kernel.vger.dwarves,org.kernel.vger.bpf
Message-ID <[email protected]>
From: Arnaldo Carvalho de Melo <[email protected]>

Three resource leaks in CTF loading error paths:

1. ctf__load_file(): if cu__new() returns NULL, the ctf state allocated
   by ctf__new() is leaked.  Add ctf__delete(state) before returning.

2. ctf__load_file(): if ctf__load() fails, both cu and state are
   leaked.  Since cu->priv = state and cu->dfops = &ctf__ops are
   already set, cu__delete(cu) will invoke ctf__cu_delete() which
   calls ctf__delete(), cleaning up both.

3. ctf__decompress(): if inflate() fails after inflateInit() succeeded,
   the zlib internal decompression state is leaked because the err:
   path only frees the output buffer without calling inflateEnd().
   Add inflateEnd(&state) before the goto.

Fixes: 2dfa5fe6eab0c157 ("[DWARVES]: Initial CTF support")
Assisted-by: Claude:claude-sonnet-4-5
Signed-off-by: Arnaldo Carvalho de Melo <[email protected]>
---
 ctf_loader.c | 8 ++++++--
 libctf.c     | 1 +
 2 files changed, 7 insertions(+), 2 deletions(-)

diff --git a/ctf_loader.c b/ctf_loader.c
index 501c4abe859c0d52..39aef17893da5314 100644
--- a/ctf_loader.c
+++ b/ctf_loader.c
@@ -704,8 +704,10 @@ int ctf__load_file(struct cus *cus, struct conf_load *conf,
 		return -1;
 
 	struct cu *cu = cu__new(filename, state->wordsize, NULL, 0, filename, false);
-	if (cu == NULL)
+	if (cu == NULL) {
+		ctf__delete(state);
 		return -1;
+	}
 
 	cu->language = LANG_C;
 	cu->uses_global_strings = false;
@@ -713,8 +715,10 @@ int ctf__load_file(struct cus *cus, struct conf_load *conf,
 	cu->dfops = &ctf__ops;
 	cu->priv = state;
 	state->priv = cu;
-	if (ctf__load(state) != 0)
+	if (ctf__load(state) != 0) {
+		cu__delete(cu);
 		return -1;
+	}
 
 	err = ctf__load_sections(state, cu);
 
diff --git a/libctf.c b/libctf.c
index 0641b10586527a6e..8e31e3d550ebd51a 100644
--- a/libctf.c
+++ b/libctf.c
@@ -104,6 +104,7 @@ static int ctf__decompress(struct ctf *ctf, void *orig_buf, size_t orig_size)
 
 	if (inflate(&state, Z_FINISH) != Z_STREAM_END) {
 		err_str = "struct ctf decompression inflate failure.";
+		inflateEnd(&state);
 		goto err;
 	}
 
-- 
2.55.0