xref: /csrg-svn/lib/libc/gen/fts.c (revision 52770)
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.32 (Berkeley) 03/01/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 
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 got 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, reading it if haven't already.  If
300 		 * the read fails for any reason, or the directory is empty,
301 		 * the fts_info field of the current node is set by fts_build.
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 state
304 		 * so the application will eventually get an error condition.
305 		 * If haven't read and fail to chdir, check to see if we're
306 		 * at the root node -- if so, we have to get back or the root
307 		 * node may be inaccessible.
308 		 */
309 		if (sp->fts_child) {
310 			if (CHDIR(sp, p->fts_accpath)) {
311 				p->fts_errno = errno;
312 				p->fts_flags |= FTS_DONTCHDIR;
313 				for (p = sp->fts_child; p; p = p->fts_link)
314 					p->fts_accpath =
315 					    p->fts_parent->fts_accpath;
316 			}
317 		} else if ((sp->fts_child = fts_build(sp, BREAD)) == NULL) {
318 			p->fts_flags |= FTS_DONTCHDIR;
319 			if (ISSET(FTS_STOP))
320 				return (NULL);
321 			if (p->fts_level == FTS_ROOTLEVEL &&
322 			    FCHDIR(sp, sp->fts_rfd)) {
323 				(void)close(sp->fts_rfd);
324 				SET(FTS_STOP);
325 				return (NULL);
326 			}
327 			(void)close(sp->fts_rfd);
328 			return (p);
329 		}
330 		p = sp->fts_child;
331 		sp->fts_child = NULL;
332 		goto name;
333 	}
334 
335 	/* Move to the next node on this level. */
336 next:	tmp = p;
337 	if (p = p->fts_link) {
338 		free(tmp);
339 
340 		/* If reached the top, load the paths for the next root. */
341 		if (p->fts_level == FTS_ROOTLEVEL) {
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 	sp->fts_path[p->fts_pathlen] = '\0';
386 
387 	/*
388 	 * Change to starting directory.  If at a root node or came through a
389 	 * symlink, go back through the file descriptor.  Otherwise, just cd
390 	 * up one directory.
391 	 */
392 	if (p->fts_level == FTS_ROOTLEVEL) {
393 		if (FCHDIR(sp, sp->fts_rfd)) {
394 			(void)close(sp->fts_rfd);
395 			SET(FTS_STOP);
396 			return (NULL);
397 		}
398 		(void)close(sp->fts_rfd);
399 	} else if (p->fts_flags & FTS_SYMFOLLOW) {
400 		if (FCHDIR(sp, p->fts_symfd)) {
401 			(void)close(p->fts_symfd);
402 			SET(FTS_STOP);
403 			return (NULL);
404 		}
405 		(void)close(p->fts_symfd);
406 	} else if (!(p->fts_flags & FTS_DONTCHDIR)) {
407 		if (CHDIR(sp, "..")) {
408 			SET(FTS_STOP);
409 			return (NULL);
410 		}
411 	}
412 	p->fts_info = p->fts_errno ? FTS_ERR : FTS_DP;
413 	return (sp->fts_cur = p);
414 }
415 
416 /*
417  * Fts_set takes the stream as an argument although it's not used in this
418  * implementation; it would be necessary if anyone wanted to add global
419  * semantics to fts using fts_set.  An error return is allowed for similar
420  * reasons.
421  */
422 /* ARGSUSED */
423 int
424 fts_set(sp, p, instr)
425 	FTS *sp;
426 	FTSENT *p;
427 	int instr;
428 {
429 	if (instr && instr != FTS_AGAIN && instr != FTS_FOLLOW &&
430 	    instr != FTS_NOINSTR && instr != FTS_SKIP) {
431 		errno = EINVAL;
432 		return (1);
433 	}
434 	p->fts_instr = instr;
435 	return (0);
436 }
437 
438 FTSENT *
439 fts_children(sp, instr)
440 	register FTS *sp;
441 	int instr;
442 {
443 	register FTSENT *p;
444 	int fd;
445 
446 	if (instr && instr != FTS_NAMEONLY) {
447 		errno = EINVAL;
448 		return (NULL);
449 	}
450 
451 	/* Set current node pointer. */
452 	p = sp->fts_cur;
453 
454 	/*
455 	 * Errno set to 0 so user can distinguish empty directory from
456 	 * an error.
457 	 */
458 	errno = 0;
459 
460 	/* Fatal errors stop here. */
461 	if (ISSET(FTS_STOP))
462 		return (NULL);
463 
464 	/* Return logical hierarchy of user's arguments. */
465 	if (p->fts_info == FTS_INIT)
466 		return (p->fts_link);
467 
468 	/*
469 	 * If not a directory being visited in pre-order, stop here.  Could
470 	 * allow FTS_DNR, assuming the user has fixed the problem, but the
471 	 * same effect is available with FTS_AGAIN.
472 	 */
473 	if (p->fts_info != FTS_D /* && p->fts_info != FTS_DNR */)
474 		return (NULL);
475 
476 	/* Free up any previous child list. */
477 	if (sp->fts_child)
478 		fts_lfree(sp->fts_child);
479 
480 	if (instr == FTS_NAMEONLY) {
481 		sp->fts_options |= FTS_NAMEONLY;
482 		instr = BNAMES;
483 	} else
484 		instr = BCHILD;
485 
486 	/*
487 	 * If using chdir on a relative path and called BEFORE fts_read does
488 	 * its chdir to the root of a traversal, we can lose -- we need to
489 	 * chdir into the subdirectory, and we don't know where the current
490 	 * directory is, so we can't get back so that the upcoming chdir by
491 	 * fts_read will work.
492 	 */
493 	if (p->fts_level != FTS_ROOTLEVEL || p->fts_accpath[0] == '/' ||
494 	    ISSET(FTS_NOCHDIR))
495 		return (sp->fts_child = fts_build(sp, instr));
496 
497 	if ((fd = open(".", O_RDONLY, 0)) < 0)
498 		return (NULL);
499 	sp->fts_child = fts_build(sp, instr);
500 	if (fchdir(fd))
501 		return (NULL);
502 	(void)close(fd);
503 	return (sp->fts_child);
504 }
505 
506 /*
507  * This is the tricky part -- do not casually change *anything* in here.  The
508  * idea is to build the linked list of entries that are used by fts_children
509  * and fts_read.  There are lots of special cases.
510  *
511  * The real slowdown in walking the tree is the stat calls.  If FTS_NOSTAT is
512  * set and it's a physical walk (so that symbolic links can't be directories),
513  * we assume that the number of subdirectories in a node is equal to the number
514  * of links to the parent.  This allows stat calls to be skipped in any leaf
515  * directories and for any nodes after the directories in the parent node have
516  * been found.  This empirically cuts the stat calls by about 2/3.
517  */
518 static FTSENT *
519 fts_build(sp, type)
520 	register FTS *sp;
521 	int type;
522 {
523 	register struct dirent *dp;
524 	register FTSENT *p, *head;
525 	register int nitems;
526 	FTSENT *cur, *tail;
527 	DIR *dirp;
528 	void *adjaddr;
529 	int cderrno, descend, len, level, maxlen, nlinks, saved_errno;
530 	char *cp;
531 
532 	/* Set current node pointer. */
533 	cur = sp->fts_cur;
534 
535 	/*
536 	 * Open the directory for reading.  If this fails, we're done.
537 	 * If being called from fts_read, set the fts_info field.
538 	 */
539 	if ((dirp = opendir(cur->fts_accpath)) == NULL) {
540 		if (type == BREAD) {
541 			cur->fts_info = FTS_DNR;
542 			cur->fts_errno = errno;
543 		}
544 		return (NULL);
545 	}
546 
547 	/*
548 	 * Nlinks is the number of possible entries of type directory in the
549 	 * directory if we're cheating on stat calls, 0 if we're not doing
550 	 * any stat calls at all, -1 if we're doing stats on everything.
551 	 */
552 	if (type == BNAMES)
553 		nlinks = 0;
554 	else if (ISSET(FTS_NOSTAT) && ISSET(FTS_PHYSICAL))
555 		nlinks = cur->fts_nlink - (ISSET(FTS_SEEDOT) ? 0 : 2);
556 	else
557 		nlinks = -1;
558 
559 #ifdef notdef
560 	(void)printf("nlinks == %d (cur: %d)\n", nlinks, cur->fts_nlink);
561 	(void)printf("NOSTAT %d PHYSICAL %d SEEDOT %d\n",
562 	    ISSET(FTS_NOSTAT), ISSET(FTS_PHYSICAL), ISSET(FTS_SEEDOT));
563 #endif
564 	/*
565 	 * If we're going to need to stat anything or we want to descend
566 	 * and stay in the directory, chdir.  If this fails we keep going.
567 	 * We won't be able to stat anything, but we can still return the
568 	 * names themselves.  Note, that since fts_read won't be able to
569 	 * chdir into the directory, it will have to return different path
570 	 * names than before, i.e. "a/b" instead of "b".  Since the node
571 	 * has already been visited in pre-order, have to wait until the
572 	 * post-order visit to return the error.  There is a special case
573 	 * here, if there was nothing to stat then it's not an error to
574 	 * not be able to stat.  This is all fairly nasty.  If a program
575 	 * needed sorted entries or stat information, they had better be
576 	 * checking FTS_NS on the returned nodes.
577 	 */
578 	if (nlinks || type == BREAD)
579 		if (FCHDIR(sp, dirfd(dirp))) {
580 			if (nlinks && type == BREAD)
581 				cur->fts_errno = errno;
582 			descend = 0;
583 			cderrno = errno;
584 		} else {
585 			descend = 1;
586 			cderrno = 0;
587 		}
588 	else
589 		descend = 0;
590 
591 	/*
592 	 * Figure out the max file name length that can be stored in the
593 	 * current path -- the inner loop allocates more path as necessary.
594 	 * We really wouldn't have to do the maxlen calculations here, we
595 	 * could do them in fts_read before returning the path, but it's a
596 	 * lot easier here since the length is part of the dirent structure.
597 	 *
598 	 * If not changing directories set a pointer so that can just append
599 	 * each new name into the path.
600 	 */
601 	maxlen = sp->fts_pathlen - cur->fts_pathlen - 1;
602 	len = NAPPEND(cur);
603 	if (ISSET(FTS_NOCHDIR)) {
604 		cp = sp->fts_path + len;
605 		*cp++ = '/';
606 	}
607 
608 	level = cur->fts_level + 1;
609 
610 	/* Read the directory, attaching each entry to the `link' pointer. */
611 	adjaddr = NULL;
612 	for (head = tail = NULL, nitems = 0; dp = readdir(dirp);) {
613 		if (!ISSET(FTS_SEEDOT) && ISDOT(dp->d_name))
614 			continue;
615 
616 		if ((p = fts_alloc(sp, dp->d_name, (int)dp->d_namlen)) == NULL)
617 			goto mem1;
618 		if (dp->d_namlen > maxlen) {
619 			if (fts_palloc(sp, (int)dp->d_namlen)) {
620 				/*
621 				 * No more memory for path or structures.  Save
622 				 * errno, free up the current structure and the
623 				 * structures already allocated.
624 				 */
625 mem1:				saved_errno = errno;
626 				if (p)
627 					free(p);
628 				fts_lfree(head);
629 				(void)closedir(dirp);
630 				errno = saved_errno;
631 				cur->fts_info = FTS_ERR;
632 				SET(FTS_STOP);
633 				return (NULL);
634 			}
635 			adjaddr = sp->fts_path;
636 			maxlen = sp->fts_pathlen - sp->fts_cur->fts_pathlen - 1;
637 		}
638 
639 		p->fts_pathlen = len + dp->d_namlen + 1;
640 		p->fts_parent = sp->fts_cur;
641 		p->fts_level = level;
642 
643 		if (cderrno) {
644 			if (nlinks) {
645 				p->fts_info = FTS_NS;
646 				p->fts_errno = cderrno;
647 			} else
648 				p->fts_info = FTS_NSOK;
649 			p->fts_accpath = cur->fts_accpath;
650 		} else if (nlinks) {
651 			/* Build a file name for fts_stat to stat. */
652 			if (ISSET(FTS_NOCHDIR)) {
653 				p->fts_accpath = p->fts_path;
654 				bcopy(p->fts_name, cp, p->fts_namelen + 1);
655 			} else
656 				p->fts_accpath = p->fts_name;
657 			p->fts_info = fts_stat(sp, p, 0);
658 			if (nlinks > 0 && (p->fts_info == FTS_D ||
659 			    p->fts_info == FTS_DC || p->fts_info == FTS_DOT))
660 				--nlinks;
661 		} else {
662 			p->fts_accpath =
663 			    ISSET(FTS_NOCHDIR) ? p->fts_path : p->fts_name;
664 			p->fts_info = FTS_NSOK;
665 		}
666 
667 		/* We walk in directory order so "ls -f" doesn't get upset. */
668 		p->fts_link = NULL;
669 		if (head == NULL)
670 			head = tail = p;
671 		else {
672 			tail->fts_link = p;
673 			tail = p;
674 		}
675 		++nitems;
676 	}
677 	(void)closedir(dirp);
678 
679 	/*
680 	 * If had to realloc the path, adjust the addresses for the rest
681 	 * of the tree.
682 	 */
683 	if (adjaddr)
684 		fts_padjust(sp, adjaddr);
685 
686 	/*
687 	 * If not changing directories, reset the path back to original
688 	 * state.
689 	 */
690 	if (ISSET(FTS_NOCHDIR)) {
691 		if (cp - 1 > sp->fts_path)
692 			--cp;
693 		*cp = '\0';
694 	}
695 
696 	/*
697 	 * If descended after called from fts_children or called from
698 	 * fts_read and didn't find anything, get back.  If can't get
699 	 * back, done.
700 	 */
701 	if (descend && (!nitems || type == BCHILD) && CHDIR(sp, "..")) {
702 		cur->fts_info = FTS_ERR;
703 		SET(FTS_STOP);
704 		return (NULL);
705 	}
706 
707 	/* If didn't find anything, just do the post-order visit */
708 	if (!nitems) {
709 		if (type == BREAD)
710 			cur->fts_info = FTS_DP;
711 		return (NULL);
712 	}
713 
714 	/* Sort the entries. */
715 	if (sp->fts_compar && nitems > 1)
716 		head = fts_sort(sp, head, nitems);
717 	return (head);
718 }
719 
720 static u_short
721 fts_stat(sp, p, follow)
722 	FTS *sp;
723 	register FTSENT *p;
724 	int follow;
725 {
726 	register FTSENT *t;
727 	register dev_t dev;
728 	register ino_t ino;
729 	struct stat *sbp, sb;
730 	int saved_errno;
731 
732 	/* If user needs stat info, stat buffer already allocated. */
733 	sbp = ISSET(FTS_NOSTAT) ? &sb : p->fts_statp;
734 
735 	/*
736 	 * If doing a logical walk, or application requested FTS_FOLLOW, do
737 	 * a stat(2).  If that fails, check for a non-existent symlink.  If
738 	 * fail, set the errno from the stat call.
739 	 */
740 	if (ISSET(FTS_LOGICAL) || follow) {
741 		if (stat(p->fts_accpath, sbp)) {
742 			saved_errno = errno;
743 			if (!lstat(p->fts_accpath, sbp)) {
744 				errno = 0;
745 				return (FTS_SLNONE);
746 			}
747 			p->fts_errno = saved_errno;
748 			goto err;
749 		}
750 	} else if (lstat(p->fts_accpath, sbp)) {
751 		p->fts_errno = errno;
752 err:		bzero(sbp, sizeof(struct stat));
753 		return (FTS_NS);
754 	}
755 
756 	if (S_ISDIR(sbp->st_mode)) {
757 		/*
758 		 * Set the device/inode.  Used to find cycles and check for
759 		 * crossing mount points.  Also remember the link count, used
760 		 * in fts_build to limit the number of stat calls.  It is
761 		 * understood that these fields are only referenced if fts_info
762 		 * is set to FTS_D.
763 		 */
764 		dev = p->fts_dev = sbp->st_dev;
765 		ino = p->fts_ino = sbp->st_ino;
766 		p->fts_nlink = sbp->st_nlink;
767 
768 		if (ISDOT(p->fts_name))
769 			return (FTS_DOT);
770 
771 		/*
772 		 * Cycle detection is done by brute force when the directory
773 		 * is first encountered.  If the tree gets deep enough or the
774 		 * number of symbolic links to directories is high enough,
775 		 * something faster might be worthwhile.
776 		 */
777 		for (t = p->fts_parent;
778 		    t->fts_level >= FTS_ROOTLEVEL; t = t->fts_parent)
779 			if (ino == t->fts_ino && dev == t->fts_dev) {
780 				p->fts_cycle = t;
781 				return (FTS_DC);
782 			}
783 		return (FTS_D);
784 	}
785 	if (S_ISLNK(sbp->st_mode))
786 		return (FTS_SL);
787 	if (S_ISREG(sbp->st_mode))
788 		return (FTS_F);
789 	return (FTS_DEFAULT);
790 }
791 
792 static FTSENT *
793 fts_sort(sp, head, nitems)
794 	FTS *sp;
795 	FTSENT *head;
796 	register int nitems;
797 {
798 	register FTSENT **ap, *p;
799 
800 	/*
801 	 * Construct an array of pointers to the structures and call qsort(3).
802 	 * Reassemble the array in the order returned by qsort.  If unable to
803 	 * sort for memory reasons, return the directory entries in their
804 	 * current order.  Allocate enough space for the current needs plus
805 	 * 40 so don't realloc one entry at a time.
806 	 */
807 	if (nitems > sp->fts_nitems) {
808 		sp->fts_nitems = nitems + 40;
809 		if ((sp->fts_array = realloc(sp->fts_array,
810 		    (size_t)(sp->fts_nitems * sizeof(FTSENT *)))) == NULL) {
811 			sp->fts_nitems = 0;
812 			return (head);
813 		}
814 	}
815 	for (ap = sp->fts_array, p = head; p; p = p->fts_link)
816 		*ap++ = p;
817 	qsort((void *)sp->fts_array, nitems, sizeof(FTSENT *), sp->fts_compar);
818 	for (head = *(ap = sp->fts_array); --nitems; ++ap)
819 		ap[0]->fts_link = ap[1];
820 	ap[0]->fts_link = NULL;
821 	return (head);
822 }
823 
824 static FTSENT *
825 fts_alloc(sp, name, len)
826 	FTS *sp;
827 	char *name;
828 	register int len;
829 {
830 	register FTSENT *p;
831 	int needstat;
832 
833 	/*
834 	 * Variable sized structures.  The stat structure isn't necessary
835 	 * if the user doesn't need it, and the name is variable length.
836 	 * Allocate enough extra space after the structure to store them.
837 	 */
838 	needstat = ISSET(FTS_NOSTAT) ? 0 : ALIGN(sizeof(struct stat));
839 	if ((p = malloc((size_t)(sizeof(FTSENT) + len + 1 + needstat))) == NULL)
840 		return (NULL);
841 	bcopy(name, p->fts_name, len + 1);
842 	if (needstat)
843 		p->fts_statp = (struct stat *)ALIGN(p->fts_name + len + 1);
844 	p->fts_namelen = len;
845 	p->fts_path = sp->fts_path;
846 	p->fts_errno = 0;
847 	p->fts_flags = 0;
848 	p->fts_instr = FTS_NOINSTR;
849 	p->fts_number = 0;
850 #ifdef NOT_NECESSARY
851 	p->fts_pointer = NULL;
852 #endif
853 	return (p);
854 }
855 
856 static void
857 fts_lfree(head)
858 	register FTSENT *head;
859 {
860 	register FTSENT *p;
861 
862 	/* Free a linked list of structures. */
863 	while (p = head) {
864 		head = head->fts_link;
865 		free(p);
866 	}
867 }
868 
869 /*
870  * Allow essentially unlimited paths; find, rm, ls should all work on any tree.
871  * Most systems will allow creation of paths much longer than MAXPATHLEN, even
872  * though the kernel won't resolve them.  Add the size (not just what's needed)
873  * plus 256 bytes so don't realloc the path 2 bytes at a time.
874  */
875 static int
876 fts_palloc(sp, more)
877 	FTS *sp;
878 	int more;
879 {
880 
881 	sp->fts_pathlen += more + 256;
882 	sp->fts_path = realloc(sp->fts_path, (size_t)sp->fts_pathlen);
883 	return (sp->fts_path == NULL);
884 }
885 
886 /*
887  * When the path is realloc'd, have to fix all of the pointers in structures
888  * already returned.
889  */
890 static void
891 fts_padjust(sp, addr)
892 	FTS *sp;
893 	void *addr;
894 {
895 	FTSENT *p;
896 
897 #define	ADJUST(p) { \
898 	(p)->fts_accpath = addr + ((p)->fts_accpath - (p)->fts_path); \
899 	(p)->fts_path = addr; \
900 }
901 	/* Adjust the current set of children. */
902 	for (p = sp->fts_child; p; p = p->fts_link)
903 		ADJUST(p);
904 
905 	/* Adjust the rest of the tree. */
906 	for (p = sp->fts_cur; p->fts_level >= FTS_ROOTLEVEL;) {
907 		ADJUST(p);
908 		p = p->fts_link ? p->fts_link : p->fts_parent;
909 	}
910 }
911