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