From dc739f280f430ad323594ab38adf1e85b5ac0efd Mon Sep 17 00:00:00 2001 From: Nick Bowler Date: Wed, 16 Sep 2009 00:37:50 -0400 Subject: [PATCH] libupkg: Add a destructor that is called on package close. This fixes mistake where fclose was called unconditionally in upkg_close. --- src/libupkg.c | 22 +++++++++++++++------- src/upkg.h | 3 ++- 2 files changed, 17 insertions(+), 8 deletions(-) diff --git a/src/libupkg.c b/src/libupkg.c index ae48820..004cb46 100644 --- a/src/libupkg.c +++ b/src/libupkg.c @@ -45,6 +45,7 @@ struct upkg_import { struct upkg_private { const struct upkg_file_ops *fops; + int (*dtor)(void *handle); void *f; struct upkg_file *last_file; @@ -78,6 +79,11 @@ static int file_eof(void *handle) return feof(handle); } +static int file_close(void *handle) +{ + return fclose(handle); +} + const struct upkg_file_ops upkg_default_fops = { .read = file_read, .seek = file_seek, @@ -380,7 +386,8 @@ err: return -1; } -struct upkg *upkg_open(void *f, const struct upkg_file_ops *fops) +struct upkg *upkg_open(void *f, const struct upkg_file_ops *fops, + int (*destructor)(void *handle)) { unsigned char hdr_buf[UPKG_HDR_SIZE]; struct upkg *pkg; @@ -398,6 +405,7 @@ struct upkg *upkg_open(void *f, const struct upkg_file_ops *fops) return NULL; } pkg->priv->fops = fops; + pkg->priv->dtor = destructor; pkg->priv->f = f; if (pkg_init_guid(pkg) != 0) { @@ -438,7 +446,7 @@ struct upkg *upkg_fopen(const char *path) return NULL; } - pkg = upkg_open(f, &upkg_default_fops); + pkg = upkg_open(f, &upkg_default_fops, file_close); if (!pkg) { fclose(f); } @@ -450,12 +458,12 @@ int upkg_close(struct upkg *pkg) { int rc = 0; - if (pkg->priv->f) { - rc = fclose(pkg->priv->f); + if (pkg->priv->dtor) { + rc = pkg->priv->dtor(pkg->priv->f); + } - for (unsigned i = 0; i < pkg->name_count; i++) { - free(pkg->priv->names[i].name); - } + for (unsigned i = 0; i < pkg->name_count; i++) { + free(pkg->priv->names[i].name); } free(pkg->priv->imports); diff --git a/src/upkg.h b/src/upkg.h index 9fc8003..c5da628 100644 --- a/src/upkg.h +++ b/src/upkg.h @@ -91,7 +91,8 @@ struct upkg_file { /* Default I/O operations for ordinary files. */ extern const struct upkg_file_ops upkg_default_fops; -struct upkg *upkg_open(void *handle, const struct upkg_file_ops *fops); +struct upkg *upkg_open(void *handle, const struct upkg_file_ops *fops, + int (*destructor)(void *handle)); struct upkg *upkg_fopen(const char *path); int upkg_close(struct upkg *pkg); -- 2.43.2