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