libc: Improve POSIX conformance of dirfd()

POSIX states that dirfd() should set errno to EINVAL and return -1 if
dirp does not refer to a valid directory stream.  Our interpretation is
that this applies if dirp is null or the file descriptor associated
with it is negative.

MFC after:	1 week
Sponsored by:	Klara, Inc.
Reviewed by:	markj
Differential Revision:	https://reviews.freebsd.org/D55025
This commit is contained in:
Dag-Erling Smørgrav
2026-02-02 16:46:57 +01:00
parent 387ae63905
commit 5074d5c984
2 changed files with 18 additions and 1 deletions
+13 -1
View File
@@ -256,7 +256,9 @@ The
function returns 0 on success and -1 on failure.
The
.Fn fdclosedir
function returns an open file descriptor on success and -1 on failure.
and
.Fn dirfd
functions return an open file descriptor on success and -1 on failure.
.Sh ERRORS
The
.Fn opendir
@@ -327,6 +329,16 @@ function may also fail and set
.Va errno
for any of the errors specified for the routine
.Xr close 2 .
.Pp
The
.Fn dirfd
function will fail if:
.Bl -tag -width Er
.It Bq Er EINVAL
The
.Fa dirp
argument does not refer to a valid directory stream.
.El
.Sh SEE ALSO
.Xr close 2 ,
.Xr lseek 2 ,
+5
View File
@@ -28,6 +28,7 @@
#include "namespace.h"
#include <dirent.h>
#include <errno.h>
#include "un-namespace.h"
#include "gen-private.h"
@@ -35,5 +36,9 @@
int
dirfd(DIR *dirp)
{
if (dirp == NULL || _dirfd(dirp) < 0) {
errno = EINVAL;
return (-1);
}
return (_dirfd(dirp));
}