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