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