Update.
[glibc.git] / sysdeps / generic / glob.c
blobd624655718965b41dbf91ab5e8aed4e24878c683
1 /* Copyright (C) 1991,92,93,94,95,96,97,98,99 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 # undef mempcpy
187 # define mempcpy(Dest, Src, Len) __mempcpy (Dest, Src, Len)
188 #endif
190 #ifndef __GNU_LIBRARY__
191 # ifdef __GNUC__
192 __inline
193 # endif
194 # ifndef __SASC
195 # ifdef WINDOWS32
196 static void *
197 # else
198 static char *
199 # endif
200 my_realloc (p, n)
201 char *p;
202 unsigned int n;
204 /* These casts are the for sake of the broken Ultrix compiler,
205 which warns of illegal pointer combinations otherwise. */
206 if (p == NULL)
207 return (char *) malloc (n);
208 return (char *) realloc (p, n);
210 # define realloc my_realloc
211 # endif /* __SASC */
212 #endif /* __GNU_LIBRARY__ */
215 #if !defined __alloca && !defined __GNU_LIBRARY__
217 # ifdef __GNUC__
218 # undef alloca
219 # define alloca(n) __builtin_alloca (n)
220 # else /* Not GCC. */
221 # ifdef HAVE_ALLOCA_H
222 # include <alloca.h>
223 # else /* Not HAVE_ALLOCA_H. */
224 # ifndef _AIX
225 # ifdef WINDOWS32
226 # include <malloc.h>
227 # else
228 extern char *alloca ();
229 # endif /* WINDOWS32 */
230 # endif /* Not _AIX. */
231 # endif /* sparc or HAVE_ALLOCA_H. */
232 # endif /* GCC. */
234 # define __alloca alloca
236 #endif
238 #ifndef __GNU_LIBRARY__
239 # define __stat stat
240 # ifdef STAT_MACROS_BROKEN
241 # undef S_ISDIR
242 # endif
243 # ifndef S_ISDIR
244 # define S_ISDIR(mode) (((mode) & S_IFMT) == S_IFDIR)
245 # endif
246 #endif
248 #ifdef _LIBC
249 # undef strdup
250 # define strdup(str) __strdup (str)
251 # define sysconf(id) __sysconf (id)
252 # define closedir(dir) __closedir (dir)
253 # define opendir(name) __opendir (name)
254 # define readdir(str) __readdir (str)
255 # define getpwnam_r(name, bufp, buf, len, res) \
256 __getpwnam_r (name, bufp, buf, len, res)
257 # ifndef __stat
258 # define __stat(fname, buf) __xstat (_STAT_VER, fname, buf)
259 # endif
260 #endif
262 #if !(defined STDC_HEADERS || defined __GNU_LIBRARY__)
263 # undef size_t
264 # define size_t unsigned int
265 #endif
267 /* Some system header files erroneously define these.
268 We want our own definitions from <fnmatch.h> to take precedence. */
269 #ifndef __GNU_LIBRARY__
270 # undef FNM_PATHNAME
271 # undef FNM_NOESCAPE
272 # undef FNM_PERIOD
273 #endif
274 #include <fnmatch.h>
276 /* Some system header files erroneously define these.
277 We want our own definitions from <glob.h> to take precedence. */
278 #ifndef __GNU_LIBRARY__
279 # undef GLOB_ERR
280 # undef GLOB_MARK
281 # undef GLOB_NOSORT
282 # undef GLOB_DOOFFS
283 # undef GLOB_NOCHECK
284 # undef GLOB_APPEND
285 # undef GLOB_NOESCAPE
286 # undef GLOB_PERIOD
287 #endif
288 #include <glob.h>
290 static
291 #if __GNUC__ - 0 >= 2
292 inline
293 #endif
294 const char *next_brace_sub __P ((const char *begin));
295 static int glob_in_dir __P ((const char *pattern, const char *directory,
296 int flags,
297 int (*errfunc) (const char *, int),
298 glob_t *pglob));
299 static int prefix_array __P ((const char *prefix, char **array, size_t n));
300 static int collated_compare __P ((const __ptr_t, const __ptr_t));
303 /* Find the end of the sub-pattern in a brace expression. We define
304 this as an inline function if the compiler permits. */
305 static
306 #if __GNUC__ - 0 >= 2
307 inline
308 #endif
309 const char *
310 next_brace_sub (begin)
311 const char *begin;
313 unsigned int depth = 0;
314 const char *cp = begin;
316 while (1)
318 if (depth == 0)
320 if (*cp != ',' && *cp != '}' && *cp != '\0')
322 if (*cp == '{')
323 ++depth;
324 ++cp;
325 continue;
328 else
330 while (*cp != '\0' && (*cp != '}' || depth > 0))
332 if (*cp == '}')
333 --depth;
334 ++cp;
336 if (*cp == '\0')
337 /* An incorrectly terminated brace expression. */
338 return NULL;
340 continue;
342 break;
345 return cp;
348 /* Do glob searching for PATTERN, placing results in PGLOB.
349 The bits defined above may be set in FLAGS.
350 If a directory cannot be opened or read and ERRFUNC is not nil,
351 it is called with the pathname that caused the error, and the
352 `errno' value from the failing call; if it returns non-zero
353 `glob' returns GLOB_ABORTED; if it returns zero, the error is ignored.
354 If memory cannot be allocated for PGLOB, GLOB_NOSPACE is returned.
355 Otherwise, `glob' returns zero. */
357 glob (pattern, flags, errfunc, pglob)
358 const char *pattern;
359 int flags;
360 int (*errfunc) __P ((const char *, int));
361 glob_t *pglob;
363 const char *filename;
364 const char *dirname;
365 size_t dirlen;
366 int status;
367 int oldcount;
369 if (pattern == NULL || pglob == NULL || (flags & ~__GLOB_FLAGS) != 0)
371 __set_errno (EINVAL);
372 return -1;
375 if (flags & GLOB_BRACE)
377 const char *begin = strchr (pattern, '{');
378 if (begin != NULL)
380 /* Allocate working buffer large enough for our work. Note that
381 we have at least an opening and closing brace. */
382 int firstc;
383 char *alt_start;
384 const char *p;
385 const char *next;
386 const char *rest;
387 size_t rest_len;
388 #ifdef __GNUC__
389 char onealt[strlen (pattern) - 1];
390 #else
391 char *onealt = (char *) malloc (strlen (pattern) - 1);
392 if (onealt == NULL)
394 if (!(flags & GLOB_APPEND))
395 globfree (pglob);
396 return GLOB_NOSPACE;
398 #endif
400 /* We know the prefix for all sub-patterns. */
401 #ifdef HAVE_MEMPCPY
402 alt_start = mempcpy (onealt, pattern, begin - pattern);
403 #else
404 memcpy (onealt, pattern, begin - pattern);
405 alt_start = &onealt[begin - pattern];
406 #endif
408 /* Find the first sub-pattern and at the same time find the
409 rest after the closing brace. */
410 next = next_brace_sub (begin + 1);
411 if (next == NULL)
413 /* It is an illegal expression. */
414 #ifndef __GNUC__
415 free (onealt);
416 #endif
417 return glob (pattern, flags & ~GLOB_BRACE, errfunc, pglob);
420 /* Now find the end of the whole brace expression. */
421 rest = next;
422 while (*rest != '}')
424 rest = next_brace_sub (rest + 1);
425 if (rest == NULL)
427 /* It is an illegal expression. */
428 #ifndef __GNUC__
429 free (onealt);
430 #endif
431 return glob (pattern, flags & ~GLOB_BRACE, errfunc, pglob);
434 /* Please note that we now can be sure the brace expression
435 is well-formed. */
436 rest_len = strlen (++rest) + 1;
438 /* We have a brace expression. BEGIN points to the opening {,
439 NEXT points past the terminator of the first element, and END
440 points past the final }. We will accumulate result names from
441 recursive runs for each brace alternative in the buffer using
442 GLOB_APPEND. */
444 if (!(flags & GLOB_APPEND))
446 /* This call is to set a new vector, so clear out the
447 vector so we can append to it. */
448 pglob->gl_pathc = 0;
449 pglob->gl_pathv = NULL;
451 firstc = pglob->gl_pathc;
453 p = begin + 1;
454 while (1)
456 int result;
458 /* Construct the new glob expression. */
459 #ifdef HAVE_MEMPCPY
460 mempcpy (mempcpy (alt_start, p, next - p), rest, rest_len);
461 #else
462 memcpy (alt_start, p, next - p);
463 memcpy (&alt_start[next - p], rest, rest_len);
464 #endif
466 result = glob (onealt,
467 ((flags & ~(GLOB_NOCHECK|GLOB_NOMAGIC))
468 | GLOB_APPEND), errfunc, pglob);
470 /* If we got an error, return it. */
471 if (result && result != GLOB_NOMATCH)
473 #ifndef __GNUC__
474 free (onealt);
475 #endif
476 if (!(flags & GLOB_APPEND))
477 globfree (pglob);
478 return result;
481 if (*next == '}')
482 /* We saw the last entry. */
483 break;
485 p = next + 1;
486 next = next_brace_sub (p);
487 assert (next != NULL);
490 #ifndef __GNUC__
491 free (onealt);
492 #endif
494 if (pglob->gl_pathc != firstc)
495 /* We found some entries. */
496 return 0;
497 else if (!(flags & (GLOB_NOCHECK|GLOB_NOMAGIC)))
498 return GLOB_NOMATCH;
502 /* Find the filename. */
503 filename = strrchr (pattern, '/');
504 #if defined __MSDOS__ || defined WINDOWS32
505 /* The case of "d:pattern". Since `:' is not allowed in
506 file names, we can safely assume that wherever it
507 happens in pattern, it signals the filename part. This
508 is so we could some day support patterns like "[a-z]:foo". */
509 if (filename == NULL)
510 filename = strchr (pattern, ':');
511 #endif /* __MSDOS__ || WINDOWS32 */
512 if (filename == NULL)
514 /* This can mean two things: a simple name or "~name". The later
515 case is nothing but a notation for a directory. */
516 if ((flags & (GLOB_TILDE|GLOB_TILDE_CHECK)) && pattern[0] == '~')
518 dirname = pattern;
519 dirlen = strlen (pattern);
521 /* Set FILENAME to NULL as a special flag. This is ugly but
522 other solutions would require much more code. We test for
523 this special case below. */
524 filename = NULL;
526 else
528 filename = pattern;
529 #ifdef _AMIGA
530 dirname = "";
531 #else
532 dirname = ".";
533 #endif
534 dirlen = 0;
537 else if (filename == pattern)
539 /* "/pattern". */
540 dirname = "/";
541 dirlen = 1;
542 ++filename;
544 else
546 char *newp;
547 dirlen = filename - pattern;
548 #if defined __MSDOS__ || defined WINDOWS32
549 if (*filename == ':'
550 || (filename > pattern + 1 && filename[-1] == ':'))
552 char *drive_spec;
554 ++dirlen;
555 drive_spec = (char *) __alloca (dirlen + 1);
556 #ifdef HAVE_MEMPCPY
557 *((char *) mempcpy (drive_spec, pattern, dirlen)) = '\0';
558 #else
559 memcpy (drive_spec, pattern, dirlen);
560 drive_spec[dirlen] = '\0';
561 #endif
562 /* For now, disallow wildcards in the drive spec, to
563 prevent infinite recursion in glob. */
564 if (__glob_pattern_p (drive_spec, !(flags & GLOB_NOESCAPE)))
565 return GLOB_NOMATCH;
566 /* If this is "d:pattern", we need to copy `:' to DIRNAME
567 as well. If it's "d:/pattern", don't remove the slash
568 from "d:/", since "d:" and "d:/" are not the same.*/
570 #endif
571 newp = (char *) __alloca (dirlen + 1);
572 #ifdef HAVE_MEMPCPY
573 *((char *) mempcpy (newp, pattern, dirlen)) = '\0';
574 #else
575 memcpy (newp, pattern, dirlen);
576 newp[dirlen] = '\0';
577 #endif
578 dirname = newp;
579 ++filename;
581 if (filename[0] == '\0'
582 #if defined __MSDOS__ || defined WINDOWS32
583 && dirname[dirlen - 1] != ':'
584 && (dirlen < 3 || dirname[dirlen - 2] != ':'
585 || dirname[dirlen - 1] != '/')
586 #endif
587 && dirlen > 1)
588 /* "pattern/". Expand "pattern", appending slashes. */
590 int val = glob (dirname, flags | GLOB_MARK, errfunc, pglob);
591 if (val == 0)
592 pglob->gl_flags = ((pglob->gl_flags & ~GLOB_MARK)
593 | (flags & GLOB_MARK));
594 return val;
598 if (!(flags & GLOB_APPEND))
600 pglob->gl_pathc = 0;
601 pglob->gl_pathv = NULL;
604 oldcount = pglob->gl_pathc;
606 #ifndef VMS
607 if ((flags & (GLOB_TILDE|GLOB_TILDE_CHECK)) && dirname[0] == '~')
609 if (dirname[1] == '\0' || dirname[1] == '/')
611 /* Look up home directory. */
612 const char *home_dir = getenv ("HOME");
613 # ifdef _AMIGA
614 if (home_dir == NULL || home_dir[0] == '\0')
615 home_dir = "SYS:";
616 # else
617 # ifdef WINDOWS32
618 if (home_dir == NULL || home_dir[0] == '\0')
619 home_dir = "c:/users/default"; /* poor default */
620 # else
621 if (home_dir == NULL || home_dir[0] == '\0')
623 int success;
624 char *name;
625 # if defined HAVE_GETLOGIN_R || defined _LIBC
626 size_t buflen = sysconf (_SC_LOGIN_NAME_MAX) + 1;
628 if (buflen == 0)
629 /* `sysconf' does not support _SC_LOGIN_NAME_MAX. Try
630 a moderate value. */
631 buflen = 20;
632 name = (char *) __alloca (buflen);
634 success = getlogin_r (name, buflen) >= 0;
635 # else
636 success = (name = getlogin ()) != NULL;
637 # endif
638 if (success)
640 struct passwd *p;
641 # if defined HAVE_GETPWNAM_R || defined _LIBC
642 size_t pwbuflen = sysconf (_SC_GETPW_R_SIZE_MAX);
643 char *pwtmpbuf;
644 struct passwd pwbuf;
645 int save = errno;
647 if (pwbuflen == -1)
648 /* `sysconf' does not support _SC_GETPW_R_SIZE_MAX.
649 Try a moderate value. */
650 pwbuflen = 1024;
651 pwtmpbuf = (char *) __alloca (pwbuflen);
653 success = 1;
654 while (getpwnam_r (name, &pwbuf, pwtmpbuf, pwbuflen, &p) < 0)
656 if (errno != ERANGE)
658 success = 0;
659 break;
661 pwbuflen *= 2;
662 pwtmpbuf = (char *) __alloca (pwbuflen);
663 __set_errno (save);
665 # else
666 p = getpwnam (name);
667 success = p != NULL;
668 # endif
669 if (success)
670 home_dir = p->pw_dir;
673 if (home_dir == NULL || home_dir[0] == '\0')
675 if (flags & GLOB_TILDE_CHECK)
676 return GLOB_NOMATCH;
677 else
678 home_dir = "~"; /* No luck. */
680 # endif /* WINDOWS32 */
681 # endif
682 /* Now construct the full directory. */
683 if (dirname[1] == '\0')
684 dirname = home_dir;
685 else
687 char *newp;
688 size_t home_len = strlen (home_dir);
689 newp = (char *) __alloca (home_len + dirlen);
690 # ifdef HAVE_MEMPCPY
691 mempcpy (mempcpy (newp, home_dir, home_len),
692 &dirname[1], dirlen);
693 # else
694 memcpy (newp, home_dir, home_len);
695 memcpy (&newp[home_len], &dirname[1], dirlen);
696 # endif
697 dirname = newp;
700 # if !defined _AMIGA && !defined WINDOWS32
701 else
703 char *end_name = strchr (dirname, '/');
704 const char *user_name;
705 const char *home_dir;
707 if (end_name == NULL)
708 user_name = dirname + 1;
709 else
711 char *newp;
712 newp = (char *) __alloca (end_name - dirname);
713 # ifdef HAVE_MEMPCPY
714 *((char *) mempcpy (newp, dirname + 1, end_name - dirname))
715 = '\0';
716 # else
717 memcpy (newp, dirname + 1, end_name - dirname);
718 newp[end_name - dirname - 1] = '\0';
719 # endif
720 user_name = newp;
723 /* Look up specific user's home directory. */
725 struct passwd *p;
726 # if defined HAVE_GETPWNAM_R || defined _LIBC
727 size_t buflen = sysconf (_SC_GETPW_R_SIZE_MAX);
728 char *pwtmpbuf;
729 struct passwd pwbuf;
730 int save = errno;
732 if (buflen == -1)
733 /* `sysconf' does not support _SC_GETPW_R_SIZE_MAX. Try a
734 moderate value. */
735 buflen = 1024;
736 pwtmpbuf = (char *) __alloca (buflen);
738 while (getpwnam_r (user_name, &pwbuf, pwtmpbuf, buflen, &p) < 0)
740 if (errno != ERANGE)
742 p = NULL;
743 break;
745 buflen *= 2;
746 pwtmpbuf = __alloca (buflen);
747 __set_errno (save);
749 # else
750 p = getpwnam (user_name);
751 # endif
752 if (p != NULL)
753 home_dir = p->pw_dir;
754 else
755 home_dir = NULL;
757 /* If we found a home directory use this. */
758 if (home_dir != NULL)
760 char *newp;
761 size_t home_len = strlen (home_dir);
762 size_t rest_len = end_name == NULL ? 0 : strlen (end_name);
763 newp = (char *) __alloca (home_len + rest_len + 1);
764 # ifdef HAVE_MEMPCPY
765 *((char *) mempcpy (mempcpy (newp, home_dir, home_len),
766 end_name, rest_len)) = '\0';
767 # else
768 memcpy (newp, home_dir, home_len);
769 memcpy (&newp[home_len], end_name, rest_len);
770 newp[home_len + rest_len] = '\0';
771 # endif
772 dirname = newp;
774 else
775 if (flags & GLOB_TILDE_CHECK)
776 /* We have to regard it as an error if we cannot find the
777 home directory. */
778 return GLOB_NOMATCH;
780 # endif /* Not Amiga && not WINDOWS32. */
782 #endif /* Not VMS. */
784 /* Now test whether we looked for "~" or "~NAME". In this case we
785 can give the answer now. */
786 if (filename == NULL)
788 struct stat st;
790 /* Return the directory if we don't check for error or if it exists. */
791 if ((flags & GLOB_NOCHECK)
792 || (((flags & GLOB_ALTDIRFUNC)
793 ? (*pglob->gl_stat) (dirname, &st)
794 : __stat (dirname, &st)) == 0
795 && S_ISDIR (st.st_mode)))
797 pglob->gl_pathv
798 = (char **) realloc (pglob->gl_pathv,
799 (pglob->gl_pathc +
800 ((flags & GLOB_DOOFFS) ?
801 pglob->gl_offs : 0) +
802 1 + 1) *
803 sizeof (char *));
804 if (pglob->gl_pathv == NULL)
805 return GLOB_NOSPACE;
807 if (flags & GLOB_DOOFFS)
808 while (pglob->gl_pathc < pglob->gl_offs)
809 pglob->gl_pathv[pglob->gl_pathc++] = NULL;
811 #if defined HAVE_STRDUP || defined _LIBC
812 pglob->gl_pathv[pglob->gl_pathc] = strdup (dirname);
813 #else
815 size_t len = strlen (dirname) + 1;
816 char *dircopy = malloc (len);
817 if (dircopy != NULL)
818 pglob->gl_pathv[pglob->gl_pathc] = memcpy (dircopy, dirname,
819 len);
821 #endif
822 if (pglob->gl_pathv[pglob->gl_pathc] == NULL)
824 free (pglob->gl_pathv);
825 return GLOB_NOSPACE;
827 pglob->gl_pathv[++pglob->gl_pathc] = NULL;
828 pglob->gl_flags = flags;
830 return 0;
833 /* Not found. */
834 return GLOB_NOMATCH;
837 if (__glob_pattern_p (dirname, !(flags & GLOB_NOESCAPE)))
839 /* The directory name contains metacharacters, so we
840 have to glob for the directory, and then glob for
841 the pattern in each directory found. */
842 glob_t dirs;
843 register int i;
845 status = glob (dirname,
846 ((flags & (GLOB_ERR | GLOB_NOCHECK | GLOB_NOESCAPE))
847 | GLOB_NOSORT | GLOB_ONLYDIR),
848 errfunc, &dirs);
849 if (status != 0)
850 return status;
852 /* We have successfully globbed the preceding directory name.
853 For each name we found, call glob_in_dir on it and FILENAME,
854 appending the results to PGLOB. */
855 for (i = 0; i < dirs.gl_pathc; ++i)
857 int old_pathc;
859 #ifdef SHELL
861 /* Make globbing interruptible in the bash shell. */
862 extern int interrupt_state;
864 if (interrupt_state)
866 globfree (&dirs);
867 globfree (&files);
868 return GLOB_ABORTED;
871 #endif /* SHELL. */
873 old_pathc = pglob->gl_pathc;
874 status = glob_in_dir (filename, dirs.gl_pathv[i],
875 ((flags | GLOB_APPEND)
876 & ~(GLOB_NOCHECK | GLOB_ERR)),
877 errfunc, pglob);
878 if (status == GLOB_NOMATCH)
879 /* No matches in this directory. Try the next. */
880 continue;
882 if (status != 0)
884 globfree (&dirs);
885 globfree (pglob);
886 return status;
889 /* Stick the directory on the front of each name. */
890 if (prefix_array (dirs.gl_pathv[i],
891 &pglob->gl_pathv[old_pathc],
892 pglob->gl_pathc - old_pathc))
894 globfree (&dirs);
895 globfree (pglob);
896 return GLOB_NOSPACE;
900 flags |= GLOB_MAGCHAR;
902 /* We have ignored the GLOB_NOCHECK flag in the `glob_in_dir' calls.
903 But if we have not found any matching entry and thie GLOB_NOCHECK
904 flag was set we must return the list consisting of the disrectory
905 names followed by the filename. */
906 if (pglob->gl_pathc == oldcount)
908 /* No matches. */
909 if (flags & GLOB_NOCHECK)
911 size_t filename_len = strlen (filename) + 1;
912 char **new_pathv;
913 struct stat st;
915 /* This is an pessimistic guess about the size. */
916 pglob->gl_pathv
917 = (char **) realloc (pglob->gl_pathv,
918 (pglob->gl_pathc +
919 ((flags & GLOB_DOOFFS) ?
920 pglob->gl_offs : 0) +
921 dirs.gl_pathc + 1) *
922 sizeof (char *));
923 if (pglob->gl_pathv == NULL)
925 globfree (&dirs);
926 return GLOB_NOSPACE;
929 if (flags & GLOB_DOOFFS)
930 while (pglob->gl_pathc < pglob->gl_offs)
931 pglob->gl_pathv[pglob->gl_pathc++] = NULL;
933 for (i = 0; i < dirs.gl_pathc; ++i)
935 const char *dir = dirs.gl_pathv[i];
936 size_t dir_len = strlen (dir);
938 /* First check whether this really is a directory. */
939 if (((flags & GLOB_ALTDIRFUNC)
940 ? (*pglob->gl_stat) (dir, &st) : __stat (dir, &st)) != 0
941 || !S_ISDIR (st.st_mode))
942 /* No directory, ignore this entry. */
943 continue;
945 pglob->gl_pathv[pglob->gl_pathc] = malloc (dir_len + 1
946 + filename_len);
947 if (pglob->gl_pathv[pglob->gl_pathc] == NULL)
949 globfree (&dirs);
950 globfree (pglob);
951 return GLOB_NOSPACE;
954 #ifdef HAVE_MEMPCPY
955 mempcpy (mempcpy (mempcpy (pglob->gl_pathv[pglob->gl_pathc],
956 dir, dir_len),
957 "/", 1),
958 filename, filename_len);
959 #else
960 memcpy (pglob->gl_pathv[pglob->gl_pathc], dir, dir_len);
961 pglob->gl_pathv[pglob->gl_pathc][dir_len] = '/';
962 memcpy (&pglob->gl_pathv[pglob->gl_pathc][dir_len + 1],
963 filename, filename_len);
964 #endif
965 ++pglob->gl_pathc;
968 pglob->gl_pathv[pglob->gl_pathc] = NULL;
969 pglob->gl_flags = flags;
971 /* Now we know how large the gl_pathv vector must be. */
972 new_pathv = (char **) realloc (pglob->gl_pathv,
973 ((pglob->gl_pathc + 1)
974 * sizeof (char *)));
975 if (new_pathv != NULL)
976 pglob->gl_pathv = new_pathv;
978 else
979 return GLOB_NOMATCH;
982 globfree (&dirs);
984 else
986 status = glob_in_dir (filename, dirname, flags, errfunc, pglob);
987 if (status != 0)
988 return status;
990 if (dirlen > 0)
992 /* Stick the directory on the front of each name. */
993 int ignore = oldcount;
995 if ((flags & GLOB_DOOFFS) && ignore < pglob->gl_offs)
996 ignore = pglob->gl_offs;
998 if (prefix_array (dirname,
999 &pglob->gl_pathv[ignore],
1000 pglob->gl_pathc - ignore))
1002 globfree (pglob);
1003 return GLOB_NOSPACE;
1008 if (flags & GLOB_MARK)
1010 /* Append slashes to directory names. */
1011 int i;
1012 struct stat st;
1013 for (i = oldcount; i < pglob->gl_pathc; ++i)
1014 if (((flags & GLOB_ALTDIRFUNC)
1015 ? (*pglob->gl_stat) (pglob->gl_pathv[i], &st)
1016 : __stat (pglob->gl_pathv[i], &st)) == 0
1017 && S_ISDIR (st.st_mode))
1019 size_t len = strlen (pglob->gl_pathv[i]) + 2;
1020 char *new = realloc (pglob->gl_pathv[i], len);
1021 if (new == NULL)
1023 globfree (pglob);
1024 return GLOB_NOSPACE;
1026 strcpy (&new[len - 2], "/");
1027 pglob->gl_pathv[i] = new;
1031 if (!(flags & GLOB_NOSORT))
1033 /* Sort the vector. */
1034 int non_sort = oldcount;
1036 if ((flags & GLOB_DOOFFS) && pglob->gl_offs > oldcount)
1037 non_sort = pglob->gl_offs;
1039 qsort ((__ptr_t) &pglob->gl_pathv[non_sort],
1040 pglob->gl_pathc - non_sort,
1041 sizeof (char *), collated_compare);
1044 return 0;
1048 /* Free storage allocated in PGLOB by a previous `glob' call. */
1049 void
1050 globfree (pglob)
1051 register glob_t *pglob;
1053 if (pglob->gl_pathv != NULL)
1055 register int i;
1056 for (i = 0; i < pglob->gl_pathc; ++i)
1057 if (pglob->gl_pathv[i] != NULL)
1058 free ((__ptr_t) pglob->gl_pathv[i]);
1059 free ((__ptr_t) pglob->gl_pathv);
1064 /* Do a collated comparison of A and B. */
1065 static int
1066 collated_compare (a, b)
1067 const __ptr_t a;
1068 const __ptr_t b;
1070 const char *const s1 = *(const char *const * const) a;
1071 const char *const s2 = *(const char *const * const) b;
1073 if (s1 == s2)
1074 return 0;
1075 if (s1 == NULL)
1076 return 1;
1077 if (s2 == NULL)
1078 return -1;
1079 return strcoll (s1, s2);
1083 /* Prepend DIRNAME to each of N members of ARRAY, replacing ARRAY's
1084 elements in place. Return nonzero if out of memory, zero if successful.
1085 A slash is inserted between DIRNAME and each elt of ARRAY,
1086 unless DIRNAME is just "/". Each old element of ARRAY is freed. */
1087 static int
1088 prefix_array (dirname, array, n)
1089 const char *dirname;
1090 char **array;
1091 size_t n;
1093 register size_t i;
1094 size_t dirlen = strlen (dirname);
1095 #if defined __MSDOS__ || defined WINDOWS32
1096 int sep_char = '/';
1097 # define DIRSEP_CHAR sep_char
1098 #else
1099 # define DIRSEP_CHAR '/'
1100 #endif
1102 if (dirlen == 1 && dirname[0] == '/')
1103 /* DIRNAME is just "/", so normal prepending would get us "//foo".
1104 We want "/foo" instead, so don't prepend any chars from DIRNAME. */
1105 dirlen = 0;
1106 #if defined __MSDOS__ || defined WINDOWS32
1107 else if (dirlen > 1)
1109 if (dirname[dirlen - 1] == '/')
1110 /* DIRNAME is "d:/". Don't prepend the slash from DIRNAME. */
1111 --dirlen;
1112 else if (dirname[dirlen - 1] == ':')
1114 /* DIRNAME is "d:". Use `:' instead of `/'. */
1115 --dirlen;
1116 sep_char = ':';
1119 #endif
1121 for (i = 0; i < n; ++i)
1123 size_t eltlen = strlen (array[i]) + 1;
1124 char *new = (char *) malloc (dirlen + 1 + eltlen);
1125 if (new == NULL)
1127 while (i > 0)
1128 free ((__ptr_t) array[--i]);
1129 return 1;
1132 #ifdef HAVE_MEMPCPY
1134 char *endp = (char *) mempcpy (new, dirname, dirlen);
1135 *endp++ = DIRSEP_CHAR;
1136 mempcpy (endp, array[i], eltlen);
1138 #else
1139 memcpy (new, dirname, dirlen);
1140 new[dirlen] = DIRSEP_CHAR;
1141 memcpy (&new[dirlen + 1], array[i], eltlen);
1142 #endif
1143 free ((__ptr_t) array[i]);
1144 array[i] = new;
1147 return 0;
1151 /* We must not compile this function twice. */
1152 #if !defined _LIBC || !defined NO_GLOB_PATTERN_P
1153 /* Return nonzero if PATTERN contains any metacharacters.
1154 Metacharacters can be quoted with backslashes if QUOTE is nonzero. */
1156 __glob_pattern_p (pattern, quote)
1157 const char *pattern;
1158 int quote;
1160 register const char *p;
1161 int open = 0;
1163 for (p = pattern; *p != '\0'; ++p)
1164 switch (*p)
1166 case '?':
1167 case '*':
1168 return 1;
1170 case '\\':
1171 if (quote && p[1] != '\0')
1172 ++p;
1173 break;
1175 case '[':
1176 open = 1;
1177 break;
1179 case ']':
1180 if (open)
1181 return 1;
1182 break;
1185 return 0;
1187 # ifdef _LIBC
1188 weak_alias (__glob_pattern_p, glob_pattern_p)
1189 # endif
1190 #endif
1193 /* Like `glob', but PATTERN is a final pathname component,
1194 and matches are searched for in DIRECTORY.
1195 The GLOB_NOSORT bit in FLAGS is ignored. No sorting is ever done.
1196 The GLOB_APPEND flag is assumed to be set (always appends). */
1197 static int
1198 glob_in_dir (pattern, directory, flags, errfunc, pglob)
1199 const char *pattern;
1200 const char *directory;
1201 int flags;
1202 int (*errfunc) __P ((const char *, int));
1203 glob_t *pglob;
1205 __ptr_t stream = NULL;
1207 struct globlink
1209 struct globlink *next;
1210 char *name;
1212 struct globlink *names = NULL;
1213 size_t nfound;
1214 int meta;
1215 int save;
1217 meta = __glob_pattern_p (pattern, !(flags & GLOB_NOESCAPE));
1218 if (meta == 0)
1220 if (flags & (GLOB_NOCHECK|GLOB_NOMAGIC))
1221 /* We need not do any tests. The PATTERN contains no meta
1222 characters and we must not return an error therefore the
1223 result will always contain exactly one name. */
1224 flags |= GLOB_NOCHECK;
1225 else
1227 /* Since we use the normal file functions we can also use stat()
1228 to verify the file is there. */
1229 struct stat st;
1230 size_t patlen = strlen (pattern);
1231 size_t dirlen = strlen (directory);
1232 char *fullname = (char *) __alloca (dirlen + 1 + patlen + 1);
1234 # ifdef HAVE_MEMPCPY
1235 mempcpy (mempcpy (mempcpy (fullname, directory, dirlen),
1236 "/", 1),
1237 pattern, patlen + 1);
1238 # else
1239 memcpy (fullname, directory, dirlen);
1240 fullname[dirlen] = '/';
1241 memcpy (&fullname[dirlen + 1], pattern, patlen + 1);
1242 # endif
1243 if (((flags & GLOB_ALTDIRFUNC)
1244 ? (*pglob->gl_stat) (fullname, &st)
1245 : __stat (fullname, &st)) == 0)
1246 /* We found this file to be existing. Now tell the rest
1247 of the function to copy this name into the result. */
1248 flags |= GLOB_NOCHECK;
1251 nfound = 0;
1253 else
1255 if (pattern[0] == '\0')
1257 /* This is a special case for matching directories like in
1258 "*a/". */
1259 names = (struct globlink *) __alloca (sizeof (struct globlink));
1260 names->name = (char *) malloc (1);
1261 if (names->name == NULL)
1262 goto memory_error;
1263 names->name[0] = '\0';
1264 names->next = NULL;
1265 nfound = 1;
1266 meta = 0;
1268 else
1270 stream = ((flags & GLOB_ALTDIRFUNC)
1271 ? (*pglob->gl_opendir) (directory)
1272 : (__ptr_t) opendir (directory));
1273 if (stream == NULL)
1275 if ((errfunc != NULL && (*errfunc) (directory, errno))
1276 || (flags & GLOB_ERR))
1277 return GLOB_ABORTED;
1278 nfound = 0;
1279 meta = 0;
1281 else
1283 int fnm_flags = ((!(flags & GLOB_PERIOD) ? FNM_PERIOD : 0)
1284 | ((flags & GLOB_NOESCAPE) ? FNM_NOESCAPE : 0)
1285 #if defined _AMIGA || defined VMS
1286 | FNM_CASEFOLD
1287 #endif
1289 nfound = 0;
1290 flags |= GLOB_MAGCHAR;
1292 while (1)
1294 const char *name;
1295 size_t len;
1296 struct dirent *d = ((flags & GLOB_ALTDIRFUNC)
1297 ? (*pglob->gl_readdir) (stream)
1298 : readdir ((DIR *) stream));
1299 if (d == NULL)
1300 break;
1301 if (! REAL_DIR_ENTRY (d))
1302 continue;
1304 #ifdef HAVE_D_TYPE
1305 /* If we shall match only directories use the information
1306 provided by the dirent call if possible. */
1307 if ((flags & GLOB_ONLYDIR)
1308 && d->d_type != DT_UNKNOWN && d->d_type != DT_DIR)
1309 continue;
1310 #endif
1312 name = d->d_name;
1314 if (fnmatch (pattern, name, fnm_flags) == 0)
1316 struct globlink *new = (struct globlink *)
1317 __alloca (sizeof (struct globlink));
1318 len = NAMLEN (d);
1319 new->name = (char *) malloc (len + 1);
1320 if (new->name == NULL)
1321 goto memory_error;
1322 #ifdef HAVE_MEMPCPY
1323 *((char *) mempcpy ((__ptr_t) new->name, name, len))
1324 = '\0';
1325 #else
1326 memcpy ((__ptr_t) new->name, name, len);
1327 new->name[len] = '\0';
1328 #endif
1329 new->next = names;
1330 names = new;
1331 ++nfound;
1338 if (nfound == 0 && (flags & GLOB_NOCHECK))
1340 size_t len = strlen (pattern);
1341 nfound = 1;
1342 names = (struct globlink *) __alloca (sizeof (struct globlink));
1343 names->next = NULL;
1344 names->name = (char *) malloc (len + 1);
1345 if (names->name == NULL)
1346 goto memory_error;
1347 #ifdef HAVE_MEMPCPY
1348 *((char *) mempcpy (names->name, pattern, len)) = '\0';
1349 #else
1350 memcpy (names->name, pattern, len);
1351 names->name[len] = '\0';
1352 #endif
1355 if (nfound != 0)
1357 pglob->gl_pathv
1358 = (char **) realloc (pglob->gl_pathv,
1359 (pglob->gl_pathc +
1360 ((flags & GLOB_DOOFFS) ? pglob->gl_offs : 0) +
1361 nfound + 1) *
1362 sizeof (char *));
1363 if (pglob->gl_pathv == NULL)
1364 goto memory_error;
1366 if (flags & GLOB_DOOFFS)
1367 while (pglob->gl_pathc < pglob->gl_offs)
1368 pglob->gl_pathv[pglob->gl_pathc++] = NULL;
1370 for (; names != NULL; names = names->next)
1371 pglob->gl_pathv[pglob->gl_pathc++] = names->name;
1372 pglob->gl_pathv[pglob->gl_pathc] = NULL;
1374 pglob->gl_flags = flags;
1377 save = errno;
1378 if (stream != NULL)
1380 if (flags & GLOB_ALTDIRFUNC)
1381 (*pglob->gl_closedir) (stream);
1382 else
1383 closedir ((DIR *) stream);
1385 __set_errno (save);
1387 return nfound == 0 ? GLOB_NOMATCH : 0;
1389 memory_error:
1391 int save = errno;
1392 if (flags & GLOB_ALTDIRFUNC)
1393 (*pglob->gl_closedir) (stream);
1394 else
1395 closedir ((DIR *) stream);
1396 __set_errno (save);
1398 while (names != NULL)
1400 if (names->name != NULL)
1401 free ((__ptr_t) names->name);
1402 names = names->next;
1404 return GLOB_NOSPACE;
1407 #endif /* Not ELIDE_CODE. */