]> git.ipfire.org Git - pakfire.git/commitdiff
file: Cleanup initializing files
authorMichael Tremer <michael.tremer@ipfire.org>
Tue, 22 Oct 2024 14:34:46 +0000 (14:34 +0000)
committerMichael Tremer <michael.tremer@ipfire.org>
Tue, 22 Oct 2024 14:34:46 +0000 (14:34 +0000)
There was a potential memory leak here if the entry could not be
allocated.

Signed-off-by: Michael Tremer <michael.tremer@ipfire.org>
src/libpakfire/file.c

index 41af11cfb8dbe4b50f56c9cd9bf0768ce91604a1..1ac87532026a7de38f0a610be5c85e1c919e9f3c 100644 (file)
@@ -277,6 +277,10 @@ static int pakfire_file_from_archive_entry(struct pakfire_file* file, struct arc
        size_t size = 0;
        int r = 0;
 
+       // Make the analyzer happy
+       if (!file)
+               return -EINVAL;
+
        // Remove the existing entry
        if (file->entry)
                archive_entry_free(file->entry);
@@ -364,9 +368,13 @@ ERROR:
 }
 
 PAKFIRE_EXPORT int pakfire_file_create(struct pakfire_file** file, struct pakfire* pakfire) {
-       struct pakfire_file* f = calloc(1, sizeof(*f));
+       struct pakfire_file* f = NULL;
+       int r = 0;
+
+       // Allocate a new object
+       f = calloc(1, sizeof(*f));
        if (!f)
-               return 1;
+               return -errno;
 
        // Store a reference to the context
        f->ctx = pakfire_ctx(pakfire);
@@ -379,11 +387,19 @@ PAKFIRE_EXPORT int pakfire_file_create(struct pakfire_file** file, struct pakfir
 
        // Create a new archive entry
        f->entry = archive_entry_new();
-       if (!f->entry)
-               return -ENOMEM;
+       if (!f->entry) {
+               r = -errno;
+               goto ERROR;
+       }
 
-       *file = f;
-       return 0;
+       // Return the pointer
+       *file = pakfire_file_ref(f);
+
+ERROR:
+       if (f)
+               pakfire_file_unref(f);
+
+       return r;
 }
 
 int pakfire_file_read(struct pakfire_file* file, struct archive* reader, const char* path) {
@@ -410,20 +426,24 @@ int pakfire_file_read(struct pakfire_file* file, struct archive* reader, const c
 
 int pakfire_file_create_from_archive_entry(struct pakfire_file** file, struct pakfire* pakfire,
                struct archive_entry* entry) {
-       int r = pakfire_file_create(file, pakfire);
-       if (r)
-               return r;
+       struct pakfire_file* f = NULL;
+       int r;
+
+       r = pakfire_file_create(&f, pakfire);
+       if (r < 0)
+               goto ERROR;
 
        // Copy archive entry
-       r = pakfire_file_from_archive_entry(*file, entry);
-       if (r)
+       r = pakfire_file_from_archive_entry(f, entry);
+       if (r < 0)
                goto ERROR;
 
-       return 0;
+       // Return the file
+       *file = pakfire_file_ref(f);
 
 ERROR:
-       pakfire_file_unref(*file);
-       *file = NULL;
+       if (f)
+               pakfire_file_unref(f);
 
        return r;
 }