[PATCH v2025.09.y 22/58] FIT: fix double free issue with >1 reference count

Ahmad Fatoum a.fatoum at pengutronix.de
Fri Mar 13 06:25:06 PDT 2026


fit_open() was recently changed to be reference counted. When the FIT is
already open, a handle will be returned with the canonical filename
being the only allocation incurred.

fit_close() however unconditionally frees the handle without regards to
the reference count.

Fix this and while at it, fix the memory leak for the canonical filename
as well.

(cherry picked from commit ba345a71e85e90d70c01a3a6ec06bf6258634d2c)

Reported-by: Claude Sonnet 4.5 <noreply at anthropic.com>
Fixes: f3aadb274abe ("FIT: add support to cache opened fit images")
Signed-off-by: Ahmad Fatoum <a.fatoum at pengutronix.de>
Reviewed-by: Marco Felsch <m.felsch at pengutronix.de>
Link: https://lore.barebox.org/20260126104433.765071-1-a.fatoum@pengutronix.de
Signed-off-by: Sascha Hauer <s.hauer at pengutronix.de>
---
 common/image-fit.c | 10 ++++++----
 1 file changed, 6 insertions(+), 4 deletions(-)

diff --git a/common/image-fit.c b/common/image-fit.c
index 6b44a79e9d1c..027b268928d3 100644
--- a/common/image-fit.c
+++ b/common/image-fit.c
@@ -1016,6 +1016,7 @@ struct fit_handle *fit_open(const char *_filename, bool verbose,
 
 	handle = fit_get_handle(filename);
 	if (handle) {
+		free(filename);
 		refcount_inc(&handle->users);
 		return handle;
 	}
@@ -1049,10 +1050,10 @@ struct fit_handle *fit_open(const char *_filename, bool verbose,
 	return handle;
 }
 
-static void __fit_close(struct fit_handle *handle)
+static bool __fit_close(struct fit_handle *handle)
 {
 	if (!refcount_dec_and_test(&handle->users))
-		return;
+		return false;
 
 	if (handle->root)
 		of_delete_node(handle->root);
@@ -1062,12 +1063,13 @@ static void __fit_close(struct fit_handle *handle)
 
 	free(handle->filename);
 	free(handle->fit_alloc);
+	return true;
 }
 
 void fit_close(struct fit_handle *handle)
 {
-	__fit_close(handle);
-	free(handle);
+	if (__fit_close(handle))
+		free(handle);
 }
 
 static int do_bootm_fit(struct image_data *data)
-- 
2.47.3




More information about the barebox mailing list