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