source: rtems/cpukit/libmisc/shell/fts.c @ 3d3e22c

4.104.115
Last change on this file since 3d3e22c was 3d3e22c, checked in by Ralf Corsepius <ralf.corsepius@…>, on 04/13/10 at 04:39:47

2010-04-13 Ralf Corsépius <ralf.corsepius@…>

  • libmisc/shell/fts.c (fts_pow2): Rebase fts_pow2 on SIZEOF_SIZE_T * CHAR_BIT.
  • Property mode set to 100644
File size: 31.2 KB
Line 
1/*      $NetBSD: fts.c,v 1.40 2009/11/02 17:17:34 stacktic Exp $        */
2
3/*-
4 * Copyright (c) 1990, 1993, 1994
5 *      The Regents of the University of California.  All rights reserved.
6 *
7 * Redistribution and use in source and binary forms, with or without
8 * modification, are permitted provided that the following conditions
9 * are met:
10 * 1. Redistributions of source code must retain the above copyright
11 *    notice, this list of conditions and the following disclaimer.
12 * 2. Redistributions in binary form must reproduce the above copyright
13 *    notice, this list of conditions and the following disclaimer in the
14 *    documentation and/or other materials provided with the distribution.
15 * 3. Neither the name of the University nor the names of its contributors
16 *    may be used to endorse or promote products derived from this software
17 *    without specific prior written permission.
18 *
19 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
20 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
21 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
22 * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
23 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
24 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
25 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
26 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
27 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
28 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
29 * SUCH DAMAGE.
30 */
31
32#ifdef HAVE_CONFIG_H
33#include "config.h"
34#endif
35
36#if HAVE_NBTOOL_CONFIG_H
37#include "nbtool_config.h"
38#endif
39
40#include <sys/cdefs.h>
41#if defined(LIBC_SCCS) && !defined(lint)
42#if 0
43static char sccsid[] = "@(#)fts.c       8.6 (Berkeley) 8/14/94";
44#else
45__RCSID("$NetBSD: fts.c,v 1.40 2009/11/02 17:17:34 stacktic Exp $");
46#endif
47#endif /* LIBC_SCCS and not lint */
48
49#ifndef __rtems__
50#include "namespace.h"
51#endif
52#include <limits.h>
53#include <sys/param.h>
54#include <sys/stat.h>
55
56#include <assert.h>
57#include <dirent.h>
58#include <errno.h>
59#include <fcntl.h>
60#include <fts.h>
61#include <stdlib.h>
62#include <string.h>
63#include <unistd.h>
64
65#define _DIAGASSERT(a)
66#undef FTS_WHITEOUT
67#define dirfd(dp)  __dirfd(dp)
68
69#if ! HAVE_NBTOOL_CONFIG_H
70#define HAVE_STRUCT_DIRENT_D_NAMLEN
71#endif
72
73static FTSENT   *fts_alloc(FTS *, const char *, size_t);
74static FTSENT   *fts_build(FTS *, int);
75static void      fts_free(FTSENT *);
76static void      fts_lfree(FTSENT *);
77static void      fts_load(FTS *, FTSENT *);
78static size_t    fts_maxarglen(char * const *);
79static size_t    fts_pow2(size_t);
80static int       fts_palloc(FTS *, size_t);
81static void      fts_padjust(FTS *, FTSENT *);
82static FTSENT   *fts_sort(FTS *, FTSENT *, size_t);
83static unsigned short fts_stat(FTS *, FTSENT *, int);
84static int       fts_safe_changedir(const FTS *, const FTSENT *, int,
85    const char *);
86
87#if defined(ALIGNBYTES) && defined(ALIGN)
88#define FTS_ALLOC_ALIGNED       1
89#else
90#undef  FTS_ALLOC_ALIGNED
91#endif
92
93#define ISDOT(a)        (a[0] == '.' && (!a[1] || (a[1] == '.' && !a[2])))
94
95#define CLR(opt)        (sp->fts_options &= ~(opt))
96#define ISSET(opt)      (sp->fts_options & (opt))
97#define SET(opt)        (sp->fts_options |= (opt))
98
99#define CHDIR(sp, path) (!ISSET(FTS_NOCHDIR) && chdir(path))
100#define FCHDIR(sp, fd)  (!ISSET(FTS_NOCHDIR) && fchdir(fd))
101
102/* fts_build flags */
103#define BCHILD          1               /* fts_children */
104#define BNAMES          2               /* fts_children, names only */
105#define BREAD           3               /* fts_read */
106
107#ifndef DTF_HIDEW
108#undef FTS_WHITEOUT
109#endif
110
111FTS *
112fts_open(char * const *argv, int options,
113    int (*compar)(const FTSENT **, const FTSENT **))
114{
115        FTS *sp;
116        FTSENT *p, *root;
117        size_t nitems;
118        FTSENT *parent, *tmp = NULL;    /* pacify gcc */
119        size_t len;
120
121        _DIAGASSERT(argv != NULL);
122
123        /* Options check. */
124        if (options & ~FTS_OPTIONMASK) {
125                errno = EINVAL;
126                return (NULL);
127        }
128
129        /* Allocate/initialize the stream */
130        if ((sp = malloc((unsigned int)sizeof(FTS))) == NULL)
131                return (NULL);
132        memset(sp, 0, sizeof(FTS));
133        sp->fts_compar = compar;
134        sp->fts_options = options;
135
136        /* Logical walks turn on NOCHDIR; symbolic links are too hard. */
137        if (ISSET(FTS_LOGICAL))
138                SET(FTS_NOCHDIR);
139
140        /*
141         * Start out with 1K of path space, and enough, in any case,
142         * to hold the user's paths.
143         */
144        if (fts_palloc(sp, MAX(fts_maxarglen(argv), MAXPATHLEN)))
145                goto mem1;
146
147        /* Allocate/initialize root's parent. */
148        if ((parent = fts_alloc(sp, "", 0)) == NULL)
149                goto mem2;
150        parent->fts_level = FTS_ROOTPARENTLEVEL;
151
152        /* Allocate/initialize root(s). */
153        for (root = NULL, nitems = 0; *argv; ++argv, ++nitems) {
154                /* Don't allow zero-length paths. */
155                if ((len = strlen(*argv)) == 0) {
156                        errno = ENOENT;
157                        goto mem3;
158                }
159
160                if ((p = fts_alloc(sp, *argv, len)) == NULL)
161                        goto mem3;
162                p->fts_level = FTS_ROOTLEVEL;
163                p->fts_parent = parent;
164                p->fts_accpath = p->fts_name;
165                p->fts_info = fts_stat(sp, p, ISSET(FTS_COMFOLLOW));
166
167                /* Command-line "." and ".." are real directories. */
168                if (p->fts_info == FTS_DOT)
169                        p->fts_info = FTS_D;
170
171                /*
172                 * If comparison routine supplied, traverse in sorted
173                 * order; otherwise traverse in the order specified.
174                 */
175                if (compar) {
176                        p->fts_link = root;
177                        root = p;
178                } else {
179                        p->fts_link = NULL;
180                        if (root == NULL)
181                                tmp = root = p;
182                        else {
183                                tmp->fts_link = p;
184                                tmp = p;
185                        }
186                }
187        }
188        if (compar && nitems > 1)
189                root = fts_sort(sp, root, nitems);
190
191        /*
192         * Allocate a dummy pointer and make fts_read think that we've just
193         * finished the node before the root(s); set p->fts_info to FTS_INIT
194         * so that everything about the "current" node is ignored.
195         */
196        if ((sp->fts_cur = fts_alloc(sp, "", 0)) == NULL)
197                goto mem3;
198        sp->fts_cur->fts_link = root;
199        sp->fts_cur->fts_info = FTS_INIT;
200
201        /*
202         * If using chdir(2), grab a file descriptor pointing to dot to insure
203         * that we can get back here; this could be avoided for some paths,
204         * but almost certainly not worth the effort.  Slashes, symbolic links,
205         * and ".." are all fairly nasty problems.  Note, if we can't get the
206         * descriptor we run anyway, just more slowly.
207         */
208        if (!ISSET(FTS_NOCHDIR)) {
209                if ((sp->fts_rfd = open(".", O_RDONLY, 0)) == -1)
210                        SET(FTS_NOCHDIR);
211                else if (fcntl(sp->fts_rfd, F_SETFD, FD_CLOEXEC) == -1) {
212                        close(sp->fts_rfd);
213                        SET(FTS_NOCHDIR);
214                }
215        }
216
217        if (nitems == 0)
218                fts_free(parent);
219
220        return (sp);
221
222mem3:   fts_lfree(root);
223        fts_free(parent);
224mem2:   free(sp->fts_path);
225mem1:   free(sp);
226        return (NULL);
227}
228
229static void
230fts_load(FTS *sp, FTSENT *p)
231{
232        size_t len;
233        char *cp;
234
235        _DIAGASSERT(sp != NULL);
236        _DIAGASSERT(p != NULL);
237
238        /*
239         * Load the stream structure for the next traversal.  Since we don't
240         * actually enter the directory until after the preorder visit, set
241         * the fts_accpath field specially so the chdir gets done to the right
242         * place and the user can access the first node.  From fts_open it's
243         * known that the path will fit.
244         */
245        len = p->fts_pathlen = p->fts_namelen;
246        memmove(sp->fts_path, p->fts_name, len + 1);
247        if ((cp = strrchr(p->fts_name, '/')) && (cp != p->fts_name || cp[1])) {
248                len = strlen(++cp);
249                memmove(p->fts_name, cp, len + 1);
250                p->fts_namelen = len;
251        }
252        p->fts_accpath = p->fts_path = sp->fts_path;
253        sp->fts_dev = p->fts_dev;
254}
255
256int
257fts_close(FTS *sp)
258{
259        FTSENT *freep, *p;
260        int saved_errno = 0;
261
262        _DIAGASSERT(sp != NULL);
263
264        /*
265         * This still works if we haven't read anything -- the dummy structure
266         * points to the root list, so we step through to the end of the root
267         * list which has a valid parent pointer.
268         */
269        if (sp->fts_cur) {
270                if (sp->fts_cur->fts_flags & FTS_SYMFOLLOW)
271                        (void)close(sp->fts_cur->fts_symfd);
272                for (p = sp->fts_cur; p->fts_level >= FTS_ROOTLEVEL;) {
273                        freep = p;
274                        p = p->fts_link ? p->fts_link : p->fts_parent;
275                        fts_free(freep);
276                }
277                fts_free(p);
278        }
279
280        /* Free up child linked list, sort array, path buffer. */
281        if (sp->fts_child)
282                fts_lfree(sp->fts_child);
283        if (sp->fts_array)
284                free(sp->fts_array);
285        free(sp->fts_path);
286
287        /* Return to original directory, save errno if necessary. */
288        if (!ISSET(FTS_NOCHDIR)) {
289                if (fchdir(sp->fts_rfd) == -1)
290                        saved_errno = errno;
291                (void)close(sp->fts_rfd);
292        }
293
294        /* Free up the stream pointer. */
295        free(sp);
296        if (saved_errno) {
297                errno = saved_errno;
298                return -1;
299        }
300
301        return 0;
302}
303
304#if !defined(__FTS_COMPAT_TAILINGSLASH)
305
306/*
307 * Special case of "/" at the end of the path so that slashes aren't
308 * appended which would cause paths to be written as "....//foo".
309 */
310#define NAPPEND(p)                                                      \
311        (p->fts_path[p->fts_pathlen - 1] == '/'                         \
312            ? p->fts_pathlen - 1 : p->fts_pathlen)
313
314#else /* !defined(__FTS_COMPAT_TAILINGSLASH) */
315
316/*
317 * compatibility with the old behaviour.
318 *
319 * Special case a root of "/" so that slashes aren't appended which would
320 * cause paths to be written as "//foo".
321 */
322
323#define NAPPEND(p)                                                      \
324        (p->fts_level == FTS_ROOTLEVEL && p->fts_pathlen == 1 &&        \
325            p->fts_path[0] == '/' ? 0 : p->fts_pathlen)
326
327#endif /* !defined(__FTS_COMPAT_TAILINGSLASH) */
328
329FTSENT *
330fts_read(FTS *sp)
331{
332        FTSENT *p, *tmp;
333        int instr;
334        char *t;
335        int saved_errno;
336
337        _DIAGASSERT(sp != NULL);
338
339        /* If finished or unrecoverable error, return NULL. */
340        if (sp->fts_cur == NULL || ISSET(FTS_STOP))
341                return (NULL);
342
343        /* Set current node pointer. */
344        p = sp->fts_cur;
345
346        /* Save and zero out user instructions. */
347        instr = p->fts_instr;
348        p->fts_instr = FTS_NOINSTR;
349
350        /* Any type of file may be re-visited; re-stat and re-turn. */
351        if (instr == FTS_AGAIN) {
352                p->fts_info = fts_stat(sp, p, 0);
353                return (p);
354        }
355
356        /*
357         * Following a symlink -- SLNONE test allows application to see
358         * SLNONE and recover.  If indirecting through a symlink, have
359         * keep a pointer to current location.  If unable to get that
360         * pointer, follow fails.
361         */
362        if (instr == FTS_FOLLOW &&
363            (p->fts_info == FTS_SL || p->fts_info == FTS_SLNONE)) {
364                p->fts_info = fts_stat(sp, p, 1);
365                if (p->fts_info == FTS_D && !ISSET(FTS_NOCHDIR)) {
366                        if ((p->fts_symfd = open(".", O_RDONLY, 0)) == -1) {
367                                p->fts_errno = errno;
368                                p->fts_info = FTS_ERR;
369                        } else if (fcntl(p->fts_symfd, F_SETFD, FD_CLOEXEC) == -1) {
370                                p->fts_errno = errno;
371                                p->fts_info = FTS_ERR;
372                                close(p->fts_symfd);
373                        } else
374                                p->fts_flags |= FTS_SYMFOLLOW;
375                }
376                return (p);
377        }
378
379        /* Directory in pre-order. */
380        if (p->fts_info == FTS_D) {
381                /* If skipped or crossed mount point, do post-order visit. */
382                if (instr == FTS_SKIP ||
383                    (ISSET(FTS_XDEV) && p->fts_dev != sp->fts_dev)) {
384                        if (p->fts_flags & FTS_SYMFOLLOW)
385                                (void)close(p->fts_symfd);
386                        if (sp->fts_child) {
387                                fts_lfree(sp->fts_child);
388                                sp->fts_child = NULL;
389                        }
390                        p->fts_info = FTS_DP;
391                        return (p);
392                }
393
394                /* Rebuild if only read the names and now traversing. */
395                if (sp->fts_child && ISSET(FTS_NAMEONLY)) {
396                        CLR(FTS_NAMEONLY);
397                        fts_lfree(sp->fts_child);
398                        sp->fts_child = NULL;
399                }
400
401                /*
402                 * Cd to the subdirectory.
403                 *
404                 * If have already read and now fail to chdir, whack the list
405                 * to make the names come out right, and set the parent errno
406                 * so the application will eventually get an error condition.
407                 * Set the FTS_DONTCHDIR flag so that when we logically change
408                 * directories back to the parent we don't do a chdir.
409                 *
410                 * If haven't read do so.  If the read fails, fts_build sets
411                 * FTS_STOP or the fts_info field of the node.
412                 */
413                if (sp->fts_child) {
414                        if (fts_safe_changedir(sp, p, -1, p->fts_accpath)) {
415                                p->fts_errno = errno;
416                                p->fts_flags |= FTS_DONTCHDIR;
417                                for (p = sp->fts_child; p; p = p->fts_link)
418                                        p->fts_accpath =
419                                            p->fts_parent->fts_accpath;
420                        }
421                } else if ((sp->fts_child = fts_build(sp, BREAD)) == NULL) {
422                        if (ISSET(FTS_STOP))
423                                return (NULL);
424                        return (p);
425                }
426                p = sp->fts_child;
427                sp->fts_child = NULL;
428                goto name;
429        }
430
431        /* Move to the next node on this level. */
432next:   tmp = p;
433        if ((p = p->fts_link) != NULL) {
434                fts_free(tmp);
435
436                /*
437                 * If reached the top, return to the original directory, and
438                 * load the paths for the next root.
439                 */
440                if (p->fts_level == FTS_ROOTLEVEL) {
441                        if (FCHDIR(sp, sp->fts_rfd)) {
442                                SET(FTS_STOP);
443                                return (NULL);
444                        }
445                        fts_load(sp, p);
446                        return (sp->fts_cur = p);
447                }
448
449                /*
450                 * User may have called fts_set on the node.  If skipped,
451                 * ignore.  If followed, get a file descriptor so we can
452                 * get back if necessary.
453                 */
454                if (p->fts_instr == FTS_SKIP)
455                        goto next;
456                if (p->fts_instr == FTS_FOLLOW) {
457                        p->fts_info = fts_stat(sp, p, 1);
458                        if (p->fts_info == FTS_D && !ISSET(FTS_NOCHDIR)) {
459                                if ((p->fts_symfd =
460                                    open(".", O_RDONLY, 0)) == -1) {
461                                        p->fts_errno = errno;
462                                        p->fts_info = FTS_ERR;
463                                } else if (fcntl(p->fts_symfd, F_SETFD, FD_CLOEXEC) == -1) {
464                                        p->fts_errno = errno;
465                                        p->fts_info = FTS_ERR;
466                                        close(p->fts_symfd);
467                                } else
468                                        p->fts_flags |= FTS_SYMFOLLOW;
469                        }
470                        p->fts_instr = FTS_NOINSTR;
471                }
472
473name:           t = sp->fts_path + NAPPEND(p->fts_parent);
474                *t++ = '/';
475                memmove(t, p->fts_name, (size_t)(p->fts_namelen + 1));
476                return (sp->fts_cur = p);
477        }
478
479        /* Move up to the parent node. */
480        p = tmp->fts_parent;
481        fts_free(tmp);
482
483        if (p->fts_level == FTS_ROOTPARENTLEVEL) {
484                /*
485                 * Done; free everything up and set errno to 0 so the user
486                 * can distinguish between error and EOF.
487                 */
488                fts_free(p);
489                errno = 0;
490                return (sp->fts_cur = NULL);
491        }
492
493        /* Nul terminate the pathname. */
494        sp->fts_path[p->fts_pathlen] = '\0';
495
496        /*
497         * Return to the parent directory.  If at a root node or came through
498         * a symlink, go back through the file descriptor.  Otherwise, cd up
499         * one directory.
500         */
501        if (p->fts_level == FTS_ROOTLEVEL) {
502                if (FCHDIR(sp, sp->fts_rfd)) {
503                        SET(FTS_STOP);
504                        return (NULL);
505                }
506        } else if (p->fts_flags & FTS_SYMFOLLOW) {
507                if (FCHDIR(sp, p->fts_symfd)) {
508                        saved_errno = errno;
509                        (void)close(p->fts_symfd);
510                        errno = saved_errno;
511                        SET(FTS_STOP);
512                        return (NULL);
513                }
514                (void)close(p->fts_symfd);
515        } else if (!(p->fts_flags & FTS_DONTCHDIR) &&
516            fts_safe_changedir(sp, p->fts_parent, -1, "..")) {
517                SET(FTS_STOP);
518                return (NULL);
519        }
520        p->fts_info = p->fts_errno ? FTS_ERR : FTS_DP;
521        return (sp->fts_cur = p);
522}
523
524/*
525 * Fts_set takes the stream as an argument although it's not used in this
526 * implementation; it would be necessary if anyone wanted to add global
527 * semantics to fts using fts_set.  An error return is allowed for similar
528 * reasons.
529 */
530/* ARGSUSED */
531int
532fts_set(FTS *sp, FTSENT *p, int instr)
533{
534
535        _DIAGASSERT(sp != NULL);
536        _DIAGASSERT(p != NULL);
537
538        if (instr && instr != FTS_AGAIN && instr != FTS_FOLLOW &&
539            instr != FTS_NOINSTR && instr != FTS_SKIP) {
540                errno = EINVAL;
541                return (1);
542        }
543        p->fts_instr = instr;
544        return (0);
545}
546
547FTSENT *
548fts_children(FTS *sp, int instr)
549{
550        FTSENT *p;
551        int fd;
552
553        _DIAGASSERT(sp != NULL);
554
555        if (instr && instr != FTS_NAMEONLY) {
556                errno = EINVAL;
557                return (NULL);
558        }
559
560        /* Set current node pointer. */
561        p = sp->fts_cur;
562
563        /*
564         * Errno set to 0 so user can distinguish empty directory from
565         * an error.
566         */
567        errno = 0;
568
569        /* Fatal errors stop here. */
570        if (ISSET(FTS_STOP))
571                return (NULL);
572
573        /* Return logical hierarchy of user's arguments. */
574        if (p->fts_info == FTS_INIT)
575                return (p->fts_link);
576
577        /*
578         * If not a directory being visited in pre-order, stop here.  Could
579         * allow FTS_DNR, assuming the user has fixed the problem, but the
580         * same effect is available with FTS_AGAIN.
581         */
582        if (p->fts_info != FTS_D /* && p->fts_info != FTS_DNR */)
583                return (NULL);
584
585        /* Free up any previous child list. */
586        if (sp->fts_child)
587                fts_lfree(sp->fts_child);
588
589        if (instr == FTS_NAMEONLY) {
590                SET(FTS_NAMEONLY);
591                instr = BNAMES;
592        } else
593                instr = BCHILD;
594
595        /*
596         * If using chdir on a relative path and called BEFORE fts_read does
597         * its chdir to the root of a traversal, we can lose -- we need to
598         * chdir into the subdirectory, and we don't know where the current
599         * directory is, so we can't get back so that the upcoming chdir by
600         * fts_read will work.
601         */
602        if (p->fts_level != FTS_ROOTLEVEL || p->fts_accpath[0] == '/' ||
603            ISSET(FTS_NOCHDIR))
604                return (sp->fts_child = fts_build(sp, instr));
605
606        if ((fd = open(".", O_RDONLY, 0)) == -1)
607                return (sp->fts_child = NULL);
608        sp->fts_child = fts_build(sp, instr);
609        if (fchdir(fd)) {
610                (void)close(fd);
611                return (NULL);
612        }
613        (void)close(fd);
614        return (sp->fts_child);
615}
616
617/*
618 * This is the tricky part -- do not casually change *anything* in here.  The
619 * idea is to build the linked list of entries that are used by fts_children
620 * and fts_read.  There are lots of special cases.
621 *
622 * The real slowdown in walking the tree is the stat calls.  If FTS_NOSTAT is
623 * set and it's a physical walk (so that symbolic links can't be directories),
624 * we can do things quickly.  First, if it's a 4.4BSD file system, the type
625 * of the file is in the directory entry.  Otherwise, we assume that the number
626 * of subdirectories in a node is equal to the number of links to the parent.
627 * The former skips all stat calls.  The latter skips stat calls in any leaf
628 * directories and for any files after the subdirectories in the directory have
629 * been found, cutting the stat calls by about 2/3.
630 */
631static FTSENT *
632fts_build(FTS *sp, int type)
633{
634        struct dirent *dp;
635        FTSENT *p, *head;
636        size_t nitems;
637        FTSENT *cur, *tail;
638        DIR *dirp;
639        void *oldaddr;
640        size_t dnamlen;
641        int cderrno, descend, level, nlinks, saved_errno, nostat, doadjust;
642        size_t len, maxlen;
643#ifdef FTS_WHITEOUT
644        int oflag;
645#endif
646        char *cp = NULL;        /* pacify gcc */
647
648        _DIAGASSERT(sp != NULL);
649
650        /* Set current node pointer. */
651        cur = sp->fts_cur;
652
653        /*
654         * Open the directory for reading.  If this fails, we're done.
655         * If being called from fts_read, set the fts_info field.
656         */
657#ifdef FTS_WHITEOUT
658        if (ISSET(FTS_WHITEOUT))
659                oflag = DTF_NODUP|DTF_REWIND;
660        else
661                oflag = DTF_HIDEW|DTF_NODUP|DTF_REWIND;
662#else
663#define __opendir2(path, flag) opendir(path)
664#endif
665        if ((dirp = __opendir2(cur->fts_accpath, oflag)) == NULL) {
666                if (type == BREAD) {
667                        cur->fts_info = FTS_DNR;
668                        cur->fts_errno = errno;
669                }
670                return (NULL);
671        }
672
673        /*
674         * Nlinks is the number of possible entries of type directory in the
675         * directory if we're cheating on stat calls, 0 if we're not doing
676         * any stat calls at all, -1 if we're doing stats on everything.
677         */
678        if (type == BNAMES) {
679                nlinks = 0;
680                nostat = 1;
681        } else if (ISSET(FTS_NOSTAT) && ISSET(FTS_PHYSICAL)) {
682                nlinks = cur->fts_nlink - (ISSET(FTS_SEEDOT) ? 0 : 2);
683                nostat = 1;
684        } else {
685                nlinks = -1;
686                nostat = 0;
687        }
688
689#ifdef notdef
690        (void)printf("nlinks == %d (cur: %d)\n", nlinks, cur->fts_nlink);
691        (void)printf("NOSTAT %d PHYSICAL %d SEEDOT %d\n",
692            ISSET(FTS_NOSTAT), ISSET(FTS_PHYSICAL), ISSET(FTS_SEEDOT));
693#endif
694        /*
695         * If we're going to need to stat anything or we want to descend
696         * and stay in the directory, chdir.  If this fails we keep going,
697         * but set a flag so we don't chdir after the post-order visit.
698         * We won't be able to stat anything, but we can still return the
699         * names themselves.  Note, that since fts_read won't be able to
700         * chdir into the directory, it will have to return different path
701         * names than before, i.e. "a/b" instead of "b".  Since the node
702         * has already been visited in pre-order, have to wait until the
703         * post-order visit to return the error.  There is a special case
704         * here, if there was nothing to stat then it's not an error to
705         * not be able to stat.  This is all fairly nasty.  If a program
706         * needed sorted entries or stat information, they had better be
707         * checking FTS_NS on the returned nodes.
708         */
709        cderrno = 0;
710        if (nlinks || type == BREAD) {
711                if (fts_safe_changedir(sp, cur, dirfd(dirp), NULL)) {
712                        if (nlinks && type == BREAD)
713                                cur->fts_errno = errno;
714                        cur->fts_flags |= FTS_DONTCHDIR;
715                        descend = 0;
716                        cderrno = errno;
717                } else
718                        descend = 1;
719        } else
720                descend = 0;
721
722        /*
723         * Figure out the max file name length that can be stored in the
724         * current path -- the inner loop allocates more path as necessary.
725         * We really wouldn't have to do the maxlen calculations here, we
726         * could do them in fts_read before returning the path, but it's a
727         * lot easier here since the length is part of the dirent structure.
728         *
729         * If not changing directories set a pointer so that can just append
730         * each new name into the path.
731         */
732        len = NAPPEND(cur);
733        if (ISSET(FTS_NOCHDIR)) {
734                cp = sp->fts_path + len;
735                *cp++ = '/';
736        }
737        len++;
738        maxlen = sp->fts_pathlen - len;
739
740#if defined(__FTS_COMPAT_LEVEL)
741        if (cur->fts_level == SHRT_MAX) {
742                (void)closedir(dirp);
743                cur->fts_info = FTS_ERR;
744                SET(FTS_STOP);
745                errno = ENAMETOOLONG;
746                return (NULL);
747        }
748#endif
749
750        level = cur->fts_level + 1;
751
752        /* Read the directory, attaching each entry to the `link' pointer. */
753        doadjust = 0;
754        for (head = tail = NULL, nitems = 0; (dp = readdir(dirp)) != NULL;) {
755
756                if (!ISSET(FTS_SEEDOT) && ISDOT(dp->d_name))
757                        continue;
758
759#if defined(HAVE_STRUCT_DIRENT_D_NAMLEN)
760                dnamlen = dp->d_namlen;
761#else
762                dnamlen = strlen(dp->d_name);
763#endif
764                if ((p = fts_alloc(sp, dp->d_name, dnamlen)) == NULL)
765                        goto mem1;
766                if (dnamlen >= maxlen) {        /* include space for NUL */
767                        oldaddr = sp->fts_path;
768                        if (fts_palloc(sp, dnamlen + len + 1)) {
769                                /*
770                                 * No more memory for path or structures.  Save
771                                 * errno, free up the current structure and the
772                                 * structures already allocated.
773                                 */
774mem1:                           saved_errno = errno;
775                                if (p)
776                                        fts_free(p);
777                                fts_lfree(head);
778                                (void)closedir(dirp);
779                                errno = saved_errno;
780                                cur->fts_info = FTS_ERR;
781                                SET(FTS_STOP);
782                                return (NULL);
783                        }
784                        /* Did realloc() change the pointer? */
785                        if (oldaddr != sp->fts_path) {
786                                doadjust = 1;
787                                if (ISSET(FTS_NOCHDIR))
788                                        cp = sp->fts_path + len;
789                        }
790                        maxlen = sp->fts_pathlen - len;
791                }
792
793#if defined(__FTS_COMPAT_LENGTH)
794                if (len + dnamlen >= USHRT_MAX) {
795                        /*
796                         * In an FTSENT, fts_pathlen is an unsigned short
797                         * so it is possible to wraparound here.
798                         * If we do, free up the current structure and the
799                         * structures already allocated, then error out
800                         * with ENAMETOOLONG.
801                         */
802                        fts_free(p);
803                        fts_lfree(head);
804                        (void)closedir(dirp);
805                        cur->fts_info = FTS_ERR;
806                        SET(FTS_STOP);
807                        errno = ENAMETOOLONG;
808                        return (NULL);
809                }
810#endif
811                p->fts_level = level;
812                p->fts_pathlen = len + dnamlen;
813                p->fts_parent = sp->fts_cur;
814
815#ifdef FTS_WHITEOUT
816                if (dp->d_type == DT_WHT)
817                        p->fts_flags |= FTS_ISW;
818#endif
819
820                if (cderrno) {
821                        if (nlinks) {
822                                p->fts_info = FTS_NS;
823                                p->fts_errno = cderrno;
824                        } /* else
825                                p->fts_info = FTS_NSOK;
826                                */
827                                /* Coverity Scan Id 1 says above is dead code */
828                        p->fts_accpath = cur->fts_accpath;
829                } else if (nlinks == 0
830#ifdef DT_DIR
831                    || (nostat &&
832                    dp->d_type != DT_DIR && dp->d_type != DT_UNKNOWN)
833#endif
834                    ) {
835                        p->fts_accpath =
836                            ISSET(FTS_NOCHDIR) ? p->fts_path : p->fts_name;
837                        p->fts_info = FTS_NSOK;
838                } else {
839                        /* Build a file name for fts_stat to stat. */
840                        if (ISSET(FTS_NOCHDIR)) {
841                                p->fts_accpath = p->fts_path;
842                                memmove(cp, p->fts_name,
843                                        (size_t)(p->fts_namelen + 1));
844                        } else
845                                p->fts_accpath = p->fts_name;
846                        /* Stat it. */
847                        p->fts_info = fts_stat(sp, p, 0);
848
849                        /* Decrement link count if applicable. */
850                        if (nlinks > 0 && (p->fts_info == FTS_D ||
851                            p->fts_info == FTS_DC || p->fts_info == FTS_DOT))
852                                --nlinks;
853                }
854
855                /* We walk in directory order so "ls -f" doesn't get upset. */
856                p->fts_link = NULL;
857                if (head == NULL)
858                        head = tail = p;
859                else {
860                        tail->fts_link = p;
861                        tail = p;
862                }
863                ++nitems;
864        }
865        (void)closedir(dirp);
866
867        /*
868         * If had to realloc the path, adjust the addresses for the rest
869         * of the tree.
870         */
871        if (doadjust)
872                fts_padjust(sp, head);
873
874        /*
875         * If not changing directories, reset the path back to original
876         * state.
877         */
878        if (ISSET(FTS_NOCHDIR)) {
879                if (len == sp->fts_pathlen || nitems == 0)
880                        --cp;
881                *cp = '\0';
882        }
883
884        /*
885         * If descended after called from fts_children or after called from
886         * fts_read and nothing found, get back.  At the root level we use
887         * the saved fd; if one of fts_open()'s arguments is a relative path
888         * to an empty directory, we wind up here with no other way back.  If
889         * can't get back, we're done.
890         */
891        if (descend && (type == BCHILD || !nitems) &&
892            (cur->fts_level == FTS_ROOTLEVEL ?
893            FCHDIR(sp, sp->fts_rfd) :
894            fts_safe_changedir(sp, cur->fts_parent, -1, ".."))) {
895                cur->fts_info = FTS_ERR;
896                SET(FTS_STOP);
897                return (NULL);
898        }
899
900        /* If didn't find anything, return NULL. */
901        if (!nitems) {
902                if (type == BREAD)
903                        cur->fts_info = FTS_DP;
904                return (NULL);
905        }
906
907        /* Sort the entries. */
908        if (sp->fts_compar && nitems > 1)
909                head = fts_sort(sp, head, nitems);
910        return (head);
911}
912
913static unsigned short
914fts_stat(FTS *sp, FTSENT *p, int follow)
915{
916        FTSENT *t;
917        dev_t dev;
918        __fts_ino_t ino;
919        __fts_stat_t *sbp, sb;
920        int saved_errno;
921
922        _DIAGASSERT(sp != NULL);
923        _DIAGASSERT(p != NULL);
924
925        /* If user needs stat info, stat buffer already allocated. */
926        sbp = ISSET(FTS_NOSTAT) ? &sb : p->fts_statp;
927
928#ifdef FTS_WHITEOUT
929        /* check for whiteout */
930        if (p->fts_flags & FTS_ISW) {
931                if (sbp != &sb) {
932                        memset(sbp, '\0', sizeof (*sbp));
933                        sbp->st_mode = S_IFWHT;
934                }
935                return (FTS_W);
936        }
937#endif
938
939        /*
940         * If doing a logical walk, or application requested FTS_FOLLOW, do
941         * a stat(2).  If that fails, check for a non-existent symlink.  If
942         * fail, set the errno from the stat call.
943         */
944        if (ISSET(FTS_LOGICAL) || follow) {
945                if (stat(p->fts_accpath, sbp)) {
946                        saved_errno = errno;
947                        if (!lstat(p->fts_accpath, sbp)) {
948                                errno = 0;
949                                return (FTS_SLNONE);
950                        }
951                        p->fts_errno = saved_errno;
952                        goto err;
953                }
954        } else if (lstat(p->fts_accpath, sbp)) {
955                p->fts_errno = errno;
956err:            memset(sbp, 0, sizeof(*sbp));
957                return (FTS_NS);
958        }
959
960        if (S_ISDIR(sbp->st_mode)) {
961                /*
962                 * Set the device/inode.  Used to find cycles and check for
963                 * crossing mount points.  Also remember the link count, used
964                 * in fts_build to limit the number of stat calls.  It is
965                 * understood that these fields are only referenced if fts_info
966                 * is set to FTS_D.
967                 */
968                dev = p->fts_dev = sbp->st_dev;
969                ino = p->fts_ino = sbp->st_ino;
970                p->fts_nlink = sbp->st_nlink;
971
972                if (ISDOT(p->fts_name))
973                        return (FTS_DOT);
974
975                /*
976                 * Cycle detection is done by brute force when the directory
977                 * is first encountered.  If the tree gets deep enough or the
978                 * number of symbolic links to directories is high enough,
979                 * something faster might be worthwhile.
980                 */
981                for (t = p->fts_parent;
982                    t->fts_level >= FTS_ROOTLEVEL; t = t->fts_parent)
983                        if (ino == t->fts_ino && dev == t->fts_dev) {
984                                p->fts_cycle = t;
985                                return (FTS_DC);
986                        }
987                return (FTS_D);
988        }
989        if (S_ISLNK(sbp->st_mode))
990                return (FTS_SL);
991        if (S_ISREG(sbp->st_mode))
992                return (FTS_F);
993        return (FTS_DEFAULT);
994}
995
996static FTSENT *
997fts_sort(FTS *sp, FTSENT *head, size_t nitems)
998{
999        FTSENT **ap, *p;
1000
1001        _DIAGASSERT(sp != NULL);
1002        _DIAGASSERT(head != NULL);
1003
1004        /*
1005         * Construct an array of pointers to the structures and call qsort(3).
1006         * Reassemble the array in the order returned by qsort.  If unable to
1007         * sort for memory reasons, return the directory entries in their
1008         * current order.  Allocate enough space for the current needs plus
1009         * 40 so don't realloc one entry at a time.
1010         */
1011        if (nitems > sp->fts_nitems) {
1012                FTSENT **new;
1013
1014                new = realloc(sp->fts_array, sizeof(FTSENT *) * (nitems + 40));
1015                if (new == 0)
1016                        return (head);
1017                sp->fts_array = new;
1018                sp->fts_nitems = nitems + 40;
1019        }
1020        for (ap = sp->fts_array, p = head; p; p = p->fts_link)
1021                *ap++ = p;
1022        qsort((void *)sp->fts_array, nitems, sizeof(FTSENT *),
1023                (int (*)(const void *, const void *))sp->fts_compar);
1024        for (head = *(ap = sp->fts_array); --nitems; ++ap)
1025                ap[0]->fts_link = ap[1];
1026        ap[0]->fts_link = NULL;
1027        return (head);
1028}
1029
1030static FTSENT *
1031fts_alloc(FTS *sp, const char *name, size_t namelen)
1032{
1033        FTSENT *p;
1034#if defined(FTS_ALLOC_ALIGNED)
1035        size_t len;
1036#endif
1037
1038        _DIAGASSERT(sp != NULL);
1039        _DIAGASSERT(name != NULL);
1040
1041#if defined(FTS_ALLOC_ALIGNED)
1042        /*
1043         * The file name is a variable length array and no stat structure is
1044         * necessary if the user has set the nostat bit.  Allocate the FTSENT
1045         * structure, the file name and the stat structure in one chunk, but
1046         * be careful that the stat structure is reasonably aligned.  Since the
1047         * fts_name field is declared to be of size 1, the fts_name pointer is
1048         * namelen + 2 before the first possible address of the stat structure.
1049         */
1050        len = sizeof(FTSENT) + namelen;
1051        if (!ISSET(FTS_NOSTAT))
1052                len += sizeof(*(p->fts_statp)) + ALIGNBYTES;
1053        if ((p = malloc(len)) == NULL)
1054                return (NULL);
1055
1056        if (!ISSET(FTS_NOSTAT))
1057                p->fts_statp = (__fts_stat_t *)ALIGN(
1058                    (unsigned long)(p->fts_name + namelen + 2));
1059#else
1060        if ((p = malloc(sizeof(FTSENT) + namelen)) == NULL)
1061                return (NULL);
1062
1063        if (!ISSET(FTS_NOSTAT))
1064                if ((p->fts_statp = malloc(sizeof(*(p->fts_statp)))) == NULL) {
1065                        free(p);
1066                        return (NULL);
1067                }
1068#endif
1069
1070        if (ISSET(FTS_NOSTAT))
1071                p->fts_statp = NULL;
1072
1073        /* Copy the name plus the trailing NULL. */
1074        memmove(p->fts_name, name, namelen + 1);
1075
1076        p->fts_namelen = namelen;
1077        p->fts_path = sp->fts_path;
1078        p->fts_errno = 0;
1079        p->fts_flags = 0;
1080        p->fts_instr = FTS_NOINSTR;
1081        p->fts_number = 0;
1082        p->fts_pointer = NULL;
1083        return (p);
1084}
1085
1086static void
1087fts_free(FTSENT *p)
1088{
1089#if !defined(FTS_ALLOC_ALIGNED)
1090        if (p->fts_statp)
1091                free(p->fts_statp);
1092#endif
1093        free(p);
1094}
1095
1096static void
1097fts_lfree(FTSENT *head)
1098{
1099        FTSENT *p;
1100
1101        /* XXX: head may be NULL ? */
1102
1103        /* Free a linked list of structures. */
1104        while ((p = head) != NULL) {
1105                head = head->fts_link;
1106                fts_free(p);
1107        }
1108}
1109
1110static size_t
1111fts_pow2(size_t x)
1112{
1113
1114        x--;
1115        x |= x>>1;
1116        x |= x>>2;
1117        x |= x>>4;
1118        x |= x>>8;
1119#if (SIZEOF_SIZE_T * CHAR_BIT) > 16
1120        x |= x>>16;
1121#endif
1122#if (SIZEOF_SIZE_T * CHAR_BIT) > 32
1123        x |= x>>32;
1124#endif
1125#if (SIZEOF_SIZE_T * CHAR_BIT) > 64
1126        x |= x>>64;
1127#endif
1128        x++;
1129        return (x);
1130}
1131
1132/*
1133 * Allow essentially unlimited paths; find, rm, ls should all work on any tree.
1134 * Most systems will allow creation of paths much longer than MAXPATHLEN, even
1135 * though the kernel won't resolve them.  Round up the new size to a power of 2,
1136 * so we don't realloc the path 2 bytes at a time.
1137 */
1138static int
1139fts_palloc(FTS *sp, size_t size)
1140{
1141        char *new;
1142
1143        _DIAGASSERT(sp != NULL);
1144
1145#ifdef __FTS_COMPAT_LENGTH
1146        /* Protect against fts_pathlen overflow. */
1147        if (size > USHRT_MAX + 1) {
1148                errno = ENAMETOOLONG;
1149                return (1);
1150        }
1151#endif
1152        size = fts_pow2(size);
1153        new = realloc(sp->fts_path, size);
1154        if (new == 0)
1155                return (1);
1156        sp->fts_path = new;
1157        sp->fts_pathlen = size;
1158        return (0);
1159}
1160
1161/*
1162 * When the path is realloc'd, have to fix all of the pointers in structures
1163 * already returned.
1164 */
1165static void
1166fts_padjust(FTS *sp, FTSENT *head)
1167{
1168        FTSENT *p;
1169        char *addr;
1170
1171        _DIAGASSERT(sp != NULL);
1172
1173#define ADJUST(p) do {                                                  \
1174        if ((p)->fts_accpath != (p)->fts_name)                          \
1175                (p)->fts_accpath =                                      \
1176                    addr + ((p)->fts_accpath - (p)->fts_path);          \
1177        (p)->fts_path = addr;                                           \
1178} while (/*CONSTCOND*/0)
1179
1180        addr = sp->fts_path;
1181
1182        /* Adjust the current set of children. */
1183        for (p = sp->fts_child; p; p = p->fts_link)
1184                ADJUST(p);
1185
1186        /* Adjust the rest of the tree, including the current level. */
1187        for (p = head; p->fts_level >= FTS_ROOTLEVEL;) {
1188                ADJUST(p);
1189                p = p->fts_link ? p->fts_link : p->fts_parent;
1190        }
1191}
1192
1193static size_t
1194fts_maxarglen(char * const *argv)
1195{
1196        size_t len, max;
1197
1198        _DIAGASSERT(argv != NULL);
1199
1200        for (max = 0; *argv; ++argv)
1201                if ((len = strlen(*argv)) > max)
1202                        max = len;
1203        return (max + 1);
1204}
1205
1206/*
1207 * Change to dir specified by fd or p->fts_accpath without getting
1208 * tricked by someone changing the world out from underneath us.
1209 * Assumes p->fts_dev and p->fts_ino are filled in.
1210 */
1211static int
1212fts_safe_changedir(const FTS *sp, const FTSENT *p, int fd, const char *path)
1213{
1214        int oldfd = fd, ret = -1;
1215        __fts_stat_t sb;
1216
1217        if (ISSET(FTS_NOCHDIR))
1218                return 0;
1219
1220        if (oldfd < 0 && (fd = open(path, O_RDONLY)) == -1)
1221                return -1;
1222
1223        if (fstat(fd, &sb) == -1)
1224                goto bail;
1225
1226        if (sb.st_ino != p->fts_ino || sb.st_dev != p->fts_dev) {
1227                errno = ENOENT;
1228                goto bail;
1229        }
1230
1231        ret = fchdir(fd);
1232
1233bail:
1234        if (oldfd < 0) {
1235                int save_errno = errno;
1236                (void)close(fd);
1237                errno = save_errno;
1238        }
1239        return ret;
1240}
Note: See TracBrowser for help on using the repository browser.