1/*
2 * Modified for the Android NDK by Gabor Cselle, http://www.gaborcselle.com/
3 * Tested with Android NDK version 5b: http://developer.android.com/sdk/ndk/index.html
4 * Last modified: March 3 2011
5 *
6 * Copyright (c) 1989, 1993
7 *	The Regents of the University of California.  All rights reserved.
8 *
9 * This code is derived from software contributed to Berkeley by
10 * Guido van Rossum.
11 *
12 * Redistribution and use in source and binary forms, with or without
13 * modification, are permitted provided that the following conditions
14 * are met:
15 * 1. Redistributions of source code must retain the above copyright
16 *    notice, this list of conditions and the following disclaimer.
17 * 2. Redistributions in binary form must reproduce the above copyright
18 *    notice, this list of conditions and the following disclaimer in the
19 *    documentation and/or other materials provided with the distribution.
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.
23 *
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
34 * SUCH DAMAGE.
35 */
36
37#if defined(LIBC_SCCS) && !defined(lint)
38static 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$");
42
43/*
44 * glob(3) -- a superset of the one defined in POSIX 1003.2.
45 *
46 * The [!...] convention to negate a range is supported (SysV, Posix, ksh).
47 *
48 * Optional extra services, controlled by flags not defined by POSIX:
49 *
50 * GLOB_QUOTE:
51 *	Escaping convention: \ inhibits any special meaning the following
52 *	character might have (except \ at end of string is retained).
53 * GLOB_MAGCHAR:
54 *	Set in gl_flags if pattern contained a globbing character.
55 * GLOB_NOMAGIC:
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]
58 * GLOB_ALTDIRFUNC:
59 *	Use alternately specified directory access functions.
60 * GLOB_TILDE:
61 *	expand ~user/foo to the /home/dir/of/user/foo
62 * GLOB_BRACE:
63 *	expand {1,2}{a,b} to 1a 1b 2a 2b
64 * gl_matchc:
65 *	Number of matches in the current invocation of glob.
66 */
67
68/*
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
74 *    cast to wchar_t.
75 * 3. State-dependent encodings are not currently supported.
76 */
77
78#include <sys/param.h>
79#include <sys/stat.h>
80
81#include <ctype.h>
82#include <dirent.h>
83#include <errno.h>
84#include "glob.h"
85#include <limits.h>
86#include <pwd.h>
87#include <stdint.h>
88#include <stdio.h>
89#include <stdlib.h>
90#include <string.h>
91#include <unistd.h>
92#include <wchar.h>
93
94//#include "collate.h" - NOTE(gabor): I took this out because it's not available for Android
95//      and collate is only used once for string comparisons. As a side-effect, you might not
96//      be able to match non-ASCII filenames.
97
98#define	DOLLAR		'$'
99#define	DOT		'.'
100#define	EOS		'\0'
101#define	LBRACKET	'['
102#define	NOT		'!'
103#define	QUESTION	'?'
104#define	QUOTE		'\\'
105#define	RANGE		'-'
106#define	RBRACKET	']'
107#define	SEP		'/'
108#define	STAR		'*'
109#define	TILDE		'~'
110#define	UNDERSCORE	'_'
111#define	LBRACE		'{'
112#define	RBRACE		'}'
113#define	SLASH		'/'
114#define	COMMA		','
115
116#ifndef DEBUG
117
118#define	M_QUOTE		0x8000000000ULL
119#define	M_PROTECT	0x4000000000ULL
120#define	M_MASK		0xffffffffffULL
121#define	M_CHAR		0x00ffffffffULL
122
123typedef uint_fast64_t Char;
124
125#else
126
127#define	M_QUOTE		0x80
128#define	M_PROTECT	0x40
129#define	M_MASK		0xff
130#define	M_CHAR		0x7f
131
132typedef char Char;
133
134#endif
135
136
137#define	CHAR(c)		((Char)((c)&M_CHAR))
138#define	META(c)		((Char)((c)|M_QUOTE))
139#define	M_ALL		META('*')
140#define	M_END		META(']')
141#define	M_NOT		META('!')
142#define	M_ONE		META('?')
143#define	M_RNG		META('-')
144#define	M_SET		META('[')
145#define	ismeta(c)	(((c)&M_QUOTE) != 0)
146
147
148static int	 compare(const void *, const void *);
149static int	 g_Ctoc(const Char *, char *, size_t);
150static int	 g_lstat(Char *, struct stat *, glob_t *);
151static DIR	*g_opendir(Char *, glob_t *);
152static const Char *g_strchr(const Char *, wchar_t);
153#ifdef notdef
154static Char	*g_strcat(Char *, const Char *);
155#endif
156static int	 g_stat(Char *, struct stat *, glob_t *);
157static int	 glob0(const Char *, glob_t *, size_t *);
158static int	 glob1(Char *, glob_t *, size_t *);
159static int	 glob2(Char *, Char *, Char *, Char *, glob_t *, size_t *);
160static int	 glob3(Char *, Char *, Char *, Char *, Char *, glob_t *, size_t *);
161static int	 globextend(const Char *, glob_t *, size_t *);
162static const Char *
163		 globtilde(const Char *, Char *, size_t, glob_t *);
164static int	 globexp1(const Char *, glob_t *, size_t *);
165static int	 globexp2(const Char *, const Char *, glob_t *, int *, size_t *);
166static int	 match(Char *, Char *, Char *);
167#ifdef DEBUG
168static void	 qprintf(const char *, Char *);
169#endif
170
171int
172glob(const char *pattern, int flags, int (*errfunc)(const char *, int), glob_t *pglob)
173{
174	const char *patnext;
175	size_t limit;
176	Char *bufnext, *bufend, patbuf[MAXPATHLEN], prot;
177	mbstate_t mbs;
178	wchar_t wc;
179	size_t clen;
180
181	patnext = pattern;
182	if (!(flags & GLOB_APPEND)) {
183		pglob->gl_pathc = 0;
184		pglob->gl_pathv = NULL;
185		if (!(flags & GLOB_DOOFFS))
186			pglob->gl_offs = 0;
187	}
188	if (flags & GLOB_LIMIT) {
189		limit = pglob->gl_matchc;
190		if (limit == 0)
191			limit = ARG_MAX;
192	} else
193		limit = 0;
194	pglob->gl_flags = flags & ~GLOB_MAGCHAR;
195	pglob->gl_errfunc = errfunc;
196	pglob->gl_matchc = 0;
197
198	bufnext = patbuf;
199	bufend = bufnext + MAXPATHLEN - 1;
200	if (flags & GLOB_NOESCAPE) {
201		memset(&mbs, 0, sizeof(mbs));
202		while (bufend - bufnext >= MB_CUR_MAX) {
203			clen = mbrtowc(&wc, patnext, MB_LEN_MAX, &mbs);
204			if (clen == (size_t)-1 || clen == (size_t)-2)
205				return (GLOB_NOMATCH);
206			else if (clen == 0)
207				break;
208			*bufnext++ = wc;
209			patnext += clen;
210		}
211	} else {
212		/* Protect the quoted characters. */
213		memset(&mbs, 0, sizeof(mbs));
214		while (bufend - bufnext >= MB_CUR_MAX) {
215			if (*patnext == QUOTE) {
216				if (*++patnext == EOS) {
217					*bufnext++ = QUOTE | M_PROTECT;
218					continue;
219				}
220				prot = M_PROTECT;
221			} else
222				prot = 0;
223			clen = mbrtowc(&wc, patnext, MB_LEN_MAX, &mbs);
224			if (clen == (size_t)-1 || clen == (size_t)-2)
225				return (GLOB_NOMATCH);
226			else if (clen == 0)
227				break;
228			*bufnext++ = wc | prot;
229			patnext += clen;
230		}
231	}
232	*bufnext = EOS;
233
234	if (flags & GLOB_BRACE)
235	    return globexp1(patbuf, pglob, &limit);
236	else
237	    return glob0(patbuf, pglob, &limit);
238}
239
240/*
241 * Expand recursively a glob {} pattern. When there is no more expansion
242 * invoke the standard globbing routine to glob the rest of the magic
243 * characters
244 */
245static int
246globexp1(const Char *pattern, glob_t *pglob, size_t *limit)
247{
248	const Char* ptr = pattern;
249	int rv;
250
251	/* Protect a single {}, for find(1), like csh */
252	if (pattern[0] == LBRACE && pattern[1] == RBRACE && pattern[2] == EOS)
253		return glob0(pattern, pglob, limit);
254
255	while ((ptr = g_strchr(ptr, LBRACE)) != NULL)
256		if (!globexp2(ptr, pattern, pglob, &rv, limit))
257			return rv;
258
259	return glob0(pattern, pglob, limit);
260}
261
262
263/*
264 * Recursive brace globbing helper. Tries to expand a single brace.
265 * If it succeeds then it invokes globexp1 with the new pattern.
266 * If it fails then it tries to glob the rest of the pattern and returns.
267 */
268static int
269globexp2(const Char *ptr, const Char *pattern, glob_t *pglob, int *rv, size_t *limit)
270{
271	int     i;
272	Char   *lm, *ls;
273	const Char *pe, *pm, *pm1, *pl;
274	Char    patbuf[MAXPATHLEN];
275
276	/* copy part up to the brace */
277	for (lm = patbuf, pm = pattern; pm != ptr; *lm++ = *pm++)
278		continue;
279	*lm = EOS;
280	ls = lm;
281
282	/* Find the balanced brace */
283	for (i = 0, pe = ++ptr; *pe; pe++)
284		if (*pe == LBRACKET) {
285			/* Ignore everything between [] */
286			for (pm = pe++; *pe != RBRACKET && *pe != EOS; pe++)
287				continue;
288			if (*pe == EOS) {
289				/*
290				 * We could not find a matching RBRACKET.
291				 * Ignore and just look for RBRACE
292				 */
293				pe = pm;
294			}
295		}
296		else if (*pe == LBRACE)
297			i++;
298		else if (*pe == RBRACE) {
299			if (i == 0)
300				break;
301			i--;
302		}
303
304	/* Non matching braces; just glob the pattern */
305	if (i != 0 || *pe == EOS) {
306		*rv = glob0(patbuf, pglob, limit);
307		return 0;
308	}
309
310	for (i = 0, pl = pm = ptr; pm <= pe; pm++)
311		switch (*pm) {
312		case LBRACKET:
313			/* Ignore everything between [] */
314			for (pm1 = pm++; *pm != RBRACKET && *pm != EOS; pm++)
315				continue;
316			if (*pm == EOS) {
317				/*
318				 * We could not find a matching RBRACKET.
319				 * Ignore and just look for RBRACE
320				 */
321				pm = pm1;
322			}
323			break;
324
325		case LBRACE:
326			i++;
327			break;
328
329		case RBRACE:
330			if (i) {
331			    i--;
332			    break;
333			}
334			/* FALLTHROUGH */
335		case COMMA:
336			if (i && *pm == COMMA)
337				break;
338			else {
339				/* Append the current string */
340				for (lm = ls; (pl < pm); *lm++ = *pl++)
341					continue;
342				/*
343				 * Append the rest of the pattern after the
344				 * closing brace
345				 */
346				for (pl = pe + 1; (*lm++ = *pl++) != EOS;)
347					continue;
348
349				/* Expand the current pattern */
350#ifdef DEBUG
351				qprintf("globexp2:", patbuf);
352#endif
353				*rv = globexp1(patbuf, pglob, limit);
354
355				/* move after the comma, to the next string */
356				pl = pm + 1;
357			}
358			break;
359
360		default:
361			break;
362		}
363	*rv = 0;
364	return 0;
365}
366
367
368
369/*
370 * expand tilde from the passwd file.
371 */
372static const Char *
373globtilde(const Char *pattern, Char *patbuf, size_t patbuf_len, glob_t *pglob)
374{
375	struct passwd *pwd;
376	char *h;
377	const Char *p;
378	Char *b, *eb;
379
380	if (*pattern != TILDE || !(pglob->gl_flags & GLOB_TILDE))
381		return pattern;
382
383	/*
384	 * Copy up to the end of the string or /
385	 */
386	eb = &patbuf[patbuf_len - 1];
387	for (p = pattern + 1, h = (char *) patbuf;
388	    h < (char *)eb && *p && *p != SLASH; *h++ = *p++)
389		continue;
390
391	*h = EOS;
392
393	if (((char *) patbuf)[0] == EOS) {
394		/*
395		 * handle a plain ~ or ~/ by expanding $HOME first (iff
396		 * we're not running setuid or setgid) and then trying
397		 * the password file
398		 */
399#ifndef __BIONIC__
400		if (issetugid() != 0 ||
401		    (h = getenv("HOME")) == NULL) {
402			if (((h = getlogin()) != NULL &&
403			     (pwd = getpwnam(h)) != NULL) ||
404			    (pwd = getpwuid(getuid())) != NULL)
405				h = pwd->pw_dir;
406			else
407				return pattern;
408		}
409#endif
410	}
411	else {
412		/*
413		 * Expand a ~user
414		 */
415		if ((pwd = getpwnam((char*) patbuf)) == NULL)
416			return pattern;
417		else
418			h = pwd->pw_dir;
419	}
420
421	/* Copy the home directory */
422	for (b = patbuf; b < eb && *h; *b++ = *h++)
423		continue;
424
425	/* Append the rest of the pattern */
426	while (b < eb && (*b++ = *p++) != EOS)
427		continue;
428	*b = EOS;
429
430	return patbuf;
431}
432
433
434/*
435 * The main glob() routine: compiles the pattern (optionally processing
436 * quotes), calls glob1() to do the real pattern matching, and finally
437 * sorts the list (unless unsorted operation is requested).  Returns 0
438 * if things went well, nonzero if errors occurred.
439 */
440static int
441glob0(const Char *pattern, glob_t *pglob, size_t *limit)
442{
443	const Char *qpatnext;
444	int err;
445	size_t oldpathc;
446	Char *bufnext, c, patbuf[MAXPATHLEN];
447
448	qpatnext = globtilde(pattern, patbuf, MAXPATHLEN, pglob);
449	oldpathc = pglob->gl_pathc;
450	bufnext = patbuf;
451
452	/* We don't need to check for buffer overflow any more. */
453	while ((c = *qpatnext++) != EOS) {
454		switch (c) {
455		case LBRACKET:
456			c = *qpatnext;
457			if (c == NOT)
458				++qpatnext;
459			if (*qpatnext == EOS ||
460			    g_strchr(qpatnext+1, RBRACKET) == NULL) {
461				*bufnext++ = LBRACKET;
462				if (c == NOT)
463					--qpatnext;
464				break;
465			}
466			*bufnext++ = M_SET;
467			if (c == NOT)
468				*bufnext++ = M_NOT;
469			c = *qpatnext++;
470			do {
471				*bufnext++ = CHAR(c);
472				if (*qpatnext == RANGE &&
473				    (c = qpatnext[1]) != RBRACKET) {
474					*bufnext++ = M_RNG;
475					*bufnext++ = CHAR(c);
476					qpatnext += 2;
477				}
478			} while ((c = *qpatnext++) != RBRACKET);
479			pglob->gl_flags |= GLOB_MAGCHAR;
480			*bufnext++ = M_END;
481			break;
482		case QUESTION:
483			pglob->gl_flags |= GLOB_MAGCHAR;
484			*bufnext++ = M_ONE;
485			break;
486		case STAR:
487			pglob->gl_flags |= GLOB_MAGCHAR;
488			/* collapse adjacent stars to one,
489			 * to avoid exponential behavior
490			 */
491			if (bufnext == patbuf || bufnext[-1] != M_ALL)
492			    *bufnext++ = M_ALL;
493			break;
494		default:
495			*bufnext++ = CHAR(c);
496			break;
497		}
498	}
499	*bufnext = EOS;
500#ifdef DEBUG
501	qprintf("glob0:", patbuf);
502#endif
503
504	if ((err = glob1(patbuf, pglob, limit)) != 0)
505		return(err);
506
507	/*
508	 * If there was no match we are going to append the pattern
509	 * if GLOB_NOCHECK was specified or if GLOB_NOMAGIC was specified
510	 * and the pattern did not contain any magic characters
511	 * GLOB_NOMAGIC is there just for compatibility with csh.
512	 */
513	if (pglob->gl_pathc == oldpathc) {
514		if (((pglob->gl_flags & GLOB_NOCHECK) ||
515		    ((pglob->gl_flags & GLOB_NOMAGIC) &&
516			!(pglob->gl_flags & GLOB_MAGCHAR))))
517			return(globextend(pattern, pglob, limit));
518		else
519			return(GLOB_NOMATCH);
520	}
521	if (!(pglob->gl_flags & GLOB_NOSORT))
522		qsort(pglob->gl_pathv + pglob->gl_offs + oldpathc,
523		    pglob->gl_pathc - oldpathc, sizeof(char *), compare);
524	return(0);
525}
526
527static int
528compare(const void *p, const void *q)
529{
530	return(strcmp(*(char **)p, *(char **)q));
531}
532
533static int
534glob1(Char *pattern, glob_t *pglob, size_t *limit)
535{
536	Char pathbuf[MAXPATHLEN];
537
538	/* A null pathname is invalid -- POSIX 1003.1 sect. 2.4. */
539	if (*pattern == EOS)
540		return(0);
541	return(glob2(pathbuf, pathbuf, pathbuf + MAXPATHLEN - 1,
542	    pattern, pglob, limit));
543}
544
545/*
546 * The functions glob2 and glob3 are mutually recursive; there is one level
547 * of recursion for each segment in the pattern that contains one or more
548 * meta characters.
549 */
550static int
551glob2(Char *pathbuf, Char *pathend, Char *pathend_last, Char *pattern,
552      glob_t *pglob, size_t *limit)
553{
554	struct stat sb;
555	Char *p, *q;
556	int anymeta;
557
558	/*
559	 * Loop over pattern segments until end of pattern or until
560	 * segment with meta character found.
561	 */
562	for (anymeta = 0;;) {
563		if (*pattern == EOS) {		/* End of pattern? */
564			*pathend = EOS;
565			if (g_lstat(pathbuf, &sb, pglob))
566				return(0);
567
568			if (((pglob->gl_flags & GLOB_MARK) &&
569			    pathend[-1] != SEP) && (S_ISDIR(sb.st_mode)
570			    || (S_ISLNK(sb.st_mode) &&
571			    (g_stat(pathbuf, &sb, pglob) == 0) &&
572			    S_ISDIR(sb.st_mode)))) {
573				if (pathend + 1 > pathend_last)
574					return (GLOB_ABORTED);
575				*pathend++ = SEP;
576				*pathend = EOS;
577			}
578			++pglob->gl_matchc;
579			return(globextend(pathbuf, pglob, limit));
580		}
581
582		/* Find end of next segment, copy tentatively to pathend. */
583		q = pathend;
584		p = pattern;
585		while (*p != EOS && *p != SEP) {
586			if (ismeta(*p))
587				anymeta = 1;
588			if (q + 1 > pathend_last)
589				return (GLOB_ABORTED);
590			*q++ = *p++;
591		}
592
593		if (!anymeta) {		/* No expansion, do next segment. */
594			pathend = q;
595			pattern = p;
596			while (*pattern == SEP) {
597				if (pathend + 1 > pathend_last)
598					return (GLOB_ABORTED);
599				*pathend++ = *pattern++;
600			}
601		} else			/* Need expansion, recurse. */
602			return(glob3(pathbuf, pathend, pathend_last, pattern, p,
603			    pglob, limit));
604	}
605	/* NOTREACHED */
606}
607
608static int
609glob3(Char *pathbuf, Char *pathend, Char *pathend_last,
610      Char *pattern, Char *restpattern,
611      glob_t *pglob, size_t *limit)
612{
613	struct dirent *dp;
614	DIR *dirp;
615	int err;
616	char buf[MAXPATHLEN];
617
618	/*
619	 * The readdirfunc declaration can't be prototyped, because it is
620	 * assigned, below, to two functions which are prototyped in glob.h
621	 * and dirent.h as taking pointers to differently typed opaque
622	 * structures.
623	 */
624	struct dirent *(*readdirfunc)();
625
626	if (pathend > pathend_last)
627		return (GLOB_ABORTED);
628	*pathend = EOS;
629	errno = 0;
630
631	if ((dirp = g_opendir(pathbuf, pglob)) == NULL) {
632		/* TODO: don't call for ENOENT or ENOTDIR? */
633		if (pglob->gl_errfunc) {
634			if (g_Ctoc(pathbuf, buf, sizeof(buf)))
635				return (GLOB_ABORTED);
636			if (pglob->gl_errfunc(buf, errno) ||
637			    pglob->gl_flags & GLOB_ERR)
638				return (GLOB_ABORTED);
639		}
640		return(0);
641	}
642
643	err = 0;
644
645	/* Search directory for matching names. */
646	if (pglob->gl_flags & GLOB_ALTDIRFUNC)
647		readdirfunc = pglob->gl_readdir;
648	else
649		readdirfunc = readdir;
650	while ((dp = (*readdirfunc)(dirp))) {
651		char *sc;
652		Char *dc;
653		wchar_t wc;
654		size_t clen;
655		mbstate_t mbs;
656
657		/* Initial DOT must be matched literally. */
658		if (dp->d_name[0] == DOT && *pattern != DOT)
659			continue;
660		memset(&mbs, 0, sizeof(mbs));
661		dc = pathend;
662		sc = dp->d_name;
663		while (dc < pathend_last) {
664			clen = mbrtowc(&wc, sc, MB_LEN_MAX, &mbs);
665			if (clen == (size_t)-1 || clen == (size_t)-2) {
666				wc = *sc;
667				clen = 1;
668				memset(&mbs, 0, sizeof(mbs));
669			}
670			if ((*dc++ = wc) == EOS)
671				break;
672			sc += clen;
673		}
674		if (!match(pathend, pattern, restpattern)) {
675			*pathend = EOS;
676			continue;
677		}
678		err = glob2(pathbuf, --dc, pathend_last, restpattern,
679		    pglob, limit);
680		if (err)
681			break;
682	}
683
684	if (pglob->gl_flags & GLOB_ALTDIRFUNC)
685		(*pglob->gl_closedir)(dirp);
686	else
687		closedir(dirp);
688	return(err);
689}
690
691
692/*
693 * Extend the gl_pathv member of a glob_t structure to accomodate a new item,
694 * add the new item, and update gl_pathc.
695 *
696 * This assumes the BSD realloc, which only copies the block when its size
697 * crosses a power-of-two boundary; for v7 realloc, this would cause quadratic
698 * behavior.
699 *
700 * Return 0 if new item added, error code if memory couldn't be allocated.
701 *
702 * Invariant of the glob_t structure:
703 *	Either gl_pathc is zero and gl_pathv is NULL; or gl_pathc > 0 and
704 *	gl_pathv points to (gl_offs + gl_pathc + 1) items.
705 */
706static int
707globextend(const Char *path, glob_t *pglob, size_t *limit)
708{
709	char **pathv;
710	size_t i, newsize, len;
711	char *copy;
712	const Char *p;
713
714	if (*limit && pglob->gl_pathc > *limit) {
715		errno = 0;
716		return (GLOB_NOSPACE);
717	}
718
719	newsize = sizeof(*pathv) * (2 + pglob->gl_pathc + pglob->gl_offs);
720	pathv = pglob->gl_pathv ?
721		    realloc((char *)pglob->gl_pathv, newsize) :
722		    malloc(newsize);
723	if (pathv == NULL) {
724		if (pglob->gl_pathv) {
725			free(pglob->gl_pathv);
726			pglob->gl_pathv = NULL;
727		}
728		return(GLOB_NOSPACE);
729	}
730
731	if (pglob->gl_pathv == NULL && pglob->gl_offs > 0) {
732		/* first time around -- clear initial gl_offs items */
733		pathv += pglob->gl_offs;
734		for (i = pglob->gl_offs + 1; --i > 0; )
735			*--pathv = NULL;
736	}
737	pglob->gl_pathv = pathv;
738
739	for (p = path; *p++;)
740		continue;
741	len = MB_CUR_MAX * (size_t)(p - path);	/* XXX overallocation */
742	if ((copy = malloc(len)) != NULL) {
743		if (g_Ctoc(path, copy, len)) {
744			free(copy);
745			return (GLOB_NOSPACE);
746		}
747		pathv[pglob->gl_offs + pglob->gl_pathc++] = copy;
748	}
749	pathv[pglob->gl_offs + pglob->gl_pathc] = NULL;
750	return(copy == NULL ? GLOB_NOSPACE : 0);
751}
752
753/*
754 * pattern matching function for filenames.  Each occurrence of the *
755 * pattern causes a recursion level.
756 */
757static int
758match(Char *name, Char *pat, Char *patend)
759{
760	int ok, negate_range;
761	Char c, k;
762
763	while (pat < patend) {
764		c = *pat++;
765		switch (c & M_MASK) {
766		case M_ALL:
767			if (pat == patend)
768				return(1);
769			do
770			    if (match(name, pat, patend))
771				    return(1);
772			while (*name++ != EOS);
773			return(0);
774		case M_ONE:
775			if (*name++ == EOS)
776				return(0);
777			break;
778		case M_SET:
779			ok = 0;
780			if ((k = *name++) == EOS)
781				return(0);
782			if ((negate_range = ((*pat & M_MASK) == M_NOT)) != EOS)
783				++pat;
784			while (((c = *pat++) & M_MASK) != M_END)
785				if ((*pat & M_MASK) == M_RNG) {
786					// NOTE(gabor): This used to be as below, but I took out the collate.h
787					// if (__collate_load_error ?
788					//     CHAR(c) <= CHAR(k) && CHAR(k) <= CHAR(pat[1]) :
789					//        __collate_range_cmp(CHAR(c), CHAR(k)) <= 0
790					//     && __collate_range_cmp(CHAR(k), CHAR(pat[1])) <= 0
791					//    )
792
793					if (CHAR(c) <= CHAR(k) && CHAR(k) <= CHAR(pat[1]))
794						ok = 1;
795					pat += 2;
796				} else if (c == k)
797					ok = 1;
798			if (ok == negate_range)
799				return(0);
800			break;
801		default:
802			if (*name++ != c)
803				return(0);
804			break;
805		}
806	}
807	return(*name == EOS);
808}
809
810/* Free allocated data belonging to a glob_t structure. */
811void
812globfree(glob_t *pglob)
813{
814	size_t i;
815	char **pp;
816
817	if (pglob->gl_pathv != NULL) {
818		pp = pglob->gl_pathv + pglob->gl_offs;
819		for (i = pglob->gl_pathc; i--; ++pp)
820			if (*pp)
821				free(*pp);
822		free(pglob->gl_pathv);
823		pglob->gl_pathv = NULL;
824	}
825}
826
827static DIR *
828g_opendir(Char *str, glob_t *pglob)
829{
830	char buf[MAXPATHLEN];
831
832	if (!*str)
833		strcpy(buf, ".");
834	else {
835		if (g_Ctoc(str, buf, sizeof(buf)))
836			return (NULL);
837	}
838
839	if (pglob->gl_flags & GLOB_ALTDIRFUNC)
840		return((*pglob->gl_opendir)(buf));
841
842	return(opendir(buf));
843}
844
845static int
846g_lstat(Char *fn, struct stat *sb, glob_t *pglob)
847{
848	char buf[MAXPATHLEN];
849
850	if (g_Ctoc(fn, buf, sizeof(buf))) {
851		errno = ENAMETOOLONG;
852		return (-1);
853	}
854	if (pglob->gl_flags & GLOB_ALTDIRFUNC)
855		return((*pglob->gl_lstat)(buf, sb));
856	return(lstat(buf, sb));
857}
858
859static int
860g_stat(Char *fn, struct stat *sb, glob_t *pglob)
861{
862	char buf[MAXPATHLEN];
863
864	if (g_Ctoc(fn, buf, sizeof(buf))) {
865		errno = ENAMETOOLONG;
866		return (-1);
867	}
868	if (pglob->gl_flags & GLOB_ALTDIRFUNC)
869		return((*pglob->gl_stat)(buf, sb));
870	return(stat(buf, sb));
871}
872
873static const Char *
874g_strchr(const Char *str, wchar_t ch)
875{
876
877	do {
878		if (*str == ch)
879			return (str);
880	} while (*str++);
881	return (NULL);
882}
883
884static int
885g_Ctoc(const Char *str, char *buf, size_t len)
886{
887	mbstate_t mbs;
888	size_t clen;
889
890	memset(&mbs, 0, sizeof(mbs));
891	while (len >= MB_CUR_MAX) {
892		clen = wcrtomb(buf, *str, &mbs);
893		if (clen == (size_t)-1)
894			return (1);
895		if (*str == L'\0')
896			return (0);
897		str++;
898		buf += clen;
899		len -= clen;
900	}
901	return (1);
902}
903
904#ifdef DEBUG
905static void
906qprintf(const char *str, Char *s)
907{
908	Char *p;
909
910	(void)printf("%s:\n", str);
911	for (p = s; *p; p++)
912		(void)printf("%c", CHAR(*p));
913	(void)printf("\n");
914	for (p = s; *p; p++)
915		(void)printf("%c", *p & M_PROTECT ? '"' : ' ');
916	(void)printf("\n");
917	for (p = s; *p; p++)
918		(void)printf("%c", ismeta(*p) ? '_' : ' ');
919	(void)printf("\n");
920}
921#endif
922