]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - contrib/mdocml/compat_fts.c
Merge bmake-20150418
[FreeBSD/FreeBSD.git] / contrib / mdocml / compat_fts.c
1 #include "config.h"
2
3 #if HAVE_FTS
4
5 int dummy;
6
7 #else
8
9 /*      $Id: compat_fts.c,v 1.8 2015/02/07 07:53:01 schwarze Exp $      */
10 /*      $OpenBSD: fts.c,v 1.50 2015/01/16 16:48:51 deraadt Exp $        */
11
12 /*-
13  * Copyright (c) 1990, 1993, 1994
14  *      The Regents of the University of California.  All rights reserved.
15  *
16  * Redistribution and use in source and binary forms, with or without
17  * modification, are permitted provided that the following conditions
18  * are met:
19  * 1. Redistributions of source code must retain the above copyright
20  *    notice, this list of conditions and the following disclaimer.
21  * 2. Redistributions in binary form must reproduce the above copyright
22  *    notice, this list of conditions and the following disclaimer in the
23  *    documentation and/or other materials provided with the distribution.
24  * 3. Neither the name of the University nor the names of its contributors
25  *    may be used to endorse or promote products derived from this software
26  *    without specific prior written permission.
27  *
28  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
29  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
30  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
31  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
32  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
33  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
34  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
35  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
36  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
37  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
38  * SUCH DAMAGE.
39  */
40
41 #include <sys/stat.h>
42 #include <sys/types.h>
43
44 #include <dirent.h>
45 #include <errno.h>
46 #include <fcntl.h>
47 #include <limits.h>
48 #include <stdlib.h>
49 #include <string.h>
50 #include <unistd.h>
51 #include "compat_fts.h"
52
53 #define MAXIMUM(a, b)   (((a) > (b)) ? (a) : (b))
54
55 static FTSENT   *fts_alloc(FTS *, const char *, size_t);
56 static FTSENT   *fts_build(FTS *);
57 static void      fts_lfree(FTSENT *);
58 static void      fts_load(FTS *, FTSENT *);
59 static size_t    fts_maxarglen(char * const *);
60 static void      fts_padjust(FTS *, FTSENT *);
61 static int       fts_palloc(FTS *, size_t);
62 static unsigned short    fts_stat(FTS *, FTSENT *);
63 static int       fts_safe_changedir(FTS *, FTSENT *, int, const char *);
64
65 #define ISDOT(a)        (a[0] == '.' && (!a[1] || (a[1] == '.' && !a[2])))
66 #ifndef O_DIRECTORY
67 #define O_DIRECTORY     0
68 #endif
69 #ifndef O_CLOEXEC
70 #define O_CLOEXEC       0
71 #endif
72
73 #define CLR(opt)        (sp->fts_options &= ~(opt))
74 #define ISSET(opt)      (sp->fts_options & (opt))
75 #define SET(opt)        (sp->fts_options |= (opt))
76
77 #define FCHDIR(sp, fd)  (!ISSET(FTS_NOCHDIR) && fchdir(fd))
78
79 FTS *
80 fts_open(char * const *argv, int options, void *dummy)
81 {
82         FTS *sp;
83         FTSENT *p, *root;
84         int nitems;
85         FTSENT *parent, *tmp;
86         size_t len;
87
88         /* Options check. */
89         if (options & ~FTS_OPTIONMASK) {
90                 errno = EINVAL;
91                 return (NULL);
92         }
93
94         /* Allocate/initialize the stream */
95         if ((sp = calloc(1, sizeof(FTS))) == NULL)
96                 return (NULL);
97         sp->fts_options = options;
98
99         /*
100          * Start out with 1K of path space, and enough, in any case,
101          * to hold the user's paths.
102          */
103         if (fts_palloc(sp, MAXIMUM(fts_maxarglen(argv), PATH_MAX)))
104                 goto mem1;
105
106         /* Allocate/initialize root's parent. */
107         if ((parent = fts_alloc(sp, "", 0)) == NULL)
108                 goto mem2;
109         parent->fts_level = FTS_ROOTPARENTLEVEL;
110
111         /* Allocate/initialize root(s). */
112         for (root = NULL, nitems = 0; *argv; ++argv, ++nitems) {
113                 /* Don't allow zero-length paths. */
114                 if ((len = strlen(*argv)) == 0) {
115                         errno = ENOENT;
116                         goto mem3;
117                 }
118
119                 if ((p = fts_alloc(sp, *argv, len)) == NULL)
120                         goto mem3;
121                 p->fts_level = FTS_ROOTLEVEL;
122                 p->fts_parent = parent;
123                 p->fts_accpath = p->fts_name;
124                 p->fts_info = fts_stat(sp, p);
125
126                 /* Command-line "." and ".." are real directories. */
127                 if (p->fts_info == FTS_DOT)
128                         p->fts_info = FTS_D;
129
130                 p->fts_link = NULL;
131                 if (root == NULL)
132                         tmp = root = p;
133                 else {
134                         tmp->fts_link = p;
135                         tmp = p;
136                 }
137         }
138
139         /*
140          * Allocate a dummy pointer and make fts_read think that we've just
141          * finished the node before the root(s); set p->fts_info to FTS_INIT
142          * so that everything about the "current" node is ignored.
143          */
144         if ((sp->fts_cur = fts_alloc(sp, "", 0)) == NULL)
145                 goto mem3;
146         sp->fts_cur->fts_link = root;
147         sp->fts_cur->fts_info = FTS_INIT;
148
149         /*
150          * If using chdir(2), grab a file descriptor pointing to dot to ensure
151          * that we can get back here; this could be avoided for some paths,
152          * but almost certainly not worth the effort.  Slashes, symbolic links,
153          * and ".." are all fairly nasty problems.  Note, if we can't get the
154          * descriptor we run anyway, just more slowly.
155          */
156         if (!ISSET(FTS_NOCHDIR) &&
157             (sp->fts_rfd = open(".", O_RDONLY | O_CLOEXEC)) < 0)
158                 SET(FTS_NOCHDIR);
159
160         if (nitems == 0)
161                 free(parent);
162
163         return (sp);
164
165 mem3:   fts_lfree(root);
166         free(parent);
167 mem2:   free(sp->fts_path);
168 mem1:   free(sp);
169         return (NULL);
170 }
171
172 static void
173 fts_load(FTS *sp, FTSENT *p)
174 {
175         size_t len;
176         char *cp;
177
178         /*
179          * Load the stream structure for the next traversal.  Since we don't
180          * actually enter the directory until after the preorder visit, set
181          * the fts_accpath field specially so the chdir gets done to the right
182          * place and the user can access the first node.  From fts_open it's
183          * known that the path will fit.
184          */
185         len = p->fts_pathlen = p->fts_namelen;
186         memmove(sp->fts_path, p->fts_name, len + 1);
187         if ((cp = strrchr(p->fts_name, '/')) && (cp != p->fts_name || cp[1])) {
188                 len = strlen(++cp);
189                 memmove(p->fts_name, cp, len + 1);
190                 p->fts_namelen = len;
191         }
192         p->fts_accpath = p->fts_path = sp->fts_path;
193         sp->fts_dev = p->fts_dev;
194 }
195
196 int
197 fts_close(FTS *sp)
198 {
199         FTSENT *freep, *p;
200         int rfd, error = 0;
201
202         /*
203          * This still works if we haven't read anything -- the dummy structure
204          * points to the root list, so we step through to the end of the root
205          * list which has a valid parent pointer.
206          */
207         if (sp->fts_cur) {
208                 for (p = sp->fts_cur; p->fts_level >= FTS_ROOTLEVEL;) {
209                         freep = p;
210                         p = p->fts_link ? p->fts_link : p->fts_parent;
211                         free(freep);
212                 }
213                 free(p);
214         }
215
216         /* Stash the original directory fd if needed. */
217         rfd = ISSET(FTS_NOCHDIR) ? -1 : sp->fts_rfd;
218
219         /* Free up child linked list, sort array, path buffer, stream ptr.*/
220         if (sp->fts_child)
221                 fts_lfree(sp->fts_child);
222         free(sp->fts_path);
223         free(sp);
224
225         /* Return to original directory, checking for error. */
226         if (rfd != -1) {
227                 int saved_errno;
228                 error = fchdir(rfd);
229                 saved_errno = errno;
230                 (void)close(rfd);
231                 errno = saved_errno;
232         }
233
234         return (error);
235 }
236
237 /*
238  * Special case of "/" at the end of the path so that slashes aren't
239  * appended which would cause paths to be written as "....//foo".
240  */
241 #define NAPPEND(p)                                                      \
242         (p->fts_path[p->fts_pathlen - 1] == '/'                         \
243             ? p->fts_pathlen - 1 : p->fts_pathlen)
244
245 FTSENT *
246 fts_read(FTS *sp)
247 {
248         FTSENT *p, *tmp;
249         int instr;
250         char *t;
251
252         /* If finished or unrecoverable error, return NULL. */
253         if (sp->fts_cur == NULL || ISSET(FTS_STOP))
254                 return (NULL);
255
256         /* Set current node pointer. */
257         p = sp->fts_cur;
258
259         /* Save and zero out user instructions. */
260         instr = p->fts_instr;
261         p->fts_instr = FTS_NOINSTR;
262
263         /* Directory in pre-order. */
264         if (p->fts_info == FTS_D) {
265                 /* If skipped or crossed mount point, do post-order visit. */
266                 if (instr == FTS_SKIP ||
267                     (ISSET(FTS_XDEV) && p->fts_dev != sp->fts_dev)) {
268                         if (sp->fts_child) {
269                                 fts_lfree(sp->fts_child);
270                                 sp->fts_child = NULL;
271                         }
272                         p->fts_info = FTS_DP;
273                         return (p);
274                 }
275
276                 /*
277                  * Cd to the subdirectory.
278                  *
279                  * If have already read and now fail to chdir, whack the list
280                  * to make the names come out right, and set the parent errno
281                  * so the application will eventually get an error condition.
282                  * Set the FTS_DONTCHDIR flag so that when we logically change
283                  * directories back to the parent we don't do a chdir.
284                  *
285                  * If haven't read do so.  If the read fails, fts_build sets
286                  * FTS_STOP or the fts_info field of the node.
287                  */
288                 if (sp->fts_child) {
289                         if (fts_safe_changedir(sp, p, -1, p->fts_accpath)) {
290                                 p->fts_errno = errno;
291                                 p->fts_flags |= FTS_DONTCHDIR;
292                                 for (p = sp->fts_child; p; p = p->fts_link)
293                                         p->fts_accpath =
294                                             p->fts_parent->fts_accpath;
295                         }
296                 } else if ((sp->fts_child = fts_build(sp)) == NULL) {
297                         if (ISSET(FTS_STOP))
298                                 return (NULL);
299                         return (p);
300                 }
301                 p = sp->fts_child;
302                 sp->fts_child = NULL;
303                 goto name;
304         }
305
306         /* Move to the next node on this level. */
307 next:   tmp = p;
308         if ((p = p->fts_link)) {
309                 free(tmp);
310
311                 /*
312                  * If reached the top, return to the original directory (or
313                  * the root of the tree), and load the paths for the next root.
314                  */
315                 if (p->fts_level == FTS_ROOTLEVEL) {
316                         if (FCHDIR(sp, sp->fts_rfd)) {
317                                 SET(FTS_STOP);
318                                 return (NULL);
319                         }
320                         fts_load(sp, p);
321                         return (sp->fts_cur = p);
322                 }
323
324                 /*
325                  * User may have called fts_set on the node.  If skipped,
326                  * ignore.  If followed, get a file descriptor so we can
327                  * get back if necessary.
328                  */
329                 if (p->fts_instr == FTS_SKIP)
330                         goto next;
331
332 name:           t = sp->fts_path + NAPPEND(p->fts_parent);
333                 *t++ = '/';
334                 memmove(t, p->fts_name, p->fts_namelen + 1);
335                 return (sp->fts_cur = p);
336         }
337
338         /* Move up to the parent node. */
339         p = tmp->fts_parent;
340         free(tmp);
341
342         if (p->fts_level == FTS_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         /* NUL terminate the pathname. */
353         sp->fts_path[p->fts_pathlen] = '\0';
354
355         /*
356          * Return to the parent directory.  If at a root node or came through
357          * a symlink, go back through the file descriptor.  Otherwise, cd up
358          * one directory.
359          */
360         if (p->fts_level == FTS_ROOTLEVEL) {
361                 if (FCHDIR(sp, sp->fts_rfd)) {
362                         SET(FTS_STOP);
363                         sp->fts_cur = p;
364                         return (NULL);
365                 }
366         } else if (!(p->fts_flags & FTS_DONTCHDIR) &&
367             fts_safe_changedir(sp, p->fts_parent, -1, "..")) {
368                 SET(FTS_STOP);
369                 sp->fts_cur = p;
370                 return (NULL);
371         }
372         p->fts_info = p->fts_errno ? FTS_ERR : FTS_DP;
373         return (sp->fts_cur = p);
374 }
375
376 /*
377  * Fts_set takes the stream as an argument although it's not used in this
378  * implementation; it would be necessary if anyone wanted to add global
379  * semantics to fts using fts_set.  An error return is allowed for similar
380  * reasons.
381  */
382 /* ARGSUSED */
383 int
384 fts_set(FTS *sp, FTSENT *p, int instr)
385 {
386         if (instr && instr != FTS_NOINSTR && instr != FTS_SKIP) {
387                 errno = EINVAL;
388                 return (1);
389         }
390         p->fts_instr = instr;
391         return (0);
392 }
393
394 /*
395  * This is the tricky part -- do not casually change *anything* in here.  The
396  * idea is to build the linked list of entries that are used by fts_children
397  * and fts_read.  There are lots of special cases.
398  *
399  * The real slowdown in walking the tree is the stat calls.  If FTS_NOSTAT is
400  * set and it's a physical walk (so that symbolic links can't be directories),
401  * we can do things quickly.  First, if it's a 4.4BSD file system, the type
402  * of the file is in the directory entry.  Otherwise, we assume that the number
403  * of subdirectories in a node is equal to the number of links to the parent.
404  * The former skips all stat calls.  The latter skips stat calls in any leaf
405  * directories and for any files after the subdirectories in the directory have
406  * been found, cutting the stat calls by about 2/3.
407  */
408 static FTSENT *
409 fts_build(FTS *sp)
410 {
411         struct dirent *dp;
412         FTSENT *p, *head;
413         FTSENT *cur, *tail;
414         DIR *dirp;
415         void *oldaddr;
416         size_t dlen, len, maxlen;
417         int nitems, cderrno, descend, level, doadjust;
418         int saved_errno;
419         char *cp;
420
421         /* Set current node pointer. */
422         cur = sp->fts_cur;
423
424         /*
425          * Open the directory for reading.  If this fails, we're done.
426          * If being called from fts_read, set the fts_info field.
427          */
428         if ((dirp = opendir(cur->fts_accpath)) == NULL) {
429                 cur->fts_info = FTS_DNR;
430                 cur->fts_errno = errno;
431                 return (NULL);
432         }
433
434         /*
435          * If we're going to need to stat anything or we want to descend
436          * and stay in the directory, chdir.  If this fails we keep going,
437          * but set a flag so we don't chdir after the post-order visit.
438          * We won't be able to stat anything, but we can still return the
439          * names themselves.  Note, that since fts_read won't be able to
440          * chdir into the directory, it will have to return different path
441          * names than before, i.e. "a/b" instead of "b".  Since the node
442          * has already been visited in pre-order, have to wait until the
443          * post-order visit to return the error.  There is a special case
444          * here, if there was nothing to stat then it's not an error to
445          * not be able to stat.  This is all fairly nasty.  If a program
446          * needed sorted entries or stat information, they had better be
447          * checking FTS_NS on the returned nodes.
448          */
449         cderrno = 0;
450         if (fts_safe_changedir(sp, cur, dirfd(dirp), NULL)) {
451                 cur->fts_errno = errno;
452                 cur->fts_flags |= FTS_DONTCHDIR;
453                 descend = 0;
454                 cderrno = errno;
455                 (void)closedir(dirp);
456                 dirp = NULL;
457         } else
458                 descend = 1;
459
460         /*
461          * Figure out the max file name length that can be stored in the
462          * current path -- the inner loop allocates more path as necessary.
463          * We really wouldn't have to do the maxlen calculations here, we
464          * could do them in fts_read before returning the path, but it's a
465          * lot easier here since the length is part of the dirent structure.
466          *
467          * If not changing directories set a pointer so that can just append
468          * each new name into the path.
469          */
470         len = NAPPEND(cur);
471         if (ISSET(FTS_NOCHDIR)) {
472                 cp = sp->fts_path + len;
473                 *cp++ = '/';
474         }
475         len++;
476         maxlen = sp->fts_pathlen - len;
477
478         /*
479          * fts_level is signed so we must prevent it from wrapping
480          * around to FTS_ROOTLEVEL and FTS_ROOTPARENTLEVEL.
481          */
482         level = cur->fts_level;
483         if (level < FTS_MAXLEVEL)
484             level++;
485
486         /* Read the directory, attaching each entry to the `link' pointer. */
487         doadjust = 0;
488         for (head = tail = NULL, nitems = 0; dirp && (dp = readdir(dirp));) {
489                 if (ISDOT(dp->d_name))
490                         continue;
491
492 #if HAVE_DIRENT_NAMLEN
493                 dlen = dp->d_namlen;
494 #else
495                 dlen = strlen(dp->d_name);
496 #endif
497
498                 if (!(p = fts_alloc(sp, dp->d_name, dlen)))
499                         goto mem1;
500                 if (dlen >= maxlen) {   /* include space for NUL */
501                         oldaddr = sp->fts_path;
502                         if (fts_palloc(sp, dlen + len + 1)) {
503                                 /*
504                                  * No more memory for path or structures.  Save
505                                  * errno, free up the current structure and the
506                                  * structures already allocated.
507                                  */
508 mem1:                           saved_errno = errno;
509                                 if (p)
510                                         free(p);
511                                 fts_lfree(head);
512                                 (void)closedir(dirp);
513                                 cur->fts_info = FTS_ERR;
514                                 SET(FTS_STOP);
515                                 errno = saved_errno;
516                                 return (NULL);
517                         }
518                         /* Did realloc() change the pointer? */
519                         if (oldaddr != sp->fts_path) {
520                                 doadjust = 1;
521                                 if (ISSET(FTS_NOCHDIR))
522                                         cp = sp->fts_path + len;
523                         }
524                         maxlen = sp->fts_pathlen - len;
525                 }
526
527                 p->fts_level = level;
528                 p->fts_parent = sp->fts_cur;
529                 p->fts_pathlen = len + dlen;
530                 if (p->fts_pathlen < len) {
531                         /*
532                          * If we wrap, free up the current structure and
533                          * the structures already allocated, then error
534                          * out with ENAMETOOLONG.
535                          */
536                         free(p);
537                         fts_lfree(head);
538                         (void)closedir(dirp);
539                         cur->fts_info = FTS_ERR;
540                         SET(FTS_STOP);
541                         errno = ENAMETOOLONG;
542                         return (NULL);
543                 }
544
545                 if (cderrno) {
546                         p->fts_info = FTS_NS;
547                         p->fts_errno = cderrno;
548                         p->fts_accpath = cur->fts_accpath;
549                 } else {
550                         /* Build a file name for fts_stat to stat. */
551                         if (ISSET(FTS_NOCHDIR)) {
552                                 p->fts_accpath = p->fts_path;
553                                 memmove(cp, p->fts_name, p->fts_namelen + 1);
554                         } else
555                                 p->fts_accpath = p->fts_name;
556                         /* Stat it. */
557                         p->fts_info = fts_stat(sp, p);
558                 }
559
560                 /* We walk in directory order so "ls -f" doesn't get upset. */
561                 p->fts_link = NULL;
562                 if (head == NULL)
563                         head = tail = p;
564                 else {
565                         tail->fts_link = p;
566                         tail = p;
567                 }
568                 ++nitems;
569         }
570         if (dirp)
571                 (void)closedir(dirp);
572
573         /*
574          * If realloc() changed the address of the path, adjust the
575          * addresses for the rest of the tree and the dir list.
576          */
577         if (doadjust)
578                 fts_padjust(sp, head);
579
580         /*
581          * If not changing directories, reset the path back to original
582          * state.
583          */
584         if (ISSET(FTS_NOCHDIR)) {
585                 if (len == sp->fts_pathlen || nitems == 0)
586                         --cp;
587                 *cp = '\0';
588         }
589
590         /*
591          * If descended after called from fts_children or after called from
592          * fts_read and nothing found, get back.  At the root level we use
593          * the saved fd; if one of fts_open()'s arguments is a relative path
594          * to an empty directory, we wind up here with no other way back.  If
595          * can't get back, we're done.
596          */
597         if (descend && !nitems &&
598             (cur->fts_level == FTS_ROOTLEVEL ? FCHDIR(sp, sp->fts_rfd) :
599             fts_safe_changedir(sp, cur->fts_parent, -1, ".."))) {
600                 cur->fts_info = FTS_ERR;
601                 SET(FTS_STOP);
602                 return (NULL);
603         }
604
605         /* If didn't find anything, return NULL. */
606         if (!nitems) {
607                 cur->fts_info = FTS_DP;
608                 return (NULL);
609         }
610         return (head);
611 }
612
613 static unsigned short
614 fts_stat(FTS *sp, FTSENT *p)
615 {
616         FTSENT *t;
617         dev_t dev;
618         ino_t ino;
619         struct stat *sbp;
620
621         /* If user needs stat info, stat buffer already allocated. */
622         sbp = p->fts_statp;
623
624         if (lstat(p->fts_accpath, sbp)) {
625                 p->fts_errno = errno;
626                 memset(sbp, 0, sizeof(struct stat));
627                 return (FTS_NS);
628         }
629
630         if (S_ISDIR(sbp->st_mode)) {
631                 /*
632                  * Set the device/inode.  Used to find cycles and check for
633                  * crossing mount points.  Also remember the link count, used
634                  * in fts_build to limit the number of stat calls.  It is
635                  * understood that these fields are only referenced if fts_info
636                  * is set to FTS_D.
637                  */
638                 dev = p->fts_dev = sbp->st_dev;
639                 ino = p->fts_ino = sbp->st_ino;
640                 p->fts_nlink = sbp->st_nlink;
641
642                 if (ISDOT(p->fts_name))
643                         return (FTS_DOT);
644
645                 /*
646                  * Cycle detection is done by brute force when the directory
647                  * is first encountered.  If the tree gets deep enough or the
648                  * number of symbolic links to directories is high enough,
649                  * something faster might be worthwhile.
650                  */
651                 for (t = p->fts_parent;
652                     t->fts_level >= FTS_ROOTLEVEL; t = t->fts_parent)
653                         if (ino == t->fts_ino && dev == t->fts_dev) {
654                                 p->fts_cycle = t;
655                                 return (FTS_DC);
656                         }
657                 return (FTS_D);
658         }
659         if (S_ISLNK(sbp->st_mode))
660                 return (FTS_SL);
661         if (S_ISREG(sbp->st_mode))
662                 return (FTS_F);
663         return (FTS_DEFAULT);
664 }
665
666 static FTSENT *
667 fts_alloc(FTS *sp, const char *name, size_t namelen)
668 {
669         FTSENT *p;
670         size_t len;
671
672         len = sizeof(FTSENT) + namelen;
673         if ((p = calloc(1, len)) == NULL)
674                 return (NULL);
675
676         p->fts_path = sp->fts_path;
677         p->fts_namelen = namelen;
678         p->fts_instr = FTS_NOINSTR;
679         p->fts_statp = malloc(sizeof(struct stat));
680         if (p->fts_statp == NULL) {
681                 free(p);
682                 return (NULL);
683         }
684         memcpy(p->fts_name, name, namelen);
685
686         return (p);
687 }
688
689 static void
690 fts_lfree(FTSENT *head)
691 {
692         FTSENT *p;
693
694         /* Free a linked list of structures. */
695         while ((p = head)) {
696                 head = head->fts_link;
697                 free(p);
698         }
699 }
700
701 /*
702  * Allow essentially unlimited paths; find, rm, ls should all work on any tree.
703  * Most systems will allow creation of paths much longer than PATH_MAX, even
704  * though the kernel won't resolve them.  Add the size (not just what's needed)
705  * plus 256 bytes so don't realloc the path 2 bytes at a time.
706  */
707 static int
708 fts_palloc(FTS *sp, size_t more)
709 {
710         char *p;
711
712         /*
713          * Check for possible wraparound.
714          */
715         more += 256;
716         if (sp->fts_pathlen + more < sp->fts_pathlen) {
717                 if (sp->fts_path)
718                         free(sp->fts_path);
719                 sp->fts_path = NULL;
720                 errno = ENAMETOOLONG;
721                 return (1);
722         }
723         sp->fts_pathlen += more;
724         p = realloc(sp->fts_path, sp->fts_pathlen);
725         if (p == NULL) {
726                 if (sp->fts_path)
727                         free(sp->fts_path);
728                 sp->fts_path = NULL;
729                 return (1);
730         }
731         sp->fts_path = p;
732         return (0);
733 }
734
735 /*
736  * When the path is realloc'd, have to fix all of the pointers in structures
737  * already returned.
738  */
739 static void
740 fts_padjust(FTS *sp, FTSENT *head)
741 {
742         FTSENT *p;
743         char *addr = sp->fts_path;
744
745 #define ADJUST(p) {                                                     \
746         if ((p)->fts_accpath != (p)->fts_name) {                        \
747                 (p)->fts_accpath =                                      \
748                     (char *)addr + ((p)->fts_accpath - (p)->fts_path);  \
749         }                                                               \
750         (p)->fts_path = addr;                                           \
751 }
752         /* Adjust the current set of children. */
753         for (p = sp->fts_child; p; p = p->fts_link)
754                 ADJUST(p);
755
756         /* Adjust the rest of the tree, including the current level. */
757         for (p = head; p->fts_level >= FTS_ROOTLEVEL;) {
758                 ADJUST(p);
759                 p = p->fts_link ? p->fts_link : p->fts_parent;
760         }
761 }
762
763 static size_t
764 fts_maxarglen(char * const *argv)
765 {
766         size_t len, max;
767
768         for (max = 0; *argv; ++argv)
769                 if ((len = strlen(*argv)) > max)
770                         max = len;
771         return (max + 1);
772 }
773
774 /*
775  * Change to dir specified by fd or p->fts_accpath without getting
776  * tricked by someone changing the world out from underneath us.
777  * Assumes p->fts_dev and p->fts_ino are filled in.
778  */
779 static int
780 fts_safe_changedir(FTS *sp, FTSENT *p, int fd, const char *path)
781 {
782         int ret, oerrno, newfd;
783         struct stat sb;
784
785         newfd = fd;
786         if (ISSET(FTS_NOCHDIR))
787                 return (0);
788         if (fd < 0 && (newfd = open(path, O_RDONLY|O_DIRECTORY|O_CLOEXEC)) < 0)
789                 return (-1);
790         if (fstat(newfd, &sb)) {
791                 ret = -1;
792                 goto bail;
793         }
794         if (p->fts_dev != sb.st_dev || p->fts_ino != sb.st_ino) {
795                 errno = ENOENT;         /* disinformation */
796                 ret = -1;
797                 goto bail;
798         }
799         ret = fchdir(newfd);
800 bail:
801         oerrno = errno;
802         if (fd < 0)
803                 (void)close(newfd);
804         errno = oerrno;
805         return (ret);
806 }
807
808 #endif