Update.
[glibc.git] / sysdeps / generic / glob.c
blob63347bdb2089776c54dec42e7186a3ffc1b7267d
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 #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 # define mempcpy(Dest, Src, Len) __mempcpy (Dest, Src, Len)
181 #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 # define sysconf(id) __sysconf (id)
244 # define closedir(dir) __closedir (dir)
245 # define opendir(name) __opendir (name)
246 # define readdir(str) __readdir (str)
247 #endif
249 #if !(defined STDC_HEADERS || defined __GNU_LIBRARY__)
250 # undef size_t
251 # define size_t unsigned int
252 #endif
254 /* Some system header files erroneously define these.
255 We want our own definitions from <fnmatch.h> to take precedence. */
256 #ifndef __GNU_LIBRARY__
257 # undef FNM_PATHNAME
258 # undef FNM_NOESCAPE
259 # undef FNM_PERIOD
260 #endif
261 #include <fnmatch.h>
263 /* Some system header files erroneously define these.
264 We want our own definitions from <glob.h> to take precedence. */
265 #ifndef __GNU_LIBRARY__
266 # undef GLOB_ERR
267 # undef GLOB_MARK
268 # undef GLOB_NOSORT
269 # undef GLOB_DOOFFS
270 # undef GLOB_NOCHECK
271 # undef GLOB_APPEND
272 # undef GLOB_NOESCAPE
273 # undef GLOB_PERIOD
274 #endif
275 #include <glob.h>
277 static
278 #if __GNUC__ - 0 >= 2
279 inline
280 #endif
281 const char *next_brace_sub __P ((const char *begin));
282 static int glob_in_dir __P ((const char *pattern, const char *directory,
283 int flags,
284 int (*errfunc) __P ((const char *, int)),
285 glob_t *pglob));
286 static int prefix_array __P ((const char *prefix, char **array, size_t n));
287 static int collated_compare __P ((const __ptr_t, const __ptr_t));
290 /* Find the end of the sub-pattern in a brace expression. We define
291 this as an inline function if the compiler permits. */
292 static
293 #if __GNUC__ - 0 >= 2
294 inline
295 #endif
296 const char *
297 next_brace_sub (begin)
298 const char *begin;
300 unsigned int depth = 0;
301 const char *cp = begin;
303 while (1)
305 if (depth == 0)
307 if (*cp != ',' && *cp != '}' && *cp != '\0')
309 if (*cp == '{')
310 ++depth;
311 ++cp;
312 continue;
315 else
317 while (*cp != '\0' && (*cp != '}' || depth > 0))
319 if (*cp == '}')
320 --depth;
321 ++cp;
323 if (*cp == '\0')
324 /* An incorrectly terminated brace expression. */
325 return NULL;
327 continue;
329 break;
332 return cp;
335 /* Do glob searching for PATTERN, placing results in PGLOB.
336 The bits defined above may be set in FLAGS.
337 If a directory cannot be opened or read and ERRFUNC is not nil,
338 it is called with the pathname that caused the error, and the
339 `errno' value from the failing call; if it returns non-zero
340 `glob' returns GLOB_ABORTED; if it returns zero, the error is ignored.
341 If memory cannot be allocated for PGLOB, GLOB_NOSPACE is returned.
342 Otherwise, `glob' returns zero. */
344 glob (pattern, flags, errfunc, pglob)
345 const char *pattern;
346 int flags;
347 int (*errfunc) __P ((const char *, int));
348 glob_t *pglob;
350 const char *filename;
351 char *dirname;
352 size_t dirlen;
353 int status;
354 int oldcount;
356 if (pattern == NULL || pglob == NULL || (flags & ~__GLOB_FLAGS) != 0)
358 __set_errno (EINVAL);
359 return -1;
362 if (flags & GLOB_BRACE)
364 const char *begin = strchr (pattern, '{');
365 if (begin != NULL)
367 /* Allocate working buffer large enough for our work. Note that
368 we have at least an opening and closing brace. */
369 int firstc;
370 char *alt_start;
371 const char *p;
372 const char *next;
373 const char *rest;
374 size_t rest_len;
375 #ifdef __GNUC__
376 char onealt[strlen (pattern) - 1];
377 #else
378 char *onealt = (char *) malloc (strlen (pattern) - 1);
379 if (onealt == NULL)
381 if (!(flags & GLOB_APPEND))
382 globfree (pglob);
383 return GLOB_NOSPACE;
385 #endif
387 /* We know the prefix for all sub-patterns. */
388 #ifdef HAVE_MEMPCPY
389 alt_start = mempcpy (onealt, pattern, begin - pattern);
390 #else
391 memcpy (onealt, pattern, begin - pattern);
392 alt_start = &onealt[begin - pattern];
393 #endif
395 /* Find the first sub-pattern and at the same time find the
396 rest after the closing brace. */
397 next = next_brace_sub (begin + 1);
398 if (next == NULL)
400 /* It is an illegal expression. */
401 #ifndef __GNUC__
402 free (onealt);
403 #endif
404 return glob (pattern, flags & ~GLOB_BRACE, errfunc, pglob);
407 /* Now find the end of the whole brace expression. */
408 rest = next;
409 while (*rest != '}')
411 rest = next_brace_sub (rest + 1);
412 if (rest == NULL)
414 /* It is an illegal expression. */
415 #ifndef __GNUC__
416 free (onealt);
417 #endif
418 return glob (pattern, flags & ~GLOB_BRACE, errfunc, pglob);
421 /* Please note that we now can be sure the brace expression
422 is well-formed. */
423 rest_len = strlen (++rest) + 1;
425 /* We have a brace expression. BEGIN points to the opening {,
426 NEXT points past the terminator of the first element, and END
427 points past the final }. We will accumulate result names from
428 recursive runs for each brace alternative in the buffer using
429 GLOB_APPEND. */
431 if (!(flags & GLOB_APPEND))
433 /* This call is to set a new vector, so clear out the
434 vector so we can append to it. */
435 pglob->gl_pathc = 0;
436 pglob->gl_pathv = NULL;
438 firstc = pglob->gl_pathc;
440 p = begin + 1;
441 while (1)
443 int result;
445 /* Construct the new glob expression. */
446 #ifdef HAVE_MEMPCPY
447 mempcpy (mempcpy (alt_start, p, next - p), rest, rest_len);
448 #else
449 memcpy (alt_start, p, next - p);
450 memcpy (&alt_start[next - p], rest, rest_len);
451 #endif
453 result = glob (onealt,
454 ((flags & ~(GLOB_NOCHECK|GLOB_NOMAGIC))
455 | GLOB_APPEND), errfunc, pglob);
457 /* If we got an error, return it. */
458 if (result && result != GLOB_NOMATCH)
460 #ifndef __GNUC__
461 free (onealt);
462 #endif
463 if (!(flags & GLOB_APPEND))
464 globfree (pglob);
465 return result;
468 if (*next == '}')
469 /* We saw the last entry. */
470 break;
472 p = next + 1;
473 next = next_brace_sub (p);
474 assert (next != NULL);
477 #ifndef __GNUC__
478 free (onealt);
479 #endif
481 if (pglob->gl_pathc != firstc)
482 /* We found some entries. */
483 return 0;
484 else if (!(flags & (GLOB_NOCHECK|GLOB_NOMAGIC)))
485 return GLOB_NOMATCH;
489 /* Find the filename. */
490 filename = strrchr (pattern, '/');
491 if (filename == NULL)
493 /* This can mean two things: a simple name or "~name". The later
494 case is nothing but a notation for a directory. */
495 if ((flags & GLOB_TILDE) && pattern[0] == '~')
497 dirname = pattern;
498 dirlen = strlen (pattern);
500 filename = "";
502 else
504 filename = pattern;
505 #ifdef _AMIGA
506 dirname = (char *) "";
507 #else
508 dirname = (char *) ".";
509 #endif
510 dirlen = 0;
513 else if (filename == pattern)
515 /* "/pattern". */
516 dirname = (char *) "/";
517 dirlen = 1;
518 ++filename;
520 else
522 dirlen = filename - pattern;
523 dirname = (char *) __alloca (dirlen + 1);
524 #ifdef HAVE_MEMPCPY
525 *((char *) mempcpy (dirname, pattern, dirlen)) = '\0';
526 #else
527 memcpy (dirname, pattern, dirlen);
528 dirname[dirlen] = '\0';
529 #endif
530 ++filename;
532 if (filename[0] == '\0' && dirlen > 1)
533 /* "pattern/". Expand "pattern", appending slashes. */
535 int val = glob (dirname, flags | GLOB_MARK, errfunc, pglob);
536 if (val == 0)
537 pglob->gl_flags = ((pglob->gl_flags & ~GLOB_MARK)
538 | (flags & GLOB_MARK));
539 return val;
543 if (!(flags & GLOB_APPEND))
545 pglob->gl_pathc = 0;
546 pglob->gl_pathv = NULL;
549 oldcount = pglob->gl_pathc;
551 #ifndef VMS
552 if ((flags & GLOB_TILDE) && dirname[0] == '~')
554 if (dirname[1] == '\0' || dirname[1] == '/')
556 /* Look up home directory. */
557 char *home_dir = getenv ("HOME");
558 # ifdef _AMIGA
559 if (home_dir == NULL || home_dir[0] == '\0')
560 home_dir = "SYS:";
561 # else
562 # ifdef WINDOWS32
563 if (home_dir == NULL || home_dir[0] == '\0')
564 home_dir = "c:/users/default"; /* poor default */
565 # else
566 if (home_dir == NULL || home_dir[0] == '\0')
568 int success;
569 # if defined HAVE_GETLOGIN_R || defined _LIBC
570 extern int getlogin_r __P ((char *, size_t));
571 size_t buflen = sysconf (_SC_LOGIN_NAME_MAX) + 1;
572 char *name;
574 if (buflen == 0)
575 /* `sysconf' does not support _SC_LOGIN_NAME_MAX. Try
576 a moderate value. */
577 buflen = 16;
578 name = (char *) __alloca (buflen);
580 success = getlogin_r (name, buflen) >= 0;
581 # else
582 extern char *getlogin __P ((void));
583 char *name;
585 success = (name = getlogin ()) != NULL;
586 # endif
587 if (success)
589 # if defined HAVE_GETPWNAM_R || defined _LIBC
590 size_t pwbuflen = sysconf (_SC_GETPW_R_SIZE_MAX);
591 char *pwtmpbuf;
592 struct passwd pwbuf, *p;
594 pwtmpbuf = (char *) __alloca (pwbuflen);
596 success = (__getpwnam_r (name, &pwbuf, pwtmpbuf,
597 pwbuflen, &p) >= 0);
598 # else
599 struct passwd *p = getpwnam (name);
600 success = p != NULL;
601 # endif
602 if (success)
603 home_dir = p->pw_dir;
606 if (home_dir == NULL || home_dir[0] == '\0')
607 home_dir = (char *) "~"; /* No luck. */
608 # endif /* WINDOWS32 */
609 # endif
610 /* Now construct the full directory. */
611 if (dirname[1] == '\0')
612 dirname = home_dir;
613 else
615 char *newp;
616 size_t home_len = strlen (home_dir);
617 newp = (char *) __alloca (home_len + dirlen);
618 # ifdef HAVE_MEMPCPY
619 mempcpy (mempcpy (newp, home_dir, home_len),
620 &dirname[1], dirlen);
621 # else
622 memcpy (newp, home_dir, home_len);
623 memcpy (&newp[home_len], &dirname[1], dirlen);
624 # endif
625 dirname = newp;
628 # if !defined _AMIGA && !defined WINDOWS32
629 else
631 char *end_name = strchr (dirname, '/');
632 char *user_name;
633 char *home_dir;
635 if (end_name == NULL)
636 user_name = dirname + 1;
637 else
639 user_name = (char *) __alloca (end_name - dirname);
640 # ifdef HAVE_MEMPCPY
641 *((char *) mempcpy (user_name, dirname + 1, end_name - dirname))
642 = '\0';
643 # else
644 memcpy (user_name, dirname + 1, end_name - dirname);
645 user_name[end_name - dirname - 1] = '\0';
646 # endif
649 /* Look up specific user's home directory. */
651 # if defined HAVE_GETPWNAM_R || defined _LIBC
652 size_t buflen = sysconf (_SC_GETPW_R_SIZE_MAX);
653 char *pwtmpbuf = (char *) __alloca (buflen);
654 struct passwd pwbuf, *p;
655 if (__getpwnam_r (user_name, &pwbuf, pwtmpbuf, buflen, &p) >= 0)
656 home_dir = p->pw_dir;
657 else
658 home_dir = NULL;
659 # else
660 struct passwd *p = getpwnam (user_name);
661 if (p != NULL)
662 home_dir = p->pw_dir;
663 else
664 home_dir = NULL;
665 # endif
667 /* If we found a home directory use this. */
668 if (home_dir != NULL)
670 char *newp;
671 size_t home_len = strlen (home_dir);
672 size_t rest_len = end_name == NULL ? 0 : strlen (end_name);
673 newp = (char *) __alloca (home_len + rest_len + 1);
674 # ifdef HAVE_MEMPCPY
675 *((char *) mempcpy (mempcpy (newp, home_dir, home_len),
676 end_name, rest_len)) = '\0';
677 # else
678 memcpy (newp, home_dir, home_len);
679 memcpy (&newp[home_len], end_name, rest_len);
680 newp[home_len + rest_len] = '\0';
681 # endif
682 dirname = newp;
685 # endif /* Not Amiga && not WINDOWS32. */
687 #endif /* Not VMS. */
689 if (__glob_pattern_p (dirname, !(flags & GLOB_NOESCAPE)))
691 /* The directory name contains metacharacters, so we
692 have to glob for the directory, and then glob for
693 the pattern in each directory found. */
694 glob_t dirs;
695 register int i;
697 status = glob (dirname,
698 ((flags & (GLOB_ERR | GLOB_NOCHECK | GLOB_NOESCAPE))
699 | GLOB_NOSORT | GLOB_ONLYDIR),
700 errfunc, &dirs);
701 if (status != 0)
702 return status;
704 /* We have successfully globbed the preceding directory name.
705 For each name we found, call glob_in_dir on it and FILENAME,
706 appending the results to PGLOB. */
707 for (i = 0; i < dirs.gl_pathc; ++i)
709 int old_pathc;
711 #ifdef SHELL
713 /* Make globbing interruptible in the bash shell. */
714 extern int interrupt_state;
716 if (interrupt_state)
718 globfree (&dirs);
719 globfree (&files);
720 return GLOB_ABORTED;
723 #endif /* SHELL. */
725 old_pathc = pglob->gl_pathc;
726 status = glob_in_dir (filename, dirs.gl_pathv[i],
727 ((flags | GLOB_APPEND)
728 & ~(GLOB_NOCHECK | GLOB_ERR)),
729 errfunc, pglob);
730 if (status == GLOB_NOMATCH)
731 /* No matches in this directory. Try the next. */
732 continue;
734 if (status != 0)
736 globfree (&dirs);
737 globfree (pglob);
738 return status;
741 /* Stick the directory on the front of each name. */
742 if (prefix_array (dirs.gl_pathv[i],
743 &pglob->gl_pathv[old_pathc],
744 pglob->gl_pathc - old_pathc))
746 globfree (&dirs);
747 globfree (pglob);
748 return GLOB_NOSPACE;
752 flags |= GLOB_MAGCHAR;
754 if (pglob->gl_pathc == oldcount)
755 /* No matches. */
756 if (flags & GLOB_NOCHECK)
758 size_t len = strlen (pattern) + 1;
759 char *patcopy = (char *) malloc (len);
760 if (patcopy == NULL)
761 return GLOB_NOSPACE;
762 memcpy (patcopy, pattern, len);
764 pglob->gl_pathv
765 = (char **) realloc (pglob->gl_pathv,
766 (pglob->gl_pathc +
767 ((flags & GLOB_DOOFFS) ?
768 pglob->gl_offs : 0) +
769 1 + 1) *
770 sizeof (char *));
771 if (pglob->gl_pathv == NULL)
773 free (patcopy);
774 return GLOB_NOSPACE;
777 if (flags & GLOB_DOOFFS)
778 while (pglob->gl_pathc < pglob->gl_offs)
779 pglob->gl_pathv[pglob->gl_pathc++] = NULL;
781 pglob->gl_pathv[pglob->gl_pathc++] = patcopy;
782 pglob->gl_pathv[pglob->gl_pathc] = NULL;
783 pglob->gl_flags = flags;
785 else
786 return GLOB_NOMATCH;
788 else
790 status = glob_in_dir (filename, dirname, flags, errfunc, pglob);
791 if (status != 0)
792 return status;
794 if (dirlen > 0)
796 /* Stick the directory on the front of each name. */
797 int ignore = oldcount;
799 if ((flags & GLOB_DOOFFS) && ignore < pglob->gl_offs)
800 ignore = pglob->gl_offs;
802 if (prefix_array (dirname,
803 &pglob->gl_pathv[ignore],
804 pglob->gl_pathc - ignore))
806 globfree (pglob);
807 return GLOB_NOSPACE;
812 if (flags & GLOB_MARK)
814 /* Append slashes to directory names. */
815 int i;
816 struct stat st;
817 for (i = oldcount; i < pglob->gl_pathc; ++i)
818 if (((flags & GLOB_ALTDIRFUNC)
819 ? (*pglob->gl_stat) (pglob->gl_pathv[i], &st)
820 : __stat (pglob->gl_pathv[i], &st)) == 0
821 && S_ISDIR (st.st_mode))
823 size_t len = strlen (pglob->gl_pathv[i]) + 2;
824 char *new = realloc (pglob->gl_pathv[i], len);
825 if (new == NULL)
827 globfree (pglob);
828 return GLOB_NOSPACE;
830 strcpy (&new[len - 2], "/");
831 pglob->gl_pathv[i] = new;
835 if (!(flags & GLOB_NOSORT))
837 /* Sort the vector. */
838 int non_sort = oldcount;
840 if ((flags & GLOB_DOOFFS) && pglob->gl_offs > oldcount)
841 non_sort = pglob->gl_offs;
843 qsort ((__ptr_t) &pglob->gl_pathv[non_sort],
844 pglob->gl_pathc - non_sort,
845 sizeof (char *), collated_compare);
848 return 0;
852 /* Free storage allocated in PGLOB by a previous `glob' call. */
853 void
854 globfree (pglob)
855 register glob_t *pglob;
857 if (pglob->gl_pathv != NULL)
859 register int i;
860 for (i = 0; i < pglob->gl_pathc; ++i)
861 if (pglob->gl_pathv[i] != NULL)
862 free ((__ptr_t) pglob->gl_pathv[i]);
863 free ((__ptr_t) pglob->gl_pathv);
868 /* Do a collated comparison of A and B. */
869 static int
870 collated_compare (a, b)
871 const __ptr_t a;
872 const __ptr_t b;
874 const char *const s1 = *(const char *const * const) a;
875 const char *const s2 = *(const char *const * const) b;
877 if (s1 == s2)
878 return 0;
879 if (s1 == NULL)
880 return 1;
881 if (s2 == NULL)
882 return -1;
883 return strcoll (s1, s2);
887 /* Prepend DIRNAME to each of N members of ARRAY, replacing ARRAY's
888 elements in place. Return nonzero if out of memory, zero if successful.
889 A slash is inserted between DIRNAME and each elt of ARRAY,
890 unless DIRNAME is just "/". Each old element of ARRAY is freed. */
891 static int
892 prefix_array (dirname, array, n)
893 const char *dirname;
894 char **array;
895 size_t n;
897 register size_t i;
898 size_t dirlen = strlen (dirname);
900 if (dirlen == 1 && dirname[0] == '/')
901 /* DIRNAME is just "/", so normal prepending would get us "//foo".
902 We want "/foo" instead, so don't prepend any chars from DIRNAME. */
903 dirlen = 0;
905 for (i = 0; i < n; ++i)
907 size_t eltlen = strlen (array[i]) + 1;
908 char *new = (char *) malloc (dirlen + 1 + eltlen);
909 if (new == NULL)
911 while (i > 0)
912 free ((__ptr_t) array[--i]);
913 return 1;
916 #ifdef HAVE_MEMPCPY
918 char *endp = (char *) mempcpy (new, dirname, dirlen);
919 *endp++ = '/';
920 mempcpy (endp, array[i], eltlen);
922 #else
923 memcpy (new, dirname, dirlen);
924 new[dirlen] = '/';
925 memcpy (&new[dirlen + 1], array[i], eltlen);
926 #endif
927 free ((__ptr_t) array[i]);
928 array[i] = new;
931 return 0;
935 /* Return nonzero if PATTERN contains any metacharacters.
936 Metacharacters can be quoted with backslashes if QUOTE is nonzero. */
938 __glob_pattern_p (pattern, quote)
939 const char *pattern;
940 int quote;
942 register const char *p;
943 int open = 0;
945 for (p = pattern; *p != '\0'; ++p)
946 switch (*p)
948 case '?':
949 case '*':
950 return 1;
952 case '\\':
953 if (quote && p[1] != '\0')
954 ++p;
955 break;
957 case '[':
958 open = 1;
959 break;
961 case ']':
962 if (open)
963 return 1;
964 break;
967 return 0;
969 #ifdef _LIBC
970 weak_alias (__glob_pattern_p, glob_pattern_p)
971 #endif
974 /* Like `glob', but PATTERN is a final pathname component,
975 and matches are searched for in DIRECTORY.
976 The GLOB_NOSORT bit in FLAGS is ignored. No sorting is ever done.
977 The GLOB_APPEND flag is assumed to be set (always appends). */
978 static int
979 glob_in_dir (pattern, directory, flags, errfunc, pglob)
980 const char *pattern;
981 const char *directory;
982 int flags;
983 int (*errfunc) __P ((const char *, int));
984 glob_t *pglob;
986 __ptr_t stream = NULL;
988 struct globlink
990 struct globlink *next;
991 char *name;
993 struct globlink *names = NULL;
994 size_t nfound;
995 int meta;
996 int save;
998 meta = __glob_pattern_p (pattern, !(flags & GLOB_NOESCAPE));
999 if (meta == 0)
1001 if (flags & (GLOB_NOCHECK|GLOB_NOMAGIC))
1002 /* We need not do any tests. The PATTERN contains no meta
1003 characters and we must not return an error therefore the
1004 result will always contain exactly the one name. */
1005 flags |= GLOB_NOCHECK;
1006 else
1008 /* Since we use the normal file functions we can also use stat()
1009 to verify the file is there. */
1010 struct stat st;
1011 size_t patlen = strlen (pattern);
1012 size_t dirlen = strlen (directory);
1013 char *fullname = __alloca (dirlen + 1 + patlen + 1);
1015 # ifdef HAVE_MEMPCPY
1016 mempcpy (mempcpy (mempcpy (fullname, directory, dirlen),
1017 "/", 1),
1018 pattern, patlen + 1);
1019 # else
1020 memcpy (fullname, directory, dirlen);
1021 fullname[dirlen] = '/';
1022 memcpy (&fullname[dirlen + 1], pattern, patlen + 1);
1023 # endif
1024 if (((flags & GLOB_ALTDIRFUNC)
1025 ? (*pglob->gl_stat) (fullname, &st)
1026 : __stat (fullname, &st)) == 0)
1027 /* We found this file to be existing. No tell the rest
1028 of the function to copy this name into the result. */
1029 flags |= GLOB_NOCHECK;
1032 nfound = 0;
1034 else
1036 if (pattern[0] == '\0')
1038 /* This is a special case for matching directories like in
1039 "*a/". */
1040 names = (struct globlink *) __alloca (sizeof (struct globlink));
1041 names->name = (char *) malloc (1);
1042 if (names->name == NULL)
1043 goto memory_error;
1044 names->name[0] = '\0';
1045 names->next = NULL;
1046 nfound = 1;
1047 meta = 0;
1049 else
1051 stream = ((flags & GLOB_ALTDIRFUNC)
1052 ? (*pglob->gl_opendir) (directory)
1053 : (__ptr_t) opendir (directory));
1054 if (stream == NULL)
1056 if ((errfunc != NULL && (*errfunc) (directory, errno))
1057 || (flags & GLOB_ERR))
1058 return GLOB_ABORTED;
1059 nfound = 0;
1060 meta = 0;
1062 else
1064 int fnm_flags = ((!(flags & GLOB_PERIOD) ? FNM_PERIOD : 0)
1065 | ((flags & GLOB_NOESCAPE) ? FNM_NOESCAPE : 0)
1066 #if defined _AMIGA || defined VMS
1067 | FNM_CASEFOLD
1068 #endif
1070 nfound = 0;
1071 flags |= GLOB_MAGCHAR;
1073 while (1)
1075 const char *name;
1076 size_t len;
1077 struct dirent *d = ((flags & GLOB_ALTDIRFUNC)
1078 ? (*pglob->gl_readdir) (stream)
1079 : readdir ((DIR *) stream));
1080 if (d == NULL)
1081 break;
1082 if (! REAL_DIR_ENTRY (d))
1083 continue;
1085 #ifdef HAVE_D_TYPE
1086 /* If we shall match only directories use the information
1087 provided by the dirent call if possible. */
1088 if ((flags & GLOB_ONLYDIR)
1089 && d->d_type != DT_UNKNOWN && d->d_type != DT_DIR)
1090 continue;
1091 #endif
1093 name = d->d_name;
1095 if (fnmatch (pattern, name, fnm_flags) == 0)
1097 struct globlink *new = (struct globlink *)
1098 __alloca (sizeof (struct globlink));
1099 len = NAMLEN (d);
1100 new->name = (char *) malloc (len + 1);
1101 if (new->name == NULL)
1102 goto memory_error;
1103 #ifdef HAVE_MEMPCPY
1104 *((char *) mempcpy ((__ptr_t) new->name, name, len))
1105 = '\0';
1106 #else
1107 memcpy ((__ptr_t) new->name, name, len);
1108 new->name[len] = '\0';
1109 #endif
1110 new->next = names;
1111 names = new;
1112 ++nfound;
1119 if (nfound == 0 && (flags & GLOB_NOCHECK))
1121 size_t len = strlen (pattern);
1122 nfound = 1;
1123 names = (struct globlink *) __alloca (sizeof (struct globlink));
1124 names->next = NULL;
1125 names->name = (char *) malloc (len + 1);
1126 if (names->name == NULL)
1127 goto memory_error;
1128 #ifdef HAVE_MEMPCPY
1129 *((char *) mempcpy (names->name, pattern, len)) = '\0';
1130 #else
1131 memcpy (names->name, pattern, len);
1132 names->name[len] = '\0';
1133 #endif
1136 if (nfound != 0)
1138 pglob->gl_pathv
1139 = (char **) realloc (pglob->gl_pathv,
1140 (pglob->gl_pathc +
1141 ((flags & GLOB_DOOFFS) ? pglob->gl_offs : 0) +
1142 nfound + 1) *
1143 sizeof (char *));
1144 if (pglob->gl_pathv == NULL)
1145 goto memory_error;
1147 if (flags & GLOB_DOOFFS)
1148 while (pglob->gl_pathc < pglob->gl_offs)
1149 pglob->gl_pathv[pglob->gl_pathc++] = NULL;
1151 for (; names != NULL; names = names->next)
1152 pglob->gl_pathv[pglob->gl_pathc++] = names->name;
1153 pglob->gl_pathv[pglob->gl_pathc] = NULL;
1155 pglob->gl_flags = flags;
1158 save = errno;
1159 if (stream != NULL)
1160 if (flags & GLOB_ALTDIRFUNC)
1161 (*pglob->gl_closedir) (stream);
1162 else
1163 closedir ((DIR *) stream);
1164 __set_errno (save);
1166 return nfound == 0 ? GLOB_NOMATCH : 0;
1168 memory_error:
1170 int save = errno;
1171 if (flags & GLOB_ALTDIRFUNC)
1172 (*pglob->gl_closedir) (stream);
1173 else
1174 closedir ((DIR *) stream);
1175 __set_errno (save);
1177 while (names != NULL)
1179 if (names->name != NULL)
1180 free ((__ptr_t) names->name);
1181 names = names->next;
1183 return GLOB_NOSPACE;
1186 #endif /* Not ELIDE_CODE. */