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