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