expand.c revision 231790
111820Sjulian/*-
211820Sjulian * Copyright (c) 1991, 1993
311820Sjulian *	The Regents of the University of California.  All rights reserved.
411820Sjulian * Copyright (c) 1997-2005
511820Sjulian *	Herbert Xu <herbert@gondor.apana.org.au>.  All rights reserved.
611820Sjulian *
711820Sjulian * This code is derived from software contributed to Berkeley by
811820Sjulian * Kenneth Almquist.
911820Sjulian *
1011820Sjulian * Redistribution and use in source and binary forms, with or without
1111820Sjulian * modification, are permitted provided that the following conditions
1211820Sjulian * are met:
1311820Sjulian * 1. Redistributions of source code must retain the above copyright
1411820Sjulian *    notice, this list of conditions and the following disclaimer.
1511820Sjulian * 2. Redistributions in binary form must reproduce the above copyright
1611820Sjulian *    notice, this list of conditions and the following disclaimer in the
1711820Sjulian *    documentation and/or other materials provided with the distribution.
1811820Sjulian * 4. Neither the name of the University nor the names of its contributors
1911820Sjulian *    may be used to endorse or promote products derived from this software
2011820Sjulian *    without specific prior written permission.
2111820Sjulian *
2211820Sjulian * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
2311820Sjulian * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
2411820Sjulian * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
2511820Sjulian * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
2611820Sjulian * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
2711820Sjulian * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
2811820Sjulian * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
2911820Sjulian * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
3011820Sjulian * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
3111820Sjulian * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
3211820Sjulian * SUCH DAMAGE.
3311820Sjulian */
3411820Sjulian
3511820Sjulian#ifndef lint
3611820Sjulian#if 0
3711820Sjulianstatic char sccsid[] = "@(#)expand.c	8.5 (Berkeley) 5/15/95";
3850479Speter#endif
3911820Sjulian#endif /* not lint */
4011820Sjulian#include <sys/cdefs.h>
4111820Sjulian__FBSDID("$FreeBSD: stable/9/bin/sh/expand.c 231790 2012-02-15 22:45:57Z jilles $");
42122760Strhodes
4311820Sjulian#include <sys/types.h>
4411820Sjulian#include <sys/time.h>
4511820Sjulian#include <sys/stat.h>
4611820Sjulian#include <dirent.h>
4711820Sjulian#include <errno.h>
4811820Sjulian#include <inttypes.h>
4911820Sjulian#include <limits.h>
5011820Sjulian#include <pwd.h>
5111820Sjulian#include <stdio.h>
5211820Sjulian#include <stdlib.h>
5311820Sjulian#include <string.h>
5411820Sjulian#include <unistd.h>
5511820Sjulian#include <wchar.h>
5611820Sjulian#include <wctype.h>
5711820Sjulian
5811820Sjulian/*
5911820Sjulian * Routines to expand arguments to commands.  We have to deal with
6011820Sjulian * backquotes, shell variables, and file metacharacters.
6111820Sjulian */
6211820Sjulian
6311820Sjulian#include "shell.h"
6411820Sjulian#include "main.h"
6511820Sjulian#include "nodes.h"
6611820Sjulian#include "eval.h"
6711820Sjulian#include "expand.h"
6811820Sjulian#include "syntax.h"
6911820Sjulian#include "parser.h"
7011820Sjulian#include "jobs.h"
7111820Sjulian#include "options.h"
7211820Sjulian#include "var.h"
7311820Sjulian#include "input.h"
7411820Sjulian#include "output.h"
7511820Sjulian#include "memalloc.h"
7611820Sjulian#include "error.h"
7711820Sjulian#include "mystring.h"
7811820Sjulian#include "arith.h"
7911820Sjulian#include "show.h"
8011820Sjulian#include "builtins.h"
8111820Sjulian
8211820Sjulian/*
8311820Sjulian * Structure specifying which parts of the string should be searched
8411820Sjulian * for IFS characters.
8511820Sjulian */
8611820Sjulian
8711820Sjulianstruct ifsregion {
8811820Sjulian	struct ifsregion *next;	/* next region in list */
8911820Sjulian	int begoff;		/* offset of start of region */
9011820Sjulian	int endoff;		/* offset of end of region */
9111820Sjulian	int inquotes;		/* search for nul bytes only */
9211820Sjulian};
9311820Sjulian
9411820Sjulian
9511820Sjulianstatic char *expdest;			/* output of current string */
9627244Sjhaystatic struct nodelist *argbackq;	/* list of back quote expressions */
9727244Sjhaystatic struct ifsregion ifsfirst;	/* first struct in list of ifs regions */
9827244Sjhaystatic struct ifsregion *ifslastp;	/* last struct in list */
9927244Sjhaystatic struct arglist exparg;		/* holds expanded arg list */
10027244Sjhay
10111820Sjulianstatic void argstr(char *, int);
10227244Sjhaystatic char *exptilde(char *, int);
10327244Sjhaystatic void expbackq(union node *, int, int);
10427244Sjhaystatic int subevalvar(char *, char *, int, int, int, int, int);
10527244Sjhaystatic char *evalvar(char *, int);
10627244Sjhaystatic int varisset(char *, int);
10727244Sjhaystatic void varvalue(char *, int, int, int);
10827244Sjhaystatic void recordregion(int, int, int);
10927244Sjhaystatic void removerecordregions(int);
11027244Sjhaystatic void ifsbreakup(char *, struct arglist *);
11127244Sjhaystatic void expandmeta(struct strlist *, int);
11227244Sjhaystatic void expmeta(char *, char *);
11327244Sjhaystatic void addfname(char *);
11427244Sjhaystatic struct strlist *expsort(struct strlist *);
11527244Sjhaystatic struct strlist *msort(struct strlist *, int);
11627244Sjhaystatic int patmatch(const char *, const char *, int);
11727244Sjhaystatic char *cvtnum(int, char *);
11827244Sjhaystatic int collate_range_cmp(wchar_t, wchar_t);
11911820Sjulian
12011820Sjulianstatic int
12127244Sjhaycollate_range_cmp(wchar_t c1, wchar_t c2)
12211820Sjulian{
12311820Sjulian	static wchar_t s1[2], s2[2];
12411820Sjulian
12511820Sjulian	s1[0] = c1;
12611820Sjulian	s2[0] = c2;
12711820Sjulian	return (wcscoll(s1, s2));
12811820Sjulian}
12911820Sjulian
13011820Sjulian/*
13111820Sjulian * Expand shell variables and backquotes inside a here document.
13211820Sjulian *	union node *arg		the document
13311820Sjulian *	int fd;			where to write the expanded version
13411820Sjulian */
13511820Sjulian
13611820Sjulianvoid
13711820Sjulianexpandhere(union node *arg, int fd)
13811820Sjulian{
13911820Sjulian	expandarg(arg, (struct arglist *)NULL, 0);
14011820Sjulian	xwrite(fd, stackblock(), expdest - stackblock());
14111820Sjulian}
14211820Sjulian
14311820Sjulianstatic char *
14411820Sjulianstputs_quotes(const char *data, const char *syntax, char *p)
14511820Sjulian{
14611820Sjulian	while (*data) {
14711820Sjulian		CHECKSTRSPACE(2, p);
14811820Sjulian		if (syntax[(int)*data] == CCTL)
14911820Sjulian			USTPUTC(CTLESC, p);
15011820Sjulian		USTPUTC(*data++, p);
15111820Sjulian	}
15211820Sjulian	return (p);
15311820Sjulian}
15411820Sjulian#define STPUTS_QUOTES(data, syntax, p) p = stputs_quotes((data), syntax, p)
15511820Sjulian
15611820Sjulian/*
15711820Sjulian * Perform expansions on an argument, placing the resulting list of arguments
15811820Sjulian * in arglist.  Parameter expansion, command substitution and arithmetic
15911820Sjulian * expansion are always performed; additional expansions can be requested
16011820Sjulian * via flag (EXP_*).
16111820Sjulian * The result is left in the stack string.
16211820Sjulian * When arglist is NULL, perform here document expansion.
16311820Sjulian *
16411820Sjulian * Caution: this function uses global state and is not reentrant.
16511820Sjulian * However, a new invocation after an interrupted invocation is safe
16611820Sjulian * and will reset the global state for the new call.
16711820Sjulian */
16811820Sjulianvoid
16911820Sjulianexpandarg(union node *arg, struct arglist *arglist, int flag)
17011820Sjulian{
17111820Sjulian	struct strlist *sp;
17211820Sjulian	char *p;
17311820Sjulian
17411820Sjulian	argbackq = arg->narg.backquote;
17511820Sjulian	STARTSTACKSTR(expdest);
17611820Sjulian	ifsfirst.next = NULL;
17711820Sjulian	ifslastp = NULL;
17811820Sjulian	argstr(arg->narg.text, flag);
17911820Sjulian	if (arglist == NULL) {
18011820Sjulian		STACKSTRNUL(expdest);
18111820Sjulian		return;			/* here document expanded */
18211820Sjulian	}
18311820Sjulian	STPUTC('\0', expdest);
18411820Sjulian	p = grabstackstr(expdest);
18511820Sjulian	exparg.lastp = &exparg.list;
18611820Sjulian	/*
18711820Sjulian	 * TODO - EXP_REDIR
18811820Sjulian	 */
18911820Sjulian	if (flag & EXP_FULL) {
19011820Sjulian		ifsbreakup(p, &exparg);
19111820Sjulian		*exparg.lastp = NULL;
19211820Sjulian		exparg.lastp = &exparg.list;
19311820Sjulian		expandmeta(exparg.list, flag);
19411820Sjulian	} else {
19511820Sjulian		if (flag & EXP_REDIR) /*XXX - for now, just remove escapes */
19611820Sjulian			rmescapes(p);
19711820Sjulian		sp = (struct strlist *)stalloc(sizeof (struct strlist));
19811820Sjulian		sp->text = p;
19911820Sjulian		*exparg.lastp = sp;
20011820Sjulian		exparg.lastp = &sp->next;
20111820Sjulian	}
20211820Sjulian	while (ifsfirst.next != NULL) {
20311820Sjulian		struct ifsregion *ifsp;
20411820Sjulian		INTOFF;
20511820Sjulian		ifsp = ifsfirst.next->next;
20611820Sjulian		ckfree(ifsfirst.next);
20711820Sjulian		ifsfirst.next = ifsp;
20811820Sjulian		INTON;
20911820Sjulian	}
21011820Sjulian	*exparg.lastp = NULL;
21111820Sjulian	if (exparg.list) {
21211820Sjulian		*arglist->lastp = exparg.list;
21311820Sjulian		arglist->lastp = exparg.lastp;
21411820Sjulian	}
21512620Sjulian}
21612620Sjulian
21711820Sjulian
21811820Sjulian
21912620Sjulian/*
22012620Sjulian * Perform parameter expansion, command substitution and arithmetic
22111820Sjulian * expansion, and tilde expansion if requested via EXP_TILDE/EXP_VARTILDE.
22211820Sjulian * Processing ends at a CTLENDVAR character as well as '\0'.
22311820Sjulian * This is used to expand word in ${var+word} etc.
22411820Sjulian * If EXP_FULL, EXP_CASE or EXP_REDIR are set, keep and/or generate CTLESC
22511820Sjulian * characters to allow for further processing.
22611820Sjulian * If EXP_FULL is set, also preserve CTLQUOTEMARK characters.
22711820Sjulian */
22811820Sjulianstatic void
22911820Sjulianargstr(char *p, int flag)
23011820Sjulian{
23111820Sjulian	char c;
23211820Sjulian	int quotes = flag & (EXP_FULL | EXP_CASE | EXP_REDIR);	/* do CTLESC */
23311820Sjulian	int firsteq = 1;
23411820Sjulian	int split_lit;
23511820Sjulian	int lit_quoted;
23611820Sjulian
23711820Sjulian	split_lit = flag & EXP_SPLIT_LIT;
23811820Sjulian	lit_quoted = flag & EXP_LIT_QUOTED;
23911820Sjulian	flag &= ~(EXP_SPLIT_LIT | EXP_LIT_QUOTED);
24011820Sjulian	if (*p == '~' && (flag & (EXP_TILDE | EXP_VARTILDE)))
24111820Sjulian		p = exptilde(p, flag);
24211820Sjulian	for (;;) {
24311820Sjulian		CHECKSTRSPACE(2, expdest);
24411820Sjulian		switch (c = *p++) {
24511820Sjulian		case '\0':
24611820Sjulian		case CTLENDVAR:
24711820Sjulian			goto breakloop;
24811820Sjulian		case CTLQUOTEMARK:
24911820Sjulian			lit_quoted = 1;
25011820Sjulian			/* "$@" syntax adherence hack */
25111820Sjulian			if (p[0] == CTLVAR && p[2] == '@' && p[3] == '=')
25211820Sjulian				break;
25311820Sjulian			if ((flag & EXP_FULL) != 0)
25411820Sjulian				USTPUTC(c, expdest);
25511820Sjulian			break;
25611820Sjulian		case CTLQUOTEEND:
25711820Sjulian			lit_quoted = 0;
25811820Sjulian			break;
25911820Sjulian		case CTLESC:
26011820Sjulian			if (quotes)
26111820Sjulian				USTPUTC(c, expdest);
26211820Sjulian			c = *p++;
26311820Sjulian			USTPUTC(c, expdest);
26411820Sjulian			if (split_lit && !lit_quoted)
26511820Sjulian				recordregion(expdest - stackblock() -
26611820Sjulian				    (quotes ? 2 : 1),
26711820Sjulian				    expdest - stackblock(), 0);
26811820Sjulian			break;
26911820Sjulian		case CTLVAR:
27011820Sjulian			p = evalvar(p, flag);
27111820Sjulian			break;
27211820Sjulian		case CTLBACKQ:
27311820Sjulian		case CTLBACKQ|CTLQUOTE:
27411820Sjulian			expbackq(argbackq->n, c & CTLQUOTE, flag);
27511820Sjulian			argbackq = argbackq->next;
27611820Sjulian			break;
27711820Sjulian		case CTLENDARI:
27811820Sjulian			expari(flag);
27911820Sjulian			break;
28011820Sjulian		case ':':
28111820Sjulian		case '=':
28211820Sjulian			/*
28311820Sjulian			 * sort of a hack - expand tildes in variable
28411820Sjulian			 * assignments (after the first '=' and after ':'s).
28511820Sjulian			 */
28611820Sjulian			USTPUTC(c, expdest);
28711820Sjulian			if (split_lit && !lit_quoted)
28811820Sjulian				recordregion(expdest - stackblock() - 1,
28911820Sjulian				    expdest - stackblock(), 0);
29011820Sjulian			if (flag & EXP_VARTILDE && *p == '~' &&
29111820Sjulian			    (c != '=' || firsteq)) {
29211820Sjulian				if (c == '=')
29311820Sjulian					firsteq = 0;
29411820Sjulian				p = exptilde(p, flag);
29511820Sjulian			}
29611820Sjulian			break;
29711820Sjulian		default:
29811820Sjulian			USTPUTC(c, expdest);
299			if (split_lit && !lit_quoted)
300				recordregion(expdest - stackblock() - 1,
301				    expdest - stackblock(), 0);
302		}
303	}
304breakloop:;
305}
306
307/*
308 * Perform tilde expansion, placing the result in the stack string and
309 * returning the next position in the input string to process.
310 */
311static char *
312exptilde(char *p, int flag)
313{
314	char c, *startp = p;
315	struct passwd *pw;
316	char *home;
317	int quotes = flag & (EXP_FULL | EXP_CASE | EXP_REDIR);
318
319	while ((c = *p) != '\0') {
320		switch(c) {
321		case CTLESC: /* This means CTL* are always considered quoted. */
322		case CTLVAR:
323		case CTLBACKQ:
324		case CTLBACKQ | CTLQUOTE:
325		case CTLARI:
326		case CTLENDARI:
327		case CTLQUOTEMARK:
328			return (startp);
329		case ':':
330			if (flag & EXP_VARTILDE)
331				goto done;
332			break;
333		case '/':
334		case CTLENDVAR:
335			goto done;
336		}
337		p++;
338	}
339done:
340	*p = '\0';
341	if (*(startp+1) == '\0') {
342		if ((home = lookupvar("HOME")) == NULL)
343			goto lose;
344	} else {
345		if ((pw = getpwnam(startp+1)) == NULL)
346			goto lose;
347		home = pw->pw_dir;
348	}
349	if (*home == '\0')
350		goto lose;
351	*p = c;
352	if (quotes)
353		STPUTS_QUOTES(home, SQSYNTAX, expdest);
354	else
355		STPUTS(home, expdest);
356	return (p);
357lose:
358	*p = c;
359	return (startp);
360}
361
362
363static void
364removerecordregions(int endoff)
365{
366	if (ifslastp == NULL)
367		return;
368
369	if (ifsfirst.endoff > endoff) {
370		while (ifsfirst.next != NULL) {
371			struct ifsregion *ifsp;
372			INTOFF;
373			ifsp = ifsfirst.next->next;
374			ckfree(ifsfirst.next);
375			ifsfirst.next = ifsp;
376			INTON;
377		}
378		if (ifsfirst.begoff > endoff)
379			ifslastp = NULL;
380		else {
381			ifslastp = &ifsfirst;
382			ifsfirst.endoff = endoff;
383		}
384		return;
385	}
386
387	ifslastp = &ifsfirst;
388	while (ifslastp->next && ifslastp->next->begoff < endoff)
389		ifslastp=ifslastp->next;
390	while (ifslastp->next != NULL) {
391		struct ifsregion *ifsp;
392		INTOFF;
393		ifsp = ifslastp->next->next;
394		ckfree(ifslastp->next);
395		ifslastp->next = ifsp;
396		INTON;
397	}
398	if (ifslastp->endoff > endoff)
399		ifslastp->endoff = endoff;
400}
401
402/*
403 * Expand arithmetic expression.  Backup to start of expression,
404 * evaluate, place result in (backed up) result, adjust string position.
405 */
406void
407expari(int flag)
408{
409	char *p, *q, *start;
410	arith_t result;
411	int begoff;
412	int quotes = flag & (EXP_FULL | EXP_CASE | EXP_REDIR);
413	int quoted;
414
415	/*
416	 * This routine is slightly over-complicated for
417	 * efficiency.  First we make sure there is
418	 * enough space for the result, which may be bigger
419	 * than the expression.  Next we
420	 * scan backwards looking for the start of arithmetic.  If the
421	 * next previous character is a CTLESC character, then we
422	 * have to rescan starting from the beginning since CTLESC
423	 * characters have to be processed left to right.
424	 */
425	CHECKSTRSPACE(DIGITS(result) - 2, expdest);
426	USTPUTC('\0', expdest);
427	start = stackblock();
428	p = expdest - 2;
429	while (p >= start && *p != CTLARI)
430		--p;
431	if (p < start || *p != CTLARI)
432		error("missing CTLARI (shouldn't happen)");
433	if (p > start && *(p - 1) == CTLESC)
434		for (p = start; *p != CTLARI; p++)
435			if (*p == CTLESC)
436				p++;
437
438	if (p[1] == '"')
439		quoted=1;
440	else
441		quoted=0;
442	begoff = p - start;
443	removerecordregions(begoff);
444	if (quotes)
445		rmescapes(p+2);
446	q = grabstackstr(expdest);
447	result = arith(p+2);
448	ungrabstackstr(q, expdest);
449	fmtstr(p, DIGITS(result), ARITH_FORMAT_STR, result);
450	while (*p++)
451		;
452	if (quoted == 0)
453		recordregion(begoff, p - 1 - start, 0);
454	result = expdest - p + 1;
455	STADJUST(-result, expdest);
456}
457
458
459/*
460 * Perform command substitution.
461 */
462static void
463expbackq(union node *cmd, int quoted, int flag)
464{
465	struct backcmd in;
466	int i;
467	char buf[128];
468	char *p;
469	char *dest = expdest;
470	struct ifsregion saveifs, *savelastp;
471	struct nodelist *saveargbackq;
472	char lastc;
473	int startloc = dest - stackblock();
474	char const *syntax = quoted? DQSYNTAX : BASESYNTAX;
475	int quotes = flag & (EXP_FULL | EXP_CASE | EXP_REDIR);
476	int nnl;
477
478	INTOFF;
479	saveifs = ifsfirst;
480	savelastp = ifslastp;
481	saveargbackq = argbackq;
482	p = grabstackstr(dest);
483	evalbackcmd(cmd, &in);
484	ungrabstackstr(p, dest);
485	ifsfirst = saveifs;
486	ifslastp = savelastp;
487	argbackq = saveargbackq;
488
489	p = in.buf;
490	lastc = '\0';
491	nnl = 0;
492	/* Don't copy trailing newlines */
493	for (;;) {
494		if (--in.nleft < 0) {
495			if (in.fd < 0)
496				break;
497			while ((i = read(in.fd, buf, sizeof buf)) < 0 && errno == EINTR);
498			TRACE(("expbackq: read returns %d\n", i));
499			if (i <= 0)
500				break;
501			p = buf;
502			in.nleft = i - 1;
503		}
504		lastc = *p++;
505		if (lastc != '\0') {
506			if (lastc == '\n') {
507				nnl++;
508			} else {
509				CHECKSTRSPACE(nnl + 2, dest);
510				while (nnl > 0) {
511					nnl--;
512					USTPUTC('\n', dest);
513				}
514				if (quotes && syntax[(int)lastc] == CCTL)
515					USTPUTC(CTLESC, dest);
516				USTPUTC(lastc, dest);
517			}
518		}
519	}
520
521	if (in.fd >= 0)
522		close(in.fd);
523	if (in.buf)
524		ckfree(in.buf);
525	if (in.jp)
526		exitstatus = waitforjob(in.jp, (int *)NULL);
527	if (quoted == 0)
528		recordregion(startloc, dest - stackblock(), 0);
529	TRACE(("expbackq: size=%td: \"%.*s\"\n",
530		((dest - stackblock()) - startloc),
531		(int)((dest - stackblock()) - startloc),
532		stackblock() + startloc));
533	expdest = dest;
534	INTON;
535}
536
537
538
539static int
540subevalvar(char *p, char *str, int strloc, int subtype, int startloc,
541  int varflags, int quotes)
542{
543	char *startp;
544	char *loc = NULL;
545	char *q;
546	int c = 0;
547	struct nodelist *saveargbackq = argbackq;
548	int amount;
549
550	argstr(p, (subtype == VSTRIMLEFT || subtype == VSTRIMLEFTMAX ||
551	    subtype == VSTRIMRIGHT || subtype == VSTRIMRIGHTMAX ?
552	    EXP_CASE : 0) | EXP_TILDE);
553	STACKSTRNUL(expdest);
554	argbackq = saveargbackq;
555	startp = stackblock() + startloc;
556	if (str == NULL)
557	    str = stackblock() + strloc;
558
559	switch (subtype) {
560	case VSASSIGN:
561		setvar(str, startp, 0);
562		amount = startp - expdest;
563		STADJUST(amount, expdest);
564		varflags &= ~VSNUL;
565		return 1;
566
567	case VSQUESTION:
568		if (*p != CTLENDVAR) {
569			outfmt(out2, "%s\n", startp);
570			error((char *)NULL);
571		}
572		error("%.*s: parameter %snot set", (int)(p - str - 1),
573		      str, (varflags & VSNUL) ? "null or "
574					      : nullstr);
575		return 0;
576
577	case VSTRIMLEFT:
578		for (loc = startp; loc < str; loc++) {
579			c = *loc;
580			*loc = '\0';
581			if (patmatch(str, startp, quotes)) {
582				*loc = c;
583				goto recordleft;
584			}
585			*loc = c;
586			if (quotes && *loc == CTLESC)
587				loc++;
588		}
589		return 0;
590
591	case VSTRIMLEFTMAX:
592		for (loc = str - 1; loc >= startp;) {
593			c = *loc;
594			*loc = '\0';
595			if (patmatch(str, startp, quotes)) {
596				*loc = c;
597				goto recordleft;
598			}
599			*loc = c;
600			loc--;
601			if (quotes && loc > startp && *(loc - 1) == CTLESC) {
602				for (q = startp; q < loc; q++)
603					if (*q == CTLESC)
604						q++;
605				if (q > loc)
606					loc--;
607			}
608		}
609		return 0;
610
611	case VSTRIMRIGHT:
612		for (loc = str - 1; loc >= startp;) {
613			if (patmatch(str, loc, quotes)) {
614				amount = loc - expdest;
615				STADJUST(amount, expdest);
616				return 1;
617			}
618			loc--;
619			if (quotes && loc > startp && *(loc - 1) == CTLESC) {
620				for (q = startp; q < loc; q++)
621					if (*q == CTLESC)
622						q++;
623				if (q > loc)
624					loc--;
625			}
626		}
627		return 0;
628
629	case VSTRIMRIGHTMAX:
630		for (loc = startp; loc < str - 1; loc++) {
631			if (patmatch(str, loc, quotes)) {
632				amount = loc - expdest;
633				STADJUST(amount, expdest);
634				return 1;
635			}
636			if (quotes && *loc == CTLESC)
637				loc++;
638		}
639		return 0;
640
641
642	default:
643		abort();
644	}
645
646recordleft:
647	amount = ((str - 1) - (loc - startp)) - expdest;
648	STADJUST(amount, expdest);
649	while (loc != str - 1)
650		*startp++ = *loc++;
651	return 1;
652}
653
654
655/*
656 * Expand a variable, and return a pointer to the next character in the
657 * input string.
658 */
659
660static char *
661evalvar(char *p, int flag)
662{
663	int subtype;
664	int varflags;
665	char *var;
666	char *val;
667	int patloc;
668	int c;
669	int set;
670	int special;
671	int startloc;
672	int varlen;
673	int varlenb;
674	int easy;
675	int quotes = flag & (EXP_FULL | EXP_CASE | EXP_REDIR);
676
677	varflags = (unsigned char)*p++;
678	subtype = varflags & VSTYPE;
679	var = p;
680	special = 0;
681	if (! is_name(*p))
682		special = 1;
683	p = strchr(p, '=') + 1;
684again: /* jump here after setting a variable with ${var=text} */
685	if (varflags & VSLINENO) {
686		set = 1;
687		special = 0;
688		val = var;
689		p[-1] = '\0';	/* temporarily overwrite '=' to have \0
690				   terminated string */
691	} else if (special) {
692		set = varisset(var, varflags & VSNUL);
693		val = NULL;
694	} else {
695		val = bltinlookup(var, 1);
696		if (val == NULL || ((varflags & VSNUL) && val[0] == '\0')) {
697			val = NULL;
698			set = 0;
699		} else
700			set = 1;
701	}
702	varlen = 0;
703	startloc = expdest - stackblock();
704	if (!set && uflag && *var != '@' && *var != '*') {
705		switch (subtype) {
706		case VSNORMAL:
707		case VSTRIMLEFT:
708		case VSTRIMLEFTMAX:
709		case VSTRIMRIGHT:
710		case VSTRIMRIGHTMAX:
711		case VSLENGTH:
712			error("%.*s: parameter not set", (int)(p - var - 1),
713			    var);
714		}
715	}
716	if (set && subtype != VSPLUS) {
717		/* insert the value of the variable */
718		if (special) {
719			varvalue(var, varflags & VSQUOTE, subtype, flag);
720			if (subtype == VSLENGTH) {
721				varlenb = expdest - stackblock() - startloc;
722				varlen = varlenb;
723				if (localeisutf8) {
724					val = stackblock() + startloc;
725					for (;val != expdest; val++)
726						if ((*val & 0xC0) == 0x80)
727							varlen--;
728				}
729				STADJUST(-varlenb, expdest);
730			}
731		} else {
732			char const *syntax = (varflags & VSQUOTE) ? DQSYNTAX
733								  : BASESYNTAX;
734
735			if (subtype == VSLENGTH) {
736				for (;*val; val++)
737					if (!localeisutf8 ||
738					    (*val & 0xC0) != 0x80)
739						varlen++;
740			}
741			else {
742				if (quotes)
743					STPUTS_QUOTES(val, syntax, expdest);
744				else
745					STPUTS(val, expdest);
746
747			}
748		}
749	}
750
751	if (subtype == VSPLUS)
752		set = ! set;
753
754	easy = ((varflags & VSQUOTE) == 0 ||
755		(*var == '@' && shellparam.nparam != 1));
756
757
758	switch (subtype) {
759	case VSLENGTH:
760		expdest = cvtnum(varlen, expdest);
761		goto record;
762
763	case VSNORMAL:
764		if (!easy)
765			break;
766record:
767		recordregion(startloc, expdest - stackblock(),
768		    varflags & VSQUOTE || (ifsset() && ifsval()[0] == '\0' &&
769		    (*var == '@' || *var == '*')));
770		break;
771
772	case VSPLUS:
773	case VSMINUS:
774		if (!set) {
775			argstr(p, flag | (flag & EXP_FULL ? EXP_SPLIT_LIT : 0) |
776			    (varflags & VSQUOTE ? EXP_LIT_QUOTED : 0));
777			break;
778		}
779		if (easy)
780			goto record;
781		break;
782
783	case VSTRIMLEFT:
784	case VSTRIMLEFTMAX:
785	case VSTRIMRIGHT:
786	case VSTRIMRIGHTMAX:
787		if (!set)
788			break;
789		/*
790		 * Terminate the string and start recording the pattern
791		 * right after it
792		 */
793		STPUTC('\0', expdest);
794		patloc = expdest - stackblock();
795		if (subevalvar(p, NULL, patloc, subtype,
796		    startloc, varflags, quotes) == 0) {
797			int amount = (expdest - stackblock() - patloc) + 1;
798			STADJUST(-amount, expdest);
799		}
800		/* Remove any recorded regions beyond start of variable */
801		removerecordregions(startloc);
802		goto record;
803
804	case VSASSIGN:
805	case VSQUESTION:
806		if (!set) {
807			if (subevalvar(p, var, 0, subtype, startloc, varflags,
808			    quotes)) {
809				varflags &= ~VSNUL;
810				/*
811				 * Remove any recorded regions beyond
812				 * start of variable
813				 */
814				removerecordregions(startloc);
815				goto again;
816			}
817			break;
818		}
819		if (easy)
820			goto record;
821		break;
822
823	case VSERROR:
824		c = p - var - 1;
825		error("${%.*s%s}: Bad substitution", c, var,
826		    (c > 0 && *p != CTLENDVAR) ? "..." : "");
827
828	default:
829		abort();
830	}
831	p[-1] = '=';	/* recover overwritten '=' */
832
833	if (subtype != VSNORMAL) {	/* skip to end of alternative */
834		int nesting = 1;
835		for (;;) {
836			if ((c = *p++) == CTLESC)
837				p++;
838			else if (c == CTLBACKQ || c == (CTLBACKQ|CTLQUOTE)) {
839				if (set)
840					argbackq = argbackq->next;
841			} else if (c == CTLVAR) {
842				if ((*p++ & VSTYPE) != VSNORMAL)
843					nesting++;
844			} else if (c == CTLENDVAR) {
845				if (--nesting == 0)
846					break;
847			}
848		}
849	}
850	return p;
851}
852
853
854
855/*
856 * Test whether a specialized variable is set.
857 */
858
859static int
860varisset(char *name, int nulok)
861{
862
863	if (*name == '!')
864		return backgndpidset();
865	else if (*name == '@' || *name == '*') {
866		if (*shellparam.p == NULL)
867			return 0;
868
869		if (nulok) {
870			char **av;
871
872			for (av = shellparam.p; *av; av++)
873				if (**av != '\0')
874					return 1;
875			return 0;
876		}
877	} else if (is_digit(*name)) {
878		char *ap;
879		int num = atoi(name);
880
881		if (num > shellparam.nparam)
882			return 0;
883
884		if (num == 0)
885			ap = arg0;
886		else
887			ap = shellparam.p[num - 1];
888
889		if (nulok && (ap == NULL || *ap == '\0'))
890			return 0;
891	}
892	return 1;
893}
894
895static void
896strtodest(const char *p, int flag, int subtype, int quoted)
897{
898	if (flag & (EXP_FULL | EXP_CASE) && subtype != VSLENGTH)
899		STPUTS_QUOTES(p, quoted ? DQSYNTAX : BASESYNTAX, expdest);
900	else
901		STPUTS(p, expdest);
902}
903
904/*
905 * Add the value of a specialized variable to the stack string.
906 */
907
908static void
909varvalue(char *name, int quoted, int subtype, int flag)
910{
911	int num;
912	char *p;
913	int i;
914	char sep;
915	char **ap;
916
917	switch (*name) {
918	case '$':
919		num = rootpid;
920		goto numvar;
921	case '?':
922		num = oexitstatus;
923		goto numvar;
924	case '#':
925		num = shellparam.nparam;
926		goto numvar;
927	case '!':
928		num = backgndpidval();
929numvar:
930		expdest = cvtnum(num, expdest);
931		break;
932	case '-':
933		for (i = 0 ; i < NOPTS ; i++) {
934			if (optlist[i].val)
935				STPUTC(optlist[i].letter, expdest);
936		}
937		break;
938	case '@':
939		if (flag & EXP_FULL && quoted) {
940			for (ap = shellparam.p ; (p = *ap++) != NULL ; ) {
941				strtodest(p, flag, subtype, quoted);
942				if (*ap)
943					STPUTC('\0', expdest);
944			}
945			break;
946		}
947		/* FALLTHROUGH */
948	case '*':
949		if (ifsset())
950			sep = ifsval()[0];
951		else
952			sep = ' ';
953		for (ap = shellparam.p ; (p = *ap++) != NULL ; ) {
954			strtodest(p, flag, subtype, quoted);
955			if (!*ap)
956				break;
957			if (sep || (flag & EXP_FULL && !quoted && **ap != '\0'))
958				STPUTC(sep, expdest);
959		}
960		break;
961	case '0':
962		p = arg0;
963		strtodest(p, flag, subtype, quoted);
964		break;
965	default:
966		if (is_digit(*name)) {
967			num = atoi(name);
968			if (num > 0 && num <= shellparam.nparam) {
969				p = shellparam.p[num - 1];
970				strtodest(p, flag, subtype, quoted);
971			}
972		}
973		break;
974	}
975}
976
977
978
979/*
980 * Record the fact that we have to scan this region of the
981 * string for IFS characters.
982 */
983
984static void
985recordregion(int start, int end, int inquotes)
986{
987	struct ifsregion *ifsp;
988
989	if (ifslastp == NULL) {
990		ifsp = &ifsfirst;
991	} else {
992		if (ifslastp->endoff == start
993		    && ifslastp->inquotes == inquotes) {
994			/* extend previous area */
995			ifslastp->endoff = end;
996			return;
997		}
998		ifsp = (struct ifsregion *)ckmalloc(sizeof (struct ifsregion));
999		ifslastp->next = ifsp;
1000	}
1001	ifslastp = ifsp;
1002	ifslastp->next = NULL;
1003	ifslastp->begoff = start;
1004	ifslastp->endoff = end;
1005	ifslastp->inquotes = inquotes;
1006}
1007
1008
1009
1010/*
1011 * Break the argument string into pieces based upon IFS and add the
1012 * strings to the argument list.  The regions of the string to be
1013 * searched for IFS characters have been stored by recordregion.
1014 * CTLESC characters are preserved but have little effect in this pass
1015 * other than escaping CTL* characters.  In particular, they do not escape
1016 * IFS characters: that should be done with the ifsregion mechanism.
1017 * CTLQUOTEMARK characters are used to preserve empty quoted strings.
1018 * This pass treats them as a regular character, making the string non-empty.
1019 * Later, they are removed along with the other CTL* characters.
1020 */
1021static void
1022ifsbreakup(char *string, struct arglist *arglist)
1023{
1024	struct ifsregion *ifsp;
1025	struct strlist *sp;
1026	char *start;
1027	char *p;
1028	char *q;
1029	const char *ifs;
1030	const char *ifsspc;
1031	int had_param_ch = 0;
1032
1033	start = string;
1034
1035	if (ifslastp == NULL) {
1036		/* Return entire argument, IFS doesn't apply to any of it */
1037		sp = (struct strlist *)stalloc(sizeof *sp);
1038		sp->text = start;
1039		*arglist->lastp = sp;
1040		arglist->lastp = &sp->next;
1041		return;
1042	}
1043
1044	ifs = ifsset() ? ifsval() : " \t\n";
1045
1046	for (ifsp = &ifsfirst; ifsp != NULL; ifsp = ifsp->next) {
1047		p = string + ifsp->begoff;
1048		while (p < string + ifsp->endoff) {
1049			q = p;
1050			if (*p == CTLESC)
1051				p++;
1052			if (ifsp->inquotes) {
1053				/* Only NULs (should be from "$@") end args */
1054				had_param_ch = 1;
1055				if (*p != 0) {
1056					p++;
1057					continue;
1058				}
1059				ifsspc = NULL;
1060			} else {
1061				if (!strchr(ifs, *p)) {
1062					had_param_ch = 1;
1063					p++;
1064					continue;
1065				}
1066				ifsspc = strchr(" \t\n", *p);
1067
1068				/* Ignore IFS whitespace at start */
1069				if (q == start && ifsspc != NULL) {
1070					p++;
1071					start = p;
1072					continue;
1073				}
1074				had_param_ch = 0;
1075			}
1076
1077			/* Save this argument... */
1078			*q = '\0';
1079			sp = (struct strlist *)stalloc(sizeof *sp);
1080			sp->text = start;
1081			*arglist->lastp = sp;
1082			arglist->lastp = &sp->next;
1083			p++;
1084
1085			if (ifsspc != NULL) {
1086				/* Ignore further trailing IFS whitespace */
1087				for (; p < string + ifsp->endoff; p++) {
1088					q = p;
1089					if (*p == CTLESC)
1090						p++;
1091					if (strchr(ifs, *p) == NULL) {
1092						p = q;
1093						break;
1094					}
1095					if (strchr(" \t\n", *p) == NULL) {
1096						p++;
1097						break;
1098					}
1099				}
1100			}
1101			start = p;
1102		}
1103	}
1104
1105	/*
1106	 * Save anything left as an argument.
1107	 * Traditionally we have treated 'IFS=':'; set -- x$IFS' as
1108	 * generating 2 arguments, the second of which is empty.
1109	 * Some recent clarification of the Posix spec say that it
1110	 * should only generate one....
1111	 */
1112	if (had_param_ch || *start != 0) {
1113		sp = (struct strlist *)stalloc(sizeof *sp);
1114		sp->text = start;
1115		*arglist->lastp = sp;
1116		arglist->lastp = &sp->next;
1117	}
1118}
1119
1120
1121static char expdir[PATH_MAX];
1122#define expdir_end (expdir + sizeof(expdir))
1123
1124/*
1125 * Perform pathname generation and remove control characters.
1126 * At this point, the only control characters should be CTLESC and CTLQUOTEMARK.
1127 * The results are stored in the list exparg.
1128 */
1129static void
1130expandmeta(struct strlist *str, int flag __unused)
1131{
1132	char *p;
1133	struct strlist **savelastp;
1134	struct strlist *sp;
1135	char c;
1136	/* TODO - EXP_REDIR */
1137
1138	while (str) {
1139		if (fflag)
1140			goto nometa;
1141		p = str->text;
1142		for (;;) {			/* fast check for meta chars */
1143			if ((c = *p++) == '\0')
1144				goto nometa;
1145			if (c == '*' || c == '?' || c == '[')
1146				break;
1147		}
1148		savelastp = exparg.lastp;
1149		INTOFF;
1150		expmeta(expdir, str->text);
1151		INTON;
1152		if (exparg.lastp == savelastp) {
1153			/*
1154			 * no matches
1155			 */
1156nometa:
1157			*exparg.lastp = str;
1158			rmescapes(str->text);
1159			exparg.lastp = &str->next;
1160		} else {
1161			*exparg.lastp = NULL;
1162			*savelastp = sp = expsort(*savelastp);
1163			while (sp->next != NULL)
1164				sp = sp->next;
1165			exparg.lastp = &sp->next;
1166		}
1167		str = str->next;
1168	}
1169}
1170
1171
1172/*
1173 * Do metacharacter (i.e. *, ?, [...]) expansion.
1174 */
1175
1176static void
1177expmeta(char *enddir, char *name)
1178{
1179	char *p;
1180	char *q;
1181	char *start;
1182	char *endname;
1183	int metaflag;
1184	struct stat statb;
1185	DIR *dirp;
1186	struct dirent *dp;
1187	int atend;
1188	int matchdot;
1189	int esc;
1190
1191	metaflag = 0;
1192	start = name;
1193	for (p = name; esc = 0, *p; p += esc + 1) {
1194		if (*p == '*' || *p == '?')
1195			metaflag = 1;
1196		else if (*p == '[') {
1197			q = p + 1;
1198			if (*q == '!' || *q == '^')
1199				q++;
1200			for (;;) {
1201				while (*q == CTLQUOTEMARK)
1202					q++;
1203				if (*q == CTLESC)
1204					q++;
1205				if (*q == '/' || *q == '\0')
1206					break;
1207				if (*++q == ']') {
1208					metaflag = 1;
1209					break;
1210				}
1211			}
1212		} else if (*p == '\0')
1213			break;
1214		else if (*p == CTLQUOTEMARK)
1215			continue;
1216		else {
1217			if (*p == CTLESC)
1218				esc++;
1219			if (p[esc] == '/') {
1220				if (metaflag)
1221					break;
1222				start = p + esc + 1;
1223			}
1224		}
1225	}
1226	if (metaflag == 0) {	/* we've reached the end of the file name */
1227		if (enddir != expdir)
1228			metaflag++;
1229		for (p = name ; ; p++) {
1230			if (*p == CTLQUOTEMARK)
1231				continue;
1232			if (*p == CTLESC)
1233				p++;
1234			*enddir++ = *p;
1235			if (*p == '\0')
1236				break;
1237			if (enddir == expdir_end)
1238				return;
1239		}
1240		if (metaflag == 0 || lstat(expdir, &statb) >= 0)
1241			addfname(expdir);
1242		return;
1243	}
1244	endname = p;
1245	if (start != name) {
1246		p = name;
1247		while (p < start) {
1248			while (*p == CTLQUOTEMARK)
1249				p++;
1250			if (*p == CTLESC)
1251				p++;
1252			*enddir++ = *p++;
1253			if (enddir == expdir_end)
1254				return;
1255		}
1256	}
1257	if (enddir == expdir) {
1258		p = ".";
1259	} else if (enddir == expdir + 1 && *expdir == '/') {
1260		p = "/";
1261	} else {
1262		p = expdir;
1263		enddir[-1] = '\0';
1264	}
1265	if ((dirp = opendir(p)) == NULL)
1266		return;
1267	if (enddir != expdir)
1268		enddir[-1] = '/';
1269	if (*endname == 0) {
1270		atend = 1;
1271	} else {
1272		atend = 0;
1273		*endname = '\0';
1274		endname += esc + 1;
1275	}
1276	matchdot = 0;
1277	p = start;
1278	while (*p == CTLQUOTEMARK)
1279		p++;
1280	if (*p == CTLESC)
1281		p++;
1282	if (*p == '.')
1283		matchdot++;
1284	while (! int_pending() && (dp = readdir(dirp)) != NULL) {
1285		if (dp->d_name[0] == '.' && ! matchdot)
1286			continue;
1287		if (patmatch(start, dp->d_name, 0)) {
1288			if (enddir + dp->d_namlen + 1 > expdir_end)
1289				continue;
1290			memcpy(enddir, dp->d_name, dp->d_namlen + 1);
1291			if (atend)
1292				addfname(expdir);
1293			else {
1294				if (enddir + dp->d_namlen + 2 > expdir_end)
1295					continue;
1296				enddir[dp->d_namlen] = '/';
1297				enddir[dp->d_namlen + 1] = '\0';
1298				expmeta(enddir + dp->d_namlen + 1, endname);
1299			}
1300		}
1301	}
1302	closedir(dirp);
1303	if (! atend)
1304		endname[-esc - 1] = esc ? CTLESC : '/';
1305}
1306
1307
1308/*
1309 * Add a file name to the list.
1310 */
1311
1312static void
1313addfname(char *name)
1314{
1315	char *p;
1316	struct strlist *sp;
1317
1318	p = stalloc(strlen(name) + 1);
1319	scopy(name, p);
1320	sp = (struct strlist *)stalloc(sizeof *sp);
1321	sp->text = p;
1322	*exparg.lastp = sp;
1323	exparg.lastp = &sp->next;
1324}
1325
1326
1327/*
1328 * Sort the results of file name expansion.  It calculates the number of
1329 * strings to sort and then calls msort (short for merge sort) to do the
1330 * work.
1331 */
1332
1333static struct strlist *
1334expsort(struct strlist *str)
1335{
1336	int len;
1337	struct strlist *sp;
1338
1339	len = 0;
1340	for (sp = str ; sp ; sp = sp->next)
1341		len++;
1342	return msort(str, len);
1343}
1344
1345
1346static struct strlist *
1347msort(struct strlist *list, int len)
1348{
1349	struct strlist *p, *q = NULL;
1350	struct strlist **lpp;
1351	int half;
1352	int n;
1353
1354	if (len <= 1)
1355		return list;
1356	half = len >> 1;
1357	p = list;
1358	for (n = half ; --n >= 0 ; ) {
1359		q = p;
1360		p = p->next;
1361	}
1362	q->next = NULL;			/* terminate first half of list */
1363	q = msort(list, half);		/* sort first half of list */
1364	p = msort(p, len - half);		/* sort second half */
1365	lpp = &list;
1366	for (;;) {
1367		if (strcmp(p->text, q->text) < 0) {
1368			*lpp = p;
1369			lpp = &p->next;
1370			if ((p = *lpp) == NULL) {
1371				*lpp = q;
1372				break;
1373			}
1374		} else {
1375			*lpp = q;
1376			lpp = &q->next;
1377			if ((q = *lpp) == NULL) {
1378				*lpp = p;
1379				break;
1380			}
1381		}
1382	}
1383	return list;
1384}
1385
1386
1387
1388static wchar_t
1389get_wc(const char **p)
1390{
1391	wchar_t c;
1392	int chrlen;
1393
1394	chrlen = mbtowc(&c, *p, 4);
1395	if (chrlen == 0)
1396		return 0;
1397	else if (chrlen == -1)
1398		c = 0;
1399	else
1400		*p += chrlen;
1401	return c;
1402}
1403
1404
1405/*
1406 * See if a character matches a character class, starting at the first colon
1407 * of "[:class:]".
1408 * If a valid character class is recognized, a pointer to the next character
1409 * after the final closing bracket is stored into *end, otherwise a null
1410 * pointer is stored into *end.
1411 */
1412static int
1413match_charclass(const char *p, wchar_t chr, const char **end)
1414{
1415	char name[20];
1416	const char *nameend;
1417	wctype_t cclass;
1418
1419	*end = NULL;
1420	p++;
1421	nameend = strstr(p, ":]");
1422	if (nameend == NULL || nameend - p >= sizeof(name) || nameend == p)
1423		return 0;
1424	memcpy(name, p, nameend - p);
1425	name[nameend - p] = '\0';
1426	*end = nameend + 2;
1427	cclass = wctype(name);
1428	/* An unknown class matches nothing but is valid nevertheless. */
1429	if (cclass == 0)
1430		return 0;
1431	return iswctype(chr, cclass);
1432}
1433
1434
1435/*
1436 * Returns true if the pattern matches the string.
1437 */
1438
1439static int
1440patmatch(const char *pattern, const char *string, int squoted)
1441{
1442	const char *p, *q, *end;
1443	char c;
1444	wchar_t wc, wc2;
1445
1446	p = pattern;
1447	q = string;
1448	for (;;) {
1449		switch (c = *p++) {
1450		case '\0':
1451			goto breakloop;
1452		case CTLESC:
1453			if (squoted && *q == CTLESC)
1454				q++;
1455			if (*q++ != *p++)
1456				return 0;
1457			break;
1458		case CTLQUOTEMARK:
1459			continue;
1460		case '?':
1461			if (squoted && *q == CTLESC)
1462				q++;
1463			if (localeisutf8)
1464				wc = get_wc(&q);
1465			else
1466				wc = (unsigned char)*q++;
1467			if (wc == '\0')
1468				return 0;
1469			break;
1470		case '*':
1471			c = *p;
1472			while (c == CTLQUOTEMARK || c == '*')
1473				c = *++p;
1474			if (c != CTLESC &&  c != CTLQUOTEMARK &&
1475			    c != '?' && c != '*' && c != '[') {
1476				while (*q != c) {
1477					if (squoted && *q == CTLESC &&
1478					    q[1] == c)
1479						break;
1480					if (*q == '\0')
1481						return 0;
1482					if (squoted && *q == CTLESC)
1483						q++;
1484					q++;
1485				}
1486			}
1487			do {
1488				if (patmatch(p, q, squoted))
1489					return 1;
1490				if (squoted && *q == CTLESC)
1491					q++;
1492			} while (*q++ != '\0');
1493			return 0;
1494		case '[': {
1495			const char *endp;
1496			int invert, found;
1497			wchar_t chr;
1498
1499			endp = p;
1500			if (*endp == '!' || *endp == '^')
1501				endp++;
1502			for (;;) {
1503				while (*endp == CTLQUOTEMARK)
1504					endp++;
1505				if (*endp == '\0')
1506					goto dft;		/* no matching ] */
1507				if (*endp == CTLESC)
1508					endp++;
1509				if (*++endp == ']')
1510					break;
1511			}
1512			invert = 0;
1513			if (*p == '!' || *p == '^') {
1514				invert++;
1515				p++;
1516			}
1517			found = 0;
1518			if (squoted && *q == CTLESC)
1519				q++;
1520			if (localeisutf8)
1521				chr = get_wc(&q);
1522			else
1523				chr = (unsigned char)*q++;
1524			if (chr == '\0')
1525				return 0;
1526			c = *p++;
1527			do {
1528				if (c == CTLQUOTEMARK)
1529					continue;
1530				if (c == '[' && *p == ':') {
1531					found |= match_charclass(p, chr, &end);
1532					if (end != NULL)
1533						p = end;
1534				}
1535				if (c == CTLESC)
1536					c = *p++;
1537				if (localeisutf8 && c & 0x80) {
1538					p--;
1539					wc = get_wc(&p);
1540					if (wc == 0) /* bad utf-8 */
1541						return 0;
1542				} else
1543					wc = (unsigned char)c;
1544				if (*p == '-' && p[1] != ']') {
1545					p++;
1546					while (*p == CTLQUOTEMARK)
1547						p++;
1548					if (*p == CTLESC)
1549						p++;
1550					if (localeisutf8) {
1551						wc2 = get_wc(&p);
1552						if (wc2 == 0) /* bad utf-8 */
1553							return 0;
1554					} else
1555						wc2 = (unsigned char)*p++;
1556					if (   collate_range_cmp(chr, wc) >= 0
1557					    && collate_range_cmp(chr, wc2) <= 0
1558					   )
1559						found = 1;
1560				} else {
1561					if (chr == wc)
1562						found = 1;
1563				}
1564			} while ((c = *p++) != ']');
1565			if (found == invert)
1566				return 0;
1567			break;
1568		}
1569dft:	        default:
1570			if (squoted && *q == CTLESC)
1571				q++;
1572			if (*q++ != c)
1573				return 0;
1574			break;
1575		}
1576	}
1577breakloop:
1578	if (*q != '\0')
1579		return 0;
1580	return 1;
1581}
1582
1583
1584
1585/*
1586 * Remove any CTLESC and CTLQUOTEMARK characters from a string.
1587 */
1588
1589void
1590rmescapes(char *str)
1591{
1592	char *p, *q;
1593
1594	p = str;
1595	while (*p != CTLESC && *p != CTLQUOTEMARK && *p != CTLQUOTEEND) {
1596		if (*p++ == '\0')
1597			return;
1598	}
1599	q = p;
1600	while (*p) {
1601		if (*p == CTLQUOTEMARK || *p == CTLQUOTEEND) {
1602			p++;
1603			continue;
1604		}
1605		if (*p == CTLESC)
1606			p++;
1607		*q++ = *p++;
1608	}
1609	*q = '\0';
1610}
1611
1612
1613
1614/*
1615 * See if a pattern matches in a case statement.
1616 */
1617
1618int
1619casematch(union node *pattern, const char *val)
1620{
1621	struct stackmark smark;
1622	int result;
1623	char *p;
1624
1625	setstackmark(&smark);
1626	argbackq = pattern->narg.backquote;
1627	STARTSTACKSTR(expdest);
1628	ifslastp = NULL;
1629	argstr(pattern->narg.text, EXP_TILDE | EXP_CASE);
1630	STPUTC('\0', expdest);
1631	p = grabstackstr(expdest);
1632	result = patmatch(p, val, 0);
1633	popstackmark(&smark);
1634	return result;
1635}
1636
1637/*
1638 * Our own itoa().
1639 */
1640
1641static char *
1642cvtnum(int num, char *buf)
1643{
1644	char temp[32];
1645	int neg = num < 0;
1646	char *p = temp + 31;
1647
1648	temp[31] = '\0';
1649
1650	do {
1651		*--p = num % 10 + '0';
1652	} while ((num /= 10) != 0);
1653
1654	if (neg)
1655		*--p = '-';
1656
1657	STPUTS(p, buf);
1658	return buf;
1659}
1660
1661/*
1662 * Do most of the work for wordexp(3).
1663 */
1664
1665int
1666wordexpcmd(int argc, char **argv)
1667{
1668	size_t len;
1669	int i;
1670
1671	out1fmt("%08x", argc - 1);
1672	for (i = 1, len = 0; i < argc; i++)
1673		len += strlen(argv[i]);
1674	out1fmt("%08x", (int)len);
1675	for (i = 1; i < argc; i++)
1676		outbin(argv[i], strlen(argv[i]) + 1, out1);
1677        return (0);
1678}
1679