Back to index

glibc  2.9
glob.c
Go to the documentation of this file.
00001 /* Copyright (C) 1991-2002, 2003, 2004, 2005, 2006, 2007, 2008
00002    Free Software Foundation, Inc.
00003    This file is part of the GNU C Library.
00004 
00005    The GNU C Library is free software; you can redistribute it and/or
00006    modify it under the terms of the GNU Lesser General Public
00007    License as published by the Free Software Foundation; either
00008    version 2.1 of the License, or (at your option) any later version.
00009 
00010    The GNU C Library is distributed in the hope that it will be useful,
00011    but WITHOUT ANY WARRANTY; without even the implied warranty of
00012    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
00013    Lesser General Public License for more details.
00014 
00015    You should have received a copy of the GNU Lesser General Public
00016    License along with the GNU C Library; if not, write to the Free
00017    Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA
00018    02111-1307 USA.  */
00019 
00020 #ifdef HAVE_CONFIG_H
00021 # include <config.h>
00022 #endif
00023 
00024 #include <glob.h>
00025 
00026 #include <errno.h>
00027 #include <sys/types.h>
00028 #include <sys/stat.h>
00029 #include <stddef.h>
00030 
00031 /* Outcomment the following line for production quality code.  */
00032 /* #define NDEBUG 1 */
00033 #include <assert.h>
00034 
00035 #include <stdio.h>          /* Needed on stupid SunOS for assert.  */
00036 
00037 #if !defined _LIBC || !defined GLOB_ONLY_P
00038 #if defined HAVE_UNISTD_H || defined _LIBC
00039 # include <unistd.h>
00040 # ifndef POSIX
00041 #  ifdef _POSIX_VERSION
00042 #   define POSIX
00043 #  endif
00044 # endif
00045 #endif
00046 
00047 #include <pwd.h>
00048 
00049 #include <errno.h>
00050 #ifndef __set_errno
00051 # define __set_errno(val) errno = (val)
00052 #endif
00053 
00054 #if defined HAVE_DIRENT_H || defined __GNU_LIBRARY__
00055 # include <dirent.h>
00056 # define NAMLEN(dirent) strlen((dirent)->d_name)
00057 #else
00058 # define dirent direct
00059 # define NAMLEN(dirent) (dirent)->d_namlen
00060 # ifdef HAVE_SYS_NDIR_H
00061 #  include <sys/ndir.h>
00062 # endif
00063 # ifdef HAVE_SYS_DIR_H
00064 #  include <sys/dir.h>
00065 # endif
00066 # ifdef HAVE_NDIR_H
00067 #  include <ndir.h>
00068 # endif
00069 # ifdef HAVE_VMSDIR_H
00070 #  include "vmsdir.h"
00071 # endif /* HAVE_VMSDIR_H */
00072 #endif
00073 
00074 
00075 /* In GNU systems, <dirent.h> defines this macro for us.  */
00076 #ifdef _D_NAMLEN
00077 # undef NAMLEN
00078 # define NAMLEN(d) _D_NAMLEN(d)
00079 #endif
00080 
00081 /* When used in the GNU libc the symbol _DIRENT_HAVE_D_TYPE is available
00082    if the `d_type' member for `struct dirent' is available.
00083    HAVE_STRUCT_DIRENT_D_TYPE plays the same role in GNULIB.  */
00084 #if defined _DIRENT_HAVE_D_TYPE || defined HAVE_STRUCT_DIRENT_D_TYPE
00085 /* True if the directory entry D must be of type T.  */
00086 # define DIRENT_MUST_BE(d, t)      ((d)->d_type == (t))
00087 
00088 /* True if the directory entry D might be a symbolic link.  */
00089 # define DIRENT_MIGHT_BE_SYMLINK(d) \
00090     ((d)->d_type == DT_UNKNOWN || (d)->d_type == DT_LNK)
00091 
00092 /* True if the directory entry D might be a directory.  */
00093 # define DIRENT_MIGHT_BE_DIR(d)     \
00094     ((d)->d_type == DT_DIR || DIRENT_MIGHT_BE_SYMLINK (d))
00095 
00096 #else /* !HAVE_D_TYPE */
00097 # define DIRENT_MUST_BE(d, t)             false
00098 # define DIRENT_MIGHT_BE_SYMLINK(d)       true
00099 # define DIRENT_MIGHT_BE_DIR(d)           true
00100 #endif /* HAVE_D_TYPE */
00101 
00102 /* If the system has the `struct dirent64' type we use it internally.  */
00103 #if defined _LIBC && !defined COMPILE_GLOB64
00104 # if defined HAVE_DIRENT_H || defined __GNU_LIBRARY__
00105 #  define CONVERT_D_NAMLEN(d64, d32)
00106 # else
00107 #  define CONVERT_D_NAMLEN(d64, d32) \
00108   (d64)->d_namlen = (d32)->d_namlen;
00109 # endif
00110 
00111 # if (defined POSIX || defined WINDOWS32) && !defined __GNU_LIBRARY__
00112 #  define CONVERT_D_INO(d64, d32)
00113 # else
00114 #  define CONVERT_D_INO(d64, d32) \
00115   (d64)->d_ino = (d32)->d_ino;
00116 # endif
00117 
00118 # ifdef _DIRENT_HAVE_D_TYPE
00119 #  define CONVERT_D_TYPE(d64, d32) \
00120   (d64)->d_type = (d32)->d_type;
00121 # else
00122 #  define CONVERT_D_TYPE(d64, d32)
00123 # endif
00124 
00125 # define CONVERT_DIRENT_DIRENT64(d64, d32) \
00126   memcpy ((d64)->d_name, (d32)->d_name, NAMLEN (d32) + 1);                  \
00127   CONVERT_D_NAMLEN (d64, d32)                                               \
00128   CONVERT_D_INO (d64, d32)                                           \
00129   CONVERT_D_TYPE (d64, d32)
00130 #endif
00131 
00132 
00133 #if (defined POSIX || defined WINDOWS32) && !defined __GNU_LIBRARY__
00134 /* Posix does not require that the d_ino field be present, and some
00135    systems do not provide it. */
00136 # define REAL_DIR_ENTRY(dp) 1
00137 #else
00138 # define REAL_DIR_ENTRY(dp) (dp->d_ino != 0)
00139 #endif /* POSIX */
00140 
00141 #include <stdlib.h>
00142 #include <string.h>
00143 
00144 /* NAME_MAX is usually defined in <dirent.h> or <limits.h>.  */
00145 #include <limits.h>
00146 #ifndef NAME_MAX
00147 # define NAME_MAX (sizeof (((struct dirent *) 0)->d_name))
00148 #endif
00149 
00150 #include <alloca.h>
00151 
00152 #ifdef _LIBC
00153 # undef strdup
00154 # define strdup(str) __strdup (str)
00155 # define sysconf(id) __sysconf (id)
00156 # define closedir(dir) __closedir (dir)
00157 # define opendir(name) __opendir (name)
00158 # define readdir(str) __readdir64 (str)
00159 # define getpwnam_r(name, bufp, buf, len, res) \
00160    __getpwnam_r (name, bufp, buf, len, res)
00161 # ifndef __stat64
00162 #  define __stat64(fname, buf) __xstat64 (_STAT_VER, fname, buf)
00163 # endif
00164 # define struct_stat64             struct stat64
00165 #else /* !_LIBC */
00166 # include "getlogin_r.h"
00167 # include "mempcpy.h"
00168 # include "stat-macros.h"
00169 # include "strdup.h"
00170 # define __stat64(fname, buf)      stat (fname, buf)
00171 # define struct_stat64             struct stat
00172 # define __stat(fname, buf) stat (fname, buf)
00173 # define __alloca           alloca
00174 # define __readdir          readdir
00175 # define __readdir64        readdir64
00176 # define __glob_pattern_p   glob_pattern_p
00177 #endif /* _LIBC */
00178 
00179 #include <fnmatch.h>
00180 
00181 #ifdef _SC_GETPW_R_SIZE_MAX
00182 # define GETPW_R_SIZE_MAX() sysconf (_SC_GETPW_R_SIZE_MAX)
00183 #else
00184 # define GETPW_R_SIZE_MAX() (-1)
00185 #endif
00186 #ifdef _SC_LOGIN_NAME_MAX
00187 # define GET_LOGIN_NAME_MAX()      sysconf (_SC_LOGIN_NAME_MAX)
00188 #else
00189 # define GET_LOGIN_NAME_MAX()      (-1)
00190 #endif
00191 
00192 static const char *next_brace_sub (const char *begin, int flags) __THROW;
00193 
00194 #endif /* !defined _LIBC || !defined GLOB_ONLY_P */
00195 
00196 #ifndef attribute_hidden
00197 # define attribute_hidden
00198 #endif
00199 
00200 static int glob_in_dir (const char *pattern, const char *directory,
00201                      int flags, int (*errfunc) (const char *, int),
00202                      glob_t *pglob);
00203 extern int __glob_pattern_type (const char *pattern, int quote)
00204     attribute_hidden;
00205 
00206 #if !defined _LIBC || !defined GLOB_ONLY_P
00207 static int prefix_array (const char *prefix, char **array, size_t n) __THROW;
00208 static int collated_compare (const void *, const void *) __THROW;
00209 
00210 
00211 /* Find the end of the sub-pattern in a brace expression.  */
00212 static const char *
00213 next_brace_sub (const char *cp, int flags)
00214 {
00215   unsigned int depth = 0;
00216   while (*cp != '\0')
00217     if ((flags & GLOB_NOESCAPE) == 0 && *cp == '\\')
00218       {
00219        if (*++cp == '\0')
00220          break;
00221        ++cp;
00222       }
00223     else
00224       {
00225        if ((*cp == '}' && depth-- == 0) || (*cp == ',' && depth == 0))
00226          break;
00227 
00228        if (*cp++ == '{')
00229          depth++;
00230       }
00231 
00232   return *cp != '\0' ? cp : NULL;
00233 }
00234 
00235 #endif /* !defined _LIBC || !defined GLOB_ONLY_P */
00236 
00237 /* Do glob searching for PATTERN, placing results in PGLOB.
00238    The bits defined above may be set in FLAGS.
00239    If a directory cannot be opened or read and ERRFUNC is not nil,
00240    it is called with the pathname that caused the error, and the
00241    `errno' value from the failing call; if it returns non-zero
00242    `glob' returns GLOB_ABORTED; if it returns zero, the error is ignored.
00243    If memory cannot be allocated for PGLOB, GLOB_NOSPACE is returned.
00244    Otherwise, `glob' returns zero.  */
00245 int
00246 #ifdef GLOB_ATTRIBUTE
00247 GLOB_ATTRIBUTE
00248 #endif
00249 glob (pattern, flags, errfunc, pglob)
00250      const char *pattern;
00251      int flags;
00252      int (*errfunc) (const char *, int);
00253      glob_t *pglob;
00254 {
00255   const char *filename;
00256   const char *dirname;
00257   size_t dirlen;
00258   int status;
00259   size_t oldcount;
00260   int meta;
00261   int dirname_modified;
00262   glob_t dirs;
00263 
00264   if (pattern == NULL || pglob == NULL || (flags & ~__GLOB_FLAGS) != 0)
00265     {
00266       __set_errno (EINVAL);
00267       return -1;
00268     }
00269 
00270   if (!(flags & GLOB_DOOFFS))
00271     /* Have to do this so `globfree' knows where to start freeing.  It
00272        also makes all the code that uses gl_offs simpler. */
00273     pglob->gl_offs = 0;
00274 
00275   if (flags & GLOB_BRACE)
00276     {
00277       const char *begin;
00278 
00279       if (flags & GLOB_NOESCAPE)
00280        begin = strchr (pattern, '{');
00281       else
00282        {
00283          begin = pattern;
00284          while (1)
00285            {
00286              if (*begin == '\0')
00287               {
00288                 begin = NULL;
00289                 break;
00290               }
00291 
00292              if (*begin == '\\' && begin[1] != '\0')
00293               ++begin;
00294              else if (*begin == '{')
00295               break;
00296 
00297              ++begin;
00298            }
00299        }
00300 
00301       if (begin != NULL)
00302        {
00303          /* Allocate working buffer large enough for our work.  Note that
00304            we have at least an opening and closing brace.  */
00305          size_t firstc;
00306          char *alt_start;
00307          const char *p;
00308          const char *next;
00309          const char *rest;
00310          size_t rest_len;
00311 #ifdef __GNUC__
00312          char onealt[strlen (pattern) - 1];
00313 #else
00314          char *onealt = (char *) malloc (strlen (pattern) - 1);
00315          if (onealt == NULL)
00316            {
00317              if (!(flags & GLOB_APPEND))
00318               {
00319                 pglob->gl_pathc = 0;
00320                 pglob->gl_pathv = NULL;
00321               }
00322              return GLOB_NOSPACE;
00323            }
00324 #endif
00325 
00326          /* We know the prefix for all sub-patterns.  */
00327          alt_start = mempcpy (onealt, pattern, begin - pattern);
00328 
00329          /* Find the first sub-pattern and at the same time find the
00330             rest after the closing brace.  */
00331          next = next_brace_sub (begin + 1, flags);
00332          if (next == NULL)
00333            {
00334              /* It is an illegal expression.  */
00335 #ifndef __GNUC__
00336              free (onealt);
00337 #endif
00338              return glob (pattern, flags & ~GLOB_BRACE, errfunc, pglob);
00339            }
00340 
00341          /* Now find the end of the whole brace expression.  */
00342          rest = next;
00343          while (*rest != '}')
00344            {
00345              rest = next_brace_sub (rest + 1, flags);
00346              if (rest == NULL)
00347               {
00348                 /* It is an illegal expression.  */
00349 #ifndef __GNUC__
00350                 free (onealt);
00351 #endif
00352                 return glob (pattern, flags & ~GLOB_BRACE, errfunc, pglob);
00353               }
00354            }
00355          /* Please note that we now can be sure the brace expression
00356             is well-formed.  */
00357          rest_len = strlen (++rest) + 1;
00358 
00359          /* We have a brace expression.  BEGIN points to the opening {,
00360             NEXT points past the terminator of the first element, and END
00361             points past the final }.  We will accumulate result names from
00362             recursive runs for each brace alternative in the buffer using
00363             GLOB_APPEND.  */
00364 
00365          if (!(flags & GLOB_APPEND))
00366            {
00367              /* This call is to set a new vector, so clear out the
00368                vector so we can append to it.  */
00369              pglob->gl_pathc = 0;
00370              pglob->gl_pathv = NULL;
00371            }
00372          firstc = pglob->gl_pathc;
00373 
00374          p = begin + 1;
00375          while (1)
00376            {
00377              int result;
00378 
00379              /* Construct the new glob expression.  */
00380              mempcpy (mempcpy (alt_start, p, next - p), rest, rest_len);
00381 
00382              result = glob (onealt,
00383                           ((flags & ~(GLOB_NOCHECK | GLOB_NOMAGIC))
00384                            | GLOB_APPEND), errfunc, pglob);
00385 
00386              /* If we got an error, return it.  */
00387              if (result && result != GLOB_NOMATCH)
00388               {
00389 #ifndef __GNUC__
00390                 free (onealt);
00391 #endif
00392                 if (!(flags & GLOB_APPEND))
00393                   {
00394                     globfree (pglob);
00395                     pglob->gl_pathc = 0;
00396                   }
00397                 return result;
00398               }
00399 
00400              if (*next == '}')
00401               /* We saw the last entry.  */
00402               break;
00403 
00404              p = next + 1;
00405              next = next_brace_sub (p, flags);
00406              assert (next != NULL);
00407            }
00408 
00409 #ifndef __GNUC__
00410          free (onealt);
00411 #endif
00412 
00413          if (pglob->gl_pathc != firstc)
00414            /* We found some entries.  */
00415            return 0;
00416          else if (!(flags & (GLOB_NOCHECK|GLOB_NOMAGIC)))
00417            return GLOB_NOMATCH;
00418        }
00419     }
00420 
00421   /* Find the filename.  */
00422   filename = strrchr (pattern, '/');
00423 #if defined __MSDOS__ || defined WINDOWS32
00424   /* The case of "d:pattern".  Since `:' is not allowed in
00425      file names, we can safely assume that wherever it
00426      happens in pattern, it signals the filename part.  This
00427      is so we could some day support patterns like "[a-z]:foo".  */
00428   if (filename == NULL)
00429     filename = strchr (pattern, ':');
00430 #endif /* __MSDOS__ || WINDOWS32 */
00431   dirname_modified = 0;
00432   if (filename == NULL)
00433     {
00434       /* This can mean two things: a simple name or "~name".  The latter
00435         case is nothing but a notation for a directory.  */
00436       if ((flags & (GLOB_TILDE|GLOB_TILDE_CHECK)) && pattern[0] == '~')
00437        {
00438          dirname = pattern;
00439          dirlen = strlen (pattern);
00440 
00441          /* Set FILENAME to NULL as a special flag.  This is ugly but
00442             other solutions would require much more code.  We test for
00443             this special case below.  */
00444          filename = NULL;
00445        }
00446       else
00447        {
00448          filename = pattern;
00449 #ifdef _AMIGA
00450          dirname = "";
00451 #else
00452          dirname = ".";
00453 #endif
00454          dirlen = 0;
00455        }
00456     }
00457   else if (filename == pattern
00458           || (filename == pattern + 1 && pattern[0] == '\\'
00459               && (flags & GLOB_NOESCAPE) == 0))
00460     {
00461       /* "/pattern" or "\\/pattern".  */
00462       dirname = "/";
00463       dirlen = 1;
00464       ++filename;
00465     }
00466   else
00467     {
00468       char *newp;
00469       dirlen = filename - pattern;
00470 #if defined __MSDOS__ || defined WINDOWS32
00471       if (*filename == ':'
00472          || (filename > pattern + 1 && filename[-1] == ':'))
00473        {
00474          char *drive_spec;
00475 
00476          ++dirlen;
00477          drive_spec = (char *) __alloca (dirlen + 1);
00478          *((char *) mempcpy (drive_spec, pattern, dirlen)) = '\0';
00479          /* For now, disallow wildcards in the drive spec, to
00480             prevent infinite recursion in glob.  */
00481          if (__glob_pattern_p (drive_spec, !(flags & GLOB_NOESCAPE)))
00482            return GLOB_NOMATCH;
00483          /* If this is "d:pattern", we need to copy `:' to DIRNAME
00484             as well.  If it's "d:/pattern", don't remove the slash
00485             from "d:/", since "d:" and "d:/" are not the same.*/
00486        }
00487 #endif
00488       newp = (char *) __alloca (dirlen + 1);
00489       *((char *) mempcpy (newp, pattern, dirlen)) = '\0';
00490       dirname = newp;
00491       ++filename;
00492 
00493       if (filename[0] == '\0'
00494 #if defined __MSDOS__ || defined WINDOWS32
00495           && dirname[dirlen - 1] != ':'
00496          && (dirlen < 3 || dirname[dirlen - 2] != ':'
00497              || dirname[dirlen - 1] != '/')
00498 #endif
00499          && dirlen > 1)
00500        /* "pattern/".  Expand "pattern", appending slashes.  */
00501        {
00502          int orig_flags = flags;
00503          if (!(flags & GLOB_NOESCAPE) && dirname[dirlen - 1] == '\\')
00504            {
00505              /* "pattern\\/".  Remove the final backslash if it hasn't
00506                been quoted.  */
00507              char *p = (char *) &dirname[dirlen - 1];
00508 
00509              while (p > dirname && p[-1] == '\\') --p;
00510              if ((&dirname[dirlen] - p) & 1)
00511               {
00512                 *(char *) &dirname[--dirlen] = '\0';
00513                 flags &= ~(GLOB_NOCHECK | GLOB_NOMAGIC);
00514               }
00515            }
00516          int val = glob (dirname, flags | GLOB_MARK, errfunc, pglob);
00517          if (val == 0)
00518            pglob->gl_flags = ((pglob->gl_flags & ~GLOB_MARK)
00519                             | (flags & GLOB_MARK));
00520          else if (val == GLOB_NOMATCH && flags != orig_flags)
00521            {
00522              /* Make sure globfree (&dirs); is a nop.  */
00523              dirs.gl_pathv = NULL;
00524              flags = orig_flags;
00525              oldcount = pglob->gl_pathc + pglob->gl_offs;
00526              goto no_matches;
00527            }
00528          return val;
00529        }
00530     }
00531 
00532   if (!(flags & GLOB_APPEND))
00533     {
00534       pglob->gl_pathc = 0;
00535       if (!(flags & GLOB_DOOFFS))
00536         pglob->gl_pathv = NULL;
00537       else
00538        {
00539          size_t i;
00540          pglob->gl_pathv = (char **) malloc ((pglob->gl_offs + 1)
00541                                          * sizeof (char *));
00542          if (pglob->gl_pathv == NULL)
00543            return GLOB_NOSPACE;
00544 
00545          for (i = 0; i <= pglob->gl_offs; ++i)
00546            pglob->gl_pathv[i] = NULL;
00547        }
00548     }
00549 
00550   oldcount = pglob->gl_pathc + pglob->gl_offs;
00551 
00552 #ifndef VMS
00553   if ((flags & (GLOB_TILDE|GLOB_TILDE_CHECK)) && dirname[0] == '~')
00554     {
00555       if (dirname[1] == '\0' || dirname[1] == '/'
00556          || (!(flags & GLOB_NOESCAPE) && dirname[1] == '\\'
00557              && (dirname[2] == '\0' || dirname[2] == '/')))
00558        {
00559          /* Look up home directory.  */
00560          const char *home_dir = getenv ("HOME");
00561 # ifdef _AMIGA
00562          if (home_dir == NULL || home_dir[0] == '\0')
00563            home_dir = "SYS:";
00564 # else
00565 #  ifdef WINDOWS32
00566          if (home_dir == NULL || home_dir[0] == '\0')
00567             home_dir = "c:/users/default"; /* poor default */
00568 #  else
00569          if (home_dir == NULL || home_dir[0] == '\0')
00570            {
00571              int success;
00572              char *name;
00573              size_t buflen = GET_LOGIN_NAME_MAX () + 1;
00574 
00575              if (buflen == 0)
00576               /* `sysconf' does not support _SC_LOGIN_NAME_MAX.  Try
00577                  a moderate value.  */
00578               buflen = 20;
00579              name = (char *) __alloca (buflen);
00580 
00581              success = getlogin_r (name, buflen) == 0;
00582              if (success)
00583               {
00584                 struct passwd *p;
00585 #   if defined HAVE_GETPWNAM_R || defined _LIBC
00586                 long int pwbuflen = GETPW_R_SIZE_MAX ();
00587                 char *pwtmpbuf;
00588                 struct passwd pwbuf;
00589                 int save = errno;
00590 
00591 #    ifndef _LIBC
00592                 if (pwbuflen == -1)
00593                   /* `sysconf' does not support _SC_GETPW_R_SIZE_MAX.
00594                      Try a moderate value.  */
00595                   pwbuflen = 1024;
00596 #    endif
00597                 pwtmpbuf = (char *) __alloca (pwbuflen);
00598 
00599                 while (getpwnam_r (name, &pwbuf, pwtmpbuf, pwbuflen, &p)
00600                       != 0)
00601                   {
00602                     if (errno != ERANGE)
00603                      {
00604                        p = NULL;
00605                        break;
00606                      }
00607 #    ifdef _LIBC
00608                     pwtmpbuf = extend_alloca (pwtmpbuf, pwbuflen,
00609                                           2 * pwbuflen);
00610 #    else
00611                     pwbuflen *= 2;
00612                     pwtmpbuf = (char *) __alloca (pwbuflen);
00613 #    endif
00614                     __set_errno (save);
00615                   }
00616 #   else
00617                 p = getpwnam (name);
00618 #   endif
00619                 if (p != NULL)
00620                   home_dir = p->pw_dir;
00621               }
00622            }
00623          if (home_dir == NULL || home_dir[0] == '\0')
00624            {
00625              if (flags & GLOB_TILDE_CHECK)
00626               return GLOB_NOMATCH;
00627              else
00628               home_dir = "~"; /* No luck.  */
00629            }
00630 #  endif /* WINDOWS32 */
00631 # endif
00632          /* Now construct the full directory.  */
00633          if (dirname[1] == '\0')
00634            {
00635              dirname = home_dir;
00636              dirlen = strlen (dirname);
00637            }
00638          else
00639            {
00640              char *newp;
00641              size_t home_len = strlen (home_dir);
00642              newp = (char *) __alloca (home_len + dirlen);
00643              mempcpy (mempcpy (newp, home_dir, home_len),
00644                      &dirname[1], dirlen);
00645              dirname = newp;
00646              dirlen += home_len - 1;
00647            }
00648          dirname_modified = 1;
00649        }
00650 # if !defined _AMIGA && !defined WINDOWS32
00651       else
00652        {
00653          char *end_name = strchr (dirname, '/');
00654          const char *user_name;
00655          const char *home_dir;
00656          char *unescape = NULL;
00657 
00658          if (!(flags & GLOB_NOESCAPE))
00659            {
00660              if (end_name == NULL)
00661               {
00662                 unescape = strchr (dirname, '\\');
00663                 if (unescape)
00664                   end_name = strchr (unescape, '\0');
00665               }
00666              else
00667               unescape = memchr (dirname, '\\', end_name - dirname);
00668            }
00669          if (end_name == NULL)
00670            user_name = dirname + 1;
00671          else
00672            {
00673              char *newp;
00674              newp = (char *) __alloca (end_name - dirname);
00675              if (unescape != NULL)
00676               {
00677                 char *p = mempcpy (newp, dirname + 1,
00678                                  unescape - dirname - 1);
00679                 char *q = unescape;
00680                 while (*q != '\0')
00681                   {
00682                     if (*q == '\\')
00683                      {
00684                        if (q[1] == '\0')
00685                          {
00686                            /* "~fo\\o\\" unescape to user_name "foo\\",
00687                              but "~fo\\o\\/" unescape to user_name
00688                              "foo".  */
00689                            if (filename == NULL)
00690                             *p++ = '\\';
00691                            break;
00692                          }
00693                        ++q;
00694                      }
00695                     *p++ = *q++;
00696                   }
00697                 *p = '\0';
00698               }
00699              else
00700               *((char *) mempcpy (newp, dirname + 1, end_name - dirname))
00701                 = '\0';
00702              user_name = newp;
00703            }
00704 
00705          /* Look up specific user's home directory.  */
00706          {
00707            struct passwd *p;
00708 #  if defined HAVE_GETPWNAM_R || defined _LIBC
00709            long int buflen = GETPW_R_SIZE_MAX ();
00710            char *pwtmpbuf;
00711            struct passwd pwbuf;
00712            int save = errno;
00713 
00714 #   ifndef _LIBC
00715            if (buflen == -1)
00716              /* `sysconf' does not support _SC_GETPW_R_SIZE_MAX.  Try a
00717                moderate value.  */
00718              buflen = 1024;
00719 #   endif
00720            pwtmpbuf = (char *) __alloca (buflen);
00721 
00722            while (getpwnam_r (user_name, &pwbuf, pwtmpbuf, buflen, &p) != 0)
00723              {
00724               if (errno != ERANGE)
00725                 {
00726                   p = NULL;
00727                   break;
00728                 }
00729 #   ifdef _LIBC
00730               pwtmpbuf = extend_alloca (pwtmpbuf, buflen, 2 * buflen);
00731 #   else
00732               buflen *= 2;
00733               pwtmpbuf = __alloca (buflen);
00734 #   endif
00735               __set_errno (save);
00736              }
00737 #  else
00738            p = getpwnam (user_name);
00739 #  endif
00740            if (p != NULL)
00741              home_dir = p->pw_dir;
00742            else
00743              home_dir = NULL;
00744          }
00745          /* If we found a home directory use this.  */
00746          if (home_dir != NULL)
00747            {
00748              char *newp;
00749              size_t home_len = strlen (home_dir);
00750              size_t rest_len = end_name == NULL ? 0 : strlen (end_name);
00751              newp = (char *) __alloca (home_len + rest_len + 1);
00752              *((char *) mempcpy (mempcpy (newp, home_dir, home_len),
00753                               end_name, rest_len)) = '\0';
00754              dirname = newp;
00755              dirlen = home_len + rest_len;
00756              dirname_modified = 1;
00757            }
00758          else
00759            if (flags & GLOB_TILDE_CHECK)
00760              /* We have to regard it as an error if we cannot find the
00761                home directory.  */
00762              return GLOB_NOMATCH;
00763        }
00764 # endif       /* Not Amiga && not WINDOWS32.  */
00765     }
00766 #endif /* Not VMS.  */
00767 
00768   /* Now test whether we looked for "~" or "~NAME".  In this case we
00769      can give the answer now.  */
00770   if (filename == NULL)
00771     {
00772       struct stat st;
00773       struct_stat64 st64;
00774 
00775       /* Return the directory if we don't check for error or if it exists.  */
00776       if ((flags & GLOB_NOCHECK)
00777          || (((__builtin_expect (flags & GLOB_ALTDIRFUNC, 0))
00778               ? ((*pglob->gl_stat) (dirname, &st) == 0
00779                 && S_ISDIR (st.st_mode))
00780               : (__stat64 (dirname, &st64) == 0 && S_ISDIR (st64.st_mode)))))
00781        {
00782          int newcount = pglob->gl_pathc + pglob->gl_offs;
00783          char **new_gl_pathv;
00784 
00785          new_gl_pathv
00786            = (char **) realloc (pglob->gl_pathv,
00787                              (newcount + 1 + 1) * sizeof (char *));
00788          if (new_gl_pathv == NULL)
00789            {
00790            nospace:
00791              free (pglob->gl_pathv);
00792              pglob->gl_pathv = NULL;
00793              pglob->gl_pathc = 0;
00794              return GLOB_NOSPACE;
00795            }
00796          pglob->gl_pathv = new_gl_pathv;
00797 
00798          if (flags & GLOB_MARK)
00799            {
00800              char *p;
00801              pglob->gl_pathv[newcount] = malloc (dirlen + 2);
00802              if (pglob->gl_pathv[newcount] == NULL)
00803               goto nospace;
00804              p = mempcpy (pglob->gl_pathv[newcount], dirname, dirlen);
00805              p[0] = '/';
00806              p[1] = '\0';
00807            }
00808          else
00809            {
00810              pglob->gl_pathv[newcount] = strdup (dirname);
00811              if (pglob->gl_pathv[newcount] == NULL)
00812               goto nospace;
00813            }
00814          pglob->gl_pathv[++newcount] = NULL;
00815          ++pglob->gl_pathc;
00816          pglob->gl_flags = flags;
00817 
00818          return 0;
00819        }
00820 
00821       /* Not found.  */
00822       return GLOB_NOMATCH;
00823     }
00824 
00825   meta = __glob_pattern_type (dirname, !(flags & GLOB_NOESCAPE));
00826   /* meta is 1 if correct glob pattern containing metacharacters.
00827      If meta has bit (1 << 2) set, it means there was an unterminated
00828      [ which we handle the same, using fnmatch.  Broken unterminated
00829      pattern bracket expressions ought to be rare enough that it is
00830      not worth special casing them, fnmatch will do the right thing.  */
00831   if (meta & 5)
00832     {
00833       /* The directory name contains metacharacters, so we
00834         have to glob for the directory, and then glob for
00835         the pattern in each directory found.  */
00836       size_t i;
00837 
00838       if (!(flags & GLOB_NOESCAPE) && dirlen > 0 && dirname[dirlen - 1] == '\\')
00839        {
00840          /* "foo\\/bar".  Remove the final backslash from dirname
00841             if it has not been quoted.  */
00842          char *p = (char *) &dirname[dirlen - 1];
00843 
00844          while (p > dirname && p[-1] == '\\') --p;
00845          if ((&dirname[dirlen] - p) & 1)
00846            *(char *) &dirname[--dirlen] = '\0';
00847        }
00848 
00849       if (__builtin_expect ((flags & GLOB_ALTDIRFUNC) != 0, 0))
00850        {
00851          /* Use the alternative access functions also in the recursive
00852             call.  */
00853          dirs.gl_opendir = pglob->gl_opendir;
00854          dirs.gl_readdir = pglob->gl_readdir;
00855          dirs.gl_closedir = pglob->gl_closedir;
00856          dirs.gl_stat = pglob->gl_stat;
00857          dirs.gl_lstat = pglob->gl_lstat;
00858        }
00859 
00860       status = glob (dirname,
00861                    ((flags & (GLOB_ERR | GLOB_NOESCAPE
00862                             | GLOB_ALTDIRFUNC))
00863                     | GLOB_NOSORT | GLOB_ONLYDIR),
00864                    errfunc, &dirs);
00865       if (status != 0)
00866        {
00867          if ((flags & GLOB_NOCHECK) == 0 || status != GLOB_NOMATCH)
00868            return status;
00869          goto no_matches;
00870        }
00871 
00872       /* We have successfully globbed the preceding directory name.
00873         For each name we found, call glob_in_dir on it and FILENAME,
00874         appending the results to PGLOB.  */
00875       for (i = 0; i < dirs.gl_pathc; ++i)
00876        {
00877          int old_pathc;
00878 
00879 #ifdef SHELL
00880          {
00881            /* Make globbing interruptible in the bash shell. */
00882            extern int interrupt_state;
00883 
00884            if (interrupt_state)
00885              {
00886               globfree (&dirs);
00887               return GLOB_ABORTED;
00888              }
00889          }
00890 #endif /* SHELL.  */
00891 
00892          old_pathc = pglob->gl_pathc;
00893          status = glob_in_dir (filename, dirs.gl_pathv[i],
00894                             ((flags | GLOB_APPEND)
00895                              & ~(GLOB_NOCHECK | GLOB_NOMAGIC)),
00896                             errfunc, pglob);
00897          if (status == GLOB_NOMATCH)
00898            /* No matches in this directory.  Try the next.  */
00899            continue;
00900 
00901          if (status != 0)
00902            {
00903              globfree (&dirs);
00904              globfree (pglob);
00905              pglob->gl_pathc = 0;
00906              return status;
00907            }
00908 
00909          /* Stick the directory on the front of each name.  */
00910          if (prefix_array (dirs.gl_pathv[i],
00911                          &pglob->gl_pathv[old_pathc + pglob->gl_offs],
00912                          pglob->gl_pathc - old_pathc))
00913            {
00914              globfree (&dirs);
00915              globfree (pglob);
00916              pglob->gl_pathc = 0;
00917              return GLOB_NOSPACE;
00918            }
00919        }
00920 
00921       flags |= GLOB_MAGCHAR;
00922 
00923       /* We have ignored the GLOB_NOCHECK flag in the `glob_in_dir' calls.
00924         But if we have not found any matching entry and the GLOB_NOCHECK
00925         flag was set we must return the input pattern itself.  */
00926       if (pglob->gl_pathc + pglob->gl_offs == oldcount)
00927        {
00928        no_matches:
00929          /* No matches.  */
00930          if (flags & GLOB_NOCHECK)
00931            {
00932              int newcount = pglob->gl_pathc + pglob->gl_offs;
00933              char **new_gl_pathv;
00934 
00935              new_gl_pathv = (char **) realloc (pglob->gl_pathv,
00936                                           (newcount + 2)
00937                                           * sizeof (char *));
00938              if (new_gl_pathv == NULL)
00939               {
00940                 globfree (&dirs);
00941                 return GLOB_NOSPACE;
00942               }
00943              pglob->gl_pathv = new_gl_pathv;
00944 
00945              pglob->gl_pathv[newcount] = __strdup (pattern);
00946              if (pglob->gl_pathv[newcount] == NULL)
00947               {
00948                 globfree (&dirs);
00949                 globfree (pglob);
00950                 pglob->gl_pathc = 0;
00951                 return GLOB_NOSPACE;
00952               }
00953 
00954              ++pglob->gl_pathc;
00955              ++newcount;
00956 
00957              pglob->gl_pathv[newcount] = NULL;
00958              pglob->gl_flags = flags;
00959            }
00960          else
00961            {
00962              globfree (&dirs);
00963              return GLOB_NOMATCH;
00964            }
00965        }
00966 
00967       globfree (&dirs);
00968     }
00969   else
00970     {
00971       int old_pathc = pglob->gl_pathc;
00972       int orig_flags = flags;
00973 
00974       if (meta & 2)
00975        {
00976          char *p = strchr (dirname, '\\'), *q;
00977          /* We need to unescape the dirname string.  It is certainly
00978             allocated by alloca, as otherwise filename would be NULL
00979             or dirname wouldn't contain backslashes.  */
00980          q = p;
00981          do
00982            {
00983              if (*p == '\\')
00984               {
00985                 *q = *++p;
00986                 --dirlen;
00987               }
00988              else
00989               *q = *p;
00990              ++q;
00991            }
00992          while (*p++ != '\0');
00993          dirname_modified = 1;
00994        }
00995       if (dirname_modified)
00996        flags &= ~(GLOB_NOCHECK | GLOB_NOMAGIC);
00997       status = glob_in_dir (filename, dirname, flags, errfunc, pglob);
00998       if (status != 0)
00999        {
01000          if (status == GLOB_NOMATCH && flags != orig_flags
01001              && pglob->gl_pathc + pglob->gl_offs == oldcount)
01002            {
01003              /* Make sure globfree (&dirs); is a nop.  */
01004              dirs.gl_pathv = NULL;
01005              flags = orig_flags;
01006              goto no_matches;
01007            }
01008          return status;
01009        }
01010 
01011       if (dirlen > 0)
01012        {
01013          /* Stick the directory on the front of each name.  */
01014          if (prefix_array (dirname,
01015                          &pglob->gl_pathv[old_pathc + pglob->gl_offs],
01016                          pglob->gl_pathc - old_pathc))
01017            {
01018              globfree (pglob);
01019              pglob->gl_pathc = 0;
01020              return GLOB_NOSPACE;
01021            }
01022        }
01023     }
01024 
01025   if (flags & GLOB_MARK)
01026     {
01027       /* Append slashes to directory names.  */
01028       size_t i;
01029       struct stat st;
01030       struct_stat64 st64;
01031 
01032       for (i = oldcount; i < pglob->gl_pathc + pglob->gl_offs; ++i)
01033        if ((__builtin_expect (flags & GLOB_ALTDIRFUNC, 0)
01034             ? ((*pglob->gl_stat) (pglob->gl_pathv[i], &st) == 0
01035               && S_ISDIR (st.st_mode))
01036             : (__stat64 (pglob->gl_pathv[i], &st64) == 0
01037               && S_ISDIR (st64.st_mode))))
01038          {
01039            size_t len = strlen (pglob->gl_pathv[i]) + 2;
01040            char *new = realloc (pglob->gl_pathv[i], len);
01041            if (new == NULL)
01042              {
01043               globfree (pglob);
01044               pglob->gl_pathc = 0;
01045               return GLOB_NOSPACE;
01046              }
01047            strcpy (&new[len - 2], "/");
01048            pglob->gl_pathv[i] = new;
01049          }
01050     }
01051 
01052   if (!(flags & GLOB_NOSORT))
01053     {
01054       /* Sort the vector.  */
01055       qsort (&pglob->gl_pathv[oldcount],
01056             pglob->gl_pathc + pglob->gl_offs - oldcount,
01057             sizeof (char *), collated_compare);
01058     }
01059 
01060   return 0;
01061 }
01062 #if defined _LIBC && !defined glob
01063 libc_hidden_def (glob)
01064 #endif
01065 
01066 
01067 #if !defined _LIBC || !defined GLOB_ONLY_P
01068 
01069 /* Free storage allocated in PGLOB by a previous `glob' call.  */
01070 void
01071 globfree (pglob)
01072      register glob_t *pglob;
01073 {
01074   if (pglob->gl_pathv != NULL)
01075     {
01076       size_t i;
01077       for (i = 0; i < pglob->gl_pathc; ++i)
01078        free (pglob->gl_pathv[pglob->gl_offs + i]);
01079       free (pglob->gl_pathv);
01080       pglob->gl_pathv = NULL;
01081     }
01082 }
01083 #if defined _LIBC && !defined globfree
01084 libc_hidden_def (globfree)
01085 #endif
01086 
01087 
01088 /* Do a collated comparison of A and B.  */
01089 static int
01090 collated_compare (const void *a, const void *b)
01091 {
01092   const char *const s1 = *(const char *const * const) a;
01093   const char *const s2 = *(const char *const * const) b;
01094 
01095   if (s1 == s2)
01096     return 0;
01097   if (s1 == NULL)
01098     return 1;
01099   if (s2 == NULL)
01100     return -1;
01101   return strcoll (s1, s2);
01102 }
01103 
01104 
01105 /* Prepend DIRNAME to each of N members of ARRAY, replacing ARRAY's
01106    elements in place.  Return nonzero if out of memory, zero if successful.
01107    A slash is inserted between DIRNAME and each elt of ARRAY,
01108    unless DIRNAME is just "/".  Each old element of ARRAY is freed.  */
01109 static int
01110 prefix_array (const char *dirname, char **array, size_t n)
01111 {
01112   register size_t i;
01113   size_t dirlen = strlen (dirname);
01114 #if defined __MSDOS__ || defined WINDOWS32
01115   int sep_char = '/';
01116 # define DIRSEP_CHAR sep_char
01117 #else
01118 # define DIRSEP_CHAR '/'
01119 #endif
01120 
01121   if (dirlen == 1 && dirname[0] == '/')
01122     /* DIRNAME is just "/", so normal prepending would get us "//foo".
01123        We want "/foo" instead, so don't prepend any chars from DIRNAME.  */
01124     dirlen = 0;
01125 #if defined __MSDOS__ || defined WINDOWS32
01126   else if (dirlen > 1)
01127     {
01128       if (dirname[dirlen - 1] == '/' && dirname[dirlen - 2] == ':')
01129        /* DIRNAME is "d:/".  Don't prepend the slash from DIRNAME.  */
01130        --dirlen;
01131       else if (dirname[dirlen - 1] == ':')
01132        {
01133          /* DIRNAME is "d:".  Use `:' instead of `/'.  */
01134          --dirlen;
01135          sep_char = ':';
01136        }
01137     }
01138 #endif
01139 
01140   for (i = 0; i < n; ++i)
01141     {
01142       size_t eltlen = strlen (array[i]) + 1;
01143       char *new = (char *) malloc (dirlen + 1 + eltlen);
01144       if (new == NULL)
01145        {
01146          while (i > 0)
01147            free (array[--i]);
01148          return 1;
01149        }
01150 
01151       {
01152        char *endp = mempcpy (new, dirname, dirlen);
01153        *endp++ = DIRSEP_CHAR;
01154        mempcpy (endp, array[i], eltlen);
01155       }
01156       free (array[i]);
01157       array[i] = new;
01158     }
01159 
01160   return 0;
01161 }
01162 
01163 
01164 /* We must not compile this function twice.  */
01165 #if !defined _LIBC || !defined NO_GLOB_PATTERN_P
01166 int
01167 __glob_pattern_type (pattern, quote)
01168      const char *pattern;
01169      int quote;
01170 {
01171   register const char *p;
01172   int ret = 0;
01173 
01174   for (p = pattern; *p != '\0'; ++p)
01175     switch (*p)
01176       {
01177       case '?':
01178       case '*':
01179        return 1;
01180 
01181       case '\\':
01182        if (quote)
01183          {
01184            if (p[1] != '\0')
01185              ++p;
01186            ret |= 2;
01187          }
01188        break;
01189 
01190       case '[':
01191        ret |= 4;
01192        break;
01193 
01194       case ']':
01195        if (ret & 4)
01196          return 1;
01197        break;
01198       }
01199 
01200   return ret;
01201 }
01202 
01203 /* Return nonzero if PATTERN contains any metacharacters.
01204    Metacharacters can be quoted with backslashes if QUOTE is nonzero.  */
01205 int
01206 __glob_pattern_p (pattern, quote)
01207      const char *pattern;
01208      int quote;
01209 {
01210   return __glob_pattern_type (pattern, quote) == 1;
01211 }
01212 # ifdef _LIBC
01213 weak_alias (__glob_pattern_p, glob_pattern_p)
01214 # endif
01215 #endif
01216 
01217 #endif /* !GLOB_ONLY_P */
01218 
01219 
01220 /* We put this in a separate function mainly to allow the memory
01221    allocated with alloca to be recycled.  */
01222 #if !defined _LIBC || !defined GLOB_ONLY_P
01223 static int
01224 __attribute_noinline__
01225 link_exists2_p (const char *dir, size_t dirlen, const char *fname,
01226               glob_t *pglob
01227 # ifndef _LIBC
01228               , int flags
01229 # endif
01230               )
01231 {
01232   size_t fnamelen = strlen (fname);
01233   char *fullname = (char *) __alloca (dirlen + 1 + fnamelen + 1);
01234   struct stat st;
01235 # ifndef _LIBC
01236   struct_stat64 st64;
01237 # endif
01238 
01239   mempcpy (mempcpy (mempcpy (fullname, dir, dirlen), "/", 1),
01240           fname, fnamelen + 1);
01241 
01242 # ifdef _LIBC
01243   return (*pglob->gl_stat) (fullname, &st) == 0;
01244 # else
01245   return ((__builtin_expect (flags & GLOB_ALTDIRFUNC, 0)
01246           ? (*pglob->gl_stat) (fullname, &st)
01247           : __stat64 (fullname, &st64)) == 0);
01248 # endif
01249 }
01250 # ifdef _LIBC
01251 #  define link_exists_p(dfd, dirname, dirnamelen, fname, pglob, flags) \
01252   (__builtin_expect (flags & GLOB_ALTDIRFUNC, 0)                     \
01253    ? link_exists2_p (dirname, dirnamelen, fname, pglob)                     \
01254    : ({ struct stat64 st64;                                          \
01255        __fxstatat64 (_STAT_VER, dfd, fname, &st64, 0) == 0; }))
01256 # else
01257 #  define link_exists_p(dfd, dirname, dirnamelen, fname, pglob, flags) \
01258   link_exists2_p (dirname, dirnamelen, fname, pglob, flags)
01259 # endif
01260 #endif
01261 
01262 
01263 /* Like `glob', but PATTERN is a final pathname component,
01264    and matches are searched for in DIRECTORY.
01265    The GLOB_NOSORT bit in FLAGS is ignored.  No sorting is ever done.
01266    The GLOB_APPEND flag is assumed to be set (always appends).  */
01267 static int
01268 glob_in_dir (const char *pattern, const char *directory, int flags,
01269             int (*errfunc) (const char *, int),
01270             glob_t *pglob)
01271 {
01272   size_t dirlen = strlen (directory);
01273   void *stream = NULL;
01274   struct globnames
01275     {
01276       struct globnames *next;
01277       size_t count;
01278       char *name[64];
01279     };
01280 #define INITIAL_COUNT sizeof (init_names.name) / sizeof (init_names.name[0])
01281   struct globnames init_names;
01282   struct globnames *names = &init_names;
01283   struct globnames *names_alloca = &init_names;
01284   size_t nfound = 0;
01285   size_t allocasize = sizeof (init_names);
01286   size_t cur = 0;
01287   int meta;
01288   int save;
01289 
01290   init_names.next = NULL;
01291   init_names.count = INITIAL_COUNT;
01292 
01293   meta = __glob_pattern_type (pattern, !(flags & GLOB_NOESCAPE));
01294   if (meta == 0 && (flags & (GLOB_NOCHECK|GLOB_NOMAGIC)))
01295     {
01296       /* We need not do any tests.  The PATTERN contains no meta
01297         characters and we must not return an error therefore the
01298         result will always contain exactly one name.  */
01299       flags |= GLOB_NOCHECK;
01300     }
01301   else if (meta == 0)
01302     {
01303       /* Since we use the normal file functions we can also use stat()
01304         to verify the file is there.  */
01305       struct stat st;
01306       struct_stat64 st64;
01307       size_t patlen = strlen (pattern);
01308       char *fullname = (char *) __alloca (dirlen + 1 + patlen + 1);
01309 
01310       mempcpy (mempcpy (mempcpy (fullname, directory, dirlen),
01311                      "/", 1),
01312               pattern, patlen + 1);
01313       if ((__builtin_expect (flags & GLOB_ALTDIRFUNC, 0)
01314           ? (*pglob->gl_stat) (fullname, &st)
01315           : __stat64 (fullname, &st64)) == 0)
01316        /* We found this file to be existing.  Now tell the rest
01317           of the function to copy this name into the result.  */
01318        flags |= GLOB_NOCHECK;
01319     }
01320   else
01321     {
01322       stream = (__builtin_expect (flags & GLOB_ALTDIRFUNC, 0)
01323               ? (*pglob->gl_opendir) (directory)
01324               : opendir (directory));
01325       if (stream == NULL)
01326        {
01327          if (errno != ENOTDIR
01328              && ((errfunc != NULL && (*errfunc) (directory, errno))
01329                 || (flags & GLOB_ERR)))
01330            return GLOB_ABORTED;
01331        }
01332       else
01333        {
01334 #ifdef _LIBC
01335          int dfd = (__builtin_expect (flags & GLOB_ALTDIRFUNC, 0)
01336                    ? -1 : dirfd ((DIR *) stream));
01337 #endif
01338          int fnm_flags = ((!(flags & GLOB_PERIOD) ? FNM_PERIOD : 0)
01339                         | ((flags & GLOB_NOESCAPE) ? FNM_NOESCAPE : 0)
01340 #if defined _AMIGA || defined VMS
01341                         | FNM_CASEFOLD
01342 #endif
01343                         );
01344          flags |= GLOB_MAGCHAR;
01345 
01346          while (1)
01347            {
01348              const char *name;
01349              size_t len;
01350 #if defined _LIBC && !defined COMPILE_GLOB64
01351              struct dirent64 *d;
01352              union
01353               {
01354                 struct dirent64 d64;
01355                 char room [offsetof (struct dirent64, d_name[0])
01356                           + NAME_MAX + 1];
01357               }
01358              d64buf;
01359 
01360              if (__builtin_expect (flags & GLOB_ALTDIRFUNC, 0))
01361               {
01362                 struct dirent *d32 = (*pglob->gl_readdir) (stream);
01363                 if (d32 != NULL)
01364                   {
01365                     CONVERT_DIRENT_DIRENT64 (&d64buf.d64, d32);
01366                     d = &d64buf.d64;
01367                   }
01368                 else
01369                   d = NULL;
01370               }
01371              else
01372               d = __readdir64 (stream);
01373 #else
01374              struct dirent *d = (__builtin_expect (flags & GLOB_ALTDIRFUNC, 0)
01375                               ? ((struct dirent *)
01376                                  (*pglob->gl_readdir) (stream))
01377                               : __readdir (stream));
01378 #endif
01379              if (d == NULL)
01380               break;
01381              if (! REAL_DIR_ENTRY (d))
01382               continue;
01383 
01384              /* If we shall match only directories use the information
01385                provided by the dirent call if possible.  */
01386              if ((flags & GLOB_ONLYDIR) && !DIRENT_MIGHT_BE_DIR (d))
01387               continue;
01388 
01389              name = d->d_name;
01390 
01391              if (fnmatch (pattern, name, fnm_flags) == 0)
01392               {
01393                 /* If the file we found is a symlink we have to
01394                    make sure the target file exists.  */
01395                 if (!DIRENT_MIGHT_BE_SYMLINK (d)
01396                     || link_exists_p (dfd, directory, dirlen, name, pglob,
01397                                    flags))
01398                   {
01399                     if (cur == names->count)
01400                      {
01401                        struct globnames *newnames;
01402                        size_t count = names->count * 2;
01403                        size_t size = (sizeof (struct globnames)
01404                                     + ((count - INITIAL_COUNT)
01405                                        * sizeof (char *)));
01406                        allocasize += size;
01407                        if (__libc_use_alloca (allocasize))
01408                          newnames = names_alloca = __alloca (size);
01409                        else if ((newnames = malloc (size))
01410                                == NULL)
01411                          goto memory_error;
01412                        newnames->count = count;
01413                        newnames->next = names;
01414                        names = newnames;
01415                        cur = 0;
01416                      }
01417                     len = NAMLEN (d);
01418                     names->name[cur] = (char *) malloc (len + 1);
01419                     if (names->name[cur] == NULL)
01420                      goto memory_error;
01421                     *((char *) mempcpy (names->name[cur++], name, len))
01422                      = '\0';
01423                     ++nfound;
01424                   }
01425               }
01426            }
01427        }
01428     }
01429 
01430   if (nfound == 0 && (flags & GLOB_NOCHECK))
01431     {
01432       size_t len = strlen (pattern);
01433       nfound = 1;
01434       names->name[cur] = (char *) malloc (len + 1);
01435       if (names->name[cur] == NULL)
01436        goto memory_error;
01437       *((char *) mempcpy (names->name[cur++], pattern, len)) = '\0';
01438     }
01439 
01440   int result = GLOB_NOMATCH;
01441   if (nfound != 0)
01442     {
01443       result = 0;
01444 
01445       char **new_gl_pathv;
01446       new_gl_pathv
01447        = (char **) realloc (pglob->gl_pathv,
01448                           (pglob->gl_pathc + pglob->gl_offs + nfound + 1)
01449                           * sizeof (char *));
01450       if (new_gl_pathv == NULL)
01451        {
01452        memory_error:
01453          while (1)
01454            {
01455              struct globnames *old = names;
01456              for (size_t i = 0; i < cur; ++i)
01457               free (names->name[i]);
01458              names = names->next;
01459              /* NB: we will not leak memory here if we exit without
01460                freeing the current block assigned to OLD.  At least
01461                the very first block is always allocated on the stack
01462                and this is the block assigned to OLD here.  */
01463              if (names == NULL)
01464               {
01465                 assert (old == &init_names);
01466                 break;
01467               }
01468              cur = names->count;
01469              if (old == names_alloca)
01470               names_alloca = names;
01471              else
01472               free (old);
01473            }
01474          result = GLOB_NOSPACE;
01475        }
01476       else
01477        {
01478          while (1)
01479            {
01480              struct globnames *old = names;
01481              for (size_t i = 0; i < cur; ++i)
01482               new_gl_pathv[pglob->gl_offs + pglob->gl_pathc++]
01483                 = names->name[i];
01484              names = names->next;
01485              /* NB: we will not leak memory here if we exit without
01486                freeing the current block assigned to OLD.  At least
01487                the very first block is always allocated on the stack
01488                and this is the block assigned to OLD here.  */
01489              if (names == NULL)
01490               {
01491                 assert (old == &init_names);
01492                 break;
01493               }
01494              cur = names->count;
01495              if (old == names_alloca)
01496               names_alloca = names;
01497              else
01498               free (old);
01499            }
01500 
01501          pglob->gl_pathv = new_gl_pathv;
01502 
01503          pglob->gl_pathv[pglob->gl_offs + pglob->gl_pathc] = NULL;
01504 
01505          pglob->gl_flags = flags;
01506        }
01507     }
01508 
01509   if (stream != NULL)
01510     {
01511       save = errno;
01512       if (__builtin_expect (flags & GLOB_ALTDIRFUNC, 0))
01513        (*pglob->gl_closedir) (stream);
01514       else
01515        closedir (stream);
01516       __set_errno (save);
01517     }
01518 
01519   return result;
01520 }