Reset errno adjacent to readdir, not at the bottom of the loop

readdir returns NULL both at end of directory and on error, so the loop
tells the two apart with a post-loop errno test. The reset feeding that
test sat at the bottom of the body, where the `continue` on "." and ".."
skips it -- and those are typically the first two entries.

POSIX allows readdir to set errno on a successful call, so a stale value
could survive to the final NULL and make walk report a failure that never
happened. Move the reset next to the call it guards.

Verified unchanged against the previous build: identical scan output over
a 270-entry tree, 4125 entries over /usr/include, and the EACCES,
empty-directory and deep-nesting paths all behave as before.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_018KyCHPAxWzqa3vHKdXJkgx
This commit is contained in:
Fabio Scotto di Santolo
2026-08-26 15:18:27 +02:00
parent c6ffc7fbb9
commit 594dcfe62c

View File

@@ -51,8 +51,16 @@ int walk(const char *directory, WalkOp op, void *context) {
char *path = NULL; char *path = NULL;
struct dirent *direntp = NULL; struct dirent *direntp = NULL;
errno = 0; for (;;) {
while ((direntp = readdir(dirp)) != NULL) { /* readdir returns NULL both at end of directory and on error, and is
allowed to set errno even when it succeeds. Reset it adjacent to the
call, so the test after the loop tells the two apart: resetting at the
bottom of the body instead would be skipped by the continue below. */
errno = 0;
direntp = readdir(dirp);
if (direntp == NULL)
break;
if (ignore_file(direntp->d_name)) if (ignore_file(direntp->d_name))
continue; continue;
@@ -87,7 +95,6 @@ int walk(const char *directory, WalkOp op, void *context) {
free(path); free(path);
path = NULL; path = NULL;
errno = 0;
} }
if (errno == 0) { if (errno == 0) {