diff --git a/libcomposefs/lcfs-utils.h b/libcomposefs/lcfs-utils.h index 240276c1..64eeb83d 100644 --- a/libcomposefs/lcfs-utils.h +++ b/libcomposefs/lcfs-utils.h @@ -45,6 +45,9 @@ static inline void cleanup_freep(void *p) free(*pp); } +// A wrapper around close() that takes a pointer to a file descriptor (integer): +// - Never returns an error (and preserves errno) +// - Sets the value to -1 after closing to make cleanup idempotent static inline void cleanup_fdp(int *fdp) { PROTECT_ERRNO; @@ -55,6 +58,7 @@ static inline void cleanup_fdp(int *fdp) fd = *fdp; if (fd != -1) (void)close(fd); + *fdp = -1; } #define cleanup_free __attribute__((cleanup(cleanup_freep))) diff --git a/tools/mkcomposefs.c b/tools/mkcomposefs.c index c67bba80..7fb7487a 100644 --- a/tools/mkcomposefs.c +++ b/tools/mkcomposefs.c @@ -245,8 +245,7 @@ static int copy_file_with_dirs_if_needed(const char *src, const char *dst_base, return res; } } - close(sfd); - sfd = -1; + cleanup_fdp(&sfd); /* Make sure file is readable by all */ res = fchmod(dfd, 0644); @@ -258,8 +257,7 @@ static int copy_file_with_dirs_if_needed(const char *src, const char *dst_base, if (res < 0) { return res; } - close(dfd); - dfd = -1; + cleanup_fdp(&dfd); if (try_enable_fsverity) { /* Try to enable fsverity */