readdir_r() stores the result of _sys_lseek() in an int. Directory
offsets are opaque cookies which can use all 64 bits: ext4, for
instance, gives 64-bit processes 63-bit hashes, and
0x7fffffffffffffff as the offset after the last entry. Truncated to an
int, such an offset is negative about half the time, and readdir_r()
takes it for an error.

Since commit 4ada5679f18d ("tools/nolibc/dirent: avoid errno in
readdir_r"), readdir_r() fails at the first entry whose offset has
bit 31 set, which on ext4 is usually one of the first few, and returns
the truncated offset as the error number. Before that, only -1 counted
as an error, which the last entry always hits: readdir_r() then
returned errno, usually 0, without filling in the entry, so the caller
got the previous entry a second time and never saw the last one.

32-bit processes get 31-bit hashes from ext4 and are not affected.

Keep the offset in an off_t.

Fixes: 665fa8dea90d ("tools/nolibc: add support for directory access")
Cc: [email protected] # v6.15+
Assisted-by: LLM
Signed-off-by: Danish Khateeb <[email protected]>
---
 tools/include/nolibc/dirent.h | 7 ++++---
 1 file changed, 4 insertions(+), 3 deletions(-)

diff --git a/tools/include/nolibc/dirent.h b/tools/include/nolibc/dirent.h
index 2dbf4052b85a..19857369de2a 100644
--- a/tools/include/nolibc/dirent.h
+++ b/tools/include/nolibc/dirent.h
@@ -81,6 +81,7 @@ int readdir_r(DIR *dirp, struct dirent *entry, struct dirent 
**result)
        struct linux_dirent64 *ldir = (void *)buf;
        intptr_t i = (intptr_t)dirp;
        int fd, ret;
+       off_t off;
 
        if (i >= 0)
                return EBADF;
@@ -100,9 +101,9 @@ int readdir_r(DIR *dirp, struct dirent *entry, struct 
dirent **result)
         * readdir() can only return one entry at a time.
         * Make sure the non-returned ones are not skipped.
         */
-       ret = _sys_lseek(fd, ldir->d_off, SEEK_SET);
-       if (ret < 0)
-               return -ret;
+       off = _sys_lseek(fd, ldir->d_off, SEEK_SET);
+       if (off < 0)
+               return -off;
 
        entry->d_ino = ldir->d_ino;
        /* the destination should always be big enough */
-- 
2.55.0


Reply via email to