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