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