From 381f7b242dadbc37fb3be135a8f7e330a27f68ea Mon Sep 17 00:00:00 2001 From: Fabio Scotto di Santolo Date: Wed, 26 Aug 2026 15:36:29 +0200 Subject: [PATCH] Report crc32 failure through the return value, not a sentinel crc32 returned 0 both for a read error and as a genuine checksum, so the caller had to remember to test ferror separately. That is precisely how the descriptor leak fixed in 9e65819 got in. The ambiguity is not hypothetical: an empty file checksums to exactly 0, and create writes one for every empty file it walks. Take a uint32_t out parameter and return 0/-1 instead. Verified byte-identical snapshots against the previous build, and the values still agree with zlib.crc32 for both an empty and a 100KB file. A read failure still surfaces: create over a symlink to a directory reports "Is a directory". Co-Authored-By: Claude Opus 5 Claude-Session: https://claude.ai/code/session_018KyCHPAxWzqa3vHKdXJkgx --- include/hash.h | 8 +++++--- src/hash.c | 7 ++++--- src/types.c | 7 +++---- 3 files changed, 12 insertions(+), 10 deletions(-) diff --git a/include/hash.h b/include/hash.h index da2f55e..dfe83ce 100644 --- a/include/hash.h +++ b/include/hash.h @@ -4,8 +4,10 @@ #include #include -/* Compute CRC-32 checksum of stream contents. - Returns 0 on read error. */ -uint32_t crc32(FILE *stream); +/* Compute the CRC-32 checksum of the stream's remaining contents into *out. + Returns 0 on success, -1 on read error, leaving *out untouched. The result + is reported through an out parameter because 0 is a perfectly good checksum + and would otherwise be indistinguishable from a failure. */ +int crc32(FILE *stream, uint32_t *out); #endif diff --git a/src/hash.c b/src/hash.c index 9f74a3b..d0d0137 100644 --- a/src/hash.c +++ b/src/hash.c @@ -34,7 +34,7 @@ static uint32_t crc32_update(uint32_t crc, const uint8_t *data, size_t length) { return crc; } -uint32_t crc32(FILE *stream) { +int crc32(FILE *stream, uint32_t *out) { uint8_t buffer[BUFFER_SIZE]; size_t bytes_read; uint32_t crc = 0xFFFFFFFF; @@ -44,7 +44,8 @@ uint32_t crc32(FILE *stream) { } if (ferror(stream)) - return 0; + return -1; - return crc ^ 0xFFFFFFFF; + *out = crc ^ 0xFFFFFFFF; + return 0; } diff --git a/src/types.c b/src/types.c index 226244c..a043d05 100644 --- a/src/types.c +++ b/src/types.c @@ -458,10 +458,9 @@ int RecordObjectWrite(struct RecordObject *self, const char *path, FILE *out) { if ((f = fopen(path, "r")) == NULL) goto cleanup; - hash = crc32(f); - /* ferror has to be sampled before fclose, but the stream must be closed - either way: short-circuiting on ferror would leak it. */ - const int read_failed = ferror(f); + /* The read result has to be captured before fclose, but the stream must be + closed either way: short-circuiting on the failure would leak it. */ + const int read_failed = crc32(f, &hash) == -1; const int close_failed = fclose(f) != 0; f = NULL; if (read_failed || close_failed)