Home | History | Annotate | Line # | Download | only in gen
fts.c revision 1.11.2.1
      1 /*-
      2  * Copyright (c) 1990, 1993, 1994
      3  *	The Regents of the University of California.  All rights reserved.
      4  *
      5  * Redistribution and use in source and binary forms, with or without
      6  * modification, are permitted provided that the following conditions
      7  * are met:
      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  * 3. All advertising materials mentioning features or use of this software
     14  *    must display the following acknowledgement:
     15  *	This product includes software developed by the University of
     16  *	California, Berkeley and its contributors.
     17  * 4. Neither the name of the University nor the names of its contributors
     18  *    may be used to endorse or promote products derived from this software
     19  *    without specific prior written permission.
     20  *
     21  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
     22  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
     23  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
     24  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
     25  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
     26  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
     27  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
     28  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
     29  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
     30  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
     31  * SUCH DAMAGE.
     32  */
     33 
     34 #if defined(LIBC_SCCS) && !defined(lint)
     35 /* from: static char sccsid[] = "@(#)fts.c	8.6 (Berkeley) 8/14/94"; */
     36 static char *rcsid = "$Id: fts.c,v 1.11.2.1 1995/05/02 19:34:44 jtc Exp $";
     37 #endif /* LIBC_SCCS and not lint */
     38 
     39 #include "namespace.h"
     40 #include <sys/param.h>
     41 #include <sys/stat.h>
     42 
     43 #include <dirent.h>
     44 #include <errno.h>
     45 #include <fcntl.h>
     46 #include <fts.h>
     47 #include <stdlib.h>
     48 #include <string.h>
     49 #include <unistd.h>
     50 
     51 static FTSENT	*fts_alloc __P((FTS *, char *, int));
     52 static FTSENT	*fts_build __P((FTS *, int));
     53 static void	 fts_lfree __P((FTSENT *));
     54 static void	 fts_load __P((FTS *, FTSENT *));
     55 static size_t	 fts_maxarglen __P((char * const *));
     56 static void	 fts_padjust __P((FTS *, void *));
     57 static int	 fts_palloc __P((FTS *, size_t));
     58 static FTSENT	*fts_sort __P((FTS *, FTSENT *, int));
     59 static u_short	 fts_stat __P((FTS *, FTSENT *, int));
     60 
     61 #define	ISDOT(a)	(a[0] == '.' && (!a[1] || a[1] == '.' && !a[2]))
     62 
     63 #define	CLR(opt)	(sp->fts_options &= ~(opt))
     64 #define	ISSET(opt)	(sp->fts_options & (opt))
     65 #define	SET(opt)	(sp->fts_options |= (opt))
     66 
     67 #define	CHDIR(sp, path)	(!ISSET(FTS_NOCHDIR) && chdir(path))
     68 #define	FCHDIR(sp, fd)	(!ISSET(FTS_NOCHDIR) && fchdir(fd))
     69 
     70 /* fts_build flags */
     71 #define	BCHILD		1		/* fts_children */
     72 #define	BNAMES		2		/* fts_children, names only */
     73 #define	BREAD		3		/* fts_read */
     74 
     75 FTS *
     76 fts_open(argv, options, compar)
     77 	char * const *argv;
     78 	register int options;
     79 	int (*compar)();
     80 {
     81 	register FTS *sp;
     82 	register FTSENT *p, *root;
     83 	register int nitems;
     84 	FTSENT *parent, *tmp;
     85 	int len;
     86 
     87 	/* Options check. */
     88 	if (options & ~FTS_OPTIONMASK) {
     89 		errno = EINVAL;
     90 		return (NULL);
     91 	}
     92 
     93 	/* Allocate/initialize the stream */
     94 	if ((sp = malloc((u_int)sizeof(FTS))) == NULL)
     95 		return (NULL);
     96 	memset(sp, 0, sizeof(FTS));
     97 	sp->fts_compar = compar;
     98 	sp->fts_options = options;
     99 
    100 	/* Logical walks turn on NOCHDIR; symbolic links are too hard. */
    101 	if (ISSET(FTS_LOGICAL))
    102 		SET(FTS_NOCHDIR);
    103 
    104 	/*
    105 	 * Start out with 1K of path space, and enough, in any case,
    106 	 * to hold the user's paths.
    107 	 */
    108 	if (fts_palloc(sp, MAX(fts_maxarglen(argv), MAXPATHLEN)))
    109 		goto mem1;
    110 
    111 	/* Allocate/initialize root's parent. */
    112 	if ((parent = fts_alloc(sp, "", 0)) == NULL)
    113 		goto mem2;
    114 	parent->fts_level = FTS_ROOTPARENTLEVEL;
    115 
    116 	/* Allocate/initialize root(s). */
    117 	for (root = NULL, nitems = 0; *argv; ++argv, ++nitems) {
    118 		/* Don't allow zero-length paths. */
    119 		if ((len = strlen(*argv)) == 0) {
    120 			errno = ENOENT;
    121 			goto mem3;
    122 		}
    123 
    124 		p = fts_alloc(sp, *argv, len);
    125 		p->fts_level = FTS_ROOTLEVEL;
    126 		p->fts_parent = parent;
    127 		p->fts_accpath = p->fts_name;
    128 		p->fts_info = fts_stat(sp, p, ISSET(FTS_COMFOLLOW));
    129 
    130 		/* Command-line "." and ".." are real directories. */
    131 		if (p->fts_info == FTS_DOT)
    132 			p->fts_info = FTS_D;
    133 
    134 		/*
    135 		 * If comparison routine supplied, traverse in sorted
    136 		 * order; otherwise traverse in the order specified.
    137 		 */
    138 		if (compar) {
    139 			p->fts_link = root;
    140 			root = p;
    141 		} else {
    142 			p->fts_link = NULL;
    143 			if (root == NULL)
    144 				tmp = root = p;
    145 			else {
    146 				tmp->fts_link = p;
    147 				tmp = p;
    148 			}
    149 		}
    150 	}
    151 	if (compar && nitems > 1)
    152 		root = fts_sort(sp, root, nitems);
    153 
    154 	/*
    155 	 * Allocate a dummy pointer and make fts_read think that we've just
    156 	 * finished the node before the root(s); set p->fts_info to FTS_INIT
    157 	 * so that everything about the "current" node is ignored.
    158 	 */
    159 	if ((sp->fts_cur = fts_alloc(sp, "", 0)) == NULL)
    160 		goto mem3;
    161 	sp->fts_cur->fts_link = root;
    162 	sp->fts_cur->fts_info = FTS_INIT;
    163 
    164 	/*
    165 	 * If using chdir(2), grab a file descriptor pointing to dot to insure
    166 	 * that we can get back here; this could be avoided for some paths,
    167 	 * but almost certainly not worth the effort.  Slashes, symbolic links,
    168 	 * and ".." are all fairly nasty problems.  Note, if we can't get the
    169 	 * descriptor we run anyway, just more slowly.
    170 	 */
    171 	if (!ISSET(FTS_NOCHDIR) && (sp->fts_rfd = open(".", O_RDONLY, 0)) < 0)
    172 		SET(FTS_NOCHDIR);
    173 
    174 	return (sp);
    175 
    176 mem3:	fts_lfree(root);
    177 	free(parent);
    178 mem2:	free(sp->fts_path);
    179 mem1:	free(sp);
    180 	return (NULL);
    181 }
    182 
    183 static void
    184 fts_load(sp, p)
    185 	FTS *sp;
    186 	register FTSENT *p;
    187 {
    188 	register int len;
    189 	register char *cp;
    190 
    191 	/*
    192 	 * Load the stream structure for the next traversal.  Since we don't
    193 	 * actually enter the directory until after the preorder visit, set
    194 	 * the fts_accpath field specially so the chdir gets done to the right
    195 	 * place and the user can access the first node.  From fts_open it's
    196 	 * known that the path will fit.
    197 	 */
    198 	len = p->fts_pathlen = p->fts_namelen;
    199 	memmove(sp->fts_path, p->fts_name, len + 1);
    200 	if ((cp = strrchr(p->fts_name, '/')) && (cp != p->fts_name || cp[1])) {
    201 		len = strlen(++cp);
    202 		memmove(p->fts_name, cp, len + 1);
    203 		p->fts_namelen = len;
    204 	}
    205 	p->fts_accpath = p->fts_path = sp->fts_path;
    206 	sp->fts_dev = p->fts_dev;
    207 }
    208 
    209 int
    210 fts_close(sp)
    211 	FTS *sp;
    212 {
    213 	register FTSENT *freep, *p;
    214 	int saved_errno;
    215 
    216 	/*
    217 	 * This still works if we haven't read anything -- the dummy structure
    218 	 * points to the root list, so we step through to the end of the root
    219 	 * list which has a valid parent pointer.
    220 	 */
    221 	if (sp->fts_cur) {
    222 		for (p = sp->fts_cur; p->fts_level >= FTS_ROOTLEVEL;) {
    223 			freep = p;
    224 			p = p->fts_link ? p->fts_link : p->fts_parent;
    225 			free(freep);
    226 		}
    227 		free(p);
    228 	}
    229 
    230 	/* Free up child linked list, sort array, path buffer. */
    231 	if (sp->fts_child)
    232 		fts_lfree(sp->fts_child);
    233 	if (sp->fts_array)
    234 		free(sp->fts_array);
    235 	free(sp->fts_path);
    236 
    237 	/* Return to original directory, save errno if necessary. */
    238 	if (!ISSET(FTS_NOCHDIR)) {
    239 		saved_errno = fchdir(sp->fts_rfd) ? errno : 0;
    240 		(void)close(sp->fts_rfd);
    241 	}
    242 
    243 	/* Free up the stream pointer. */
    244 	free(sp);
    245 
    246 	/* Set errno and return. */
    247 	if (!ISSET(FTS_NOCHDIR) && saved_errno) {
    248 		errno = saved_errno;
    249 		return (-1);
    250 	}
    251 	return (0);
    252 }
    253 
    254 /*
    255  * Special case a root of "/" so that slashes aren't appended which would
    256  * cause paths to be written as "//foo".
    257  */
    258 #define	NAPPEND(p)							\
    259 	(p->fts_level == FTS_ROOTLEVEL && p->fts_pathlen == 1 &&	\
    260 	    p->fts_path[0] == '/' ? 0 : p->fts_pathlen)
    261 
    262 FTSENT *
    263 fts_read(sp)
    264 	register FTS *sp;
    265 {
    266 	register FTSENT *p, *tmp;
    267 	register int instr;
    268 	register char *t;
    269 	int saved_errno;
    270 
    271 	/* If finished or unrecoverable error, return NULL. */
    272 	if (sp->fts_cur == NULL || ISSET(FTS_STOP))
    273 		return (NULL);
    274 
    275 	/* Set current node pointer. */
    276 	p = sp->fts_cur;
    277 
    278 	/* Save and zero out user instructions. */
    279 	instr = p->fts_instr;
    280 	p->fts_instr = FTS_NOINSTR;
    281 
    282 	/* Any type of file may be re-visited; re-stat and re-turn. */
    283 	if (instr == FTS_AGAIN) {
    284 		p->fts_info = fts_stat(sp, p, 0);
    285 		return (p);
    286 	}
    287 
    288 	/*
    289 	 * Following a symlink -- SLNONE test allows application to see
    290 	 * SLNONE and recover.  If indirecting through a symlink, have
    291 	 * keep a pointer to current location.  If unable to get that
    292 	 * pointer, follow fails.
    293 	 */
    294 	if (instr == FTS_FOLLOW &&
    295 	    (p->fts_info == FTS_SL || p->fts_info == FTS_SLNONE)) {
    296 		p->fts_info = fts_stat(sp, p, 1);
    297 		if (p->fts_info == FTS_D && !ISSET(FTS_NOCHDIR))
    298 			if ((p->fts_symfd = open(".", O_RDONLY, 0)) < 0) {
    299 				p->fts_errno = errno;
    300 				p->fts_info = FTS_ERR;
    301 			} else
    302 				p->fts_flags |= FTS_SYMFOLLOW;
    303 		return (p);
    304 	}
    305 
    306 	/* Directory in pre-order. */
    307 	if (p->fts_info == FTS_D) {
    308 		/* If skipped or crossed mount point, do post-order visit. */
    309 		if (instr == FTS_SKIP ||
    310 		    ISSET(FTS_XDEV) && p->fts_dev != sp->fts_dev) {
    311 			if (p->fts_flags & FTS_SYMFOLLOW)
    312 				(void)close(p->fts_symfd);
    313 			if (sp->fts_child) {
    314 				fts_lfree(sp->fts_child);
    315 				sp->fts_child = NULL;
    316 			}
    317 			p->fts_info = FTS_DP;
    318 			return (p);
    319 		}
    320 
    321 		/* Rebuild if only read the names and now traversing. */
    322 		if (sp->fts_child && ISSET(FTS_NAMEONLY)) {
    323 			CLR(FTS_NAMEONLY);
    324 			fts_lfree(sp->fts_child);
    325 			sp->fts_child = NULL;
    326 		}
    327 
    328 		/*
    329 		 * Cd to the subdirectory.
    330 		 *
    331 		 * If have already read and now fail to chdir, whack the list
    332 		 * to make the names come out right, and set the parent errno
    333 		 * so the application will eventually get an error condition.
    334 		 * Set the FTS_DONTCHDIR flag so that when we logically change
    335 		 * directories back to the parent we don't do a chdir.
    336 		 *
    337 		 * If haven't read do so.  If the read fails, fts_build sets
    338 		 * FTS_STOP or the fts_info field of the node.
    339 		 */
    340 		if (sp->fts_child) {
    341 			if (CHDIR(sp, p->fts_accpath)) {
    342 				p->fts_errno = errno;
    343 				p->fts_flags |= FTS_DONTCHDIR;
    344 				for (p = sp->fts_child; p; p = p->fts_link)
    345 					p->fts_accpath =
    346 					    p->fts_parent->fts_accpath;
    347 			}
    348 		} else if ((sp->fts_child = fts_build(sp, BREAD)) == NULL) {
    349 			if (ISSET(FTS_STOP))
    350 				return (NULL);
    351 			return (p);
    352 		}
    353 		p = sp->fts_child;
    354 		sp->fts_child = NULL;
    355 		goto name;
    356 	}
    357 
    358 	/* Move to the next node on this level. */
    359 next:	tmp = p;
    360 	if (p = p->fts_link) {
    361 		free(tmp);
    362 
    363 		/*
    364 		 * If reached the top, return to the original directory, and
    365 		 * load the paths for the next root.
    366 		 */
    367 		if (p->fts_level == FTS_ROOTLEVEL) {
    368 			if (!ISSET(FTS_NOCHDIR) && FCHDIR(sp, sp->fts_rfd)) {
    369 				SET(FTS_STOP);
    370 				return (NULL);
    371 			}
    372 			fts_load(sp, p);
    373 			return (sp->fts_cur = p);
    374 		}
    375 
    376 		/*
    377 		 * User may have called fts_set on the node.  If skipped,
    378 		 * ignore.  If followed, get a file descriptor so we can
    379 		 * get back if necessary.
    380 		 */
    381 		if (p->fts_instr == FTS_SKIP)
    382 			goto next;
    383 		if (p->fts_instr == FTS_FOLLOW) {
    384 			p->fts_info = fts_stat(sp, p, 1);
    385 			if (p->fts_info == FTS_D && !ISSET(FTS_NOCHDIR))
    386 				if ((p->fts_symfd =
    387 				    open(".", O_RDONLY, 0)) < 0) {
    388 					p->fts_errno = errno;
    389 					p->fts_info = FTS_ERR;
    390 				} else
    391 					p->fts_flags |= FTS_SYMFOLLOW;
    392 			p->fts_instr = FTS_NOINSTR;
    393 		}
    394 
    395 name:		t = sp->fts_path + NAPPEND(p->fts_parent);
    396 		*t++ = '/';
    397 		memmove(t, p->fts_name, p->fts_namelen + 1);
    398 		return (sp->fts_cur = p);
    399 	}
    400 
    401 	/* Move up to the parent node. */
    402 	p = tmp->fts_parent;
    403 	free(tmp);
    404 
    405 	if (p->fts_level == FTS_ROOTPARENTLEVEL) {
    406 		/*
    407 		 * Done; free everything up and set errno to 0 so the user
    408 		 * can distinguish between error and EOF.
    409 		 */
    410 		free(p);
    411 		errno = 0;
    412 		return (sp->fts_cur = NULL);
    413 	}
    414 
    415 	/* Nul terminate the pathname. */
    416 	sp->fts_path[p->fts_pathlen] = '\0';
    417 
    418 	/*
    419 	 * Return to the parent directory.  If at a root node or came through
    420 	 * a symlink, go back through the file descriptor.  Otherwise, cd up
    421 	 * one directory.
    422 	 */
    423 	if (p->fts_level == FTS_ROOTLEVEL) {
    424 		if (!ISSET(FTS_NOCHDIR) && FCHDIR(sp, sp->fts_rfd)) {
    425 			SET(FTS_STOP);
    426 			return (NULL);
    427 		}
    428 	} else if (p->fts_flags & FTS_SYMFOLLOW) {
    429 		if (FCHDIR(sp, p->fts_symfd)) {
    430 			saved_errno = errno;
    431 			(void)close(p->fts_symfd);
    432 			errno = saved_errno;
    433 			SET(FTS_STOP);
    434 			return (NULL);
    435 		}
    436 		(void)close(p->fts_symfd);
    437 	} else if (!(p->fts_flags & FTS_DONTCHDIR)) {
    438 		if (CHDIR(sp, "..")) {
    439 			SET(FTS_STOP);
    440 			return (NULL);
    441 		}
    442 	}
    443 	p->fts_info = p->fts_errno ? FTS_ERR : FTS_DP;
    444 	return (sp->fts_cur = p);
    445 }
    446 
    447 /*
    448  * Fts_set takes the stream as an argument although it's not used in this
    449  * implementation; it would be necessary if anyone wanted to add global
    450  * semantics to fts using fts_set.  An error return is allowed for similar
    451  * reasons.
    452  */
    453 /* ARGSUSED */
    454 int
    455 fts_set(sp, p, instr)
    456 	FTS *sp;
    457 	FTSENT *p;
    458 	int instr;
    459 {
    460 	if (instr && instr != FTS_AGAIN && instr != FTS_FOLLOW &&
    461 	    instr != FTS_NOINSTR && instr != FTS_SKIP) {
    462 		errno = EINVAL;
    463 		return (1);
    464 	}
    465 	p->fts_instr = instr;
    466 	return (0);
    467 }
    468 
    469 FTSENT *
    470 fts_children(sp, instr)
    471 	register FTS *sp;
    472 	int instr;
    473 {
    474 	register FTSENT *p;
    475 	int fd;
    476 
    477 	if (instr && instr != FTS_NAMEONLY) {
    478 		errno = EINVAL;
    479 		return (NULL);
    480 	}
    481 
    482 	/* Set current node pointer. */
    483 	p = sp->fts_cur;
    484 
    485 	/*
    486 	 * Errno set to 0 so user can distinguish empty directory from
    487 	 * an error.
    488 	 */
    489 	errno = 0;
    490 
    491 	/* Fatal errors stop here. */
    492 	if (ISSET(FTS_STOP))
    493 		return (NULL);
    494 
    495 	/* Return logical hierarchy of user's arguments. */
    496 	if (p->fts_info == FTS_INIT)
    497 		return (p->fts_link);
    498 
    499 	/*
    500 	 * If not a directory being visited in pre-order, stop here.  Could
    501 	 * allow FTS_DNR, assuming the user has fixed the problem, but the
    502 	 * same effect is available with FTS_AGAIN.
    503 	 */
    504 	if (p->fts_info != FTS_D /* && p->fts_info != FTS_DNR */)
    505 		return (NULL);
    506 
    507 	/* Free up any previous child list. */
    508 	if (sp->fts_child)
    509 		fts_lfree(sp->fts_child);
    510 
    511 	if (instr == FTS_NAMEONLY) {
    512 		SET(FTS_NAMEONLY);
    513 		instr = BNAMES;
    514 	} else
    515 		instr = BCHILD;
    516 
    517 	/*
    518 	 * If using chdir on a relative path and called BEFORE fts_read does
    519 	 * its chdir to the root of a traversal, we can lose -- we need to
    520 	 * chdir into the subdirectory, and we don't know where the current
    521 	 * directory is, so we can't get back so that the upcoming chdir by
    522 	 * fts_read will work.
    523 	 */
    524 	if (p->fts_level != FTS_ROOTLEVEL || p->fts_accpath[0] == '/' ||
    525 	    ISSET(FTS_NOCHDIR))
    526 		return (sp->fts_child = fts_build(sp, instr));
    527 
    528 	if ((fd = open(".", O_RDONLY, 0)) < 0)
    529 		return (NULL);
    530 	sp->fts_child = fts_build(sp, instr);
    531 	if (fchdir(fd))
    532 		return (NULL);
    533 	(void)close(fd);
    534 	return (sp->fts_child);
    535 }
    536 
    537 /*
    538  * This is the tricky part -- do not casually change *anything* in here.  The
    539  * idea is to build the linked list of entries that are used by fts_children
    540  * and fts_read.  There are lots of special cases.
    541  *
    542  * The real slowdown in walking the tree is the stat calls.  If FTS_NOSTAT is
    543  * set and it's a physical walk (so that symbolic links can't be directories),
    544  * we can do things quickly.  First, if it's a 4.4BSD file system, the type
    545  * of the file is in the directory entry.  Otherwise, we assume that the number
    546  * of subdirectories in a node is equal to the number of links to the parent.
    547  * The former skips all stat calls.  The latter skips stat calls in any leaf
    548  * directories and for any files after the subdirectories in the directory have
    549  * been found, cutting the stat calls by about 2/3.
    550  */
    551 static FTSENT *
    552 fts_build(sp, type)
    553 	register FTS *sp;
    554 	int type;
    555 {
    556 	register struct dirent *dp;
    557 	register FTSENT *p, *head;
    558 	register int nitems;
    559 	FTSENT *cur, *tail;
    560 	DIR *dirp;
    561 	void *adjaddr;
    562 	int cderrno, descend, len, level, maxlen, nlinks, oflag, saved_errno,
    563 	    nostat;
    564 	char *cp;
    565 
    566 	/* Set current node pointer. */
    567 	cur = sp->fts_cur;
    568 
    569 	/*
    570 	 * Open the directory for reading.  If this fails, we're done.
    571 	 * If being called from fts_read, set the fts_info field.
    572 	 */
    573 #ifdef FTS_WHITEOUT
    574 	if (ISSET(FTS_WHITEOUT))
    575 		oflag = DTF_NODUP|DTF_REWIND;
    576 	else
    577 		oflag = DTF_HIDEW|DTF_NODUP|DTF_REWIND;
    578 #else
    579 #define __opendir2(path, flag) opendir(path)
    580 #endif
    581 	if ((dirp = __opendir2(cur->fts_accpath, oflag)) == NULL) {
    582 		if (type == BREAD) {
    583 			cur->fts_info = FTS_DNR;
    584 			cur->fts_errno = errno;
    585 		}
    586 		return (NULL);
    587 	}
    588 
    589 	/*
    590 	 * Nlinks is the number of possible entries of type directory in the
    591 	 * directory if we're cheating on stat calls, 0 if we're not doing
    592 	 * any stat calls at all, -1 if we're doing stats on everything.
    593 	 */
    594 	if (type == BNAMES)
    595 		nlinks = 0;
    596 	else if (ISSET(FTS_NOSTAT) && ISSET(FTS_PHYSICAL)) {
    597 		nlinks = cur->fts_nlink - (ISSET(FTS_SEEDOT) ? 0 : 2);
    598 		nostat = 1;
    599 	} else {
    600 		nlinks = -1;
    601 		nostat = 0;
    602 	}
    603 
    604 #ifdef notdef
    605 	(void)printf("nlinks == %d (cur: %d)\n", nlinks, cur->fts_nlink);
    606 	(void)printf("NOSTAT %d PHYSICAL %d SEEDOT %d\n",
    607 	    ISSET(FTS_NOSTAT), ISSET(FTS_PHYSICAL), ISSET(FTS_SEEDOT));
    608 #endif
    609 	/*
    610 	 * If we're going to need to stat anything or we want to descend
    611 	 * and stay in the directory, chdir.  If this fails we keep going,
    612 	 * but set a flag so we don't chdir after the post-order visit.
    613 	 * We won't be able to stat anything, but we can still return the
    614 	 * names themselves.  Note, that since fts_read won't be able to
    615 	 * chdir into the directory, it will have to return different path
    616 	 * names than before, i.e. "a/b" instead of "b".  Since the node
    617 	 * has already been visited in pre-order, have to wait until the
    618 	 * post-order visit to return the error.  There is a special case
    619 	 * here, if there was nothing to stat then it's not an error to
    620 	 * not be able to stat.  This is all fairly nasty.  If a program
    621 	 * needed sorted entries or stat information, they had better be
    622 	 * checking FTS_NS on the returned nodes.
    623 	 */
    624 	cderrno = 0;
    625 	if (nlinks || type == BREAD)
    626 		if (FCHDIR(sp, dirfd(dirp))) {
    627 			if (nlinks && type == BREAD)
    628 				cur->fts_errno = errno;
    629 			cur->fts_flags |= FTS_DONTCHDIR;
    630 			descend = 0;
    631 			cderrno = errno;
    632 		} else
    633 			descend = 1;
    634 	else
    635 		descend = 0;
    636 
    637 	/*
    638 	 * Figure out the max file name length that can be stored in the
    639 	 * current path -- the inner loop allocates more path as necessary.
    640 	 * We really wouldn't have to do the maxlen calculations here, we
    641 	 * could do them in fts_read before returning the path, but it's a
    642 	 * lot easier here since the length is part of the dirent structure.
    643 	 *
    644 	 * If not changing directories set a pointer so that can just append
    645 	 * each new name into the path.
    646 	 */
    647 	maxlen = sp->fts_pathlen - cur->fts_pathlen - 1;
    648 	len = NAPPEND(cur);
    649 	if (ISSET(FTS_NOCHDIR)) {
    650 		cp = sp->fts_path + len;
    651 		*cp++ = '/';
    652 	}
    653 
    654 	level = cur->fts_level + 1;
    655 
    656 	/* Read the directory, attaching each entry to the `link' pointer. */
    657 	adjaddr = NULL;
    658 	for (head = tail = NULL, nitems = 0; dp = readdir(dirp);) {
    659 		if (!ISSET(FTS_SEEDOT) && ISDOT(dp->d_name))
    660 			continue;
    661 
    662 		if ((p = fts_alloc(sp, dp->d_name, (int)dp->d_namlen)) == NULL)
    663 			goto mem1;
    664 		if (dp->d_namlen > maxlen) {
    665 			if (fts_palloc(sp, (size_t)dp->d_namlen)) {
    666 				/*
    667 				 * No more memory for path or structures.  Save
    668 				 * errno, free up the current structure and the
    669 				 * structures already allocated.
    670 				 */
    671 mem1:				saved_errno = errno;
    672 				if (p)
    673 					free(p);
    674 				fts_lfree(head);
    675 				(void)closedir(dirp);
    676 				errno = saved_errno;
    677 				cur->fts_info = FTS_ERR;
    678 				SET(FTS_STOP);
    679 				return (NULL);
    680 			}
    681 			adjaddr = sp->fts_path;
    682 			maxlen = sp->fts_pathlen - sp->fts_cur->fts_pathlen - 1;
    683 		}
    684 
    685 		p->fts_pathlen = len + dp->d_namlen + 1;
    686 		p->fts_parent = sp->fts_cur;
    687 		p->fts_level = level;
    688 
    689 #ifdef FTS_WHITEOUT
    690 		if (dp->d_type == DT_WHT)
    691 			p->fts_flags |= FTS_ISW;
    692 #endif
    693 
    694 		if (cderrno) {
    695 			if (nlinks) {
    696 				p->fts_info = FTS_NS;
    697 				p->fts_errno = cderrno;
    698 			} else
    699 				p->fts_info = FTS_NSOK;
    700 			p->fts_accpath = cur->fts_accpath;
    701 		} else if (nlinks == 0
    702 #ifdef DT_DIR
    703 		    || nostat &&
    704 		    dp->d_type != DT_DIR && dp->d_type != DT_UNKNOWN
    705 #endif
    706 		    ) {
    707 			p->fts_accpath =
    708 			    ISSET(FTS_NOCHDIR) ? p->fts_path : p->fts_name;
    709 			p->fts_info = FTS_NSOK;
    710 		} else {
    711 			/* Build a file name for fts_stat to stat. */
    712 			if (ISSET(FTS_NOCHDIR)) {
    713 				p->fts_accpath = p->fts_path;
    714 				memmove(cp, p->fts_name, p->fts_namelen + 1);
    715 			} else
    716 				p->fts_accpath = p->fts_name;
    717 			/* Stat it. */
    718 			p->fts_info = fts_stat(sp, p, 0);
    719 
    720 			/* Decrement link count if applicable. */
    721 			if (nlinks > 0 && (p->fts_info == FTS_D ||
    722 			    p->fts_info == FTS_DC || p->fts_info == FTS_DOT))
    723 				--nlinks;
    724 		}
    725 
    726 		/* We walk in directory order so "ls -f" doesn't get upset. */
    727 		p->fts_link = NULL;
    728 		if (head == NULL)
    729 			head = tail = p;
    730 		else {
    731 			tail->fts_link = p;
    732 			tail = p;
    733 		}
    734 		++nitems;
    735 	}
    736 	(void)closedir(dirp);
    737 
    738 	/*
    739 	 * If had to realloc the path, adjust the addresses for the rest
    740 	 * of the tree.
    741 	 */
    742 	if (adjaddr)
    743 		fts_padjust(sp, adjaddr);
    744 
    745 	/*
    746 	 * If not changing directories, reset the path back to original
    747 	 * state.
    748 	 */
    749 	if (ISSET(FTS_NOCHDIR)) {
    750 		if (cp - 1 > sp->fts_path)
    751 			--cp;
    752 		*cp = '\0';
    753 	}
    754 
    755 	/*
    756 	 * If descended after called from fts_children or after called from
    757 	 * fts_read and nothing found, get back.  At the root level we use
    758 	 * the saved fd; if one of fts_open()'s arguments is a relative path
    759 	 * to an empty directory, we wind up here with no other way back.  If
    760 	 * can't get back, we're done.
    761 	 */
    762 	if (descend && (type == BCHILD || !nitems) &&
    763 	    (cur->fts_level == FTS_ROOTLEVEL ?
    764 	    FCHDIR(sp, sp->fts_rfd) : CHDIR(sp, ".."))) {
    765 		cur->fts_info = FTS_ERR;
    766 		SET(FTS_STOP);
    767 		return (NULL);
    768 	}
    769 
    770 	/* If didn't find anything, return NULL. */
    771 	if (!nitems) {
    772 		if (type == BREAD)
    773 			cur->fts_info = FTS_DP;
    774 		return (NULL);
    775 	}
    776 
    777 	/* Sort the entries. */
    778 	if (sp->fts_compar && nitems > 1)
    779 		head = fts_sort(sp, head, nitems);
    780 	return (head);
    781 }
    782 
    783 static u_short
    784 fts_stat(sp, p, follow)
    785 	FTS *sp;
    786 	register FTSENT *p;
    787 	int follow;
    788 {
    789 	register FTSENT *t;
    790 	register dev_t dev;
    791 	register ino_t ino;
    792 	struct stat *sbp, sb;
    793 	int saved_errno;
    794 
    795 	/* If user needs stat info, stat buffer already allocated. */
    796 	sbp = ISSET(FTS_NOSTAT) ? &sb : p->fts_statp;
    797 
    798 #ifdef FTS_WHITEOUT
    799 	/* check for whiteout */
    800 	if (p->fts_flags & FTS_ISW) {
    801 		if (sbp != &sb) {
    802 			memset(sbp, '\0', sizeof (*sbp));
    803 			sbp->st_mode = S_IFWHT;
    804 		}
    805 		return (FTS_W);
    806 	}
    807 #endif
    808 
    809 	/*
    810 	 * If doing a logical walk, or application requested FTS_FOLLOW, do
    811 	 * a stat(2).  If that fails, check for a non-existent symlink.  If
    812 	 * fail, set the errno from the stat call.
    813 	 */
    814 	if (ISSET(FTS_LOGICAL) || follow) {
    815 		if (stat(p->fts_accpath, sbp)) {
    816 			saved_errno = errno;
    817 			if (!lstat(p->fts_accpath, sbp)) {
    818 				errno = 0;
    819 				return (FTS_SLNONE);
    820 			}
    821 			p->fts_errno = saved_errno;
    822 			goto err;
    823 		}
    824 	} else if (lstat(p->fts_accpath, sbp)) {
    825 		p->fts_errno = errno;
    826 err:		memset(sbp, 0, sizeof(struct stat));
    827 		return (FTS_NS);
    828 	}
    829 
    830 	if (S_ISDIR(sbp->st_mode)) {
    831 		/*
    832 		 * Set the device/inode.  Used to find cycles and check for
    833 		 * crossing mount points.  Also remember the link count, used
    834 		 * in fts_build to limit the number of stat calls.  It is
    835 		 * understood that these fields are only referenced if fts_info
    836 		 * is set to FTS_D.
    837 		 */
    838 		dev = p->fts_dev = sbp->st_dev;
    839 		ino = p->fts_ino = sbp->st_ino;
    840 		p->fts_nlink = sbp->st_nlink;
    841 
    842 		if (ISDOT(p->fts_name))
    843 			return (FTS_DOT);
    844 
    845 		/*
    846 		 * Cycle detection is done by brute force when the directory
    847 		 * is first encountered.  If the tree gets deep enough or the
    848 		 * number of symbolic links to directories is high enough,
    849 		 * something faster might be worthwhile.
    850 		 */
    851 		for (t = p->fts_parent;
    852 		    t->fts_level >= FTS_ROOTLEVEL; t = t->fts_parent)
    853 			if (ino == t->fts_ino && dev == t->fts_dev) {
    854 				p->fts_cycle = t;
    855 				return (FTS_DC);
    856 			}
    857 		return (FTS_D);
    858 	}
    859 	if (S_ISLNK(sbp->st_mode))
    860 		return (FTS_SL);
    861 	if (S_ISREG(sbp->st_mode))
    862 		return (FTS_F);
    863 	return (FTS_DEFAULT);
    864 }
    865 
    866 static FTSENT *
    867 fts_sort(sp, head, nitems)
    868 	FTS *sp;
    869 	FTSENT *head;
    870 	register int nitems;
    871 {
    872 	register FTSENT **ap, *p;
    873 
    874 	/*
    875 	 * Construct an array of pointers to the structures and call qsort(3).
    876 	 * Reassemble the array in the order returned by qsort.  If unable to
    877 	 * sort for memory reasons, return the directory entries in their
    878 	 * current order.  Allocate enough space for the current needs plus
    879 	 * 40 so don't realloc one entry at a time.
    880 	 */
    881 	if (nitems > sp->fts_nitems) {
    882 		sp->fts_nitems = nitems + 40;
    883 		if ((sp->fts_array = realloc(sp->fts_array,
    884 		    (size_t)(sp->fts_nitems * sizeof(FTSENT *)))) == NULL) {
    885 			sp->fts_nitems = 0;
    886 			return (head);
    887 		}
    888 	}
    889 	for (ap = sp->fts_array, p = head; p; p = p->fts_link)
    890 		*ap++ = p;
    891 	qsort((void *)sp->fts_array, nitems, sizeof(FTSENT *), sp->fts_compar);
    892 	for (head = *(ap = sp->fts_array); --nitems; ++ap)
    893 		ap[0]->fts_link = ap[1];
    894 	ap[0]->fts_link = NULL;
    895 	return (head);
    896 }
    897 
    898 static FTSENT *
    899 fts_alloc(sp, name, namelen)
    900 	FTS *sp;
    901 	char *name;
    902 	register int namelen;
    903 {
    904 	register FTSENT *p;
    905 	size_t len;
    906 
    907 	/*
    908 	 * The file name is a variable length array and no stat structure is
    909 	 * necessary if the user has set the nostat bit.  Allocate the FTSENT
    910 	 * structure, the file name and the stat structure in one chunk, but
    911 	 * be careful that the stat structure is reasonably aligned.  Since the
    912 	 * fts_name field is declared to be of size 1, the fts_name pointer is
    913 	 * namelen + 2 before the first possible address of the stat structure.
    914 	 */
    915 	len = sizeof(FTSENT) + namelen;
    916 	if (!ISSET(FTS_NOSTAT))
    917 		len += sizeof(struct stat) + ALIGNBYTES;
    918 	if ((p = malloc(len)) == NULL)
    919 		return (NULL);
    920 
    921 	/* Copy the name plus the trailing NULL. */
    922 	memmove(p->fts_name, name, namelen + 1);
    923 
    924 	if (!ISSET(FTS_NOSTAT))
    925 		p->fts_statp = (struct stat *)ALIGN(p->fts_name + namelen + 2);
    926 	p->fts_namelen = namelen;
    927 	p->fts_path = sp->fts_path;
    928 	p->fts_errno = 0;
    929 	p->fts_flags = 0;
    930 	p->fts_instr = FTS_NOINSTR;
    931 	p->fts_number = 0;
    932 	p->fts_pointer = NULL;
    933 	return (p);
    934 }
    935 
    936 static void
    937 fts_lfree(head)
    938 	register FTSENT *head;
    939 {
    940 	register FTSENT *p;
    941 
    942 	/* Free a linked list of structures. */
    943 	while (p = head) {
    944 		head = head->fts_link;
    945 		free(p);
    946 	}
    947 }
    948 
    949 /*
    950  * Allow essentially unlimited paths; find, rm, ls should all work on any tree.
    951  * Most systems will allow creation of paths much longer than MAXPATHLEN, even
    952  * though the kernel won't resolve them.  Add the size (not just what's needed)
    953  * plus 256 bytes so don't realloc the path 2 bytes at a time.
    954  */
    955 static int
    956 fts_palloc(sp, more)
    957 	FTS *sp;
    958 	size_t more;
    959 {
    960 	sp->fts_pathlen += more + 256;
    961 	sp->fts_path = realloc(sp->fts_path, (size_t)sp->fts_pathlen);
    962 	return (sp->fts_path == NULL);
    963 }
    964 
    965 /*
    966  * When the path is realloc'd, have to fix all of the pointers in structures
    967  * already returned.
    968  */
    969 static void
    970 fts_padjust(sp, addr)
    971 	FTS *sp;
    972 	void *addr;
    973 {
    974 	FTSENT *p;
    975 
    976 #define	ADJUST(p) {							\
    977 	(p)->fts_accpath =						\
    978 	    (char *)addr + ((p)->fts_accpath - (p)->fts_path);		\
    979 	(p)->fts_path = addr;						\
    980 }
    981 	/* Adjust the current set of children. */
    982 	for (p = sp->fts_child; p; p = p->fts_link)
    983 		ADJUST(p);
    984 
    985 	/* Adjust the rest of the tree. */
    986 	for (p = sp->fts_cur; p->fts_level >= FTS_ROOTLEVEL;) {
    987 		ADJUST(p);
    988 		p = p->fts_link ? p->fts_link : p->fts_parent;
    989 	}
    990 }
    991 
    992 static size_t
    993 fts_maxarglen(argv)
    994 	char * const *argv;
    995 {
    996 	size_t len, max;
    997 
    998 	for (max = 0; *argv; ++argv)
    999 		if ((len = strlen(*argv)) > max)
   1000 			max = len;
   1001 	return (max);
   1002 }
   1003