1 /* Traverse a file hierarchy.
3 Copyright (C) 2004, 2005, 2006 Free Software Foundation, Inc.
5 This program is free software; you can redistribute it and/or modify
6 it under the terms of the GNU General Public License as published by
7 the Free Software Foundation; either version 2, or (at your option)
10 This program is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 GNU General Public License for more details.
15 You should have received a copy of the GNU General Public License
16 along with this program; if not, write to the Free Software Foundation,
17 Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */
20 * Copyright (c) 1990, 1993, 1994
21 * The Regents of the University of California. All rights reserved.
23 * Redistribution and use in source and binary forms, with or without
24 * modification, are permitted provided that the following conditions
26 * 1. Redistributions of source code must retain the above copyright
27 * notice, this list of conditions and the following disclaimer.
28 * 2. Redistributions in binary form must reproduce the above copyright
29 * notice, this list of conditions and the following disclaimer in the
30 * documentation and/or other materials provided with the distribution.
31 * 4. Neither the name of the University nor the names of its contributors
32 * may be used to endorse or promote products derived from this software
33 * without specific prior written permission.
35 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
36 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
37 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
38 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
39 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
40 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
41 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
42 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
43 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
44 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
52 #if defined(LIBC_SCCS) && !defined(lint)
53 static char sccsid[] = "@(#)fts.c 8.6 (Berkeley) 8/14/94";
54 #endif /* LIBC_SCCS and not lint */
58 #if HAVE_SYS_PARAM_H || defined _LIBC
59 # include <sys/param.h>
62 # include <include/sys/stat.h>
64 # include <sys/stat.h>
78 # include "unistd--.h"
82 #ifndef _D_EXACT_NAMLEN
83 # define _D_EXACT_NAMLEN(dirent) strlen ((dirent)->d_name)
88 # define close __close
90 # define closedir __closedir
92 # define fchdir __fchdir
96 # define opendir __opendir
98 # define readdir __readdir
100 # undef internal_function
101 # define internal_function /* empty */
105 # define __set_errno(Val) errno = (Val)
108 #ifndef __attribute__
109 # if __GNUC__ < 2 || (__GNUC__ == 2 && __GNUC_MINOR__ < 8) || __STRICT_ANSI__
110 # define __attribute__(x) /* empty */
114 #ifndef ATTRIBUTE_UNUSED
115 # define ATTRIBUTE_UNUSED __attribute__ ((__unused__))
118 /* If this host provides the openat function, then we can avoid
119 attempting to open "." in some initialization code below. */
121 # define HAVE_OPENAT_SUPPORT 1
123 # define HAVE_OPENAT_SUPPORT 0
126 static FTSENT *fts_alloc (FTS *, const char *, size_t) internal_function;
127 static FTSENT *fts_build (FTS *, int) internal_function;
128 static void fts_lfree (FTSENT *) internal_function;
129 static void fts_load (FTS *, FTSENT *) internal_function;
130 static size_t fts_maxarglen (char * const *) internal_function;
131 static void fts_padjust (FTS *, FTSENT *) internal_function;
132 static bool fts_palloc (FTS *, size_t) internal_function;
133 static FTSENT *fts_sort (FTS *, FTSENT *, size_t) internal_function;
134 static unsigned short int fts_stat (FTS *, FTSENT *, bool) internal_function;
135 static int fts_safe_changedir (FTS *, FTSENT *, int, const char *)
139 static bool enter_dir (FTS *fts, FTSENT *ent) { return true; }
140 static void leave_dir (FTS *fts, FTSENT *ent) {}
141 static bool setup_dir (FTS *fts) { return true; }
142 static void free_dir (FTS *fts) {}
144 # include "fcntl--.h"
145 # include "fts-cycle.c"
149 # define MAX(a,b) ((a) > (b) ? (a) : (b))
153 # define SIZE_MAX ((size_t) -1)
157 # define O_DIRECTORY 0
160 #define ISDOT(a) (a[0] == '.' && (!a[1] || (a[1] == '.' && !a[2])))
161 #define STREQ(a, b) (strcmp ((a), (b)) == 0)
163 #define CLR(opt) (sp->fts_options &= ~(opt))
164 #define ISSET(opt) (sp->fts_options & (opt))
165 #define SET(opt) (sp->fts_options |= (opt))
167 #define RESTORE_INITIAL_CWD(sp) FCHDIR (sp, (ISSET (FTS_CWDFD) \
171 #define FCHDIR(sp, fd) (!ISSET(FTS_NOCHDIR) \
172 && (ISSET(FTS_CWDFD) \
173 ? (cwd_advance_fd (sp, fd), 0) \
177 /* fts_build flags */
178 #define BCHILD 1 /* fts_children */
179 #define BNAMES 2 /* fts_children, names only */
180 #define BREAD 3 /* fts_read */
183 # include <inttypes.h>
186 bool fts_debug = false;
187 # define Dprintf(x) do { if (fts_debug) printf x; } while (0)
192 #define LEAVE_DIR(Fts, Ent, Tag) \
195 Dprintf ((" %s-leaving: %s\n", Tag, (Ent)->fts_path)); \
196 leave_dir (Fts, Ent); \
200 /* file-descriptor-relative opendir. */
201 /* FIXME: if others need this function, move it into lib/openat.c */
204 opendirat (int fd, char const *dir)
206 int new_fd = openat (fd, dir, O_RDONLY);
211 dirp = fdopendir (new_fd);
214 int saved_errno = errno;
221 /* Virtual fchdir. Advance SP's working directory
222 file descriptor, SP->fts_cwd_fd, to FD, and close
223 the previous one, ignoring any error. */
226 cwd_advance_fd (FTS *sp, int fd)
228 int old = sp->fts_cwd_fd;
229 if (old == fd && old != AT_FDCWD)
233 close (old); /* ignore any close failure */
236 /* Open the directory DIR if possible, and return a file
237 descriptor. Return -1 and set errno on failure. It doesn't matter
238 whether the file descriptor has read or write access. */
242 diropen (FTS const *sp, char const *dir)
244 int open_flags = (O_RDONLY | O_DIRECTORY | O_NOCTTY | O_NONBLOCK
245 | (ISSET (FTS_PHYSICAL) ? O_NOFOLLOW : 0));
247 return (ISSET (FTS_CWDFD)
248 ? openat (sp->fts_cwd_fd, dir, open_flags)
249 : open (dir, open_flags));
253 fts_open (char * const *argv,
254 register int options,
255 int (*compar) (FTSENT const **, FTSENT const **))
258 register FTSENT *p, *root;
259 register size_t nitems;
260 FTSENT *parent = NULL;
261 FTSENT *tmp = NULL; /* pacify gcc */
265 if (options & ~FTS_OPTIONMASK) {
266 __set_errno (EINVAL);
269 if ((options & FTS_NOCHDIR) && (options & FTS_CWDFD)) {
270 __set_errno (EINVAL);
273 if ( ! (options & (FTS_LOGICAL | FTS_PHYSICAL))) {
274 __set_errno (EINVAL);
278 /* Allocate/initialize the stream */
279 if ((sp = malloc(sizeof(FTS))) == NULL)
281 memset(sp, 0, sizeof(FTS));
282 sp->fts_compar = compar;
283 sp->fts_options = options;
285 /* Logical walks turn on NOCHDIR; symbolic links are too hard. */
286 if (ISSET(FTS_LOGICAL)) {
291 /* Initialize fts_cwd_fd. */
292 sp->fts_cwd_fd = AT_FDCWD;
293 if ( ISSET(FTS_CWDFD) && ! HAVE_OPENAT_SUPPORT)
295 /* While it isn't technically necessary to open "." this
296 early, doing it here saves us the trouble of ensuring
297 later (where it'd be messier) that "." can in fact
298 be opened. If not, revert to FTS_NOCHDIR mode. */
299 int fd = open (".", O_RDONLY);
302 /* Even if `.' is unreadable, don't revert to FTS_NOCHDIR mode
303 on systems like Linux+PROC_FS, where our openat emulation
304 is good enough. Note: on a system that emulates
305 openat via /proc, this technique can still fail, but
306 only in extreme conditions, e.g., when the working
307 directory cannot be saved (i.e. save_cwd fails) --
308 and that happens only on Linux only when "." is unreadable
309 and the CWD would be longer than PATH_MAX.
310 FIXME: once Linux kernel openat support is well established,
311 replace the above open call and this entire if/else block
312 with the body of the if-block below. */
313 if ( openat_needs_fchdir ())
326 * Start out with 1K of file name space, and enough, in any case,
327 * to hold the user's file names.
330 # define MAXPATHLEN 1024
333 size_t maxarglen = fts_maxarglen(argv);
334 if (! fts_palloc(sp, MAX(maxarglen, MAXPATHLEN)))
338 /* Allocate/initialize root's parent. */
340 if ((parent = fts_alloc(sp, "", 0)) == NULL)
342 parent->fts_level = FTS_ROOTPARENTLEVEL;
345 /* Allocate/initialize root(s). */
346 for (root = NULL, nitems = 0; *argv != NULL; ++argv, ++nitems) {
347 /* Don't allow zero-length file names. */
348 if ((len = strlen(*argv)) == 0) {
349 __set_errno (ENOENT);
353 if ((p = fts_alloc(sp, *argv, len)) == NULL)
355 p->fts_level = FTS_ROOTLEVEL;
356 p->fts_parent = parent;
357 p->fts_accpath = p->fts_name;
358 p->fts_info = fts_stat(sp, p, ISSET(FTS_COMFOLLOW) != 0);
360 /* Command-line "." and ".." are real directories. */
361 if (p->fts_info == FTS_DOT)
365 * If comparison routine supplied, traverse in sorted
366 * order; otherwise traverse in the order specified.
381 if (compar && nitems > 1)
382 root = fts_sort(sp, root, nitems);
385 * Allocate a dummy pointer and make fts_read think that we've just
386 * finished the node before the root(s); set p->fts_info to FTS_INIT
387 * so that everything about the "current" node is ignored.
389 if ((sp->fts_cur = fts_alloc(sp, "", 0)) == NULL)
391 sp->fts_cur->fts_link = root;
392 sp->fts_cur->fts_info = FTS_INIT;
393 if (! setup_dir (sp))
397 * If using chdir(2), grab a file descriptor pointing to dot to ensure
398 * that we can get back here; this could be avoided for some file names,
399 * but almost certainly not worth the effort. Slashes, symbolic links,
400 * and ".." are all fairly nasty problems. Note, if we can't get the
401 * descriptor we run anyway, just more slowly.
403 if (!ISSET(FTS_NOCHDIR) && !ISSET(FTS_CWDFD)
404 && (sp->fts_rfd = diropen (sp, ".")) < 0)
409 mem3: fts_lfree(root);
411 mem2: free(sp->fts_path);
418 fts_load (FTS *sp, register FTSENT *p)
424 * Load the stream structure for the next traversal. Since we don't
425 * actually enter the directory until after the preorder visit, set
426 * the fts_accpath field specially so the chdir gets done to the right
427 * place and the user can access the first node. From fts_open it's
428 * known that the file name will fit.
430 len = p->fts_pathlen = p->fts_namelen;
431 memmove(sp->fts_path, p->fts_name, len + 1);
432 if ((cp = strrchr(p->fts_name, '/')) && (cp != p->fts_name || cp[1])) {
434 memmove(p->fts_name, cp, len + 1);
435 p->fts_namelen = len;
437 p->fts_accpath = p->fts_path = sp->fts_path;
438 sp->fts_dev = p->fts_statp->st_dev;
444 register FTSENT *freep, *p;
448 * This still works if we haven't read anything -- the dummy structure
449 * points to the root list, so we step through to the end of the root
450 * list which has a valid parent pointer.
453 for (p = sp->fts_cur; p->fts_level >= FTS_ROOTLEVEL;) {
455 p = p->fts_link != NULL ? p->fts_link : p->fts_parent;
461 /* Free up child linked list, sort array, file name buffer. */
463 fts_lfree(sp->fts_child);
468 if (ISSET(FTS_CWDFD))
470 if (0 <= sp->fts_cwd_fd)
471 close (sp->fts_cwd_fd);
473 else if (!ISSET(FTS_NOCHDIR))
475 /* Return to original directory, save errno if necessary. */
476 if (fchdir(sp->fts_rfd))
483 /* Free up the stream pointer. */
486 /* Set errno and return. */
488 __set_errno (saved_errno);
496 * Special case of "/" at the end of the file name so that slashes aren't
497 * appended which would cause file names to be written as "....//foo".
500 (p->fts_path[p->fts_pathlen - 1] == '/' \
501 ? p->fts_pathlen - 1 : p->fts_pathlen)
504 fts_read (register FTS *sp)
506 register FTSENT *p, *tmp;
507 register unsigned short int instr;
510 /* If finished or unrecoverable error, return NULL. */
511 if (sp->fts_cur == NULL || ISSET(FTS_STOP))
514 /* Set current node pointer. */
517 /* Save and zero out user instructions. */
518 instr = p->fts_instr;
519 p->fts_instr = FTS_NOINSTR;
521 /* Any type of file may be re-visited; re-stat and re-turn. */
522 if (instr == FTS_AGAIN) {
523 p->fts_info = fts_stat(sp, p, false);
526 Dprintf (("fts_read: p=%s\n",
527 p->fts_info == FTS_INIT ? "" : p->fts_path));
530 * Following a symlink -- SLNONE test allows application to see
531 * SLNONE and recover. If indirecting through a symlink, have
532 * keep a pointer to current location. If unable to get that
533 * pointer, follow fails.
535 if (instr == FTS_FOLLOW &&
536 (p->fts_info == FTS_SL || p->fts_info == FTS_SLNONE)) {
537 p->fts_info = fts_stat(sp, p, true);
538 if (p->fts_info == FTS_D && !ISSET(FTS_NOCHDIR)) {
539 if ((p->fts_symfd = diropen (sp, ".")) < 0) {
540 p->fts_errno = errno;
541 p->fts_info = FTS_ERR;
543 p->fts_flags |= FTS_SYMFOLLOW;
548 /* Directory in pre-order. */
549 if (p->fts_info == FTS_D) {
550 /* If skipped or crossed mount point, do post-order visit. */
551 if (instr == FTS_SKIP ||
552 (ISSET(FTS_XDEV) && p->fts_statp->st_dev != sp->fts_dev)) {
553 if (p->fts_flags & FTS_SYMFOLLOW)
554 (void)close(p->fts_symfd);
556 fts_lfree(sp->fts_child);
557 sp->fts_child = NULL;
559 p->fts_info = FTS_DP;
560 LEAVE_DIR (sp, p, "1");
564 /* Rebuild if only read the names and now traversing. */
565 if (sp->fts_child != NULL && ISSET(FTS_NAMEONLY)) {
567 fts_lfree(sp->fts_child);
568 sp->fts_child = NULL;
572 * Cd to the subdirectory.
574 * If have already read and now fail to chdir, whack the list
575 * to make the names come out right, and set the parent errno
576 * so the application will eventually get an error condition.
577 * Set the FTS_DONTCHDIR flag so that when we logically change
578 * directories back to the parent we don't do a chdir.
580 * If haven't read do so. If the read fails, fts_build sets
581 * FTS_STOP or the fts_info field of the node.
583 if (sp->fts_child != NULL) {
584 if (fts_safe_changedir(sp, p, -1, p->fts_accpath)) {
585 p->fts_errno = errno;
586 p->fts_flags |= FTS_DONTCHDIR;
587 for (p = sp->fts_child; p != NULL;
590 p->fts_parent->fts_accpath;
592 } else if ((sp->fts_child = fts_build(sp, BREAD)) == NULL) {
595 /* If fts_build's call to fts_safe_changedir failed
596 because it was not able to fchdir into a
597 subdirectory, tell the caller. */
599 p->fts_info = FTS_ERR;
600 LEAVE_DIR (sp, p, "2");
604 sp->fts_child = NULL;
608 /* Move to the next node on this level. */
610 if ((p = p->fts_link) != NULL) {
614 * If reached the top, return to the original directory (or
615 * the root of the tree), and load the file names for the next
618 if (p->fts_level == FTS_ROOTLEVEL) {
619 if (RESTORE_INITIAL_CWD(sp)) {
629 * User may have called fts_set on the node. If skipped,
630 * ignore. If followed, get a file descriptor so we can
631 * get back if necessary.
633 if (p->fts_instr == FTS_SKIP)
635 if (p->fts_instr == FTS_FOLLOW) {
636 p->fts_info = fts_stat(sp, p, true);
637 if (p->fts_info == FTS_D && !ISSET(FTS_NOCHDIR)) {
638 if ((p->fts_symfd = diropen (sp, ".")) < 0) {
639 p->fts_errno = errno;
640 p->fts_info = FTS_ERR;
642 p->fts_flags |= FTS_SYMFOLLOW;
644 p->fts_instr = FTS_NOINSTR;
647 name: t = sp->fts_path + NAPPEND(p->fts_parent);
649 memmove(t, p->fts_name, p->fts_namelen + 1);
652 if (p->fts_info == FTS_D)
654 Dprintf ((" %s-entering: %s\n", sp, p->fts_path));
655 if (! enter_dir (sp, p))
657 __set_errno (ENOMEM);
664 /* Move up to the parent node. */
668 if (p->fts_level == FTS_ROOTPARENTLEVEL) {
670 * Done; free everything up and set errno to 0 so the user
671 * can distinguish between error and EOF.
675 return (sp->fts_cur = NULL);
678 /* NUL terminate the file name. */
679 sp->fts_path[p->fts_pathlen] = '\0';
682 * Return to the parent directory. If at a root node, restore
683 * the initial working directory. If we came through a symlink,
684 * go back through the file descriptor. Otherwise, move up
685 * one level, via "..".
687 if (p->fts_level == FTS_ROOTLEVEL) {
688 if (RESTORE_INITIAL_CWD(sp)) {
689 p->fts_errno = errno;
692 } else if (p->fts_flags & FTS_SYMFOLLOW) {
693 if (FCHDIR(sp, p->fts_symfd)) {
694 int saved_errno = errno;
695 (void)close(p->fts_symfd);
696 __set_errno (saved_errno);
697 p->fts_errno = errno;
700 (void)close(p->fts_symfd);
701 } else if (!(p->fts_flags & FTS_DONTCHDIR) &&
702 fts_safe_changedir(sp, p->fts_parent, -1, "..")) {
703 p->fts_errno = errno;
706 p->fts_info = p->fts_errno ? FTS_ERR : FTS_DP;
707 if (p->fts_errno == 0)
708 LEAVE_DIR (sp, p, "3");
710 return ISSET(FTS_STOP) ? NULL : p;
714 * Fts_set takes the stream as an argument although it's not used in this
715 * implementation; it would be necessary if anyone wanted to add global
716 * semantics to fts using fts_set. An error return is allowed for similar
721 fts_set(FTS *sp ATTRIBUTE_UNUSED, FTSENT *p, int instr)
723 if (instr != 0 && instr != FTS_AGAIN && instr != FTS_FOLLOW &&
724 instr != FTS_NOINSTR && instr != FTS_SKIP) {
725 __set_errno (EINVAL);
728 p->fts_instr = instr;
733 fts_children (register FTS *sp, int instr)
738 if (instr != 0 && instr != FTS_NAMEONLY) {
739 __set_errno (EINVAL);
743 /* Set current node pointer. */
747 * Errno set to 0 so user can distinguish empty directory from
752 /* Fatal errors stop here. */
756 /* Return logical hierarchy of user's arguments. */
757 if (p->fts_info == FTS_INIT)
758 return (p->fts_link);
761 * If not a directory being visited in pre-order, stop here. Could
762 * allow FTS_DNR, assuming the user has fixed the problem, but the
763 * same effect is available with FTS_AGAIN.
765 if (p->fts_info != FTS_D /* && p->fts_info != FTS_DNR */)
768 /* Free up any previous child list. */
769 if (sp->fts_child != NULL)
770 fts_lfree(sp->fts_child);
772 if (instr == FTS_NAMEONLY) {
779 * If using chdir on a relative file name and called BEFORE fts_read
780 * does its chdir to the root of a traversal, we can lose -- we need to
781 * chdir into the subdirectory, and we don't know where the current
782 * directory is, so we can't get back so that the upcoming chdir by
783 * fts_read will work.
785 if (p->fts_level != FTS_ROOTLEVEL || p->fts_accpath[0] == '/' ||
787 return (sp->fts_child = fts_build(sp, instr));
789 if ((fd = diropen (sp, ".")) < 0)
790 return (sp->fts_child = NULL);
791 sp->fts_child = fts_build(sp, instr);
792 if (ISSET(FTS_CWDFD))
794 cwd_advance_fd (sp, fd);
800 int saved_errno = errno;
802 __set_errno (saved_errno);
807 return (sp->fts_child);
811 * This is the tricky part -- do not casually change *anything* in here. The
812 * idea is to build the linked list of entries that are used by fts_children
813 * and fts_read. There are lots of special cases.
815 * The real slowdown in walking the tree is the stat calls. If FTS_NOSTAT is
816 * set and it's a physical walk (so that symbolic links can't be directories),
817 * we can do things quickly. First, if it's a 4.4BSD file system, the type
818 * of the file is in the directory entry. Otherwise, we assume that the number
819 * of subdirectories in a node is equal to the number of links to the parent.
820 * The former skips all stat calls. The latter skips stat calls in any leaf
821 * directories and for any files after the subdirectories in the directory have
822 * been found, cutting the stat calls by about 2/3.
826 fts_build (register FTS *sp, int type)
828 register struct dirent *dp;
829 register FTSENT *p, *head;
830 register size_t nitems;
840 size_t len, maxlen, new_len;
843 /* Set current node pointer. */
847 * Open the directory for reading. If this fails, we're done.
848 * If being called from fts_read, set the fts_info field.
850 #if defined FTS_WHITEOUT && 0
851 if (ISSET(FTS_WHITEOUT))
852 oflag = DTF_NODUP|DTF_REWIND;
854 oflag = DTF_HIDEW|DTF_NODUP|DTF_REWIND;
856 # define __opendir2(file, flag) \
857 ( ! ISSET(FTS_NOCHDIR) && ISSET(FTS_CWDFD) \
858 ? opendirat(sp->fts_cwd_fd, file) \
861 if ((dirp = __opendir2(cur->fts_accpath, oflag)) == NULL) {
863 cur->fts_info = FTS_DNR;
864 cur->fts_errno = errno;
870 * Nlinks is the number of possible entries of type directory in the
871 * directory if we're cheating on stat calls, 0 if we're not doing
872 * any stat calls at all, (nlink_t) -1 if we're statting everything.
874 if (type == BNAMES) {
876 /* Be quiet about nostat, GCC. */
878 } else if (ISSET(FTS_NOSTAT) && ISSET(FTS_PHYSICAL)) {
879 nlinks = (cur->fts_statp->st_nlink
880 - (ISSET(FTS_SEEDOT) ? 0 : 2));
888 * If we're going to need to stat anything or we want to descend
889 * and stay in the directory, chdir. If this fails we keep going,
890 * but set a flag so we don't chdir after the post-order visit.
891 * We won't be able to stat anything, but we can still return the
892 * names themselves. Note, that since fts_read won't be able to
893 * chdir into the directory, it will have to return different file
894 * names than before, i.e. "a/b" instead of "b". Since the node
895 * has already been visited in pre-order, have to wait until the
896 * post-order visit to return the error. There is a special case
897 * here, if there was nothing to stat then it's not an error to
898 * not be able to stat. This is all fairly nasty. If a program
899 * needed sorted entries or stat information, they had better be
900 * checking FTS_NS on the returned nodes.
902 if (nlinks || type == BREAD) {
903 int dir_fd = dirfd(dirp);
904 if (ISSET(FTS_CWDFD) && 0 <= dir_fd)
905 dir_fd = dup (dir_fd);
906 if (dir_fd < 0 || fts_safe_changedir(sp, cur, dir_fd, NULL)) {
907 if (nlinks && type == BREAD)
908 cur->fts_errno = errno;
909 cur->fts_flags |= FTS_DONTCHDIR;
912 if (ISSET(FTS_CWDFD) && 0 <= dir_fd)
921 * Figure out the max file name length that can be stored in the
922 * current buffer -- the inner loop allocates more space as necessary.
923 * We really wouldn't have to do the maxlen calculations here, we
924 * could do them in fts_read before returning the name, but it's a
925 * lot easier here since the length is part of the dirent structure.
927 * If not changing directories set a pointer so that can just append
928 * each new component into the file name.
931 if (ISSET(FTS_NOCHDIR)) {
932 cp = sp->fts_path + len;
935 /* GCC, you're too verbose. */
939 maxlen = sp->fts_pathlen - len;
941 level = cur->fts_level + 1;
943 /* Read the directory, attaching each entry to the `link' pointer. */
945 for (head = tail = NULL, nitems = 0; dirp && (dp = readdir(dirp));) {
946 if (!ISSET(FTS_SEEDOT) && ISDOT(dp->d_name))
949 if ((p = fts_alloc (sp, dp->d_name,
950 _D_EXACT_NAMLEN (dp))) == NULL)
952 if (_D_EXACT_NAMLEN (dp) >= maxlen) {
953 /* include space for NUL */
954 oldaddr = sp->fts_path;
955 if (! fts_palloc(sp, _D_EXACT_NAMLEN (dp) + len + 1)) {
957 * No more memory. Save
958 * errno, free up the current structure and the
959 * structures already allocated.
961 mem1: saved_errno = errno;
966 cur->fts_info = FTS_ERR;
968 __set_errno (saved_errno);
971 /* Did realloc() change the pointer? */
972 if (oldaddr != sp->fts_path) {
974 if (ISSET(FTS_NOCHDIR))
975 cp = sp->fts_path + len;
977 maxlen = sp->fts_pathlen - len;
980 new_len = len + _D_EXACT_NAMLEN (dp);
983 * In the unlikely even that we would end up
984 * with a file name longer than SIZE_MAX, free up
985 * the current structure and the structures already
986 * allocated, then error out with ENAMETOOLONG.
991 cur->fts_info = FTS_ERR;
993 __set_errno (ENAMETOOLONG);
996 p->fts_level = level;
997 p->fts_parent = sp->fts_cur;
998 p->fts_pathlen = new_len;
1000 #if defined FTS_WHITEOUT && 0
1001 if (dp->d_type == DT_WHT)
1002 p->fts_flags |= FTS_ISW;
1005 /* Build a file name for fts_stat to stat. */
1006 if (ISSET(FTS_NOCHDIR)) {
1007 p->fts_accpath = p->fts_path;
1008 memmove(cp, p->fts_name, p->fts_namelen + 1);
1010 p->fts_accpath = p->fts_name;
1012 p->fts_info = fts_stat(sp, p, false);
1014 /* Decrement link count if applicable. */
1015 if (nlinks > 0 && (p->fts_info == FTS_D ||
1016 p->fts_info == FTS_DC || p->fts_info == FTS_DOT))
1019 /* We walk in directory order so "ls -f" doesn't get upset. */
1033 * If realloc() changed the address of the file name, adjust the
1034 * addresses for the rest of the tree and the dir list.
1037 fts_padjust(sp, head);
1040 * If not changing directories, reset the file name back to original
1043 if (ISSET(FTS_NOCHDIR)) {
1044 if (len == sp->fts_pathlen || nitems == 0)
1050 * If descended after called from fts_children or after called from
1051 * fts_read and nothing found, get back. At the root level we use
1052 * the saved fd; if one of fts_open()'s arguments is a relative name
1053 * to an empty directory, we wind up here with no other way back. If
1054 * can't get back, we're done.
1056 if (descend && (type == BCHILD || !nitems) &&
1057 (cur->fts_level == FTS_ROOTLEVEL
1058 ? RESTORE_INITIAL_CWD(sp)
1059 : fts_safe_changedir(sp, cur->fts_parent, -1, ".."))) {
1060 cur->fts_info = FTS_ERR;
1066 /* If didn't find anything, return NULL. */
1069 cur->fts_info = FTS_DP;
1074 /* Sort the entries. */
1075 if (sp->fts_compar && nitems > 1)
1076 head = fts_sort(sp, head, nitems);
1082 /* Walk ->fts_parent links starting at E_CURR, until the root of the
1083 current hierarchy. There should be a directory with dev/inode
1084 matching those of AD. If not, print a lot of diagnostics. */
1086 find_matching_ancestor (FTSENT const *e_curr, struct Active_dir const *ad)
1089 for (ent = e_curr; ent->fts_level >= FTS_ROOTLEVEL; ent = ent->fts_parent)
1091 if (ad->ino == ent->fts_statp->st_ino
1092 && ad->dev == ent->fts_statp->st_dev)
1095 printf ("ERROR: tree dir, %s, not active\n", ad->fts_ent->fts_accpath);
1096 printf ("active dirs:\n");
1098 ent->fts_level >= FTS_ROOTLEVEL; ent = ent->fts_parent)
1099 printf (" %s(%"PRIuMAX"/%"PRIuMAX") to %s(%"PRIuMAX"/%"PRIuMAX")...\n",
1100 ad->fts_ent->fts_accpath,
1101 (uintmax_t) ad->dev,
1102 (uintmax_t) ad->ino,
1104 (uintmax_t) ent->fts_statp->st_dev,
1105 (uintmax_t) ent->fts_statp->st_ino);
1109 fts_cross_check (FTS const *sp)
1111 FTSENT const *ent = sp->fts_cur;
1113 if ( ! ISSET (FTS_TIGHT_CYCLE_CHECK))
1116 Dprintf (("fts-cross-check cur=%s\n", ent->fts_path));
1117 /* Make sure every parent dir is in the tree. */
1118 for (t = ent->fts_parent; t->fts_level >= FTS_ROOTLEVEL; t = t->fts_parent)
1120 struct Active_dir ad;
1121 ad.ino = t->fts_statp->st_ino;
1122 ad.dev = t->fts_statp->st_dev;
1123 if ( ! hash_lookup (sp->fts_cycle.ht, &ad))
1124 printf ("ERROR: active dir, %s, not in tree\n", t->fts_path);
1127 /* Make sure every dir in the tree is an active dir.
1128 But ENT is not necessarily a directory. If so, just skip this part. */
1129 if (ent->fts_parent->fts_level >= FTS_ROOTLEVEL
1130 && (ent->fts_info == FTS_DP
1131 || ent->fts_info == FTS_D))
1133 struct Active_dir *ad;
1134 for (ad = hash_get_first (sp->fts_cycle.ht); ad != NULL;
1135 ad = hash_get_next (sp->fts_cycle.ht, ad))
1137 find_matching_ancestor (ent, ad);
1143 static unsigned short int
1145 fts_stat(FTS *sp, register FTSENT *p, bool follow)
1147 struct stat *sbp = p->fts_statp;
1150 #if defined FTS_WHITEOUT && 0
1151 /* check for whiteout */
1152 if (p->fts_flags & FTS_ISW) {
1153 memset(sbp, '\0', sizeof (*sbp));
1154 sbp->st_mode = S_IFWHT;
1160 * If doing a logical walk, or application requested FTS_FOLLOW, do
1161 * a stat(2). If that fails, check for a non-existent symlink. If
1162 * fail, set the errno from the stat call.
1164 if (ISSET(FTS_LOGICAL) || follow) {
1165 if (stat(p->fts_accpath, sbp)) {
1166 saved_errno = errno;
1168 && lstat(p->fts_accpath, sbp) == 0) {
1170 return (FTS_SLNONE);
1172 p->fts_errno = saved_errno;
1175 } else if (fstatat(sp->fts_cwd_fd, p->fts_accpath, sbp,
1176 AT_SYMLINK_NOFOLLOW)) {
1177 p->fts_errno = errno;
1178 err: memset(sbp, 0, sizeof(struct stat));
1182 if (S_ISDIR(sbp->st_mode)) {
1183 if (ISDOT(p->fts_name))
1189 * Cycle detection is done by brute force when the directory
1190 * is first encountered. If the tree gets deep enough or the
1191 * number of symbolic links to directories is high enough,
1192 * something faster might be worthwhile.
1196 for (t = p->fts_parent;
1197 t->fts_level >= FTS_ROOTLEVEL; t = t->fts_parent)
1198 if (sbp->st_ino == t->fts_statp->st_ino
1199 && sbp->st_dev == t->fts_statp->st_dev)
1209 if (S_ISLNK(sbp->st_mode))
1211 if (S_ISREG(sbp->st_mode))
1213 return (FTS_DEFAULT);
1217 fts_compar (void const *a, void const *b)
1219 /* Convert A and B to the correct types, to pacify the compiler, and
1220 for portability to bizarre hosts where "void const *" and "FTSENT
1221 const **" differ in runtime representation. The comparison
1222 function cannot modify *a and *b, but there is no compile-time
1224 FTSENT const **pa = (FTSENT const **) a;
1225 FTSENT const **pb = (FTSENT const **) b;
1226 return pa[0]->fts_fts->fts_compar (pa, pb);
1231 fts_sort (FTS *sp, FTSENT *head, register size_t nitems)
1233 register FTSENT **ap, *p;
1235 /* On most modern hosts, void * and FTSENT ** have the same
1236 run-time representation, and one can convert sp->fts_compar to
1237 the type qsort expects without problem. Use the heuristic that
1238 this is OK if the two pointer types are the same size, and if
1239 converting FTSENT ** to long int is the same as converting
1240 FTSENT ** to void * and then to long int. This heuristic isn't
1241 valid in general but we don't know of any counterexamples. */
1243 int (*compare) (void const *, void const *) =
1244 ((sizeof &dummy == sizeof (void *)
1245 && (long int) &dummy == (long int) (void *) &dummy)
1246 ? (int (*) (void const *, void const *)) sp->fts_compar
1250 * Construct an array of pointers to the structures and call qsort(3).
1251 * Reassemble the array in the order returned by qsort. If unable to
1252 * sort for memory reasons, return the directory entries in their
1253 * current order. Allocate enough space for the current needs plus
1254 * 40 so don't realloc one entry at a time.
1256 if (nitems > sp->fts_nitems) {
1259 sp->fts_nitems = nitems + 40;
1260 if (SIZE_MAX / sizeof *a < sp->fts_nitems
1261 || ! (a = realloc (sp->fts_array,
1262 sp->fts_nitems * sizeof *a))) {
1263 free(sp->fts_array);
1264 sp->fts_array = NULL;
1270 for (ap = sp->fts_array, p = head; p; p = p->fts_link)
1272 qsort((void *)sp->fts_array, nitems, sizeof(FTSENT *), compare);
1273 for (head = *(ap = sp->fts_array); --nitems; ++ap)
1274 ap[0]->fts_link = ap[1];
1275 ap[0]->fts_link = NULL;
1281 fts_alloc (FTS *sp, const char *name, register size_t namelen)
1287 * The file name is a variable length array. Allocate the FTSENT
1288 * structure and the file name in one chunk.
1290 len = sizeof(FTSENT) + namelen;
1291 if ((p = malloc(len)) == NULL)
1294 /* Copy the name and guarantee NUL termination. */
1295 memmove(p->fts_name, name, namelen);
1296 p->fts_name[namelen] = '\0';
1298 p->fts_namelen = namelen;
1300 p->fts_path = sp->fts_path;
1303 p->fts_instr = FTS_NOINSTR;
1305 p->fts_pointer = NULL;
1311 fts_lfree (register FTSENT *head)
1315 /* Free a linked list of structures. */
1316 while ((p = head)) {
1317 head = head->fts_link;
1323 * Allow essentially unlimited file name lengths; find, rm, ls should
1324 * all work on any tree. Most systems will allow creation of file
1325 * names much longer than MAXPATHLEN, even though the kernel won't
1326 * resolve them. Add the size (not just what's needed) plus 256 bytes
1327 * so don't realloc the file name 2 bytes at a time.
1331 fts_palloc (FTS *sp, size_t more)
1334 size_t new_len = sp->fts_pathlen + more + 256;
1337 * See if fts_pathlen would overflow.
1339 if (new_len < sp->fts_pathlen) {
1342 sp->fts_path = NULL;
1344 sp->fts_path = NULL;
1345 __set_errno (ENAMETOOLONG);
1348 sp->fts_pathlen = new_len;
1349 p = realloc(sp->fts_path, sp->fts_pathlen);
1352 sp->fts_path = NULL;
1360 * When the file name is realloc'd, have to fix all of the pointers in
1361 * structures already returned.
1365 fts_padjust (FTS *sp, FTSENT *head)
1368 char *addr = sp->fts_path;
1370 #define ADJUST(p) do { \
1371 if ((p)->fts_accpath != (p)->fts_name) { \
1372 (p)->fts_accpath = \
1373 (char *)addr + ((p)->fts_accpath - (p)->fts_path); \
1375 (p)->fts_path = addr; \
1377 /* Adjust the current set of children. */
1378 for (p = sp->fts_child; p; p = p->fts_link)
1381 /* Adjust the rest of the tree, including the current level. */
1382 for (p = head; p->fts_level >= FTS_ROOTLEVEL;) {
1384 p = p->fts_link ? p->fts_link : p->fts_parent;
1390 fts_maxarglen (char * const *argv)
1394 for (max = 0; *argv; ++argv)
1395 if ((len = strlen(*argv)) > max)
1401 * Change to dir specified by fd or file name without getting
1402 * tricked by someone changing the world out from underneath us.
1403 * Assumes p->fts_statp->st_dev and p->fts_statp->st_ino are filled in.
1404 * If FD is non-negative, expect it to be used after this function returns,
1405 * and to be closed eventually. So don't pass e.g., `dirfd(dirp)' and then
1406 * do closedir(dirp), because that would invalidate the saved FD.
1407 * Upon failure, close FD immediately and return nonzero.
1411 fts_safe_changedir (FTS *sp, FTSENT *p, int fd, char const *dir)
1416 if (ISSET(FTS_NOCHDIR)) {
1417 if (ISSET(FTS_CWDFD) && 0 <= fd)
1421 if (fd < 0 && (newfd = diropen (sp, dir)) < 0)
1424 /* The following dev/inode check is necessary if we're doing
1425 a `logical' traversal (through symlinks, a la chown -L),
1426 if the system lacks O_NOFOLLOW support, or if we're changing
1427 to "..". In the latter case, O_NOFOLLOW can't help. In
1428 general (when the target is not ".."), diropen's use of
1429 O_NOFOLLOW ensures we don't mistakenly follow a symlink,
1430 so we can avoid the expense of this fstat. */
1431 if (ISSET(FTS_LOGICAL) || O_NOFOLLOW == 0
1432 || (dir && STREQ (dir, "..")))
1435 if (fstat(newfd, &sb))
1440 if (p->fts_statp->st_dev != sb.st_dev
1441 || p->fts_statp->st_ino != sb.st_ino)
1443 __set_errno (ENOENT); /* disinformation */
1449 if (ISSET(FTS_CWDFD))
1451 cwd_advance_fd (sp, newfd);
1455 ret = fchdir(newfd);
1461 __set_errno (oerrno);