Update.
[glibc.git] / sysdeps / generic / glob.c
blob7ab48995e266a266a0805b09072497389ecfd77e
1 /* Copyright (C) 1991,92,93,94,95,96,97,98 Free Software Foundation, Inc.
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.
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.
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. */
18 /* AIX requires this to be the first thing in the file. */
19 #if defined _AIX && !defined __GNUC__
20 #pragma alloca
21 #endif
23 #ifdef HAVE_CONFIG_H
24 # include <config.h>
25 #endif
27 /* Enable GNU extensions in glob.h. */
28 #ifndef _GNU_SOURCE
29 # define _GNU_SOURCE 1
30 #endif
32 #include <errno.h>
33 #include <sys/types.h>
34 #include <sys/stat.h>
36 /* Outcomment the following line for production quality code. */
37 /* #define NDEBUG 1 */
38 #include <assert.h>
40 #include <stdio.h> /* Needed on stupid SunOS for assert. */
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. */
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
59 #ifndef ELIDE_CODE
61 #if defined STDC_HEADERS || defined __GNU_LIBRARY__
62 # include <stddef.h>
63 #endif
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
74 #if !defined _AMIGA && !defined VMS && !defined WINDOWS32
75 # include <pwd.h>
76 #endif
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
85 #ifndef NULL
86 # define NULL 0
87 #endif
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
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
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
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 */
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. */
138 extern char *getenv ();
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
150 extern char *malloc (), *realloc ();
151 extern void free ();
153 extern void qsort ();
154 extern void abort (), exit ();
156 #endif /* Standard headers. */
158 #ifdef HAVE_GETLOGIN_R
159 extern int getlogin_r __P ((char *, size_t));
160 #else
161 extern char *getlogin __P ((void));
162 #endif
164 #ifndef ANSI_STRING
166 # ifndef bzero
167 extern void bzero ();
168 # endif
169 # ifndef bcopy
170 extern void bcopy ();
171 # endif
173 # define memcpy(d, s, n) bcopy ((s), (d), (n))
174 # define strrchr rindex
175 /* memset is only used for zero here, but let's be paranoid. */
176 # define memset(s, better_be_zero, n) \
177 ((void) ((better_be_zero) == 0 ? (bzero((s), (n)), 0) : (abort(), 0)))
178 #endif /* Not ANSI_STRING. */
180 #if !defined HAVE_STRCOLL && !defined _LIBC
181 # define strcoll strcmp
182 #endif
184 #if !defined HAVE_MEMPCPY && __GLIBC__ - 0 == 2 && __GLIBC_MINOR__ >= 1
185 # define HAVE_MEMPCPY 1
186 # define mempcpy(Dest, Src, Len) __mempcpy (Dest, Src, Len)
187 #endif
189 #ifndef __GNU_LIBRARY__
190 # ifdef __GNUC__
191 __inline
192 # endif
193 # ifndef __SASC
194 # ifdef WINDOWS32
195 static void *
196 # else
197 static char *
198 # endif
199 my_realloc (p, n)
200 char *p;
201 unsigned int n;
203 /* These casts are the for sake of the broken Ultrix compiler,
204 which warns of illegal pointer combinations otherwise. */
205 if (p == NULL)
206 return (char *) malloc (n);
207 return (char *) realloc (p, n);
209 # define realloc my_realloc
210 # endif /* __SASC */
211 #endif /* __GNU_LIBRARY__ */
214 #if !defined __alloca && !defined __GNU_LIBRARY__
216 # ifdef __GNUC__
217 # undef alloca
218 # define alloca(n) __builtin_alloca (n)
219 # else /* Not GCC. */
220 # ifdef HAVE_ALLOCA_H
221 # include <alloca.h>
222 # else /* Not HAVE_ALLOCA_H. */
223 # ifndef _AIX
224 # ifdef WINDOWS32
225 # include <malloc.h>
226 # else
227 extern char *alloca ();
228 # endif /* WINDOWS32 */
229 # endif /* Not _AIX. */
230 # endif /* sparc or HAVE_ALLOCA_H. */
231 # endif /* GCC. */
233 # define __alloca alloca
235 #endif
237 #ifndef __GNU_LIBRARY__
238 # define __stat stat
239 # ifdef STAT_MACROS_BROKEN
240 # undef S_ISDIR
241 # endif
242 # ifndef S_ISDIR
243 # define S_ISDIR(mode) (((mode) & S_IFMT) == S_IFDIR)
244 # endif
245 #endif
247 #ifdef _LIBC
248 # define strdup(str) __strdup (str)
249 # define sysconf(id) __sysconf (id)
250 # define closedir(dir) __closedir (dir)
251 # define opendir(name) __opendir (name)
252 # define readdir(str) __readdir (str)
253 # define getpwnam_r(name, bufp, buf, len, res) \
254 __getpwnam_r (name, bufp, buf, len, res)
255 #endif
257 #if !(defined STDC_HEADERS || defined __GNU_LIBRARY__)
258 # undef size_t
259 # define size_t unsigned int
260 #endif
262 /* Some system header files erroneously define these.
263 We want our own definitions from <fnmatch.h> to take precedence. */
264 #ifndef __GNU_LIBRARY__
265 # undef FNM_PATHNAME
266 # undef FNM_NOESCAPE
267 # undef FNM_PERIOD
268 #endif
269 #include <fnmatch.h>
271 /* Some system header files erroneously define these.
272 We want our own definitions from <glob.h> to take precedence. */
273 #ifndef __GNU_LIBRARY__
274 # undef GLOB_ERR
275 # undef GLOB_MARK
276 # undef GLOB_NOSORT
277 # undef GLOB_DOOFFS
278 # undef GLOB_NOCHECK
279 # undef GLOB_APPEND
280 # undef GLOB_NOESCAPE
281 # undef GLOB_PERIOD
282 #endif
283 #include <glob.h>
285 static
286 #if __GNUC__ - 0 >= 2
287 inline
288 #endif
289 const char *next_brace_sub __P ((const char *begin));
290 static int glob_in_dir __P ((const char *pattern, const char *directory,
291 int flags,
292 int (*errfunc) __P ((const char *, int)),
293 glob_t *pglob));
294 static int prefix_array __P ((const char *prefix, char **array, size_t n));
295 static int collated_compare __P ((const __ptr_t, const __ptr_t));
298 /* Find the end of the sub-pattern in a brace expression. We define
299 this as an inline function if the compiler permits. */
300 static
301 #if __GNUC__ - 0 >= 2
302 inline
303 #endif
304 const char *
305 next_brace_sub (begin)
306 const char *begin;
308 unsigned int depth = 0;
309 const char *cp = begin;
311 while (1)
313 if (depth == 0)
315 if (*cp != ',' && *cp != '}' && *cp != '\0')
317 if (*cp == '{')
318 ++depth;
319 ++cp;
320 continue;
323 else
325 while (*cp != '\0' && (*cp != '}' || depth > 0))
327 if (*cp == '}')
328 --depth;
329 ++cp;
331 if (*cp == '\0')
332 /* An incorrectly terminated brace expression. */
333 return NULL;
335 continue;
337 break;
340 return cp;
343 /* Do glob searching for PATTERN, placing results in PGLOB.
344 The bits defined above may be set in FLAGS.
345 If a directory cannot be opened or read and ERRFUNC is not nil,
346 it is called with the pathname that caused the error, and the
347 `errno' value from the failing call; if it returns non-zero
348 `glob' returns GLOB_ABORTED; if it returns zero, the error is ignored.
349 If memory cannot be allocated for PGLOB, GLOB_NOSPACE is returned.
350 Otherwise, `glob' returns zero. */
352 glob (pattern, flags, errfunc, pglob)
353 const char *pattern;
354 int flags;
355 int (*errfunc) __P ((const char *, int));
356 glob_t *pglob;
358 const char *filename;
359 const char *dirname;
360 size_t dirlen;
361 int status;
362 int oldcount;
364 if (pattern == NULL || pglob == NULL || (flags & ~__GLOB_FLAGS) != 0)
366 __set_errno (EINVAL);
367 return -1;
370 if (flags & GLOB_BRACE)
372 const char *begin = strchr (pattern, '{');
373 if (begin != NULL)
375 /* Allocate working buffer large enough for our work. Note that
376 we have at least an opening and closing brace. */
377 int firstc;
378 char *alt_start;
379 const char *p;
380 const char *next;
381 const char *rest;
382 size_t rest_len;
383 #ifdef __GNUC__
384 char onealt[strlen (pattern) - 1];
385 #else
386 char *onealt = (char *) malloc (strlen (pattern) - 1);
387 if (onealt == NULL)
389 if (!(flags & GLOB_APPEND))
390 globfree (pglob);
391 return GLOB_NOSPACE;
393 #endif
395 /* We know the prefix for all sub-patterns. */
396 #ifdef HAVE_MEMPCPY
397 alt_start = mempcpy (onealt, pattern, begin - pattern);
398 #else
399 memcpy (onealt, pattern, begin - pattern);
400 alt_start = &onealt[begin - pattern];
401 #endif
403 /* Find the first sub-pattern and at the same time find the
404 rest after the closing brace. */
405 next = next_brace_sub (begin + 1);
406 if (next == NULL)
408 /* It is an illegal expression. */
409 #ifndef __GNUC__
410 free (onealt);
411 #endif
412 return glob (pattern, flags & ~GLOB_BRACE, errfunc, pglob);
415 /* Now find the end of the whole brace expression. */
416 rest = next;
417 while (*rest != '}')
419 rest = next_brace_sub (rest + 1);
420 if (rest == NULL)
422 /* It is an illegal expression. */
423 #ifndef __GNUC__
424 free (onealt);
425 #endif
426 return glob (pattern, flags & ~GLOB_BRACE, errfunc, pglob);
429 /* Please note that we now can be sure the brace expression
430 is well-formed. */
431 rest_len = strlen (++rest) + 1;
433 /* We have a brace expression. BEGIN points to the opening {,
434 NEXT points past the terminator of the first element, and END
435 points past the final }. We will accumulate result names from
436 recursive runs for each brace alternative in the buffer using
437 GLOB_APPEND. */
439 if (!(flags & GLOB_APPEND))
441 /* This call is to set a new vector, so clear out the
442 vector so we can append to it. */
443 pglob->gl_pathc = 0;
444 pglob->gl_pathv = NULL;
446 firstc = pglob->gl_pathc;
448 p = begin + 1;
449 while (1)
451 int result;
453 /* Construct the new glob expression. */
454 #ifdef HAVE_MEMPCPY
455 mempcpy (mempcpy (alt_start, p, next - p), rest, rest_len);
456 #else
457 memcpy (alt_start, p, next - p);
458 memcpy (&alt_start[next - p], rest, rest_len);
459 #endif
461 result = glob (onealt,
462 ((flags & ~(GLOB_NOCHECK|GLOB_NOMAGIC))
463 | GLOB_APPEND), errfunc, pglob);
465 /* If we got an error, return it. */
466 if (result && result != GLOB_NOMATCH)
468 #ifndef __GNUC__
469 free (onealt);
470 #endif
471 if (!(flags & GLOB_APPEND))
472 globfree (pglob);
473 return result;
476 if (*next == '}')
477 /* We saw the last entry. */
478 break;
480 p = next + 1;
481 next = next_brace_sub (p);
482 assert (next != NULL);
485 #ifndef __GNUC__
486 free (onealt);
487 #endif
489 if (pglob->gl_pathc != firstc)
490 /* We found some entries. */
491 return 0;
492 else if (!(flags & (GLOB_NOCHECK|GLOB_NOMAGIC)))
493 return GLOB_NOMATCH;
497 /* Find the filename. */
498 filename = strrchr (pattern, '/');
499 #if defined __MSDOS__ || defined WINDOWS32
500 /* The case of "d:pattern". Since `:' is not allowed in
501 file names, we can safely assume that wherever it
502 happens in pattern, it signals the filename part. This
503 is so we could some day support patterns like "[a-z]:foo". */
504 if (filename == NULL)
505 filename = strchr (pattern, ':');
506 #endif /* __MSDOS__ || WINDOWS32 */
507 if (filename == NULL)
509 /* This can mean two things: a simple name or "~name". The later
510 case is nothing but a notation for a directory. */
511 if ((flags & (GLOB_TILDE|GLOB_TILDE_CHECK)) && pattern[0] == '~')
513 dirname = (char *) pattern;
514 dirlen = strlen (pattern);
516 /* Set FILENAME to NULL as a special flag. This is ugly but
517 other solutions would require much more code. We test for
518 this special case below. */
519 filename = NULL;
521 else
523 filename = pattern;
524 #ifdef _AMIGA
525 dirname = "";
526 #else
527 dirname = ".";
528 #endif
529 dirlen = 0;
532 else if (filename == pattern)
534 /* "/pattern". */
535 dirname = "/";
536 dirlen = 1;
537 ++filename;
539 else
541 char *newp;
542 dirlen = filename - pattern;
543 #if defined __MSDOS__ || defined WINDOWS32
544 if (*filename == ':'
545 || (filename > pattern + 1 && filename[-1] == ':'))
547 char *drive_spec;
549 ++dirlen;
550 drive_spec = (char *) __alloca (dirlen + 1);
551 #ifdef HAVE_MEMPCPY
552 *((char *) mempcpy (drive_spec, pattern, dirlen)) = '\0';
553 #else
554 memcpy (drive_spec, pattern, dirlen);
555 drive_spec[dirlen] = '\0';
556 #endif
557 /* For now, disallow wildcards in the drive spec, to
558 prevent infinite recursion in glob. */
559 if (__glob_pattern_p (drive_spec, !(flags & GLOB_NOESCAPE)))
560 return GLOB_NOMATCH;
561 /* If this is "d:pattern", we need to copy `:' to DIRNAME
562 as well. If it's "d:/pattern", don't remove the slash
563 from "d:/", since "d:" and "d:/" are not the same.*/
565 #endif
566 newp = (char *) __alloca (dirlen + 1);
567 #ifdef HAVE_MEMPCPY
568 *((char *) mempcpy (newp, pattern, dirlen)) = '\0';
569 #else
570 memcpy (newp, pattern, dirlen);
571 newp[dirlen] = '\0';
572 #endif
573 dirname = newp;
574 ++filename;
576 if (filename[0] == '\0'
577 #if defined __MSDOS__ || defined WINDOWS32
578 && dirname[dirlen - 1] != ':'
579 && (dirlen < 3 || dirname[dirlen - 2] != ':'
580 || dirname[dirlen - 1] != '/')
581 #endif
582 && dirlen > 1)
583 /* "pattern/". Expand "pattern", appending slashes. */
585 int val = glob (dirname, flags | GLOB_MARK, errfunc, pglob);
586 if (val == 0)
587 pglob->gl_flags = ((pglob->gl_flags & ~GLOB_MARK)
588 | (flags & GLOB_MARK));
589 return val;
593 if (!(flags & GLOB_APPEND))
595 pglob->gl_pathc = 0;
596 pglob->gl_pathv = NULL;
599 oldcount = pglob->gl_pathc;
601 #ifndef VMS
602 if ((flags & (GLOB_TILDE|GLOB_TILDE_CHECK)) && dirname[0] == '~')
604 if (dirname[1] == '\0' || dirname[1] == '/')
606 /* Look up home directory. */
607 const char *home_dir = getenv ("HOME");
608 # ifdef _AMIGA
609 if (home_dir == NULL || home_dir[0] == '\0')
610 home_dir = "SYS:";
611 # else
612 # ifdef WINDOWS32
613 if (home_dir == NULL || home_dir[0] == '\0')
614 home_dir = "c:/users/default"; /* poor default */
615 # else
616 if (home_dir == NULL || home_dir[0] == '\0')
618 int success;
619 char *name;
620 # if defined HAVE_GETLOGIN_R || defined _LIBC
621 size_t buflen = sysconf (_SC_LOGIN_NAME_MAX) + 1;
623 if (buflen == 0)
624 /* `sysconf' does not support _SC_LOGIN_NAME_MAX. Try
625 a moderate value. */
626 buflen = 20;
627 name = (char *) __alloca (buflen);
629 success = getlogin_r (name, buflen) >= 0;
630 # else
631 success = (name = getlogin ()) != NULL;
632 # endif
633 if (success)
635 struct passwd *p;
636 # if defined HAVE_GETPWNAM_R || defined _LIBC
637 size_t pwbuflen = sysconf (_SC_GETPW_R_SIZE_MAX);
638 char *pwtmpbuf;
639 struct passwd pwbuf;
641 if (pwbuflen == -1)
642 /* `sysconf' does not support _SC_GETPW_R_SIZE_MAX.
643 Try a moderate value. */
644 pwbuflen = 1024;
645 pwtmpbuf = (char *) __alloca (pwbuflen);
647 success = (getpwnam_r (name, &pwbuf, pwtmpbuf, pwbuflen, &p)
648 >= 0);
649 # else
650 p = getpwnam (name);
651 success = p != NULL;
652 # endif
653 if (success)
654 home_dir = p->pw_dir;
657 if (home_dir == NULL || home_dir[0] == '\0')
658 if (flags & GLOB_TILDE_CHECK)
659 return GLOB_NOMATCH;
660 else
661 home_dir = "~"; /* No luck. */
662 # endif /* WINDOWS32 */
663 # endif
664 /* Now construct the full directory. */
665 if (dirname[1] == '\0')
666 dirname = home_dir;
667 else
669 char *newp;
670 size_t home_len = strlen (home_dir);
671 newp = (char *) __alloca (home_len + dirlen);
672 # ifdef HAVE_MEMPCPY
673 mempcpy (mempcpy (newp, home_dir, home_len),
674 &dirname[1], dirlen);
675 # else
676 memcpy (newp, home_dir, home_len);
677 memcpy (&newp[home_len], &dirname[1], dirlen);
678 # endif
679 dirname = newp;
682 # if !defined _AMIGA && !defined WINDOWS32
683 else
685 char *end_name = strchr (dirname, '/');
686 const char *user_name;
687 const char *home_dir;
689 if (end_name == NULL)
690 user_name = dirname + 1;
691 else
693 char *newp;
694 newp = (char *) __alloca (end_name - dirname);
695 # ifdef HAVE_MEMPCPY
696 *((char *) mempcpy (newp, dirname + 1, end_name - dirname))
697 = '\0';
698 # else
699 memcpy (newp, dirname + 1, end_name - dirname);
700 newp[end_name - dirname - 1] = '\0';
701 # endif
702 user_name = newp;
705 /* Look up specific user's home directory. */
707 struct passwd *p;
708 # if defined HAVE_GETPWNAM_R || defined _LIBC
709 size_t buflen = sysconf (_SC_GETPW_R_SIZE_MAX);
710 char *pwtmpbuf;
711 struct passwd pwbuf;
713 if (buflen == -1)
714 /* `sysconf' does not support _SC_GETPW_R_SIZE_MAX. Try a
715 moderate value. */
716 buflen = 1024;
717 pwtmpbuf = (char *) __alloca (buflen);
719 if (getpwnam_r (user_name, &pwbuf, pwtmpbuf, buflen, &p) >= 0)
720 home_dir = p->pw_dir;
721 else
722 home_dir = NULL;
723 # else
724 p = getpwnam (user_name);
725 if (p != NULL)
726 home_dir = p->pw_dir;
727 else
728 home_dir = NULL;
729 # endif
731 /* If we found a home directory use this. */
732 if (home_dir != NULL)
734 char *newp;
735 size_t home_len = strlen (home_dir);
736 size_t rest_len = end_name == NULL ? 0 : strlen (end_name);
737 newp = (char *) __alloca (home_len + rest_len + 1);
738 # ifdef HAVE_MEMPCPY
739 *((char *) mempcpy (mempcpy (newp, home_dir, home_len),
740 end_name, rest_len)) = '\0';
741 # else
742 memcpy (newp, home_dir, home_len);
743 memcpy (&newp[home_len], end_name, rest_len);
744 newp[home_len + rest_len] = '\0';
745 # endif
746 dirname = newp;
748 else
749 if (flags & GLOB_TILDE_CHECK)
750 /* We have to regard it as an error if we cannot find the
751 home directory. */
752 return GLOB_NOMATCH;
754 # endif /* Not Amiga && not WINDOWS32. */
756 #endif /* Not VMS. */
758 /* Now test whether we looked for "~" or "~NAME". In this case we
759 can give the answer now. */
760 if (filename == NULL)
762 struct stat st;
764 /* Return the directory if we don't check for error or if it exists. */
765 if ((flags & GLOB_NOCHECK)
766 || (((flags & GLOB_ALTDIRFUNC)
767 ? (*pglob->gl_stat) (dirname, &st)
768 : __stat (dirname, &st)) == 0
769 && S_ISDIR (st.st_mode)))
771 pglob->gl_pathv
772 = (char **) realloc (pglob->gl_pathv,
773 (pglob->gl_pathc +
774 ((flags & GLOB_DOOFFS) ?
775 pglob->gl_offs : 0) +
776 1 + 1) *
777 sizeof (char *));
778 if (pglob->gl_pathv == NULL)
779 return GLOB_NOSPACE;
781 if (flags & GLOB_DOOFFS)
782 while (pglob->gl_pathc < pglob->gl_offs)
783 pglob->gl_pathv[pglob->gl_pathc++] = NULL;
785 #if defined HAVE_STRDUP || defined _LIBC
786 pglob->gl_pathv[pglob->gl_pathc] = strdup (dirname);
787 #else
789 size_t len = strlen (dirname) + 1;
790 char *dircopy = malloc (len);
791 if (dircopy != NULL)
792 pglob->gl_pathv[pglob->gl_pathc] = memcpy (dircopy, dirname,
793 len);
795 #endif
796 if (pglob->gl_pathv[pglob->gl_pathc] == NULL)
798 free (pglob->gl_pathv);
799 return GLOB_NOSPACE;
801 pglob->gl_pathv[++pglob->gl_pathc] = NULL;
802 pglob->gl_flags = flags;
804 return 0;
807 /* Not found. */
808 return GLOB_NOMATCH;
811 if (__glob_pattern_p (dirname, !(flags & GLOB_NOESCAPE)))
813 /* The directory name contains metacharacters, so we
814 have to glob for the directory, and then glob for
815 the pattern in each directory found. */
816 glob_t dirs;
817 register int i;
819 status = glob (dirname,
820 ((flags & (GLOB_ERR | GLOB_NOCHECK | GLOB_NOESCAPE))
821 | GLOB_NOSORT | GLOB_ONLYDIR),
822 errfunc, &dirs);
823 if (status != 0)
824 return status;
826 /* We have successfully globbed the preceding directory name.
827 For each name we found, call glob_in_dir on it and FILENAME,
828 appending the results to PGLOB. */
829 for (i = 0; i < dirs.gl_pathc; ++i)
831 int old_pathc;
833 #ifdef SHELL
835 /* Make globbing interruptible in the bash shell. */
836 extern int interrupt_state;
838 if (interrupt_state)
840 globfree (&dirs);
841 globfree (&files);
842 return GLOB_ABORTED;
845 #endif /* SHELL. */
847 old_pathc = pglob->gl_pathc;
848 status = glob_in_dir (filename, dirs.gl_pathv[i],
849 ((flags | GLOB_APPEND)
850 & ~(GLOB_NOCHECK | GLOB_ERR)),
851 errfunc, pglob);
852 if (status == GLOB_NOMATCH)
853 /* No matches in this directory. Try the next. */
854 continue;
856 if (status != 0)
858 globfree (&dirs);
859 globfree (pglob);
860 return status;
863 /* Stick the directory on the front of each name. */
864 if (prefix_array (dirs.gl_pathv[i],
865 &pglob->gl_pathv[old_pathc],
866 pglob->gl_pathc - old_pathc))
868 globfree (&dirs);
869 globfree (pglob);
870 return GLOB_NOSPACE;
874 flags |= GLOB_MAGCHAR;
876 /* We have ignored the GLOB_NOCHECK flag in the `glob_in_dir' calls.
877 But if we have not found any matching entry and thie GLOB_NOCHECK
878 flag was set we must return the list consisting of the disrectory
879 names followed by the filename. */
880 if (pglob->gl_pathc == oldcount)
881 /* No matches. */
882 if (flags & GLOB_NOCHECK)
884 size_t filename_len = strlen (filename) + 1;
885 char **new_pathv;
886 struct stat st;
888 /* This is an pessimistic guess about the size. */
889 pglob->gl_pathv
890 = (char **) realloc (pglob->gl_pathv,
891 (pglob->gl_pathc +
892 ((flags & GLOB_DOOFFS) ?
893 pglob->gl_offs : 0) +
894 dirs.gl_pathc + 1) *
895 sizeof (char *));
896 if (pglob->gl_pathv == NULL)
898 globfree (&dirs);
899 return GLOB_NOSPACE;
902 if (flags & GLOB_DOOFFS)
903 while (pglob->gl_pathc < pglob->gl_offs)
904 pglob->gl_pathv[pglob->gl_pathc++] = NULL;
906 for (i = 0; i < dirs.gl_pathc; ++i)
908 const char *dir = dirs.gl_pathv[i];
909 size_t dir_len = strlen (dir);
911 /* First check whether this really is a directory. */
912 if (((flags & GLOB_ALTDIRFUNC)
913 ? (*pglob->gl_stat) (dir, &st) : __stat (dir, &st)) != 0
914 || !S_ISDIR (st.st_mode))
915 /* No directory, ignore this entry. */
916 continue;
918 pglob->gl_pathv[pglob->gl_pathc] = malloc (dir_len + 1
919 + filename_len);
920 if (pglob->gl_pathv[pglob->gl_pathc] == NULL)
922 globfree (&dirs);
923 globfree (pglob);
924 return GLOB_NOSPACE;
927 #ifdef HAVE_MEMPCPY
928 mempcpy (mempcpy (mempcpy (pglob->gl_pathv[pglob->gl_pathc],
929 dir, dir_len),
930 "/", 1),
931 filename, filename_len);
932 #else
933 memcpy (pglob->gl_pathv[pglob->gl_pathc], dir, dir_len);
934 pglob->gl_pathv[pglob->gl_pathc][dir_len] = '/';
935 memcpy (&pglob->gl_pathv[pglob->gl_pathc][dir_len + 1],
936 filename, filename_len);
937 #endif
938 ++pglob->gl_pathc;
941 pglob->gl_pathv[pglob->gl_pathc] = NULL;
942 pglob->gl_flags = flags;
944 /* Now we know how large the gl_pathv vector must be. */
945 new_pathv = (char **) realloc (pglob->gl_pathv,
946 ((pglob->gl_pathc + 1)
947 * sizeof (char *)));
948 if (new_pathv != NULL)
949 pglob->gl_pathv = new_pathv;
951 else
952 return GLOB_NOMATCH;
954 globfree (&dirs);
956 else
958 status = glob_in_dir (filename, dirname, flags, errfunc, pglob);
959 if (status != 0)
960 return status;
962 if (dirlen > 0)
964 /* Stick the directory on the front of each name. */
965 int ignore = oldcount;
967 if ((flags & GLOB_DOOFFS) && ignore < pglob->gl_offs)
968 ignore = pglob->gl_offs;
970 if (prefix_array (dirname,
971 &pglob->gl_pathv[ignore],
972 pglob->gl_pathc - ignore))
974 globfree (pglob);
975 return GLOB_NOSPACE;
980 if (flags & GLOB_MARK)
982 /* Append slashes to directory names. */
983 int i;
984 struct stat st;
985 for (i = oldcount; i < pglob->gl_pathc; ++i)
986 if (((flags & GLOB_ALTDIRFUNC)
987 ? (*pglob->gl_stat) (pglob->gl_pathv[i], &st)
988 : __stat (pglob->gl_pathv[i], &st)) == 0
989 && S_ISDIR (st.st_mode))
991 size_t len = strlen (pglob->gl_pathv[i]) + 2;
992 char *new = realloc (pglob->gl_pathv[i], len);
993 if (new == NULL)
995 globfree (pglob);
996 return GLOB_NOSPACE;
998 strcpy (&new[len - 2], "/");
999 pglob->gl_pathv[i] = new;
1003 if (!(flags & GLOB_NOSORT))
1005 /* Sort the vector. */
1006 int non_sort = oldcount;
1008 if ((flags & GLOB_DOOFFS) && pglob->gl_offs > oldcount)
1009 non_sort = pglob->gl_offs;
1011 qsort ((__ptr_t) &pglob->gl_pathv[non_sort],
1012 pglob->gl_pathc - non_sort,
1013 sizeof (char *), collated_compare);
1016 return 0;
1020 /* Free storage allocated in PGLOB by a previous `glob' call. */
1021 void
1022 globfree (pglob)
1023 register glob_t *pglob;
1025 if (pglob->gl_pathv != NULL)
1027 register int i;
1028 for (i = 0; i < pglob->gl_pathc; ++i)
1029 if (pglob->gl_pathv[i] != NULL)
1030 free ((__ptr_t) pglob->gl_pathv[i]);
1031 free ((__ptr_t) pglob->gl_pathv);
1036 /* Do a collated comparison of A and B. */
1037 static int
1038 collated_compare (a, b)
1039 const __ptr_t a;
1040 const __ptr_t b;
1042 const char *const s1 = *(const char *const * const) a;
1043 const char *const s2 = *(const char *const * const) b;
1045 if (s1 == s2)
1046 return 0;
1047 if (s1 == NULL)
1048 return 1;
1049 if (s2 == NULL)
1050 return -1;
1051 return strcoll (s1, s2);
1055 /* Prepend DIRNAME to each of N members of ARRAY, replacing ARRAY's
1056 elements in place. Return nonzero if out of memory, zero if successful.
1057 A slash is inserted between DIRNAME and each elt of ARRAY,
1058 unless DIRNAME is just "/". Each old element of ARRAY is freed. */
1059 static int
1060 prefix_array (dirname, array, n)
1061 const char *dirname;
1062 char **array;
1063 size_t n;
1065 register size_t i;
1066 size_t dirlen = strlen (dirname);
1067 #if defined __MSDOS__ || defined WINDOWS32
1068 int sep_char = '/';
1069 # define DIRSEP_CHAR sep_char
1070 #else
1071 # define DIRSEP_CHAR '/'
1072 #endif
1074 if (dirlen == 1 && dirname[0] == '/')
1075 /* DIRNAME is just "/", so normal prepending would get us "//foo".
1076 We want "/foo" instead, so don't prepend any chars from DIRNAME. */
1077 dirlen = 0;
1078 #if defined __MSDOS__ || defined WINDOWS32
1079 else if (dirlen > 1)
1081 if (dirname[dirlen - 1] == '/')
1082 /* DIRNAME is "d:/". Don't prepend the slash from DIRNAME. */
1083 --dirlen;
1084 else if (dirname[dirlen - 1] == ':')
1086 /* DIRNAME is "d:". Use `:' instead of `/'. */
1087 --dirlen;
1088 sep_char = ':';
1091 #endif
1093 for (i = 0; i < n; ++i)
1095 size_t eltlen = strlen (array[i]) + 1;
1096 char *new = (char *) malloc (dirlen + 1 + eltlen);
1097 if (new == NULL)
1099 while (i > 0)
1100 free ((__ptr_t) array[--i]);
1101 return 1;
1104 #ifdef HAVE_MEMPCPY
1106 char *endp = (char *) mempcpy (new, dirname, dirlen);
1107 *endp++ = DIRSEP_CHAR;
1108 mempcpy (endp, array[i], eltlen);
1110 #else
1111 memcpy (new, dirname, dirlen);
1112 new[dirlen] = DIRSEP_CHAR;
1113 memcpy (&new[dirlen + 1], array[i], eltlen);
1114 #endif
1115 free ((__ptr_t) array[i]);
1116 array[i] = new;
1119 return 0;
1123 /* Return nonzero if PATTERN contains any metacharacters.
1124 Metacharacters can be quoted with backslashes if QUOTE is nonzero. */
1126 __glob_pattern_p (pattern, quote)
1127 const char *pattern;
1128 int quote;
1130 register const char *p;
1131 int open = 0;
1133 for (p = pattern; *p != '\0'; ++p)
1134 switch (*p)
1136 case '?':
1137 case '*':
1138 return 1;
1140 case '\\':
1141 if (quote && p[1] != '\0')
1142 ++p;
1143 break;
1145 case '[':
1146 open = 1;
1147 break;
1149 case ']':
1150 if (open)
1151 return 1;
1152 break;
1155 return 0;
1157 #ifdef _LIBC
1158 weak_alias (__glob_pattern_p, glob_pattern_p)
1159 #endif
1162 /* Like `glob', but PATTERN is a final pathname component,
1163 and matches are searched for in DIRECTORY.
1164 The GLOB_NOSORT bit in FLAGS is ignored. No sorting is ever done.
1165 The GLOB_APPEND flag is assumed to be set (always appends). */
1166 static int
1167 glob_in_dir (pattern, directory, flags, errfunc, pglob)
1168 const char *pattern;
1169 const char *directory;
1170 int flags;
1171 int (*errfunc) __P ((const char *, int));
1172 glob_t *pglob;
1174 __ptr_t stream = NULL;
1176 struct globlink
1178 struct globlink *next;
1179 char *name;
1181 struct globlink *names = NULL;
1182 size_t nfound;
1183 int meta;
1184 int save;
1186 meta = __glob_pattern_p (pattern, !(flags & GLOB_NOESCAPE));
1187 if (meta == 0)
1189 if (flags & (GLOB_NOCHECK|GLOB_NOMAGIC))
1190 /* We need not do any tests. The PATTERN contains no meta
1191 characters and we must not return an error therefore the
1192 result will always contain exactly one name. */
1193 flags |= GLOB_NOCHECK;
1194 else
1196 /* Since we use the normal file functions we can also use stat()
1197 to verify the file is there. */
1198 struct stat st;
1199 size_t patlen = strlen (pattern);
1200 size_t dirlen = strlen (directory);
1201 char *fullname = (char *) __alloca (dirlen + 1 + patlen + 1);
1203 # ifdef HAVE_MEMPCPY
1204 mempcpy (mempcpy (mempcpy (fullname, directory, dirlen),
1205 "/", 1),
1206 pattern, patlen + 1);
1207 # else
1208 memcpy (fullname, directory, dirlen);
1209 fullname[dirlen] = '/';
1210 memcpy (&fullname[dirlen + 1], pattern, patlen + 1);
1211 # endif
1212 if (((flags & GLOB_ALTDIRFUNC)
1213 ? (*pglob->gl_stat) (fullname, &st)
1214 : __stat (fullname, &st)) == 0)
1215 /* We found this file to be existing. Now tell the rest
1216 of the function to copy this name into the result. */
1217 flags |= GLOB_NOCHECK;
1220 nfound = 0;
1222 else
1224 if (pattern[0] == '\0')
1226 /* This is a special case for matching directories like in
1227 "*a/". */
1228 names = (struct globlink *) __alloca (sizeof (struct globlink));
1229 names->name = (char *) malloc (1);
1230 if (names->name == NULL)
1231 goto memory_error;
1232 names->name[0] = '\0';
1233 names->next = NULL;
1234 nfound = 1;
1235 meta = 0;
1237 else
1239 stream = ((flags & GLOB_ALTDIRFUNC)
1240 ? (*pglob->gl_opendir) (directory)
1241 : (__ptr_t) opendir (directory));
1242 if (stream == NULL)
1244 if ((errfunc != NULL && (*errfunc) (directory, errno))
1245 || (flags & GLOB_ERR))
1246 return GLOB_ABORTED;
1247 nfound = 0;
1248 meta = 0;
1250 else
1252 int fnm_flags = ((!(flags & GLOB_PERIOD) ? FNM_PERIOD : 0)
1253 | ((flags & GLOB_NOESCAPE) ? FNM_NOESCAPE : 0)
1254 #if defined _AMIGA || defined VMS
1255 | FNM_CASEFOLD
1256 #endif
1258 nfound = 0;
1259 flags |= GLOB_MAGCHAR;
1261 while (1)
1263 const char *name;
1264 size_t len;
1265 struct dirent *d = ((flags & GLOB_ALTDIRFUNC)
1266 ? (*pglob->gl_readdir) (stream)
1267 : readdir ((DIR *) stream));
1268 if (d == NULL)
1269 break;
1270 if (! REAL_DIR_ENTRY (d))
1271 continue;
1273 #ifdef HAVE_D_TYPE
1274 /* If we shall match only directories use the information
1275 provided by the dirent call if possible. */
1276 if ((flags & GLOB_ONLYDIR)
1277 && d->d_type != DT_UNKNOWN && d->d_type != DT_DIR)
1278 continue;
1279 #endif
1281 name = d->d_name;
1283 if (fnmatch (pattern, name, fnm_flags) == 0)
1285 struct globlink *new = (struct globlink *)
1286 __alloca (sizeof (struct globlink));
1287 len = NAMLEN (d);
1288 new->name = (char *) malloc (len + 1);
1289 if (new->name == NULL)
1290 goto memory_error;
1291 #ifdef HAVE_MEMPCPY
1292 *((char *) mempcpy ((__ptr_t) new->name, name, len))
1293 = '\0';
1294 #else
1295 memcpy ((__ptr_t) new->name, name, len);
1296 new->name[len] = '\0';
1297 #endif
1298 new->next = names;
1299 names = new;
1300 ++nfound;
1307 if (nfound == 0 && (flags & GLOB_NOCHECK))
1309 size_t len = strlen (pattern);
1310 nfound = 1;
1311 names = (struct globlink *) __alloca (sizeof (struct globlink));
1312 names->next = NULL;
1313 names->name = (char *) malloc (len + 1);
1314 if (names->name == NULL)
1315 goto memory_error;
1316 #ifdef HAVE_MEMPCPY
1317 *((char *) mempcpy (names->name, pattern, len)) = '\0';
1318 #else
1319 memcpy (names->name, pattern, len);
1320 names->name[len] = '\0';
1321 #endif
1324 if (nfound != 0)
1326 pglob->gl_pathv
1327 = (char **) realloc (pglob->gl_pathv,
1328 (pglob->gl_pathc +
1329 ((flags & GLOB_DOOFFS) ? pglob->gl_offs : 0) +
1330 nfound + 1) *
1331 sizeof (char *));
1332 if (pglob->gl_pathv == NULL)
1333 goto memory_error;
1335 if (flags & GLOB_DOOFFS)
1336 while (pglob->gl_pathc < pglob->gl_offs)
1337 pglob->gl_pathv[pglob->gl_pathc++] = NULL;
1339 for (; names != NULL; names = names->next)
1340 pglob->gl_pathv[pglob->gl_pathc++] = names->name;
1341 pglob->gl_pathv[pglob->gl_pathc] = NULL;
1343 pglob->gl_flags = flags;
1346 save = errno;
1347 if (stream != NULL)
1348 if (flags & GLOB_ALTDIRFUNC)
1349 (*pglob->gl_closedir) (stream);
1350 else
1351 closedir ((DIR *) stream);
1352 __set_errno (save);
1354 return nfound == 0 ? GLOB_NOMATCH : 0;
1356 memory_error:
1358 int save = errno;
1359 if (flags & GLOB_ALTDIRFUNC)
1360 (*pglob->gl_closedir) (stream);
1361 else
1362 closedir ((DIR *) stream);
1363 __set_errno (save);
1365 while (names != NULL)
1367 if (names->name != NULL)
1368 free ((__ptr_t) names->name);
1369 names = names->next;
1371 return GLOB_NOSPACE;
1374 #endif /* Not ELIDE_CODE. */