From 7f0c18df76dfa07965d41ccccd704801bd78c40a Mon Sep 17 00:00:00 2001 From: Fabio Scotto di Santolo Date: Wed, 26 Aug 2026 15:11:06 +0200 Subject: [PATCH] Let a cleanup failure keep its own errno in copy and create Both cleanup blocks saved errno on entry and restored it whenever rc had become -1, including when it was the cleanup itself that had just failed. On the success path the saved value is meaningless, so a genuine fclose error was reported through a stale errno, usually 0: $ fsnap create dir /dev/full create failed: Success A buffered write may succeed and only fail at flush or close, which is exactly the case SPEC.md section 8 asks not to lose. Adopt the scheme already used in list(): a pre-existing error keeps errno, a cleanup error keeps its own, and either one yields -1. $ fsnap create dir /dev/full create failed: No space left on device Co-Authored-By: Claude Opus 5 Claude-Session: https://claude.ai/code/session_018KyCHPAxWzqa3vHKdXJkgx --- src/create.c | 20 ++++++++++++++++---- src/utility.c | 24 ++++++++++++++++++------ 2 files changed, 34 insertions(+), 10 deletions(-) diff --git a/src/create.c b/src/create.c index e9a19a1..d63f928 100644 --- a/src/create.c +++ b/src/create.c @@ -72,12 +72,24 @@ int create(const char *directory, const char *output_file) { rc = 0; cleanup:; + /* An error that happened before the cleanup owns errno; one raised by the + cleanup itself owns it only when nothing had failed yet. A buffered write + can fail for the first time in fclose, so that errno must survive. */ const int saved_errno = errno; + int cleanup_errno = 0; + free(resolved); unlink(template); - if (tmp != NULL && fclose(tmp) != 0 && rc == 0) - rc = -1; - if (rc == -1) + if (tmp != NULL && fclose(tmp) != 0) + cleanup_errno = errno; + + if (rc == -1) { errno = saved_errno; - return rc; + return -1; + } + if (cleanup_errno != 0) { + errno = cleanup_errno; + return -1; + } + return 0; } diff --git a/src/utility.c b/src/utility.c index e0c5532..d738778 100644 --- a/src/utility.c +++ b/src/utility.c @@ -74,14 +74,26 @@ int copy(const char *src, const char *dst) { rc = 0; cleanup:; + /* An error that happened before the cleanup owns errno; one raised by the + cleanup itself owns it only when nothing had failed yet. A buffered write + can fail for the first time in fclose, so that errno must survive. */ const int saved_errno = errno; - if (file1 != NULL && fclose(file1) != 0 && rc == 0) - rc = -1; - if (file2 != NULL && fclose(file2) != 0 && rc == 0) - rc = -1; - if (rc == -1) + int cleanup_errno = 0; + + if (file1 != NULL && fclose(file1) != 0 && cleanup_errno == 0) + cleanup_errno = errno; + if (file2 != NULL && fclose(file2) != 0 && cleanup_errno == 0) + cleanup_errno = errno; + + if (rc == -1) { errno = saved_errno; - return rc; + return -1; + } + if (cleanup_errno != 0) { + errno = cleanup_errno; + return -1; + } + return 0; } int count_lines(const char *file) {