Re: [PATCH v2 1/2] tools/nolibc: Add dirfd()

From: Thomas Weißschuh

Date: Wed Oct 07 2026 - 04:08:36 EST


On 2026-10-07 14:29:12+0900, Daniel Palmer wrote:
> This is useful for things like fstatat() on children of a directory
> opened with opendir().
>
> At the same time use the new internal helper to replace the two places
> that are converting the DIR pointer back into an fd.
>
> Signed-off-by: Daniel Palmer <daniel@xxxxxxxxx>
> ---
> tools/include/nolibc/dirent.h | 38 +++++++++++++++++++++++++++--------
> 1 file changed, 30 insertions(+), 8 deletions(-)
>
> diff --git a/tools/include/nolibc/dirent.h b/tools/include/nolibc/dirent.h
> index 4e02ef25e72d..d282ea8eb5d3 100644
> --- a/tools/include/nolibc/dirent.h
> +++ b/tools/include/nolibc/dirent.h
> @@ -27,6 +27,18 @@ typedef struct {
> char dummy[1];
> } DIR;
>
> +/* Internal dirfd() that does not set errno */
> +static __attribute__((unused))
> +int __nolibc_dirfd(DIR *dirp)
> +{
> + intptr_t i = (intptr_t)dirp;
> +
> + if (i >= 0)
> + return -1;
> +
> + return ~i;
> +}

I'm fine with keeping __nolibc_dirfd(), but the diffs would be nicer if
it was introduced in a dedicated commit.

> +
> static __attribute__((unused))
> DIR *fdopendir(int fd)
> {
> @@ -49,15 +61,27 @@ DIR *opendir(const char *name)
> }
>
> static __attribute__((unused))
> -int closedir(DIR *dirp)
> +int dirfd(DIR *dirp)
> {
> - intptr_t i = (intptr_t)dirp;
> + int fd = __nolibc_dirfd(dirp);
>
> - if (i >= 0) {
> + if (fd < 0) {
> SET_ERRNO(EBADF);
> return -1;
> }
> - return close(~i);
> +
> + return fd;
> +}

(...)