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