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