xref: /original-bsd/lib/libc/gen/fts.c (revision acda45c0)
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.16 (Berkeley) 03/11/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 *
40 fts_open(argv, options, compar)
41 	char * const *argv;
42 	register int options;
43 	int (*compar)();
44 {
45 	register FTS *sp;
46 	register FTSENT *p, *root;
47 	register int nitems, maxlen;
48 	FTSENT *parent, *tmp;
49 	int len;
50 
51 	/* Allocate/initialize the stream */
52 	if (!(sp = (FTS *)malloc((u_int)sizeof(FTS))))
53 		return(NULL);
54 	bzero(sp, sizeof(FTS));
55 	sp->fts_compar = compar;
56 	sp->fts_options = options;
57 
58 	/* Logical walks turn on NOCHDIR; symbolic links are too hard. */
59 	if (ISSET(FTS_LOGICAL))
60 		SET(FTS_NOCHDIR);
61 
62 	/* Allocate/initialize root's parent. */
63 	if (!(parent = fts_alloc(sp, "", 0)))
64 		goto mem1;
65 	parent->fts_level = FTS_ROOTPARENTLEVEL;
66 
67 	/* Allocate/initialize root(s). */
68 	maxlen = -1;
69 	for (root = NULL, nitems = 0; *argv; ++argv, ++nitems) {
70 		if (!(len = strlen(*argv))) {
71 			errno = ENOENT;
72 			goto mem2;
73 		}
74 		if (maxlen < len)
75 			maxlen = len;
76 		p = fts_alloc(sp, *argv, len);
77 		/*
78 		 * If comparison routine supplied, traverse in sorted
79 		 * order; otherwise traverse in the order specified.
80 		 */
81 		if (compar) {
82 			p->fts_link = root;
83 			root = p;
84 			p->fts_accpath = p->fts_name;
85 			if (!(options & FTS_NOSTAT))
86 				p->fts_info = fts_stat(sp, p, 0);
87 		} else {
88 			p->fts_link = NULL;
89 			if (!root)
90 				tmp = root = p;
91 			else {
92 				tmp->fts_link = p;
93 				tmp = p;
94 			}
95 		}
96 		p->fts_level = FTS_ROOTLEVEL;
97 		p->fts_parent = parent;
98 	}
99 	if (compar && nitems > 1)
100 		root = fts_sort(sp, root, nitems);
101 
102 	/*
103 	 * Allocate a dummy pointer and make fts_read think that we've just
104 	 * finished the node before the root(s); set p->fts_info to FTS_NS
105 	 * so that everything about the "current" node is ignored.
106 	 */
107 	if (!(sp->fts_cur = fts_alloc(sp, "", 0)))
108 		goto mem2;
109 	sp->fts_cur->fts_link = root;
110 	sp->fts_cur->fts_info = FTS_NS;
111 
112 	/* Start out with at least 1K+ of path space. */
113 	if (!fts_path(sp, MAX(maxlen, MAXPATHLEN)))
114 		goto mem3;
115 
116 	/*
117 	 * If using chdir(2), grab a file descriptor pointing to dot to insure
118 	 * that we can get back here; this could be avoided for some paths,
119 	 * but almost certainly not worth the effort.  Slashes, symbolic links,
120 	 * and ".." are all fairly nasty problems.  Note, if we can't get the
121 	 * descriptor we run anyway, just more slowly.
122 	 */
123 	if (!ISSET(FTS_NOCHDIR) && (sp->fts_rfd = open(".", O_RDONLY, 0)) < 0)
124 		SET(FTS_NOCHDIR);
125 
126 	return(sp);
127 
128 mem3:	free(sp->fts_cur);
129 mem2:	fts_lfree(root);
130 	free(parent);
131 mem1:	free(sp);
132 	return(NULL);
133 }
134 
135 static
136 fts_load(sp, p)
137 	FTS *sp;
138 	register FTSENT *p;
139 {
140 	register int len;
141 	register char *cp;
142 
143 	/*
144 	 * Load the stream structure for the next traversal.  Since we don't
145 	 * actually enter the directory until after the preorder visit, set
146 	 * the fts_accpath field specially so the chdir gets done to the right
147 	 * place and the user can access the first node.
148 	 */
149 	len = p->fts_pathlen = p->fts_namelen;
150 	bcopy(p->fts_name, sp->fts_path, len + 1);
151 	if ((cp = rindex(p->fts_name, '/')) && (cp != p->fts_name || cp[1])) {
152 		len = strlen(++cp);
153 		bcopy(cp, p->fts_name, len + 1);
154 		p->fts_namelen = len;
155 	}
156 	p->fts_accpath = p->fts_path = sp->fts_path;
157 
158 	sp->rdev = p->fts_statb.st_dev;
159 	p->fts_info = fts_stat(sp, p, 0);
160 	return(1);
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 			if (!fts_load(sp, p))
310 				return(NULL);
311 			return(sp->fts_cur = p);
312 		}
313 
314 		/* User may have called fts_set on the node. */
315 		if (p->fts_instr == FTS_SKIP)
316 			goto next;
317 		if (p->fts_instr == FTS_FOLLOW) {
318 			p->fts_info = fts_stat(sp, p, 1);
319 			p->fts_instr = FTS_NOINSTR;
320 		}
321 
322 name:		t = sp->fts_path + NAPPEND(p->fts_parent);
323 		*t++ = '/';
324 		bcopy(p->fts_name, t, p->fts_namelen + 1);
325 		return(sp->fts_cur = p);
326 	}
327 
328 	/* Move up to the parent node. */
329 	p = tmp->fts_parent;
330 	free(tmp);
331 
332 	if (p->fts_level == FTS_ROOTPARENTLEVEL) {
333 		/*
334 		 * Done; free everything up and set errno to 0 so the user
335 		 * can distinguish between error and EOF.
336 		 */
337 		free(p);
338 		errno = 0;
339 		return(sp->fts_cur = NULL);
340 	}
341 
342 	sp->fts_path[p->fts_pathlen] = '\0';
343 
344 	/*
345 	 * Cd back up to the parent directory.  If at a root node, have to cd
346 	 * back to the original place, otherwise may not be able to access the
347 	 * original node on post-order.
348 	 */
349 	if (p->fts_level == FTS_ROOTLEVEL) {
350 		if (FCHDIR(sp, sp->fts_rfd)) {
351 			SET(FTS_STOP);
352 			return(NULL);
353 		}
354 	}
355 	else if (CHDIR(sp, "..")) {
356 		SET(FTS_STOP);
357 		return(NULL);
358 	}
359 
360 	/*
361 	 * If had a chdir error when trying to get into the directory, set the
362 	 * info field to reflect this, and restore errno.  The error indicator
363 	 * has to be reset to 0 so that if the user does an FTS_AGAIN, it all
364 	 * works.
365 	 */
366 	if (p->fts_cderr) {
367 		errno = p->fts_cderr;
368 		p->fts_cderr = 0;
369 		p->fts_info = FTS_ERR;
370 	} else
371 		p->fts_info = FTS_DP;
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 != FTS_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 > FTS_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