New module 'fchdir'.
[gnulib.git] / lib / glob.c
1 /* Copyright (C) 1991-2002,2003,2004,2005,2006 Free Software Foundation, Inc.
2    This file is part of the GNU C Library.
3
4    The GNU C Library is free software; you can redistribute it and/or
5    modify it under the terms of the GNU Lesser General Public
6    License as published by the Free Software Foundation; either
7    version 2.1 of the License, or (at your option) any later version.
8
9    The GNU C Library is distributed in the hope that it will be useful,
10    but WITHOUT ANY WARRANTY; without even the implied warranty of
11    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
12    Lesser General Public License for more details.
13
14    You should have received a copy of the GNU Lesser General Public
15    License along with the GNU C Library; if not, write to the Free
16    Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA
17    02111-1307 USA.  */
18
19 #ifndef _LIBC
20 # include <config.h>
21 #endif
22
23 #include <glob.h>
24
25 #include <errno.h>
26 #include <sys/types.h>
27 #include <sys/stat.h>
28 #include <stddef.h>
29
30 /* Outcomment the following line for production quality code.  */
31 /* #define NDEBUG 1 */
32 #include <assert.h>
33
34 #include <stdio.h>              /* Needed on stupid SunOS for assert.  */
35
36 #if !defined _LIBC || !defined GLOB_ONLY_P
37
38 #include <unistd.h>
39 #if !defined POSIX && defined _POSIX_VERSION
40 # define POSIX
41 #endif
42
43 #include <pwd.h>
44
45 #include <errno.h>
46 #ifndef __set_errno
47 # define __set_errno(val) errno = (val)
48 #endif
49
50 #include <dirent.h>
51
52
53 /* In GNU systems, <dirent.h> defines this macro for us.  */
54 #ifndef _D_EXACT_NAMLEN
55 # define _D_EXACT_NAMLEN(dirent) strlen ((dirent)->d_name)
56 #endif
57
58 /* When used in the GNU libc the symbol _DIRENT_HAVE_D_TYPE is available
59    if the `d_type' member for `struct dirent' is available.
60    HAVE_STRUCT_DIRENT_D_TYPE plays the same role in GNULIB.  */
61 #if defined _DIRENT_HAVE_D_TYPE || defined HAVE_STRUCT_DIRENT_D_TYPE
62 /* True if the directory entry D must be of type T.  */
63 # define DIRENT_MUST_BE(d, t)   ((d)->d_type == (t))
64
65 /* True if the directory entry D might be a symbolic link.  */
66 # define DIRENT_MIGHT_BE_SYMLINK(d) \
67     ((d)->d_type == DT_UNKNOWN || (d)->d_type == DT_LNK)
68
69 /* True if the directory entry D might be a directory.  */
70 # define DIRENT_MIGHT_BE_DIR(d)  \
71     ((d)->d_type == DT_DIR || DIRENT_MIGHT_BE_SYMLINK (d))
72
73 #else /* !HAVE_D_TYPE */
74 # define DIRENT_MUST_BE(d, t)           false
75 # define DIRENT_MIGHT_BE_SYMLINK(d)     true
76 # define DIRENT_MIGHT_BE_DIR(d)         true
77 #endif /* HAVE_D_TYPE */
78
79 /* If the system has the `struct dirent64' type we use it internally.  */
80 #if defined _LIBC && !defined COMPILE_GLOB64
81 # if (defined POSIX || defined WINDOWS32) && !defined __GNU_LIBRARY__
82 #  define CONVERT_D_INO(d64, d32)
83 # else
84 #  define CONVERT_D_INO(d64, d32) \
85   (d64)->d_ino = (d32)->d_ino;
86 # endif
87
88 # ifdef _DIRENT_HAVE_D_TYPE
89 #  define CONVERT_D_TYPE(d64, d32) \
90   (d64)->d_type = (d32)->d_type;
91 # else
92 #  define CONVERT_D_TYPE(d64, d32)
93 # endif
94
95 # define CONVERT_DIRENT_DIRENT64(d64, d32) \
96   memcpy ((d64)->d_name, (d32)->d_name, _D_EXACT_NAMLEN (d32) + 1);           \
97   CONVERT_D_INO (d64, d32)                                                    \
98   CONVERT_D_TYPE (d64, d32)
99 #endif
100
101
102 #if (defined POSIX || defined WINDOWS32) && !defined __GNU_LIBRARY__
103 /* Posix does not require that the d_ino field be present, and some
104    systems do not provide it. */
105 # define REAL_DIR_ENTRY(dp) 1
106 #else
107 # define REAL_DIR_ENTRY(dp) (dp->d_ino != 0)
108 #endif /* POSIX */
109
110 #include <stdlib.h>
111 #include <string.h>
112
113 /* NAME_MAX is usually defined in <dirent.h> or <limits.h>.  */
114 #include <limits.h>
115 #ifndef NAME_MAX
116 # define NAME_MAX (sizeof (((struct dirent *) 0)->d_name))
117 #endif
118
119 #include <alloca.h>
120
121 #ifdef _LIBC
122 # undef strdup
123 # define strdup(str) __strdup (str)
124 # define sysconf(id) __sysconf (id)
125 # define closedir(dir) __closedir (dir)
126 # define opendir(name) __opendir (name)
127 # define readdir(str) __readdir64 (str)
128 # define getpwnam_r(name, bufp, buf, len, res) \
129    __getpwnam_r (name, bufp, buf, len, res)
130 # ifndef __stat64
131 #  define __stat64(fname, buf) __xstat64 (_STAT_VER, fname, buf)
132 # endif
133 # define struct_stat64          struct stat64
134 #else /* !_LIBC */
135 # include "getlogin_r.h"
136 # include "mempcpy.h"
137 # include "strdup.h"
138 # define __stat64(fname, buf)   stat (fname, buf)
139 # define struct_stat64          struct stat
140 # define __stat(fname, buf)     stat (fname, buf)
141 # define __alloca               alloca
142 # define __readdir              readdir
143 # define __readdir64            readdir64
144 # define __glob_pattern_p       glob_pattern_p
145 #endif /* _LIBC */
146
147 #include <stdbool.h>
148 #include <fnmatch.h>
149
150 #ifdef _SC_GETPW_R_SIZE_MAX
151 # define GETPW_R_SIZE_MAX()     sysconf (_SC_GETPW_R_SIZE_MAX)
152 #else
153 # define GETPW_R_SIZE_MAX()     (-1)
154 #endif
155 #ifdef _SC_LOGIN_NAME_MAX
156 # define GET_LOGIN_NAME_MAX()   sysconf (_SC_LOGIN_NAME_MAX)
157 #else
158 # define GET_LOGIN_NAME_MAX()   (-1)
159 #endif
160 \f
161 static const char *next_brace_sub (const char *begin, int flags) __THROW;
162
163 #endif /* !defined _LIBC || !defined GLOB_ONLY_P */
164
165 /* The results of opendir() in this file are not used with dirfd and fchdir,
166    therefore save some unnecessary work in fchdir.c.  */
167 #undef opendir
168 #undef closedir
169
170 static int glob_in_dir (const char *pattern, const char *directory,
171                         int flags, int (*errfunc) (const char *, int),
172                         glob_t *pglob);
173
174 #if !defined _LIBC || !defined GLOB_ONLY_P
175 static int prefix_array (const char *prefix, char **array, size_t n) __THROW;
176 static int collated_compare (const void *, const void *) __THROW;
177
178
179 /* Find the end of the sub-pattern in a brace expression.  */
180 static const char *
181 next_brace_sub (const char *cp, int flags)
182 {
183   unsigned int depth = 0;
184   while (*cp != '\0')
185     if ((flags & GLOB_NOESCAPE) == 0 && *cp == '\\')
186       {
187         if (*++cp == '\0')
188           break;
189         ++cp;
190       }
191     else
192       {
193         if ((*cp == '}' && depth-- == 0) || (*cp == ',' && depth == 0))
194           break;
195
196         if (*cp++ == '{')
197           depth++;
198       }
199
200   return *cp != '\0' ? cp : NULL;
201 }
202
203 #endif /* !defined _LIBC || !defined GLOB_ONLY_P */
204
205 /* Do glob searching for PATTERN, placing results in PGLOB.
206    The bits defined above may be set in FLAGS.
207    If a directory cannot be opened or read and ERRFUNC is not nil,
208    it is called with the pathname that caused the error, and the
209    `errno' value from the failing call; if it returns non-zero
210    `glob' returns GLOB_ABORTED; if it returns zero, the error is ignored.
211    If memory cannot be allocated for PGLOB, GLOB_NOSPACE is returned.
212    Otherwise, `glob' returns zero.  */
213 int
214 #ifdef GLOB_ATTRIBUTE
215 GLOB_ATTRIBUTE
216 #endif
217 glob (pattern, flags, errfunc, pglob)
218      const char *pattern;
219      int flags;
220      int (*errfunc) (const char *, int);
221      glob_t *pglob;
222 {
223   const char *filename;
224   const char *dirname;
225   size_t dirlen;
226   int status;
227   size_t oldcount;
228
229   if (pattern == NULL || pglob == NULL || (flags & ~__GLOB_FLAGS) != 0)
230     {
231       __set_errno (EINVAL);
232       return -1;
233     }
234
235   if (!(flags & GLOB_DOOFFS))
236     /* Have to do this so `globfree' knows where to start freeing.  It
237        also makes all the code that uses gl_offs simpler. */
238     pglob->gl_offs = 0;
239
240   if (flags & GLOB_BRACE)
241     {
242       const char *begin;
243
244       if (flags & GLOB_NOESCAPE)
245         begin = strchr (pattern, '{');
246       else
247         {
248           begin = pattern;
249           while (1)
250             {
251               if (*begin == '\0')
252                 {
253                   begin = NULL;
254                   break;
255                 }
256
257               if (*begin == '\\' && begin[1] != '\0')
258                 ++begin;
259               else if (*begin == '{')
260                 break;
261
262               ++begin;
263             }
264         }
265
266       if (begin != NULL)
267         {
268           /* Allocate working buffer large enough for our work.  Note that
269             we have at least an opening and closing brace.  */
270           size_t firstc;
271           char *alt_start;
272           const char *p;
273           const char *next;
274           const char *rest;
275           size_t rest_len;
276 #ifdef __GNUC__
277           char onealt[strlen (pattern) - 1];
278 #else
279           char *onealt = malloc (strlen (pattern) - 1);
280           if (onealt == NULL)
281             {
282               if (!(flags & GLOB_APPEND))
283                 {
284                   pglob->gl_pathc = 0;
285                   pglob->gl_pathv = NULL;
286                 }
287               return GLOB_NOSPACE;
288             }
289 #endif
290
291           /* We know the prefix for all sub-patterns.  */
292           alt_start = mempcpy (onealt, pattern, begin - pattern);
293
294           /* Find the first sub-pattern and at the same time find the
295              rest after the closing brace.  */
296           next = next_brace_sub (begin + 1, flags);
297           if (next == NULL)
298             {
299               /* It is an invalid expression.  */
300 #ifndef __GNUC__
301               free (onealt);
302 #endif
303               return glob (pattern, flags & ~GLOB_BRACE, errfunc, pglob);
304             }
305
306           /* Now find the end of the whole brace expression.  */
307           rest = next;
308           while (*rest != '}')
309             {
310               rest = next_brace_sub (rest + 1, flags);
311               if (rest == NULL)
312                 {
313                   /* It is an invalid expression.  */
314 #ifndef __GNUC__
315                   free (onealt);
316 #endif
317                   return glob (pattern, flags & ~GLOB_BRACE, errfunc, pglob);
318                 }
319             }
320           /* Please note that we now can be sure the brace expression
321              is well-formed.  */
322           rest_len = strlen (++rest) + 1;
323
324           /* We have a brace expression.  BEGIN points to the opening {,
325              NEXT points past the terminator of the first element, and END
326              points past the final }.  We will accumulate result names from
327              recursive runs for each brace alternative in the buffer using
328              GLOB_APPEND.  */
329
330           if (!(flags & GLOB_APPEND))
331             {
332               /* This call is to set a new vector, so clear out the
333                  vector so we can append to it.  */
334               pglob->gl_pathc = 0;
335               pglob->gl_pathv = NULL;
336             }
337           firstc = pglob->gl_pathc;
338
339           p = begin + 1;
340           while (1)
341             {
342               int result;
343
344               /* Construct the new glob expression.  */
345               mempcpy (mempcpy (alt_start, p, next - p), rest, rest_len);
346
347               result = glob (onealt,
348                              ((flags & ~(GLOB_NOCHECK | GLOB_NOMAGIC))
349                               | GLOB_APPEND), errfunc, pglob);
350
351               /* If we got an error, return it.  */
352               if (result && result != GLOB_NOMATCH)
353                 {
354 #ifndef __GNUC__
355                   free (onealt);
356 #endif
357                   if (!(flags & GLOB_APPEND))
358                     {
359                       globfree (pglob);
360                       pglob->gl_pathc = 0;
361                     }
362                   return result;
363                 }
364
365               if (*next == '}')
366                 /* We saw the last entry.  */
367                 break;
368
369               p = next + 1;
370               next = next_brace_sub (p, flags);
371               assert (next != NULL);
372             }
373
374 #ifndef __GNUC__
375           free (onealt);
376 #endif
377
378           if (pglob->gl_pathc != firstc)
379             /* We found some entries.  */
380             return 0;
381           else if (!(flags & (GLOB_NOCHECK|GLOB_NOMAGIC)))
382             return GLOB_NOMATCH;
383         }
384     }
385
386   /* Find the filename.  */
387   filename = strrchr (pattern, '/');
388 #if defined __MSDOS__ || defined WINDOWS32
389   /* The case of "d:pattern".  Since `:' is not allowed in
390      file names, we can safely assume that wherever it
391      happens in pattern, it signals the filename part.  This
392      is so we could some day support patterns like "[a-z]:foo".  */
393   if (filename == NULL)
394     filename = strchr (pattern, ':');
395 #endif /* __MSDOS__ || WINDOWS32 */
396   if (filename == NULL)
397     {
398       /* This can mean two things: a simple name or "~name".  The latter
399          case is nothing but a notation for a directory.  */
400       if ((flags & (GLOB_TILDE|GLOB_TILDE_CHECK)) && pattern[0] == '~')
401         {
402           dirname = pattern;
403           dirlen = strlen (pattern);
404
405           /* Set FILENAME to NULL as a special flag.  This is ugly but
406              other solutions would require much more code.  We test for
407              this special case below.  */
408           filename = NULL;
409         }
410       else
411         {
412           filename = pattern;
413 #ifdef _AMIGA
414           dirname = "";
415 #else
416           dirname = ".";
417 #endif
418           dirlen = 0;
419         }
420     }
421   else if (filename == pattern)
422     {
423       /* "/pattern".  */
424       dirname = "/";
425       dirlen = 1;
426       ++filename;
427     }
428   else
429     {
430       char *newp;
431       dirlen = filename - pattern;
432 #if defined __MSDOS__ || defined WINDOWS32
433       if (*filename == ':'
434           || (filename > pattern + 1 && filename[-1] == ':'))
435         {
436           char *drive_spec;
437
438           ++dirlen;
439           drive_spec = __alloca (dirlen + 1);
440           *((char *) mempcpy (drive_spec, pattern, dirlen)) = '\0';
441           /* For now, disallow wildcards in the drive spec, to
442              prevent infinite recursion in glob.  */
443           if (__glob_pattern_p (drive_spec, !(flags & GLOB_NOESCAPE)))
444             return GLOB_NOMATCH;
445           /* If this is "d:pattern", we need to copy `:' to DIRNAME
446              as well.  If it's "d:/pattern", don't remove the slash
447              from "d:/", since "d:" and "d:/" are not the same.*/
448         }
449 #endif
450       newp = __alloca (dirlen + 1);
451       *((char *) mempcpy (newp, pattern, dirlen)) = '\0';
452       dirname = newp;
453       ++filename;
454
455       if (filename[0] == '\0'
456 #if defined __MSDOS__ || defined WINDOWS32
457           && dirname[dirlen - 1] != ':'
458           && (dirlen < 3 || dirname[dirlen - 2] != ':'
459               || dirname[dirlen - 1] != '/')
460 #endif
461           && dirlen > 1)
462         /* "pattern/".  Expand "pattern", appending slashes.  */
463         {
464           int val = glob (dirname, flags | GLOB_MARK, errfunc, pglob);
465           if (val == 0)
466             pglob->gl_flags = ((pglob->gl_flags & ~GLOB_MARK)
467                                | (flags & GLOB_MARK));
468           return val;
469         }
470     }
471
472   if (!(flags & GLOB_APPEND))
473     {
474       pglob->gl_pathc = 0;
475       if (!(flags & GLOB_DOOFFS))
476         pglob->gl_pathv = NULL;
477       else
478         {
479           size_t i;
480           pglob->gl_pathv = malloc ((pglob->gl_offs + 1) * sizeof (char *));
481           if (pglob->gl_pathv == NULL)
482             return GLOB_NOSPACE;
483
484           for (i = 0; i <= pglob->gl_offs; ++i)
485             pglob->gl_pathv[i] = NULL;
486         }
487     }
488
489   oldcount = pglob->gl_pathc + pglob->gl_offs;
490
491   if ((flags & (GLOB_TILDE|GLOB_TILDE_CHECK)) && dirname[0] == '~')
492     {
493       if (dirname[1] == '\0' || dirname[1] == '/')
494         {
495           /* Look up home directory.  */
496           const char *home_dir = getenv ("HOME");
497 # ifdef _AMIGA
498           if (home_dir == NULL || home_dir[0] == '\0')
499             home_dir = "SYS:";
500 # else
501 #  ifdef WINDOWS32
502           if (home_dir == NULL || home_dir[0] == '\0')
503             home_dir = "c:/users/default"; /* poor default */
504 #  else
505           if (home_dir == NULL || home_dir[0] == '\0')
506             {
507               int success;
508               char *name;
509               size_t buflen = GET_LOGIN_NAME_MAX () + 1;
510
511               if (buflen == 0)
512                 /* `sysconf' does not support _SC_LOGIN_NAME_MAX.  Try
513                    a moderate value.  */
514                 buflen = 20;
515               name = __alloca (buflen);
516
517               success = getlogin_r (name, buflen) == 0;
518               if (success)
519                 {
520                   struct passwd *p;
521 #   if defined HAVE_GETPWNAM_R || defined _LIBC
522                   long int pwbuflen = GETPW_R_SIZE_MAX ();
523                   char *pwtmpbuf;
524                   struct passwd pwbuf;
525                   int save = errno;
526
527 #    ifndef _LIBC
528                   if (pwbuflen == -1)
529                     /* `sysconf' does not support _SC_GETPW_R_SIZE_MAX.
530                        Try a moderate value.  */
531                     pwbuflen = 1024;
532 #    endif
533                   pwtmpbuf = __alloca (pwbuflen);
534
535                   while (getpwnam_r (name, &pwbuf, pwtmpbuf, pwbuflen, &p)
536                          != 0)
537                     {
538                       if (errno != ERANGE)
539                         {
540                           p = NULL;
541                           break;
542                         }
543 #    ifdef _LIBC
544                       pwtmpbuf = extend_alloca (pwtmpbuf, pwbuflen,
545                                                 2 * pwbuflen);
546 #    else
547                       pwbuflen *= 2;
548                       pwtmpbuf = __alloca (pwbuflen);
549 #    endif
550                       __set_errno (save);
551                     }
552 #   else
553                   p = getpwnam (name);
554 #   endif
555                   if (p != NULL)
556                     home_dir = p->pw_dir;
557                 }
558             }
559           if (home_dir == NULL || home_dir[0] == '\0')
560             {
561               if (flags & GLOB_TILDE_CHECK)
562                 return GLOB_NOMATCH;
563               else
564                 home_dir = "~"; /* No luck.  */
565             }
566 #  endif /* WINDOWS32 */
567 # endif
568           /* Now construct the full directory.  */
569           if (dirname[1] == '\0')
570             dirname = home_dir;
571           else
572             {
573               char *newp;
574               size_t home_len = strlen (home_dir);
575               newp = __alloca (home_len + dirlen);
576               mempcpy (mempcpy (newp, home_dir, home_len),
577                        &dirname[1], dirlen);
578               dirname = newp;
579             }
580         }
581 # if !defined _AMIGA && !defined WINDOWS32
582       else
583         {
584           char *end_name = strchr (dirname, '/');
585           const char *user_name;
586           const char *home_dir;
587
588           if (end_name == NULL)
589             user_name = dirname + 1;
590           else
591             {
592               char *newp;
593               newp = __alloca (end_name - dirname);
594               *((char *) mempcpy (newp, dirname + 1, end_name - dirname))
595                 = '\0';
596               user_name = newp;
597             }
598
599           /* Look up specific user's home directory.  */
600           {
601             struct passwd *p;
602 #  if defined HAVE_GETPWNAM_R || defined _LIBC
603             long int buflen = GETPW_R_SIZE_MAX ();
604             char *pwtmpbuf;
605             struct passwd pwbuf;
606             int save = errno;
607
608 #   ifndef _LIBC
609             if (buflen == -1)
610               /* `sysconf' does not support _SC_GETPW_R_SIZE_MAX.  Try a
611                  moderate value.  */
612               buflen = 1024;
613 #   endif
614             pwtmpbuf = __alloca (buflen);
615
616             while (getpwnam_r (user_name, &pwbuf, pwtmpbuf, buflen, &p) != 0)
617               {
618                 if (errno != ERANGE)
619                   {
620                     p = NULL;
621                     break;
622                   }
623 #   ifdef _LIBC
624                 pwtmpbuf = extend_alloca (pwtmpbuf, buflen, 2 * buflen);
625 #   else
626                 buflen *= 2;
627                 pwtmpbuf = __alloca (buflen);
628 #   endif
629                 __set_errno (save);
630               }
631 #  else
632             p = getpwnam (user_name);
633 #  endif
634             if (p != NULL)
635               home_dir = p->pw_dir;
636             else
637               home_dir = NULL;
638           }
639           /* If we found a home directory use this.  */
640           if (home_dir != NULL)
641             {
642               char *newp;
643               size_t home_len = strlen (home_dir);
644               size_t rest_len = end_name == NULL ? 0 : strlen (end_name);
645               newp = __alloca (home_len + rest_len + 1);
646               *((char *) mempcpy (mempcpy (newp, home_dir, home_len),
647                                   end_name, rest_len)) = '\0';
648               dirname = newp;
649             }
650           else
651             if (flags & GLOB_TILDE_CHECK)
652               /* We have to regard it as an error if we cannot find the
653                  home directory.  */
654               return GLOB_NOMATCH;
655         }
656 # endif /* Not Amiga && not WINDOWS32.  */
657     }
658
659   /* Now test whether we looked for "~" or "~NAME".  In this case we
660      can give the answer now.  */
661   if (filename == NULL)
662     {
663       struct stat st;
664       struct_stat64 st64;
665
666       /* Return the directory if we don't check for error or if it exists.  */
667       if ((flags & GLOB_NOCHECK)
668           || (((flags & GLOB_ALTDIRFUNC)
669                ? ((*pglob->gl_stat) (dirname, &st) == 0
670                   && S_ISDIR (st.st_mode))
671                : (__stat64 (dirname, &st64) == 0 && S_ISDIR (st64.st_mode)))))
672         {
673           int newcount = pglob->gl_pathc + pglob->gl_offs;
674           char **new_gl_pathv;
675
676           new_gl_pathv
677             = realloc (pglob->gl_pathv, (newcount + 1 + 1) * sizeof (char *));
678           if (new_gl_pathv == NULL)
679             {
680             nospace:
681               free (pglob->gl_pathv);
682               pglob->gl_pathv = NULL;
683               pglob->gl_pathc = 0;
684               return GLOB_NOSPACE;
685             }
686           pglob->gl_pathv = new_gl_pathv;
687
688            pglob->gl_pathv[newcount] = strdup (dirname);
689           if (pglob->gl_pathv[newcount] == NULL)
690             goto nospace;
691           pglob->gl_pathv[++newcount] = NULL;
692           ++pglob->gl_pathc;
693           pglob->gl_flags = flags;
694
695           return 0;
696         }
697
698       /* Not found.  */
699       return GLOB_NOMATCH;
700     }
701
702   if (__glob_pattern_p (dirname, !(flags & GLOB_NOESCAPE)))
703     {
704       /* The directory name contains metacharacters, so we
705          have to glob for the directory, and then glob for
706          the pattern in each directory found.  */
707       glob_t dirs;
708       size_t i;
709
710       if ((flags & GLOB_ALTDIRFUNC) != 0)
711         {
712           /* Use the alternative access functions also in the recursive
713              call.  */
714           dirs.gl_opendir = pglob->gl_opendir;
715           dirs.gl_readdir = pglob->gl_readdir;
716           dirs.gl_closedir = pglob->gl_closedir;
717           dirs.gl_stat = pglob->gl_stat;
718           dirs.gl_lstat = pglob->gl_lstat;
719         }
720
721       status = glob (dirname,
722                      ((flags & (GLOB_ERR | GLOB_NOCHECK | GLOB_NOESCAPE
723                                 | GLOB_ALTDIRFUNC))
724                       | GLOB_NOSORT | GLOB_ONLYDIR),
725                      errfunc, &dirs);
726       if (status != 0)
727         return status;
728
729       /* We have successfully globbed the preceding directory name.
730          For each name we found, call glob_in_dir on it and FILENAME,
731          appending the results to PGLOB.  */
732       for (i = 0; i < dirs.gl_pathc; ++i)
733         {
734           int old_pathc;
735
736 #ifdef  SHELL
737           {
738             /* Make globbing interruptible in the bash shell. */
739             extern int interrupt_state;
740
741             if (interrupt_state)
742               {
743                 globfree (&dirs);
744                 return GLOB_ABORTED;
745               }
746           }
747 #endif /* SHELL.  */
748
749           old_pathc = pglob->gl_pathc;
750           status = glob_in_dir (filename, dirs.gl_pathv[i],
751                                 ((flags | GLOB_APPEND)
752                                  & ~(GLOB_NOCHECK | GLOB_NOMAGIC)),
753                                 errfunc, pglob);
754           if (status == GLOB_NOMATCH)
755             /* No matches in this directory.  Try the next.  */
756             continue;
757
758           if (status != 0)
759             {
760               globfree (&dirs);
761               globfree (pglob);
762               pglob->gl_pathc = 0;
763               return status;
764             }
765
766           /* Stick the directory on the front of each name.  */
767           if (prefix_array (dirs.gl_pathv[i],
768                             &pglob->gl_pathv[old_pathc + pglob->gl_offs],
769                             pglob->gl_pathc - old_pathc))
770             {
771               globfree (&dirs);
772               globfree (pglob);
773               pglob->gl_pathc = 0;
774               return GLOB_NOSPACE;
775             }
776         }
777
778       flags |= GLOB_MAGCHAR;
779
780       /* We have ignored the GLOB_NOCHECK flag in the `glob_in_dir' calls.
781          But if we have not found any matching entry and the GLOB_NOCHECK
782          flag was set we must return the input pattern itself.  */
783       if (pglob->gl_pathc + pglob->gl_offs == oldcount)
784         {
785           /* No matches.  */
786           if (flags & GLOB_NOCHECK)
787             {
788               int newcount = pglob->gl_pathc + pglob->gl_offs;
789               char **new_gl_pathv;
790
791               new_gl_pathv = realloc (pglob->gl_pathv,
792                                       (newcount + 2) * sizeof (char *));
793               if (new_gl_pathv == NULL)
794                 {
795                   globfree (&dirs);
796                   return GLOB_NOSPACE;
797                 }
798               pglob->gl_pathv = new_gl_pathv;
799
800               pglob->gl_pathv[newcount] = strdup (pattern);
801               if (pglob->gl_pathv[newcount] == NULL)
802                 {
803                   globfree (&dirs);
804                   globfree (pglob);
805                   pglob->gl_pathc = 0;
806                   return GLOB_NOSPACE;
807                 }
808
809               ++pglob->gl_pathc;
810               ++newcount;
811
812               pglob->gl_pathv[newcount] = NULL;
813               pglob->gl_flags = flags;
814             }
815           else
816             {
817               globfree (&dirs);
818               return GLOB_NOMATCH;
819             }
820         }
821
822       globfree (&dirs);
823     }
824   else
825     {
826       int old_pathc = pglob->gl_pathc;
827
828       status = glob_in_dir (filename, dirname, flags, errfunc, pglob);
829       if (status != 0)
830         return status;
831
832       if (dirlen > 0)
833         {
834           /* Stick the directory on the front of each name.  */
835           if (prefix_array (dirname,
836                             &pglob->gl_pathv[old_pathc + pglob->gl_offs],
837                             pglob->gl_pathc - old_pathc))
838             {
839               globfree (pglob);
840               pglob->gl_pathc = 0;
841               return GLOB_NOSPACE;
842             }
843         }
844     }
845
846   if (!(flags & GLOB_NOSORT))
847     {
848       /* Sort the vector.  */
849       qsort (&pglob->gl_pathv[oldcount],
850              pglob->gl_pathc + pglob->gl_offs - oldcount,
851              sizeof (char *), collated_compare);
852     }
853
854   return 0;
855 }
856 #if defined _LIBC && !defined glob
857 libc_hidden_def (glob)
858 #endif
859
860
861 #if !defined _LIBC || !defined GLOB_ONLY_P
862
863 /* Free storage allocated in PGLOB by a previous `glob' call.  */
864 void
865 globfree (pglob)
866      register glob_t *pglob;
867 {
868   if (pglob->gl_pathv != NULL)
869     {
870       size_t i;
871       for (i = 0; i < pglob->gl_pathc; ++i)
872         if (pglob->gl_pathv[pglob->gl_offs + i] != NULL)
873           free (pglob->gl_pathv[pglob->gl_offs + i]);
874       free (pglob->gl_pathv);
875       pglob->gl_pathv = NULL;
876     }
877 }
878 #if defined _LIBC && !defined globfree
879 libc_hidden_def (globfree)
880 #endif
881
882
883 /* Do a collated comparison of A and B.  */
884 static int
885 collated_compare (const void *a, const void *b)
886 {
887   char *const *ps1 = a; char *s1 = *ps1;
888   char *const *ps2 = b; char *s2 = *ps2;
889
890   if (s1 == s2)
891     return 0;
892   if (s1 == NULL)
893     return 1;
894   if (s2 == NULL)
895     return -1;
896   return strcoll (s1, s2);
897 }
898
899
900 /* Prepend DIRNAME to each of N members of ARRAY, replacing ARRAY's
901    elements in place.  Return nonzero if out of memory, zero if successful.
902    A slash is inserted between DIRNAME and each elt of ARRAY,
903    unless DIRNAME is just "/".  Each old element of ARRAY is freed.  */
904 static int
905 prefix_array (const char *dirname, char **array, size_t n)
906 {
907   register size_t i;
908   size_t dirlen = strlen (dirname);
909 #if defined __MSDOS__ || defined WINDOWS32
910   int sep_char = '/';
911 # define DIRSEP_CHAR sep_char
912 #else
913 # define DIRSEP_CHAR '/'
914 #endif
915
916   if (dirlen == 1 && dirname[0] == '/')
917     /* DIRNAME is just "/", so normal prepending would get us "//foo".
918        We want "/foo" instead, so don't prepend any chars from DIRNAME.  */
919     dirlen = 0;
920 #if defined __MSDOS__ || defined WINDOWS32
921   else if (dirlen > 1)
922     {
923       if (dirname[dirlen - 1] == '/' && dirname[dirlen - 2] == ':')
924         /* DIRNAME is "d:/".  Don't prepend the slash from DIRNAME.  */
925         --dirlen;
926       else if (dirname[dirlen - 1] == ':')
927         {
928           /* DIRNAME is "d:".  Use `:' instead of `/'.  */
929           --dirlen;
930           sep_char = ':';
931         }
932     }
933 #endif
934
935   for (i = 0; i < n; ++i)
936     {
937       size_t eltlen = strlen (array[i]) + 1;
938       char *new = malloc (dirlen + 1 + eltlen);
939       if (new == NULL)
940         {
941           while (i > 0)
942             free (array[--i]);
943           return 1;
944         }
945
946       {
947         char *endp = mempcpy (new, dirname, dirlen);
948         *endp++ = DIRSEP_CHAR;
949         mempcpy (endp, array[i], eltlen);
950       }
951       free (array[i]);
952       array[i] = new;
953     }
954
955   return 0;
956 }
957
958
959 /* We must not compile this function twice.  */
960 #if !defined _LIBC || !defined NO_GLOB_PATTERN_P
961 /* Return nonzero if PATTERN contains any metacharacters.
962    Metacharacters can be quoted with backslashes if QUOTE is nonzero.  */
963 int
964 __glob_pattern_p (pattern, quote)
965      const char *pattern;
966      int quote;
967 {
968   register const char *p;
969   int open = 0;
970
971   for (p = pattern; *p != '\0'; ++p)
972     switch (*p)
973       {
974       case '?':
975       case '*':
976         return 1;
977
978       case '\\':
979         if (quote && p[1] != '\0')
980           ++p;
981         break;
982
983       case '[':
984         open = 1;
985         break;
986
987       case ']':
988         if (open)
989           return 1;
990         break;
991       }
992
993   return 0;
994 }
995 # ifdef _LIBC
996 weak_alias (__glob_pattern_p, glob_pattern_p)
997 # endif
998 #endif
999
1000 #endif /* !GLOB_ONLY_P */
1001
1002
1003 /* We put this in a separate function mainly to allow the memory
1004    allocated with alloca to be recycled.  */
1005 #if !defined _LIBC || !defined GLOB_ONLY_P
1006 static bool
1007 is_dir_p (const char *dir, size_t dirlen, const char *fname,
1008           glob_t *pglob, int flags)
1009 {
1010   size_t fnamelen = strlen (fname);
1011   char *fullname = __alloca (dirlen + 1 + fnamelen + 1);
1012   struct stat st;
1013   struct_stat64 st64;
1014
1015   mempcpy (mempcpy (mempcpy (fullname, dir, dirlen), "/", 1),
1016            fname, fnamelen + 1);
1017
1018   return ((flags & GLOB_ALTDIRFUNC)
1019           ? (*pglob->gl_stat) (fullname, &st) == 0 && S_ISDIR (st.st_mode)
1020           : __stat64 (fullname, &st64) == 0 && S_ISDIR (st64.st_mode));
1021 }
1022 #endif
1023
1024
1025 /* Like `glob', but PATTERN is a final pathname component,
1026    and matches are searched for in DIRECTORY.
1027    The GLOB_NOSORT bit in FLAGS is ignored.  No sorting is ever done.
1028    The GLOB_APPEND flag is assumed to be set (always appends).  */
1029 static int
1030 glob_in_dir (const char *pattern, const char *directory, int flags,
1031              int (*errfunc) (const char *, int),
1032              glob_t *pglob)
1033 {
1034   size_t dirlen = strlen (directory);
1035   void *stream = NULL;
1036   struct globlink
1037     {
1038       struct globlink *next;
1039       char *name;
1040     };
1041   struct globlink *names = NULL;
1042   size_t nfound;
1043   int meta;
1044   int save;
1045
1046   meta = __glob_pattern_p (pattern, !(flags & GLOB_NOESCAPE));
1047   if (meta == 0 && (flags & (GLOB_NOCHECK|GLOB_NOMAGIC)))
1048     {
1049       /* We need not do any tests.  The PATTERN contains no meta
1050          characters and we must not return an error therefore the
1051          result will always contain exactly one name.  */
1052       flags |= GLOB_NOCHECK;
1053       nfound = 0;
1054     }
1055   else if (meta == 0 &&
1056            ((flags & GLOB_NOESCAPE) || strchr (pattern, '\\') == NULL))
1057     {
1058       /* Since we use the normal file functions we can also use stat()
1059          to verify the file is there.  */
1060       struct stat st;
1061       struct_stat64 st64;
1062       size_t patlen = strlen (pattern);
1063       char *fullname = __alloca (dirlen + 1 + patlen + 1);
1064
1065       mempcpy (mempcpy (mempcpy (fullname, directory, dirlen),
1066                         "/", 1),
1067                pattern, patlen + 1);
1068       if (((flags & GLOB_ALTDIRFUNC)
1069            ? (*pglob->gl_stat) (fullname, &st)
1070            : __stat64 (fullname, &st64)) == 0)
1071         /* We found this file to be existing.  Now tell the rest
1072            of the function to copy this name into the result.  */
1073         flags |= GLOB_NOCHECK;
1074
1075       nfound = 0;
1076     }
1077   else
1078     {
1079       if (pattern[0] == '\0')
1080         {
1081           /* This is a special case for matching directories like in
1082              "*a/".  */
1083           names = __alloca (sizeof (struct globlink));
1084           names->name = malloc (1);
1085           if (names->name == NULL)
1086             goto memory_error;
1087           names->name[0] = '\0';
1088           names->next = NULL;
1089           nfound = 1;
1090           meta = 0;
1091         }
1092       else
1093         {
1094           stream = ((flags & GLOB_ALTDIRFUNC)
1095                     ? (*pglob->gl_opendir) (directory)
1096                     : opendir (directory));
1097           if (stream == NULL)
1098             {
1099               if (errno != ENOTDIR
1100                   && ((errfunc != NULL && (*errfunc) (directory, errno))
1101                       || (flags & GLOB_ERR)))
1102                 return GLOB_ABORTED;
1103               nfound = 0;
1104               meta = 0;
1105             }
1106           else
1107             {
1108               int fnm_flags = ((!(flags & GLOB_PERIOD) ? FNM_PERIOD : 0)
1109                                | ((flags & GLOB_NOESCAPE) ? FNM_NOESCAPE : 0)
1110 #if defined _AMIGA || defined __VMS
1111                                | FNM_CASEFOLD
1112 #endif
1113                                );
1114               nfound = 0;
1115               flags |= GLOB_MAGCHAR;
1116
1117               while (1)
1118                 {
1119                   const char *name;
1120                   size_t len;
1121 #if defined _LIBC && !defined COMPILE_GLOB64
1122                   struct dirent64 *d;
1123                   union
1124                     {
1125                       struct dirent64 d64;
1126                       char room [offsetof (struct dirent64, d_name[0])
1127                                  + NAME_MAX + 1];
1128                     }
1129                   d64buf;
1130
1131                   if (flags & GLOB_ALTDIRFUNC)
1132                     {
1133                       struct dirent *d32 = (*pglob->gl_readdir) (stream);
1134                       if (d32 != NULL)
1135                         {
1136                           CONVERT_DIRENT_DIRENT64 (&d64buf.d64, d32);
1137                           d = &d64buf.d64;
1138                         }
1139                       else
1140                         d = NULL;
1141                     }
1142                   else
1143                     d = __readdir64 (stream);
1144 #else
1145                   struct dirent *d = ((flags & GLOB_ALTDIRFUNC)
1146                                       ? ((*pglob->gl_readdir) (stream))
1147                                       : __readdir (stream));
1148 #endif
1149                   if (d == NULL)
1150                     break;
1151                   if (! REAL_DIR_ENTRY (d))
1152                     continue;
1153
1154                   /* If we shall match only directories use the information
1155                      provided by the dirent call if possible.  */
1156                   if ((flags & GLOB_ONLYDIR) && !DIRENT_MIGHT_BE_DIR (d))
1157                     continue;
1158
1159                   name = d->d_name;
1160
1161                   if (fnmatch (pattern, name, fnm_flags) == 0)
1162                     {
1163                       /* ISDIR will often be incorrectly set to false
1164                          when not in GLOB_ONLYDIR || GLOB_MARK mode, but we
1165                          don't care.  It won't be used and we save the
1166                          expensive call to stat.  */
1167                       int need_dir_test =
1168                         (GLOB_MARK | (DIRENT_MIGHT_BE_SYMLINK (d)
1169                                       ? GLOB_ONLYDIR : 0));
1170                       bool isdir = (DIRENT_MUST_BE (d, DT_DIR)
1171                                     || ((flags & need_dir_test)
1172                                         && is_dir_p (directory, dirlen, name,
1173                                                      pglob, flags)));
1174
1175                       /* In GLOB_ONLYDIR mode, skip non-dirs.  */
1176                       if ((flags & GLOB_ONLYDIR) && !isdir)
1177                           continue;
1178
1179                         {
1180                           struct globlink *new =
1181                             __alloca (sizeof (struct globlink));
1182                           char *p;
1183                           len = _D_EXACT_NAMLEN (d);
1184                           new->name =
1185                             malloc (len + 1 + ((flags & GLOB_MARK) && isdir));
1186                           if (new->name == NULL)
1187                             goto memory_error;
1188                           p = mempcpy (new->name, name, len);
1189                           if ((flags & GLOB_MARK) && isdir)
1190                               *p++ = '/';
1191                           *p = '\0';
1192                           new->next = names;
1193                           names = new;
1194                           ++nfound;
1195                         }
1196                     }
1197                 }
1198             }
1199         }
1200     }
1201
1202   if (nfound == 0 && (flags & GLOB_NOCHECK))
1203     {
1204       size_t len = strlen (pattern);
1205       nfound = 1;
1206       names = __alloca (sizeof (struct globlink));
1207       names->next = NULL;
1208       names->name = malloc (len + 1);
1209       if (names->name == NULL)
1210         goto memory_error;
1211       *((char *) mempcpy (names->name, pattern, len)) = '\0';
1212     }
1213
1214   if (nfound != 0)
1215     {
1216       char **new_gl_pathv;
1217
1218       new_gl_pathv
1219         = realloc (pglob->gl_pathv,
1220                    (pglob->gl_pathc + pglob->gl_offs + nfound + 1)
1221                    * sizeof (char *));
1222       if (new_gl_pathv == NULL)
1223         goto memory_error;
1224       pglob->gl_pathv = new_gl_pathv;
1225
1226       for (; names != NULL; names = names->next)
1227         pglob->gl_pathv[pglob->gl_offs + pglob->gl_pathc++] = names->name;
1228       pglob->gl_pathv[pglob->gl_offs + pglob->gl_pathc] = NULL;
1229
1230       pglob->gl_flags = flags;
1231     }
1232
1233   save = errno;
1234   if (stream != NULL)
1235     {
1236       if (flags & GLOB_ALTDIRFUNC)
1237         (*pglob->gl_closedir) (stream);
1238       else
1239         closedir (stream);
1240     }
1241   __set_errno (save);
1242
1243   return nfound == 0 ? GLOB_NOMATCH : 0;
1244
1245  memory_error:
1246   {
1247     int save = errno;
1248     if (flags & GLOB_ALTDIRFUNC)
1249       (*pglob->gl_closedir) (stream);
1250     else
1251       closedir (stream);
1252     __set_errno (save);
1253   }
1254   while (names != NULL)
1255     {
1256       if (names->name != NULL)
1257         free (names->name);
1258       names = names->next;
1259     }
1260   return GLOB_NOSPACE;
1261 }