673693a67175a42ee2fe133ea7cdf5a132be4d38
[gnulib.git] / lib / fts.c
1 /* Traverse a file hierarchy.
2
3    Copyright (C) 2004, 2005, 2006, 2007, 2008 Free Software Foundation, Inc.
4
5    This program is free software: you can redistribute it and/or modify
6    it under the terms of the GNU General Public License as published by
7    the Free Software Foundation; either version 3 of the License, or
8    (at your option) any later version.
9
10    This program is distributed in the hope that it will be useful,
11    but WITHOUT ANY WARRANTY; without even the implied warranty of
12    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13    GNU General Public License for more details.
14
15    You should have received a copy of the GNU General Public License
16    along with this program.  If not, see <http://www.gnu.org/licenses/>.  */
17
18 /*-
19  * Copyright (c) 1990, 1993, 1994
20  *      The Regents of the University of California.  All rights reserved.
21  *
22  * Redistribution and use in source and binary forms, with or without
23  * modification, are permitted provided that the following conditions
24  * are met:
25  * 1. Redistributions of source code must retain the above copyright
26  *    notice, this list of conditions and the following disclaimer.
27  * 2. Redistributions in binary form must reproduce the above copyright
28  *    notice, this list of conditions and the following disclaimer in the
29  *    documentation and/or other materials provided with the distribution.
30  * 4. Neither the name of the University nor the names of its contributors
31  *    may be used to endorse or promote products derived from this software
32  *    without specific prior written permission.
33  *
34  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
35  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
36  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
37  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
38  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
39  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
40  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
41  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
42  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
43  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
44  * SUCH DAMAGE.
45  */
46
47 #include <config.h>
48
49 #if defined(LIBC_SCCS) && !defined(lint)
50 static char sccsid[] = "@(#)fts.c       8.6 (Berkeley) 8/14/94";
51 #endif /* LIBC_SCCS and not lint */
52
53 #include "fts_.h"
54
55 #if HAVE_SYS_PARAM_H || defined _LIBC
56 # include <sys/param.h>
57 #endif
58 #ifdef _LIBC
59 # include <include/sys/stat.h>
60 #else
61 # include <sys/stat.h>
62 #endif
63 #include <fcntl.h>
64 #include <errno.h>
65 #include "dirfd.h"
66 #include <stdbool.h>
67 #include <stdlib.h>
68 #include <string.h>
69 #include <unistd.h>
70
71 #if ! _LIBC
72 # include "fcntl--.h"
73 # include "lstat.h"
74 # include "openat.h"
75 # include "unistd--.h"
76 # include "same-inode.h"
77 #endif
78
79 #include <dirent.h>
80 #ifndef _D_EXACT_NAMLEN
81 # define _D_EXACT_NAMLEN(dirent) strlen ((dirent)->d_name)
82 #endif
83
84 #if HAVE_STRUCT_DIRENT_D_TYPE
85 /* True if the type of the directory entry D is known.  */
86 # define DT_IS_KNOWN(d) ((d)->d_type != DT_UNKNOWN)
87 /* True if the type of the directory entry D must be T.  */
88 # define DT_MUST_BE(d, t) ((d)->d_type == (t))
89 #else
90 # define DT_IS_KNOWN(d) false
91 # define DT_MUST_BE(d, t) false
92 #endif
93
94 enum
95 {
96   NOT_AN_INODE_NUMBER = 0
97 };
98
99 #ifdef D_INO_IN_DIRENT
100 # define D_INO(dp) (dp)->d_ino
101 #else
102 /* Some systems don't have inodes, so fake them to avoid lots of ifdefs.  */
103 # define D_INO(dp) NOT_AN_INODE_NUMBER
104 #endif
105
106 /* If there are more than this many entries in a directory,
107    and the conditions mentioned below are satisfied, then sort
108    the entries on inode number before any further processing.  */
109 #ifndef FTS_INODE_SORT_DIR_ENTRIES_THRESHOLD
110 # define FTS_INODE_SORT_DIR_ENTRIES_THRESHOLD 10000
111 #endif
112 enum
113 {
114   _FTS_INODE_SORT_DIR_ENTRIES_THRESHOLD = FTS_INODE_SORT_DIR_ENTRIES_THRESHOLD
115 };
116
117 enum Fts_stat
118 {
119   FTS_NO_STAT_REQUIRED = 1,
120   FTS_STAT_REQUIRED = 2
121 };
122
123 #ifdef _LIBC
124 # undef close
125 # define close __close
126 # undef closedir
127 # define closedir __closedir
128 # undef fchdir
129 # define fchdir __fchdir
130 # undef open
131 # define open __open
132 # undef opendir
133 # define opendir __opendir
134 # undef readdir
135 # define readdir __readdir
136 #else
137 # undef internal_function
138 # define internal_function /* empty */
139 #endif
140
141 #ifndef __set_errno
142 # define __set_errno(Val) errno = (Val)
143 #endif
144
145 #ifndef __attribute__
146 # if __GNUC__ < 2 || (__GNUC__ == 2 && __GNUC_MINOR__ < 8)
147 #  define __attribute__(x) /* empty */
148 # endif
149 #endif
150
151 #ifndef ATTRIBUTE_UNUSED
152 # define ATTRIBUTE_UNUSED __attribute__ ((__unused__))
153 #endif
154
155 /* If this host provides the openat function, then we can avoid
156    attempting to open "." in some initialization code below.  */
157 #ifdef HAVE_OPENAT
158 # define HAVE_OPENAT_SUPPORT 1
159 #else
160 # define HAVE_OPENAT_SUPPORT 0
161 #endif
162
163 #ifdef NDEBUG
164 # define fts_assert(expr) ((void) 0)
165 #else
166 # define fts_assert(expr)       \
167     do                          \
168       {                         \
169         if (!(expr))            \
170           abort ();             \
171       }                         \
172     while (false)
173 #endif
174
175 static FTSENT   *fts_alloc (FTS *, const char *, size_t) internal_function;
176 static FTSENT   *fts_build (FTS *, int) internal_function;
177 static void      fts_lfree (FTSENT *) internal_function;
178 static void      fts_load (FTS *, FTSENT *) internal_function;
179 static size_t    fts_maxarglen (char * const *) internal_function;
180 static void      fts_padjust (FTS *, FTSENT *) internal_function;
181 static bool      fts_palloc (FTS *, size_t) internal_function;
182 static FTSENT   *fts_sort (FTS *, FTSENT *, size_t) internal_function;
183 static unsigned short int fts_stat (FTS *, FTSENT *, bool) internal_function;
184 static int      fts_safe_changedir (FTS *, FTSENT *, int, const char *)
185      internal_function;
186
187 #if GNULIB_FTS
188 # include "fts-cycle.c"
189 #else
190 static bool enter_dir (FTS *fts, FTSENT *ent) { return true; }
191 static void leave_dir (FTS *fts, FTSENT *ent) {}
192 static bool setup_dir (FTS *fts) { return true; }
193 static void free_dir (FTS *fts) {}
194 #endif
195
196 #ifndef MAX
197 # define MAX(a,b) ((a) > (b) ? (a) : (b))
198 #endif
199
200 #ifndef SIZE_MAX
201 # define SIZE_MAX ((size_t) -1)
202 #endif
203
204 #ifndef O_DIRECTORY
205 # define O_DIRECTORY 0
206 #endif
207
208 #define ISDOT(a)        (a[0] == '.' && (!a[1] || (a[1] == '.' && !a[2])))
209 #define STREQ(a, b)     (strcmp ((a), (b)) == 0)
210
211 #define CLR(opt)        (sp->fts_options &= ~(opt))
212 #define ISSET(opt)      (sp->fts_options & (opt))
213 #define SET(opt)        (sp->fts_options |= (opt))
214
215 /* FIXME: make this a function */
216 #define RESTORE_INITIAL_CWD(sp)                 \
217   (fd_ring_clear (&((sp)->fts_fd_ring)),        \
218    FCHDIR ((sp), (ISSET (FTS_CWDFD) ? AT_FDCWD : (sp)->fts_rfd)))
219
220 /* FIXME: FTS_NOCHDIR is now misnamed.
221    Call it FTS_USE_FULL_RELATIVE_FILE_NAMES instead. */
222 #define FCHDIR(sp, fd)                                  \
223   (!ISSET(FTS_NOCHDIR) && (ISSET(FTS_CWDFD)             \
224                            ? (cwd_advance_fd ((sp), (fd), true), 0) \
225                            : fchdir (fd)))
226
227
228 /* fts_build flags */
229 /* FIXME: make this an enum */
230 #define BCHILD          1               /* fts_children */
231 #define BNAMES          2               /* fts_children, names only */
232 #define BREAD           3               /* fts_read */
233
234 #if FTS_DEBUG
235 # include <inttypes.h>
236 # include <stdint.h>
237 # include <stdio.h>
238 # include "getcwdat.h"
239 bool fts_debug = false;
240 # define Dprintf(x) do { if (fts_debug) printf x; } while (false)
241 #else
242 # define Dprintf(x)
243 # define fd_ring_check(x)
244 # define fd_ring_print(a, b, c)
245 #endif
246
247 #define LEAVE_DIR(Fts, Ent, Tag)                                \
248   do                                                            \
249     {                                                           \
250       Dprintf (("  %s-leaving: %s\n", Tag, (Ent)->fts_path));   \
251       leave_dir (Fts, Ent);                                     \
252       fd_ring_check (Fts);                                      \
253     }                                                           \
254   while (false)
255
256 static void
257 fd_ring_clear (I_ring *fd_ring)
258 {
259   while ( ! i_ring_empty (fd_ring))
260     {
261       int fd = i_ring_pop (fd_ring);
262       if (0 <= fd)
263         close (fd);
264     }
265 }
266
267 /* Overload the fts_statp->st_size member (otherwise unused, when
268    fts_info is FTS_NSOK) to indicate whether fts_read should stat
269    this entry or not.  */
270 static void
271 fts_set_stat_required (FTSENT *p, bool required)
272 {
273   fts_assert (p->fts_info == FTS_NSOK);
274   p->fts_statp->st_size = (required
275                            ? FTS_STAT_REQUIRED
276                            : FTS_NO_STAT_REQUIRED);
277 }
278
279 /* file-descriptor-relative opendir.  */
280 /* FIXME: if others need this function, move it into lib/openat.c */
281 static inline DIR *
282 internal_function
283 opendirat (int fd, char const *dir)
284 {
285   int new_fd = openat (fd, dir, O_RDONLY);
286   DIR *dirp;
287
288   if (new_fd < 0)
289     return NULL;
290   dirp = fdopendir (new_fd);
291   if (dirp == NULL)
292     {
293       int saved_errno = errno;
294       close (new_fd);
295       errno = saved_errno;
296     }
297   return dirp;
298 }
299
300 /* Virtual fchdir.  Advance SP's working directory file descriptor,
301    SP->fts_cwd_fd, to FD, and push the previous value onto the fd_ring.
302    CHDIR_DOWN_ONE is true if FD corresponds to an entry in the directory
303    open on sp->fts_cwd_fd; i.e., to move the working directory one level
304    down.  */
305 static void
306 internal_function
307 cwd_advance_fd (FTS *sp, int fd, bool chdir_down_one)
308 {
309   int old = sp->fts_cwd_fd;
310   fts_assert (old != fd || old == AT_FDCWD);
311
312   if (chdir_down_one)
313     {
314       /* Push "old" onto the ring.
315          If the displaced file descriptor is non-negative, close it.  */
316       int prev_fd_in_slot = i_ring_push (&sp->fts_fd_ring, old);
317       fd_ring_print (sp, stderr, "post-push");
318       if (0 <= prev_fd_in_slot)
319         close (prev_fd_in_slot); /* ignore any close failure */
320     }
321   else if ( ! ISSET (FTS_NOCHDIR))
322     {
323       if (0 <= old)
324         close (old); /* ignore any close failure */
325     }
326
327   sp->fts_cwd_fd = fd;
328 }
329
330 /* Open the directory DIR if possible, and return a file
331    descriptor.  Return -1 and set errno on failure.  It doesn't matter
332    whether the file descriptor has read or write access.  */
333
334 static inline int
335 internal_function
336 diropen (FTS const *sp, char const *dir)
337 {
338   int open_flags = (O_RDONLY | O_DIRECTORY | O_NOCTTY | O_NONBLOCK
339                     | (ISSET (FTS_PHYSICAL) ? O_NOFOLLOW : 0));
340
341   return (ISSET (FTS_CWDFD)
342           ? openat (sp->fts_cwd_fd, dir, open_flags)
343           : open (dir, open_flags));
344 }
345
346 FTS *
347 fts_open (char * const *argv,
348           register int options,
349           int (*compar) (FTSENT const **, FTSENT const **))
350 {
351         register FTS *sp;
352         register FTSENT *p, *root;
353         register size_t nitems;
354         FTSENT *parent = NULL;
355         FTSENT *tmp = NULL;     /* pacify gcc */
356         size_t len;
357         bool defer_stat;
358
359         /* Options check. */
360         if (options & ~FTS_OPTIONMASK) {
361                 __set_errno (EINVAL);
362                 return (NULL);
363         }
364         if ((options & FTS_NOCHDIR) && (options & FTS_CWDFD)) {
365                 __set_errno (EINVAL);
366                 return (NULL);
367         }
368         if ( ! (options & (FTS_LOGICAL | FTS_PHYSICAL))) {
369                 __set_errno (EINVAL);
370                 return (NULL);
371         }
372
373         /* Allocate/initialize the stream */
374         if ((sp = malloc(sizeof(FTS))) == NULL)
375                 return (NULL);
376         memset(sp, 0, sizeof(FTS));
377         sp->fts_compar = compar;
378         sp->fts_options = options;
379
380         /* Logical walks turn on NOCHDIR; symbolic links are too hard. */
381         if (ISSET(FTS_LOGICAL)) {
382                 SET(FTS_NOCHDIR);
383                 CLR(FTS_CWDFD);
384         }
385
386         /* Initialize fts_cwd_fd.  */
387         sp->fts_cwd_fd = AT_FDCWD;
388         if ( ISSET(FTS_CWDFD) && ! HAVE_OPENAT_SUPPORT)
389           {
390             /* While it isn't technically necessary to open "." this
391                early, doing it here saves us the trouble of ensuring
392                later (where it'd be messier) that "." can in fact
393                be opened.  If not, revert to FTS_NOCHDIR mode.  */
394             int fd = open (".", O_RDONLY);
395             if (fd < 0)
396               {
397                 /* Even if `.' is unreadable, don't revert to FTS_NOCHDIR mode
398                    on systems like Linux+PROC_FS, where our openat emulation
399                    is good enough.  Note: on a system that emulates
400                    openat via /proc, this technique can still fail, but
401                    only in extreme conditions, e.g., when the working
402                    directory cannot be saved (i.e. save_cwd fails) --
403                    and that happens on Linux only when "." is unreadable
404                    and the CWD would be longer than PATH_MAX.
405                    FIXME: once Linux kernel openat support is well established,
406                    replace the above open call and this entire if/else block
407                    with the body of the if-block below.  */
408                 if ( openat_needs_fchdir ())
409                   {
410                     SET(FTS_NOCHDIR);
411                     CLR(FTS_CWDFD);
412                   }
413               }
414             else
415               {
416                 close (fd);
417               }
418           }
419
420         /*
421          * Start out with 1K of file name space, and enough, in any case,
422          * to hold the user's file names.
423          */
424 #ifndef MAXPATHLEN
425 # define MAXPATHLEN 1024
426 #endif
427         {
428           size_t maxarglen = fts_maxarglen(argv);
429           if (! fts_palloc(sp, MAX(maxarglen, MAXPATHLEN)))
430                   goto mem1;
431         }
432
433         /* Allocate/initialize root's parent. */
434         if (*argv != NULL) {
435                 if ((parent = fts_alloc(sp, "", 0)) == NULL)
436                         goto mem2;
437                 parent->fts_level = FTS_ROOTPARENTLEVEL;
438           }
439
440         /* The classic fts implementation would call fts_stat with
441            a new entry for each iteration of the loop below.
442            If the comparison function is not specified or if the
443            FTS_DEFER_STAT option is in effect, don't stat any entry
444            in this loop.  This is an attempt to minimize the interval
445            between the initial stat/lstat/fstatat and the point at which
446            a directory argument is first opened.  This matters for any
447            directory command line argument that resides on a file system
448            without genuine i-nodes.  If you specify FTS_DEFER_STAT along
449            with a comparison function, that function must not access any
450            data via the fts_statp pointer.  */
451         defer_stat = (compar == NULL || ISSET(FTS_DEFER_STAT));
452
453         /* Allocate/initialize root(s). */
454         for (root = NULL, nitems = 0; *argv != NULL; ++argv, ++nitems) {
455                 /* Don't allow zero-length file names. */
456                 if ((len = strlen(*argv)) == 0) {
457                         __set_errno (ENOENT);
458                         goto mem3;
459                 }
460
461                 if ((p = fts_alloc(sp, *argv, len)) == NULL)
462                         goto mem3;
463                 p->fts_level = FTS_ROOTLEVEL;
464                 p->fts_parent = parent;
465                 p->fts_accpath = p->fts_name;
466                 /* Even when defer_stat is true, be sure to stat the first
467                    command line argument, since fts_read (at least with
468                    FTS_XDEV) requires that.  */
469                 if (defer_stat && root != NULL) {
470                         p->fts_info = FTS_NSOK;
471                         fts_set_stat_required(p, true);
472                 } else {
473                         p->fts_info = fts_stat(sp, p, false);
474                 }
475
476                 /*
477                  * If comparison routine supplied, traverse in sorted
478                  * order; otherwise traverse in the order specified.
479                  */
480                 if (compar) {
481                         p->fts_link = root;
482                         root = p;
483                 } else {
484                         p->fts_link = NULL;
485                         if (root == NULL)
486                                 tmp = root = p;
487                         else {
488                                 tmp->fts_link = p;
489                                 tmp = p;
490                         }
491                 }
492         }
493         if (compar && nitems > 1)
494                 root = fts_sort(sp, root, nitems);
495
496         /*
497          * Allocate a dummy pointer and make fts_read think that we've just
498          * finished the node before the root(s); set p->fts_info to FTS_INIT
499          * so that everything about the "current" node is ignored.
500          */
501         if ((sp->fts_cur = fts_alloc(sp, "", 0)) == NULL)
502                 goto mem3;
503         sp->fts_cur->fts_link = root;
504         sp->fts_cur->fts_info = FTS_INIT;
505         if (! setup_dir (sp))
506                 goto mem3;
507
508         /*
509          * If using chdir(2), grab a file descriptor pointing to dot to ensure
510          * that we can get back here; this could be avoided for some file names,
511          * but almost certainly not worth the effort.  Slashes, symbolic links,
512          * and ".." are all fairly nasty problems.  Note, if we can't get the
513          * descriptor we run anyway, just more slowly.
514          */
515         if (!ISSET(FTS_NOCHDIR) && !ISSET(FTS_CWDFD)
516             && (sp->fts_rfd = diropen (sp, ".")) < 0)
517                 SET(FTS_NOCHDIR);
518
519         i_ring_init (&sp->fts_fd_ring, -1);
520         return (sp);
521
522 mem3:   fts_lfree(root);
523         free(parent);
524 mem2:   free(sp->fts_path);
525 mem1:   free(sp);
526         return (NULL);
527 }
528
529 static void
530 internal_function
531 fts_load (FTS *sp, register FTSENT *p)
532 {
533         register size_t len;
534         register char *cp;
535
536         /*
537          * Load the stream structure for the next traversal.  Since we don't
538          * actually enter the directory until after the preorder visit, set
539          * the fts_accpath field specially so the chdir gets done to the right
540          * place and the user can access the first node.  From fts_open it's
541          * known that the file name will fit.
542          */
543         len = p->fts_pathlen = p->fts_namelen;
544         memmove(sp->fts_path, p->fts_name, len + 1);
545         if ((cp = strrchr(p->fts_name, '/')) && (cp != p->fts_name || cp[1])) {
546                 len = strlen(++cp);
547                 memmove(p->fts_name, cp, len + 1);
548                 p->fts_namelen = len;
549         }
550         p->fts_accpath = p->fts_path = sp->fts_path;
551 }
552
553 int
554 fts_close (FTS *sp)
555 {
556         register FTSENT *freep, *p;
557         int saved_errno = 0;
558
559         /*
560          * This still works if we haven't read anything -- the dummy structure
561          * points to the root list, so we step through to the end of the root
562          * list which has a valid parent pointer.
563          */
564         if (sp->fts_cur) {
565                 for (p = sp->fts_cur; p->fts_level >= FTS_ROOTLEVEL;) {
566                         freep = p;
567                         p = p->fts_link != NULL ? p->fts_link : p->fts_parent;
568                         free(freep);
569                 }
570                 free(p);
571         }
572
573         /* Free up child linked list, sort array, file name buffer. */
574         if (sp->fts_child)
575                 fts_lfree(sp->fts_child);
576         free(sp->fts_array);
577         free(sp->fts_path);
578
579         if (ISSET(FTS_CWDFD))
580           {
581             if (0 <= sp->fts_cwd_fd)
582               close (sp->fts_cwd_fd);
583           }
584         else if (!ISSET(FTS_NOCHDIR))
585           {
586             /* Return to original directory, save errno if necessary. */
587             if (fchdir(sp->fts_rfd))
588               saved_errno = errno;
589             close(sp->fts_rfd);
590           }
591
592         fd_ring_clear (&sp->fts_fd_ring);
593         free_dir (sp);
594
595         /* Free up the stream pointer. */
596         free(sp);
597
598         /* Set errno and return. */
599         if (saved_errno) {
600                 __set_errno (saved_errno);
601                 return (-1);
602         }
603
604         return (0);
605 }
606
607 /*
608  * Special case of "/" at the end of the file name so that slashes aren't
609  * appended which would cause file names to be written as "....//foo".
610  */
611 #define NAPPEND(p)                                                      \
612         (p->fts_path[p->fts_pathlen - 1] == '/'                         \
613             ? p->fts_pathlen - 1 : p->fts_pathlen)
614
615 FTSENT *
616 fts_read (register FTS *sp)
617 {
618         register FTSENT *p, *tmp;
619         register unsigned short int instr;
620         register char *t;
621
622         /* If finished or unrecoverable error, return NULL. */
623         if (sp->fts_cur == NULL || ISSET(FTS_STOP))
624                 return (NULL);
625
626         /* Set current node pointer. */
627         p = sp->fts_cur;
628
629         /* Save and zero out user instructions. */
630         instr = p->fts_instr;
631         p->fts_instr = FTS_NOINSTR;
632
633         /* Any type of file may be re-visited; re-stat and re-turn. */
634         if (instr == FTS_AGAIN) {
635                 p->fts_info = fts_stat(sp, p, false);
636                 return (p);
637         }
638         Dprintf (("fts_read: p=%s\n",
639                   p->fts_info == FTS_INIT ? "" : p->fts_path));
640
641         /*
642          * Following a symlink -- SLNONE test allows application to see
643          * SLNONE and recover.  If indirecting through a symlink, have
644          * keep a pointer to current location.  If unable to get that
645          * pointer, follow fails.
646          */
647         if (instr == FTS_FOLLOW &&
648             (p->fts_info == FTS_SL || p->fts_info == FTS_SLNONE)) {
649                 p->fts_info = fts_stat(sp, p, true);
650                 if (p->fts_info == FTS_D && !ISSET(FTS_NOCHDIR)) {
651                         if ((p->fts_symfd = diropen (sp, ".")) < 0) {
652                                 p->fts_errno = errno;
653                                 p->fts_info = FTS_ERR;
654                         } else
655                                 p->fts_flags |= FTS_SYMFOLLOW;
656                 }
657                 goto check_for_dir;
658         }
659
660         /* Directory in pre-order. */
661         if (p->fts_info == FTS_D) {
662                 /* If skipped or crossed mount point, do post-order visit. */
663                 if (instr == FTS_SKIP ||
664                     (ISSET(FTS_XDEV) && p->fts_statp->st_dev != sp->fts_dev)) {
665                         if (p->fts_flags & FTS_SYMFOLLOW)
666                                 (void)close(p->fts_symfd);
667                         if (sp->fts_child) {
668                                 fts_lfree(sp->fts_child);
669                                 sp->fts_child = NULL;
670                         }
671                         p->fts_info = FTS_DP;
672                         LEAVE_DIR (sp, p, "1");
673                         return (p);
674                 }
675
676                 /* Rebuild if only read the names and now traversing. */
677                 if (sp->fts_child != NULL && ISSET(FTS_NAMEONLY)) {
678                         CLR(FTS_NAMEONLY);
679                         fts_lfree(sp->fts_child);
680                         sp->fts_child = NULL;
681                 }
682
683                 /*
684                  * Cd to the subdirectory.
685                  *
686                  * If have already read and now fail to chdir, whack the list
687                  * to make the names come out right, and set the parent errno
688                  * so the application will eventually get an error condition.
689                  * Set the FTS_DONTCHDIR flag so that when we logically change
690                  * directories back to the parent we don't do a chdir.
691                  *
692                  * If haven't read do so.  If the read fails, fts_build sets
693                  * FTS_STOP or the fts_info field of the node.
694                  */
695                 if (sp->fts_child != NULL) {
696                         if (fts_safe_changedir(sp, p, -1, p->fts_accpath)) {
697                                 p->fts_errno = errno;
698                                 p->fts_flags |= FTS_DONTCHDIR;
699                                 for (p = sp->fts_child; p != NULL;
700                                      p = p->fts_link)
701                                         p->fts_accpath =
702                                             p->fts_parent->fts_accpath;
703                         }
704                 } else if ((sp->fts_child = fts_build(sp, BREAD)) == NULL) {
705                         if (ISSET(FTS_STOP))
706                                 return (NULL);
707                         /* If fts_build's call to fts_safe_changedir failed
708                            because it was not able to fchdir into a
709                            subdirectory, tell the caller.  */
710                         if (p->fts_errno && p->fts_info != FTS_DNR)
711                                 p->fts_info = FTS_ERR;
712                         LEAVE_DIR (sp, p, "2");
713                         return (p);
714                 }
715                 p = sp->fts_child;
716                 sp->fts_child = NULL;
717                 goto name;
718         }
719
720         /* Move to the next node on this level. */
721 next:   tmp = p;
722         if ((p = p->fts_link) != NULL) {
723                 sp->fts_cur = p;
724                 free(tmp);
725
726                 /*
727                  * If reached the top, return to the original directory (or
728                  * the root of the tree), and load the file names for the next
729                  * root.
730                  */
731                 if (p->fts_level == FTS_ROOTLEVEL) {
732                         if (RESTORE_INITIAL_CWD(sp)) {
733                                 SET(FTS_STOP);
734                                 return (NULL);
735                         }
736                         fts_load(sp, p);
737                         goto check_for_dir;
738                 }
739
740                 /*
741                  * User may have called fts_set on the node.  If skipped,
742                  * ignore.  If followed, get a file descriptor so we can
743                  * get back if necessary.
744                  */
745                 if (p->fts_instr == FTS_SKIP)
746                         goto next;
747                 if (p->fts_instr == FTS_FOLLOW) {
748                         p->fts_info = fts_stat(sp, p, true);
749                         if (p->fts_info == FTS_D && !ISSET(FTS_NOCHDIR)) {
750                                 if ((p->fts_symfd = diropen (sp, ".")) < 0) {
751                                         p->fts_errno = errno;
752                                         p->fts_info = FTS_ERR;
753                                 } else
754                                         p->fts_flags |= FTS_SYMFOLLOW;
755                         }
756                         p->fts_instr = FTS_NOINSTR;
757                 }
758
759 name:           t = sp->fts_path + NAPPEND(p->fts_parent);
760                 *t++ = '/';
761                 memmove(t, p->fts_name, p->fts_namelen + 1);
762 check_for_dir:
763                 sp->fts_cur = p;
764                 if (p->fts_info == FTS_NSOK)
765                   {
766                     if (p->fts_statp->st_size == FTS_STAT_REQUIRED)
767                       p->fts_info = fts_stat(sp, p, false);
768                     else
769                       fts_assert (p->fts_statp->st_size == FTS_NO_STAT_REQUIRED);
770                   }
771
772                 if (p->fts_info == FTS_D)
773                   {
774                     /* Now that P->fts_statp is guaranteed to be valid,
775                        if this is a command-line directory, record its
776                        device number, to be used for FTS_XDEV.  */
777                     if (p->fts_level == FTS_ROOTLEVEL)
778                       sp->fts_dev = p->fts_statp->st_dev;
779                     Dprintf (("  entering: %s\n", p->fts_path));
780                     if (! enter_dir (sp, p))
781                       {
782                         __set_errno (ENOMEM);
783                         return NULL;
784                       }
785                   }
786                 return p;
787         }
788
789         /* Move up to the parent node. */
790         p = tmp->fts_parent;
791         sp->fts_cur = p;
792         free(tmp);
793
794         if (p->fts_level == FTS_ROOTPARENTLEVEL) {
795                 /*
796                  * Done; free everything up and set errno to 0 so the user
797                  * can distinguish between error and EOF.
798                  */
799                 free(p);
800                 __set_errno (0);
801                 return (sp->fts_cur = NULL);
802         }
803
804         fts_assert (p->fts_info != FTS_NSOK);
805
806         /* NUL terminate the file name.  */
807         sp->fts_path[p->fts_pathlen] = '\0';
808
809         /*
810          * Return to the parent directory.  If at a root node, restore
811          * the initial working directory.  If we came through a symlink,
812          * go back through the file descriptor.  Otherwise, move up
813          * one level, via "..".
814          */
815         if (p->fts_level == FTS_ROOTLEVEL) {
816                 if (RESTORE_INITIAL_CWD(sp)) {
817                         p->fts_errno = errno;
818                         SET(FTS_STOP);
819                 }
820         } else if (p->fts_flags & FTS_SYMFOLLOW) {
821                 if (FCHDIR(sp, p->fts_symfd)) {
822                         int saved_errno = errno;
823                         (void)close(p->fts_symfd);
824                         __set_errno (saved_errno);
825                         p->fts_errno = errno;
826                         SET(FTS_STOP);
827                 }
828                 (void)close(p->fts_symfd);
829         } else if (!(p->fts_flags & FTS_DONTCHDIR) &&
830                    fts_safe_changedir(sp, p->fts_parent, -1, "..")) {
831                 p->fts_errno = errno;
832                 SET(FTS_STOP);
833         }
834         p->fts_info = p->fts_errno ? FTS_ERR : FTS_DP;
835         if (p->fts_errno == 0)
836                 LEAVE_DIR (sp, p, "3");
837         return ISSET(FTS_STOP) ? NULL : p;
838 }
839
840 /*
841  * Fts_set takes the stream as an argument although it's not used in this
842  * implementation; it would be necessary if anyone wanted to add global
843  * semantics to fts using fts_set.  An error return is allowed for similar
844  * reasons.
845  */
846 /* ARGSUSED */
847 int
848 fts_set(FTS *sp ATTRIBUTE_UNUSED, FTSENT *p, int instr)
849 {
850         if (instr != 0 && instr != FTS_AGAIN && instr != FTS_FOLLOW &&
851             instr != FTS_NOINSTR && instr != FTS_SKIP) {
852                 __set_errno (EINVAL);
853                 return (1);
854         }
855         p->fts_instr = instr;
856         return (0);
857 }
858
859 FTSENT *
860 fts_children (register FTS *sp, int instr)
861 {
862         register FTSENT *p;
863         int fd;
864
865         if (instr != 0 && instr != FTS_NAMEONLY) {
866                 __set_errno (EINVAL);
867                 return (NULL);
868         }
869
870         /* Set current node pointer. */
871         p = sp->fts_cur;
872
873         /*
874          * Errno set to 0 so user can distinguish empty directory from
875          * an error.
876          */
877         __set_errno (0);
878
879         /* Fatal errors stop here. */
880         if (ISSET(FTS_STOP))
881                 return (NULL);
882
883         /* Return logical hierarchy of user's arguments. */
884         if (p->fts_info == FTS_INIT)
885                 return (p->fts_link);
886
887         /*
888          * If not a directory being visited in pre-order, stop here.  Could
889          * allow FTS_DNR, assuming the user has fixed the problem, but the
890          * same effect is available with FTS_AGAIN.
891          */
892         if (p->fts_info != FTS_D /* && p->fts_info != FTS_DNR */)
893                 return (NULL);
894
895         /* Free up any previous child list. */
896         if (sp->fts_child != NULL)
897                 fts_lfree(sp->fts_child);
898
899         if (instr == FTS_NAMEONLY) {
900                 SET(FTS_NAMEONLY);
901                 instr = BNAMES;
902         } else
903                 instr = BCHILD;
904
905         /*
906          * If using chdir on a relative file name and called BEFORE fts_read
907          * does its chdir to the root of a traversal, we can lose -- we need to
908          * chdir into the subdirectory, and we don't know where the current
909          * directory is, so we can't get back so that the upcoming chdir by
910          * fts_read will work.
911          */
912         if (p->fts_level != FTS_ROOTLEVEL || p->fts_accpath[0] == '/' ||
913             ISSET(FTS_NOCHDIR))
914                 return (sp->fts_child = fts_build(sp, instr));
915
916         if ((fd = diropen (sp, ".")) < 0)
917                 return (sp->fts_child = NULL);
918         sp->fts_child = fts_build(sp, instr);
919         if (ISSET(FTS_CWDFD))
920           {
921             cwd_advance_fd (sp, fd, true);
922           }
923         else
924           {
925             if (fchdir(fd))
926               {
927                 int saved_errno = errno;
928                 close (fd);
929                 __set_errno (saved_errno);
930                 return NULL;
931               }
932             close (fd);
933           }
934         return (sp->fts_child);
935 }
936
937 #if defined HAVE_SYS_VFS_H && HAVE_FSTATFS && HAVE_STRUCT_STATFS_F_TYPE
938 # include <sys/statfs.h>
939 /* FIXME: what about when f_type is not an integral type?
940    deal with that if/when it's encountered.  */
941 static bool
942 fs_handles_readdir_ordered_dirents_efficiently (uintmax_t fs_type)
943 {
944 /* From coreutils' src/fs.h */
945 #define S_MAGIC_TMPFS 0x1021994
946 #define S_MAGIC_NFS 0x6969
947   switch (fs_type)
948     {
949     case S_MAGIC_TMPFS:
950     case S_MAGIC_NFS:
951       return true;
952     default:
953       return false;
954     }
955 }
956
957 /* Return true if it is easy to determine the file system type of the
958    current directory, and sorting dirents on inode numbers is known to
959    improve traversal performance with that type of file system.  */
960 static bool
961 dirent_inode_sort_may_be_useful (FTS const *sp)
962 {
963   struct statfs fs_buf;
964   /* Skip the sort only if we can determine efficiently
965      that it's the right thing to do.  */
966   bool skip = (ISSET (FTS_CWDFD)
967                && fstatfs (sp->fts_cwd_fd, &fs_buf) == 0
968                && fs_handles_readdir_ordered_dirents_efficiently
969                     (fs_buf.f_type));
970   return !skip;
971 }
972 #else
973 static bool dirent_inode_sort_may_be_useful (FTS const *sp) { return true; }
974 #endif
975
976 /* A comparison function to sort on increasing inode number.
977    For some file system types, sorting either way makes a huge
978    performance difference for a directory with very many entries,
979    but sorting on increasing values is slightly better than sorting
980    on decreasing values.  The difference is in the 5% range.  */
981 static int
982 fts_compare_ino (struct _ftsent const **a, struct _ftsent const **b)
983 {
984   return (a[0]->fts_statp->st_ino < b[0]->fts_statp->st_ino ? -1
985           : b[0]->fts_statp->st_ino < a[0]->fts_statp->st_ino ? 1 : 0);
986 }
987
988 /*
989  * This is the tricky part -- do not casually change *anything* in here.  The
990  * idea is to build the linked list of entries that are used by fts_children
991  * and fts_read.  There are lots of special cases.
992  *
993  * The real slowdown in walking the tree is the stat calls.  If FTS_NOSTAT is
994  * set and it's a physical walk (so that symbolic links can't be directories),
995  * we can do things quickly.  First, if it's a 4.4BSD file system, the type
996  * of the file is in the directory entry.  Otherwise, we assume that the number
997  * of subdirectories in a node is equal to the number of links to the parent.
998  * The former skips all stat calls.  The latter skips stat calls in any leaf
999  * directories and for any files after the subdirectories in the directory have
1000  * been found, cutting the stat calls by about 2/3.
1001  */
1002 static FTSENT *
1003 internal_function
1004 fts_build (register FTS *sp, int type)
1005 {
1006         register struct dirent *dp;
1007         register FTSENT *p, *head;
1008         register size_t nitems;
1009         FTSENT *cur, *tail;
1010         DIR *dirp;
1011         void *oldaddr;
1012         int saved_errno;
1013         bool descend;
1014         bool doadjust;
1015         ptrdiff_t level;
1016         nlink_t nlinks;
1017         bool nostat;
1018         size_t len, maxlen, new_len;
1019         char *cp;
1020
1021         /* Set current node pointer. */
1022         cur = sp->fts_cur;
1023
1024         /*
1025          * Open the directory for reading.  If this fails, we're done.
1026          * If being called from fts_read, set the fts_info field.
1027          */
1028 #if defined FTS_WHITEOUT && 0
1029         if (ISSET(FTS_WHITEOUT))
1030                 oflag = DTF_NODUP|DTF_REWIND;
1031         else
1032                 oflag = DTF_HIDEW|DTF_NODUP|DTF_REWIND;
1033 #else
1034 # define __opendir2(file, flag) \
1035         ( ! ISSET(FTS_NOCHDIR) && ISSET(FTS_CWDFD) \
1036           ? opendirat(sp->fts_cwd_fd, file)        \
1037           : opendir(file))
1038 #endif
1039        if ((dirp = __opendir2(cur->fts_accpath, oflag)) == NULL) {
1040                 if (type == BREAD) {
1041                         cur->fts_info = FTS_DNR;
1042                         cur->fts_errno = errno;
1043                 }
1044                 return (NULL);
1045         }
1046        /* Rather than calling fts_stat for each and every entry encountered
1047           in the readdir loop (below), stat each directory only right after
1048           opening it.  */
1049        if (cur->fts_info == FTS_NSOK)
1050          cur->fts_info = fts_stat(sp, cur, false);
1051
1052         /*
1053          * Nlinks is the number of possible entries of type directory in the
1054          * directory if we're cheating on stat calls, 0 if we're not doing
1055          * any stat calls at all, (nlink_t) -1 if we're statting everything.
1056          */
1057         if (type == BNAMES) {
1058                 nlinks = 0;
1059                 /* Be quiet about nostat, GCC. */
1060                 nostat = false;
1061         } else if (ISSET(FTS_NOSTAT) && ISSET(FTS_PHYSICAL)) {
1062                 nlinks = (cur->fts_statp->st_nlink
1063                           - (ISSET(FTS_SEEDOT) ? 0 : 2));
1064                 nostat = true;
1065         } else {
1066                 nlinks = -1;
1067                 nostat = false;
1068         }
1069
1070         /*
1071          * If we're going to need to stat anything or we want to descend
1072          * and stay in the directory, chdir.  If this fails we keep going,
1073          * but set a flag so we don't chdir after the post-order visit.
1074          * We won't be able to stat anything, but we can still return the
1075          * names themselves.  Note, that since fts_read won't be able to
1076          * chdir into the directory, it will have to return different file
1077          * names than before, i.e. "a/b" instead of "b".  Since the node
1078          * has already been visited in pre-order, have to wait until the
1079          * post-order visit to return the error.  There is a special case
1080          * here, if there was nothing to stat then it's not an error to
1081          * not be able to stat.  This is all fairly nasty.  If a program
1082          * needed sorted entries or stat information, they had better be
1083          * checking FTS_NS on the returned nodes.
1084          */
1085         if (nlinks || type == BREAD) {
1086                 int dir_fd = dirfd(dirp);
1087                 if (ISSET(FTS_CWDFD) && 0 <= dir_fd)
1088                   dir_fd = dup (dir_fd);
1089                 if (dir_fd < 0 || fts_safe_changedir(sp, cur, dir_fd, NULL)) {
1090                         if (nlinks && type == BREAD)
1091                                 cur->fts_errno = errno;
1092                         cur->fts_flags |= FTS_DONTCHDIR;
1093                         descend = false;
1094                         closedir(dirp);
1095                         if (ISSET(FTS_CWDFD) && 0 <= dir_fd)
1096                                 close (dir_fd);
1097                         dirp = NULL;
1098                 } else
1099                         descend = true;
1100         } else
1101                 descend = false;
1102
1103         /*
1104          * Figure out the max file name length that can be stored in the
1105          * current buffer -- the inner loop allocates more space as necessary.
1106          * We really wouldn't have to do the maxlen calculations here, we
1107          * could do them in fts_read before returning the name, but it's a
1108          * lot easier here since the length is part of the dirent structure.
1109          *
1110          * If not changing directories set a pointer so that can just append
1111          * each new component into the file name.
1112          */
1113         len = NAPPEND(cur);
1114         if (ISSET(FTS_NOCHDIR)) {
1115                 cp = sp->fts_path + len;
1116                 *cp++ = '/';
1117         } else {
1118                 /* GCC, you're too verbose. */
1119                 cp = NULL;
1120         }
1121         len++;
1122         maxlen = sp->fts_pathlen - len;
1123
1124         level = cur->fts_level + 1;
1125
1126         /* Read the directory, attaching each entry to the `link' pointer. */
1127         doadjust = false;
1128         for (head = tail = NULL, nitems = 0; dirp && (dp = readdir(dirp));) {
1129                 bool is_dir;
1130
1131                 if (!ISSET(FTS_SEEDOT) && ISDOT(dp->d_name))
1132                         continue;
1133
1134                 if ((p = fts_alloc (sp, dp->d_name,
1135                                     _D_EXACT_NAMLEN (dp))) == NULL)
1136                         goto mem1;
1137                 if (_D_EXACT_NAMLEN (dp) >= maxlen) {
1138                         /* include space for NUL */
1139                         oldaddr = sp->fts_path;
1140                         if (! fts_palloc(sp, _D_EXACT_NAMLEN (dp) + len + 1)) {
1141                                 /*
1142                                  * No more memory.  Save
1143                                  * errno, free up the current structure and the
1144                                  * structures already allocated.
1145                                  */
1146 mem1:                           saved_errno = errno;
1147                                 free(p);
1148                                 fts_lfree(head);
1149                                 closedir(dirp);
1150                                 cur->fts_info = FTS_ERR;
1151                                 SET(FTS_STOP);
1152                                 __set_errno (saved_errno);
1153                                 return (NULL);
1154                         }
1155                         /* Did realloc() change the pointer? */
1156                         if (oldaddr != sp->fts_path) {
1157                                 doadjust = true;
1158                                 if (ISSET(FTS_NOCHDIR))
1159                                         cp = sp->fts_path + len;
1160                         }
1161                         maxlen = sp->fts_pathlen - len;
1162                 }
1163
1164                 new_len = len + _D_EXACT_NAMLEN (dp);
1165                 if (new_len < len) {
1166                         /*
1167                          * In the unlikely event that we would end up
1168                          * with a file name longer than SIZE_MAX, free up
1169                          * the current structure and the structures already
1170                          * allocated, then error out with ENAMETOOLONG.
1171                          */
1172                         free(p);
1173                         fts_lfree(head);
1174                         closedir(dirp);
1175                         cur->fts_info = FTS_ERR;
1176                         SET(FTS_STOP);
1177                         __set_errno (ENAMETOOLONG);
1178                         return (NULL);
1179                 }
1180                 p->fts_level = level;
1181                 p->fts_parent = sp->fts_cur;
1182                 p->fts_pathlen = new_len;
1183
1184 #if defined FTS_WHITEOUT && 0
1185                 if (dp->d_type == DT_WHT)
1186                         p->fts_flags |= FTS_ISW;
1187 #endif
1188                 /* Store dirent.d_ino, in case we need to sort
1189                    entries before processing them.  */
1190                 p->fts_statp->st_ino = D_INO (dp);
1191
1192                 /* Build a file name for fts_stat to stat. */
1193                 if (ISSET(FTS_NOCHDIR)) {
1194                         p->fts_accpath = p->fts_path;
1195                         memmove(cp, p->fts_name, p->fts_namelen + 1);
1196                 } else
1197                         p->fts_accpath = p->fts_name;
1198
1199                 if (sp->fts_compar == NULL || ISSET(FTS_DEFER_STAT)) {
1200                         /* Record what fts_read will have to do with this
1201                            entry. In many cases, it will simply fts_stat it,
1202                            but we can take advantage of any d_type information
1203                            to optimize away the unnecessary stat calls.  I.e.,
1204                            if FTS_NOSTAT is in effect and we're not following
1205                            symlinks (FTS_PHYSICAL) and d_type indicates this
1206                            is *not* a directory, then we won't have to stat it
1207                            at all.  If it *is* a directory, then (currently)
1208                            we stat it regardless, in order to get device and
1209                            inode numbers.  Some day we might optimize that
1210                            away, too, for directories where d_ino is known to
1211                            be valid.  */
1212                         bool skip_stat = (ISSET(FTS_PHYSICAL)
1213                                           && ISSET(FTS_NOSTAT)
1214                                           && DT_IS_KNOWN(dp)
1215                                           && ! DT_MUST_BE(dp, DT_DIR));
1216                         p->fts_info = FTS_NSOK;
1217                         fts_set_stat_required(p, !skip_stat);
1218                         is_dir = (ISSET(FTS_PHYSICAL) && ISSET(FTS_NOSTAT)
1219                                   && DT_MUST_BE(dp, DT_DIR));
1220                 } else {
1221                         p->fts_info = fts_stat(sp, p, false);
1222                         is_dir = (p->fts_info == FTS_D
1223                                   || p->fts_info == FTS_DC
1224                                   || p->fts_info == FTS_DOT);
1225                 }
1226
1227                 /* Decrement link count if applicable. */
1228                 if (nlinks > 0 && is_dir)
1229                         nlinks -= nostat;
1230
1231                 /* We walk in directory order so "ls -f" doesn't get upset. */
1232                 p->fts_link = NULL;
1233                 if (head == NULL)
1234                         head = tail = p;
1235                 else {
1236                         tail->fts_link = p;
1237                         tail = p;
1238                 }
1239                 ++nitems;
1240         }
1241         if (dirp)
1242                 closedir(dirp);
1243
1244         /*
1245          * If realloc() changed the address of the file name, adjust the
1246          * addresses for the rest of the tree and the dir list.
1247          */
1248         if (doadjust)
1249                 fts_padjust(sp, head);
1250
1251         /*
1252          * If not changing directories, reset the file name back to original
1253          * state.
1254          */
1255         if (ISSET(FTS_NOCHDIR)) {
1256                 if (len == sp->fts_pathlen || nitems == 0)
1257                         --cp;
1258                 *cp = '\0';
1259         }
1260
1261         /*
1262          * If descended after called from fts_children or after called from
1263          * fts_read and nothing found, get back.  At the root level we use
1264          * the saved fd; if one of fts_open()'s arguments is a relative name
1265          * to an empty directory, we wind up here with no other way back.  If
1266          * can't get back, we're done.
1267          */
1268         if (descend && (type == BCHILD || !nitems) &&
1269             (cur->fts_level == FTS_ROOTLEVEL
1270              ? RESTORE_INITIAL_CWD(sp)
1271              : fts_safe_changedir(sp, cur->fts_parent, -1, ".."))) {
1272                 cur->fts_info = FTS_ERR;
1273                 SET(FTS_STOP);
1274                 fts_lfree(head);
1275                 return (NULL);
1276         }
1277
1278         /* If didn't find anything, return NULL. */
1279         if (!nitems) {
1280                 if (type == BREAD)
1281                         cur->fts_info = FTS_DP;
1282                 fts_lfree(head);
1283                 return (NULL);
1284         }
1285
1286         /* If there are many entries, no sorting function has been specified,
1287            and this file system is of a type that may be slow with a large
1288            number of entries, then sort the directory entries on increasing
1289            inode numbers.  */
1290         if (nitems > _FTS_INODE_SORT_DIR_ENTRIES_THRESHOLD
1291             && !sp->fts_compar
1292             && dirent_inode_sort_may_be_useful (sp)) {
1293                 sp->fts_compar = fts_compare_ino;
1294                 head = fts_sort (sp, head, nitems);
1295                 sp->fts_compar = NULL;
1296         }
1297
1298         /* Sort the entries. */
1299         if (sp->fts_compar && nitems > 1)
1300                 head = fts_sort(sp, head, nitems);
1301         return (head);
1302 }
1303
1304 #if FTS_DEBUG
1305
1306 /* Walk ->fts_parent links starting at E_CURR, until the root of the
1307    current hierarchy.  There should be a directory with dev/inode
1308    matching those of AD.  If not, print a lot of diagnostics.  */
1309 static void
1310 find_matching_ancestor (FTSENT const *e_curr, struct Active_dir const *ad)
1311 {
1312   FTSENT const *ent;
1313   for (ent = e_curr; ent->fts_level >= FTS_ROOTLEVEL; ent = ent->fts_parent)
1314     {
1315       if (ad->ino == ent->fts_statp->st_ino
1316           && ad->dev == ent->fts_statp->st_dev)
1317         return;
1318     }
1319   printf ("ERROR: tree dir, %s, not active\n", ad->fts_ent->fts_accpath);
1320   printf ("active dirs:\n");
1321   for (ent = e_curr;
1322        ent->fts_level >= FTS_ROOTLEVEL; ent = ent->fts_parent)
1323     printf ("  %s(%"PRIuMAX"/%"PRIuMAX") to %s(%"PRIuMAX"/%"PRIuMAX")...\n",
1324             ad->fts_ent->fts_accpath,
1325             (uintmax_t) ad->dev,
1326             (uintmax_t) ad->ino,
1327             ent->fts_accpath,
1328             (uintmax_t) ent->fts_statp->st_dev,
1329             (uintmax_t) ent->fts_statp->st_ino);
1330 }
1331
1332 void
1333 fts_cross_check (FTS const *sp)
1334 {
1335   FTSENT const *ent = sp->fts_cur;
1336   FTSENT const *t;
1337   if ( ! ISSET (FTS_TIGHT_CYCLE_CHECK))
1338     return;
1339
1340   Dprintf (("fts-cross-check cur=%s\n", ent->fts_path));
1341   /* Make sure every parent dir is in the tree.  */
1342   for (t = ent->fts_parent; t->fts_level >= FTS_ROOTLEVEL; t = t->fts_parent)
1343     {
1344       struct Active_dir ad;
1345       ad.ino = t->fts_statp->st_ino;
1346       ad.dev = t->fts_statp->st_dev;
1347       if ( ! hash_lookup (sp->fts_cycle.ht, &ad))
1348         printf ("ERROR: active dir, %s, not in tree\n", t->fts_path);
1349     }
1350
1351   /* Make sure every dir in the tree is an active dir.
1352      But ENT is not necessarily a directory.  If so, just skip this part. */
1353   if (ent->fts_parent->fts_level >= FTS_ROOTLEVEL
1354       && (ent->fts_info == FTS_DP
1355           || ent->fts_info == FTS_D))
1356     {
1357       struct Active_dir *ad;
1358       for (ad = hash_get_first (sp->fts_cycle.ht); ad != NULL;
1359            ad = hash_get_next (sp->fts_cycle.ht, ad))
1360         {
1361           find_matching_ancestor (ent, ad);
1362         }
1363     }
1364 }
1365
1366 static bool
1367 same_fd (int fd1, int fd2)
1368 {
1369   struct stat sb1, sb2;
1370   return (fstat (fd1, &sb1) == 0
1371           && fstat (fd2, &sb2) == 0
1372           && SAME_INODE (sb1, sb2));
1373 }
1374
1375 static void
1376 fd_ring_print (FTS const *sp, FILE *stream, char const *msg)
1377 {
1378   I_ring const *fd_ring = &sp->fts_fd_ring;
1379   unsigned int i = fd_ring->fts_front;
1380   char *cwd = getcwdat (sp->fts_cwd_fd, NULL, 0);
1381   fprintf (stream, "=== %s ========== %s\n", msg, cwd);
1382   free (cwd);
1383   if (i_ring_empty (fd_ring))
1384     return;
1385
1386   while (true)
1387     {
1388       int fd = fd_ring->fts_fd_ring[i];
1389       if (fd < 0)
1390         fprintf (stream, "%d: %d:\n", i, fd);
1391       else
1392         {
1393           char *wd = getcwdat (fd, NULL, 0);
1394           fprintf (stream, "%d: %d: %s\n", i, fd, wd);
1395           free (wd);
1396         }
1397       if (i == fd_ring->fts_back)
1398         break;
1399       i = (i + I_RING_SIZE - 1) % I_RING_SIZE;
1400     }
1401 }
1402
1403 /* Ensure that each file descriptor on the fd_ring matches a
1404    parent, grandparent, etc. of the current working directory.  */
1405 static void
1406 fd_ring_check (FTS const *sp)
1407 {
1408   if (!fts_debug)
1409     return;
1410
1411   /* Make a writable copy.  */
1412   I_ring fd_w = sp->fts_fd_ring;
1413
1414   int cwd_fd = sp->fts_cwd_fd;
1415   cwd_fd = dup (cwd_fd);
1416   char *dot = getcwdat (cwd_fd, NULL, 0);
1417   error (0, 0, "===== check ===== cwd: %s", dot);
1418   free (dot);
1419   while ( ! i_ring_empty (&fd_w))
1420     {
1421       int fd = i_ring_pop (&fd_w);
1422       if (0 <= fd)
1423         {
1424           int parent_fd = openat (cwd_fd, "..", O_RDONLY);
1425           if (parent_fd < 0)
1426             {
1427               // Warn?
1428               break;
1429             }
1430           if (!same_fd (fd, parent_fd))
1431             {
1432               char *cwd = getcwdat (fd, NULL, 0);
1433               error (0, errno, "ring  : %s", cwd);
1434               char *c2 = getcwdat (parent_fd, NULL, 0);
1435               error (0, errno, "parent: %s", c2);
1436               free (cwd);
1437               free (c2);
1438               fts_assert (0);
1439             }
1440           close (cwd_fd);
1441           cwd_fd = parent_fd;
1442         }
1443     }
1444   close (cwd_fd);
1445 }
1446 #endif
1447
1448 static unsigned short int
1449 internal_function
1450 fts_stat(FTS *sp, register FTSENT *p, bool follow)
1451 {
1452         struct stat *sbp = p->fts_statp;
1453         int saved_errno;
1454
1455         if (p->fts_level == FTS_ROOTLEVEL && ISSET(FTS_COMFOLLOW))
1456                 follow = true;
1457
1458 #if defined FTS_WHITEOUT && 0
1459         /* check for whiteout */
1460         if (p->fts_flags & FTS_ISW) {
1461                 memset(sbp, '\0', sizeof (*sbp));
1462                 sbp->st_mode = S_IFWHT;
1463                 return (FTS_W);
1464        }
1465 #endif
1466
1467         /*
1468          * If doing a logical walk, or application requested FTS_FOLLOW, do
1469          * a stat(2).  If that fails, check for a non-existent symlink.  If
1470          * fail, set the errno from the stat call.
1471          */
1472         if (ISSET(FTS_LOGICAL) || follow) {
1473                 if (stat(p->fts_accpath, sbp)) {
1474                         saved_errno = errno;
1475                         if (errno == ENOENT
1476                             && lstat(p->fts_accpath, sbp) == 0) {
1477                                 __set_errno (0);
1478                                 return (FTS_SLNONE);
1479                         }
1480                         p->fts_errno = saved_errno;
1481                         goto err;
1482                 }
1483         } else if (fstatat(sp->fts_cwd_fd, p->fts_accpath, sbp,
1484                            AT_SYMLINK_NOFOLLOW)) {
1485                 p->fts_errno = errno;
1486 err:            memset(sbp, 0, sizeof(struct stat));
1487                 return (FTS_NS);
1488         }
1489
1490         if (S_ISDIR(sbp->st_mode)) {
1491                 if (ISDOT(p->fts_name)) {
1492                         /* Command-line "." and ".." are real directories. */
1493                         return (p->fts_level == FTS_ROOTLEVEL ? FTS_D : FTS_DOT);
1494                 }
1495
1496 #if !GNULIB_FTS
1497                 {
1498                   /*
1499                    * Cycle detection is done by brute force when the directory
1500                    * is first encountered.  If the tree gets deep enough or the
1501                    * number of symbolic links to directories is high enough,
1502                    * something faster might be worthwhile.
1503                    */
1504                   FTSENT *t;
1505
1506                   for (t = p->fts_parent;
1507                        t->fts_level >= FTS_ROOTLEVEL; t = t->fts_parent)
1508                     if (sbp->st_ino == t->fts_statp->st_ino
1509                         && sbp->st_dev == t->fts_statp->st_dev)
1510                       {
1511                         p->fts_cycle = t;
1512                         return (FTS_DC);
1513                       }
1514                 }
1515 #endif
1516
1517                 return (FTS_D);
1518         }
1519         if (S_ISLNK(sbp->st_mode))
1520                 return (FTS_SL);
1521         if (S_ISREG(sbp->st_mode))
1522                 return (FTS_F);
1523         return (FTS_DEFAULT);
1524 }
1525
1526 static int
1527 fts_compar (void const *a, void const *b)
1528 {
1529   /* Convert A and B to the correct types, to pacify the compiler, and
1530      for portability to bizarre hosts where "void const *" and "FTSENT
1531      const **" differ in runtime representation.  The comparison
1532      function cannot modify *a and *b, but there is no compile-time
1533      check for this.  */
1534   FTSENT const **pa = (FTSENT const **) a;
1535   FTSENT const **pb = (FTSENT const **) b;
1536   return pa[0]->fts_fts->fts_compar (pa, pb);
1537 }
1538
1539 static FTSENT *
1540 internal_function
1541 fts_sort (FTS *sp, FTSENT *head, register size_t nitems)
1542 {
1543         register FTSENT **ap, *p;
1544
1545         /* On most modern hosts, void * and FTSENT ** have the same
1546            run-time representation, and one can convert sp->fts_compar to
1547            the type qsort expects without problem.  Use the heuristic that
1548            this is OK if the two pointer types are the same size, and if
1549            converting FTSENT ** to long int is the same as converting
1550            FTSENT ** to void * and then to long int.  This heuristic isn't
1551            valid in general but we don't know of any counterexamples.  */
1552         FTSENT *dummy;
1553         int (*compare) (void const *, void const *) =
1554           ((sizeof &dummy == sizeof (void *)
1555             && (long int) &dummy == (long int) (void *) &dummy)
1556            ? (int (*) (void const *, void const *)) sp->fts_compar
1557            : fts_compar);
1558
1559         /*
1560          * Construct an array of pointers to the structures and call qsort(3).
1561          * Reassemble the array in the order returned by qsort.  If unable to
1562          * sort for memory reasons, return the directory entries in their
1563          * current order.  Allocate enough space for the current needs plus
1564          * 40 so don't realloc one entry at a time.
1565          */
1566         if (nitems > sp->fts_nitems) {
1567                 FTSENT **a;
1568
1569                 sp->fts_nitems = nitems + 40;
1570                 if (SIZE_MAX / sizeof *a < sp->fts_nitems
1571                     || ! (a = realloc (sp->fts_array,
1572                                        sp->fts_nitems * sizeof *a))) {
1573                         free(sp->fts_array);
1574                         sp->fts_array = NULL;
1575                         sp->fts_nitems = 0;
1576                         return (head);
1577                 }
1578                 sp->fts_array = a;
1579         }
1580         for (ap = sp->fts_array, p = head; p; p = p->fts_link)
1581                 *ap++ = p;
1582         qsort((void *)sp->fts_array, nitems, sizeof(FTSENT *), compare);
1583         for (head = *(ap = sp->fts_array); --nitems; ++ap)
1584                 ap[0]->fts_link = ap[1];
1585         ap[0]->fts_link = NULL;
1586         return (head);
1587 }
1588
1589 static FTSENT *
1590 internal_function
1591 fts_alloc (FTS *sp, const char *name, register size_t namelen)
1592 {
1593         register FTSENT *p;
1594         size_t len;
1595
1596         /*
1597          * The file name is a variable length array.  Allocate the FTSENT
1598          * structure and the file name in one chunk.
1599          */
1600         len = sizeof(FTSENT) + namelen;
1601         if ((p = malloc(len)) == NULL)
1602                 return (NULL);
1603
1604         /* Copy the name and guarantee NUL termination. */
1605         memmove(p->fts_name, name, namelen);
1606         p->fts_name[namelen] = '\0';
1607
1608         p->fts_namelen = namelen;
1609         p->fts_fts = sp;
1610         p->fts_path = sp->fts_path;
1611         p->fts_errno = 0;
1612         p->fts_flags = 0;
1613         p->fts_instr = FTS_NOINSTR;
1614         p->fts_number = 0;
1615         p->fts_pointer = NULL;
1616         return (p);
1617 }
1618
1619 static void
1620 internal_function
1621 fts_lfree (register FTSENT *head)
1622 {
1623         register FTSENT *p;
1624
1625         /* Free a linked list of structures. */
1626         while ((p = head)) {
1627                 head = head->fts_link;
1628                 free(p);
1629         }
1630 }
1631
1632 /*
1633  * Allow essentially unlimited file name lengths; find, rm, ls should
1634  * all work on any tree.  Most systems will allow creation of file
1635  * names much longer than MAXPATHLEN, even though the kernel won't
1636  * resolve them.  Add the size (not just what's needed) plus 256 bytes
1637  * so don't realloc the file name 2 bytes at a time.
1638  */
1639 static bool
1640 internal_function
1641 fts_palloc (FTS *sp, size_t more)
1642 {
1643         char *p;
1644         size_t new_len = sp->fts_pathlen + more + 256;
1645
1646         /*
1647          * See if fts_pathlen would overflow.
1648          */
1649         if (new_len < sp->fts_pathlen) {
1650                 free(sp->fts_path);
1651                 sp->fts_path = NULL;
1652                 __set_errno (ENAMETOOLONG);
1653                 return false;
1654         }
1655         sp->fts_pathlen = new_len;
1656         p = realloc(sp->fts_path, sp->fts_pathlen);
1657         if (p == NULL) {
1658                 free(sp->fts_path);
1659                 sp->fts_path = NULL;
1660                 return false;
1661         }
1662         sp->fts_path = p;
1663         return true;
1664 }
1665
1666 /*
1667  * When the file name is realloc'd, have to fix all of the pointers in
1668  *  structures already returned.
1669  */
1670 static void
1671 internal_function
1672 fts_padjust (FTS *sp, FTSENT *head)
1673 {
1674         FTSENT *p;
1675         char *addr = sp->fts_path;
1676
1677 #define ADJUST(p) do {                                                  \
1678         if ((p)->fts_accpath != (p)->fts_name) {                        \
1679                 (p)->fts_accpath =                                      \
1680                     (char *)addr + ((p)->fts_accpath - (p)->fts_path);  \
1681         }                                                               \
1682         (p)->fts_path = addr;                                           \
1683 } while (0)
1684         /* Adjust the current set of children. */
1685         for (p = sp->fts_child; p; p = p->fts_link)
1686                 ADJUST(p);
1687
1688         /* Adjust the rest of the tree, including the current level. */
1689         for (p = head; p->fts_level >= FTS_ROOTLEVEL;) {
1690                 ADJUST(p);
1691                 p = p->fts_link ? p->fts_link : p->fts_parent;
1692         }
1693 }
1694
1695 static size_t
1696 internal_function
1697 fts_maxarglen (char * const *argv)
1698 {
1699         size_t len, max;
1700
1701         for (max = 0; *argv; ++argv)
1702                 if ((len = strlen(*argv)) > max)
1703                         max = len;
1704         return (max + 1);
1705 }
1706
1707 /*
1708  * Change to dir specified by fd or file name without getting
1709  * tricked by someone changing the world out from underneath us.
1710  * Assumes p->fts_statp->st_dev and p->fts_statp->st_ino are filled in.
1711  * If FD is non-negative, expect it to be used after this function returns,
1712  * and to be closed eventually.  So don't pass e.g., `dirfd(dirp)' and then
1713  * do closedir(dirp), because that would invalidate the saved FD.
1714  * Upon failure, close FD immediately and return nonzero.
1715  */
1716 static int
1717 internal_function
1718 fts_safe_changedir (FTS *sp, FTSENT *p, int fd, char const *dir)
1719 {
1720         int ret;
1721         bool is_dotdot = dir && STREQ (dir, "..");
1722         int newfd;
1723
1724         /* This clause handles the unusual case in which FTS_NOCHDIR
1725            is specified, along with FTS_CWDFD.  In that case, there is
1726            no need to change even the virtual cwd file descriptor.
1727            However, if FD is non-negative, we do close it here.  */
1728         if (ISSET (FTS_NOCHDIR))
1729           {
1730             if (ISSET (FTS_CWDFD) && 0 <= fd)
1731               close (fd);
1732             return 0;
1733           }
1734
1735         if (fd < 0 && is_dotdot && ISSET (FTS_CWDFD))
1736           {
1737             /* When possible, skip the diropen and subsequent fstat+dev/ino
1738                comparison.  I.e., when changing to parent directory
1739                (chdir ("..")), use a file descriptor from the ring and
1740                save the overhead of diropen+fstat, as well as avoiding
1741                failure when we lack "x" access to the virtual cwd.  */
1742             if ( ! i_ring_empty (&sp->fts_fd_ring))
1743               {
1744                 int parent_fd;
1745                 fd_ring_print (sp, stderr, "pre-pop");
1746                 parent_fd = i_ring_pop (&sp->fts_fd_ring);
1747                 is_dotdot = true;
1748                 if (0 <= parent_fd)
1749                   {
1750                     fd = parent_fd;
1751                     dir = NULL;
1752                   }
1753               }
1754           }
1755
1756         newfd = fd;
1757         if (fd < 0 && (newfd = diropen (sp, dir)) < 0)
1758           return -1;
1759
1760         /* The following dev/inode check is necessary if we're doing a
1761            `logical' traversal (through symlinks, a la chown -L), if the
1762            system lacks O_NOFOLLOW support, or if we're changing to ".."
1763            (but not via a popped file descriptor).  When changing to the
1764            name "..", O_NOFOLLOW can't help.  In general, when the target is
1765            not "..", diropen's use of O_NOFOLLOW ensures we don't mistakenly
1766            follow a symlink, so we can avoid the expense of this fstat.  */
1767         if (ISSET(FTS_LOGICAL) || ! HAVE_WORKING_O_NOFOLLOW
1768             || (dir && STREQ (dir, "..")))
1769           {
1770             struct stat sb;
1771             if (fstat(newfd, &sb))
1772               {
1773                 ret = -1;
1774                 goto bail;
1775               }
1776             if (p->fts_statp->st_dev != sb.st_dev
1777                 || p->fts_statp->st_ino != sb.st_ino)
1778               {
1779                 __set_errno (ENOENT);           /* disinformation */
1780                 ret = -1;
1781                 goto bail;
1782               }
1783           }
1784
1785         if (ISSET(FTS_CWDFD))
1786           {
1787             cwd_advance_fd (sp, newfd, ! is_dotdot);
1788             return 0;
1789           }
1790
1791         ret = fchdir(newfd);
1792 bail:
1793         if (fd < 0)
1794           {
1795             int oerrno = errno;
1796             (void)close(newfd);
1797             __set_errno (oerrno);
1798           }
1799         return ret;
1800 }