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