From 0f261188f1161a685b22c1e3d3e07b3666a31971 Mon Sep 17 00:00:00 2001 From: Evgeniy Naydanov Date: Tue, 10 Oct 2023 13:57:43 +0300 Subject: [PATCH] target: fix a memory leak in image_open Change-Id: I629be26e7752858091ad58c2b3b07f43e22e8c23 Signed-off-by: Evgeniy Naydanov Reviewed-on: https://review.openocd.org/c/openocd/+/7935 Reviewed-by: Antonio Borneo Tested-by: jenkins --- src/target/image.c | 22 ++++++++++++++-------- 1 file changed, 14 insertions(+), 8 deletions(-) diff --git a/src/target/image.c b/src/target/image.c index e998a35f4d..9175c200af 100644 --- a/src/target/image.c +++ b/src/target/image.c @@ -968,12 +968,13 @@ int image_open(struct image *image, const char *url, const char *type_string) retval = fileio_open(&image_binary->fileio, url, FILEIO_READ, FILEIO_BINARY); if (retval != ERROR_OK) - return retval; + goto free_mem_on_error; + size_t filesize; retval = fileio_size(image_binary->fileio, &filesize); if (retval != ERROR_OK) { fileio_close(image_binary->fileio); - return retval; + goto free_mem_on_error; } image->num_sections = 1; @@ -988,14 +989,14 @@ int image_open(struct image *image, const char *url, const char *type_string) retval = fileio_open(&image_ihex->fileio, url, FILEIO_READ, FILEIO_TEXT); if (retval != ERROR_OK) - return retval; + goto free_mem_on_error; retval = image_ihex_buffer_complete(image); if (retval != ERROR_OK) { LOG_ERROR( "failed buffering IHEX image, check server output for additional information"); fileio_close(image_ihex->fileio); - return retval; + goto free_mem_on_error; } } else if (image->type == IMAGE_ELF) { struct image_elf *image_elf; @@ -1004,12 +1005,12 @@ int image_open(struct image *image, const char *url, const char *type_string) retval = fileio_open(&image_elf->fileio, url, FILEIO_READ, FILEIO_BINARY); if (retval != ERROR_OK) - return retval; + goto free_mem_on_error; retval = image_elf_read_headers(image); if (retval != ERROR_OK) { fileio_close(image_elf->fileio); - return retval; + goto free_mem_on_error; } } else if (image->type == IMAGE_MEMORY) { struct target *target = get_target(url); @@ -1039,14 +1040,14 @@ int image_open(struct image *image, const char *url, const char *type_string) retval = fileio_open(&image_mot->fileio, url, FILEIO_READ, FILEIO_TEXT); if (retval != ERROR_OK) - return retval; + goto free_mem_on_error; retval = image_mot_buffer_complete(image); if (retval != ERROR_OK) { LOG_ERROR( "failed buffering S19 image, check server output for additional information"); fileio_close(image_mot->fileio); - return retval; + goto free_mem_on_error; } } else if (image->type == IMAGE_BUILDER) { image->num_sections = 0; @@ -1067,6 +1068,11 @@ int image_open(struct image *image, const char *url, const char *type_string) } return retval; + +free_mem_on_error: + free(image->type_private); + image->type_private = NULL; + return retval; }; int image_read_section(struct image *image,