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