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