From 8a0a7cf93eeec6f5873529145088b61b259112cc Mon Sep 17 00:00:00 2001 From: Aaron Merey Date: Mon, 18 Nov 2024 18:35:38 -0500 Subject: [PATCH] srcfiles.cxx: Prevent fd and entry leak Make sure to free fd and the archive entry if an error is encountered while adding source files to the archive. Signed-off-by: Aaron Merey --- src/srcfiles.cxx | 29 +++++++++++++++++------------ 1 file changed, 17 insertions(+), 12 deletions(-) diff --git a/src/srcfiles.cxx b/src/srcfiles.cxx index c466b307..c36a7034 100644 --- a/src/srcfiles.cxx +++ b/src/srcfiles.cxx @@ -312,7 +312,6 @@ void zip_files() struct stat st; char buff[BUFFER_SIZE]; int len; - int fd; #ifdef ENABLE_LIBDEBUGINFOD /* Initialize a debuginfod client. */ static unique_ptr @@ -325,8 +324,10 @@ void zip_files() int missing_files = 0; for (const auto &pair : debug_sourcefiles) { - fd = -1; + int fd = -1; const std::string &file_path = pair.first; + struct archive_entry *entry = NULL; + string entry_name; /* Attempt to query debuginfod client to fetch source files. */ #ifdef ENABLE_LIBDEBUGINFOD @@ -352,9 +353,9 @@ void zip_files() if (!no_backup) #endif /* ENABLE_LIBDEBUGINFOD */ - /* Files could not be located using debuginfod, search locally */ - if (fd < 0) - fd = open(file_path.c_str(), O_RDONLY); + /* Files could not be located using debuginfod, search locally */ + if (fd < 0) + fd = open(file_path.c_str(), O_RDONLY); if (fd < 0) { if (verbose) @@ -371,11 +372,11 @@ void zip_files() missing_files++; if (verbose) cerr << "Error: Failed to get file status for " << file_path << ": " << strerror(errno) << endl; - continue; + goto next; } - struct archive_entry *entry = archive_entry_new(); + entry = archive_entry_new(); /* Removing first "/"" to make the path "relative" before zipping, otherwise warnings are raised when unzipping. */ - string entry_name = file_path.substr(file_path.find_first_of('/') + 1); + entry_name = file_path.substr(file_path.find_first_of('/') + 1); archive_entry_set_pathname(entry, entry_name.c_str()); archive_entry_copy_stat(entry, &st); if (archive_write_header(a, entry) != ARCHIVE_OK) @@ -385,7 +386,7 @@ void zip_files() missing_files++; if (verbose) cerr << "Error: failed to write header for " << file_path << ": " << archive_error_string(a) << endl; - continue; + goto next; } /* Write the file to the zip. */ @@ -397,7 +398,7 @@ void zip_files() missing_files++; if (verbose) cerr << "Error: Failed to open file: " << file_path << ": " << strerror(errno) < 0) { @@ -409,8 +410,12 @@ void zip_files() } len = read(fd, buff, sizeof(buff)); } - close(fd); - archive_entry_free(entry); + +next: + if (fd >= 0) + close(fd); + if (entry != NULL) + archive_entry_free(entry); } if (verbose && missing_files > 0 ) cerr << missing_files << " file(s) listed above could not be found. " << endl; -- 2.47.2