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. Neither the name of the University nor the names of its contributors
17 * may be used to endorse or promote products derived from this software
18 * without specific prior written permission.
20 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
21 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
22 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
23 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
24 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
25 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
26 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
27 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
28 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
29 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
33 #if defined(LIBC_SCCS) && !defined(lint)
34 static char sccsid[] = "@(#)glob.c 8.3 (Berkeley) 10/13/93";
35 /* most changes between the version above and the one below have been ported:
36 static char sscsid[]= "$OpenBSD: glob.c,v 1.8.10.1 2001/04/10 jason Exp $";
38 #endif /* LIBC_SCCS and not lint */
41 * glob(3) -- a superset of the one defined in POSIX 1003.2.
43 * The [!...] convention to negate a range is supported (SysV, Posix, ksh).
45 * Optional extra services, controlled by flags not defined by POSIX:
48 * Escaping convention: \ inhibits any special meaning the following
49 * character might have (except \ at end of string is retained).
51 * Set in gl_flags if pattern contained a globbing character.
53 * Same as GLOB_NOCHECK, but it will only append pattern if it did
54 * not contain any magic characters. [Used in csh style globbing]
56 * Use alternately specified directory access functions.
58 * expand ~user/foo to the /home/dir/of/user/foo
60 * expand {1,2}{a,b} to 1a 1b 2a 2b
62 * Number of matches in the current invocation of glob.
64 * sort alphabetically like csh (case doesn't matter) instead of in ASCII
76 #if defined(HAS_PASSWD) && !defined(VMS)
77 struct passwd *getpwnam(char *);
78 struct passwd *getpwuid(Uid_t);
84 # define MAXPATHLEN PATH_MAX
85 # ifdef MACOS_TRADITIONAL
86 # define MAXPATHLEN 255
88 # define MAXPATHLEN 1024
98 # ifdef MACOS_TRADITIONAL
99 # define ARG_MAX 65536 /* Mac OS is actually unlimited */
102 # define ARG_MAX (sysconf(_SC_ARG_MAX))
104 # ifdef _POSIX_ARG_MAX
105 # define ARG_MAX _POSIX_ARG_MAX
108 # define ARG_MAX 14500 /* from VC's limits.h */
110 # define ARG_MAX 4096 /* from POSIX, be conservative */
117 #define BG_DOLLAR '$'
120 #define BG_LBRACKET '['
122 #define BG_QUESTION '?'
123 #define BG_QUOTE '\\'
125 #define BG_RBRACKET ']'
126 #ifdef MACOS_TRADITIONAL
136 #define BG_UNDERSCORE '_'
137 #define BG_LBRACE '{'
138 #define BG_RBRACE '}'
144 #define M_QUOTE 0x8000
145 #define M_PROTECT 0x4000
146 #define M_MASK 0xffff
147 #define M_ASCII 0x00ff
154 #define M_PROTECT 0x40
160 #endif /* !GLOB_DEBUG */
163 #define CHAR(c) ((Char)((c)&M_ASCII))
164 #define META(c) ((Char)((c)|M_QUOTE))
165 #define M_ALL META('*')
166 #define M_END META(']')
167 #define M_NOT META('!')
168 #define M_ONE META('?')
169 #define M_RNG META('-')
170 #define M_SET META('[')
171 #define ismeta(c) (((c)&M_QUOTE) != 0)
174 static int compare(const void *, const void *);
175 static int ci_compare(const void *, const void *);
176 static int g_Ctoc(const Char *, char *, STRLEN);
177 static int g_lstat(Char *, Stat_t *, glob_t *);
178 static DIR *g_opendir(Char *, glob_t *);
179 static Char *g_strchr(Char *, int);
180 static int g_stat(Char *, Stat_t *, glob_t *);
181 static int glob0(const Char *, glob_t *);
182 static int glob1(Char *, Char *, glob_t *, size_t *);
183 static int glob2(Char *, Char *, Char *, Char *, Char *, Char *,
185 static int glob3(Char *, Char *, Char *, Char *, Char *, Char *,
186 Char *, Char *, glob_t *, size_t *);
187 static int globextend(const Char *, glob_t *, size_t *);
189 globtilde(const Char *, Char *, size_t, glob_t *);
190 static int globexp1(const Char *, glob_t *);
191 static int globexp2(const Char *, const Char *, glob_t *, int *);
192 static int match(Char *, Char *, Char *, int);
194 static void qprintf(const char *, Char *);
195 #endif /* GLOB_DEBUG */
197 #ifdef PERL_IMPLICIT_CONTEXT
198 static Direntry_t * my_readdir(DIR*);
204 return PerlDir_read(d);
206 return (DIR *)PerlDir_read(d);
211 /* ReliantUNIX (OS formerly known as SINIX) defines readdir
212 * in LFS-mode to be a 64-bit version of readdir. */
215 static Direntry_t * my_readdir(DIR*);
224 # define my_readdir readdir
230 #ifdef MACOS_TRADITIONAL
235 #define NO_UPDIR_ERR 1 /* updir resolving failed */
237 static Boolean g_matchVol; /* global variable */
238 static short updir(char *path);
239 static short resolve_updirs(char *new_pattern);
240 static void remove_trColon(char *path);
241 static short glob_mark_Mac(Char *pathbuf, Char *pathend, Char *pathend_last);
242 static OSErr GetVolInfo(short volume, Boolean indexed, FSSpec *spec);
243 static void name_f_FSSpec(StrFileName volname, FSSpec *spec);
248 bsd_glob(const char *pattern, int flags,
249 int (*errfunc)(const char *, int), glob_t *pglob)
253 Char *bufnext, *bufend, patbuf[MAXPATHLEN];
255 #ifdef MACOS_TRADITIONAL
256 char *new_pat, *p, *np;
261 #ifndef MACOS_TRADITIONAL
262 patnext = (U8 *) pattern;
264 /* TODO: GLOB_APPEND / GLOB_DOOFFS aren't supported yet */
266 if (!(flags & GLOB_APPEND)) {
268 pglob->gl_pathv = NULL;
269 if (!(flags & GLOB_DOOFFS))
274 pglob->gl_pathv = NULL;
277 pglob->gl_flags = flags & ~GLOB_MAGCHAR;
278 pglob->gl_errfunc = errfunc;
279 pglob->gl_matchc = 0;
282 bufend = bufnext + MAXPATHLEN - 1;
284 /* Nasty hack to treat patterns like "C:*" correctly. In this
285 * case, the * should match any file in the current directory
286 * on the C: drive. However, the glob code does not treat the
287 * colon specially, so it looks for files beginning "C:" in
288 * the current directory. To fix this, change the pattern to
289 * add an explicit "./" at the start (just after the drive
290 * letter and colon - ie change to "C:./").
292 if (isalpha(pattern[0]) && pattern[1] == ':' &&
293 pattern[2] != BG_SEP && pattern[2] != BG_SEP2 &&
294 bufend - bufnext > 4) {
295 *bufnext++ = pattern[0];
303 #ifdef MACOS_TRADITIONAL
304 /* Check if we need to match a volume name (e.g. '*HD:*') */
306 p = (char *) pattern;
309 while (*p != BG_EOS) {
318 /* Transform the pattern:
319 * (a) Resolve updirs, e.g.
321 * ':a*:tmp::::' -> '::'
322 * ':base::t*p:::' -> '::'
323 * '*HD::' -> return 0 (error, quit silently)
325 * (b) Remove a single trailing ':', unless it's a "match volume only"
326 * pattern like '*HD:'; e.g.
327 * '*:tmp:' -> '*:tmp' but
329 * (If we don't do that, even filenames will have a trailing ':' in
333 /* We operate on a copy of the pattern */
334 len = strlen(pattern);
335 Newx(new_pat, len + 1, char);
337 return (GLOB_NOSPACE);
339 p = (char *) pattern;
341 while (*np++ = *p++) ;
343 /* Resolve updirs ... */
344 err = resolve_updirs(new_pat);
347 /* The pattern is incorrect: tried to move
348 up above the volume root, see above.
352 /* remove trailing colon ... */
353 remove_trColon(new_pat);
354 patnext = (U8 *) new_pat;
356 #endif /* MACOS_TRADITIONAL */
358 if (flags & GLOB_QUOTE) {
359 /* Protect the quoted characters. */
360 while (bufnext < bufend && (c = *patnext++) != BG_EOS)
363 /* To avoid backslashitis on Win32,
364 * we only treat \ as a quoting character
365 * if it precedes one of the
366 * metacharacters []-{}~\
368 if ((c = *patnext++) != '[' && c != ']' &&
369 c != '-' && c != '{' && c != '}' &&
370 c != '~' && c != '\\') {
372 if ((c = *patnext++) == BG_EOS) {
377 *bufnext++ = c | M_PROTECT;
381 while (bufnext < bufend && (c = *patnext++) != BG_EOS)
385 #ifdef MACOS_TRADITIONAL
386 if (flags & GLOB_BRACE)
387 err = globexp1(patbuf, pglob);
389 err = glob0(patbuf, pglob);
393 if (flags & GLOB_BRACE)
394 return globexp1(patbuf, pglob);
396 return glob0(patbuf, pglob);
401 * Expand recursively a glob {} pattern. When there is no more expansion
402 * invoke the standard globbing routine to glob the rest of the magic
406 globexp1(const Char *pattern, glob_t *pglob)
408 const Char* ptr = pattern;
411 /* Protect a single {}, for find(1), like csh */
412 if (pattern[0] == BG_LBRACE && pattern[1] == BG_RBRACE && pattern[2] == BG_EOS)
413 return glob0(pattern, pglob);
415 while ((ptr = (const Char *) g_strchr((Char *) ptr, BG_LBRACE)) != NULL)
416 if (!globexp2(ptr, pattern, pglob, &rv))
419 return glob0(pattern, pglob);
424 * Recursive brace globbing helper. Tries to expand a single brace.
425 * If it succeeds then it invokes globexp1 with the new pattern.
426 * If it fails then it tries to glob the rest of the pattern and returns.
429 globexp2(const Char *ptr, const Char *pattern,
430 glob_t *pglob, int *rv)
434 const Char *pe, *pm, *pm1, *pl;
435 Char patbuf[MAXPATHLEN];
437 /* copy part up to the brace */
438 for (lm = patbuf, pm = pattern; pm != ptr; *lm++ = *pm++)
443 /* Find the balanced brace */
444 for (i = 0, pe = ++ptr; *pe; pe++)
445 if (*pe == BG_LBRACKET) {
446 /* Ignore everything between [] */
447 for (pm = pe++; *pe != BG_RBRACKET && *pe != BG_EOS; pe++)
451 * We could not find a matching BG_RBRACKET.
452 * Ignore and just look for BG_RBRACE
456 } else if (*pe == BG_LBRACE)
458 else if (*pe == BG_RBRACE) {
464 /* Non matching braces; just glob the pattern */
465 if (i != 0 || *pe == BG_EOS) {
466 *rv = glob0(patbuf, pglob);
470 for (i = 0, pl = pm = ptr; pm <= pe; pm++) {
473 /* Ignore everything between [] */
474 for (pm1 = pm++; *pm != BG_RBRACKET && *pm != BG_EOS; pm++)
478 * We could not find a matching BG_RBRACKET.
479 * Ignore and just look for BG_RBRACE
496 if (i && *pm == BG_COMMA)
499 /* Append the current string */
500 for (lm = ls; (pl < pm); *lm++ = *pl++)
504 * Append the rest of the pattern after the
507 for (pl = pe + 1; (*lm++ = *pl++) != BG_EOS; )
510 /* Expand the current pattern */
512 qprintf("globexp2:", patbuf);
513 #endif /* GLOB_DEBUG */
514 *rv = globexp1(patbuf, pglob);
516 /* move after the comma, to the next string */
532 * expand tilde from the passwd file.
535 globtilde(const Char *pattern, Char *patbuf, size_t patbuf_len, glob_t *pglob)
541 if (*pattern != BG_TILDE || !(pglob->gl_flags & GLOB_TILDE))
544 /* Copy up to the end of the string or / */
545 eb = &patbuf[patbuf_len - 1];
546 for (p = pattern + 1, h = (char *) patbuf;
547 h < (char*)eb && *p && *p != BG_SLASH; *h++ = (char)*p++)
557 if (((char *) patbuf)[0] == BG_EOS) {
559 * handle a plain ~ or ~/ by expanding $HOME
560 * first and then trying the password file
562 if ((h = getenv("HOME")) == NULL) {
565 if ((pwd = getpwuid(getuid())) == NULL)
579 if ((pwd = getpwnam((char*) patbuf)) == NULL)
588 /* Copy the home directory */
589 for (b = patbuf; b < eb && *h; *b++ = *h++)
592 /* Append the rest of the pattern */
593 while (b < eb && (*b++ = *p++) != BG_EOS)
602 * The main glob() routine: compiles the pattern (optionally processing
603 * quotes), calls glob1() to do the real pattern matching, and finally
604 * sorts the list (unless unsorted operation is requested). Returns 0
605 * if things went well, nonzero if errors occurred. It is not an error
606 * to find no matches.
609 glob0(const Char *pattern, glob_t *pglob)
611 const Char *qpat, *qpatnext;
612 int c, err, oldflags, oldpathc;
613 Char *bufnext, patbuf[MAXPATHLEN];
616 #ifdef MACOS_TRADITIONAL
617 if ( (*pattern == BG_TILDE) && (pglob->gl_flags & GLOB_TILDE) ) {
618 return(globextend(pattern, pglob, &limit));
622 qpat = globtilde(pattern, patbuf, MAXPATHLEN, pglob);
624 oldflags = pglob->gl_flags;
625 oldpathc = pglob->gl_pathc;
628 /* We don't need to check for buffer overflow any more. */
629 while ((c = *qpatnext++) != BG_EOS) {
635 if (*qpatnext == BG_EOS ||
636 g_strchr((Char *) qpatnext+1, BG_RBRACKET) == NULL) {
637 *bufnext++ = BG_LBRACKET;
647 *bufnext++ = CHAR(c);
648 if (*qpatnext == BG_RANGE &&
649 (c = qpatnext[1]) != BG_RBRACKET) {
651 *bufnext++ = CHAR(c);
654 } while ((c = *qpatnext++) != BG_RBRACKET);
655 pglob->gl_flags |= GLOB_MAGCHAR;
659 pglob->gl_flags |= GLOB_MAGCHAR;
663 pglob->gl_flags |= GLOB_MAGCHAR;
664 /* collapse adjacent stars to one,
665 * to avoid exponential behavior
667 if (bufnext == patbuf || bufnext[-1] != M_ALL)
671 *bufnext++ = CHAR(c);
677 qprintf("glob0:", patbuf);
678 #endif /* GLOB_DEBUG */
680 if ((err = glob1(patbuf, patbuf+MAXPATHLEN-1, pglob, &limit)) != 0) {
681 pglob->gl_flags = oldflags;
686 * If there was no match we are going to append the pattern
687 * if GLOB_NOCHECK was specified or if GLOB_NOMAGIC was specified
688 * and the pattern did not contain any magic characters
689 * GLOB_NOMAGIC is there just for compatibility with csh.
691 if (pglob->gl_pathc == oldpathc &&
692 ((pglob->gl_flags & GLOB_NOCHECK) ||
693 ((pglob->gl_flags & GLOB_NOMAGIC) &&
694 !(pglob->gl_flags & GLOB_MAGCHAR))))
697 printf("calling globextend from glob0\n");
698 #endif /* GLOB_DEBUG */
699 pglob->gl_flags = oldflags;
700 return(globextend(qpat, pglob, &limit));
702 else if (!(pglob->gl_flags & GLOB_NOSORT))
703 qsort(pglob->gl_pathv + pglob->gl_offs + oldpathc,
704 pglob->gl_pathc - oldpathc, sizeof(char *),
705 (pglob->gl_flags & (GLOB_ALPHASORT|GLOB_NOCASE))
706 ? ci_compare : compare);
707 pglob->gl_flags = oldflags;
712 ci_compare(const void *p, const void *q)
714 const char *pp = *(const char **)p;
715 const char *qq = *(const char **)q;
718 if (toLOWER(*pp) != toLOWER(*qq))
723 ci = toLOWER(*pp) - toLOWER(*qq);
725 return compare(p, q);
730 compare(const void *p, const void *q)
732 return(strcmp(*(char **)p, *(char **)q));
736 glob1(Char *pattern, Char *pattern_last, glob_t *pglob, size_t *limitp)
738 Char pathbuf[MAXPATHLEN];
740 /* A null pathname is invalid -- POSIX 1003.1 sect. 2.4. */
741 if (*pattern == BG_EOS)
743 return(glob2(pathbuf, pathbuf+MAXPATHLEN-1,
744 pathbuf, pathbuf+MAXPATHLEN-1,
745 pattern, pattern_last, pglob, limitp));
749 * The functions glob2 and glob3 are mutually recursive; there is one level
750 * of recursion for each segment in the pattern that contains one or more
754 glob2(Char *pathbuf, Char *pathbuf_last, Char *pathend, Char *pathend_last,
755 Char *pattern, Char *pattern_last, glob_t *pglob, size_t *limitp)
762 * Loop over pattern segments until end of pattern or until
763 * segment with meta character found.
765 for (anymeta = 0;;) {
766 if (*pattern == BG_EOS) { /* End of pattern? */
768 if (g_lstat(pathbuf, &sb, pglob))
771 if (((pglob->gl_flags & GLOB_MARK) &&
772 pathend[-1] != BG_SEP
774 && pathend[-1] != BG_SEP2
776 ) && (S_ISDIR(sb.st_mode) ||
777 (S_ISLNK(sb.st_mode) &&
778 (g_stat(pathbuf, &sb, pglob) == 0) &&
779 S_ISDIR(sb.st_mode)))) {
780 #ifdef MACOS_TRADITIONAL
782 err = glob_mark_Mac(pathbuf, pathend, pathend_last);
786 if (pathend+1 > pathend_last)
794 printf("calling globextend from glob2\n");
795 #endif /* GLOB_DEBUG */
796 return(globextend(pathbuf, pglob, limitp));
799 /* Find end of next segment, copy tentatively to pathend. */
802 while (*p != BG_EOS && *p != BG_SEP
809 if (q+1 > pathend_last)
814 if (!anymeta) { /* No expansion, do next segment. */
817 while (*pattern == BG_SEP
819 || *pattern == BG_SEP2
822 if (pathend+1 > pathend_last)
824 *pathend++ = *pattern++;
827 /* Need expansion, recurse. */
828 return(glob3(pathbuf, pathbuf_last, pathend,
829 pathend_last, pattern, pattern_last,
830 p, pattern_last, pglob, limitp));
836 glob3(Char *pathbuf, Char *pathbuf_last, Char *pathend, Char *pathend_last,
837 Char *pattern, Char *pattern_last,
838 Char *restpattern, Char *restpattern_last, glob_t *pglob, size_t *limitp)
840 register Direntry_t *dp;
844 char buf[MAXPATHLEN];
847 * The readdirfunc declaration can't be prototyped, because it is
848 * assigned, below, to two functions which are prototyped in glob.h
849 * and dirent.h as taking pointers to differently typed opaque
852 Direntry_t *(*readdirfunc)(DIR*);
854 if (pathend > pathend_last)
862 if (q - pathbuf > 5) {
865 tolower(q[1]) == 'd' && tolower(q[2]) == 'i' &&
866 tolower(q[3]) == 'r' && q[4] == '/')
876 #ifdef MACOS_TRADITIONAL
877 if ((!*pathbuf) && (g_matchVol)) {
880 StrFileName vol_name; /* unsigned char[64] on MacOS */
883 nocase = ((pglob->gl_flags & GLOB_NOCASE) != 0);
885 /* Get and match a list of volume names */
886 for (index = 0; !GetVolInfo(index+1, true, &spec); ++index) {
890 name_f_FSSpec(vol_name, &spec);
892 /* Initial BG_DOT must be matched literally. */
893 if (*vol_name == BG_DOT && *pattern != BG_DOT)
896 sc = (U8 *) vol_name;
897 while (dc < pathend_last && (*dc++ = *sc++) != BG_EOS)
899 if (dc >= pathend_last) {
905 if (!match(pathend, pattern, restpattern, nocase)) {
909 err = glob2(pathbuf, pathbuf_last, --dc, pathend_last,
910 restpattern, restpattern_last, pglob, limitp);
916 } else { /* open dir */
917 #endif /* MACOS_TRADITIONAL */
919 if ((dirp = g_opendir(pathbuf, pglob)) == NULL) {
920 /* TODO: don't call for ENOENT or ENOTDIR? */
921 if (pglob->gl_errfunc) {
922 if (g_Ctoc(pathbuf, buf, sizeof(buf)))
924 if (pglob->gl_errfunc(buf, errno) ||
925 (pglob->gl_flags & GLOB_ERR))
932 nocase = ((pglob->gl_flags & GLOB_NOCASE) != 0);
934 /* Search directory for matching names. */
935 if (pglob->gl_flags & GLOB_ALTDIRFUNC)
936 readdirfunc = (Direntry_t *(*)(DIR *))pglob->gl_readdir;
938 readdirfunc = (Direntry_t *(*)(DIR *))my_readdir;
939 while ((dp = (*readdirfunc)(dirp))) {
943 /* Initial BG_DOT must be matched literally. */
944 if (dp->d_name[0] == BG_DOT && *pattern != BG_DOT)
947 sc = (U8 *) dp->d_name;
948 while (dc < pathend_last && (*dc++ = *sc++) != BG_EOS)
950 if (dc >= pathend_last) {
956 if (!match(pathend, pattern, restpattern, nocase)) {
960 err = glob2(pathbuf, pathbuf_last, --dc, pathend_last,
961 restpattern, restpattern_last, pglob, limitp);
966 if (pglob->gl_flags & GLOB_ALTDIRFUNC)
967 (*pglob->gl_closedir)(dirp);
972 #ifdef MACOS_TRADITIONAL
979 * Extend the gl_pathv member of a glob_t structure to accomodate a new item,
980 * add the new item, and update gl_pathc.
982 * This assumes the BSD realloc, which only copies the block when its size
983 * crosses a power-of-two boundary; for v7 realloc, this would cause quadratic
986 * Return 0 if new item added, error code if memory couldn't be allocated.
988 * Invariant of the glob_t structure:
989 * Either gl_pathc is zero and gl_pathv is NULL; or gl_pathc > 0 and
990 * gl_pathv points to (gl_offs + gl_pathc + 1) items.
993 globextend(const Char *path, glob_t *pglob, size_t *limitp)
995 register char **pathv;
1003 for (p = path; *p; p++)
1004 (void)printf("%c", CHAR(*p));
1006 #endif /* GLOB_DEBUG */
1008 newsize = sizeof(*pathv) * (2 + pglob->gl_pathc + pglob->gl_offs);
1009 if (pglob->gl_pathv)
1010 pathv = Renew(pglob->gl_pathv,newsize,char*);
1012 Newx(pathv,newsize,char*);
1013 if (pathv == NULL) {
1014 if (pglob->gl_pathv) {
1015 Safefree(pglob->gl_pathv);
1016 pglob->gl_pathv = NULL;
1018 return(GLOB_NOSPACE);
1021 if (pglob->gl_pathv == NULL && pglob->gl_offs > 0) {
1022 /* first time around -- clear initial gl_offs items */
1023 pathv += pglob->gl_offs;
1024 for (i = pglob->gl_offs; --i >= 0; )
1027 pglob->gl_pathv = pathv;
1029 for (p = path; *p++;)
1031 len = (STRLEN)(p - path);
1033 Newx(copy, p-path, char);
1035 if (g_Ctoc(path, copy, len)) {
1037 return(GLOB_NOSPACE);
1039 pathv[pglob->gl_offs + pglob->gl_pathc++] = copy;
1041 pathv[pglob->gl_offs + pglob->gl_pathc] = NULL;
1043 if ((pglob->gl_flags & GLOB_LIMIT) &&
1044 newsize + *limitp >= ARG_MAX) {
1046 return(GLOB_NOSPACE);
1049 return(copy == NULL ? GLOB_NOSPACE : 0);
1054 * pattern matching function for filenames. Each occurrence of the *
1055 * pattern causes a recursion level.
1058 match(register Char *name, register Char *pat, register Char *patend, int nocase)
1060 int ok, negate_range;
1063 while (pat < patend) {
1065 switch (c & M_MASK) {
1070 if (match(name, pat, patend, nocase))
1072 while (*name++ != BG_EOS)
1076 if (*name++ == BG_EOS)
1081 if ((k = *name++) == BG_EOS)
1083 if ((negate_range = ((*pat & M_MASK) == M_NOT)) != BG_EOS)
1085 while (((c = *pat++) & M_MASK) != M_END)
1086 if ((*pat & M_MASK) == M_RNG) {
1088 if (tolower(c) <= tolower(k) && tolower(k) <= tolower(pat[1]))
1091 if (c <= k && k <= pat[1])
1095 } else if (nocase ? (tolower(c) == tolower(k)) : (c == k))
1097 if (ok == negate_range)
1102 if (nocase ? (tolower(k) != tolower(c)) : (k != c))
1107 return(*name == BG_EOS);
1110 /* Free allocated data belonging to a glob_t structure. */
1112 bsd_globfree(glob_t *pglob)
1117 if (pglob->gl_pathv != NULL) {
1118 pp = pglob->gl_pathv + pglob->gl_offs;
1119 for (i = pglob->gl_pathc; i--; ++pp)
1122 Safefree(pglob->gl_pathv);
1123 pglob->gl_pathv = NULL;
1128 g_opendir(register Char *str, glob_t *pglob)
1130 char buf[MAXPATHLEN];
1133 #ifdef MACOS_TRADITIONAL
1134 my_strlcpy(buf, ":", sizeof(buf));
1136 my_strlcpy(buf, ".", sizeof(buf));
1139 if (g_Ctoc(str, buf, sizeof(buf)))
1143 if (pglob->gl_flags & GLOB_ALTDIRFUNC)
1144 return((DIR*)(*pglob->gl_opendir)(buf));
1146 return(PerlDir_open(buf));
1150 g_lstat(register Char *fn, Stat_t *sb, glob_t *pglob)
1152 char buf[MAXPATHLEN];
1154 if (g_Ctoc(fn, buf, sizeof(buf)))
1156 if (pglob->gl_flags & GLOB_ALTDIRFUNC)
1157 return((*pglob->gl_lstat)(buf, sb));
1159 return(PerlLIO_lstat(buf, sb));
1161 return(PerlLIO_stat(buf, sb));
1162 #endif /* HAS_LSTAT */
1166 g_stat(register Char *fn, Stat_t *sb, glob_t *pglob)
1168 char buf[MAXPATHLEN];
1170 if (g_Ctoc(fn, buf, sizeof(buf)))
1172 if (pglob->gl_flags & GLOB_ALTDIRFUNC)
1173 return((*pglob->gl_stat)(buf, sb));
1174 return(PerlLIO_stat(buf, sb));
1178 g_strchr(Char *str, int ch)
1188 g_Ctoc(register const Char *str, char *buf, STRLEN len)
1191 if ((*buf++ = (char)*str++) == BG_EOS)
1199 qprintf(const char *str, register Char *s)
1203 (void)printf("%s:\n", str);
1204 for (p = s; *p; p++)
1205 (void)printf("%c", CHAR(*p));
1207 for (p = s; *p; p++)
1208 (void)printf("%c", *p & M_PROTECT ? '"' : ' ');
1210 for (p = s; *p; p++)
1211 (void)printf("%c", ismeta(*p) ? '_' : ' ');
1214 #endif /* GLOB_DEBUG */
1217 #ifdef MACOS_TRADITIONAL
1219 /* Replace the last occurrence of the pattern ":[^:]+::", e.g. ":lib::",
1220 with a single ':', if possible. It is not an error, if the pattern
1221 doesn't match (we return -1), but if there are two consecutive colons
1222 '::', there must be a preceding ':[^:]+'. Hence, a volume path like
1223 "HD::" is considered to be an error (we return 1), that is, it can't
1224 be resolved. We return 0 on success.
1230 char *pb, *pe, *lastchar;
1231 char *bgn_mark, *end_mark;
1232 char *f, *m, *b; /* front, middle, back */
1236 lastchar = path + (len-1);
1241 /* find a '[^:]::' (e.g. b::) pattern ... */
1242 while ( !( (*f != BG_SEP) && (*m == BG_SEP) && (*b == BG_SEP) )
1249 if (f < path) { /* no (more) match */
1255 /* ... and now find its preceding colon ':' */
1256 while ((*f != BG_SEP) && (f >= path)) {
1260 /* No preceding colon found, must be a
1261 volume path. We can't move up the
1262 tree and that's an error */
1267 /* Shrink path, i.e. exclude all characters between
1268 bgn_mark and end_mark */
1272 while (*pb++ = *pe++) ;
1277 /* Resolve all updirs in pattern. */
1280 resolve_updirs(char *new_pattern)
1285 err = updir(new_pattern);
1288 return NO_UPDIR_ERR;
1294 /* Remove a trailing colon from the path, but only if it's
1295 not a volume path (e.g. HD:) and not a path consisting
1296 solely of colons. */
1299 remove_trColon(char *path)
1301 char *lastchar, *lc;
1303 /* if path matches the pattern /:[^:]+:$/, we can
1304 remove the trailing ':' */
1306 lc = lastchar = path + (strlen(path) - 1);
1307 if (*lastchar == BG_SEP) {
1308 /* there's a trailing ':', there must be at least
1309 one preceding char != ':' and a preceding ':' */
1311 if ((*lc != BG_SEP) && (lc >= path)) {
1316 while ((*lc != BG_SEP) && (lc >= path)) {
1320 /* ... there's a preceding ':', we remove
1321 the trailing colon */
1328 /* With the GLOB_MARK flag on, we append a colon, if pathbuf
1329 is a directory. If the directory name contains no colons,
1330 e.g. 'lib', we can't simply append a ':', since this (e.g.
1331 'lib:') is not a valid (relative) path on Mac OS. Instead,
1332 we add a leading _and_ trailing ':'. */
1335 glob_mark_Mac(Char *pathbuf, Char *pathend, Char *pathend_last)
1338 Boolean is_file = true;
1340 /* check if pathbuf contains a ':',
1341 i.e. is not a file name */
1343 while (*p != BG_EOS) {
1352 if (pathend+2 > pathend_last) {
1355 /* right shift one char */
1359 while (p >= pathbuf) {
1362 /* first char becomes a colon */
1364 /* append a colon */
1365 *pathend++ = BG_SEP;
1369 if (pathend+1 > pathend_last) {
1372 *pathend++ = BG_SEP;
1379 /* Return a FSSpec record for the specified volume
1380 (borrowed from MacPerl.xs). */
1383 GetVolInfo(short volume, Boolean indexed, FSSpec* spec)
1385 OSErr err; /* OSErr: 16-bit integer */
1388 pb.volumeParam.ioNamePtr = spec->name;
1389 pb.volumeParam.ioVRefNum = indexed ? 0 : volume;
1390 pb.volumeParam.ioVolIndex = indexed ? volume : 0;
1392 if (err = PBHGetVInfoSync(&pb))
1395 spec->vRefNum = pb.volumeParam.ioVRefNum;
1398 return noErr; /* 0 */
1401 /* Extract a C name from a FSSpec. Note that there are
1402 no leading or trailing colons. */
1405 name_f_FSSpec(StrFileName name, FSSpec *spec)
1408 const short len = spec->name[0];
1411 /* FSSpec.name is a Pascal string,
1412 convert it to C ... */
1414 for (i=1; i<=len; i++) {
1415 *nc++ = spec->name[i];
1420 #endif /* MACOS_TRADITIONAL */