xref: /original-bsd/lib/libc/gen/fts.c (revision 4670e840)
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.41 (Berkeley) 03/07/93";
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 assume that the number of subdirectories in a node is equal to the number
515  * of links to the parent.  This allows stat calls to be skipped in any leaf
516  * directories and for any nodes after the directories in the parent node have
517  * been found.  This empirically cuts the stat calls by about 2/3.
518  */
519 static FTSENT *
520 fts_build(sp, type)
521 	register FTS *sp;
522 	int type;
523 {
524 	register struct dirent *dp;
525 	register FTSENT *p, *head;
526 	register int nitems;
527 	FTSENT *cur, *tail;
528 	DIR *dirp;
529 	void *adjaddr;
530 	int cderrno, descend, len, level, maxlen, nlinks, saved_errno;
531 	char *cp;
532 
533 	/* Set current node pointer. */
534 	cur = sp->fts_cur;
535 
536 	/*
537 	 * Open the directory for reading.  If this fails, we're done.
538 	 * If being called from fts_read, set the fts_info field.
539 	 */
540 	if ((dirp = opendir(cur->fts_accpath)) == NULL) {
541 		if (type == BREAD) {
542 			cur->fts_info = FTS_DNR;
543 			cur->fts_errno = errno;
544 		}
545 		return (NULL);
546 	}
547 
548 	/*
549 	 * Nlinks is the number of possible entries of type directory in the
550 	 * directory if we're cheating on stat calls, 0 if we're not doing
551 	 * any stat calls at all, -1 if we're doing stats on everything.
552 	 */
553 	if (type == BNAMES)
554 		nlinks = 0;
555 	else if (ISSET(FTS_NOSTAT) && ISSET(FTS_PHYSICAL))
556 		nlinks = cur->fts_nlink - (ISSET(FTS_SEEDOT) ? 0 : 2);
557 	else
558 		nlinks = -1;
559 
560 #ifdef notdef
561 	(void)printf("nlinks == %d (cur: %d)\n", nlinks, cur->fts_nlink);
562 	(void)printf("NOSTAT %d PHYSICAL %d SEEDOT %d\n",
563 	    ISSET(FTS_NOSTAT), ISSET(FTS_PHYSICAL), ISSET(FTS_SEEDOT));
564 #endif
565 	/*
566 	 * If we're going to need to stat anything or we want to descend
567 	 * and stay in the directory, chdir.  If this fails we keep going,
568 	 * but set a flag so we don't chdir after the post-order visit.
569 	 * We won't be able to stat anything, but we can still return the
570 	 * names themselves.  Note, that since fts_read won't be able to
571 	 * chdir into the directory, it will have to return different path
572 	 * names than before, i.e. "a/b" instead of "b".  Since the node
573 	 * has already been visited in pre-order, have to wait until the
574 	 * post-order visit to return the error.  There is a special case
575 	 * here, if there was nothing to stat then it's not an error to
576 	 * not be able to stat.  This is all fairly nasty.  If a program
577 	 * needed sorted entries or stat information, they had better be
578 	 * checking FTS_NS on the returned nodes.
579 	 */
580 	cderrno = 0;
581 	if (nlinks || type == BREAD)
582 		if (FCHDIR(sp, dirfd(dirp))) {
583 			if (nlinks && type == BREAD)
584 				cur->fts_errno = errno;
585 			cur->fts_flags |= FTS_DONTCHDIR;
586 			descend = 0;
587 			cderrno = errno;
588 		} else
589 			descend = 1;
590 	else
591 		descend = 0;
592 
593 	/*
594 	 * Figure out the max file name length that can be stored in the
595 	 * current path -- the inner loop allocates more path as necessary.
596 	 * We really wouldn't have to do the maxlen calculations here, we
597 	 * could do them in fts_read before returning the path, but it's a
598 	 * lot easier here since the length is part of the dirent structure.
599 	 *
600 	 * If not changing directories set a pointer so that can just append
601 	 * each new name into the path.
602 	 */
603 	maxlen = sp->fts_pathlen - cur->fts_pathlen - 1;
604 	len = NAPPEND(cur);
605 	if (ISSET(FTS_NOCHDIR)) {
606 		cp = sp->fts_path + len;
607 		*cp++ = '/';
608 	}
609 
610 	level = cur->fts_level + 1;
611 
612 	/* Read the directory, attaching each entry to the `link' pointer. */
613 	adjaddr = NULL;
614 	for (head = tail = NULL, nitems = 0; dp = readdir(dirp);) {
615 		if (!ISSET(FTS_SEEDOT) && ISDOT(dp->d_name))
616 			continue;
617 
618 		if ((p = fts_alloc(sp, dp->d_name, (int)dp->d_namlen)) == NULL)
619 			goto mem1;
620 		if (dp->d_namlen > maxlen) {
621 			if (fts_palloc(sp, (size_t)dp->d_namlen)) {
622 				/*
623 				 * No more memory for path or structures.  Save
624 				 * errno, free up the current structure and the
625 				 * structures already allocated.
626 				 */
627 mem1:				saved_errno = errno;
628 				if (p)
629 					free(p);
630 				fts_lfree(head);
631 				(void)closedir(dirp);
632 				errno = saved_errno;
633 				cur->fts_info = FTS_ERR;
634 				SET(FTS_STOP);
635 				return (NULL);
636 			}
637 			adjaddr = sp->fts_path;
638 			maxlen = sp->fts_pathlen - sp->fts_cur->fts_pathlen - 1;
639 		}
640 
641 		p->fts_pathlen = len + dp->d_namlen + 1;
642 		p->fts_parent = sp->fts_cur;
643 		p->fts_level = level;
644 
645 		if (cderrno) {
646 			if (nlinks) {
647 				p->fts_info = FTS_NS;
648 				p->fts_errno = cderrno;
649 			} else
650 				p->fts_info = FTS_NSOK;
651 			p->fts_accpath = cur->fts_accpath;
652 		} else if (nlinks) {
653 			/* Build a file name for fts_stat to stat. */
654 			if (ISSET(FTS_NOCHDIR)) {
655 				p->fts_accpath = p->fts_path;
656 				bcopy(p->fts_name, cp, p->fts_namelen + 1);
657 			} else
658 				p->fts_accpath = p->fts_name;
659 			p->fts_info = fts_stat(sp, p, 0);
660 			if (nlinks > 0 && (p->fts_info == FTS_D ||
661 			    p->fts_info == FTS_DC || p->fts_info == FTS_DOT))
662 				--nlinks;
663 		} else {
664 			p->fts_accpath =
665 			    ISSET(FTS_NOCHDIR) ? p->fts_path : p->fts_name;
666 			p->fts_info = FTS_NSOK;
667 		}
668 
669 		/* We walk in directory order so "ls -f" doesn't get upset. */
670 		p->fts_link = NULL;
671 		if (head == NULL)
672 			head = tail = p;
673 		else {
674 			tail->fts_link = p;
675 			tail = p;
676 		}
677 		++nitems;
678 	}
679 	(void)closedir(dirp);
680 
681 	/*
682 	 * If had to realloc the path, adjust the addresses for the rest
683 	 * of the tree.
684 	 */
685 	if (adjaddr)
686 		fts_padjust(sp, adjaddr);
687 
688 	/*
689 	 * If not changing directories, reset the path back to original
690 	 * state.
691 	 */
692 	if (ISSET(FTS_NOCHDIR)) {
693 		if (cp - 1 > sp->fts_path)
694 			--cp;
695 		*cp = '\0';
696 	}
697 
698 	/*
699 	 * If descended after called from fts_children or called from
700 	 * fts_read and didn't find anything, get back.  If can't get
701 	 * back, done.
702 	 */
703 	if (descend && (!nitems || type == BCHILD) && CHDIR(sp, "..")) {
704 		cur->fts_info = FTS_ERR;
705 		SET(FTS_STOP);
706 		return (NULL);
707 	}
708 
709 	/* If didn't find anything, return NULL. */
710 	if (!nitems) {
711 		if (type == BREAD)
712 			cur->fts_info = FTS_DP;
713 		return (NULL);
714 	}
715 
716 	/* Sort the entries. */
717 	if (sp->fts_compar && nitems > 1)
718 		head = fts_sort(sp, head, nitems);
719 	return (head);
720 }
721 
722 static u_short
723 fts_stat(sp, p, follow)
724 	FTS *sp;
725 	register FTSENT *p;
726 	int follow;
727 {
728 	register FTSENT *t;
729 	register dev_t dev;
730 	register ino_t ino;
731 	struct stat *sbp, sb;
732 	int saved_errno;
733 
734 	/* If user needs stat info, stat buffer already allocated. */
735 	sbp = ISSET(FTS_NOSTAT) ? &sb : p->fts_statp;
736 
737 	/*
738 	 * If doing a logical walk, or application requested FTS_FOLLOW, do
739 	 * a stat(2).  If that fails, check for a non-existent symlink.  If
740 	 * fail, set the errno from the stat call.
741 	 */
742 	if (ISSET(FTS_LOGICAL) || follow) {
743 		if (stat(p->fts_accpath, sbp)) {
744 			saved_errno = errno;
745 			if (!lstat(p->fts_accpath, sbp)) {
746 				errno = 0;
747 				return (FTS_SLNONE);
748 			}
749 			p->fts_errno = saved_errno;
750 			goto err;
751 		}
752 	} else if (lstat(p->fts_accpath, sbp)) {
753 		p->fts_errno = errno;
754 err:		bzero(sbp, sizeof(struct stat));
755 		return (FTS_NS);
756 	}
757 
758 	if (S_ISDIR(sbp->st_mode)) {
759 		/*
760 		 * Set the device/inode.  Used to find cycles and check for
761 		 * crossing mount points.  Also remember the link count, used
762 		 * in fts_build to limit the number of stat calls.  It is
763 		 * understood that these fields are only referenced if fts_info
764 		 * is set to FTS_D.
765 		 */
766 		dev = p->fts_dev = sbp->st_dev;
767 		ino = p->fts_ino = sbp->st_ino;
768 		p->fts_nlink = sbp->st_nlink;
769 
770 		if (ISDOT(p->fts_name))
771 			return (FTS_DOT);
772 
773 		/*
774 		 * Cycle detection is done by brute force when the directory
775 		 * is first encountered.  If the tree gets deep enough or the
776 		 * number of symbolic links to directories is high enough,
777 		 * something faster might be worthwhile.
778 		 */
779 		for (t = p->fts_parent;
780 		    t->fts_level >= FTS_ROOTLEVEL; t = t->fts_parent)
781 			if (ino == t->fts_ino && dev == t->fts_dev) {
782 				p->fts_cycle = t;
783 				return (FTS_DC);
784 			}
785 		return (FTS_D);
786 	}
787 	if (S_ISLNK(sbp->st_mode))
788 		return (FTS_SL);
789 	if (S_ISREG(sbp->st_mode))
790 		return (FTS_F);
791 	return (FTS_DEFAULT);
792 }
793 
794 static FTSENT *
795 fts_sort(sp, head, nitems)
796 	FTS *sp;
797 	FTSENT *head;
798 	register int nitems;
799 {
800 	register FTSENT **ap, *p;
801 
802 	/*
803 	 * Construct an array of pointers to the structures and call qsort(3).
804 	 * Reassemble the array in the order returned by qsort.  If unable to
805 	 * sort for memory reasons, return the directory entries in their
806 	 * current order.  Allocate enough space for the current needs plus
807 	 * 40 so don't realloc one entry at a time.
808 	 */
809 	if (nitems > sp->fts_nitems) {
810 		sp->fts_nitems = nitems + 40;
811 		if ((sp->fts_array = realloc(sp->fts_array,
812 		    (size_t)(sp->fts_nitems * sizeof(FTSENT *)))) == NULL) {
813 			sp->fts_nitems = 0;
814 			return (head);
815 		}
816 	}
817 	for (ap = sp->fts_array, p = head; p; p = p->fts_link)
818 		*ap++ = p;
819 	qsort((void *)sp->fts_array, nitems, sizeof(FTSENT *), sp->fts_compar);
820 	for (head = *(ap = sp->fts_array); --nitems; ++ap)
821 		ap[0]->fts_link = ap[1];
822 	ap[0]->fts_link = NULL;
823 	return (head);
824 }
825 
826 static FTSENT *
827 fts_alloc(sp, name, namelen)
828 	FTS *sp;
829 	char *name;
830 	register int namelen;
831 {
832 	register FTSENT *p;
833 	size_t len;
834 
835 	/*
836 	 * The file name is a variable length array and no stat structure is
837 	 * necessary if the user has set the nostat bit.  Allocate the FTSENT
838 	 * structure, the file name and the stat structure in one chunk, but
839 	 * be careful that the stat structure is reasonably aligned.  Since the
840 	 * fts_name field is declared to be of size 1, the fts_name pointer is
841 	 * namelen + 2 before the first possible address of the stat structure.
842 	 */
843 	len = sizeof(FTSENT) + namelen;
844 	if (!ISSET(FTS_NOSTAT))
845 		len += sizeof(struct stat) + ALIGNBYTES;
846 	if ((p = malloc(len)) == NULL)
847 		return (NULL);
848 
849 	/* Copy the name plus the trailing NULL. */
850 	bcopy(name, p->fts_name, namelen + 1);
851 
852 	if (!ISSET(FTS_NOSTAT))
853 		p->fts_statp = (struct stat *)ALIGN(p->fts_name + namelen + 2);
854 	p->fts_namelen = namelen;
855 	p->fts_path = sp->fts_path;
856 	p->fts_errno = 0;
857 	p->fts_flags = 0;
858 	p->fts_instr = FTS_NOINSTR;
859 	p->fts_number = 0;
860 	p->fts_pointer = NULL;
861 	return (p);
862 }
863 
864 static void
865 fts_lfree(head)
866 	register FTSENT *head;
867 {
868 	register FTSENT *p;
869 
870 	/* Free a linked list of structures. */
871 	while (p = head) {
872 		head = head->fts_link;
873 		free(p);
874 	}
875 }
876 
877 /*
878  * Allow essentially unlimited paths; find, rm, ls should all work on any tree.
879  * Most systems will allow creation of paths much longer than MAXPATHLEN, even
880  * though the kernel won't resolve them.  Add the size (not just what's needed)
881  * plus 256 bytes so don't realloc the path 2 bytes at a time.
882  */
883 static int
884 fts_palloc(sp, more)
885 	FTS *sp;
886 	size_t more;
887 {
888 	sp->fts_pathlen += more + 256;
889 	sp->fts_path = realloc(sp->fts_path, (size_t)sp->fts_pathlen);
890 	return (sp->fts_path == NULL);
891 }
892 
893 /*
894  * When the path is realloc'd, have to fix all of the pointers in structures
895  * already returned.
896  */
897 static void
898 fts_padjust(sp, addr)
899 	FTS *sp;
900 	void *addr;
901 {
902 	FTSENT *p;
903 
904 #define	ADJUST(p) {							\
905 	(p)->fts_accpath = addr + ((p)->fts_accpath - (p)->fts_path);	\
906 	(p)->fts_path = addr;						\
907 }
908 	/* Adjust the current set of children. */
909 	for (p = sp->fts_child; p; p = p->fts_link)
910 		ADJUST(p);
911 
912 	/* Adjust the rest of the tree. */
913 	for (p = sp->fts_cur; p->fts_level >= FTS_ROOTLEVEL;) {
914 		ADJUST(p);
915 		p = p->fts_link ? p->fts_link : p->fts_parent;
916 	}
917 }
918 
919 static size_t
920 fts_maxarglen(argv)
921 	char * const *argv;
922 {
923 	size_t len, max;
924 
925 	for (max = 0; *argv; ++argv)
926 		if ((len = strlen(*argv)) > max)
927 			max = len;
928 	return (max);
929 }
930