xref: /dragonfly/contrib/tcsh-6/glob.c (revision b97fef05)
1 /*
2  * Copyright (c) 1989 The Regents of the University of California.
3  * All rights reserved.
4  *
5  * This code is derived from software contributed to Berkeley by
6  * Guido van Rossum.
7  *
8  * Redistribution and use in source and binary forms, with or without
9  * modification, are permitted provided that the following conditions
10  * are met:
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.
19  *
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
30  * SUCH DAMAGE.
31  */
32 #if defined(LIBC_SCCS) && !defined(lint)
33 static char sccsid[] = "@(#)glob.c	5.12 (Berkeley) 6/24/91";
34 #endif /* LIBC_SCCS and not lint */
35 /*
36  * Glob: the interface is a superset of the one defined in POSIX 1003.2,
37  * draft 9.
38  *
39  * The [!...] convention to negate a range is supported (SysV, Posix, ksh).
40  *
41  * Optional extra services, controlled by flags not defined by POSIX:
42  *
43  * GLOB_QUOTE:
44  *	Escaping convention: \ inhibits any special meaning the following
45  *	character might have (except \ at end of string is retained).
46  * GLOB_MAGCHAR:
47  *	Set in gl_flags if pattern contained a globbing character.
48  * GLOB_ALTNOT:
49  *	Use ^ instead of ! for "not".
50  * gl_matchc:
51  *	Number of matches in the current invocation of glob.
52  */
53 
54 #ifdef WINNT_NATIVE
55 	#pragma warning(disable:4244)
56 #endif /* WINNT_NATIVE */
57 
58 #define Char __Char
59 #include "sh.h"
60 #include "glob.h"
61 
62 #ifndef HAVE_MBLEN
63 #undef mblen
64 #define mblen(_s,_n)	mbrlen((_s),(_n),NULL)
65 #endif
66 
67 #undef Char
68 #undef QUOTE
69 #undef TILDE
70 #undef META
71 #undef ismeta
72 #undef Strchr
73 
74 #ifndef S_ISDIR
75 #define S_ISDIR(a)	(((a) & S_IFMT) == S_IFDIR)
76 #endif
77 
78 #if !defined(S_ISLNK) && defined(S_IFLNK)
79 #define S_ISLNK(a)	(((a) & S_IFMT) == S_IFLNK)
80 #endif
81 
82 #if !defined(S_ISLNK) && !defined(lstat)
83 #define lstat stat
84 #endif
85 
86 typedef unsigned short Char;
87 
88 static	int	 glob1 		(Char *, glob_t *, int);
89 static	int	 glob2		(struct strbuf *, const Char *, glob_t *, int);
90 static	int	 glob3		(struct strbuf *, const Char *, const Char *,
91 				 const Char *, glob_t *, int);
92 static	void	 globextend	(const char *, glob_t *);
93 static	int	 match		(const char *, const Char *, const Char *,
94 				 int);
95 static	int	 compare	(const void *, const void *);
96 static 	DIR	*Opendir	(const char *);
97 #ifdef S_IFLNK
98 static	int	 Lstat		(const char *, struct stat *);
99 #endif
100 static	int	 Stat		(const char *, struct stat *sb);
101 static 	Char 	*Strchr		(Char *, int);
102 #ifdef DEBUG
103 static	void	 qprintf	(const char *, const Char *);
104 #endif
105 
106 #define	DOLLAR		'$'
107 #define	DOT		'.'
108 #define	EOS		'\0'
109 #define	LBRACKET	'['
110 #define	NOT		'!'
111 #define ALTNOT		'^'
112 #define	QUESTION	'?'
113 #define	QUOTE		'\\'
114 #define	RANGE		'-'
115 #define	RBRACKET	']'
116 #define	SEP		'/'
117 #define	STAR		'*'
118 #define	TILDE		'~'
119 #define	UNDERSCORE	'_'
120 
121 #define	M_META		0x8000
122 #define M_PROTECT	0x4000
123 #define	M_MASK		0xffff
124 #define	M_ASCII		0x00ff
125 
126 #define	LCHAR(c)	((c)&M_ASCII)
127 #define	META(c)		((c)|M_META)
128 #define	M_ALL		META('*')
129 #define	M_END		META(']')
130 #define	M_NOT		META('!')
131 #define	M_ALTNOT	META('^')
132 #define	M_ONE		META('?')
133 #define	M_RNG		META('-')
134 #define	M_SET		META('[')
135 #define	ismeta(c)	(((c)&M_META) != 0)
136 
137 int
138 globcharcoll(__Char c1, __Char c2, int cs)
139 {
140 #if defined(NLS) && defined(LC_COLLATE) && defined(HAVE_STRCOLL)
141 # if defined(WIDE_STRINGS)
142     wchar_t s1[2], s2[2];
143 
144     if (c1 == c2)
145 	return (0);
146     if (cs) {
147 	c1 = towlower(c1);
148 	c2 = towlower(c2);
149     } else {
150 	/* This should not be here, but I'll rather leave it in than engage in
151 	   a LC_COLLATE flamewar about a shell I don't use... */
152 	if (iswlower(c1) && iswupper(c2))
153 	    return (1);
154 	if (iswupper(c1) && iswlower(c2))
155 	    return (-1);
156     }
157     s1[0] = c1;
158     s2[0] = c2;
159     s1[1] = s2[1] = '\0';
160     return wcscoll(s1, s2);
161 # else /* not WIDE_STRINGS */
162     char s1[2], s2[2];
163 
164     if (c1 == c2)
165 	return (0);
166     /*
167      * From kevin lyda <kevin@suberic.net>:
168      * strcoll does not guarantee case sorting, so we pre-process now:
169      */
170     if (cs) {
171 	c1 = islower(c1) ? c1 : tolower(c1);
172 	c2 = islower(c2) ? c2 : tolower(c2);
173     } else {
174 	if (islower(c1) && isupper(c2))
175 	    return (1);
176 	if (isupper(c1) && islower(c2))
177 	    return (-1);
178     }
179     s1[0] = c1;
180     s2[0] = c2;
181     s1[1] = s2[1] = '\0';
182     return strcoll(s1, s2);
183 # endif
184 #else
185     return (c1 - c2);
186 #endif
187 }
188 
189 /*
190  * Need to dodge two kernel bugs:
191  * opendir("") != opendir(".")
192  * NAMEI_BUG: on plain files trailing slashes are ignored in some kernels.
193  *            POSIX specifies that they should be ignored in directories.
194  */
195 
196 static DIR *
197 Opendir(const char *str)
198 {
199 #if defined(hpux) || defined(__hpux)
200     struct stat st;
201 #endif
202 
203     if (!*str)
204 	return (opendir("."));
205 #if defined(hpux) || defined(__hpux)
206     /*
207      * Opendir on some device files hangs, so avoid it
208      */
209     if (stat(str, &st) == -1 || !S_ISDIR(st.st_mode))
210 	return NULL;
211 #endif
212     return opendir(str);
213 }
214 
215 #ifdef S_IFLNK
216 static int
217 Lstat(const char *fn, struct stat *sb)
218 {
219     int st;
220 
221     st = lstat(fn, sb);
222 # ifdef NAMEI_BUG
223     if (*fn != 0 && strend(fn)[-1] == '/' && !S_ISDIR(sb->st_mode))
224 	st = -1;
225 # endif	/* NAMEI_BUG */
226     return st;
227 }
228 #else
229 #define Lstat Stat
230 #endif /* S_IFLNK */
231 
232 static int
233 Stat(const char *fn, struct stat *sb)
234 {
235     int st;
236 
237     st = stat(fn, sb);
238 #ifdef NAMEI_BUG
239     if (*fn != 0 && strend(fn)[-1] == '/' && !S_ISDIR(sb->st_mode))
240 	st = -1;
241 #endif /* NAMEI_BUG */
242     return st;
243 }
244 
245 static Char *
246 Strchr(Char *str, int ch)
247 {
248     do
249 	if (*str == ch)
250 	    return (str);
251     while (*str++);
252     return (NULL);
253 }
254 
255 #ifdef DEBUG
256 static void
257 qprintf(const char *pre, const Char *s)
258 {
259     const Char *p;
260 
261     xprintf("%s", pre);
262     for (p = s; *p; p++)
263 	xprintf("%c", *p & 0xff);
264     xprintf("\n%s", pre);
265     for (p = s; *p; p++)
266 	xprintf("%c", *p & M_PROTECT ? '"' : ' ');
267     xprintf("\n%s", pre);
268     for (p = s; *p; p++)
269 	xprintf("%c", *p & M_META ? '_' : ' ');
270     xprintf("\n");
271 }
272 #endif /* DEBUG */
273 
274 static int
275 compare(const void *p, const void *q)
276 {
277 #if defined(NLS) && defined(HAVE_STRCOLL)
278     return (strcoll(*(char *const *) p, *(char *const *) q));
279 #else
280     return (strcmp(*(char *const *) p, *(char *const *) q));
281 #endif /* NLS && HAVE_STRCOLL */
282 }
283 
284 /*
285  * The main glob() routine: compiles the pattern (optionally processing
286  * quotes), calls glob1() to do the real pattern matching, and finally
287  * sorts the list (unless unsorted operation is requested).  Returns 0
288  * if things went well, nonzero if errors occurred.  It is not an error
289  * to find no matches.
290  */
291 int
292 glob(const char *pattern, int flags, int (*errfunc) (const char *, int),
293      glob_t *pglob)
294 {
295     int     err, oldpathc;
296     Char *bufnext, m_not;
297     const unsigned char *patnext;
298     int     c, not;
299     Char *qpatnext, *patbuf;
300     int     no_match;
301 
302     patnext = (const unsigned char *) pattern;
303     if (!(flags & GLOB_APPEND)) {
304 	pglob->gl_pathc = 0;
305 	pglob->gl_pathv = NULL;
306 	if (!(flags & GLOB_DOOFFS))
307 	    pglob->gl_offs = 0;
308     }
309     pglob->gl_flags = flags & ~GLOB_MAGCHAR;
310     pglob->gl_errfunc = errfunc;
311     oldpathc = pglob->gl_pathc;
312     pglob->gl_matchc = 0;
313 
314     if (pglob->gl_flags & GLOB_ALTNOT) {
315 	not = ALTNOT;
316 	m_not = M_ALTNOT;
317     }
318     else {
319 	not = NOT;
320 	m_not = M_NOT;
321     }
322 
323     patbuf = xmalloc((strlen(pattern) + 1) * sizeof(*patbuf));
324     bufnext = patbuf;
325 
326     no_match = *patnext == not;
327     if (no_match)
328 	patnext++;
329 
330     if (flags & GLOB_QUOTE) {
331 	/* Protect the quoted characters */
332 	while ((c = *patnext++) != EOS) {
333 #ifdef WIDE_STRINGS
334 	    int len;
335 
336 	    len = mblen((const char *)(patnext - 1), MB_LEN_MAX);
337 	    if (len == -1)
338 		TCSH_IGNORE(mblen(NULL, 0));
339 	    else if (len > 1) {
340 		*bufnext++ = (Char) c;
341 		while (--len != 0)
342 		    *bufnext++ = (Char) (*patnext++ | M_PROTECT);
343 	    } else
344 #endif /* WIDE_STRINGS */
345 	    if (c == QUOTE) {
346 		if ((c = *patnext++) == EOS) {
347 		    c = QUOTE;
348 		    --patnext;
349 		}
350 		*bufnext++ = (Char) (c | M_PROTECT);
351 	    }
352 	    else
353 		*bufnext++ = (Char) c;
354 	}
355     }
356     else
357 	while ((c = *patnext++) != EOS)
358 	    *bufnext++ = (Char) c;
359     *bufnext = EOS;
360 
361     bufnext = patbuf;
362     qpatnext = patbuf;
363     while ((c = *qpatnext++) != EOS) {
364 	switch (c) {
365 	case LBRACKET:
366 	    c = *qpatnext;
367 	    if (c == not)
368 		++qpatnext;
369 	    if (*qpatnext == EOS ||
370 		Strchr(qpatnext + 1, RBRACKET) == NULL) {
371 		*bufnext++ = LBRACKET;
372 		if (c == not)
373 		    --qpatnext;
374 		break;
375 	    }
376 	    pglob->gl_flags |= GLOB_MAGCHAR;
377 	    *bufnext++ = M_SET;
378 	    if (c == not)
379 		*bufnext++ = m_not;
380 	    c = *qpatnext++;
381 	    do {
382 		*bufnext++ = LCHAR(c);
383 		if (*qpatnext == RANGE &&
384 		    (c = qpatnext[1]) != RBRACKET) {
385 		    *bufnext++ = M_RNG;
386 		    *bufnext++ = LCHAR(c);
387 		    qpatnext += 2;
388 		}
389 	    } while ((c = *qpatnext++) != RBRACKET);
390 	    *bufnext++ = M_END;
391 	    break;
392 	case QUESTION:
393 	    pglob->gl_flags |= GLOB_MAGCHAR;
394 	    *bufnext++ = M_ONE;
395 	    break;
396 	case STAR:
397 	    pglob->gl_flags |= GLOB_MAGCHAR;
398 	    /* collapse adjacent stars to one [or three if globstar],
399 	     * to avoid exponential behavior
400 	     */
401 	    if (bufnext == patbuf || bufnext[-1] != M_ALL ||
402 	       ((flags & GLOB_STAR) != 0 &&
403 		 (bufnext - 1 == patbuf || bufnext[-2] != M_ALL ||
404 		 bufnext - 2 == patbuf || bufnext[-3] != M_ALL)))
405 		*bufnext++ = M_ALL;
406 	    break;
407 	default:
408 	    *bufnext++ = LCHAR(c);
409 	    break;
410 	}
411     }
412     *bufnext = EOS;
413 #ifdef DEBUG
414     qprintf("patbuf=", patbuf);
415 #endif
416 
417     if ((err = glob1(patbuf, pglob, no_match)) != 0) {
418 	xfree(patbuf);
419 	return (err);
420     }
421 
422     /*
423      * If there was no match we are going to append the pattern
424      * if GLOB_NOCHECK was specified or if GLOB_NOMAGIC was specified
425      * and the pattern did not contain any magic characters
426      * GLOB_NOMAGIC is there just for compatibility with csh.
427      */
428     if (pglob->gl_pathc == oldpathc &&
429 	((flags & GLOB_NOCHECK) ||
430 	 ((flags & GLOB_NOMAGIC) && !(pglob->gl_flags & GLOB_MAGCHAR)))) {
431 	if (!(flags & GLOB_QUOTE))
432 	    globextend(pattern, pglob);
433 	else {
434 	    char *copy, *dest;
435 	    const char *src;
436 
437 	    /* copy pattern, interpreting quotes */
438 	    copy = xmalloc(strlen(pattern) + 1);
439 	    dest = copy;
440 	    src = pattern;
441 	    while (*src != EOS) {
442 		/* Don't interpret quotes. The spec does not say we should do */
443 		if (*src == QUOTE) {
444 		    if (*++src == EOS)
445 			--src;
446 		}
447 		*dest++ = *src++;
448 	    }
449 	    *dest = EOS;
450 	    globextend(copy, pglob);
451 	    xfree(copy);
452 	}
453 	xfree(patbuf);
454 	return 0;
455     }
456     else if (!(flags & GLOB_NOSORT) && (pglob->gl_pathc != oldpathc))
457 	qsort(pglob->gl_pathv + pglob->gl_offs + oldpathc,
458 	      pglob->gl_pathc - oldpathc, sizeof(char *), compare);
459     xfree(patbuf);
460     return (0);
461 }
462 
463 static int
464 glob1(Char *pattern, glob_t *pglob, int no_match)
465 {
466     struct strbuf pathbuf = strbuf_INIT;
467     int err;
468 
469     /*
470      * a null pathname is invalid -- POSIX 1003.1 sect. 2.4.
471      */
472     if (*pattern == EOS)
473 	return (0);
474     err = glob2(&pathbuf, pattern, pglob, no_match);
475     xfree(pathbuf.s);
476     return err;
477 }
478 
479 /*
480  * functions glob2 and glob3 are mutually recursive; there is one level
481  * of recursion for each segment in the pattern that contains one or
482  * more meta characters.
483  */
484 static int
485 glob2(struct strbuf *pathbuf, const Char *pattern, glob_t *pglob, int no_match)
486 {
487     struct stat sbuf;
488     int anymeta;
489     const Char *p;
490     size_t orig_len;
491 
492     /*
493      * loop over pattern segments until end of pattern or until segment with
494      * meta character found.
495      */
496     anymeta = 0;
497     for (;;) {
498 	if (*pattern == EOS) {	/* end of pattern? */
499 	    strbuf_terminate(pathbuf);
500 
501 	    if (Lstat(pathbuf->s, &sbuf))
502 		return (0);
503 
504 	    if (((pglob->gl_flags & GLOB_MARK) &&
505 		 pathbuf->s[pathbuf->len - 1] != SEP) &&
506 		(S_ISDIR(sbuf.st_mode)
507 #ifdef S_IFLNK
508 		 || (S_ISLNK(sbuf.st_mode) &&
509 		     (Stat(pathbuf->s, &sbuf) == 0) &&
510 		     S_ISDIR(sbuf.st_mode))
511 #endif
512 		 )) {
513 		strbuf_append1(pathbuf, SEP);
514 		strbuf_terminate(pathbuf);
515 	    }
516 	    ++pglob->gl_matchc;
517 	    globextend(pathbuf->s, pglob);
518 	    return 0;
519 	}
520 
521 	/* find end of next segment, tentatively copy to pathbuf */
522 	p = pattern;
523 	orig_len = pathbuf->len;
524 	while (*p != EOS && *p != SEP) {
525 	    if (ismeta(*p))
526 		anymeta = 1;
527 	    strbuf_append1(pathbuf, *p++);
528 	}
529 
530 	if (!anymeta) {		/* no expansion, do next segment */
531 	    pattern = p;
532 	    while (*pattern == SEP)
533 		strbuf_append1(pathbuf, *pattern++);
534 	}
535 	else {			/* need expansion, recurse */
536 	    pathbuf->len = orig_len;
537 	    return (glob3(pathbuf, pattern, p, pattern, pglob, no_match));
538 	}
539     }
540     /* NOTREACHED */
541 }
542 
543 static size_t
544 One_Char_mbtowc(__Char *pwc, const Char *s, size_t n)
545 {
546 #ifdef WIDE_STRINGS
547     char buf[MB_LEN_MAX], *p;
548 
549     if (n > MB_LEN_MAX)
550 	n = MB_LEN_MAX;
551     p = buf;
552     while (p < buf + n && (*p++ = LCHAR(*s++)) != 0)
553 	;
554     return one_mbtowc(pwc, buf, n);
555 #else
556     (void)n;
557     *pwc = *s & CHAR;
558     return 1;
559 #endif
560 }
561 
562 static int
563 glob3(struct strbuf *pathbuf, const Char *pattern, const Char *restpattern,
564       const Char *pglobstar, glob_t *pglob, int no_match)
565 {
566     DIR    *dirp;
567     struct dirent *dp;
568     struct stat sbuf;
569     int     err;
570     Char m_not = (pglob->gl_flags & GLOB_ALTNOT) ? M_ALTNOT : M_NOT;
571     size_t orig_len;
572     int globstar = 0;
573     int chase_symlinks = 0;
574     const Char *termstar = NULL;
575 
576     strbuf_terminate(pathbuf);
577     orig_len = pathbuf->len;
578     errno = err = 0;
579 
580     while (pglobstar < restpattern) {
581 	__Char wc;
582 	size_t width = One_Char_mbtowc(&wc, pglobstar, MB_LEN_MAX);
583 	if ((pglobstar[0] & M_MASK) == M_ALL &&
584 	    (pglobstar[width] & M_MASK) == M_ALL) {
585 	    globstar = 1;
586 	    chase_symlinks = (pglobstar[2 * width] & M_MASK) == M_ALL;
587 	    termstar = pglobstar + (2 + chase_symlinks) * width;
588 	    break;
589 	}
590         pglobstar += width;
591     }
592 
593     if (globstar) {
594 	err = pglobstar==pattern && termstar==restpattern ?
595 		*restpattern == EOS ?
596 		glob2(pathbuf, restpattern - 1, pglob, no_match) :
597 		glob2(pathbuf, restpattern + 1, pglob, no_match) :
598 		glob3(pathbuf, pattern, restpattern, termstar, pglob, no_match);
599 	if (err)
600 	    return err;
601 	pathbuf->len = orig_len;
602 	strbuf_terminate(pathbuf);
603     }
604 
605     if (*pathbuf->s && (Lstat(pathbuf->s, &sbuf) || !S_ISDIR(sbuf.st_mode)
606 #ifdef S_IFLINK
607 	     && ((globstar && !chase_symlinks) || !S_ISLNK(sbuf.st_mode))
608 #endif
609 	))
610 	return 0;
611 
612     if (!(dirp = Opendir(pathbuf->s))) {
613 	/* todo: don't call for ENOENT or ENOTDIR? */
614 	if ((pglob->gl_errfunc && (*pglob->gl_errfunc) (pathbuf->s, errno)) ||
615 	    (pglob->gl_flags & GLOB_ERR))
616 	    return (GLOB_ABEND);
617 	else
618 	    return (0);
619     }
620 
621     /* search directory for matching names */
622     while ((dp = readdir(dirp)) != NULL) {
623 	/* initial DOT must be matched literally */
624 	if (dp->d_name[0] == DOT && *pattern != DOT)
625 	    if (!(pglob->gl_flags & GLOB_DOT) || !dp->d_name[1] ||
626 		(dp->d_name[1] == DOT && !dp->d_name[2]))
627 		continue; /*unless globdot and not . or .. */
628 	pathbuf->len = orig_len;
629 	strbuf_append(pathbuf, dp->d_name);
630 	strbuf_terminate(pathbuf);
631 
632 	if (globstar) {
633 #ifdef S_IFLNK
634 	    if (!chase_symlinks &&
635 		(Lstat(pathbuf->s, &sbuf) || S_ISLNK(sbuf.st_mode)))
636 		    continue;
637 #endif
638 	    if (match(pathbuf->s + orig_len, pattern, termstar,
639 		(int)m_not) == no_match)
640 		    continue;
641 	    strbuf_append1(pathbuf, SEP);
642 	    strbuf_terminate(pathbuf);
643 	    if ((err = glob2(pathbuf, pglobstar, pglob, no_match)) != 0)
644 		break;
645 	} else {
646 	    if (match(pathbuf->s + orig_len, pattern, restpattern,
647 		(int) m_not) == no_match)
648 		continue;
649 	    if ((err = glob2(pathbuf, restpattern, pglob, no_match)) != 0)
650 		break;
651 	}
652     }
653     /* todo: check error from readdir? */
654     closedir(dirp);
655     return (err);
656 }
657 
658 
659 /*
660  * Extend the gl_pathv member of a glob_t structure to accomodate a new item,
661  * add the new item, and update gl_pathc.
662  *
663  * This assumes the BSD realloc, which only copies the block when its size
664  * crosses a power-of-two boundary; for v7 realloc, this would cause quadratic
665  * behavior.
666  *
667  * Return 0 if new item added, error code if memory couldn't be allocated.
668  *
669  * Invariant of the glob_t structure:
670  *	Either gl_pathc is zero and gl_pathv is NULL; or gl_pathc > 0 and
671  *	 gl_pathv points to (gl_offs + gl_pathc + 1) items.
672  */
673 static void
674 globextend(const char *path, glob_t *pglob)
675 {
676     char **pathv;
677     int i;
678     size_t newsize;
679 
680     newsize = sizeof(*pathv) * (2 + pglob->gl_pathc + pglob->gl_offs);
681     pathv = xrealloc(pglob->gl_pathv, newsize);
682 
683     if (pglob->gl_pathv == NULL && pglob->gl_offs > 0) {
684 	/* first time around -- clear initial gl_offs items */
685 	pathv += pglob->gl_offs;
686 	for (i = pglob->gl_offs; --i >= 0;)
687 	    *--pathv = NULL;
688     }
689     pglob->gl_pathv = pathv;
690 
691     pathv[pglob->gl_offs + pglob->gl_pathc++] = strsave(path);
692     pathv[pglob->gl_offs + pglob->gl_pathc] = NULL;
693 }
694 
695 /*
696  * pattern matching function for filenames.
697  */
698 static  int
699 match(const char *name, const Char *pat, const Char *patend, int m_not)
700 {
701     int ok, negate_range;
702     const Char *patNext;
703     const char *nameNext, *nameStart, *nameEnd;
704     Char c;
705 
706     patNext = pat;
707     nameStart = nameNext = name;
708     nameEnd = NULL;
709 
710     while (pat < patend || *name) {
711 	size_t lwk, pwk;
712 	__Char wc, wk, wc1;
713 
714 	c = *pat; /* Only for M_MASK bits */
715 	if (*name == EOS)
716 		nameEnd = name;
717 
718 	pwk = One_Char_mbtowc(&wc, pat, MB_LEN_MAX);
719 	lwk = one_mbtowc(&wk, name, MB_LEN_MAX);
720 	switch (c & M_MASK) {
721 	case M_ALL:
722 	    while ((*(pat + pwk) & M_MASK) == M_ALL) {
723 		pat += pwk;
724 		pwk = One_Char_mbtowc(&wc, pat, MB_LEN_MAX);
725 	    }
726 	    patNext = pat;
727 	    nameNext = name + lwk;
728 	    pat += pwk;
729 	    continue;
730 	case M_ONE:
731 	    if (*name == EOS)
732 		break;
733 	    name += lwk;
734 	    pat += pwk;
735 	    continue;
736 	case M_SET:
737 	    ok = 0;
738 	    if (*name == EOS)
739 		break;
740 	    pat += pwk;
741 	    pwk = One_Char_mbtowc(&wc, pat, MB_LEN_MAX);
742 	    name += lwk;
743 	    if ((negate_range = ((*pat & M_MASK) == m_not)) != 0) {
744 		pat += pwk;
745 		pwk = One_Char_mbtowc(&wc, pat, MB_LEN_MAX);
746 	    }
747 	    wc1 = wc;
748 	    while ((*pat & M_MASK) != M_END) {
749 		if ((*pat & M_MASK) == M_RNG) {
750 		    __Char wc2;
751 
752 		    pat += pwk;
753 		    pwk = One_Char_mbtowc(&wc2, pat, MB_LEN_MAX);
754 		    if (globcharcoll(wc1, wk, 0) <= 0 &&
755 			globcharcoll(wk, wc2, 0) <= 0)
756 			ok = 1;
757 		} else if (wc == wk)
758 		    ok = 1;
759 		pat += pwk;
760 		wc1 = wc;
761 		pwk = One_Char_mbtowc(&wc, pat, MB_LEN_MAX);
762 	    }
763 	    pat += pwk;
764 	    pwk = One_Char_mbtowc(&wc, pat, MB_LEN_MAX);
765 	    if (ok == negate_range)
766 		break;
767 	    continue;
768 	default:
769 	    if (*name == EOS || samecase(wk) != samecase(wc))
770 		break;
771 	    name += lwk;
772 	    pat += pwk;
773 	    continue;
774 	}
775 	if (nameNext != nameStart
776 	    && (nameEnd == NULL || nameNext <= nameEnd)) {
777 	    pat = patNext;
778 	    name = nameNext;
779 	    continue;
780 	}
781 	return 0;
782     }
783     return 1;
784 }
785 
786 /* free allocated data belonging to a glob_t structure */
787 void
788 globfree(glob_t *pglob)
789 {
790     int i;
791     char **pp;
792 
793     if (pglob->gl_pathv != NULL) {
794 	pp = pglob->gl_pathv + pglob->gl_offs;
795 	for (i = pglob->gl_pathc; i--; ++pp)
796 	    if (*pp)
797 		xfree(*pp), *pp = NULL;
798 	xfree(pglob->gl_pathv), pglob->gl_pathv = NULL;
799     }
800 }
801