]>
git.saurik.com Git - apple/libc.git/blob - gen/FreeBSD/glob.c
2 * Copyright (c) 1989, 1993
3 * The Regents of the University of California. All rights reserved.
5 * This code is derived from software contributed to Berkeley by
8 * Redistribution and use in source and binary forms, with or without
9 * modification, are permitted provided that the following conditions
11 * 1. Redistributions of source code must retain the above copyright
12 * notice, this list of conditions and the following disclaimer.
13 * 2. Redistributions in binary form must reproduce the above copyright
14 * notice, this list of conditions and the following disclaimer in the
15 * documentation and/or other materials provided with the distribution.
16 * 3. All advertising materials mentioning features or use of this software
17 * must display the following acknowledgement:
18 * This product includes software developed by the University of
19 * California, Berkeley and its contributors.
20 * 4. Neither the name of the University nor the names of its contributors
21 * may be used to endorse or promote products derived from this software
22 * without specific prior written permission.
24 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
25 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
26 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
27 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
28 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
29 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
30 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
31 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
32 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
33 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
37 #if defined(LIBC_SCCS) && !defined(lint)
38 static char sccsid
[] = "@(#)glob.c 8.3 (Berkeley) 10/13/93";
39 #endif /* LIBC_SCCS and not lint */
40 #include <sys/cdefs.h>
41 __FBSDID("$FreeBSD: src/lib/libc/gen/glob.c,v 1.22 2004/07/29 03:48:52 tjr Exp $");
44 * glob(3) -- a superset of the one defined in POSIX 1003.2.
46 * The [!...] convention to negate a range is supported (SysV, Posix, ksh).
48 * Optional extra services, controlled by flags not defined by POSIX:
51 * Escaping convention: \ inhibits any special meaning the following
52 * character might have (except \ at end of string is retained).
54 * Set in gl_flags if pattern contained a globbing character.
56 * Same as GLOB_NOCHECK, but it will only append pattern if it did
57 * not contain any magic characters. [Used in csh style globbing]
59 * Use alternately specified directory access functions.
61 * expand ~user/foo to the /home/dir/of/user/foo
63 * expand {1,2}{a,b} to 1a 1b 2a 2b
65 * Number of matches in the current invocation of glob.
69 * Some notes on multibyte character support:
70 * 1. Patterns with illegal byte sequences match nothing - even if
71 * GLOB_NOCHECK is specified.
72 * 2. Illegal byte sequences in filenames are handled by treating them as
73 * single-byte characters with a value of the first byte of the sequence
75 * 3. State-dependent encodings are not currently supported.
78 #include <sys/param.h>
108 #define UNDERSCORE '_'
116 #define M_QUOTE 0x8000000000ULL
117 #define M_PROTECT 0x4000000000ULL
118 #define M_MASK 0xffffffffffULL
119 #define M_CHAR 0x00ffffffffULL
121 typedef uint_fast64_t Char
;
126 #define M_PROTECT 0x40
135 #define CHAR(c) ((Char)((c)&M_CHAR))
136 #define META(c) ((Char)((c)|M_QUOTE))
137 #define M_ALL META('*')
138 #define M_END META(']')
139 #define M_NOT META('!')
140 #define M_ONE META('?')
141 #define M_RNG META('-')
142 #define M_SET META('[')
143 #define ismeta(c) (((c)&M_QUOTE) != 0)
146 static int compare(const void *, const void *);
147 static int g_Ctoc(const Char
*, char *, u_int
);
148 static int g_lstat(Char
*, struct stat
*, glob_t
*);
149 static DIR *g_opendir(Char
*, glob_t
*);
150 static Char
*g_strchr(Char
*, wchar_t);
152 static Char
*g_strcat(Char
*, const Char
*);
154 static int g_stat(Char
*, struct stat
*, glob_t
*);
155 static int glob0(const Char
*, glob_t
*, int *);
156 static int glob1(Char
*, glob_t
*, int *);
157 static int glob2(Char
*, Char
*, Char
*, Char
*, glob_t
*, int *);
158 static int glob3(Char
*, Char
*, Char
*, Char
*, Char
*, glob_t
*, int *);
159 static int globextend(const Char
*, glob_t
*, int *);
161 globtilde(const Char
*, Char
*, size_t, glob_t
*);
162 static int globexp1(const Char
*, glob_t
*, int *);
163 static int globexp2(const Char
*, const Char
*, glob_t
*, int *, int *);
164 static int match(Char
*, Char
*, Char
*);
166 static void qprintf(const char *, Char
*);
170 glob(pattern
, flags
, errfunc
, pglob
)
172 int flags
, (*errfunc
)(const char *, int);
175 const u_char
*patnext
;
177 Char
*bufnext
, *bufend
, patbuf
[MAXPATHLEN
], prot
;
182 patnext
= (u_char
*) pattern
;
183 if (!(flags
& GLOB_APPEND
)) {
185 pglob
->gl_pathv
= NULL
;
186 if (!(flags
& GLOB_DOOFFS
))
189 if (flags
& GLOB_LIMIT
) {
190 limit
= pglob
->gl_matchc
;
195 pglob
->gl_flags
= flags
& ~GLOB_MAGCHAR
;
196 pglob
->gl_errfunc
= errfunc
;
197 pglob
->gl_matchc
= 0;
200 bufend
= bufnext
+ MAXPATHLEN
- 1;
201 if (flags
& GLOB_NOESCAPE
) {
202 memset(&mbs
, 0, sizeof(mbs
));
203 while (bufend
- bufnext
>= MB_CUR_MAX
) {
204 clen
= mbrtowc(&wc
, patnext
, MB_LEN_MAX
, &mbs
);
205 if (clen
== (size_t)-1 || clen
== (size_t)-2)
206 return (GLOB_NOMATCH
);
213 /* Protect the quoted characters. */
214 memset(&mbs
, 0, sizeof(mbs
));
215 while (bufend
- bufnext
>= MB_CUR_MAX
) {
216 if (*patnext
== QUOTE
) {
217 if (*++patnext
== EOS
) {
218 *bufnext
++ = QUOTE
| M_PROTECT
;
224 clen
= mbrtowc(&wc
, patnext
, MB_LEN_MAX
, &mbs
);
225 if (clen
== (size_t)-1 || clen
== (size_t)-2)
226 return (GLOB_NOMATCH
);
229 *bufnext
++ = wc
| prot
;
235 if (flags
& GLOB_BRACE
)
236 return globexp1(patbuf
, pglob
, &limit
);
238 return glob0(patbuf
, pglob
, &limit
);
242 * Expand recursively a glob {} pattern. When there is no more expansion
243 * invoke the standard globbing routine to glob the rest of the magic
247 globexp1(pattern
, pglob
, limit
)
252 const Char
* ptr
= pattern
;
255 /* Protect a single {}, for find(1), like csh */
256 if (pattern
[0] == LBRACE
&& pattern
[1] == RBRACE
&& pattern
[2] == EOS
)
257 return glob0(pattern
, pglob
, limit
);
259 while ((ptr
= (const Char
*) g_strchr((Char
*) ptr
, LBRACE
)) != NULL
)
260 if (!globexp2(ptr
, pattern
, pglob
, &rv
, limit
))
263 return glob0(pattern
, pglob
, limit
);
268 * Recursive brace globbing helper. Tries to expand a single brace.
269 * If it succeeds then it invokes globexp1 with the new pattern.
270 * If it fails then it tries to glob the rest of the pattern and returns.
273 globexp2(ptr
, pattern
, pglob
, rv
, limit
)
274 const Char
*ptr
, *pattern
;
280 const Char
*pe
, *pm
, *pl
;
281 Char patbuf
[MAXPATHLEN
];
283 /* copy part up to the brace */
284 for (lm
= patbuf
, pm
= pattern
; pm
!= ptr
; *lm
++ = *pm
++)
289 /* Find the balanced brace */
290 for (i
= 0, pe
= ++ptr
; *pe
; pe
++)
291 if (*pe
== LBRACKET
) {
292 /* Ignore everything between [] */
293 for (pm
= pe
++; *pe
!= RBRACKET
&& *pe
!= EOS
; pe
++)
297 * We could not find a matching RBRACKET.
298 * Ignore and just look for RBRACE
303 else if (*pe
== LBRACE
)
305 else if (*pe
== RBRACE
) {
311 /* Non matching braces; just glob the pattern */
312 if (i
!= 0 || *pe
== EOS
) {
313 *rv
= glob0(patbuf
, pglob
, limit
);
317 for (i
= 0, pl
= pm
= ptr
; pm
<= pe
; pm
++)
320 /* Ignore everything between [] */
321 for (pl
= pm
++; *pm
!= RBRACKET
&& *pm
!= EOS
; pm
++)
325 * We could not find a matching RBRACKET.
326 * Ignore and just look for RBRACE
343 if (i
&& *pm
== COMMA
)
346 /* Append the current string */
347 for (lm
= ls
; (pl
< pm
); *lm
++ = *pl
++)
350 * Append the rest of the pattern after the
353 for (pl
= pe
+ 1; (*lm
++ = *pl
++) != EOS
;)
356 /* Expand the current pattern */
358 qprintf("globexp2:", patbuf
);
360 *rv
= globexp1(patbuf
, pglob
, limit
);
362 /* move after the comma, to the next string */
377 * expand tilde from the passwd file.
380 globtilde(pattern
, patbuf
, patbuf_len
, pglob
)
391 if (*pattern
!= TILDE
|| !(pglob
->gl_flags
& GLOB_TILDE
))
395 * Copy up to the end of the string or /
397 eb
= &patbuf
[patbuf_len
- 1];
398 for (p
= pattern
+ 1, h
= (char *) patbuf
;
399 h
< (char *)eb
&& *p
&& *p
!= SLASH
; *h
++ = *p
++)
404 if (((char *) patbuf
)[0] == EOS
) {
406 * handle a plain ~ or ~/ by expanding $HOME first (iff
407 * we're not running setuid or setgid) and then trying
410 if (issetugid() != 0 ||
411 (h
= getenv("HOME")) == NULL
) {
412 if (((h
= getlogin()) != NULL
&&
413 (pwd
= getpwnam(h
)) != NULL
) ||
414 (pwd
= getpwuid(getuid())) != NULL
)
424 if ((pwd
= getpwnam((char*) patbuf
)) == NULL
)
430 /* Copy the home directory */
431 for (b
= patbuf
; b
< eb
&& *h
; *b
++ = *h
++)
434 /* Append the rest of the pattern */
435 while (b
< eb
&& (*b
++ = *p
++) != EOS
)
444 * The main glob() routine: compiles the pattern (optionally processing
445 * quotes), calls glob1() to do the real pattern matching, and finally
446 * sorts the list (unless unsorted operation is requested). Returns 0
447 * if things went well, nonzero if errors occurred.
450 glob0(pattern
, pglob
, limit
)
455 const Char
*qpatnext
;
456 int c
, err
, oldpathc
;
457 Char
*bufnext
, patbuf
[MAXPATHLEN
];
459 qpatnext
= globtilde(pattern
, patbuf
, MAXPATHLEN
, pglob
);
460 oldpathc
= pglob
->gl_pathc
;
463 /* We don't need to check for buffer overflow any more. */
464 while ((c
= *qpatnext
++) != EOS
) {
470 if (*qpatnext
== EOS
||
471 g_strchr((Char
*) qpatnext
+1, RBRACKET
) == NULL
) {
472 *bufnext
++ = LBRACKET
;
482 *bufnext
++ = CHAR(c
);
483 if (*qpatnext
== RANGE
&&
484 (c
= qpatnext
[1]) != RBRACKET
) {
486 *bufnext
++ = CHAR(c
);
489 } while ((c
= *qpatnext
++) != RBRACKET
);
490 pglob
->gl_flags
|= GLOB_MAGCHAR
;
494 pglob
->gl_flags
|= GLOB_MAGCHAR
;
498 pglob
->gl_flags
|= GLOB_MAGCHAR
;
499 /* collapse adjacent stars to one,
500 * to avoid exponential behavior
502 if (bufnext
== patbuf
|| bufnext
[-1] != M_ALL
)
506 *bufnext
++ = CHAR(c
);
512 qprintf("glob0:", patbuf
);
515 if ((err
= glob1(patbuf
, pglob
, limit
)) != 0)
519 * If there was no match we are going to append the pattern
520 * if GLOB_NOCHECK was specified or if GLOB_NOMAGIC was specified
521 * and the pattern did not contain any magic characters
522 * GLOB_NOMAGIC is there just for compatibility with csh.
524 if (pglob
->gl_pathc
== oldpathc
) {
525 if (((pglob
->gl_flags
& GLOB_NOCHECK
) ||
526 ((pglob
->gl_flags
& GLOB_NOMAGIC
) &&
527 !(pglob
->gl_flags
& GLOB_MAGCHAR
))))
528 return(globextend(pattern
, pglob
, limit
));
530 return(GLOB_NOMATCH
);
532 if (!(pglob
->gl_flags
& GLOB_NOSORT
))
533 qsort(pglob
->gl_pathv
+ pglob
->gl_offs
+ oldpathc
,
534 pglob
->gl_pathc
- oldpathc
, sizeof(char *), compare
);
542 return(strcmp(*(char **)p
, *(char **)q
));
546 glob1(pattern
, pglob
, limit
)
551 Char pathbuf
[MAXPATHLEN
];
553 /* A null pathname is invalid -- POSIX 1003.1 sect. 2.4. */
556 return(glob2(pathbuf
, pathbuf
, pathbuf
+ MAXPATHLEN
- 1,
557 pattern
, pglob
, limit
));
561 * The functions glob2 and glob3 are mutually recursive; there is one level
562 * of recursion for each segment in the pattern that contains one or more
566 glob2(pathbuf
, pathend
, pathend_last
, pattern
, pglob
, limit
)
567 Char
*pathbuf
, *pathend
, *pathend_last
, *pattern
;
576 * Loop over pattern segments until end of pattern or until
577 * segment with meta character found.
579 for (anymeta
= 0;;) {
580 if (*pattern
== EOS
) { /* End of pattern? */
582 if (g_lstat(pathbuf
, &sb
, pglob
))
585 if (((pglob
->gl_flags
& GLOB_MARK
) &&
586 pathend
[-1] != SEP
) && (S_ISDIR(sb
.st_mode
)
587 || (S_ISLNK(sb
.st_mode
) &&
588 (g_stat(pathbuf
, &sb
, pglob
) == 0) &&
589 S_ISDIR(sb
.st_mode
)))) {
590 if (pathend
+ 1 > pathend_last
)
591 return (GLOB_ABORTED
);
596 return(globextend(pathbuf
, pglob
, limit
));
599 /* Find end of next segment, copy tentatively to pathend. */
602 while (*p
!= EOS
&& *p
!= SEP
) {
605 if (q
+ 1 > pathend_last
)
606 return (GLOB_ABORTED
);
610 if (!anymeta
) { /* No expansion, do next segment. */
613 while (*pattern
== SEP
) {
614 if (pathend
+ 1 > pathend_last
)
615 return (GLOB_ABORTED
);
616 *pathend
++ = *pattern
++;
618 } else /* Need expansion, recurse. */
619 return(glob3(pathbuf
, pathend
, pathend_last
, pattern
, p
,
626 glob3(pathbuf
, pathend
, pathend_last
, pattern
, restpattern
, pglob
, limit
)
627 Char
*pathbuf
, *pathend
, *pathend_last
, *pattern
, *restpattern
;
634 char buf
[MAXPATHLEN
];
637 * The readdirfunc declaration can't be prototyped, because it is
638 * assigned, below, to two functions which are prototyped in glob.h
639 * and dirent.h as taking pointers to differently typed opaque
642 struct dirent
*(*readdirfunc
)();
644 if (pathend
> pathend_last
)
645 return (GLOB_ABORTED
);
649 if ((dirp
= g_opendir(pathbuf
, pglob
)) == NULL
) {
650 /* TODO: don't call for ENOENT or ENOTDIR? */
651 if (pglob
->gl_errfunc
) {
652 if (g_Ctoc(pathbuf
, buf
, sizeof(buf
)))
653 return (GLOB_ABORTED
);
654 if (pglob
->gl_errfunc(buf
, errno
) ||
655 pglob
->gl_flags
& GLOB_ERR
)
656 return (GLOB_ABORTED
);
663 /* Search directory for matching names. */
664 if (pglob
->gl_flags
& GLOB_ALTDIRFUNC
)
665 readdirfunc
= pglob
->gl_readdir
;
667 readdirfunc
= readdir
;
668 while ((dp
= (*readdirfunc
)(dirp
))) {
675 /* Initial DOT must be matched literally. */
676 if (dp
->d_name
[0] == DOT
&& *pattern
!= DOT
)
678 memset(&mbs
, 0, sizeof(mbs
));
680 sc
= (u_char
*) dp
->d_name
;
681 while (dc
< pathend_last
) {
682 clen
= mbrtowc(&wc
, sc
, MB_LEN_MAX
, &mbs
);
683 if (clen
== (size_t)-1 || clen
== (size_t)-2) {
686 memset(&mbs
, 0, sizeof(mbs
));
688 if ((*dc
++ = wc
) == EOS
)
692 if (!match(pathend
, pattern
, restpattern
)) {
696 err
= glob2(pathbuf
, --dc
, pathend_last
, restpattern
,
702 if (pglob
->gl_flags
& GLOB_ALTDIRFUNC
)
703 (*pglob
->gl_closedir
)(dirp
);
711 * Extend the gl_pathv member of a glob_t structure to accomodate a new item,
712 * add the new item, and update gl_pathc.
714 * This assumes the BSD realloc, which only copies the block when its size
715 * crosses a power-of-two boundary; for v7 realloc, this would cause quadratic
718 * Return 0 if new item added, error code if memory couldn't be allocated.
720 * Invariant of the glob_t structure:
721 * Either gl_pathc is zero and gl_pathv is NULL; or gl_pathc > 0 and
722 * gl_pathv points to (gl_offs + gl_pathc + 1) items.
725 globextend(path
, pglob
, limit
)
736 if (*limit
&& pglob
->gl_pathc
> *limit
) {
738 return (GLOB_NOSPACE
);
741 newsize
= sizeof(*pathv
) * (2 + pglob
->gl_pathc
+ pglob
->gl_offs
);
742 pathv
= pglob
->gl_pathv
?
743 realloc((char *)pglob
->gl_pathv
, newsize
) :
746 if (pglob
->gl_pathv
) {
747 free(pglob
->gl_pathv
);
748 pglob
->gl_pathv
= NULL
;
750 return(GLOB_NOSPACE
);
753 if (pglob
->gl_pathv
== NULL
&& pglob
->gl_offs
> 0) {
754 /* first time around -- clear initial gl_offs items */
755 pathv
+= pglob
->gl_offs
;
756 for (i
= pglob
->gl_offs
; --i
>= 0; )
759 pglob
->gl_pathv
= pathv
;
761 for (p
= path
; *p
++;)
763 len
= MB_CUR_MAX
* (size_t)(p
- path
); /* XXX overallocation */
764 if ((copy
= malloc(len
)) != NULL
) {
765 if (g_Ctoc(path
, copy
, len
)) {
767 return (GLOB_NOSPACE
);
769 pathv
[pglob
->gl_offs
+ pglob
->gl_pathc
++] = copy
;
771 pathv
[pglob
->gl_offs
+ pglob
->gl_pathc
] = NULL
;
772 return(copy
== NULL
? GLOB_NOSPACE
: 0);
776 * pattern matching function for filenames. Each occurrence of the *
777 * pattern causes a recursion level.
780 match(name
, pat
, patend
)
781 Char
*name
, *pat
, *patend
;
783 int ok
, negate_range
;
786 while (pat
< patend
) {
788 switch (c
& M_MASK
) {
793 if (match(name
, pat
, patend
))
795 while (*name
++ != EOS
);
803 if ((k
= *name
++) == EOS
)
805 if ((negate_range
= ((*pat
& M_MASK
) == M_NOT
)) != EOS
)
807 while (((c
= *pat
++) & M_MASK
) != M_END
)
808 if ((*pat
& M_MASK
) == M_RNG
) {
809 if (__collate_load_error
?
810 CHAR(c
) <= CHAR(k
) && CHAR(k
) <= CHAR(pat
[1]) :
811 __collate_range_cmp(CHAR(c
), CHAR(k
)) <= 0
812 && __collate_range_cmp(CHAR(k
), CHAR(pat
[1])) <= 0
818 if (ok
== negate_range
)
827 return(*name
== EOS
);
830 /* Free allocated data belonging to a glob_t structure. */
838 if (pglob
->gl_pathv
!= NULL
) {
839 pp
= pglob
->gl_pathv
+ pglob
->gl_offs
;
840 for (i
= pglob
->gl_pathc
; i
--; ++pp
)
843 free(pglob
->gl_pathv
);
844 pglob
->gl_pathv
= NULL
;
849 g_opendir(str
, pglob
)
853 char buf
[MAXPATHLEN
];
858 if (g_Ctoc(str
, buf
, sizeof(buf
)))
862 if (pglob
->gl_flags
& GLOB_ALTDIRFUNC
)
863 return((*pglob
->gl_opendir
)(buf
));
865 return(opendir(buf
));
869 g_lstat(fn
, sb
, pglob
)
874 char buf
[MAXPATHLEN
];
876 if (g_Ctoc(fn
, buf
, sizeof(buf
))) {
877 errno
= ENAMETOOLONG
;
880 if (pglob
->gl_flags
& GLOB_ALTDIRFUNC
)
881 return((*pglob
->gl_lstat
)(buf
, sb
));
882 return(lstat(buf
, sb
));
886 g_stat(fn
, sb
, pglob
)
891 char buf
[MAXPATHLEN
];
893 if (g_Ctoc(fn
, buf
, sizeof(buf
))) {
894 errno
= ENAMETOOLONG
;
897 if (pglob
->gl_flags
& GLOB_ALTDIRFUNC
)
898 return((*pglob
->gl_stat
)(buf
, sb
));
899 return(stat(buf
, sb
));
915 g_Ctoc(str
, buf
, len
)
923 memset(&mbs
, 0, sizeof(mbs
));
924 while (len
>= MB_CUR_MAX
) {
925 clen
= wcrtomb(buf
, *str
, &mbs
);
926 if (clen
== (size_t)-1)
945 (void)printf("%s:\n", str
);
947 (void)printf("%c", CHAR(*p
));
950 (void)printf("%c", *p
& M_PROTECT
? '"' : ' ');
953 (void)printf("%c", ismeta(*p
) ? '_' : ' ');