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