59beb96c5e1c15f59100d93bc8dd28025f4ff517
[gnulib.git] / lib / glob.c
1 /* Copyright (C) 1991-2012 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 __alloca               alloca
149 # define __readdir              readdir
150 # define __glob_pattern_p       glob_pattern_p
151 #endif /* _LIBC */
152
153 #include <fnmatch.h>
154
155 #ifdef _SC_GETPW_R_SIZE_MAX
156 # define GETPW_R_SIZE_MAX()     sysconf (_SC_GETPW_R_SIZE_MAX)
157 #else
158 # define GETPW_R_SIZE_MAX()     (-1)
159 #endif
160 #ifdef _SC_LOGIN_NAME_MAX
161 # define GET_LOGIN_NAME_MAX()   sysconf (_SC_LOGIN_NAME_MAX)
162 #else
163 # define GET_LOGIN_NAME_MAX()   (-1)
164 #endif
165 \f
166 static const char *next_brace_sub (const char *begin, int flags) __THROW;
167
168 #endif /* !defined _LIBC || !defined GLOB_ONLY_P */
169
170 #ifndef attribute_hidden
171 # define attribute_hidden
172 #endif
173
174 #ifndef __attribute_noinline__
175 # if __GNUC__ < 3 || (__GNUC__ == 3 && __GNUC_MINOR__ < 1)
176 #  define __attribute_noinline__ /* Ignore */
177 #else
178 #  define __attribute_noinline__ __attribute__ ((__noinline__))
179 # endif
180 #endif
181
182 #if ! defined __builtin_expect && __GNUC__ < 3
183 # define __builtin_expect(expr, expected) (expr)
184 #endif
185
186 #ifndef _LIBC
187 /* The results of opendir() in this file are not used with dirfd and fchdir,
188    and we do not leak fds to any single-threaded code that could use stdio,
189    therefore save some unnecessary recursion in fchdir.c and opendir_safer.c.
190    FIXME - if the kernel ever adds support for multi-thread safety for
191    avoiding standard fds, then we should use opendir_safer.  */
192 # undef opendir
193 # undef closedir
194
195 # if HAVE_ALLOCA
196 /* The OS usually guarantees only one guard page at the bottom of the stack,
197    and a page size can be as small as 4096 bytes.  So we cannot safely
198    allocate anything larger than 4096 bytes.  Also care for the possibility
199    of a few compiler-allocated temporary stack slots.  */
200 #  define __libc_use_alloca(n) ((n) < 4032)
201 # else
202 /* alloca is implemented with malloc, so just use malloc.  */
203 #  define __libc_use_alloca(n) 0
204 # endif
205 #endif
206
207 static int glob_in_dir (const char *pattern, const char *directory,
208                         int flags, int (*errfunc) (const char *, int),
209                         glob_t *pglob);
210 extern int __glob_pattern_type (const char *pattern, int quote)
211     attribute_hidden;
212
213 #if !defined _LIBC || !defined GLOB_ONLY_P
214 static int prefix_array (const char *prefix, char **array, size_t n) __THROW;
215 static int collated_compare (const void *, const void *) __THROW;
216
217
218 /* Find the end of the sub-pattern in a brace expression.  */
219 static const char *
220 next_brace_sub (const char *cp, int flags)
221 {
222   unsigned int depth = 0;
223   while (*cp != '\0')
224     if ((flags & GLOB_NOESCAPE) == 0 && *cp == '\\')
225       {
226         if (*++cp == '\0')
227           break;
228         ++cp;
229       }
230     else
231       {
232         if ((*cp == '}' && depth-- == 0) || (*cp == ',' && depth == 0))
233           break;
234
235         if (*cp++ == '{')
236           depth++;
237       }
238
239   return *cp != '\0' ? cp : NULL;
240 }
241
242 #endif /* !defined _LIBC || !defined GLOB_ONLY_P */
243
244 /* Do glob searching for PATTERN, placing results in PGLOB.
245    The bits defined above may be set in FLAGS.
246    If a directory cannot be opened or read and ERRFUNC is not nil,
247    it is called with the pathname that caused the error, and the
248    'errno' value from the failing call; if it returns non-zero
249    'glob' returns GLOB_ABORTED; if it returns zero, the error is ignored.
250    If memory cannot be allocated for PGLOB, GLOB_NOSPACE is returned.
251    Otherwise, 'glob' returns zero.  */
252 int
253 #ifdef GLOB_ATTRIBUTE
254 GLOB_ATTRIBUTE
255 #endif
256 glob (pattern, flags, errfunc, pglob)
257      const char * restrict pattern;
258      int flags;
259      int (*errfunc) (const char *, int);
260      glob_t * restrict pglob;
261 {
262   const char *filename;
263   const char *dirname;
264   size_t dirlen;
265   int status;
266   size_t oldcount;
267   int meta;
268   int dirname_modified;
269   glob_t dirs;
270
271   if (pattern == NULL || pglob == NULL || (flags & ~__GLOB_FLAGS) != 0)
272     {
273       __set_errno (EINVAL);
274       return -1;
275     }
276
277   if (!(flags & GLOB_DOOFFS))
278     /* Have to do this so 'globfree' knows where to start freeing.  It
279        also makes all the code that uses gl_offs simpler. */
280     pglob->gl_offs = 0;
281
282   if (flags & GLOB_BRACE)
283     {
284       const char *begin;
285
286       if (flags & GLOB_NOESCAPE)
287         begin = strchr (pattern, '{');
288       else
289         {
290           begin = pattern;
291           while (1)
292             {
293               if (*begin == '\0')
294                 {
295                   begin = NULL;
296                   break;
297                 }
298
299               if (*begin == '\\' && begin[1] != '\0')
300                 ++begin;
301               else if (*begin == '{')
302                 break;
303
304               ++begin;
305             }
306         }
307
308       if (begin != NULL)
309         {
310           /* Allocate working buffer large enough for our work.  Note that
311             we have at least an opening and closing brace.  */
312           size_t firstc;
313           char *alt_start;
314           const char *p;
315           const char *next;
316           const char *rest;
317           size_t rest_len;
318 #ifdef __GNUC__
319           char onealt[strlen (pattern) - 1];
320 #else
321           char *onealt = malloc (strlen (pattern) - 1);
322           if (onealt == NULL)
323             {
324               if (!(flags & GLOB_APPEND))
325                 {
326                   pglob->gl_pathc = 0;
327                   pglob->gl_pathv = NULL;
328                 }
329               return GLOB_NOSPACE;
330             }
331 #endif
332
333           /* We know the prefix for all sub-patterns.  */
334           alt_start = mempcpy (onealt, pattern, begin - pattern);
335
336           /* Find the first sub-pattern and at the same time find the
337              rest after the closing brace.  */
338           next = next_brace_sub (begin + 1, flags);
339           if (next == NULL)
340             {
341               /* It is an invalid expression.  */
342 #ifndef __GNUC__
343               free (onealt);
344 #endif
345               return glob (pattern, flags & ~GLOB_BRACE, errfunc, pglob);
346             }
347
348           /* Now find the end of the whole brace expression.  */
349           rest = next;
350           while (*rest != '}')
351             {
352               rest = next_brace_sub (rest + 1, flags);
353               if (rest == NULL)
354                 {
355                   /* It is an invalid expression.  */
356 #ifndef __GNUC__
357                   free (onealt);
358 #endif
359                   return glob (pattern, flags & ~GLOB_BRACE, errfunc, pglob);
360                 }
361             }
362           /* Please note that we now can be sure the brace expression
363              is well-formed.  */
364           rest_len = strlen (++rest) + 1;
365
366           /* We have a brace expression.  BEGIN points to the opening {,
367              NEXT points past the terminator of the first element, and END
368              points past the final }.  We will accumulate result names from
369              recursive runs for each brace alternative in the buffer using
370              GLOB_APPEND.  */
371
372           if (!(flags & GLOB_APPEND))
373             {
374               /* This call is to set a new vector, so clear out the
375                  vector so we can append to it.  */
376               pglob->gl_pathc = 0;
377               pglob->gl_pathv = NULL;
378             }
379           firstc = pglob->gl_pathc;
380
381           p = begin + 1;
382           while (1)
383             {
384               int result;
385
386               /* Construct the new glob expression.  */
387               mempcpy (mempcpy (alt_start, p, next - p), rest, rest_len);
388
389               result = glob (onealt,
390                              ((flags & ~(GLOB_NOCHECK | GLOB_NOMAGIC))
391                               | GLOB_APPEND), errfunc, pglob);
392
393               /* If we got an error, return it.  */
394               if (result && result != GLOB_NOMATCH)
395                 {
396 #ifndef __GNUC__
397                   free (onealt);
398 #endif
399                   if (!(flags & GLOB_APPEND))
400                     {
401                       globfree (pglob);
402                       pglob->gl_pathc = 0;
403                     }
404                   return result;
405                 }
406
407               if (*next == '}')
408                 /* We saw the last entry.  */
409                 break;
410
411               p = next + 1;
412               next = next_brace_sub (p, flags);
413               assert (next != NULL);
414             }
415
416 #ifndef __GNUC__
417           free (onealt);
418 #endif
419
420           if (pglob->gl_pathc != firstc)
421             /* We found some entries.  */
422             return 0;
423           else if (!(flags & (GLOB_NOCHECK|GLOB_NOMAGIC)))
424             return GLOB_NOMATCH;
425         }
426     }
427
428   /* Find the filename.  */
429   filename = strrchr (pattern, '/');
430 #if defined __MSDOS__ || defined WINDOWS32
431   /* The case of "d:pattern".  Since ':' is not allowed in
432      file names, we can safely assume that wherever it
433      happens in pattern, it signals the filename part.  This
434      is so we could some day support patterns like "[a-z]:foo".  */
435   if (filename == NULL)
436     filename = strchr (pattern, ':');
437 #endif /* __MSDOS__ || WINDOWS32 */
438   dirname_modified = 0;
439   if (filename == NULL)
440     {
441       /* This can mean two things: a simple name or "~name".  The latter
442          case is nothing but a notation for a directory.  */
443       if ((flags & (GLOB_TILDE|GLOB_TILDE_CHECK)) && pattern[0] == '~')
444         {
445           dirname = pattern;
446           dirlen = strlen (pattern);
447
448           /* Set FILENAME to NULL as a special flag.  This is ugly but
449              other solutions would require much more code.  We test for
450              this special case below.  */
451           filename = NULL;
452         }
453       else
454         {
455           filename = pattern;
456 #ifdef _AMIGA
457           dirname = "";
458 #else
459           dirname = ".";
460 #endif
461           dirlen = 0;
462         }
463     }
464   else if (filename == pattern
465            || (filename == pattern + 1 && pattern[0] == '\\'
466                && (flags & GLOB_NOESCAPE) == 0))
467     {
468       /* "/pattern" or "\\/pattern".  */
469       dirname = "/";
470       dirlen = 1;
471       ++filename;
472     }
473   else
474     {
475       char *newp;
476       dirlen = filename - pattern;
477 #if defined __MSDOS__ || defined WINDOWS32
478       if (*filename == ':'
479           || (filename > pattern + 1 && filename[-1] == ':'))
480         {
481           char *drive_spec;
482
483           ++dirlen;
484           drive_spec = __alloca (dirlen + 1);
485           *((char *) mempcpy (drive_spec, pattern, dirlen)) = '\0';
486           /* For now, disallow wildcards in the drive spec, to
487              prevent infinite recursion in glob.  */
488           if (__glob_pattern_p (drive_spec, !(flags & GLOB_NOESCAPE)))
489             return GLOB_NOMATCH;
490           /* If this is "d:pattern", we need to copy ':' to DIRNAME
491              as well.  If it's "d:/pattern", don't remove the slash
492              from "d:/", since "d:" and "d:/" are not the same.*/
493         }
494 #endif
495       newp = __alloca (dirlen + 1);
496       *((char *) mempcpy (newp, pattern, dirlen)) = '\0';
497       dirname = newp;
498       ++filename;
499
500       if (filename[0] == '\0'
501 #if defined __MSDOS__ || defined WINDOWS32
502           && dirname[dirlen - 1] != ':'
503           && (dirlen < 3 || dirname[dirlen - 2] != ':'
504               || dirname[dirlen - 1] != '/')
505 #endif
506           && dirlen > 1)
507         /* "pattern/".  Expand "pattern", appending slashes.  */
508         {
509           int orig_flags = flags;
510           int val;
511           if (!(flags & GLOB_NOESCAPE) && dirname[dirlen - 1] == '\\')
512             {
513               /* "pattern\\/".  Remove the final backslash if it hasn't
514                  been quoted.  */
515               char *p = (char *) &dirname[dirlen - 1];
516
517               while (p > dirname && p[-1] == '\\') --p;
518               if ((&dirname[dirlen] - p) & 1)
519                 {
520                   *(char *) &dirname[--dirlen] = '\0';
521                   flags &= ~(GLOB_NOCHECK | GLOB_NOMAGIC);
522                 }
523             }
524           val = glob (dirname, flags | GLOB_MARK, errfunc, pglob);
525           if (val == 0)
526             pglob->gl_flags = ((pglob->gl_flags & ~GLOB_MARK)
527                                | (flags & GLOB_MARK));
528           else if (val == GLOB_NOMATCH && flags != orig_flags)
529             {
530               /* Make sure globfree (&dirs); is a nop.  */
531               dirs.gl_pathv = NULL;
532               flags = orig_flags;
533               oldcount = pglob->gl_pathc + pglob->gl_offs;
534               goto no_matches;
535             }
536           return val;
537         }
538     }
539
540   if (!(flags & GLOB_APPEND))
541     {
542       pglob->gl_pathc = 0;
543       if (!(flags & GLOB_DOOFFS))
544         pglob->gl_pathv = NULL;
545       else
546         {
547           size_t i;
548           pglob->gl_pathv = malloc ((pglob->gl_offs + 1) * sizeof (char *));
549           if (pglob->gl_pathv == NULL)
550             return GLOB_NOSPACE;
551
552           for (i = 0; i <= pglob->gl_offs; ++i)
553             pglob->gl_pathv[i] = NULL;
554         }
555     }
556
557   oldcount = pglob->gl_pathc + pglob->gl_offs;
558
559   if ((flags & (GLOB_TILDE|GLOB_TILDE_CHECK)) && dirname[0] == '~')
560     {
561       if (dirname[1] == '\0' || dirname[1] == '/'
562           || (!(flags & GLOB_NOESCAPE) && dirname[1] == '\\'
563               && (dirname[2] == '\0' || dirname[2] == '/')))
564         {
565           /* Look up home directory.  */
566           const char *home_dir = getenv ("HOME");
567 # ifdef _AMIGA
568           if (home_dir == NULL || home_dir[0] == '\0')
569             home_dir = "SYS:";
570 # else
571 #  ifdef WINDOWS32
572           /* Windows NT defines HOMEDRIVE and HOMEPATH.  But give preference
573              to HOME, because the user can change HOME.  */
574           if (home_dir == NULL || home_dir[0] == '\0')
575             {
576               const char *home_drive = getenv ("HOMEDRIVE");
577               const char *home_path = getenv ("HOMEPATH");
578
579               if (home_drive != NULL && home_path != NULL)
580                 {
581                   size_t home_drive_len = strlen (home_drive);
582                   size_t home_path_len = strlen (home_path);
583                   char *mem = alloca (home_drive_len + home_path_len + 1);
584
585                   memcpy (mem, home_drive, home_drive_len);
586                   memcpy (mem + home_drive_len, home_path, home_path_len + 1);
587                   home_dir = mem;
588                 }
589               else
590                 home_dir = "c:/users/default"; /* poor default */
591             }
592 #  else
593           if (home_dir == NULL || home_dir[0] == '\0')
594             {
595               int success;
596               char *name;
597               size_t buflen = GET_LOGIN_NAME_MAX () + 1;
598
599               if (buflen == 0)
600                 /* 'sysconf' does not support _SC_LOGIN_NAME_MAX.  Try
601                    a moderate value.  */
602                 buflen = 20;
603               name = __alloca (buflen);
604
605               success = getlogin_r (name, buflen) == 0;
606               if (success)
607                 {
608                   struct passwd *p;
609 #   if defined HAVE_GETPWNAM_R || defined _LIBC
610                   long int pwbuflen = GETPW_R_SIZE_MAX ();
611                   char *pwtmpbuf;
612                   struct passwd pwbuf;
613                   int save = errno;
614
615 #    ifndef _LIBC
616                   if (pwbuflen == -1)
617                     /* 'sysconf' does not support _SC_GETPW_R_SIZE_MAX.
618                        Try a moderate value.  */
619                     pwbuflen = 1024;
620 #    endif
621                   pwtmpbuf = __alloca (pwbuflen);
622
623                   while (getpwnam_r (name, &pwbuf, pwtmpbuf, pwbuflen, &p)
624                          != 0)
625                     {
626                       if (errno != ERANGE)
627                         {
628                           p = NULL;
629                           break;
630                         }
631 #    ifdef _LIBC
632                       pwtmpbuf = extend_alloca (pwtmpbuf, pwbuflen,
633                                                 2 * pwbuflen);
634 #    else
635                       pwbuflen *= 2;
636                       pwtmpbuf = __alloca (pwbuflen);
637 #    endif
638                       __set_errno (save);
639                     }
640 #   else
641                   p = getpwnam (name);
642 #   endif
643                   if (p != NULL)
644                     home_dir = p->pw_dir;
645                 }
646             }
647           if (home_dir == NULL || home_dir[0] == '\0')
648             {
649               if (flags & GLOB_TILDE_CHECK)
650                 return GLOB_NOMATCH;
651               else
652                 home_dir = "~"; /* No luck.  */
653             }
654 #  endif /* WINDOWS32 */
655 # endif
656           /* Now construct the full directory.  */
657           if (dirname[1] == '\0')
658             {
659               dirname = home_dir;
660               dirlen = strlen (dirname);
661             }
662           else
663             {
664               char *newp;
665               size_t home_len = strlen (home_dir);
666               newp = __alloca (home_len + dirlen);
667               mempcpy (mempcpy (newp, home_dir, home_len),
668                        &dirname[1], dirlen);
669               dirname = newp;
670               dirlen += home_len - 1;
671             }
672           dirname_modified = 1;
673         }
674 # if !defined _AMIGA && !defined WINDOWS32
675       else
676         {
677           char *end_name = strchr (dirname, '/');
678           const char *user_name;
679           const char *home_dir;
680           char *unescape = NULL;
681
682           if (!(flags & GLOB_NOESCAPE))
683             {
684               if (end_name == NULL)
685                 {
686                   unescape = strchr (dirname, '\\');
687                   if (unescape)
688                     end_name = strchr (unescape, '\0');
689                 }
690               else
691                 unescape = memchr (dirname, '\\', end_name - dirname);
692             }
693           if (end_name == NULL)
694             user_name = dirname + 1;
695           else
696             {
697               char *newp;
698               newp = __alloca (end_name - dirname);
699               *((char *) mempcpy (newp, dirname + 1, end_name - dirname))
700                 = '\0';
701               if (unescape != NULL)
702                 {
703                   char *p = mempcpy (newp, dirname + 1,
704                                      unescape - dirname - 1);
705                   char *q = unescape;
706                   while (*q != '\0')
707                     {
708                       if (*q == '\\')
709                         {
710                           if (q[1] == '\0')
711                             {
712                               /* "~fo\\o\\" unescape to user_name "foo\\",
713                                  but "~fo\\o\\/" unescape to user_name
714                                  "foo".  */
715                               if (filename == NULL)
716                                 *p++ = '\\';
717                               break;
718                             }
719                           ++q;
720                         }
721                       *p++ = *q++;
722                     }
723                   *p = '\0';
724                 }
725               else
726                 *((char *) mempcpy (newp, dirname + 1, end_name - dirname))
727                   = '\0';
728               user_name = newp;
729             }
730
731           /* Look up specific user's home directory.  */
732           {
733             struct passwd *p;
734 #  if defined HAVE_GETPWNAM_R || defined _LIBC
735             long int buflen = GETPW_R_SIZE_MAX ();
736             char *pwtmpbuf;
737             struct passwd pwbuf;
738             int save = errno;
739
740 #   ifndef _LIBC
741             if (buflen == -1)
742               /* 'sysconf' does not support _SC_GETPW_R_SIZE_MAX.  Try a
743                  moderate value.  */
744               buflen = 1024;
745 #   endif
746             pwtmpbuf = __alloca (buflen);
747
748             while (getpwnam_r (user_name, &pwbuf, pwtmpbuf, buflen, &p) != 0)
749               {
750                 if (errno != ERANGE)
751                   {
752                     p = NULL;
753                     break;
754                   }
755 #   ifdef _LIBC
756                 pwtmpbuf = extend_alloca (pwtmpbuf, buflen, 2 * buflen);
757 #   else
758                 buflen *= 2;
759                 pwtmpbuf = __alloca (buflen);
760 #   endif
761                 __set_errno (save);
762               }
763 #  else
764             p = getpwnam (user_name);
765 #  endif
766             if (p != NULL)
767               home_dir = p->pw_dir;
768             else
769               home_dir = NULL;
770           }
771           /* If we found a home directory use this.  */
772           if (home_dir != NULL)
773             {
774               char *newp;
775               size_t home_len = strlen (home_dir);
776               size_t rest_len = end_name == NULL ? 0 : strlen (end_name);
777               newp = __alloca (home_len + rest_len + 1);
778               *((char *) mempcpy (mempcpy (newp, home_dir, home_len),
779                                   end_name, rest_len)) = '\0';
780               dirname = newp;
781               dirlen = home_len + rest_len;
782               dirname_modified = 1;
783             }
784           else
785             if (flags & GLOB_TILDE_CHECK)
786               /* We have to regard it as an error if we cannot find the
787                  home directory.  */
788               return GLOB_NOMATCH;
789         }
790 # endif /* Not Amiga && not WINDOWS32.  */
791     }
792
793   /* Now test whether we looked for "~" or "~NAME".  In this case we
794      can give the answer now.  */
795   if (filename == NULL)
796     {
797       struct stat st;
798       struct_stat64 st64;
799
800       /* Return the directory if we don't check for error or if it exists.  */
801       if ((flags & GLOB_NOCHECK)
802           || (((__builtin_expect (flags & GLOB_ALTDIRFUNC, 0))
803                ? ((*pglob->gl_stat) (dirname, &st) == 0
804                   && S_ISDIR (st.st_mode))
805                : (__stat64 (dirname, &st64) == 0 && S_ISDIR (st64.st_mode)))))
806         {
807           int newcount = pglob->gl_pathc + pglob->gl_offs;
808           char **new_gl_pathv;
809
810           new_gl_pathv
811             = realloc (pglob->gl_pathv, (newcount + 1 + 1) * sizeof (char *));
812           if (new_gl_pathv == NULL)
813             {
814             nospace:
815               free (pglob->gl_pathv);
816               pglob->gl_pathv = NULL;
817               pglob->gl_pathc = 0;
818               return GLOB_NOSPACE;
819             }
820           pglob->gl_pathv = new_gl_pathv;
821
822           if (flags & GLOB_MARK)
823             {
824               char *p;
825               pglob->gl_pathv[newcount] = malloc (dirlen + 2);
826               if (pglob->gl_pathv[newcount] == NULL)
827                 goto nospace;
828               p = mempcpy (pglob->gl_pathv[newcount], dirname, dirlen);
829               p[0] = '/';
830               p[1] = '\0';
831             }
832           else
833             {
834               pglob->gl_pathv[newcount] = strdup (dirname);
835               if (pglob->gl_pathv[newcount] == NULL)
836                 goto nospace;
837             }
838           pglob->gl_pathv[++newcount] = NULL;
839           ++pglob->gl_pathc;
840           pglob->gl_flags = flags;
841
842           return 0;
843         }
844
845       /* Not found.  */
846       return GLOB_NOMATCH;
847     }
848
849   meta = __glob_pattern_type (dirname, !(flags & GLOB_NOESCAPE));
850   /* meta is 1 if correct glob pattern containing metacharacters.
851      If meta has bit (1 << 2) set, it means there was an unterminated
852      [ which we handle the same, using fnmatch.  Broken unterminated
853      pattern bracket expressions ought to be rare enough that it is
854      not worth special casing them, fnmatch will do the right thing.  */
855   if (meta & 5)
856     {
857       /* The directory name contains metacharacters, so we
858          have to glob for the directory, and then glob for
859          the pattern in each directory found.  */
860       size_t i;
861
862       if (!(flags & GLOB_NOESCAPE) && dirlen > 0 && dirname[dirlen - 1] == '\\')
863         {
864           /* "foo\\/bar".  Remove the final backslash from dirname
865              if it has not been quoted.  */
866           char *p = (char *) &dirname[dirlen - 1];
867
868           while (p > dirname && p[-1] == '\\') --p;
869           if ((&dirname[dirlen] - p) & 1)
870             *(char *) &dirname[--dirlen] = '\0';
871         }
872
873       if (__builtin_expect ((flags & GLOB_ALTDIRFUNC) != 0, 0))
874         {
875           /* Use the alternative access functions also in the recursive
876              call.  */
877           dirs.gl_opendir = pglob->gl_opendir;
878           dirs.gl_readdir = pglob->gl_readdir;
879           dirs.gl_closedir = pglob->gl_closedir;
880           dirs.gl_stat = pglob->gl_stat;
881           dirs.gl_lstat = pglob->gl_lstat;
882         }
883
884       status = glob (dirname,
885                      ((flags & (GLOB_ERR | GLOB_NOESCAPE
886                                 | GLOB_ALTDIRFUNC))
887                       | GLOB_NOSORT | GLOB_ONLYDIR),
888                      errfunc, &dirs);
889       if (status != 0)
890         {
891           if ((flags & GLOB_NOCHECK) == 0 || status != GLOB_NOMATCH)
892             return status;
893           goto no_matches;
894         }
895
896       /* We have successfully globbed the preceding directory name.
897          For each name we found, call glob_in_dir on it and FILENAME,
898          appending the results to PGLOB.  */
899       for (i = 0; i < dirs.gl_pathc; ++i)
900         {
901           int old_pathc;
902
903 #ifdef SHELL
904           {
905             /* Make globbing interruptible in the bash shell. */
906             extern int interrupt_state;
907
908             if (interrupt_state)
909               {
910                 globfree (&dirs);
911                 return GLOB_ABORTED;
912               }
913           }
914 #endif /* SHELL.  */
915
916           old_pathc = pglob->gl_pathc;
917           status = glob_in_dir (filename, dirs.gl_pathv[i],
918                                 ((flags | GLOB_APPEND)
919                                  & ~(GLOB_NOCHECK | GLOB_NOMAGIC)),
920                                 errfunc, pglob);
921           if (status == GLOB_NOMATCH)
922             /* No matches in this directory.  Try the next.  */
923             continue;
924
925           if (status != 0)
926             {
927               globfree (&dirs);
928               globfree (pglob);
929               pglob->gl_pathc = 0;
930               return status;
931             }
932
933           /* Stick the directory on the front of each name.  */
934           if (prefix_array (dirs.gl_pathv[i],
935                             &pglob->gl_pathv[old_pathc + pglob->gl_offs],
936                             pglob->gl_pathc - old_pathc))
937             {
938               globfree (&dirs);
939               globfree (pglob);
940               pglob->gl_pathc = 0;
941               return GLOB_NOSPACE;
942             }
943         }
944
945       flags |= GLOB_MAGCHAR;
946
947       /* We have ignored the GLOB_NOCHECK flag in the 'glob_in_dir' calls.
948          But if we have not found any matching entry and the GLOB_NOCHECK
949          flag was set we must return the input pattern itself.  */
950       if (pglob->gl_pathc + pglob->gl_offs == oldcount)
951         {
952         no_matches:
953           /* No matches.  */
954           if (flags & GLOB_NOCHECK)
955             {
956               int newcount = pglob->gl_pathc + pglob->gl_offs;
957               char **new_gl_pathv;
958
959               new_gl_pathv = realloc (pglob->gl_pathv,
960                                       (newcount + 2) * sizeof (char *));
961               if (new_gl_pathv == NULL)
962                 {
963                   globfree (&dirs);
964                   return GLOB_NOSPACE;
965                 }
966               pglob->gl_pathv = new_gl_pathv;
967
968               pglob->gl_pathv[newcount] = strdup (pattern);
969               if (pglob->gl_pathv[newcount] == NULL)
970                 {
971                   globfree (&dirs);
972                   globfree (pglob);
973                   pglob->gl_pathc = 0;
974                   return GLOB_NOSPACE;
975                 }
976
977               ++pglob->gl_pathc;
978               ++newcount;
979
980               pglob->gl_pathv[newcount] = NULL;
981               pglob->gl_flags = flags;
982             }
983           else
984             {
985               globfree (&dirs);
986               return GLOB_NOMATCH;
987             }
988         }
989
990       globfree (&dirs);
991     }
992   else
993     {
994       int old_pathc = pglob->gl_pathc;
995       int orig_flags = flags;
996
997       if (meta & 2)
998         {
999           char *p = strchr (dirname, '\\'), *q;
1000           /* We need to unescape the dirname string.  It is certainly
1001              allocated by alloca, as otherwise filename would be NULL
1002              or dirname wouldn't contain backslashes.  */
1003           q = p;
1004           do
1005             {
1006               if (*p == '\\')
1007                 {
1008                   *q = *++p;
1009                   --dirlen;
1010                 }
1011               else
1012                 *q = *p;
1013               ++q;
1014             }
1015           while (*p++ != '\0');
1016           dirname_modified = 1;
1017         }
1018       if (dirname_modified)
1019         flags &= ~(GLOB_NOCHECK | GLOB_NOMAGIC);
1020       status = glob_in_dir (filename, dirname, flags, errfunc, pglob);
1021       if (status != 0)
1022         {
1023           if (status == GLOB_NOMATCH && flags != orig_flags
1024               && pglob->gl_pathc + pglob->gl_offs == oldcount)
1025             {
1026               /* Make sure globfree (&dirs); is a nop.  */
1027               dirs.gl_pathv = NULL;
1028               flags = orig_flags;
1029               goto no_matches;
1030             }
1031           return status;
1032         }
1033
1034       if (dirlen > 0)
1035         {
1036           /* Stick the directory on the front of each name.  */
1037           if (prefix_array (dirname,
1038                             &pglob->gl_pathv[old_pathc + pglob->gl_offs],
1039                             pglob->gl_pathc - old_pathc))
1040             {
1041               globfree (pglob);
1042               pglob->gl_pathc = 0;
1043               return GLOB_NOSPACE;
1044             }
1045         }
1046     }
1047
1048   if (flags & GLOB_MARK)
1049     {
1050       /* Append slashes to directory names.  */
1051       size_t i;
1052       struct stat st;
1053       struct_stat64 st64;
1054
1055       for (i = oldcount; i < pglob->gl_pathc + pglob->gl_offs; ++i)
1056         if ((__builtin_expect (flags & GLOB_ALTDIRFUNC, 0)
1057              ? ((*pglob->gl_stat) (pglob->gl_pathv[i], &st) == 0
1058                 && S_ISDIR (st.st_mode))
1059              : (__stat64 (pglob->gl_pathv[i], &st64) == 0
1060                 && S_ISDIR (st64.st_mode))))
1061           {
1062             size_t len = strlen (pglob->gl_pathv[i]) + 2;
1063             char *new = realloc (pglob->gl_pathv[i], len);
1064             if (new == NULL)
1065               {
1066                 globfree (pglob);
1067                 pglob->gl_pathc = 0;
1068                 return GLOB_NOSPACE;
1069               }
1070             strcpy (&new[len - 2], "/");
1071             pglob->gl_pathv[i] = new;
1072           }
1073     }
1074
1075   if (!(flags & GLOB_NOSORT))
1076     {
1077       /* Sort the vector.  */
1078       qsort (&pglob->gl_pathv[oldcount],
1079              pglob->gl_pathc + pglob->gl_offs - oldcount,
1080              sizeof (char *), collated_compare);
1081     }
1082
1083   return 0;
1084 }
1085 #if defined _LIBC && !defined glob
1086 libc_hidden_def (glob)
1087 #endif
1088
1089
1090 #if !defined _LIBC || !defined GLOB_ONLY_P
1091
1092 /* Free storage allocated in PGLOB by a previous 'glob' call.  */
1093 void
1094 globfree (pglob)
1095      register glob_t *pglob;
1096 {
1097   if (pglob->gl_pathv != NULL)
1098     {
1099       size_t i;
1100       for (i = 0; i < pglob->gl_pathc; ++i)
1101         if (pglob->gl_pathv[pglob->gl_offs + i] != NULL)
1102           free (pglob->gl_pathv[pglob->gl_offs + i]);
1103       free (pglob->gl_pathv);
1104       pglob->gl_pathv = NULL;
1105     }
1106 }
1107 #if defined _LIBC && !defined globfree
1108 libc_hidden_def (globfree)
1109 #endif
1110
1111
1112 /* Do a collated comparison of A and B.  */
1113 static int
1114 collated_compare (const void *a, const void *b)
1115 {
1116   char *const *ps1 = a; char *s1 = *ps1;
1117   char *const *ps2 = b; char *s2 = *ps2;
1118
1119   if (s1 == s2)
1120     return 0;
1121   if (s1 == NULL)
1122     return 1;
1123   if (s2 == NULL)
1124     return -1;
1125   return strcoll (s1, s2);
1126 }
1127
1128
1129 /* Prepend DIRNAME to each of N members of ARRAY, replacing ARRAY's
1130    elements in place.  Return nonzero if out of memory, zero if successful.
1131    A slash is inserted between DIRNAME and each elt of ARRAY,
1132    unless DIRNAME is just "/".  Each old element of ARRAY is freed.  */
1133 static int
1134 prefix_array (const char *dirname, char **array, size_t n)
1135 {
1136   register size_t i;
1137   size_t dirlen = strlen (dirname);
1138 #if defined __MSDOS__ || defined WINDOWS32
1139   int sep_char = '/';
1140 # define DIRSEP_CHAR sep_char
1141 #else
1142 # define DIRSEP_CHAR '/'
1143 #endif
1144
1145   if (dirlen == 1 && dirname[0] == '/')
1146     /* DIRNAME is just "/", so normal prepending would get us "//foo".
1147        We want "/foo" instead, so don't prepend any chars from DIRNAME.  */
1148     dirlen = 0;
1149 #if defined __MSDOS__ || defined WINDOWS32
1150   else if (dirlen > 1)
1151     {
1152       if (dirname[dirlen - 1] == '/' && dirname[dirlen - 2] == ':')
1153         /* DIRNAME is "d:/".  Don't prepend the slash from DIRNAME.  */
1154         --dirlen;
1155       else if (dirname[dirlen - 1] == ':')
1156         {
1157           /* DIRNAME is "d:".  Use ':' instead of '/'.  */
1158           --dirlen;
1159           sep_char = ':';
1160         }
1161     }
1162 #endif
1163
1164   for (i = 0; i < n; ++i)
1165     {
1166       size_t eltlen = strlen (array[i]) + 1;
1167       char *new = malloc (dirlen + 1 + eltlen);
1168       if (new == NULL)
1169         {
1170           while (i > 0)
1171             free (array[--i]);
1172           return 1;
1173         }
1174
1175       {
1176         char *endp = mempcpy (new, dirname, dirlen);
1177         *endp++ = DIRSEP_CHAR;
1178         mempcpy (endp, array[i], eltlen);
1179       }
1180       free (array[i]);
1181       array[i] = new;
1182     }
1183
1184   return 0;
1185 }
1186
1187
1188 /* We must not compile this function twice.  */
1189 #if !defined _LIBC || !defined NO_GLOB_PATTERN_P
1190 int
1191 __glob_pattern_type (pattern, quote)
1192      const char *pattern;
1193      int quote;
1194 {
1195   register const char *p;
1196   int ret = 0;
1197
1198   for (p = pattern; *p != '\0'; ++p)
1199     switch (*p)
1200       {
1201       case '?':
1202       case '*':
1203         return 1;
1204
1205       case '\\':
1206         if (quote)
1207           {
1208             if (p[1] != '\0')
1209               ++p;
1210             ret |= 2;
1211           }
1212         break;
1213
1214       case '[':
1215         ret |= 4;
1216         break;
1217
1218       case ']':
1219         if (ret & 4)
1220           return 1;
1221         break;
1222       }
1223
1224   return ret;
1225 }
1226
1227 /* Return nonzero if PATTERN contains any metacharacters.
1228    Metacharacters can be quoted with backslashes if QUOTE is nonzero.  */
1229 int
1230 __glob_pattern_p (pattern, quote)
1231      const char *pattern;
1232      int quote;
1233 {
1234   return __glob_pattern_type (pattern, quote) == 1;
1235 }
1236 # ifdef _LIBC
1237 weak_alias (__glob_pattern_p, glob_pattern_p)
1238 # endif
1239 #endif
1240
1241 #endif /* !GLOB_ONLY_P */
1242
1243
1244 #if !defined _LIBC || !defined GLOB_ONLY_P
1245 /* We put this in a separate function mainly to allow the memory
1246    allocated with alloca to be recycled.  */
1247 static int
1248 __attribute_noinline__
1249 link_exists2_p (const char *dir, size_t dirlen, const char *fname,
1250                 glob_t *pglob
1251 # if !defined _LIBC && !HAVE_FSTATAT
1252                 , int flags
1253 # endif
1254                 )
1255 {
1256   size_t fnamelen = strlen (fname);
1257   char *fullname = __alloca (dirlen + 1 + fnamelen + 1);
1258   struct stat st;
1259
1260   mempcpy (mempcpy (mempcpy (fullname, dir, dirlen), "/", 1),
1261            fname, fnamelen + 1);
1262
1263 # if !defined _LIBC && !HAVE_FSTATAT
1264   if (__builtin_expect ((flags & GLOB_ALTDIRFUNC) == 0, 1))
1265     {
1266       struct_stat64 st64;
1267       return __stat64 (fullname, &st64) == 0;
1268     }
1269 # endif
1270   return (*pglob->gl_stat) (fullname, &st) == 0;
1271 }
1272
1273 /* Return true if DIR/FNAME exists.  */
1274 static int
1275 link_exists_p (int dfd, const char *dir, size_t dirlen, const char *fname,
1276                glob_t *pglob, int flags)
1277 {
1278 # if defined _LIBC || HAVE_FSTATAT
1279   if (__builtin_expect (flags & GLOB_ALTDIRFUNC, 0))
1280     return link_exists2_p (dir, dirlen, fname, pglob);
1281   else
1282     {
1283       /* dfd cannot be -1 here, because dirfd never returns -1 on
1284          glibc, or on hosts that have fstatat.  */
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 }