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