]>
git.saurik.com Git - apple/libc.git/blob - gen/glob.c
2 * Copyright (c) 1999 Apple Computer, Inc. All rights reserved.
4 * @APPLE_LICENSE_HEADER_START@
6 * Copyright (c) 1999-2003 Apple Computer, Inc. All Rights Reserved.
8 * This file contains Original Code and/or Modifications of Original Code
9 * as defined in and that are subject to the Apple Public Source License
10 * Version 2.0 (the 'License'). You may not use this file except in
11 * compliance with the License. Please obtain a copy of the License at
12 * http://www.opensource.apple.com/apsl/ and read it before using this
15 * The Original Code and all software distributed under the License are
16 * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER
17 * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES,
18 * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY,
19 * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT.
20 * Please see the License for the specific language governing rights and
21 * limitations under the License.
23 * @APPLE_LICENSE_HEADER_END@
26 * Copyright (c) 1989, 1993
27 * The Regents of the University of California. All rights reserved.
29 * This code is derived from software contributed to Berkeley by
32 * Redistribution and use in source and binary forms, with or without
33 * modification, are permitted provided that the following conditions
35 * 1. Redistributions of source code must retain the above copyright
36 * notice, this list of conditions and the following disclaimer.
37 * 2. Redistributions in binary form must reproduce the above copyright
38 * notice, this list of conditions and the following disclaimer in the
39 * documentation and/or other materials provided with the distribution.
40 * 3. All advertising materials mentioning features or use of this software
41 * must display the following acknowledgement:
42 * This product includes software developed by the University of
43 * California, Berkeley and its contributors.
44 * 4. Neither the name of the University nor the names of its contributors
45 * may be used to endorse or promote products derived from this software
46 * without specific prior written permission.
48 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
49 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
50 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
51 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
52 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
53 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
54 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
55 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
56 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
57 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
63 * glob(3) -- a superset of the one defined in POSIX 1003.2.
65 * The [!...] convention to negate a range is supported (SysV, Posix, ksh).
67 * Optional extra services, controlled by flags not defined by POSIX:
70 * Escaping convention: \ inhibits any special meaning the following
71 * character might have (except \ at end of string is retained).
73 * Set in gl_flags if pattern contained a globbing character.
75 * Same as GLOB_NOCHECK, but it will only append pattern if it did
76 * not contain any magic characters. [Used in csh style globbing]
78 * Use alternately specified directory access functions.
80 * expand ~user/foo to the /home/dir/of/user/foo
82 * expand {1,2}{a,b} to 1a 1b 2a 2b
84 * Number of matches in the current invocation of glob.
87 #include <sys/param.h>
112 #define UNDERSCORE '_'
120 #define M_QUOTE 0x8000
121 #define M_PROTECT 0x4000
122 #define M_MASK 0xffff
123 #define M_ASCII 0x00ff
125 typedef u_short Char
;
130 #define M_PROTECT 0x40
139 #define CHAR(c) ((Char)((c)&M_ASCII))
140 #define META(c) ((Char)((c)|M_QUOTE))
141 #define M_ALL META('*')
142 #define M_END META(']')
143 #define M_NOT META('!')
144 #define M_ONE META('?')
145 #define M_RNG META('-')
146 #define M_SET META('[')
147 #define ismeta(c) (((c)&M_QUOTE) != 0)
150 static int compare
__P((const void *, const void *));
151 static void g_Ctoc
__P((const Char
*, char *));
152 static int g_lstat
__P((Char
*, struct stat
*, glob_t
*));
153 static DIR *g_opendir
__P((Char
*, glob_t
*));
154 static Char
*g_strchr
__P((Char
*, int));
156 static Char
*g_strcat
__P((Char
*, const Char
*));
158 static int g_stat
__P((Char
*, struct stat
*, glob_t
*));
159 static int glob0
__P((const Char
*, glob_t
*));
160 static int glob1
__P((Char
*, glob_t
*));
161 static int glob2
__P((Char
*, Char
*, Char
*, glob_t
*));
162 static int glob3
__P((Char
*, Char
*, Char
*, Char
*, glob_t
*));
163 static int globextend
__P((const Char
*, glob_t
*));
164 static const Char
* globtilde
__P((const Char
*, Char
*, glob_t
*));
165 static int globexp1
__P((const Char
*, glob_t
*));
166 static int globexp2
__P((const Char
*, const Char
*, glob_t
*, int *));
167 static int match
__P((Char
*, Char
*, Char
*));
169 static void qprintf
__P((const char *, Char
*));
173 glob(pattern
, flags
, errfunc
, pglob
)
175 int flags
, (*errfunc
) __P((const char *, int));
178 const u_char
*patnext
;
180 Char
*bufnext
, *bufend
, patbuf
[MAXPATHLEN
+1];
182 patnext
= (u_char
*) pattern
;
183 if (!(flags
& GLOB_APPEND
)) {
185 pglob
->gl_pathv
= NULL
;
186 if (!(flags
& GLOB_DOOFFS
))
189 pglob
->gl_flags
= flags
& ~GLOB_MAGCHAR
;
190 pglob
->gl_errfunc
= errfunc
;
191 pglob
->gl_matchc
= 0;
194 bufend
= bufnext
+ MAXPATHLEN
;
195 if (flags
& GLOB_QUOTE
) {
196 /* Protect the quoted characters. */
197 while (bufnext
< bufend
&& (c
= *patnext
++) != EOS
)
199 if ((c
= *patnext
++) == EOS
) {
203 *bufnext
++ = c
| M_PROTECT
;
209 while (bufnext
< bufend
&& (c
= *patnext
++) != EOS
)
213 if (flags
& GLOB_BRACE
)
214 return globexp1(patbuf
, pglob
);
216 return glob0(patbuf
, pglob
);
220 * Expand recursively a glob {} pattern. When there is no more expansion
221 * invoke the standard globbing routine to glob the rest of the magic
224 static int globexp1(pattern
, pglob
)
228 const Char
* ptr
= pattern
;
231 /* Protect a single {}, for find(1), like csh */
232 if (pattern
[0] == LBRACE
&& pattern
[1] == RBRACE
&& pattern
[2] == EOS
)
233 return glob0(pattern
, pglob
);
235 while ((ptr
= (const Char
*) g_strchr((Char
*) ptr
, LBRACE
)) != NULL
)
236 if (!globexp2(ptr
, pattern
, pglob
, &rv
))
239 return glob0(pattern
, pglob
);
244 * Recursive brace globbing helper. Tries to expand a single brace.
245 * If it succeeds then it invokes globexp1 with the new pattern.
246 * If it fails then it tries to glob the rest of the pattern and returns.
248 static int globexp2(ptr
, pattern
, pglob
, rv
)
249 const Char
*ptr
, *pattern
;
255 const Char
*pe
, *pm
, *pl
;
256 Char patbuf
[MAXPATHLEN
+ 1];
258 /* copy part up to the brace */
259 for (lm
= patbuf
, pm
= pattern
; pm
!= ptr
; *lm
++ = *pm
++)
263 /* Find the balanced brace */
264 for (i
= 0, pe
= ++ptr
; *pe
; pe
++)
265 if (*pe
== LBRACKET
) {
266 /* Ignore everything between [] */
267 for (pm
= pe
++; *pe
!= RBRACKET
&& *pe
!= EOS
; pe
++)
271 * We could not find a matching RBRACKET.
272 * Ignore and just look for RBRACE
277 else if (*pe
== LBRACE
)
279 else if (*pe
== RBRACE
) {
285 /* Non matching braces; just glob the pattern */
286 if (i
!= 0 || *pe
== EOS
) {
287 *rv
= glob0(patbuf
, pglob
);
291 for (i
= 0, pl
= pm
= ptr
; pm
<= pe
; pm
++)
294 /* Ignore everything between [] */
295 for (pl
= pm
++; *pm
!= RBRACKET
&& *pm
!= EOS
; pm
++)
299 * We could not find a matching RBRACKET.
300 * Ignore and just look for RBRACE
317 if (i
&& *pm
== COMMA
)
320 /* Append the current string */
321 for (lm
= ls
; (pl
< pm
); *lm
++ = *pl
++)
324 * Append the rest of the pattern after the
327 for (pl
= pe
+ 1; (*lm
++ = *pl
++) != EOS
;)
330 /* Expand the current pattern */
332 qprintf("globexp2:", patbuf
);
334 *rv
= globexp1(patbuf
, pglob
);
336 /* move after the comma, to the next string */
351 * expand tilde from the passwd file.
354 globtilde(pattern
, patbuf
, pglob
)
364 if (*pattern
!= TILDE
|| !(pglob
->gl_flags
& GLOB_TILDE
))
367 /* Copy up to the end of the string or / */
368 for (p
= pattern
+ 1, h
= (char *) patbuf
; *p
&& *p
!= SLASH
;
374 if (((char *) patbuf
)[0] == EOS
) {
376 * handle a plain ~ or ~/ by expanding $HOME
377 * first and then trying the password file
379 if ((h
= getenv("HOME")) == NULL
) {
380 if ((pwd
= getpwuid(getuid())) == NULL
)
390 if ((pwd
= getpwnam((char*) patbuf
)) == NULL
)
396 /* Copy the home directory */
397 for (b
= patbuf
; *h
; *b
++ = *h
++)
400 /* Append the rest of the pattern */
401 while ((*b
++ = *p
++) != EOS
)
409 * The main glob() routine: compiles the pattern (optionally processing
410 * quotes), calls glob1() to do the real pattern matching, and finally
411 * sorts the list (unless unsorted operation is requested). Returns 0
412 * if things went well, nonzero if errors occurred. It is not an error
413 * to find no matches.
416 glob0(pattern
, pglob
)
420 const Char
*qpatnext
;
421 int c
, err
, oldpathc
;
422 Char
*bufnext
, patbuf
[MAXPATHLEN
+1];
424 qpatnext
= globtilde(pattern
, patbuf
, pglob
);
425 oldpathc
= pglob
->gl_pathc
;
428 /* We don't need to check for buffer overflow any more. */
429 while ((c
= *qpatnext
++) != EOS
) {
435 if (*qpatnext
== EOS
||
436 g_strchr((Char
*) qpatnext
+1, RBRACKET
) == NULL
) {
437 *bufnext
++ = LBRACKET
;
447 *bufnext
++ = CHAR(c
);
448 if (*qpatnext
== RANGE
&&
449 (c
= qpatnext
[1]) != RBRACKET
) {
451 *bufnext
++ = CHAR(c
);
454 } while ((c
= *qpatnext
++) != RBRACKET
);
455 pglob
->gl_flags
|= GLOB_MAGCHAR
;
459 pglob
->gl_flags
|= GLOB_MAGCHAR
;
463 pglob
->gl_flags
|= GLOB_MAGCHAR
;
464 /* collapse adjacent stars to one,
465 * to avoid exponential behavior
467 if (bufnext
== patbuf
|| bufnext
[-1] != M_ALL
)
471 *bufnext
++ = CHAR(c
);
477 qprintf("glob0:", patbuf
);
480 if ((err
= glob1(patbuf
, pglob
)) != 0)
484 * If there was no match we are going to append the pattern
485 * if GLOB_NOCHECK was specified or if GLOB_NOMAGIC was specified
486 * and the pattern did not contain any magic characters
487 * GLOB_NOMAGIC is there just for compatibility with csh.
489 if (pglob
->gl_pathc
== oldpathc
&&
490 ((pglob
->gl_flags
& GLOB_NOCHECK
) ||
491 ((pglob
->gl_flags
& GLOB_NOMAGIC
) &&
492 !(pglob
->gl_flags
& GLOB_MAGCHAR
))))
493 return(globextend(pattern
, pglob
));
494 else if (!(pglob
->gl_flags
& GLOB_NOSORT
))
495 qsort(pglob
->gl_pathv
+ pglob
->gl_offs
+ oldpathc
,
496 pglob
->gl_pathc
- oldpathc
, sizeof(char *), compare
);
504 return(strcmp(*(char **)p
, *(char **)q
));
508 glob1(pattern
, pglob
)
512 Char pathbuf
[MAXPATHLEN
+1];
514 /* A null pathname is invalid -- POSIX 1003.1 sect. 2.4. */
517 return(glob2(pathbuf
, pathbuf
, pattern
, pglob
));
521 * The functions glob2 and glob3 are mutually recursive; there is one level
522 * of recursion for each segment in the pattern that contains one or more
526 glob2(pathbuf
, pathend
, pattern
, pglob
)
527 Char
*pathbuf
, *pathend
, *pattern
;
535 * Loop over pattern segments until end of pattern or until
536 * segment with meta character found.
538 for (anymeta
= 0;;) {
539 if (*pattern
== EOS
) { /* End of pattern? */
541 if (g_lstat(pathbuf
, &sb
, pglob
))
544 if (((pglob
->gl_flags
& GLOB_MARK
) &&
545 pathend
[-1] != SEP
) && (S_ISDIR(sb
.st_mode
)
546 || (S_ISLNK(sb
.st_mode
) &&
547 (g_stat(pathbuf
, &sb
, pglob
) == 0) &&
548 S_ISDIR(sb
.st_mode
)))) {
553 return(globextend(pathbuf
, pglob
));
556 /* Find end of next segment, copy tentatively to pathend. */
559 while (*p
!= EOS
&& *p
!= SEP
) {
565 if (!anymeta
) { /* No expansion, do next segment. */
568 while (*pattern
== SEP
)
569 *pathend
++ = *pattern
++;
570 } else /* Need expansion, recurse. */
571 return(glob3(pathbuf
, pathend
, pattern
, p
, pglob
));
577 glob3(pathbuf
, pathend
, pattern
, restpattern
, pglob
)
578 Char
*pathbuf
, *pathend
, *pattern
, *restpattern
;
581 register struct dirent
*dp
;
584 char buf
[MAXPATHLEN
];
587 * The readdirfunc declaration can't be prototyped, because it is
588 * assigned, below, to two functions which are prototyped in glob.h
589 * and dirent.h as taking pointers to differently typed opaque
592 struct dirent
*(*readdirfunc
)();
597 if ((dirp
= g_opendir(pathbuf
, pglob
)) == NULL
) {
598 /* TODO: don't call for ENOENT or ENOTDIR? */
599 if (pglob
->gl_errfunc
) {
600 g_Ctoc(pathbuf
, buf
);
601 if (pglob
->gl_errfunc(buf
, errno
) ||
602 pglob
->gl_flags
& GLOB_ERR
)
610 /* Search directory for matching names. */
611 if (pglob
->gl_flags
& GLOB_ALTDIRFUNC
)
612 readdirfunc
= pglob
->gl_readdir
;
614 readdirfunc
= readdir
;
615 while ((dp
= (*readdirfunc
)(dirp
))) {
619 /* Initial DOT must be matched literally. */
620 if (dp
->d_name
[0] == DOT
&& *pattern
!= DOT
)
622 for (sc
= (u_char
*) dp
->d_name
, dc
= pathend
;
623 (*dc
++ = *sc
++) != EOS
;)
625 if (!match(pathend
, pattern
, restpattern
)) {
629 err
= glob2(pathbuf
, --dc
, restpattern
, pglob
);
634 if (pglob
->gl_flags
& GLOB_ALTDIRFUNC
)
635 (*pglob
->gl_closedir
)(dirp
);
643 * Extend the gl_pathv member of a glob_t structure to accomodate a new item,
644 * add the new item, and update gl_pathc.
646 * This assumes the BSD realloc, which only copies the block when its size
647 * crosses a power-of-two boundary; for v7 realloc, this would cause quadratic
650 * Return 0 if new item added, error code if memory couldn't be allocated.
652 * Invariant of the glob_t structure:
653 * Either gl_pathc is zero and gl_pathv is NULL; or gl_pathc > 0 and
654 * gl_pathv points to (gl_offs + gl_pathc + 1) items.
657 globextend(path
, pglob
)
661 register char **pathv
;
667 newsize
= sizeof(*pathv
) * (2 + pglob
->gl_pathc
+ pglob
->gl_offs
);
668 pathv
= pglob
->gl_pathv
?
669 realloc((char *)pglob
->gl_pathv
, newsize
) :
672 return(GLOB_NOSPACE
);
674 if (pglob
->gl_pathv
== NULL
&& pglob
->gl_offs
> 0) {
675 /* first time around -- clear initial gl_offs items */
676 pathv
+= pglob
->gl_offs
;
677 for (i
= pglob
->gl_offs
; --i
>= 0; )
680 pglob
->gl_pathv
= pathv
;
682 for (p
= path
; *p
++;)
684 if ((copy
= malloc(p
- path
)) != NULL
) {
686 pathv
[pglob
->gl_offs
+ pglob
->gl_pathc
++] = copy
;
688 pathv
[pglob
->gl_offs
+ pglob
->gl_pathc
] = NULL
;
689 return(copy
== NULL
? GLOB_NOSPACE
: 0);
694 * pattern matching function for filenames. Each occurrence of the *
695 * pattern causes a recursion level.
698 match(name
, pat
, patend
)
699 register Char
*name
, *pat
, *patend
;
701 int ok
, negate_range
;
704 while (pat
< patend
) {
706 switch (c
& M_MASK
) {
711 if (match(name
, pat
, patend
))
713 while (*name
++ != EOS
);
721 if ((k
= *name
++) == EOS
)
723 if ((negate_range
= ((*pat
& M_MASK
) == M_NOT
)) != EOS
)
725 while (((c
= *pat
++) & M_MASK
) != M_END
)
726 if ((*pat
& M_MASK
) == M_RNG
) {
727 if (c
<= k
&& k
<= pat
[1])
732 if (ok
== negate_range
)
741 return(*name
== EOS
);
744 /* Free allocated data belonging to a glob_t structure. */
752 if (pglob
->gl_pathv
!= NULL
) {
753 pp
= pglob
->gl_pathv
+ pglob
->gl_offs
;
754 for (i
= pglob
->gl_pathc
; i
--; ++pp
)
757 free(pglob
->gl_pathv
);
762 g_opendir(str
, pglob
)
766 char buf
[MAXPATHLEN
];
773 if (pglob
->gl_flags
& GLOB_ALTDIRFUNC
)
774 return((*pglob
->gl_opendir
)(buf
));
776 return(opendir(buf
));
780 g_lstat(fn
, sb
, pglob
)
785 char buf
[MAXPATHLEN
];
788 if (pglob
->gl_flags
& GLOB_ALTDIRFUNC
)
789 return((*pglob
->gl_lstat
)(buf
, sb
));
790 return(lstat(buf
, sb
));
794 g_stat(fn
, sb
, pglob
)
799 char buf
[MAXPATHLEN
];
802 if (pglob
->gl_flags
& GLOB_ALTDIRFUNC
)
803 return((*pglob
->gl_stat
)(buf
, sb
));
804 return(stat(buf
, sb
));
830 while((*dst
++ = *src
++) != EOS
)
839 register const Char
*str
;
844 for (dc
= buf
; (*dc
++ = *str
++) != EOS
;)
856 (void)printf("%s:\n", str
);
858 (void)printf("%c", CHAR(*p
));
861 (void)printf("%c", *p
& M_PROTECT
? '"' : ' ');
864 (void)printf("%c", ismeta(*p
) ? '_' : ' ');