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