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