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