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