More copyright/license updates.
[make.git] / glob / glob.c
blob8deb273e4d09cd7a720309dba71933954da40b41
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 License
14 along with this library; see the file COPYING.LIB. If not, write to the Free
15 Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301
16 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 #ifndef ANSI_STRING
160 # ifndef bzero
161 extern void bzero ();
162 # endif
163 # ifndef bcopy
164 extern void bcopy ();
165 # endif
167 # define memcpy(d, s, n) bcopy ((s), (d), (n))
168 # define strrchr rindex
169 /* memset is only used for zero here, but let's be paranoid. */
170 # define memset(s, better_be_zero, n) \
171 ((void) ((better_be_zero) == 0 ? (bzero((s), (n)), 0) : (abort(), 0)))
172 #endif /* Not ANSI_STRING. */
174 #if !defined HAVE_STRCOLL && !defined _LIBC
175 # define strcoll strcmp
176 #endif
178 #if !defined HAVE_MEMPCPY && __GLIBC__ - 0 == 2 && __GLIBC_MINOR__ >= 1
179 # define HAVE_MEMPCPY 1
180 # undef mempcpy
181 # define mempcpy(Dest, Src, Len) __mempcpy (Dest, Src, Len)
182 #endif
184 #ifndef __GNU_LIBRARY__
185 # ifdef __GNUC__
186 __inline
187 # endif
188 # ifndef __SASC
189 # ifdef WINDOWS32
190 static void *
191 # else
192 static char *
193 # endif
194 my_realloc (p, n)
195 char *p;
196 unsigned int n;
198 /* These casts are the for sake of the broken Ultrix compiler,
199 which warns of illegal pointer combinations otherwise. */
200 if (p == NULL)
201 return (char *) malloc (n);
202 return (char *) realloc (p, n);
204 # define realloc my_realloc
205 # endif /* __SASC */
206 #endif /* __GNU_LIBRARY__ */
209 #if !defined __alloca && !defined __GNU_LIBRARY__
211 # ifdef __GNUC__
212 # undef alloca
213 # define alloca(n) __builtin_alloca (n)
214 # else /* Not GCC. */
215 # ifdef HAVE_ALLOCA_H
216 # include <alloca.h>
217 # else /* Not HAVE_ALLOCA_H. */
218 # ifndef _AIX
219 # ifdef WINDOWS32
220 # include <malloc.h>
221 # else
222 extern char *alloca ();
223 # endif /* WINDOWS32 */
224 # endif /* Not _AIX. */
225 # endif /* sparc or HAVE_ALLOCA_H. */
226 # endif /* GCC. */
228 # define __alloca alloca
230 #endif
232 #ifndef __GNU_LIBRARY__
233 # define __stat stat
234 # ifdef STAT_MACROS_BROKEN
235 # undef S_ISDIR
236 # endif
237 # ifndef S_ISDIR
238 # define S_ISDIR(mode) (((mode) & S_IFMT) == S_IFDIR)
239 # endif
240 #endif
242 #ifdef _LIBC
243 # undef strdup
244 # define strdup(str) __strdup (str)
245 # define sysconf(id) __sysconf (id)
246 # define closedir(dir) __closedir (dir)
247 # define opendir(name) __opendir (name)
248 # define readdir(str) __readdir (str)
249 # define getpwnam_r(name, bufp, buf, len, res) \
250 __getpwnam_r (name, bufp, buf, len, res)
251 # ifndef __stat
252 # define __stat(fname, buf) __xstat (_STAT_VER, fname, buf)
253 # endif
254 #endif
256 #if !(defined STDC_HEADERS || defined __GNU_LIBRARY__)
257 # undef size_t
258 # define size_t unsigned int
259 #endif
261 /* Some system header files erroneously define these.
262 We want our own definitions from <fnmatch.h> to take precedence. */
263 #ifndef __GNU_LIBRARY__
264 # undef FNM_PATHNAME
265 # undef FNM_NOESCAPE
266 # undef FNM_PERIOD
267 #endif
268 #include <fnmatch.h>
270 /* Some system header files erroneously define these.
271 We want our own definitions from <glob.h> to take precedence. */
272 #ifndef __GNU_LIBRARY__
273 # undef GLOB_ERR
274 # undef GLOB_MARK
275 # undef GLOB_NOSORT
276 # undef GLOB_DOOFFS
277 # undef GLOB_NOCHECK
278 # undef GLOB_APPEND
279 # undef GLOB_NOESCAPE
280 # undef GLOB_PERIOD
281 #endif
282 #include <glob.h>
284 #ifdef HAVE_GETLOGIN_R
285 extern int getlogin_r __P ((char *, size_t));
286 #else
287 extern char *getlogin __P ((void));
288 #endif
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));
302 #if !defined _LIBC || !defined NO_GLOB_PATTERN_P
303 int __glob_pattern_p __P ((const char *pattern, int quote));
304 #endif
306 /* Find the end of the sub-pattern in a brace expression. We define
307 this as an inline function if the compiler permits. */
308 static
309 #if __GNUC__ - 0 >= 2
310 inline
311 #endif
312 const char *
313 next_brace_sub (begin)
314 const char *begin;
316 unsigned int depth = 0;
317 const char *cp = begin;
319 while (1)
321 if (depth == 0)
323 if (*cp != ',' && *cp != '}' && *cp != '\0')
325 if (*cp == '{')
326 ++depth;
327 ++cp;
328 continue;
331 else
333 while (*cp != '\0' && (*cp != '}' || depth > 0))
335 if (*cp == '}')
336 --depth;
337 ++cp;
339 if (*cp == '\0')
340 /* An incorrectly terminated brace expression. */
341 return NULL;
343 continue;
345 break;
348 return cp;
351 /* Do glob searching for PATTERN, placing results in PGLOB.
352 The bits defined above may be set in FLAGS.
353 If a directory cannot be opened or read and ERRFUNC is not nil,
354 it is called with the pathname that caused the error, and the
355 `errno' value from the failing call; if it returns non-zero
356 `glob' returns GLOB_ABORTED; if it returns zero, the error is ignored.
357 If memory cannot be allocated for PGLOB, GLOB_NOSPACE is returned.
358 Otherwise, `glob' returns zero. */
360 glob (pattern, flags, errfunc, pglob)
361 const char *pattern;
362 int flags;
363 int (*errfunc) __P ((const char *, int));
364 glob_t *pglob;
366 const char *filename;
367 const char *dirname;
368 size_t dirlen;
369 int status;
370 int oldcount;
372 if (pattern == NULL || pglob == NULL || (flags & ~__GLOB_FLAGS) != 0)
374 __set_errno (EINVAL);
375 return -1;
378 if (flags & GLOB_BRACE)
380 const char *begin = strchr (pattern, '{');
381 if (begin != NULL)
383 /* Allocate working buffer large enough for our work. Note that
384 we have at least an opening and closing brace. */
385 int firstc;
386 char *alt_start;
387 const char *p;
388 const char *next;
389 const char *rest;
390 size_t rest_len;
391 #ifdef __GNUC__
392 char onealt[strlen (pattern) - 1];
393 #else
394 char *onealt = (char *) malloc (strlen (pattern) - 1);
395 if (onealt == NULL)
397 if (!(flags & GLOB_APPEND))
398 globfree (pglob);
399 return GLOB_NOSPACE;
401 #endif
403 /* We know the prefix for all sub-patterns. */
404 #ifdef HAVE_MEMPCPY
405 alt_start = mempcpy (onealt, pattern, begin - pattern);
406 #else
407 memcpy (onealt, pattern, begin - pattern);
408 alt_start = &onealt[begin - pattern];
409 #endif
411 /* Find the first sub-pattern and at the same time find the
412 rest after the closing brace. */
413 next = next_brace_sub (begin + 1);
414 if (next == NULL)
416 /* It is an illegal expression. */
417 #ifndef __GNUC__
418 free (onealt);
419 #endif
420 return glob (pattern, flags & ~GLOB_BRACE, errfunc, pglob);
423 /* Now find the end of the whole brace expression. */
424 rest = next;
425 while (*rest != '}')
427 rest = next_brace_sub (rest + 1);
428 if (rest == NULL)
430 /* It is an illegal expression. */
431 #ifndef __GNUC__
432 free (onealt);
433 #endif
434 return glob (pattern, flags & ~GLOB_BRACE, errfunc, pglob);
437 /* Please note that we now can be sure the brace expression
438 is well-formed. */
439 rest_len = strlen (++rest) + 1;
441 /* We have a brace expression. BEGIN points to the opening {,
442 NEXT points past the terminator of the first element, and END
443 points past the final }. We will accumulate result names from
444 recursive runs for each brace alternative in the buffer using
445 GLOB_APPEND. */
447 if (!(flags & GLOB_APPEND))
449 /* This call is to set a new vector, so clear out the
450 vector so we can append to it. */
451 pglob->gl_pathc = 0;
452 pglob->gl_pathv = NULL;
454 firstc = pglob->gl_pathc;
456 p = begin + 1;
457 while (1)
459 int result;
461 /* Construct the new glob expression. */
462 #ifdef HAVE_MEMPCPY
463 mempcpy (mempcpy (alt_start, p, next - p), rest, rest_len);
464 #else
465 memcpy (alt_start, p, next - p);
466 memcpy (&alt_start[next - p], rest, rest_len);
467 #endif
469 result = glob (onealt,
470 ((flags & ~(GLOB_NOCHECK|GLOB_NOMAGIC))
471 | GLOB_APPEND), errfunc, pglob);
473 /* If we got an error, return it. */
474 if (result && result != GLOB_NOMATCH)
476 #ifndef __GNUC__
477 free (onealt);
478 #endif
479 if (!(flags & GLOB_APPEND))
480 globfree (pglob);
481 return result;
484 if (*next == '}')
485 /* We saw the last entry. */
486 break;
488 p = next + 1;
489 next = next_brace_sub (p);
490 assert (next != NULL);
493 #ifndef __GNUC__
494 free (onealt);
495 #endif
497 if (pglob->gl_pathc != firstc)
498 /* We found some entries. */
499 return 0;
500 else if (!(flags & (GLOB_NOCHECK|GLOB_NOMAGIC)))
501 return GLOB_NOMATCH;
505 /* Find the filename. */
506 filename = strrchr (pattern, '/');
507 #if defined __MSDOS__ || defined WINDOWS32
508 /* The case of "d:pattern". Since `:' is not allowed in
509 file names, we can safely assume that wherever it
510 happens in pattern, it signals the filename part. This
511 is so we could some day support patterns like "[a-z]:foo". */
512 if (filename == NULL)
513 filename = strchr (pattern, ':');
514 #endif /* __MSDOS__ || WINDOWS32 */
515 if (filename == NULL)
517 /* This can mean two things: a simple name or "~name". The later
518 case is nothing but a notation for a directory. */
519 if ((flags & (GLOB_TILDE|GLOB_TILDE_CHECK)) && pattern[0] == '~')
521 dirname = pattern;
522 dirlen = strlen (pattern);
524 /* Set FILENAME to NULL as a special flag. This is ugly but
525 other solutions would require much more code. We test for
526 this special case below. */
527 filename = NULL;
529 else
531 filename = pattern;
532 #ifdef _AMIGA
533 dirname = "";
534 #else
535 dirname = ".";
536 #endif
537 dirlen = 0;
540 else if (filename == pattern)
542 /* "/pattern". */
543 dirname = "/";
544 dirlen = 1;
545 ++filename;
547 else
549 char *newp;
550 dirlen = filename - pattern;
551 #if defined __MSDOS__ || defined WINDOWS32
552 if (*filename == ':'
553 || (filename > pattern + 1 && filename[-1] == ':'))
555 char *drive_spec;
557 ++dirlen;
558 drive_spec = (char *) __alloca (dirlen + 1);
559 #ifdef HAVE_MEMPCPY
560 *((char *) mempcpy (drive_spec, pattern, dirlen)) = '\0';
561 #else
562 memcpy (drive_spec, pattern, dirlen);
563 drive_spec[dirlen] = '\0';
564 #endif
565 /* For now, disallow wildcards in the drive spec, to
566 prevent infinite recursion in glob. */
567 if (__glob_pattern_p (drive_spec, !(flags & GLOB_NOESCAPE)))
568 return GLOB_NOMATCH;
569 /* If this is "d:pattern", we need to copy `:' to DIRNAME
570 as well. If it's "d:/pattern", don't remove the slash
571 from "d:/", since "d:" and "d:/" are not the same.*/
573 #endif
574 newp = (char *) __alloca (dirlen + 1);
575 #ifdef HAVE_MEMPCPY
576 *((char *) mempcpy (newp, pattern, dirlen)) = '\0';
577 #else
578 memcpy (newp, pattern, dirlen);
579 newp[dirlen] = '\0';
580 #endif
581 dirname = newp;
582 ++filename;
584 if (filename[0] == '\0'
585 #if defined __MSDOS__ || defined WINDOWS32
586 && dirname[dirlen - 1] != ':'
587 && (dirlen < 3 || dirname[dirlen - 2] != ':'
588 || dirname[dirlen - 1] != '/')
589 #endif
590 && dirlen > 1)
591 /* "pattern/". Expand "pattern", appending slashes. */
593 int val = glob (dirname, flags | GLOB_MARK, errfunc, pglob);
594 if (val == 0)
595 pglob->gl_flags = ((pglob->gl_flags & ~GLOB_MARK)
596 | (flags & GLOB_MARK));
597 return val;
601 if (!(flags & GLOB_APPEND))
603 pglob->gl_pathc = 0;
604 pglob->gl_pathv = NULL;
607 oldcount = pglob->gl_pathc;
609 #ifndef VMS
610 if ((flags & (GLOB_TILDE|GLOB_TILDE_CHECK)) && dirname[0] == '~')
612 if (dirname[1] == '\0' || dirname[1] == '/')
614 /* Look up home directory. */
615 #ifdef VMS
616 /* This isn't obvious, RTLs of DECC and VAXC know about "HOME" */
617 const char *home_dir = getenv ("SYS$LOGIN");
618 #else
619 const char *home_dir = getenv ("HOME");
620 #endif
621 # ifdef _AMIGA
622 if (home_dir == NULL || home_dir[0] == '\0')
623 home_dir = "SYS:";
624 # else
625 # ifdef WINDOWS32
626 if (home_dir == NULL || home_dir[0] == '\0')
627 home_dir = "c:/users/default"; /* poor default */
628 # else
629 # ifdef VMS
630 /* Again, this isn't obvious, if "HOME" isn't known "SYS$LOGIN" should be set */
631 if (home_dir == NULL || home_dir[0] == '\0')
632 home_dir = "SYS$DISK:[]";
633 # else
634 if (home_dir == NULL || home_dir[0] == '\0')
636 int success;
637 char *name;
638 # if defined HAVE_GETLOGIN_R || defined _LIBC
639 size_t buflen = sysconf (_SC_LOGIN_NAME_MAX) + 1;
641 if (buflen == 0)
642 /* `sysconf' does not support _SC_LOGIN_NAME_MAX. Try
643 a moderate value. */
644 buflen = 20;
645 name = (char *) __alloca (buflen);
647 success = getlogin_r (name, buflen) >= 0;
648 # else
649 success = (name = getlogin ()) != NULL;
650 # endif
651 if (success)
653 struct passwd *p;
654 # if defined HAVE_GETPWNAM_R || defined _LIBC
655 size_t pwbuflen = sysconf (_SC_GETPW_R_SIZE_MAX);
656 char *pwtmpbuf;
657 struct passwd pwbuf;
658 int save = errno;
660 if (pwbuflen == -1)
661 /* `sysconf' does not support _SC_GETPW_R_SIZE_MAX.
662 Try a moderate value. */
663 pwbuflen = 1024;
664 pwtmpbuf = (char *) __alloca (pwbuflen);
666 while (getpwnam_r (name, &pwbuf, pwtmpbuf, pwbuflen, &p)
667 != 0)
669 if (errno != ERANGE)
671 p = NULL;
672 break;
674 pwbuflen *= 2;
675 pwtmpbuf = (char *) __alloca (pwbuflen);
676 __set_errno (save);
678 # else
679 p = getpwnam (name);
680 # endif
681 if (p != NULL)
682 home_dir = p->pw_dir;
685 if (home_dir == NULL || home_dir[0] == '\0')
687 if (flags & GLOB_TILDE_CHECK)
688 return GLOB_NOMATCH;
689 else
690 home_dir = "~"; /* No luck. */
692 # endif /* VMS */
693 # endif /* WINDOWS32 */
694 # endif
695 /* Now construct the full directory. */
696 if (dirname[1] == '\0')
697 dirname = home_dir;
698 else
700 char *newp;
701 size_t home_len = strlen (home_dir);
702 newp = (char *) __alloca (home_len + dirlen);
703 # ifdef HAVE_MEMPCPY
704 mempcpy (mempcpy (newp, home_dir, home_len),
705 &dirname[1], dirlen);
706 # else
707 memcpy (newp, home_dir, home_len);
708 memcpy (&newp[home_len], &dirname[1], dirlen);
709 # endif
710 dirname = newp;
713 # if !defined _AMIGA && !defined WINDOWS32 && !defined VMS
714 else
716 char *end_name = strchr (dirname, '/');
717 const char *user_name;
718 const char *home_dir;
720 if (end_name == NULL)
721 user_name = dirname + 1;
722 else
724 char *newp;
725 newp = (char *) __alloca (end_name - dirname);
726 # ifdef HAVE_MEMPCPY
727 *((char *) mempcpy (newp, dirname + 1, end_name - dirname))
728 = '\0';
729 # else
730 memcpy (newp, dirname + 1, end_name - dirname);
731 newp[end_name - dirname - 1] = '\0';
732 # endif
733 user_name = newp;
736 /* Look up specific user's home directory. */
738 struct passwd *p;
739 # if defined HAVE_GETPWNAM_R || defined _LIBC
740 size_t buflen = sysconf (_SC_GETPW_R_SIZE_MAX);
741 char *pwtmpbuf;
742 struct passwd pwbuf;
743 int save = errno;
745 if (buflen == -1)
746 /* `sysconf' does not support _SC_GETPW_R_SIZE_MAX. Try a
747 moderate value. */
748 buflen = 1024;
749 pwtmpbuf = (char *) __alloca (buflen);
751 while (getpwnam_r (user_name, &pwbuf, pwtmpbuf, buflen, &p) != 0)
753 if (errno != ERANGE)
755 p = NULL;
756 break;
758 buflen *= 2;
759 pwtmpbuf = __alloca (buflen);
760 __set_errno (save);
762 # else
763 p = getpwnam (user_name);
764 # endif
765 if (p != NULL)
766 home_dir = p->pw_dir;
767 else
768 home_dir = NULL;
770 /* If we found a home directory use this. */
771 if (home_dir != NULL)
773 char *newp;
774 size_t home_len = strlen (home_dir);
775 size_t rest_len = end_name == NULL ? 0 : strlen (end_name);
776 newp = (char *) __alloca (home_len + rest_len + 1);
777 # ifdef HAVE_MEMPCPY
778 *((char *) mempcpy (mempcpy (newp, home_dir, home_len),
779 end_name, rest_len)) = '\0';
780 # else
781 memcpy (newp, home_dir, home_len);
782 memcpy (&newp[home_len], end_name, rest_len);
783 newp[home_len + rest_len] = '\0';
784 # endif
785 dirname = newp;
787 else
788 if (flags & GLOB_TILDE_CHECK)
789 /* We have to regard it as an error if we cannot find the
790 home directory. */
791 return GLOB_NOMATCH;
793 # endif /* Not Amiga && not WINDOWS32 && not VMS. */
795 #endif /* Not VMS. */
797 /* Now test whether we looked for "~" or "~NAME". In this case we
798 can give the answer now. */
799 if (filename == NULL)
801 struct stat st;
803 /* Return the directory if we don't check for error or if it exists. */
804 if ((flags & GLOB_NOCHECK)
805 || (((flags & GLOB_ALTDIRFUNC)
806 ? (*pglob->gl_stat) (dirname, &st)
807 : __stat (dirname, &st)) == 0
808 && S_ISDIR (st.st_mode)))
810 pglob->gl_pathv
811 = (char **) realloc (pglob->gl_pathv,
812 (pglob->gl_pathc +
813 ((flags & GLOB_DOOFFS) ?
814 pglob->gl_offs : 0) +
815 1 + 1) *
816 sizeof (char *));
817 if (pglob->gl_pathv == NULL)
818 return GLOB_NOSPACE;
820 if (flags & GLOB_DOOFFS)
821 while (pglob->gl_pathc < pglob->gl_offs)
822 pglob->gl_pathv[pglob->gl_pathc++] = NULL;
824 #if defined HAVE_STRDUP || defined _LIBC
825 pglob->gl_pathv[pglob->gl_pathc] = strdup (dirname);
826 #else
828 size_t len = strlen (dirname) + 1;
829 char *dircopy = malloc (len);
830 if (dircopy != NULL)
831 pglob->gl_pathv[pglob->gl_pathc] = memcpy (dircopy, dirname,
832 len);
834 #endif
835 if (pglob->gl_pathv[pglob->gl_pathc] == NULL)
837 free (pglob->gl_pathv);
838 return GLOB_NOSPACE;
840 pglob->gl_pathv[++pglob->gl_pathc] = NULL;
841 pglob->gl_flags = flags;
843 return 0;
846 /* Not found. */
847 return GLOB_NOMATCH;
850 if (__glob_pattern_p (dirname, !(flags & GLOB_NOESCAPE)))
852 /* The directory name contains metacharacters, so we
853 have to glob for the directory, and then glob for
854 the pattern in each directory found. */
855 glob_t dirs;
856 register int i;
858 status = glob (dirname,
859 ((flags & (GLOB_ERR | GLOB_NOCHECK | GLOB_NOESCAPE))
860 | GLOB_NOSORT | GLOB_ONLYDIR),
861 errfunc, &dirs);
862 if (status != 0)
863 return status;
865 /* We have successfully globbed the preceding directory name.
866 For each name we found, call glob_in_dir on it and FILENAME,
867 appending the results to PGLOB. */
868 for (i = 0; i < dirs.gl_pathc; ++i)
870 int old_pathc;
872 #ifdef SHELL
874 /* Make globbing interruptible in the bash shell. */
875 extern int interrupt_state;
877 if (interrupt_state)
879 globfree (&dirs);
880 globfree (&files);
881 return GLOB_ABORTED;
884 #endif /* SHELL. */
886 old_pathc = pglob->gl_pathc;
887 status = glob_in_dir (filename, dirs.gl_pathv[i],
888 ((flags | GLOB_APPEND)
889 & ~(GLOB_NOCHECK | GLOB_ERR)),
890 errfunc, pglob);
891 if (status == GLOB_NOMATCH)
892 /* No matches in this directory. Try the next. */
893 continue;
895 if (status != 0)
897 globfree (&dirs);
898 globfree (pglob);
899 return status;
902 /* Stick the directory on the front of each name. */
903 if (prefix_array (dirs.gl_pathv[i],
904 &pglob->gl_pathv[old_pathc],
905 pglob->gl_pathc - old_pathc))
907 globfree (&dirs);
908 globfree (pglob);
909 return GLOB_NOSPACE;
913 flags |= GLOB_MAGCHAR;
915 /* We have ignored the GLOB_NOCHECK flag in the `glob_in_dir' calls.
916 But if we have not found any matching entry and thie GLOB_NOCHECK
917 flag was set we must return the list consisting of the disrectory
918 names followed by the filename. */
919 if (pglob->gl_pathc == oldcount)
921 /* No matches. */
922 if (flags & GLOB_NOCHECK)
924 size_t filename_len = strlen (filename) + 1;
925 char **new_pathv;
926 struct stat st;
928 /* This is an pessimistic guess about the size. */
929 pglob->gl_pathv
930 = (char **) realloc (pglob->gl_pathv,
931 (pglob->gl_pathc +
932 ((flags & GLOB_DOOFFS) ?
933 pglob->gl_offs : 0) +
934 dirs.gl_pathc + 1) *
935 sizeof (char *));
936 if (pglob->gl_pathv == NULL)
938 globfree (&dirs);
939 return GLOB_NOSPACE;
942 if (flags & GLOB_DOOFFS)
943 while (pglob->gl_pathc < pglob->gl_offs)
944 pglob->gl_pathv[pglob->gl_pathc++] = NULL;
946 for (i = 0; i < dirs.gl_pathc; ++i)
948 const char *dir = dirs.gl_pathv[i];
949 size_t dir_len = strlen (dir);
951 /* First check whether this really is a directory. */
952 if (((flags & GLOB_ALTDIRFUNC)
953 ? (*pglob->gl_stat) (dir, &st) : __stat (dir, &st)) != 0
954 || !S_ISDIR (st.st_mode))
955 /* No directory, ignore this entry. */
956 continue;
958 pglob->gl_pathv[pglob->gl_pathc] = malloc (dir_len + 1
959 + filename_len);
960 if (pglob->gl_pathv[pglob->gl_pathc] == NULL)
962 globfree (&dirs);
963 globfree (pglob);
964 return GLOB_NOSPACE;
967 #ifdef HAVE_MEMPCPY
968 mempcpy (mempcpy (mempcpy (pglob->gl_pathv[pglob->gl_pathc],
969 dir, dir_len),
970 "/", 1),
971 filename, filename_len);
972 #else
973 memcpy (pglob->gl_pathv[pglob->gl_pathc], dir, dir_len);
974 pglob->gl_pathv[pglob->gl_pathc][dir_len] = '/';
975 memcpy (&pglob->gl_pathv[pglob->gl_pathc][dir_len + 1],
976 filename, filename_len);
977 #endif
978 ++pglob->gl_pathc;
981 pglob->gl_pathv[pglob->gl_pathc] = NULL;
982 pglob->gl_flags = flags;
984 /* Now we know how large the gl_pathv vector must be. */
985 new_pathv = (char **) realloc (pglob->gl_pathv,
986 ((pglob->gl_pathc + 1)
987 * sizeof (char *)));
988 if (new_pathv != NULL)
989 pglob->gl_pathv = new_pathv;
991 else
992 return GLOB_NOMATCH;
995 globfree (&dirs);
997 else
999 status = glob_in_dir (filename, dirname, flags, errfunc, pglob);
1000 if (status != 0)
1001 return status;
1003 if (dirlen > 0)
1005 /* Stick the directory on the front of each name. */
1006 int ignore = oldcount;
1008 if ((flags & GLOB_DOOFFS) && ignore < pglob->gl_offs)
1009 ignore = pglob->gl_offs;
1011 if (prefix_array (dirname,
1012 &pglob->gl_pathv[ignore],
1013 pglob->gl_pathc - ignore))
1015 globfree (pglob);
1016 return GLOB_NOSPACE;
1021 if (flags & GLOB_MARK)
1023 /* Append slashes to directory names. */
1024 int i;
1025 struct stat st;
1026 for (i = oldcount; i < pglob->gl_pathc; ++i)
1027 if (((flags & GLOB_ALTDIRFUNC)
1028 ? (*pglob->gl_stat) (pglob->gl_pathv[i], &st)
1029 : __stat (pglob->gl_pathv[i], &st)) == 0
1030 && S_ISDIR (st.st_mode))
1032 size_t len = strlen (pglob->gl_pathv[i]) + 2;
1033 char *new = realloc (pglob->gl_pathv[i], len);
1034 if (new == NULL)
1036 globfree (pglob);
1037 return GLOB_NOSPACE;
1039 strcpy (&new[len - 2], "/");
1040 pglob->gl_pathv[i] = new;
1044 if (!(flags & GLOB_NOSORT))
1046 /* Sort the vector. */
1047 int non_sort = oldcount;
1049 if ((flags & GLOB_DOOFFS) && pglob->gl_offs > oldcount)
1050 non_sort = pglob->gl_offs;
1052 qsort ((__ptr_t) &pglob->gl_pathv[non_sort],
1053 pglob->gl_pathc - non_sort,
1054 sizeof (char *), collated_compare);
1057 return 0;
1061 /* Free storage allocated in PGLOB by a previous `glob' call. */
1062 void
1063 globfree (pglob)
1064 register glob_t *pglob;
1066 if (pglob->gl_pathv != NULL)
1068 register int i;
1069 for (i = 0; i < pglob->gl_pathc; ++i)
1070 if (pglob->gl_pathv[i] != NULL)
1071 free ((__ptr_t) pglob->gl_pathv[i]);
1072 free ((__ptr_t) pglob->gl_pathv);
1077 /* Do a collated comparison of A and B. */
1078 static int
1079 collated_compare (a, b)
1080 const __ptr_t a;
1081 const __ptr_t b;
1083 const char *const s1 = *(const char *const * const) a;
1084 const char *const s2 = *(const char *const * const) b;
1086 if (s1 == s2)
1087 return 0;
1088 if (s1 == NULL)
1089 return 1;
1090 if (s2 == NULL)
1091 return -1;
1092 return strcoll (s1, s2);
1096 /* Prepend DIRNAME to each of N members of ARRAY, replacing ARRAY's
1097 elements in place. Return nonzero if out of memory, zero if successful.
1098 A slash is inserted between DIRNAME and each elt of ARRAY,
1099 unless DIRNAME is just "/". Each old element of ARRAY is freed. */
1100 static int
1101 prefix_array (dirname, array, n)
1102 const char *dirname;
1103 char **array;
1104 size_t n;
1106 register size_t i;
1107 size_t dirlen = strlen (dirname);
1108 #if defined __MSDOS__ || defined WINDOWS32
1109 int sep_char = '/';
1110 # define DIRSEP_CHAR sep_char
1111 #else
1112 # define DIRSEP_CHAR '/'
1113 #endif
1115 if (dirlen == 1 && dirname[0] == '/')
1116 /* DIRNAME is just "/", so normal prepending would get us "//foo".
1117 We want "/foo" instead, so don't prepend any chars from DIRNAME. */
1118 dirlen = 0;
1119 #if defined __MSDOS__ || defined WINDOWS32
1120 else if (dirlen > 1)
1122 if (dirname[dirlen - 1] == '/' && dirname[dirlen - 2] == ':')
1123 /* DIRNAME is "d:/". Don't prepend the slash from DIRNAME. */
1124 --dirlen;
1125 else if (dirname[dirlen - 1] == ':')
1127 /* DIRNAME is "d:". Use `:' instead of `/'. */
1128 --dirlen;
1129 sep_char = ':';
1132 #endif
1134 for (i = 0; i < n; ++i)
1136 size_t eltlen = strlen (array[i]) + 1;
1137 char *new = (char *) malloc (dirlen + 1 + eltlen);
1138 if (new == NULL)
1140 while (i > 0)
1141 free ((__ptr_t) array[--i]);
1142 return 1;
1145 #ifdef HAVE_MEMPCPY
1147 char *endp = (char *) mempcpy (new, dirname, dirlen);
1148 *endp++ = DIRSEP_CHAR;
1149 mempcpy (endp, array[i], eltlen);
1151 #else
1152 memcpy (new, dirname, dirlen);
1153 new[dirlen] = DIRSEP_CHAR;
1154 memcpy (&new[dirlen + 1], array[i], eltlen);
1155 #endif
1156 free ((__ptr_t) array[i]);
1157 array[i] = new;
1160 return 0;
1164 /* We must not compile this function twice. */
1165 #if !defined _LIBC || !defined NO_GLOB_PATTERN_P
1166 /* Return nonzero if PATTERN contains any metacharacters.
1167 Metacharacters can be quoted with backslashes if QUOTE is nonzero. */
1169 __glob_pattern_p (pattern, quote)
1170 const char *pattern;
1171 int quote;
1173 register const char *p;
1174 int open = 0;
1176 for (p = pattern; *p != '\0'; ++p)
1177 switch (*p)
1179 case '?':
1180 case '*':
1181 return 1;
1183 case '\\':
1184 if (quote && p[1] != '\0')
1185 ++p;
1186 break;
1188 case '[':
1189 open = 1;
1190 break;
1192 case ']':
1193 if (open)
1194 return 1;
1195 break;
1198 return 0;
1200 # ifdef _LIBC
1201 weak_alias (__glob_pattern_p, glob_pattern_p)
1202 # endif
1203 #endif
1206 /* Like `glob', but PATTERN is a final pathname component,
1207 and matches are searched for in DIRECTORY.
1208 The GLOB_NOSORT bit in FLAGS is ignored. No sorting is ever done.
1209 The GLOB_APPEND flag is assumed to be set (always appends). */
1210 static int
1211 glob_in_dir (pattern, directory, flags, errfunc, pglob)
1212 const char *pattern;
1213 const char *directory;
1214 int flags;
1215 int (*errfunc) __P ((const char *, int));
1216 glob_t *pglob;
1218 __ptr_t stream = NULL;
1220 struct globlink
1222 struct globlink *next;
1223 char *name;
1225 struct globlink *names = NULL;
1226 size_t nfound;
1227 int meta;
1228 int save;
1230 #ifdef VMS
1231 if (*directory == 0)
1232 directory = "[]";
1233 #endif
1234 meta = __glob_pattern_p (pattern, !(flags & GLOB_NOESCAPE));
1235 if (meta == 0)
1237 if (flags & (GLOB_NOCHECK|GLOB_NOMAGIC))
1238 /* We need not do any tests. The PATTERN contains no meta
1239 characters and we must not return an error therefore the
1240 result will always contain exactly one name. */
1241 flags |= GLOB_NOCHECK;
1242 else
1244 /* Since we use the normal file functions we can also use stat()
1245 to verify the file is there. */
1246 struct stat st;
1247 size_t patlen = strlen (pattern);
1248 size_t dirlen = strlen (directory);
1249 char *fullname = (char *) __alloca (dirlen + 1 + patlen + 1);
1251 # ifdef HAVE_MEMPCPY
1252 mempcpy (mempcpy (mempcpy (fullname, directory, dirlen),
1253 "/", 1),
1254 pattern, patlen + 1);
1255 # else
1256 memcpy (fullname, directory, dirlen);
1257 fullname[dirlen] = '/';
1258 memcpy (&fullname[dirlen + 1], pattern, patlen + 1);
1259 # endif
1260 if (((flags & GLOB_ALTDIRFUNC)
1261 ? (*pglob->gl_stat) (fullname, &st)
1262 : __stat (fullname, &st)) == 0)
1263 /* We found this file to be existing. Now tell the rest
1264 of the function to copy this name into the result. */
1265 flags |= GLOB_NOCHECK;
1268 nfound = 0;
1270 else
1272 if (pattern[0] == '\0')
1274 /* This is a special case for matching directories like in
1275 "*a/". */
1276 names = (struct globlink *) __alloca (sizeof (struct globlink));
1277 names->name = (char *) malloc (1);
1278 if (names->name == NULL)
1279 goto memory_error;
1280 names->name[0] = '\0';
1281 names->next = NULL;
1282 nfound = 1;
1283 meta = 0;
1285 else
1287 stream = ((flags & GLOB_ALTDIRFUNC)
1288 ? (*pglob->gl_opendir) (directory)
1289 : (__ptr_t) opendir (directory));
1290 if (stream == NULL)
1292 if (errno != ENOTDIR
1293 && ((errfunc != NULL && (*errfunc) (directory, errno))
1294 || (flags & GLOB_ERR)))
1295 return GLOB_ABORTED;
1296 nfound = 0;
1297 meta = 0;
1299 else
1301 int fnm_flags = ((!(flags & GLOB_PERIOD) ? FNM_PERIOD : 0)
1302 | ((flags & GLOB_NOESCAPE) ? FNM_NOESCAPE : 0)
1303 #if defined HAVE_CASE_INSENSITIVE_FS
1304 | FNM_CASEFOLD
1305 #endif
1307 nfound = 0;
1308 flags |= GLOB_MAGCHAR;
1310 while (1)
1312 const char *name;
1313 size_t len;
1314 struct dirent *d = ((flags & GLOB_ALTDIRFUNC)
1315 ? (*pglob->gl_readdir) (stream)
1316 : readdir ((DIR *) stream));
1317 if (d == NULL)
1318 break;
1319 if (! REAL_DIR_ENTRY (d))
1320 continue;
1322 #ifdef HAVE_D_TYPE
1323 /* If we shall match only directories use the information
1324 provided by the dirent call if possible. */
1325 if ((flags & GLOB_ONLYDIR)
1326 && d->d_type != DT_UNKNOWN && d->d_type != DT_DIR)
1327 continue;
1328 #endif
1330 name = d->d_name;
1332 if (fnmatch (pattern, name, fnm_flags) == 0)
1334 struct globlink *new = (struct globlink *)
1335 __alloca (sizeof (struct globlink));
1336 len = NAMLEN (d);
1337 new->name = (char *) malloc (len + 1);
1338 if (new->name == NULL)
1339 goto memory_error;
1340 #ifdef HAVE_MEMPCPY
1341 *((char *) mempcpy ((__ptr_t) new->name, name, len))
1342 = '\0';
1343 #else
1344 memcpy ((__ptr_t) new->name, name, len);
1345 new->name[len] = '\0';
1346 #endif
1347 new->next = names;
1348 names = new;
1349 ++nfound;
1356 if (nfound == 0 && (flags & GLOB_NOCHECK))
1358 size_t len = strlen (pattern);
1359 nfound = 1;
1360 names = (struct globlink *) __alloca (sizeof (struct globlink));
1361 names->next = NULL;
1362 names->name = (char *) malloc (len + 1);
1363 if (names->name == NULL)
1364 goto memory_error;
1365 #ifdef HAVE_MEMPCPY
1366 *((char *) mempcpy (names->name, pattern, len)) = '\0';
1367 #else
1368 memcpy (names->name, pattern, len);
1369 names->name[len] = '\0';
1370 #endif
1373 if (nfound != 0)
1375 pglob->gl_pathv
1376 = (char **) realloc (pglob->gl_pathv,
1377 (pglob->gl_pathc +
1378 ((flags & GLOB_DOOFFS) ? pglob->gl_offs : 0) +
1379 nfound + 1) *
1380 sizeof (char *));
1381 if (pglob->gl_pathv == NULL)
1382 goto memory_error;
1384 if (flags & GLOB_DOOFFS)
1385 while (pglob->gl_pathc < pglob->gl_offs)
1386 pglob->gl_pathv[pglob->gl_pathc++] = NULL;
1388 for (; names != NULL; names = names->next)
1389 pglob->gl_pathv[pglob->gl_pathc++] = names->name;
1390 pglob->gl_pathv[pglob->gl_pathc] = NULL;
1392 pglob->gl_flags = flags;
1395 save = errno;
1396 if (stream != NULL)
1398 if (flags & GLOB_ALTDIRFUNC)
1399 (*pglob->gl_closedir) (stream);
1400 else
1401 closedir ((DIR *) stream);
1403 __set_errno (save);
1405 return nfound == 0 ? GLOB_NOMATCH : 0;
1407 memory_error:
1409 int save = errno;
1410 if (flags & GLOB_ALTDIRFUNC)
1411 (*pglob->gl_closedir) (stream);
1412 else
1413 closedir ((DIR *) stream);
1414 __set_errno (save);
1416 while (names != NULL)
1418 if (names->name != NULL)
1419 free ((__ptr_t) names->name);
1420 names = names->next;
1422 return GLOB_NOSPACE;
1425 #endif /* Not ELIDE_CODE. */