2 * Copyright (c) 1990, 1993, 1994
3 * The Regents of the University of California. All rights reserved.
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions
8 * 1. Redistributions of source code must retain the above copyright
9 * notice, this list of conditions and the following disclaimer.
10 * 2. Redistributions in binary form must reproduce the above copyright
11 * notice, this list of conditions and the following disclaimer in the
12 * documentation and/or other materials provided with the distribution.
13 * 4. Neither the name of the University nor the names of its contributors
14 * may be used to endorse or promote products derived from this software
15 * without specific prior written permission.
17 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
18 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
19 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
20 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
21 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
22 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
23 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
24 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
25 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
26 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
30 #if defined(LIBC_SCCS) && !defined(lint)
31 static char sccsid[] = "@(#)fts.c 8.6 (Berkeley) 8/14/94";
32 #endif /* LIBC_SCCS and not lint */
35 #include <sys/param.h>
36 #include <include/sys/stat.h>
46 # define _INCLUDE_POSIX_SOURCE
47 # define __errno_location() (&errno)
48 # define dirfd(dirp) -1
51 # define __fxstat64(_stat_ver, _fd, _sbp) fstat((_fd), (_sbp))
54 # define __errno_location() (&errno)
55 # define dirfd(dirp) -1
57 # define __fxstat64(_stat_ver, _fd, _sbp) fstat((_fd), (_sbp))
59 #if defined(__APPLE__)
60 # define __errno_location() (__error())
62 # define __fxstat64(_stat_ver, _fd, _sbp) fstat64((_fd), (_sbp))
69 # define __set_errno(val) (*__errno_location ()) = (val)
71 # define __close close
72 # define __fchdir fchdir
76 /* Largest alignment size needed, minus one.
77 Usually long double is the worst case. */
79 #define ALIGNBYTES (__alignof__ (long double) - 1)
81 /* Align P to that size. */
83 #define ALIGN(p) (((unsigned long int) (p) + ALIGNBYTES) & ~ALIGNBYTES)
87 static FTSENT * fts_alloc(FTS * sp, const char * name, int namelen);
88 static FTSENT * fts_build(FTS * sp, int type);
89 static void fts_lfree(FTSENT * head);
90 static void fts_load(FTS * sp, FTSENT * p);
91 static size_t fts_maxarglen(char * const * argv);
92 static void fts_padjust(FTS * sp, FTSENT * head);
93 static int fts_palloc(FTS * sp, size_t more);
94 static FTSENT * fts_sort(FTS * sp, FTSENT * head, int nitems);
95 static uint16_t fts_stat(FTS * sp, FTSENT * p, int follow);
96 static int fts_safe_changedir(FTS * sp, FTSENT * p, int fd,
100 #define MAX(a, b) ({ __typeof__ (a) _a = (a); \
101 __typeof__ (b) _b = (b); \
102 _a > _b ? _a : _b; })
105 #define ISDOT(a) (a[0] == '.' && (!a[1] || (a[1] == '.' && !a[2])))
107 #define CLR(opt) (sp->fts_options &= ~(opt))
108 #define ISSET(opt) (sp->fts_options & (opt))
109 #define SET(opt) (sp->fts_options |= (opt))
111 #define FCHDIR(sp, fd) (!ISSET(FTS_NOCHDIR) && __fchdir(fd))
113 /* fts_build flags */
114 #define BCHILD 1 /* fts_children */
115 #define BNAMES 2 /* fts_children, names only */
116 #define BREAD 3 /* fts_read */
119 Fts_open(char * const * argv, int options,
120 int (*compar) (const FTSENT **, const FTSENT **))
123 register FTSENT *p, *root;
125 FTSENT *parent, *tmp = NULL;
129 if (options & ~FTS_OPTIONMASK) {
130 __set_errno (EINVAL);
134 /* Allocate/initialize the stream */
135 if ((sp = malloc(sizeof(*sp))) == NULL)
137 memset(sp, 0, sizeof(*sp));
138 sp->fts_compar = (int (*) (const void *, const void *)) compar;
139 sp->fts_opendir = opendir;
140 sp->fts_readdir = readdir;
141 sp->fts_closedir = closedir;
143 sp->fts_lstat = lstat;
144 sp->fts_options = options;
146 /* Logical walks turn on NOCHDIR; symbolic links are too hard. */
147 if (ISSET(FTS_LOGICAL))
151 * Start out with 1K of path space, and enough, in any case,
152 * to hold the user's paths.
155 #define MAXPATHLEN 1024
157 if (fts_palloc(sp, MAX(fts_maxarglen(argv), MAXPATHLEN)))
160 /* Allocate/initialize root's parent. */
161 if ((parent = fts_alloc(sp, "", 0)) == NULL)
163 parent->fts_level = FTS_ROOTPARENTLEVEL;
165 /* Allocate/initialize root(s). */
166 for (root = NULL, nitems = 0; *argv != NULL; ++argv, ++nitems) {
167 /* Don't allow zero-length paths. */
168 if ((len = strlen(*argv)) == 0) {
169 __set_errno (ENOENT);
173 p = fts_alloc(sp, *argv, len);
176 p->fts_level = FTS_ROOTLEVEL;
177 p->fts_parent = parent;
178 p->fts_accpath = p->fts_name;
179 p->fts_info = fts_stat(sp, p, ISSET(FTS_COMFOLLOW));
181 /* Command-line "." and ".." are real directories. */
182 if (p->fts_info == FTS_DOT)
186 * If comparison routine supplied, traverse in sorted
187 * order; otherwise traverse in the order specified.
197 if (tmp != NULL) /* XXX can't happen */
203 if (compar && nitems > 1)
204 root = fts_sort(sp, root, nitems);
207 * Allocate a dummy pointer and make fts_read think that we've just
208 * finished the node before the root(s); set p->fts_info to FTS_INIT
209 * so that everything about the "current" node is ignored.
211 if ((sp->fts_cur = fts_alloc(sp, "", 0)) == NULL)
213 sp->fts_cur->fts_link = root;
214 sp->fts_cur->fts_info = FTS_INIT;
217 * If using chdir(2), grab a file descriptor pointing to dot to ensure
218 * that we can get back here; this could be avoided for some paths,
219 * but almost certainly not worth the effort. Slashes, symbolic links,
220 * and ".." are all fairly nasty problems. Note, if we can't get the
221 * descriptor we run anyway, just more slowly.
223 if (!ISSET(FTS_NOCHDIR)
224 && (sp->fts_rfd = __open(".", O_RDONLY, 0)) < 0)
229 mem3: fts_lfree(root);
231 mem2: free(sp->fts_path);
237 fts_load(FTS * sp, FTSENT * p)
243 * Load the stream structure for the next traversal. Since we don't
244 * actually enter the directory until after the preorder visit, set
245 * the fts_accpath field specially so the chdir gets done to the right
246 * place and the user can access the first node. From fts_open it's
247 * known that the path will fit.
249 len = p->fts_pathlen = p->fts_namelen;
250 memmove(sp->fts_path, p->fts_name, len + 1);
251 if ((cp = strrchr(p->fts_name, '/')) && (cp != p->fts_name || cp[1])) {
253 memmove(p->fts_name, cp, len + 1);
254 p->fts_namelen = len;
256 p->fts_accpath = p->fts_path = sp->fts_path;
257 sp->fts_dev = p->fts_dev;
263 register FTSENT *freep, *p;
270 * This still works if we haven't read anything -- the dummy structure
271 * points to the root list, so we step through to the end of the root
272 * list which has a valid parent pointer.
275 for (p = sp->fts_cur; p->fts_level >= FTS_ROOTLEVEL;) {
277 p = p->fts_link != NULL ? p->fts_link : p->fts_parent;
283 /* Free up child linked list, sort array, path buffer. */
285 fts_lfree(sp->fts_child);
290 /* Return to original directory, save errno if necessary. */
291 if (!ISSET(FTS_NOCHDIR)) {
292 saved_errno = __fchdir(sp->fts_rfd) ? errno : 0;
293 (void)__close(sp->fts_rfd);
295 /* Set errno and return. */
296 if (saved_errno != 0) {
297 /* Free up the stream pointer. */
299 __set_errno (saved_errno);
304 /* Free up the stream pointer. */
310 * Special case of "/" at the end of the path so that slashes aren't
311 * appended which would cause paths to be written as "....//foo".
314 (p->fts_path[p->fts_pathlen - 1] == '/' \
315 ? p->fts_pathlen - 1 : p->fts_pathlen)
321 register FTSENT *tmp;
326 /* If finished or unrecoverable error, return NULL. */
327 if (sp == NULL || sp->fts_cur == NULL || ISSET(FTS_STOP))
330 /* Set current node pointer. */
333 /* Save and zero out user instructions. */
334 instr = p->fts_instr;
335 p->fts_instr = FTS_NOINSTR;
337 /* Any type of file may be re-visited; re-stat and re-turn. */
338 if (instr == FTS_AGAIN) {
339 p->fts_info = fts_stat(sp, p, 0);
344 * Following a symlink -- SLNONE test allows application to see
345 * SLNONE and recover. If indirecting through a symlink, have
346 * keep a pointer to current location. If unable to get that
347 * pointer, follow fails.
349 if (instr == FTS_FOLLOW &&
350 (p->fts_info == FTS_SL || p->fts_info == FTS_SLNONE)) {
351 p->fts_info = fts_stat(sp, p, 1);
352 if (p->fts_info == FTS_D && !ISSET(FTS_NOCHDIR)) {
353 if ((p->fts_symfd = __open(".", O_RDONLY, 0)) < 0) {
354 p->fts_errno = errno;
355 p->fts_info = FTS_ERR;
357 p->fts_flags |= FTS_SYMFOLLOW;
362 /* Directory in pre-order. */
363 if (p->fts_info == FTS_D) {
364 /* If skipped or crossed mount point, do post-order visit. */
365 if (instr == FTS_SKIP ||
366 (ISSET(FTS_XDEV) && p->fts_dev != sp->fts_dev)) {
367 if (p->fts_flags & FTS_SYMFOLLOW)
368 (void)__close(p->fts_symfd);
370 fts_lfree(sp->fts_child);
371 sp->fts_child = NULL;
373 p->fts_info = FTS_DP;
377 /* Rebuild if only read the names and now traversing. */
378 if (sp->fts_child != NULL && ISSET(FTS_NAMEONLY)) {
380 fts_lfree(sp->fts_child);
381 sp->fts_child = NULL;
385 * Cd to the subdirectory.
387 * If have already read and now fail to chdir, whack the list
388 * to make the names come out right, and set the parent errno
389 * so the application will eventually get an error condition.
390 * Set the FTS_DONTCHDIR flag so that when we logically change
391 * directories back to the parent we don't do a chdir.
393 * If haven't read do so. If the read fails, fts_build sets
394 * FTS_STOP or the fts_info field of the node.
396 if (sp->fts_child != NULL) {
397 if (fts_safe_changedir(sp, p, -1, p->fts_accpath)) {
398 p->fts_errno = errno;
399 p->fts_flags |= FTS_DONTCHDIR;
400 for (p = sp->fts_child; p != NULL;
403 p->fts_parent->fts_accpath;
405 } else if ((sp->fts_child = fts_build(sp, BREAD)) == NULL) {
411 sp->fts_child = NULL;
415 /* Move to the next node on this level. */
417 if ((p = p->fts_link) != NULL) {
421 * If reached the top, return to the original directory (or
422 * the root of the tree), and load the paths for the next root.
424 if (p->fts_level == FTS_ROOTLEVEL) {
425 if (FCHDIR(sp, sp->fts_rfd)) {
430 return (sp->fts_cur = p);
434 * User may have called fts_set on the node. If skipped,
435 * ignore. If followed, get a file descriptor so we can
436 * get back if necessary.
438 if (p->fts_instr == FTS_SKIP)
440 if (p->fts_instr == FTS_FOLLOW) {
441 p->fts_info = fts_stat(sp, p, 1);
442 if (p->fts_info == FTS_D && !ISSET(FTS_NOCHDIR)) {
444 __open(".", O_RDONLY, 0)) < 0) {
445 p->fts_errno = errno;
446 p->fts_info = FTS_ERR;
448 p->fts_flags |= FTS_SYMFOLLOW;
450 p->fts_instr = FTS_NOINSTR;
453 name: t = sp->fts_path + NAPPEND(p->fts_parent);
455 memmove(t, p->fts_name, p->fts_namelen + 1);
456 return (sp->fts_cur = p);
459 /* Move up to the parent node. */
463 if (p->fts_level == FTS_ROOTPARENTLEVEL) {
465 * Done; free everything up and set errno to 0 so the user
466 * can distinguish between error and EOF.
470 return (sp->fts_cur = NULL);
473 /* NUL terminate the pathname. */
474 sp->fts_path[p->fts_pathlen] = '\0';
477 * Return to the parent directory. If at a root node or came through
478 * a symlink, go back through the file descriptor. Otherwise, cd up
481 if (p->fts_level == FTS_ROOTLEVEL) {
482 if (FCHDIR(sp, sp->fts_rfd)) {
486 } else if (p->fts_flags & FTS_SYMFOLLOW) {
487 if (FCHDIR(sp, p->fts_symfd)) {
489 (void)__close(p->fts_symfd);
490 __set_errno (saved_errno);
494 (void)__close(p->fts_symfd);
495 } else if (!(p->fts_flags & FTS_DONTCHDIR) &&
496 fts_safe_changedir(sp, p->fts_parent, -1, "..")) {
500 p->fts_info = p->fts_errno ? FTS_ERR : FTS_DP;
501 return (sp->fts_cur = p);
505 * Fts_set takes the stream as an argument although it's not used in this
506 * implementation; it would be necessary if anyone wanted to add global
507 * semantics to fts using fts_set. An error return is allowed for similar
511 Fts_set(FTS * sp, FTSENT * p, int instr)
513 if (instr != 0 && instr != FTS_AGAIN && instr != FTS_FOLLOW &&
514 instr != FTS_NOINSTR && instr != FTS_SKIP) {
515 __set_errno (EINVAL);
518 p->fts_instr = instr;
523 Fts_children(FTS * sp, int instr)
528 if (instr != 0 && instr != FTS_NAMEONLY) {
529 __set_errno (EINVAL);
533 /* Set current node pointer. */
537 * Errno set to 0 so user can distinguish empty directory from
542 /* Fatal errors stop here. */
546 /* Return logical hierarchy of user's arguments. */
547 if (p->fts_info == FTS_INIT)
548 return (p->fts_link);
551 * If not a directory being visited in pre-order, stop here. Could
552 * allow FTS_DNR, assuming the user has fixed the problem, but the
553 * same effect is available with FTS_AGAIN.
555 if (p->fts_info != FTS_D /* && p->fts_info != FTS_DNR */)
558 /* Free up any previous child list. */
559 if (sp->fts_child != NULL)
560 fts_lfree(sp->fts_child);
562 if (instr == FTS_NAMEONLY) {
569 * If using chdir on a relative path and called BEFORE fts_read does
570 * its chdir to the root of a traversal, we can lose -- we need to
571 * chdir into the subdirectory, and we don't know where the current
572 * directory is, so we can't get back so that the upcoming chdir by
573 * fts_read will work.
575 if (p->fts_level != FTS_ROOTLEVEL || p->fts_accpath[0] == '/' ||
577 return (sp->fts_child = fts_build(sp, instr));
579 if ((fd = __open(".", O_RDONLY, 0)) < 0)
581 sp->fts_child = fts_build(sp, instr);
585 return (sp->fts_child);
589 * This is the tricky part -- do not casually change *anything* in here. The
590 * idea is to build the linked list of entries that are used by fts_children
591 * and fts_read. There are lots of special cases.
593 * The real slowdown in walking the tree is the stat calls. If FTS_NOSTAT is
594 * set and it's a physical walk (so that symbolic links can't be directories),
595 * we can do things quickly. First, if it's a 4.4BSD file system, the type
596 * of the file is in the directory entry. Otherwise, we assume that the number
597 * of subdirectories in a node is equal to the number of links to the parent.
598 * The former skips all stat calls. The latter skips stat calls in any leaf
599 * directories and for any files after the subdirectories in the directory have
600 * been found, cutting the stat calls by about 2/3.
603 fts_build(FTS * sp, int type)
605 register struct dirent *dp;
606 register FTSENT *p, *head;
611 int cderrno, descend, len, level, maxlen, nlinks, saved_errno,
615 /* Set current node pointer. */
619 * Open the directory for reading. If this fails, we're done.
620 * If being called from fts_read, set the fts_info field.
622 #if defined FTS_WHITEOUT && 0
623 if (ISSET(FTS_WHITEOUT))
624 oflag = DTF_NODUP|DTF_REWIND;
626 oflag = DTF_HIDEW|DTF_NODUP|DTF_REWIND;
628 # define __opendir2(path, flag) (*sp->fts_opendir) (path)
630 if ((dirp = __opendir2(cur->fts_accpath, oflag)) == NULL) {
632 cur->fts_info = FTS_DNR;
633 cur->fts_errno = errno;
639 * Nlinks is the number of possible entries of type directory in the
640 * directory if we're cheating on stat calls, 0 if we're not doing
641 * any stat calls at all, -1 if we're doing stats on everything.
643 if (type == BNAMES) {
645 /* Be quiet about nostat, GCC. */
647 } else if (ISSET(FTS_NOSTAT) && ISSET(FTS_PHYSICAL)) {
648 nlinks = cur->fts_nlink - (ISSET(FTS_SEEDOT) ? 0 : 2);
656 (void)printf("nlinks == %d (cur: %d)\n", nlinks, cur->fts_nlink);
657 (void)printf("NOSTAT %d PHYSICAL %d SEEDOT %d\n",
658 ISSET(FTS_NOSTAT), ISSET(FTS_PHYSICAL), ISSET(FTS_SEEDOT));
661 * If we're going to need to stat anything or we want to descend
662 * and stay in the directory, chdir. If this fails we keep going,
663 * but set a flag so we don't chdir after the post-order visit.
664 * We won't be able to stat anything, but we can still return the
665 * names themselves. Note, that since fts_read won't be able to
666 * chdir into the directory, it will have to return different path
667 * names than before, i.e. "a/b" instead of "b". Since the node
668 * has already been visited in pre-order, have to wait until the
669 * post-order visit to return the error. There is a special case
670 * here, if there was nothing to stat then it's not an error to
671 * not be able to stat. This is all fairly nasty. If a program
672 * needed sorted entries or stat information, they had better be
673 * checking FTS_NS on the returned nodes.
676 if (nlinks || type == BREAD) {
677 if (fts_safe_changedir(sp, cur, dirfd(dirp), NULL)) {
678 if (nlinks && type == BREAD)
679 cur->fts_errno = errno;
680 cur->fts_flags |= FTS_DONTCHDIR;
683 (void) (*sp->fts_closedir) (dirp);
691 * Figure out the max file name length that can be stored in the
692 * current path -- the inner loop allocates more path as necessary.
693 * We really wouldn't have to do the maxlen calculations here, we
694 * could do them in fts_read before returning the path, but it's a
695 * lot easier here since the length is part of the dirent structure.
697 * If not changing directories set a pointer so that can just append
698 * each new name into the path.
701 if (ISSET(FTS_NOCHDIR)) {
702 cp = sp->fts_path + len;
705 /* GCC, you're too verbose. */
709 maxlen = sp->fts_pathlen - len;
711 level = cur->fts_level + 1;
713 /* Read the directory, attaching each entry to the `link' pointer. */
715 for (head = tail = NULL, nitems = 0;
716 dirp && (dp = (*sp->fts_readdir) (dirp));)
718 if (!ISSET(FTS_SEEDOT) && ISDOT(dp->d_name))
721 if ((p = fts_alloc(sp, dp->d_name, (int)_D_EXACT_NAMLEN (dp))) == NULL)
723 if (_D_EXACT_NAMLEN (dp) >= maxlen) {/* include space for NUL */
724 oldaddr = sp->fts_path;
725 if (fts_palloc(sp, _D_EXACT_NAMLEN (dp) + len + 1)) {
727 * No more memory for path or structures. Save
728 * errno, free up the current structure and the
729 * structures already allocated.
731 mem1: saved_errno = errno;
735 (void) (*sp->fts_closedir) (dirp);
736 cur->fts_info = FTS_ERR;
738 __set_errno (saved_errno);
741 /* Did realloc() change the pointer? */
742 if (oldaddr != sp->fts_path) {
744 if (ISSET(FTS_NOCHDIR))
745 cp = sp->fts_path + len;
747 maxlen = sp->fts_pathlen - len;
750 if (len + _D_EXACT_NAMLEN (dp) >= UINT16_MAX) {
752 * In an FTSENT, fts_pathlen is a uint16_t so it is
753 * possible to wraparound here. If we do, free up
754 * the current structure and the structures already
755 * allocated, then error out with ENAMETOOLONG.
759 (void) (*sp->fts_closedir) (dirp);
760 cur->fts_info = FTS_ERR;
762 __set_errno (ENAMETOOLONG);
765 p->fts_level = level;
766 p->fts_parent = sp->fts_cur;
767 p->fts_pathlen = len + _D_EXACT_NAMLEN (dp);
769 #if defined FTS_WHITEOUT && 0
770 if (dp->d_type == DT_WHT)
771 p->fts_flags |= FTS_ISW;
776 p->fts_info = FTS_NS;
777 p->fts_errno = cderrno;
779 p->fts_info = FTS_NSOK;
780 p->fts_accpath = cur->fts_accpath;
781 } else if (nlinks == 0
782 #if defined DT_DIR && defined _DIRENT_HAVE_D_TYPE
784 dp->d_type != DT_DIR && dp->d_type != DT_UNKNOWN)
788 ISSET(FTS_NOCHDIR) ? p->fts_path : p->fts_name;
789 p->fts_info = FTS_NSOK;
791 /* Build a file name for fts_stat to stat. */
792 if (ISSET(FTS_NOCHDIR)) {
793 p->fts_accpath = p->fts_path;
794 memmove(cp, p->fts_name, p->fts_namelen + 1);
796 p->fts_accpath = p->fts_name;
798 p->fts_info = fts_stat(sp, p, 0);
800 /* Decrement link count if applicable. */
801 if (nlinks > 0 && (p->fts_info == FTS_D ||
802 p->fts_info == FTS_DC || p->fts_info == FTS_DOT))
806 /* We walk in directory order so "ls -f" doesn't get upset. */
817 (void) (*sp->fts_closedir) (dirp);
820 * If realloc() changed the address of the path, adjust the
821 * addresses for the rest of the tree and the dir list.
824 fts_padjust(sp, head);
827 * If not changing directories, reset the path back to original
830 if (ISSET(FTS_NOCHDIR)) {
831 if (len == sp->fts_pathlen || nitems == 0)
833 if (cp != NULL) /* XXX can't happen */
838 * If descended after called from fts_children or after called from
839 * fts_read and nothing found, get back. At the root level we use
840 * the saved fd; if one of fts_open()'s arguments is a relative path
841 * to an empty directory, we wind up here with no other way back. If
842 * can't get back, we're done.
844 if (descend && (type == BCHILD || !nitems) &&
845 (cur->fts_level == FTS_ROOTLEVEL ?
846 FCHDIR(sp, sp->fts_rfd) :
847 fts_safe_changedir(sp, cur->fts_parent, -1, ".."))) {
848 cur->fts_info = FTS_ERR;
853 /* If didn't find anything, return NULL. */
856 cur->fts_info = FTS_DP;
860 /* Sort the entries. */
861 if (sp->fts_compar && nitems > 1)
862 head = fts_sort(sp, head, nitems);
867 fts_stat(FTS * sp, FTSENT * p, int follow)
872 struct stat *sbp, sb;
875 /* If user needs stat info, stat buffer already allocated. */
876 sbp = ISSET(FTS_NOSTAT) ? &sb : p->fts_statp;
878 #if defined FTS_WHITEOUT && 0
879 /* check for whiteout */
880 if (p->fts_flags & FTS_ISW) {
882 memset(sbp, '\0', sizeof (*sbp));
883 sbp->st_mode = S_IFWHT;
890 * If doing a logical walk, or application requested FTS_FOLLOW, do
891 * a stat(2). If that fails, check for a non-existent symlink. If
892 * fail, set the errno from the stat call.
894 if (ISSET(FTS_LOGICAL) || follow) {
895 if ((*sp->fts_stat) (p->fts_accpath, sbp)) {
897 if (!(*sp->fts_lstat) (p->fts_accpath, sbp)) {
901 p->fts_errno = saved_errno;
904 } else if ((*sp->fts_lstat) (p->fts_accpath, sbp)) {
905 p->fts_errno = errno;
906 err: memset(sbp, 0, sizeof(*sbp));
910 if (S_ISDIR(sbp->st_mode)) {
912 * Set the device/inode. Used to find cycles and check for
913 * crossing mount points. Also remember the link count, used
914 * in fts_build to limit the number of stat calls. It is
915 * understood that these fields are only referenced if fts_info
918 dev = p->fts_dev = sbp->st_dev;
919 ino = p->fts_ino = sbp->st_ino;
920 p->fts_nlink = sbp->st_nlink;
922 if (ISDOT(p->fts_name))
926 * Cycle detection is done by brute force when the directory
927 * is first encountered. If the tree gets deep enough or the
928 * number of symbolic links to directories is high enough,
929 * something faster might be worthwhile.
931 for (t = p->fts_parent;
932 t->fts_level >= FTS_ROOTLEVEL; t = t->fts_parent)
933 if (ino == t->fts_ino && dev == t->fts_dev) {
939 if (S_ISLNK(sbp->st_mode))
941 if (S_ISREG(sbp->st_mode))
943 return (FTS_DEFAULT);
947 fts_sort(FTS * sp, FTSENT * head, int nitems)
949 register FTSENT **ap, *p;
952 * Construct an array of pointers to the structures and call qsort(3).
953 * Reassemble the array in the order returned by qsort. If unable to
954 * sort for memory reasons, return the directory entries in their
955 * current order. Allocate enough space for the current needs plus
956 * 40 so don't realloc one entry at a time.
958 if (nitems > sp->fts_nitems) {
961 sp->fts_nitems = nitems + 40;
962 if ((a = realloc(sp->fts_array,
963 (size_t)(sp->fts_nitems * sizeof(*sp->fts_array)))) == NULL)
966 sp->fts_array = NULL;
972 for (ap = sp->fts_array, p = head; p != NULL; p = p->fts_link)
974 qsort((void *)sp->fts_array, nitems, sizeof(*sp->fts_array),
976 for (head = *(ap = sp->fts_array); --nitems; ++ap)
977 ap[0]->fts_link = ap[1];
978 ap[0]->fts_link = NULL;
983 fts_alloc(FTS * sp, const char * name, int namelen)
989 * The file name is a variable length array and no stat structure is
990 * necessary if the user has set the nostat bit. Allocate the FTSENT
991 * structure, the file name and the stat structure in one chunk, but
992 * be careful that the stat structure is reasonably aligned. Since the
993 * fts_name field is declared to be of size 1, the fts_name pointer is
994 * namelen + 2 before the first possible address of the stat structure.
996 len = sizeof(*p) + namelen;
997 if (!ISSET(FTS_NOSTAT))
998 len += sizeof(*p->fts_statp) + ALIGNBYTES;
999 if ((p = malloc(len)) == NULL)
1002 /* Copy the name and guarantee NUL termination. */
1003 memmove(p->fts_name, name, namelen);
1004 p->fts_name[namelen] = '\0';
1006 if (!ISSET(FTS_NOSTAT))
1007 p->fts_statp = (struct stat *)ALIGN(p->fts_name + namelen + 2);
1008 p->fts_namelen = namelen;
1009 p->fts_path = sp->fts_path;
1012 p->fts_instr = FTS_NOINSTR;
1014 p->fts_pointer = NULL;
1019 fts_lfree(FTSENT * head)
1023 /* Free a linked list of structures. */
1024 while ((p = head)) {
1025 head = head->fts_link;
1031 * Allow essentially unlimited paths; find, rm, ls should all work on any tree.
1032 * Most systems will allow creation of paths much longer than MAXPATHLEN, even
1033 * though the kernel won't resolve them. Add the size (not just what's needed)
1034 * plus 256 bytes so don't realloc the path 2 bytes at a time.
1037 fts_palloc(FTS * sp, size_t more)
1041 sp->fts_pathlen += more + 256;
1043 * Check for possible wraparound. In an FTS, fts_pathlen is
1044 * a signed int but in an FTSENT it is an unsigned short.
1045 * We limit fts_pathlen to UINT16_MAX to be safe in both cases.
1047 if (sp->fts_pathlen < 0 || sp->fts_pathlen >= UINT16_MAX) {
1050 sp->fts_path = NULL;
1052 sp->fts_path = NULL;
1053 __set_errno (ENAMETOOLONG);
1056 p = realloc(sp->fts_path, sp->fts_pathlen);
1059 sp->fts_path = NULL;
1067 * When the path is realloc'd, have to fix all of the pointers in structures
1071 fts_padjust(FTS * sp, FTSENT * head)
1074 char *addr = sp->fts_path;
1076 #define ADJUST(p) do { \
1077 if ((p)->fts_accpath != (p)->fts_name) { \
1078 (p)->fts_accpath = \
1079 (char *)addr + ((p)->fts_accpath - (p)->fts_path); \
1081 (p)->fts_path = addr; \
1083 /* Adjust the current set of children. */
1084 for (p = sp->fts_child; p != NULL; p = p->fts_link)
1087 /* Adjust the rest of the tree, including the current level. */
1088 for (p = head; p->fts_level >= FTS_ROOTLEVEL;) {
1090 p = p->fts_link ? p->fts_link : p->fts_parent;
1095 fts_maxarglen(char * const * argv)
1099 for (max = 0; *argv; ++argv)
1100 if ((len = strlen(*argv)) > max)
1106 * Change to dir specified by fd or p->fts_accpath without getting
1107 * tricked by someone changing the world out from underneath us.
1108 * Assumes p->fts_dev and p->fts_ino are filled in.
1111 fts_safe_changedir(FTS * sp, FTSENT * p, int fd, const char * path)
1113 int ret, oerrno, newfd;
1117 if (ISSET(FTS_NOCHDIR))
1119 if (fd < 0 && (newfd = __open(path, O_RDONLY, 0)) < 0)
1121 if (__fxstat64(_STAT_VER, newfd, &sb)) {
1125 if (p->fts_dev != sb.st_dev || p->fts_ino != sb.st_ino) {
1126 __set_errno (ENOENT); /* disinformation */
1130 ret = __fchdir(newfd);
1134 (void)__close(newfd);
1135 __set_errno (oerrno);