16 # include <dirstream.h>
17 # include <not-cancel.h>
22 # define __builtin_expect(expr, expected_val) expr
27 # define dirent64 dirent
28 # define __fxstat64(V, fd, sb) fstat(fd, sb)
29 # define __fcntl fcntl
30 # define __set_errno(Val) do { errno = (Val); } while (0)
31 # define __libc_lock_init(NAME) ((NAME) = 0, 0)
32 # define close_not_cancel_no_status(fd) close (fd)
34 # define internal_function __attribute ((regparm (3), stdcall))
36 # define internal_function
41 int fd; /* File descriptor. */
43 char *data; /* Directory block. */
44 size_t allocation; /* Space allocated for the block. */
45 size_t size; /* Total valid data in the block. */
46 size_t offset; /* Current offset into the block. */
48 off_t filepos; /* Position of next entry to read. */
53 #undef _STATBUF_ST_BLKSIZE
57 __alloc_dir (int fd, bool close_fd)
59 if (__builtin_expect (__fcntl (fd, F_SETFD, FD_CLOEXEC), 0) < 0)
63 #ifdef _STATBUF_ST_BLKSIZE
64 if (__builtin_expect ((size_t) statp->st_blksize >= sizeof (struct dirent64),
66 allocation = statp->st_blksize;
69 allocation = (BUFSIZ < sizeof (struct dirent64)
70 ? sizeof (struct dirent64) : BUFSIZ);
72 const int pad = -sizeof (DIR) % __alignof__ (struct dirent64);
74 DIR *dirp = (DIR *) malloc (sizeof (DIR) + allocation + pad);
80 int save_errno = errno;
81 close_not_cancel_no_status (fd);
82 __set_errno (save_errno);
86 memset (dirp, '\0', sizeof (DIR));
87 dirp->data = (char *) (dirp + 1) + pad;
88 dirp->allocation = allocation;
91 __libc_lock_init (dirp->lock);
100 struct stat64 statbuf;
102 if (__builtin_expect (__fxstat64 (_STAT_VER, fd, &statbuf), 0) < 0)
104 if (__builtin_expect (! S_ISDIR (statbuf.st_mode), 0))
106 __set_errno (ENOTDIR);
109 /* Make sure the descriptor allows for reading. */
110 int flags = __fcntl (fd, F_GETFL);
111 if (__builtin_expect (flags == -1, 0))
113 if (__builtin_expect ((flags & O_ACCMODE) == O_WRONLY, 0))
115 __set_errno (EINVAL);
120 return __alloc_dir (fd, false);