(glob_in_dir): Add support for cases insensitive VMS.
[platform/upstream/glibc.git] / posix / glob.c
1 /* Copyright (C) 1991,92,93,94,95,96,97,98 Free Software Foundation, Inc.
2
3    This library is free software; you can redistribute it and/or
4    modify it under the terms of the GNU Library General Public License as
5    published by the Free Software Foundation; either version 2 of the
6    License, or (at your option) any later version.
7
8    This library is distributed in the hope that it will be useful,
9    but WITHOUT ANY WARRANTY; without even the implied warranty of
10    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
11    Library General Public License for more details.
12
13    You should have received a copy of the GNU Library General Public
14    License along with this library; see the file COPYING.LIB.  If not,
15    write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330,
16    Boston, MA 02111-1307, USA.  */
17
18 /* AIX requires this to be the first thing in the file.  */
19 #if defined _AIX && !defined __GNUC__
20  #pragma alloca
21 #endif
22
23 #ifdef  HAVE_CONFIG_H
24 # include <config.h>
25 #endif
26
27 /* Enable GNU extensions in glob.h.  */
28 #ifndef _GNU_SOURCE
29 # define _GNU_SOURCE    1
30 #endif
31
32 #include <errno.h>
33 #include <sys/types.h>
34 #include <sys/stat.h>
35
36 /* Outcomment the following line for production quality code.  */
37 /* #define NDEBUG 1 */
38 #include <assert.h>
39
40 #include <stdio.h>              /* Needed on stupid SunOS for assert.  */
41
42
43 /* Comment out all this code if we are using the GNU C Library, and are not
44    actually compiling the library itself.  This code is part of the GNU C
45    Library, but also included in many other GNU distributions.  Compiling
46    and linking in this code is a waste when using the GNU C library
47    (especially if it is a shared library).  Rather than having every GNU
48    program understand `configure --with-gnu-libc' and omit the object files,
49    it is simpler to just do this in the source for each such file.  */
50
51 #define GLOB_INTERFACE_VERSION 1
52 #if !defined _LIBC && defined __GNU_LIBRARY__ && __GNU_LIBRARY__ > 1
53 # include <gnu-versions.h>
54 # if _GNU_GLOB_INTERFACE_VERSION == GLOB_INTERFACE_VERSION
55 #  define ELIDE_CODE
56 # endif
57 #endif
58
59 #ifndef ELIDE_CODE
60
61 #if defined STDC_HEADERS || defined __GNU_LIBRARY__
62 # include <stddef.h>
63 #endif
64
65 #if defined HAVE_UNISTD_H || defined _LIBC
66 # include <unistd.h>
67 # ifndef POSIX
68 #  ifdef _POSIX_VERSION
69 #   define POSIX
70 #  endif
71 # endif
72 #endif
73
74 #if !defined _AMIGA && !defined VMS && !defined WINDOWS32
75 # include <pwd.h>
76 #endif
77
78 #if !defined __GNU_LIBRARY__ && !defined STDC_HEADERS
79 extern int errno;
80 #endif
81 #ifndef __set_errno
82 # define __set_errno(val) errno = (val)
83 #endif
84
85 #ifndef NULL
86 # define NULL   0
87 #endif
88
89
90 #if defined HAVE_DIRENT_H || defined __GNU_LIBRARY__
91 # include <dirent.h>
92 # define NAMLEN(dirent) strlen((dirent)->d_name)
93 #else
94 # define dirent direct
95 # define NAMLEN(dirent) (dirent)->d_namlen
96 # ifdef HAVE_SYS_NDIR_H
97 #  include <sys/ndir.h>
98 # endif
99 # ifdef HAVE_SYS_DIR_H
100 #  include <sys/dir.h>
101 # endif
102 # ifdef HAVE_NDIR_H
103 #  include <ndir.h>
104 # endif
105 # ifdef HAVE_VMSDIR_H
106 #  include "vmsdir.h"
107 # endif /* HAVE_VMSDIR_H */
108 #endif
109
110
111 /* In GNU systems, <dirent.h> defines this macro for us.  */
112 #ifdef _D_NAMLEN
113 # undef NAMLEN
114 # define NAMLEN(d) _D_NAMLEN(d)
115 #endif
116
117 /* When used in the GNU libc the symbol _DIRENT_HAVE_D_TYPE is available
118    if the `d_type' member for `struct dirent' is available.  */
119 #ifdef _DIRENT_HAVE_D_TYPE
120 # define HAVE_D_TYPE    1
121 #endif
122
123
124 #if (defined POSIX || defined WINDOWS32) && !defined __GNU_LIBRARY__
125 /* Posix does not require that the d_ino field be present, and some
126    systems do not provide it. */
127 # define REAL_DIR_ENTRY(dp) 1
128 #else
129 # define REAL_DIR_ENTRY(dp) (dp->d_ino != 0)
130 #endif /* POSIX */
131
132 #if defined STDC_HEADERS || defined __GNU_LIBRARY__
133 # include <stdlib.h>
134 # include <string.h>
135 # define        ANSI_STRING
136 #else   /* No standard headers.  */
137
138 extern char *getenv ();
139
140 # ifdef HAVE_STRING_H
141 #  include <string.h>
142 #  define ANSI_STRING
143 # else
144 #  include <strings.h>
145 # endif
146 # ifdef HAVE_MEMORY_H
147 #  include <memory.h>
148 # endif
149
150 extern char *malloc (), *realloc ();
151 extern void free ();
152
153 extern void qsort ();
154 extern void abort (), exit ();
155
156 #endif  /* Standard headers.  */
157
158 #ifndef ANSI_STRING
159
160 # ifndef bzero
161 extern void bzero ();
162 # endif
163 # ifndef bcopy
164 extern void bcopy ();
165 # endif
166
167 # define memcpy(d, s, n)        bcopy ((s), (d), (n))
168 # define strrchr        rindex
169 /* memset is only used for zero here, but let's be paranoid.  */
170 # define memset(s, better_be_zero, n) \
171   ((void) ((better_be_zero) == 0 ? (bzero((s), (n)), 0) : (abort(), 0)))
172 #endif  /* Not ANSI_STRING.  */
173
174 #if !defined HAVE_STRCOLL && !defined _LIBC
175 # define strcoll        strcmp
176 #endif
177
178 #if !defined HAVE_MEMPCPY && __GLIBC__ - 0 == 2 && __GLIBC_MINOR__ >= 1
179 # define HAVE_MEMPCPY   1
180 # define mempcpy(Dest, Src, Len) __mempcpy (Dest, Src, Len)
181 #endif
182
183
184 #ifndef __GNU_LIBRARY__
185 # ifdef __GNUC__
186 __inline
187 # endif
188 # ifndef __SASC
189 #  ifdef WINDOWS32
190 static void *
191 #  else
192 static char *
193 # endif
194 my_realloc (p, n)
195      char *p;
196      unsigned int n;
197 {
198   /* These casts are the for sake of the broken Ultrix compiler,
199      which warns of illegal pointer combinations otherwise.  */
200   if (p == NULL)
201     return (char *) malloc (n);
202   return (char *) realloc (p, n);
203 }
204 # define        realloc my_realloc
205 # endif /* __SASC */
206 #endif /* __GNU_LIBRARY__ */
207
208
209 #if !defined __alloca && !defined __GNU_LIBRARY__
210
211 # ifdef __GNUC__
212 #  undef alloca
213 #  define alloca(n)     __builtin_alloca (n)
214 # else  /* Not GCC.  */
215 #  ifdef HAVE_ALLOCA_H
216 #   include <alloca.h>
217 #  else /* Not HAVE_ALLOCA_H.  */
218 #   ifndef _AIX
219 #    ifdef WINDOWS32
220 #     include <malloc.h>
221 #    else
222 extern char *alloca ();
223 #    endif /* WINDOWS32 */
224 #   endif /* Not _AIX.  */
225 #  endif /* sparc or HAVE_ALLOCA_H.  */
226 # endif /* GCC.  */
227
228 # define __alloca       alloca
229
230 #endif
231
232 #ifndef __GNU_LIBRARY__
233 # define __stat stat
234 # ifdef STAT_MACROS_BROKEN
235 #  undef S_ISDIR
236 # endif
237 # ifndef S_ISDIR
238 #  define S_ISDIR(mode) (((mode) & S_IFMT) == S_IFDIR)
239 # endif
240 #endif
241
242 #if !(defined STDC_HEADERS || defined __GNU_LIBRARY__)
243 # undef size_t
244 # define size_t unsigned int
245 #endif
246
247 /* Some system header files erroneously define these.
248    We want our own definitions from <fnmatch.h> to take precedence.  */
249 #undef  FNM_PATHNAME
250 #undef  FNM_NOESCAPE
251 #undef  FNM_PERIOD
252 #include <fnmatch.h>
253
254 /* Some system header files erroneously define these.
255    We want our own definitions from <glob.h> to take precedence.  */
256 #undef  GLOB_ERR
257 #undef  GLOB_MARK
258 #undef  GLOB_NOSORT
259 #undef  GLOB_DOOFFS
260 #undef  GLOB_NOCHECK
261 #undef  GLOB_APPEND
262 #undef  GLOB_NOESCAPE
263 #undef  GLOB_PERIOD
264 #include <glob.h>
265 \f
266 static
267 #if __GNUC__ - 0 >= 2
268 inline
269 #endif
270 const char *next_brace_sub __P ((const char *begin));
271 static int glob_in_dir __P ((const char *pattern, const char *directory,
272                              int flags,
273                              int (*errfunc) __P ((const char *, int)),
274                              glob_t *pglob));
275 static int prefix_array __P ((const char *prefix, char **array, size_t n));
276 static int collated_compare __P ((const __ptr_t, const __ptr_t));
277
278
279 /* Find the end of the sub-pattern in a brace expression.  We define
280    this as an inline function if the compiler permits.  */
281 static
282 #if __GNUC__ - 0 >= 2
283 inline
284 #endif
285 const char *
286 next_brace_sub (begin)
287      const char *begin;
288 {
289   unsigned int depth = 0;
290   const char *cp = begin;
291
292   while (1)
293     {
294       if (depth == 0)
295         {
296           if (*cp != ',' && *cp != '}' && *cp != '\0')
297             {
298               if (*cp == '{')
299                 ++depth;
300               ++cp;
301               continue;
302             }
303         }
304       else
305         {
306           while (*cp != '\0' && (*cp != '}' || depth > 0))
307             {
308               if (*cp == '}')
309                 --depth;
310               ++cp;
311             }
312           if (*cp == '\0')
313             /* An incorrectly terminated brace expression.  */
314             return NULL;
315
316           continue;
317         }
318       break;
319     }
320
321   return cp;
322 }
323
324 /* Do glob searching for PATTERN, placing results in PGLOB.
325    The bits defined above may be set in FLAGS.
326    If a directory cannot be opened or read and ERRFUNC is not nil,
327    it is called with the pathname that caused the error, and the
328    `errno' value from the failing call; if it returns non-zero
329    `glob' returns GLOB_ABORTED; if it returns zero, the error is ignored.
330    If memory cannot be allocated for PGLOB, GLOB_NOSPACE is returned.
331    Otherwise, `glob' returns zero.  */
332 int
333 glob (pattern, flags, errfunc, pglob)
334      const char *pattern;
335      int flags;
336      int (*errfunc) __P ((const char *, int));
337      glob_t *pglob;
338 {
339   const char *filename;
340   char *dirname;
341   size_t dirlen;
342   int status;
343   int oldcount;
344
345   if (pattern == NULL || pglob == NULL || (flags & ~__GLOB_FLAGS) != 0)
346     {
347       __set_errno (EINVAL);
348       return -1;
349     }
350
351   if (flags & GLOB_BRACE)
352     {
353       const char *begin = strchr (pattern, '{');
354       if (begin != NULL)
355         {
356           /* Allocate working buffer large enough for our work.  Note that
357             we have at least an opening and closing brace.  */
358           int firstc;
359           char *alt_start;
360           const char *p;
361           const char *next;
362           const char *rest;
363           size_t rest_len;
364 #ifdef __GNUC__
365           char onealt[strlen (pattern) - 1];
366 #else
367           char *onealt = (char *) malloc (strlen (pattern) - 1);
368           if (onealt == NULL)
369             {
370               if (!(flags & GLOB_APPEND))
371                 globfree (pglob);
372               return GLOB_NOSPACE;
373             }
374 #endif
375
376           /* We know the prefix for all sub-patterns.  */
377 #ifdef HAVE_MEMPCPY
378           alt_start = mempcpy (onealt, pattern, begin - pattern);
379 #else
380           memcpy (onealt, pattern, begin - pattern);
381           alt_start = &onealt[begin - pattern];
382 #endif
383
384           /* Find the first sub-pattern and at the same time find the
385              rest after the closing brace.  */
386           next = next_brace_sub (begin + 1);
387           if (next == NULL)
388             {
389               /* It is an illegal expression.  */
390 #ifndef __GNUC__
391               free (onealt);
392 #endif
393               return glob (pattern, flags & ~GLOB_BRACE, errfunc, pglob);
394             }
395
396           /* Now find the end of the whole brace expression.  */
397           rest = next;
398           while (*rest != '}')
399             {
400               rest = next_brace_sub (rest + 1);
401               if (rest == NULL)
402                 {
403                   /* It is an illegal expression.  */
404 #ifndef __GNUC__
405                   free (onealt);
406 #endif
407                   return glob (pattern, flags & ~GLOB_BRACE, errfunc, pglob);
408                 }
409             }
410           /* Please note that we now can be sure the brace expression
411              is well-formed.  */
412           rest_len = strlen (++rest) + 1;
413
414           /* We have a brace expression.  BEGIN points to the opening {,
415              NEXT points past the terminator of the first element, and END
416              points past the final }.  We will accumulate result names from
417              recursive runs for each brace alternative in the buffer using
418              GLOB_APPEND.  */
419
420           if (!(flags & GLOB_APPEND))
421             {
422               /* This call is to set a new vector, so clear out the
423                  vector so we can append to it.  */
424               pglob->gl_pathc = 0;
425               pglob->gl_pathv = NULL;
426             }
427           firstc = pglob->gl_pathc;
428
429           p = begin + 1;
430           while (1)
431             {
432               int result;
433
434               /* Construct the new glob expression.  */
435 #ifdef HAVE_MEMPCPY
436               mempcpy (mempcpy (alt_start, p, next - p), rest, rest_len);
437 #else
438               memcpy (alt_start, p, next - p);
439               memcpy (&alt_start[next - p], rest, rest_len);
440 #endif
441
442               result = glob (onealt,
443                              ((flags & ~(GLOB_NOCHECK|GLOB_NOMAGIC))
444                               | GLOB_APPEND), errfunc, pglob);
445
446               /* If we got an error, return it.  */
447               if (result && result != GLOB_NOMATCH)
448                 {
449 #ifndef __GNUC__
450                   free (onealt);
451 #endif
452                   if (!(flags & GLOB_APPEND))
453                     globfree (pglob);
454                   return result;
455                 }
456
457               if (*next == '}')
458                 /* We saw the last entry.  */
459                 break;
460
461               p = next + 1;
462               next = next_brace_sub (p);
463               assert (next != NULL);
464             }
465
466 #ifndef __GNUC__
467           free (onealt);
468 #endif
469
470           if (pglob->gl_pathc != firstc)
471             /* We found some entries.  */
472             return 0;
473           else if (!(flags & (GLOB_NOCHECK|GLOB_NOMAGIC)))
474             return GLOB_NOMATCH;
475         }
476     }
477
478   /* Find the filename.  */
479   filename = strrchr (pattern, '/');
480   if (filename == NULL)
481     {
482       filename = pattern;
483 #ifdef _AMIGA
484       dirname = (char *) "";
485 #else
486       dirname = (char *) ".";
487 #endif
488       dirlen = 0;
489     }
490   else if (filename == pattern)
491     {
492       /* "/pattern".  */
493       dirname = (char *) "/";
494       dirlen = 1;
495       ++filename;
496     }
497   else
498     {
499       dirlen = filename - pattern;
500       dirname = (char *) __alloca (dirlen + 1);
501 #ifdef HAVE_MEMPCPY
502       *((char *) mempcpy (dirname, pattern, dirlen)) = '\0';
503 #else
504       memcpy (dirname, pattern, dirlen);
505       dirname[dirlen] = '\0';
506 #endif
507       ++filename;
508     }
509
510   if (filename[0] == '\0' && dirlen > 1)
511     /* "pattern/".  Expand "pattern", appending slashes.  */
512     {
513       int val = glob (dirname, flags | GLOB_MARK, errfunc, pglob);
514       if (val == 0)
515         pglob->gl_flags = (pglob->gl_flags & ~GLOB_MARK) | (flags & GLOB_MARK);
516       return val;
517     }
518
519   if (!(flags & GLOB_APPEND))
520     {
521       pglob->gl_pathc = 0;
522       pglob->gl_pathv = NULL;
523     }
524
525   oldcount = pglob->gl_pathc;
526
527 #ifndef VMS
528   if ((flags & GLOB_TILDE) && dirname[0] == '~')
529     {
530       if (dirname[1] == '\0' || dirname[1] == '/')
531         {
532           /* Look up home directory.  */
533           char *home_dir = getenv ("HOME");
534 # ifdef _AMIGA
535           if (home_dir == NULL || home_dir[0] == '\0')
536             home_dir = "SYS:";
537 # else
538 #  ifdef WINDOWS32
539           if (home_dir == NULL || home_dir[0] == '\0')
540             home_dir = "c:/users/default"; /* poor default */
541 #  else
542           if (home_dir == NULL || home_dir[0] == '\0')
543             {
544               int success;
545 #   if defined HAVE_GETLOGIN_R || defined _LIBC
546               extern int getlogin_r __P ((char *, size_t));
547               size_t buflen = sysconf (_SC_LOGIN_NAME_MAX) + 1;
548               char *name;
549
550               if (buflen == 0)
551                 /* `sysconf' does not support _SC_LOGIN_NAME_MAX.  Try
552                    a moderate value.  */
553                 buflen = 16;
554               name = (char *) __alloca (buflen);
555
556               success = getlogin_r (name, buflen) >= 0;
557 #   else
558               extern char *getlogin __P ((void));
559               char *name;
560
561               success = (name = getlogin ()) != NULL;
562 #   endif
563               if (success)
564                 {
565 #   if defined HAVE_GETPWNAM_R || defined _LIBC
566                   size_t pwbuflen = sysconf (_SC_GETPW_R_SIZE_MAX);
567                   char *pwtmpbuf;
568                   struct passwd pwbuf, *p;
569
570                   pwtmpbuf = (char *) __alloca (pwbuflen);
571
572                   success = (__getpwnam_r (name, &pwbuf, pwtmpbuf,
573                                            pwbuflen, &p) >= 0);
574 #   else
575                   struct passwd *p = getpwnam (name);
576                   success = p != NULL;
577 #   endif
578                   if (success)
579                     home_dir = p->pw_dir;
580                 }
581             }
582           if (home_dir == NULL || home_dir[0] == '\0')
583             home_dir = (char *) "~"; /* No luck.  */
584 #  endif /* WINDOWS32 */
585 # endif
586           /* Now construct the full directory.  */
587           if (dirname[1] == '\0')
588             dirname = home_dir;
589           else
590             {
591               char *newp;
592               size_t home_len = strlen (home_dir);
593               newp = (char *) __alloca (home_len + dirlen);
594 # ifdef HAVE_MEMPCPY
595               mempcpy (mempcpy (newp, home_dir, home_len),
596                        &dirname[1], dirlen);
597 # else
598               memcpy (newp, home_dir, home_len);
599               memcpy (&newp[home_len], &dirname[1], dirlen);
600 # endif
601               dirname = newp;
602             }
603         }
604 # if !defined _AMIGA && !defined WINDOWS32
605       else
606         {
607           char *end_name = strchr (dirname, '/');
608           char *user_name;
609           char *home_dir;
610
611           if (end_name == NULL)
612             user_name = dirname + 1;
613           else
614             {
615               user_name = (char *) __alloca (end_name - dirname);
616 # ifdef HAVE_MEMPCPY
617               *((char *) mempcpy (user_name, dirname + 1, end_name - dirname))
618                 = '\0';
619 # else
620               memcpy (user_name, dirname + 1, end_name - dirname);
621               user_name[end_name - dirname - 1] = '\0';
622 # endif
623             }
624
625           /* Look up specific user's home directory.  */
626           {
627 #  if defined HAVE_GETPWNAM_R || defined _LIBC
628             size_t buflen = sysconf (_SC_GETPW_R_SIZE_MAX);
629             char *pwtmpbuf = (char *) __alloca (buflen);
630             struct passwd pwbuf, *p;
631             if (__getpwnam_r (user_name, &pwbuf, pwtmpbuf, buflen, &p) >= 0)
632               home_dir = p->pw_dir;
633             else
634               home_dir = NULL;
635 #  else
636             struct passwd *p = getpwnam (user_name);
637             if (p != NULL)
638               home_dir = p->pw_dir;
639             else
640               home_dir = NULL;
641 #  endif
642           }
643           /* If we found a home directory use this.  */
644           if (home_dir != NULL)
645             {
646               char *newp;
647               size_t home_len = strlen (home_dir);
648               size_t rest_len = end_name == NULL ? 0 : strlen (end_name);
649               newp = (char *) __alloca (home_len + rest_len + 1);
650 #  ifdef HAVE_MEMPCPY
651               *((char *) mempcpy (mempcpy (newp, home_dir, home_len),
652                                   end_name, rest_len)) = '\0';
653 #  else
654               memcpy (newp, home_dir, home_len);
655               memcpy (&newp[home_len], end_name, rest_len);
656               newp[home_len + rest_len] = '\0';
657 #  endif
658               dirname = newp;
659             }
660         }
661 # endif /* Not Amiga && not WINDOWS32.  */
662     }
663 #endif  /* Not VMS.  */
664
665   if (__glob_pattern_p (dirname, !(flags & GLOB_NOESCAPE)))
666     {
667       /* The directory name contains metacharacters, so we
668          have to glob for the directory, and then glob for
669          the pattern in each directory found.  */
670       glob_t dirs;
671       register int i;
672
673       status = glob (dirname,
674                      ((flags & (GLOB_ERR | GLOB_NOCHECK | GLOB_NOESCAPE))
675                       | GLOB_NOSORT | GLOB_ONLYDIR),
676                      errfunc, &dirs);
677       if (status != 0)
678         return status;
679
680       /* We have successfully globbed the preceding directory name.
681          For each name we found, call glob_in_dir on it and FILENAME,
682          appending the results to PGLOB.  */
683       for (i = 0; i < dirs.gl_pathc; ++i)
684         {
685           int oldcount;
686
687 #ifdef  SHELL
688           {
689             /* Make globbing interruptible in the bash shell. */
690             extern int interrupt_state;
691
692             if (interrupt_state)
693               {
694                 globfree (&dirs);
695                 globfree (&files);
696                 return GLOB_ABORTED;
697               }
698           }
699 #endif /* SHELL.  */
700
701           oldcount = pglob->gl_pathc;
702           status = glob_in_dir (filename, dirs.gl_pathv[i],
703                                 ((flags | GLOB_APPEND)
704                                  & ~(GLOB_NOCHECK | GLOB_ERR)),
705                                 errfunc, pglob);
706           if (status == GLOB_NOMATCH)
707             /* No matches in this directory.  Try the next.  */
708             continue;
709
710           if (status != 0)
711             {
712               globfree (&dirs);
713               globfree (pglob);
714               return status;
715             }
716
717           /* Stick the directory on the front of each name.  */
718           if (prefix_array (dirs.gl_pathv[i],
719                             &pglob->gl_pathv[oldcount],
720                             pglob->gl_pathc - oldcount))
721             {
722               globfree (&dirs);
723               globfree (pglob);
724               return GLOB_NOSPACE;
725             }
726         }
727
728       flags |= GLOB_MAGCHAR;
729
730       if (pglob->gl_pathc == oldcount)
731         /* No matches.  */
732         if (flags & GLOB_NOCHECK)
733           {
734             size_t len = strlen (pattern) + 1;
735             char *patcopy = (char *) malloc (len);
736             if (patcopy == NULL)
737               return GLOB_NOSPACE;
738             memcpy (patcopy, pattern, len);
739
740             pglob->gl_pathv
741               = (char **) realloc (pglob->gl_pathv,
742                                    (pglob->gl_pathc +
743                                     ((flags & GLOB_DOOFFS) ?
744                                      pglob->gl_offs : 0) +
745                                     1 + 1) *
746                                    sizeof (char *));
747             if (pglob->gl_pathv == NULL)
748               {
749                 free (patcopy);
750                 return GLOB_NOSPACE;
751               }
752
753             if (flags & GLOB_DOOFFS)
754               while (pglob->gl_pathc < pglob->gl_offs)
755                 pglob->gl_pathv[pglob->gl_pathc++] = NULL;
756
757             pglob->gl_pathv[pglob->gl_pathc++] = patcopy;
758             pglob->gl_pathv[pglob->gl_pathc] = NULL;
759             pglob->gl_flags = flags;
760           }
761         else
762           return GLOB_NOMATCH;
763     }
764   else
765     {
766       status = glob_in_dir (filename, dirname, flags, errfunc, pglob);
767       if (status != 0)
768         return status;
769
770       if (dirlen > 0)
771         {
772           /* Stick the directory on the front of each name.  */
773           if (prefix_array (dirname,
774                             &pglob->gl_pathv[oldcount],
775                             pglob->gl_pathc - oldcount))
776             {
777               globfree (pglob);
778               return GLOB_NOSPACE;
779             }
780         }
781     }
782
783   if (flags & GLOB_MARK)
784     {
785       /* Append slashes to directory names.  */
786       int i;
787       struct stat st;
788       for (i = oldcount; i < pglob->gl_pathc; ++i)
789         if (((flags & GLOB_ALTDIRFUNC) ?
790              (*pglob->gl_stat) (pglob->gl_pathv[i], &st) :
791              __stat (pglob->gl_pathv[i], &st)) == 0 &&
792             S_ISDIR (st.st_mode))
793           {
794             size_t len = strlen (pglob->gl_pathv[i]) + 2;
795             char *new = realloc (pglob->gl_pathv[i], len);
796             if (new == NULL)
797               {
798                 globfree (pglob);
799                 return GLOB_NOSPACE;
800               }
801             strcpy (&new[len - 2], "/");
802             pglob->gl_pathv[i] = new;
803           }
804     }
805
806   if (!(flags & GLOB_NOSORT))
807     /* Sort the vector.  */
808     qsort ((__ptr_t) &pglob->gl_pathv[oldcount],
809            pglob->gl_pathc - oldcount,
810            sizeof (char *), collated_compare);
811
812   return 0;
813 }
814
815
816 /* Free storage allocated in PGLOB by a previous `glob' call.  */
817 void
818 globfree (pglob)
819      register glob_t *pglob;
820 {
821   if (pglob->gl_pathv != NULL)
822     {
823       register int i;
824       for (i = 0; i < pglob->gl_pathc; ++i)
825         if (pglob->gl_pathv[i] != NULL)
826           free ((__ptr_t) pglob->gl_pathv[i]);
827       free ((__ptr_t) pglob->gl_pathv);
828     }
829 }
830
831
832 /* Do a collated comparison of A and B.  */
833 static int
834 collated_compare (a, b)
835      const __ptr_t a;
836      const __ptr_t b;
837 {
838   const char *const s1 = *(const char *const * const) a;
839   const char *const s2 = *(const char *const * const) b;
840
841   if (s1 == s2)
842     return 0;
843   if (s1 == NULL)
844     return 1;
845   if (s2 == NULL)
846     return -1;
847   return strcoll (s1, s2);
848 }
849
850
851 /* Prepend DIRNAME to each of N members of ARRAY, replacing ARRAY's
852    elements in place.  Return nonzero if out of memory, zero if successful.
853    A slash is inserted between DIRNAME and each elt of ARRAY,
854    unless DIRNAME is just "/".  Each old element of ARRAY is freed.  */
855 static int
856 prefix_array (dirname, array, n)
857      const char *dirname;
858      char **array;
859      size_t n;
860 {
861   register size_t i;
862   size_t dirlen = strlen (dirname);
863
864   if (dirlen == 1 && dirname[0] == '/')
865     /* DIRNAME is just "/", so normal prepending would get us "//foo".
866        We want "/foo" instead, so don't prepend any chars from DIRNAME.  */
867     dirlen = 0;
868
869   for (i = 0; i < n; ++i)
870     {
871       size_t eltlen = strlen (array[i]) + 1;
872       char *new = (char *) malloc (dirlen + 1 + eltlen);
873       if (new == NULL)
874         {
875           while (i > 0)
876             free ((__ptr_t) array[--i]);
877           return 1;
878         }
879
880 #ifdef HAVE_MEMPCPY
881       {
882         char *endp = (char *) mempcpy (new, dirname, dirlen);
883         *endp++ = '/';
884         mempcpy (endp, array[i], eltlen);
885       }
886 #else
887       memcpy (new, dirname, dirlen);
888       new[dirlen] = '/';
889       memcpy (&new[dirlen + 1], array[i], eltlen);
890 #endif
891       free ((__ptr_t) array[i]);
892       array[i] = new;
893     }
894
895   return 0;
896 }
897
898
899 /* Return nonzero if PATTERN contains any metacharacters.
900    Metacharacters can be quoted with backslashes if QUOTE is nonzero.  */
901 int
902 __glob_pattern_p (pattern, quote)
903      const char *pattern;
904      int quote;
905 {
906   register const char *p;
907   int open = 0;
908
909   for (p = pattern; *p != '\0'; ++p)
910     switch (*p)
911       {
912       case '?':
913       case '*':
914         return 1;
915
916       case '\\':
917         if (quote && p[1] != '\0')
918           ++p;
919         break;
920
921       case '[':
922         open = 1;
923         break;
924
925       case ']':
926         if (open)
927           return 1;
928         break;
929       }
930
931   return 0;
932 }
933 #ifdef _LIBC
934 weak_alias (__glob_pattern_p, glob_pattern_p)
935 #endif
936
937
938 /* Like `glob', but PATTERN is a final pathname component,
939    and matches are searched for in DIRECTORY.
940    The GLOB_NOSORT bit in FLAGS is ignored.  No sorting is ever done.
941    The GLOB_APPEND flag is assumed to be set (always appends).  */
942 static int
943 glob_in_dir (pattern, directory, flags, errfunc, pglob)
944      const char *pattern;
945      const char *directory;
946      int flags;
947      int (*errfunc) __P ((const char *, int));
948      glob_t *pglob;
949 {
950   __ptr_t stream;
951
952   struct globlink
953     {
954       struct globlink *next;
955       char *name;
956     };
957   struct globlink *names = NULL;
958   size_t nfound;
959   int meta;
960   int save;
961
962   stream = ((flags & GLOB_ALTDIRFUNC) ?
963             (*pglob->gl_opendir) (directory) :
964             (__ptr_t) opendir (directory));
965   if (stream == NULL)
966     {
967       if ((errfunc != NULL && (*errfunc) (directory, errno)) ||
968           (flags & GLOB_ERR))
969         return GLOB_ABORTED;
970       nfound = 0;
971       meta = 0;
972     }
973   else if (pattern[0] == '\0')
974     {
975       /* This is a special case for matching directories like in
976          "*a/".  */
977       names = (struct globlink *) __alloca (sizeof (struct globlink));
978       names->name = (char *) malloc (1);
979       if (names->name == NULL)
980         goto memory_error;
981       names->name[0] = '\0';
982       names->next = NULL;
983       nfound = 1;
984       meta = 0;
985     }
986   else
987     {
988       nfound = 0;
989       meta = __glob_pattern_p (pattern, !(flags & GLOB_NOESCAPE));
990       if(meta)
991         flags |= GLOB_MAGCHAR;
992
993       while (1)
994         {
995           const char *name;
996           size_t len;
997           struct dirent *d = ((flags & GLOB_ALTDIRFUNC) ?
998                               (*pglob->gl_readdir) (stream) :
999                               readdir ((DIR *) stream));
1000           if (d == NULL)
1001             break;
1002           if (! REAL_DIR_ENTRY (d))
1003             continue;
1004
1005 #ifdef HAVE_D_TYPE
1006           /* If we shall match only directories use the information
1007              provided by the dirent call if possible.  */
1008           if ((flags & GLOB_ONLYDIR)
1009               && d->d_type != DT_UNKNOWN && d->d_type != DT_DIR)
1010             continue;
1011 #endif
1012
1013           name = d->d_name;
1014
1015           if ((!meta && strcmp (pattern, name) == 0)
1016               || fnmatch (pattern, name,
1017                           (!(flags & GLOB_PERIOD) ? FNM_PERIOD : 0) |
1018                           ((flags & GLOB_NOESCAPE) ? FNM_NOESCAPE : 0)
1019 #if defined _AMIGA || defined VMS
1020                           | FNM_CASEFOLD
1021 #endif
1022                          ) == 0)
1023             {
1024               struct globlink *new
1025                 = (struct globlink *) __alloca (sizeof (struct globlink));
1026               len = NAMLEN (d);
1027               new->name = (char *) malloc (len + 1);
1028               if (new->name == NULL)
1029                 goto memory_error;
1030 #ifdef HAVE_MEMPCPY
1031               *((char *) mempcpy ((__ptr_t) new->name, name, len)) = '\0';
1032 #else
1033               memcpy ((__ptr_t) new->name, name, len);
1034               new->name[len] = '\0';
1035 #endif
1036               new->next = names;
1037               names = new;
1038               ++nfound;
1039               if (!meta)
1040                 break;
1041             }
1042         }
1043     }
1044
1045   if (nfound == 0 && (flags & GLOB_NOMAGIC) && !meta)
1046     flags |= GLOB_NOCHECK;
1047
1048   if (nfound == 0 && (flags & GLOB_NOCHECK))
1049     {
1050       size_t len = strlen (pattern);
1051       nfound = 1;
1052       names = (struct globlink *) __alloca (sizeof (struct globlink));
1053       names->next = NULL;
1054       names->name = (char *) malloc (len + 1);
1055       if (names->name == NULL)
1056         goto memory_error;
1057 #ifdef HAVE_MEMPCPY
1058       *((char *) mempcpy (names->name, pattern, len)) = '\0';
1059 #else
1060       memcpy (names->name, pattern, len);
1061       names->name[len] = '\0';
1062 #endif
1063     }
1064
1065   if (nfound != 0)
1066     {
1067       pglob->gl_pathv
1068         = (char **) realloc (pglob->gl_pathv,
1069                              (pglob->gl_pathc +
1070                               ((flags & GLOB_DOOFFS) ? pglob->gl_offs : 0) +
1071                               nfound + 1) *
1072                              sizeof (char *));
1073       if (pglob->gl_pathv == NULL)
1074         goto memory_error;
1075
1076       if (flags & GLOB_DOOFFS)
1077         while (pglob->gl_pathc < pglob->gl_offs)
1078           pglob->gl_pathv[pglob->gl_pathc++] = NULL;
1079
1080       for (; names != NULL; names = names->next)
1081         pglob->gl_pathv[pglob->gl_pathc++] = names->name;
1082       pglob->gl_pathv[pglob->gl_pathc] = NULL;
1083
1084       pglob->gl_flags = flags;
1085     }
1086
1087   save = errno;
1088   if (flags & GLOB_ALTDIRFUNC)
1089     (*pglob->gl_closedir) (stream);
1090   else
1091     closedir ((DIR *) stream);
1092   __set_errno (save);
1093
1094   return nfound == 0 ? GLOB_NOMATCH : 0;
1095
1096  memory_error:
1097   {
1098     int save = errno;
1099     if (flags & GLOB_ALTDIRFUNC)
1100       (*pglob->gl_closedir) (stream);
1101     else
1102       closedir ((DIR *) stream);
1103     __set_errno (save);
1104   }
1105   while (names != NULL)
1106     {
1107       if (names->name != NULL)
1108         free ((__ptr_t) names->name);
1109       names = names->next;
1110     }
1111   return GLOB_NOSPACE;
1112 }
1113
1114 #endif  /* Not ELIDE_CODE.  */