]>
git.saurik.com Git - apple/libc.git/blob - gen/glob.c
273d6c92dc9253e732e0c8f52b72344bfed21310
2 * Copyright (c) 1999 Apple Computer, Inc. All rights reserved.
4 * @APPLE_LICENSE_HEADER_START@
6 * The contents of this file constitute Original Code as defined in and
7 * are subject to the Apple Public Source License Version 1.1 (the
8 * "License"). You may not use this file except in compliance with the
9 * License. Please obtain a copy of the License at
10 * http://www.apple.com/publicsource and read it before using this file.
12 * This Original Code and all software distributed under the License are
13 * distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY KIND, EITHER
14 * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES,
15 * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY,
16 * FITNESS FOR A PARTICULAR PURPOSE OR NON-INFRINGEMENT. Please see the
17 * License for the specific language governing rights and limitations
20 * @APPLE_LICENSE_HEADER_END@
23 * Copyright (c) 1989, 1993
24 * The Regents of the University of California. All rights reserved.
26 * This code is derived from software contributed to Berkeley by
29 * Redistribution and use in source and binary forms, with or without
30 * modification, are permitted provided that the following conditions
32 * 1. Redistributions of source code must retain the above copyright
33 * notice, this list of conditions and the following disclaimer.
34 * 2. Redistributions in binary form must reproduce the above copyright
35 * notice, this list of conditions and the following disclaimer in the
36 * documentation and/or other materials provided with the distribution.
37 * 3. All advertising materials mentioning features or use of this software
38 * must display the following acknowledgement:
39 * This product includes software developed by the University of
40 * California, Berkeley and its contributors.
41 * 4. Neither the name of the University nor the names of its contributors
42 * may be used to endorse or promote products derived from this software
43 * without specific prior written permission.
45 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
46 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
47 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
48 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
49 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
50 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
51 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
52 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
53 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
54 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
60 * glob(3) -- a superset of the one defined in POSIX 1003.2.
62 * The [!...] convention to negate a range is supported (SysV, Posix, ksh).
64 * Optional extra services, controlled by flags not defined by POSIX:
67 * Escaping convention: \ inhibits any special meaning the following
68 * character might have (except \ at end of string is retained).
70 * Set in gl_flags if pattern contained a globbing character.
72 * Same as GLOB_NOCHECK, but it will only append pattern if it did
73 * not contain any magic characters. [Used in csh style globbing]
75 * Use alternately specified directory access functions.
77 * expand ~user/foo to the /home/dir/of/user/foo
79 * expand {1,2}{a,b} to 1a 1b 2a 2b
81 * Number of matches in the current invocation of glob.
84 #include <sys/param.h>
109 #define UNDERSCORE '_'
117 #define M_QUOTE 0x8000
118 #define M_PROTECT 0x4000
119 #define M_MASK 0xffff
120 #define M_ASCII 0x00ff
122 typedef u_short Char
;
127 #define M_PROTECT 0x40
136 #define CHAR(c) ((Char)((c)&M_ASCII))
137 #define META(c) ((Char)((c)|M_QUOTE))
138 #define M_ALL META('*')
139 #define M_END META(']')
140 #define M_NOT META('!')
141 #define M_ONE META('?')
142 #define M_RNG META('-')
143 #define M_SET META('[')
144 #define ismeta(c) (((c)&M_QUOTE) != 0)
147 static int compare
__P((const void *, const void *));
148 static void g_Ctoc
__P((const Char
*, char *));
149 static int g_lstat
__P((Char
*, struct stat
*, glob_t
*));
150 static DIR *g_opendir
__P((Char
*, glob_t
*));
151 static Char
*g_strchr
__P((Char
*, int));
153 static Char
*g_strcat
__P((Char
*, const Char
*));
155 static int g_stat
__P((Char
*, struct stat
*, glob_t
*));
156 static int glob0
__P((const Char
*, glob_t
*));
157 static int glob1
__P((Char
*, glob_t
*));
158 static int glob2
__P((Char
*, Char
*, Char
*, glob_t
*));
159 static int glob3
__P((Char
*, Char
*, Char
*, Char
*, glob_t
*));
160 static int globextend
__P((const Char
*, glob_t
*));
161 static const Char
* globtilde
__P((const Char
*, Char
*, glob_t
*));
162 static int globexp1
__P((const Char
*, glob_t
*));
163 static int globexp2
__P((const Char
*, const Char
*, glob_t
*, int *));
164 static int match
__P((Char
*, Char
*, Char
*));
166 static void qprintf
__P((const char *, Char
*));
170 glob(pattern
, flags
, errfunc
, pglob
)
172 int flags
, (*errfunc
) __P((const char *, int));
175 const u_char
*patnext
;
177 Char
*bufnext
, *bufend
, patbuf
[MAXPATHLEN
+1];
179 patnext
= (u_char
*) pattern
;
180 if (!(flags
& GLOB_APPEND
)) {
182 pglob
->gl_pathv
= NULL
;
183 if (!(flags
& GLOB_DOOFFS
))
186 pglob
->gl_flags
= flags
& ~GLOB_MAGCHAR
;
187 pglob
->gl_errfunc
= errfunc
;
188 pglob
->gl_matchc
= 0;
191 bufend
= bufnext
+ MAXPATHLEN
;
192 if (flags
& GLOB_QUOTE
) {
193 /* Protect the quoted characters. */
194 while (bufnext
< bufend
&& (c
= *patnext
++) != EOS
)
196 if ((c
= *patnext
++) == EOS
) {
200 *bufnext
++ = c
| M_PROTECT
;
206 while (bufnext
< bufend
&& (c
= *patnext
++) != EOS
)
210 if (flags
& GLOB_BRACE
)
211 return globexp1(patbuf
, pglob
);
213 return glob0(patbuf
, pglob
);
217 * Expand recursively a glob {} pattern. When there is no more expansion
218 * invoke the standard globbing routine to glob the rest of the magic
221 static int globexp1(pattern
, pglob
)
225 const Char
* ptr
= pattern
;
228 /* Protect a single {}, for find(1), like csh */
229 if (pattern
[0] == LBRACE
&& pattern
[1] == RBRACE
&& pattern
[2] == EOS
)
230 return glob0(pattern
, pglob
);
232 while ((ptr
= (const Char
*) g_strchr((Char
*) ptr
, LBRACE
)) != NULL
)
233 if (!globexp2(ptr
, pattern
, pglob
, &rv
))
236 return glob0(pattern
, pglob
);
241 * Recursive brace globbing helper. Tries to expand a single brace.
242 * If it succeeds then it invokes globexp1 with the new pattern.
243 * If it fails then it tries to glob the rest of the pattern and returns.
245 static int globexp2(ptr
, pattern
, pglob
, rv
)
246 const Char
*ptr
, *pattern
;
252 const Char
*pe
, *pm
, *pl
;
253 Char patbuf
[MAXPATHLEN
+ 1];
255 /* copy part up to the brace */
256 for (lm
= patbuf
, pm
= pattern
; pm
!= ptr
; *lm
++ = *pm
++)
260 /* Find the balanced brace */
261 for (i
= 0, pe
= ++ptr
; *pe
; pe
++)
262 if (*pe
== LBRACKET
) {
263 /* Ignore everything between [] */
264 for (pm
= pe
++; *pe
!= RBRACKET
&& *pe
!= EOS
; pe
++)
268 * We could not find a matching RBRACKET.
269 * Ignore and just look for RBRACE
274 else if (*pe
== LBRACE
)
276 else if (*pe
== RBRACE
) {
282 /* Non matching braces; just glob the pattern */
283 if (i
!= 0 || *pe
== EOS
) {
284 *rv
= glob0(patbuf
, pglob
);
288 for (i
= 0, pl
= pm
= ptr
; pm
<= pe
; pm
++)
291 /* Ignore everything between [] */
292 for (pl
= pm
++; *pm
!= RBRACKET
&& *pm
!= EOS
; pm
++)
296 * We could not find a matching RBRACKET.
297 * Ignore and just look for RBRACE
314 if (i
&& *pm
== COMMA
)
317 /* Append the current string */
318 for (lm
= ls
; (pl
< pm
); *lm
++ = *pl
++)
321 * Append the rest of the pattern after the
324 for (pl
= pe
+ 1; (*lm
++ = *pl
++) != EOS
;)
327 /* Expand the current pattern */
329 qprintf("globexp2:", patbuf
);
331 *rv
= globexp1(patbuf
, pglob
);
333 /* move after the comma, to the next string */
348 * expand tilde from the passwd file.
351 globtilde(pattern
, patbuf
, pglob
)
361 if (*pattern
!= TILDE
|| !(pglob
->gl_flags
& GLOB_TILDE
))
364 /* Copy up to the end of the string or / */
365 for (p
= pattern
+ 1, h
= (char *) patbuf
; *p
&& *p
!= SLASH
;
371 if (((char *) patbuf
)[0] == EOS
) {
373 * handle a plain ~ or ~/ by expanding $HOME
374 * first and then trying the password file
376 if ((h
= getenv("HOME")) == NULL
) {
377 if ((pwd
= getpwuid(getuid())) == NULL
)
387 if ((pwd
= getpwnam((char*) patbuf
)) == NULL
)
393 /* Copy the home directory */
394 for (b
= patbuf
; *h
; *b
++ = *h
++)
397 /* Append the rest of the pattern */
398 while ((*b
++ = *p
++) != EOS
)
406 * The main glob() routine: compiles the pattern (optionally processing
407 * quotes), calls glob1() to do the real pattern matching, and finally
408 * sorts the list (unless unsorted operation is requested). Returns 0
409 * if things went well, nonzero if errors occurred. It is not an error
410 * to find no matches.
413 glob0(pattern
, pglob
)
417 const Char
*qpatnext
;
418 int c
, err
, oldpathc
;
419 Char
*bufnext
, patbuf
[MAXPATHLEN
+1];
421 qpatnext
= globtilde(pattern
, patbuf
, pglob
);
422 oldpathc
= pglob
->gl_pathc
;
425 /* We don't need to check for buffer overflow any more. */
426 while ((c
= *qpatnext
++) != EOS
) {
432 if (*qpatnext
== EOS
||
433 g_strchr((Char
*) qpatnext
+1, RBRACKET
) == NULL
) {
434 *bufnext
++ = LBRACKET
;
444 *bufnext
++ = CHAR(c
);
445 if (*qpatnext
== RANGE
&&
446 (c
= qpatnext
[1]) != RBRACKET
) {
448 *bufnext
++ = CHAR(c
);
451 } while ((c
= *qpatnext
++) != RBRACKET
);
452 pglob
->gl_flags
|= GLOB_MAGCHAR
;
456 pglob
->gl_flags
|= GLOB_MAGCHAR
;
460 pglob
->gl_flags
|= GLOB_MAGCHAR
;
461 /* collapse adjacent stars to one,
462 * to avoid exponential behavior
464 if (bufnext
== patbuf
|| bufnext
[-1] != M_ALL
)
468 *bufnext
++ = CHAR(c
);
474 qprintf("glob0:", patbuf
);
477 if ((err
= glob1(patbuf
, pglob
)) != 0)
481 * If there was no match we are going to append the pattern
482 * if GLOB_NOCHECK was specified or if GLOB_NOMAGIC was specified
483 * and the pattern did not contain any magic characters
484 * GLOB_NOMAGIC is there just for compatibility with csh.
486 if (pglob
->gl_pathc
== oldpathc
&&
487 ((pglob
->gl_flags
& GLOB_NOCHECK
) ||
488 ((pglob
->gl_flags
& GLOB_NOMAGIC
) &&
489 !(pglob
->gl_flags
& GLOB_MAGCHAR
))))
490 return(globextend(pattern
, pglob
));
491 else if (!(pglob
->gl_flags
& GLOB_NOSORT
))
492 qsort(pglob
->gl_pathv
+ pglob
->gl_offs
+ oldpathc
,
493 pglob
->gl_pathc
- oldpathc
, sizeof(char *), compare
);
501 return(strcmp(*(char **)p
, *(char **)q
));
505 glob1(pattern
, pglob
)
509 Char pathbuf
[MAXPATHLEN
+1];
511 /* A null pathname is invalid -- POSIX 1003.1 sect. 2.4. */
514 return(glob2(pathbuf
, pathbuf
, pattern
, pglob
));
518 * The functions glob2 and glob3 are mutually recursive; there is one level
519 * of recursion for each segment in the pattern that contains one or more
523 glob2(pathbuf
, pathend
, pattern
, pglob
)
524 Char
*pathbuf
, *pathend
, *pattern
;
532 * Loop over pattern segments until end of pattern or until
533 * segment with meta character found.
535 for (anymeta
= 0;;) {
536 if (*pattern
== EOS
) { /* End of pattern? */
538 if (g_lstat(pathbuf
, &sb
, pglob
))
541 if (((pglob
->gl_flags
& GLOB_MARK
) &&
542 pathend
[-1] != SEP
) && (S_ISDIR(sb
.st_mode
)
543 || (S_ISLNK(sb
.st_mode
) &&
544 (g_stat(pathbuf
, &sb
, pglob
) == 0) &&
545 S_ISDIR(sb
.st_mode
)))) {
550 return(globextend(pathbuf
, pglob
));
553 /* Find end of next segment, copy tentatively to pathend. */
556 while (*p
!= EOS
&& *p
!= SEP
) {
562 if (!anymeta
) { /* No expansion, do next segment. */
565 while (*pattern
== SEP
)
566 *pathend
++ = *pattern
++;
567 } else /* Need expansion, recurse. */
568 return(glob3(pathbuf
, pathend
, pattern
, p
, pglob
));
574 glob3(pathbuf
, pathend
, pattern
, restpattern
, pglob
)
575 Char
*pathbuf
, *pathend
, *pattern
, *restpattern
;
578 register struct dirent
*dp
;
581 char buf
[MAXPATHLEN
];
584 * The readdirfunc declaration can't be prototyped, because it is
585 * assigned, below, to two functions which are prototyped in glob.h
586 * and dirent.h as taking pointers to differently typed opaque
589 struct dirent
*(*readdirfunc
)();
594 if ((dirp
= g_opendir(pathbuf
, pglob
)) == NULL
) {
595 /* TODO: don't call for ENOENT or ENOTDIR? */
596 if (pglob
->gl_errfunc
) {
597 g_Ctoc(pathbuf
, buf
);
598 if (pglob
->gl_errfunc(buf
, errno
) ||
599 pglob
->gl_flags
& GLOB_ERR
)
607 /* Search directory for matching names. */
608 if (pglob
->gl_flags
& GLOB_ALTDIRFUNC
)
609 readdirfunc
= pglob
->gl_readdir
;
611 readdirfunc
= readdir
;
612 while ((dp
= (*readdirfunc
)(dirp
))) {
616 /* Initial DOT must be matched literally. */
617 if (dp
->d_name
[0] == DOT
&& *pattern
!= DOT
)
619 for (sc
= (u_char
*) dp
->d_name
, dc
= pathend
;
620 (*dc
++ = *sc
++) != EOS
;)
622 if (!match(pathend
, pattern
, restpattern
)) {
626 err
= glob2(pathbuf
, --dc
, restpattern
, pglob
);
631 if (pglob
->gl_flags
& GLOB_ALTDIRFUNC
)
632 (*pglob
->gl_closedir
)(dirp
);
640 * Extend the gl_pathv member of a glob_t structure to accomodate a new item,
641 * add the new item, and update gl_pathc.
643 * This assumes the BSD realloc, which only copies the block when its size
644 * crosses a power-of-two boundary; for v7 realloc, this would cause quadratic
647 * Return 0 if new item added, error code if memory couldn't be allocated.
649 * Invariant of the glob_t structure:
650 * Either gl_pathc is zero and gl_pathv is NULL; or gl_pathc > 0 and
651 * gl_pathv points to (gl_offs + gl_pathc + 1) items.
654 globextend(path
, pglob
)
658 register char **pathv
;
664 newsize
= sizeof(*pathv
) * (2 + pglob
->gl_pathc
+ pglob
->gl_offs
);
665 pathv
= pglob
->gl_pathv
?
666 realloc((char *)pglob
->gl_pathv
, newsize
) :
669 return(GLOB_NOSPACE
);
671 if (pglob
->gl_pathv
== NULL
&& pglob
->gl_offs
> 0) {
672 /* first time around -- clear initial gl_offs items */
673 pathv
+= pglob
->gl_offs
;
674 for (i
= pglob
->gl_offs
; --i
>= 0; )
677 pglob
->gl_pathv
= pathv
;
679 for (p
= path
; *p
++;)
681 if ((copy
= malloc(p
- path
)) != NULL
) {
683 pathv
[pglob
->gl_offs
+ pglob
->gl_pathc
++] = copy
;
685 pathv
[pglob
->gl_offs
+ pglob
->gl_pathc
] = NULL
;
686 return(copy
== NULL
? GLOB_NOSPACE
: 0);
691 * pattern matching function for filenames. Each occurrence of the *
692 * pattern causes a recursion level.
695 match(name
, pat
, patend
)
696 register Char
*name
, *pat
, *patend
;
698 int ok
, negate_range
;
701 while (pat
< patend
) {
703 switch (c
& M_MASK
) {
708 if (match(name
, pat
, patend
))
710 while (*name
++ != EOS
);
718 if ((k
= *name
++) == EOS
)
720 if ((negate_range
= ((*pat
& M_MASK
) == M_NOT
)) != EOS
)
722 while (((c
= *pat
++) & M_MASK
) != M_END
)
723 if ((*pat
& M_MASK
) == M_RNG
) {
724 if (c
<= k
&& k
<= pat
[1])
729 if (ok
== negate_range
)
738 return(*name
== EOS
);
741 /* Free allocated data belonging to a glob_t structure. */
749 if (pglob
->gl_pathv
!= NULL
) {
750 pp
= pglob
->gl_pathv
+ pglob
->gl_offs
;
751 for (i
= pglob
->gl_pathc
; i
--; ++pp
)
754 free(pglob
->gl_pathv
);
759 g_opendir(str
, pglob
)
763 char buf
[MAXPATHLEN
];
770 if (pglob
->gl_flags
& GLOB_ALTDIRFUNC
)
771 return((*pglob
->gl_opendir
)(buf
));
773 return(opendir(buf
));
777 g_lstat(fn
, sb
, pglob
)
782 char buf
[MAXPATHLEN
];
785 if (pglob
->gl_flags
& GLOB_ALTDIRFUNC
)
786 return((*pglob
->gl_lstat
)(buf
, sb
));
787 return(lstat(buf
, sb
));
791 g_stat(fn
, sb
, pglob
)
796 char buf
[MAXPATHLEN
];
799 if (pglob
->gl_flags
& GLOB_ALTDIRFUNC
)
800 return((*pglob
->gl_stat
)(buf
, sb
));
801 return(stat(buf
, sb
));
827 while((*dst
++ = *src
++) != EOS
)
836 register const Char
*str
;
841 for (dc
= buf
; (*dc
++ = *str
++) != EOS
;)
853 (void)printf("%s:\n", str
);
855 (void)printf("%c", CHAR(*p
));
858 (void)printf("%c", *p
& M_PROTECT
? '"' : ' ');
861 (void)printf("%c", ismeta(*p
) ? '_' : ' ');