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