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