expand.c revision 164003
11556Srgrimes/*-
21556Srgrimes * Copyright (c) 1991, 1993
31556Srgrimes *	The Regents of the University of California.  All rights reserved.
41556Srgrimes *
51556Srgrimes * This code is derived from software contributed to Berkeley by
61556Srgrimes * Kenneth Almquist.
71556Srgrimes *
81556Srgrimes * Redistribution and use in source and binary forms, with or without
91556Srgrimes * modification, are permitted provided that the following conditions
101556Srgrimes * are met:
111556Srgrimes * 1. Redistributions of source code must retain the above copyright
121556Srgrimes *    notice, this list of conditions and the following disclaimer.
131556Srgrimes * 2. Redistributions in binary form must reproduce the above copyright
141556Srgrimes *    notice, this list of conditions and the following disclaimer in the
151556Srgrimes *    documentation and/or other materials provided with the distribution.
161556Srgrimes * 4. Neither the name of the University nor the names of its contributors
171556Srgrimes *    may be used to endorse or promote products derived from this software
181556Srgrimes *    without specific prior written permission.
191556Srgrimes *
201556Srgrimes * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
211556Srgrimes * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
221556Srgrimes * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
231556Srgrimes * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
241556Srgrimes * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
251556Srgrimes * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
261556Srgrimes * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
271556Srgrimes * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
281556Srgrimes * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
291556Srgrimes * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
301556Srgrimes * SUCH DAMAGE.
311556Srgrimes */
321556Srgrimes
331556Srgrimes#ifndef lint
3436150Scharnier#if 0
3536150Scharnierstatic char sccsid[] = "@(#)expand.c	8.5 (Berkeley) 5/15/95";
3636150Scharnier#endif
371556Srgrimes#endif /* not lint */
3899110Sobrien#include <sys/cdefs.h>
3999110Sobrien__FBSDID("$FreeBSD: head/bin/sh/expand.c 164003 2006-11-05 18:36:05Z stefanf $");
401556Srgrimes
4117987Speter#include <sys/types.h>
4217987Speter#include <sys/time.h>
4317987Speter#include <sys/stat.h>
4417987Speter#include <errno.h>
4517987Speter#include <dirent.h>
4617987Speter#include <unistd.h>
4717987Speter#include <pwd.h>
4817987Speter#include <stdlib.h>
4919281Sache#include <limits.h>
5038887Stegge#include <stdio.h>
51108286Stjr#include <string.h>
5217987Speter
531556Srgrimes/*
541556Srgrimes * Routines to expand arguments to commands.  We have to deal with
551556Srgrimes * backquotes, shell variables, and file metacharacters.
561556Srgrimes */
571556Srgrimes
581556Srgrimes#include "shell.h"
591556Srgrimes#include "main.h"
601556Srgrimes#include "nodes.h"
611556Srgrimes#include "eval.h"
621556Srgrimes#include "expand.h"
631556Srgrimes#include "syntax.h"
641556Srgrimes#include "parser.h"
651556Srgrimes#include "jobs.h"
661556Srgrimes#include "options.h"
671556Srgrimes#include "var.h"
681556Srgrimes#include "input.h"
691556Srgrimes#include "output.h"
701556Srgrimes#include "memalloc.h"
711556Srgrimes#include "error.h"
721556Srgrimes#include "mystring.h"
7317987Speter#include "arith.h"
7417987Speter#include "show.h"
751556Srgrimes
761556Srgrimes/*
771556Srgrimes * Structure specifying which parts of the string should be searched
781556Srgrimes * for IFS characters.
791556Srgrimes */
801556Srgrimes
811556Srgrimesstruct ifsregion {
821556Srgrimes	struct ifsregion *next;	/* next region in list */
831556Srgrimes	int begoff;		/* offset of start of region */
841556Srgrimes	int endoff;		/* offset of end of region */
851556Srgrimes	int nulonly;		/* search for nul bytes only */
861556Srgrimes};
871556Srgrimes
881556Srgrimes
89117261SddsSTATIC char *expdest;			/* output of current string */
90117261SddsSTATIC struct nodelist *argbackq;	/* list of back quote expressions */
91117261SddsSTATIC struct ifsregion ifsfirst;	/* first struct in list of ifs regions */
92117261SddsSTATIC struct ifsregion *ifslastp;	/* last struct in list */
93117261SddsSTATIC struct arglist exparg;		/* holds expanded arg list */
941556Srgrimes
9590111SimpSTATIC void argstr(char *, int);
9690111SimpSTATIC char *exptilde(char *, int);
9790111SimpSTATIC void expbackq(union node *, int, int);
9890111SimpSTATIC int subevalvar(char *, char *, int, int, int, int);
9990111SimpSTATIC char *evalvar(char *, int);
10090111SimpSTATIC int varisset(char *, int);
10190111SimpSTATIC void varvalue(char *, int, int);
10290111SimpSTATIC void recordregion(int, int, int);
103155301SschweikhSTATIC void removerecordregions(int);
10490111SimpSTATIC void ifsbreakup(char *, struct arglist *);
10590111SimpSTATIC void expandmeta(struct strlist *, int);
10690111SimpSTATIC void expmeta(char *, char *);
10790111SimpSTATIC void addfname(char *);
10890111SimpSTATIC struct strlist *expsort(struct strlist *);
10990111SimpSTATIC struct strlist *msort(struct strlist *, int);
11090111SimpSTATIC int pmatch(char *, char *, int);
11190111SimpSTATIC char *cvtnum(int, char *);
11290111SimpSTATIC int collate_range_cmp(int, int);
1131556Srgrimes
11490111SimpSTATIC int
115118374Sachecollate_range_cmp(int c1, int c2)
11619281Sache{
11719281Sache	static char s1[2], s2[2];
11819281Sache
11919281Sache	s1[0] = c1;
12019281Sache	s2[0] = c2;
121118374Sache	return (strcoll(s1, s2));
12219281Sache}
12319281Sache
1241556Srgrimes/*
1251556Srgrimes * Expand shell variables and backquotes inside a here document.
12690111Simp *	union node *arg		the document
12790111Simp *	int fd;			where to write the expanded version
1281556Srgrimes */
1291556Srgrimes
1301556Srgrimesvoid
13190111Simpexpandhere(union node *arg, int fd)
13290111Simp{
1331556Srgrimes	herefd = fd;
1341556Srgrimes	expandarg(arg, (struct arglist *)NULL, 0);
13539137Stegge	xwrite(fd, stackblock(), expdest - stackblock());
1361556Srgrimes}
1371556Srgrimes
1381556Srgrimes
1391556Srgrimes/*
1401556Srgrimes * Perform variable substitution and command substitution on an argument,
1411556Srgrimes * placing the resulting list of arguments in arglist.  If EXP_FULL is true,
1421556Srgrimes * perform splitting and file name expansion.  When arglist is NULL, perform
1431556Srgrimes * here document expansion.
1441556Srgrimes */
1451556Srgrimes
1461556Srgrimesvoid
14790111Simpexpandarg(union node *arg, struct arglist *arglist, int flag)
14817987Speter{
1491556Srgrimes	struct strlist *sp;
1501556Srgrimes	char *p;
1511556Srgrimes
1521556Srgrimes	argbackq = arg->narg.backquote;
1531556Srgrimes	STARTSTACKSTR(expdest);
1541556Srgrimes	ifsfirst.next = NULL;
1551556Srgrimes	ifslastp = NULL;
1561556Srgrimes	argstr(arg->narg.text, flag);
1571556Srgrimes	if (arglist == NULL) {
1581556Srgrimes		return;			/* here document expanded */
1591556Srgrimes	}
1601556Srgrimes	STPUTC('\0', expdest);
1611556Srgrimes	p = grabstackstr(expdest);
1621556Srgrimes	exparg.lastp = &exparg.list;
1631556Srgrimes	/*
1641556Srgrimes	 * TODO - EXP_REDIR
1651556Srgrimes	 */
1661556Srgrimes	if (flag & EXP_FULL) {
1671556Srgrimes		ifsbreakup(p, &exparg);
1681556Srgrimes		*exparg.lastp = NULL;
1691556Srgrimes		exparg.lastp = &exparg.list;
1701556Srgrimes		expandmeta(exparg.list, flag);
1711556Srgrimes	} else {
1721556Srgrimes		if (flag & EXP_REDIR) /*XXX - for now, just remove escapes */
1731556Srgrimes			rmescapes(p);
1741556Srgrimes		sp = (struct strlist *)stalloc(sizeof (struct strlist));
1751556Srgrimes		sp->text = p;
1761556Srgrimes		*exparg.lastp = sp;
1771556Srgrimes		exparg.lastp = &sp->next;
1781556Srgrimes	}
1791556Srgrimes	while (ifsfirst.next != NULL) {
1801556Srgrimes		struct ifsregion *ifsp;
1811556Srgrimes		INTOFF;
1821556Srgrimes		ifsp = ifsfirst.next->next;
1831556Srgrimes		ckfree(ifsfirst.next);
1841556Srgrimes		ifsfirst.next = ifsp;
1851556Srgrimes		INTON;
1861556Srgrimes	}
1871556Srgrimes	*exparg.lastp = NULL;
1881556Srgrimes	if (exparg.list) {
1891556Srgrimes		*arglist->lastp = exparg.list;
1901556Srgrimes		arglist->lastp = exparg.lastp;
1911556Srgrimes	}
1921556Srgrimes}
1931556Srgrimes
1941556Srgrimes
1951556Srgrimes
1961556Srgrimes/*
1971556Srgrimes * Perform variable and command substitution.  If EXP_FULL is set, output CTLESC
1981556Srgrimes * characters to allow for further processing.  Otherwise treat
1991556Srgrimes * $@ like $* since no splitting will be performed.
2001556Srgrimes */
2011556Srgrimes
2021556SrgrimesSTATIC void
20390111Simpargstr(char *p, int flag)
20417987Speter{
20525233Ssteve	char c;
206104672Stjr	int quotes = flag & (EXP_FULL | EXP_CASE | EXP_REDIR);	/* do CTLESC */
2071556Srgrimes	int firsteq = 1;
2081556Srgrimes
2091556Srgrimes	if (*p == '~' && (flag & (EXP_TILDE | EXP_VARTILDE)))
2101556Srgrimes		p = exptilde(p, flag);
2111556Srgrimes	for (;;) {
2121556Srgrimes		switch (c = *p++) {
2131556Srgrimes		case '\0':
2141556Srgrimes		case CTLENDVAR: /* ??? */
2151556Srgrimes			goto breakloop;
21638887Stegge		case CTLQUOTEMARK:
21738887Stegge			/* "$@" syntax adherence hack */
21838887Stegge			if (p[0] == CTLVAR && p[2] == '@' && p[3] == '=')
21938887Stegge				break;
22039137Stegge			if ((flag & EXP_FULL) != 0)
22139137Stegge				STPUTC(c, expdest);
22238887Stegge			break;
2231556Srgrimes		case CTLESC:
2241556Srgrimes			if (quotes)
2251556Srgrimes				STPUTC(c, expdest);
2261556Srgrimes			c = *p++;
2271556Srgrimes			STPUTC(c, expdest);
2281556Srgrimes			break;
2291556Srgrimes		case CTLVAR:
2301556Srgrimes			p = evalvar(p, flag);
2311556Srgrimes			break;
2321556Srgrimes		case CTLBACKQ:
2331556Srgrimes		case CTLBACKQ|CTLQUOTE:
2341556Srgrimes			expbackq(argbackq->n, c & CTLQUOTE, flag);
2351556Srgrimes			argbackq = argbackq->next;
2361556Srgrimes			break;
2371556Srgrimes		case CTLENDARI:
2381556Srgrimes			expari(flag);
2391556Srgrimes			break;
2401556Srgrimes		case ':':
2411556Srgrimes		case '=':
2421556Srgrimes			/*
2431556Srgrimes			 * sort of a hack - expand tildes in variable
2441556Srgrimes			 * assignments (after the first '=' and after ':'s).
2451556Srgrimes			 */
2461556Srgrimes			STPUTC(c, expdest);
2471556Srgrimes			if (flag & EXP_VARTILDE && *p == '~') {
2481556Srgrimes				if (c == '=') {
2491556Srgrimes					if (firsteq)
2501556Srgrimes						firsteq = 0;
2511556Srgrimes					else
2521556Srgrimes						break;
2531556Srgrimes				}
2541556Srgrimes				p = exptilde(p, flag);
2551556Srgrimes			}
2561556Srgrimes			break;
2571556Srgrimes		default:
2581556Srgrimes			STPUTC(c, expdest);
2591556Srgrimes		}
2601556Srgrimes	}
2611556Srgrimesbreakloop:;
2621556Srgrimes}
2631556Srgrimes
2641556SrgrimesSTATIC char *
26590111Simpexptilde(char *p, int flag)
26617987Speter{
2671556Srgrimes	char c, *startp = p;
2681556Srgrimes	struct passwd *pw;
2691556Srgrimes	char *home;
270108935Stjr	int quotes = flag & (EXP_FULL | EXP_CASE | EXP_REDIR);
2711556Srgrimes
27217987Speter	while ((c = *p) != '\0') {
2731556Srgrimes		switch(c) {
2741556Srgrimes		case CTLESC:
2751556Srgrimes			return (startp);
27639137Stegge		case CTLQUOTEMARK:
27739137Stegge			return (startp);
2781556Srgrimes		case ':':
2791556Srgrimes			if (flag & EXP_VARTILDE)
2801556Srgrimes				goto done;
2811556Srgrimes			break;
2821556Srgrimes		case '/':
2831556Srgrimes			goto done;
2841556Srgrimes		}
2851556Srgrimes		p++;
2861556Srgrimes	}
2871556Srgrimesdone:
2881556Srgrimes	*p = '\0';
2891556Srgrimes	if (*(startp+1) == '\0') {
2901556Srgrimes		if ((home = lookupvar("HOME")) == NULL)
2911556Srgrimes			goto lose;
2921556Srgrimes	} else {
2931556Srgrimes		if ((pw = getpwnam(startp+1)) == NULL)
2941556Srgrimes			goto lose;
2951556Srgrimes		home = pw->pw_dir;
2961556Srgrimes	}
2971556Srgrimes	if (*home == '\0')
2981556Srgrimes		goto lose;
2991556Srgrimes	*p = c;
30017987Speter	while ((c = *home++) != '\0') {
30183675Stegge		if (quotes && SQSYNTAX[(int)c] == CCTL)
3021556Srgrimes			STPUTC(CTLESC, expdest);
3031556Srgrimes		STPUTC(c, expdest);
3041556Srgrimes	}
3051556Srgrimes	return (p);
3061556Srgrimeslose:
3071556Srgrimes	*p = c;
3081556Srgrimes	return (startp);
3091556Srgrimes}
3101556Srgrimes
3111556Srgrimes
312155301SschweikhSTATIC void
31390111Simpremoverecordregions(int endoff)
31438887Stegge{
31538887Stegge	if (ifslastp == NULL)
31638887Stegge		return;
31738887Stegge
31838887Stegge	if (ifsfirst.endoff > endoff) {
31938887Stegge		while (ifsfirst.next != NULL) {
32038887Stegge			struct ifsregion *ifsp;
32138887Stegge			INTOFF;
32238887Stegge			ifsp = ifsfirst.next->next;
32338887Stegge			ckfree(ifsfirst.next);
32438887Stegge			ifsfirst.next = ifsp;
32538887Stegge			INTON;
32638887Stegge		}
32738887Stegge		if (ifsfirst.begoff > endoff)
32838887Stegge			ifslastp = NULL;
32938887Stegge		else {
33038887Stegge			ifslastp = &ifsfirst;
33138887Stegge			ifsfirst.endoff = endoff;
33238887Stegge		}
33338887Stegge		return;
33438887Stegge	}
335155301Sschweikh
33638887Stegge	ifslastp = &ifsfirst;
33738887Stegge	while (ifslastp->next && ifslastp->next->begoff < endoff)
33838887Stegge		ifslastp=ifslastp->next;
33938887Stegge	while (ifslastp->next != NULL) {
34038887Stegge		struct ifsregion *ifsp;
34138887Stegge		INTOFF;
34238887Stegge		ifsp = ifslastp->next->next;
34338887Stegge		ckfree(ifslastp->next);
34438887Stegge		ifslastp->next = ifsp;
34538887Stegge		INTON;
34638887Stegge	}
34738887Stegge	if (ifslastp->endoff > endoff)
34838887Stegge		ifslastp->endoff = endoff;
34938887Stegge}
35038887Stegge
3511556Srgrimes/*
3521556Srgrimes * Expand arithmetic expression.  Backup to start of expression,
3531556Srgrimes * evaluate, place result in (backed up) result, adjust string position.
3541556Srgrimes */
3551556Srgrimesvoid
35690111Simpexpari(int flag)
35717987Speter{
3581556Srgrimes	char *p, *start;
3591556Srgrimes	int result;
36038887Stegge	int begoff;
361108935Stjr	int quotes = flag & (EXP_FULL | EXP_CASE | EXP_REDIR);
36238887Stegge	int quoted;
3631556Srgrimes
36425233Ssteve
3651556Srgrimes	/*
36646684Skris	 * This routine is slightly over-complicated for
3671556Srgrimes	 * efficiency.  First we make sure there is
3681556Srgrimes	 * enough space for the result, which may be bigger
36946684Skris	 * than the expression if we add exponentiation.  Next we
3701556Srgrimes	 * scan backwards looking for the start of arithmetic.  If the
3711556Srgrimes	 * next previous character is a CTLESC character, then we
3721556Srgrimes	 * have to rescan starting from the beginning since CTLESC
3738855Srgrimes	 * characters have to be processed left to right.
3741556Srgrimes	 */
37522777Ssteve#if INT_MAX / 1000000000 >= 10 || INT_MIN / 1000000000 <= -10
37622777Ssteve#error "integers with more than 10 digits are not supported"
37722777Ssteve#endif
37822777Ssteve	CHECKSTRSPACE(12 - 2, expdest);
3798855Srgrimes	USTPUTC('\0', expdest);
3801556Srgrimes	start = stackblock();
38183676Stegge	p = expdest - 2;
38283676Stegge	while (p >= start && *p != CTLARI)
3831556Srgrimes		--p;
38483676Stegge	if (p < start || *p != CTLARI)
3851556Srgrimes		error("missing CTLARI (shouldn't happen)");
38683676Stegge	if (p > start && *(p - 1) == CTLESC)
3871556Srgrimes		for (p = start; *p != CTLARI; p++)
3881556Srgrimes			if (*p == CTLESC)
3891556Srgrimes				p++;
39038887Stegge
39138887Stegge	if (p[1] == '"')
39238887Stegge		quoted=1;
39338887Stegge	else
39438887Stegge		quoted=0;
39538887Stegge	begoff = p - start;
39638887Stegge	removerecordregions(begoff);
3971556Srgrimes	if (quotes)
39838887Stegge		rmescapes(p+2);
39938887Stegge	result = arith(p+2);
40022777Ssteve	fmtstr(p, 12, "%d", result);
4011556Srgrimes	while (*p++)
4021556Srgrimes		;
40338887Stegge	if (quoted == 0)
40438887Stegge		recordregion(begoff, p - 1 - start, 0);
4051556Srgrimes	result = expdest - p + 1;
4061556Srgrimes	STADJUST(-result, expdest);
4071556Srgrimes}
4081556Srgrimes
4091556Srgrimes
4101556Srgrimes/*
4111556Srgrimes * Expand stuff in backwards quotes.
4121556Srgrimes */
4131556Srgrimes
4141556SrgrimesSTATIC void
41590111Simpexpbackq(union node *cmd, int quoted, int flag)
41617987Speter{
4171556Srgrimes	struct backcmd in;
4181556Srgrimes	int i;
4191556Srgrimes	char buf[128];
4201556Srgrimes	char *p;
4211556Srgrimes	char *dest = expdest;
4221556Srgrimes	struct ifsregion saveifs, *savelastp;
4231556Srgrimes	struct nodelist *saveargbackq;
4241556Srgrimes	char lastc;
4251556Srgrimes	int startloc = dest - stackblock();
4261556Srgrimes	char const *syntax = quoted? DQSYNTAX : BASESYNTAX;
4271556Srgrimes	int saveherefd;
428108935Stjr	int quotes = flag & (EXP_FULL | EXP_CASE | EXP_REDIR);
429115424Sfenner	int nnl;
4301556Srgrimes
4311556Srgrimes	INTOFF;
4321556Srgrimes	saveifs = ifsfirst;
4331556Srgrimes	savelastp = ifslastp;
4341556Srgrimes	saveargbackq = argbackq;
4358855Srgrimes	saveherefd = herefd;
4361556Srgrimes	herefd = -1;
4371556Srgrimes	p = grabstackstr(dest);
4381556Srgrimes	evalbackcmd(cmd, &in);
4391556Srgrimes	ungrabstackstr(p, dest);
4401556Srgrimes	ifsfirst = saveifs;
4411556Srgrimes	ifslastp = savelastp;
4421556Srgrimes	argbackq = saveargbackq;
4431556Srgrimes	herefd = saveherefd;
4441556Srgrimes
4451556Srgrimes	p = in.buf;
4461556Srgrimes	lastc = '\0';
447115424Sfenner	nnl = 0;
448115424Sfenner	/* Don't copy trailing newlines */
4491556Srgrimes	for (;;) {
4501556Srgrimes		if (--in.nleft < 0) {
4511556Srgrimes			if (in.fd < 0)
4521556Srgrimes				break;
4531556Srgrimes			while ((i = read(in.fd, buf, sizeof buf)) < 0 && errno == EINTR);
4541556Srgrimes			TRACE(("expbackq: read returns %d\n", i));
4551556Srgrimes			if (i <= 0)
4561556Srgrimes				break;
4571556Srgrimes			p = buf;
4581556Srgrimes			in.nleft = i - 1;
4591556Srgrimes		}
4601556Srgrimes		lastc = *p++;
4611556Srgrimes		if (lastc != '\0') {
46283675Stegge			if (quotes && syntax[(int)lastc] == CCTL)
4631556Srgrimes				STPUTC(CTLESC, dest);
464115424Sfenner			if (lastc == '\n') {
465115424Sfenner				nnl++;
466115424Sfenner			} else {
467115424Sfenner				while (nnl > 0) {
468115424Sfenner					nnl--;
469115424Sfenner					STPUTC('\n', dest);
470115424Sfenner				}
471115424Sfenner				STPUTC(lastc, dest);
472115424Sfenner			}
4731556Srgrimes		}
4741556Srgrimes	}
47517987Speter
4761556Srgrimes	if (in.fd >= 0)
4771556Srgrimes		close(in.fd);
4781556Srgrimes	if (in.buf)
4791556Srgrimes		ckfree(in.buf);
4801556Srgrimes	if (in.jp)
48145916Scracauer		exitstatus = waitforjob(in.jp, (int *)NULL);
4821556Srgrimes	if (quoted == 0)
4831556Srgrimes		recordregion(startloc, dest - stackblock(), 0);
4841556Srgrimes	TRACE(("evalbackq: size=%d: \"%.*s\"\n",
4851556Srgrimes		(dest - stackblock()) - startloc,
4861556Srgrimes		(dest - stackblock()) - startloc,
4871556Srgrimes		stackblock() + startloc));
4881556Srgrimes	expdest = dest;
4891556Srgrimes	INTON;
4901556Srgrimes}
4911556Srgrimes
4921556Srgrimes
4931556Srgrimes
49417987SpeterSTATIC int
49590111Simpsubevalvar(char *p, char *str, int strloc, int subtype, int startloc,
49690111Simp  int varflags)
49717987Speter{
49817987Speter	char *startp;
49917987Speter	char *loc = NULL;
50045514Stegge	char *q;
50117987Speter	int c = 0;
50217987Speter	int saveherefd = herefd;
50317987Speter	struct nodelist *saveargbackq = argbackq;
50420425Ssteve	int amount;
50520425Ssteve
50617987Speter	herefd = -1;
50717987Speter	argstr(p, 0);
50817987Speter	STACKSTRNUL(expdest);
50917987Speter	herefd = saveherefd;
51017987Speter	argbackq = saveargbackq;
51117987Speter	startp = stackblock() + startloc;
51220425Ssteve	if (str == NULL)
51320425Ssteve	    str = stackblock() + strloc;
51417987Speter
51517987Speter	switch (subtype) {
51617987Speter	case VSASSIGN:
51717987Speter		setvar(str, startp, 0);
51820425Ssteve		amount = startp - expdest;
51920425Ssteve		STADJUST(amount, expdest);
52017987Speter		varflags &= ~VSNUL;
52117987Speter		if (c != 0)
52217987Speter			*loc = c;
52317987Speter		return 1;
52417987Speter
52517987Speter	case VSQUESTION:
52617987Speter		if (*p != CTLENDVAR) {
52717987Speter			outfmt(&errout, "%s\n", startp);
52817987Speter			error((char *)NULL);
52917987Speter		}
530112254Sru		error("%.*s: parameter %snot set", (int)(p - str - 1),
53117987Speter		      str, (varflags & VSNUL) ? "null or "
53217987Speter					      : nullstr);
53317987Speter		return 0;
53417987Speter
53517987Speter	case VSTRIMLEFT:
53625233Ssteve		for (loc = startp; loc < str; loc++) {
53717987Speter			c = *loc;
53817987Speter			*loc = '\0';
53945514Stegge			if (patmatch(str, startp, varflags & VSQUOTE)) {
54017987Speter				*loc = c;
54117987Speter				goto recordleft;
54217987Speter			}
54317987Speter			*loc = c;
54445514Stegge			if ((varflags & VSQUOTE) && *loc == CTLESC)
54545514Stegge				loc++;
54617987Speter		}
54717987Speter		return 0;
54817987Speter
54917987Speter	case VSTRIMLEFTMAX:
55045514Stegge		for (loc = str - 1; loc >= startp;) {
55117987Speter			c = *loc;
55217987Speter			*loc = '\0';
55345514Stegge			if (patmatch(str, startp, varflags & VSQUOTE)) {
55417987Speter				*loc = c;
55517987Speter				goto recordleft;
55617987Speter			}
55717987Speter			*loc = c;
55845514Stegge			loc--;
55945514Stegge			if ((varflags & VSQUOTE) && loc > startp &&
56045514Stegge			    *(loc - 1) == CTLESC) {
56145514Stegge				for (q = startp; q < loc; q++)
56245514Stegge					if (*q == CTLESC)
56345514Stegge						q++;
56445514Stegge				if (q > loc)
56545514Stegge					loc--;
56645514Stegge			}
56717987Speter		}
56817987Speter		return 0;
56917987Speter
57017987Speter	case VSTRIMRIGHT:
57145514Stegge		for (loc = str - 1; loc >= startp;) {
57245514Stegge			if (patmatch(str, loc, varflags & VSQUOTE)) {
57320425Ssteve				amount = loc - expdest;
57420425Ssteve				STADJUST(amount, expdest);
57517987Speter				return 1;
57617987Speter			}
57745514Stegge			loc--;
57845514Stegge			if ((varflags & VSQUOTE) && loc > startp &&
579155301Sschweikh			    *(loc - 1) == CTLESC) {
58045514Stegge				for (q = startp; q < loc; q++)
58145514Stegge					if (*q == CTLESC)
58245514Stegge						q++;
58345514Stegge				if (q > loc)
58445514Stegge					loc--;
58545514Stegge			}
58617987Speter		}
58717987Speter		return 0;
58817987Speter
58917987Speter	case VSTRIMRIGHTMAX:
59017987Speter		for (loc = startp; loc < str - 1; loc++) {
59145514Stegge			if (patmatch(str, loc, varflags & VSQUOTE)) {
59220425Ssteve				amount = loc - expdest;
59320425Ssteve				STADJUST(amount, expdest);
59417987Speter				return 1;
59517987Speter			}
59645514Stegge			if ((varflags & VSQUOTE) && *loc == CTLESC)
59745514Stegge				loc++;
59817987Speter		}
59917987Speter		return 0;
60017987Speter
60117987Speter
60217987Speter	default:
60317987Speter		abort();
60417987Speter	}
60517987Speter
60617987Speterrecordleft:
60720425Ssteve	amount = ((str - 1) - (loc - startp)) - expdest;
60820425Ssteve	STADJUST(amount, expdest);
60917987Speter	while (loc != str - 1)
61017987Speter		*startp++ = *loc++;
61117987Speter	return 1;
61217987Speter}
61317987Speter
61417987Speter
6151556Srgrimes/*
6161556Srgrimes * Expand a variable, and return a pointer to the next character in the
6171556Srgrimes * input string.
6181556Srgrimes */
6191556Srgrimes
6201556SrgrimesSTATIC char *
62190111Simpevalvar(char *p, int flag)
62217987Speter{
6231556Srgrimes	int subtype;
6241556Srgrimes	int varflags;
6251556Srgrimes	char *var;
6261556Srgrimes	char *val;
62745644Stegge	int patloc;
6281556Srgrimes	int c;
6291556Srgrimes	int set;
6301556Srgrimes	int special;
6311556Srgrimes	int startloc;
63217987Speter	int varlen;
63317987Speter	int easy;
634108935Stjr	int quotes = flag & (EXP_FULL | EXP_CASE | EXP_REDIR);
6351556Srgrimes
6361556Srgrimes	varflags = *p++;
6371556Srgrimes	subtype = varflags & VSTYPE;
6381556Srgrimes	var = p;
6391556Srgrimes	special = 0;
6401556Srgrimes	if (! is_name(*p))
6411556Srgrimes		special = 1;
6421556Srgrimes	p = strchr(p, '=') + 1;
6431556Srgrimesagain: /* jump here after setting a variable with ${var=text} */
6441556Srgrimes	if (special) {
64525233Ssteve		set = varisset(var, varflags & VSNUL);
6461556Srgrimes		val = NULL;
6471556Srgrimes	} else {
64860592Scracauer		val = bltinlookup(var, 1);
64917987Speter		if (val == NULL || ((varflags & VSNUL) && val[0] == '\0')) {
6501556Srgrimes			val = NULL;
6511556Srgrimes			set = 0;
6521556Srgrimes		} else
6531556Srgrimes			set = 1;
6541556Srgrimes	}
65517987Speter	varlen = 0;
6561556Srgrimes	startloc = expdest - stackblock();
65796939Stjr	if (!set && uflag) {
65896939Stjr		switch (subtype) {
65996939Stjr		case VSNORMAL:
66096939Stjr		case VSTRIMLEFT:
66196939Stjr		case VSTRIMLEFTMAX:
66296939Stjr		case VSTRIMRIGHT:
66396939Stjr		case VSTRIMRIGHTMAX:
66496939Stjr		case VSLENGTH:
665112254Sru			error("%.*s: parameter not set", (int)(p - var - 1),
666112254Sru			    var);
66796939Stjr		}
66896939Stjr	}
6691556Srgrimes	if (set && subtype != VSPLUS) {
6701556Srgrimes		/* insert the value of the variable */
6711556Srgrimes		if (special) {
67218202Speter			varvalue(var, varflags & VSQUOTE, flag & EXP_FULL);
67317987Speter			if (subtype == VSLENGTH) {
67425233Ssteve				varlen = expdest - stackblock() - startloc;
67525233Ssteve				STADJUST(-varlen, expdest);
67617987Speter			}
6771556Srgrimes		} else {
67820425Ssteve			char const *syntax = (varflags & VSQUOTE) ? DQSYNTAX
67917987Speter								  : BASESYNTAX;
6801556Srgrimes
68117987Speter			if (subtype == VSLENGTH) {
68217987Speter				for (;*val; val++)
68317987Speter					varlen++;
6841556Srgrimes			}
68517987Speter			else {
68617987Speter				while (*val) {
68783675Stegge					if (quotes &&
68854132Scracauer					    syntax[(int)*val] == CCTL)
68917987Speter						STPUTC(CTLESC, expdest);
69017987Speter					STPUTC(*val++, expdest);
69117987Speter				}
69217987Speter
69317987Speter			}
6941556Srgrimes		}
6951556Srgrimes	}
69620425Ssteve
6971556Srgrimes	if (subtype == VSPLUS)
6981556Srgrimes		set = ! set;
69917987Speter
70020425Ssteve	easy = ((varflags & VSQUOTE) == 0 ||
70117987Speter		(*var == '@' && shellparam.nparam != 1));
70217987Speter
70317987Speter
70417987Speter	switch (subtype) {
70517987Speter	case VSLENGTH:
70617987Speter		expdest = cvtnum(varlen, expdest);
70717987Speter		goto record;
70817987Speter
70917987Speter	case VSNORMAL:
71017987Speter		if (!easy)
71117987Speter			break;
71217987Speterrecord:
71320425Ssteve		recordregion(startloc, expdest - stackblock(),
71417987Speter			     varflags & VSQUOTE);
71517987Speter		break;
71617987Speter
71717987Speter	case VSPLUS:
71817987Speter	case VSMINUS:
71917987Speter		if (!set) {
7201556Srgrimes			argstr(p, flag);
72117987Speter			break;
72217987Speter		}
72317987Speter		if (easy)
72417987Speter			goto record;
72517987Speter		break;
72617987Speter
72717987Speter	case VSTRIMLEFT:
72817987Speter	case VSTRIMLEFTMAX:
72917987Speter	case VSTRIMRIGHT:
73017987Speter	case VSTRIMRIGHTMAX:
73117987Speter		if (!set)
73217987Speter			break;
73317987Speter		/*
73417987Speter		 * Terminate the string and start recording the pattern
73517987Speter		 * right after it
73617987Speter		 */
73717987Speter		STPUTC('\0', expdest);
73845644Stegge		patloc = expdest - stackblock();
73945644Stegge		if (subevalvar(p, NULL, patloc, subtype,
74038887Stegge			       startloc, varflags) == 0) {
74145644Stegge			int amount = (expdest - stackblock() - patloc) + 1;
74225233Ssteve			STADJUST(-amount, expdest);
74325233Ssteve		}
74438887Stegge		/* Remove any recorded regions beyond start of variable */
74538887Stegge		removerecordregions(startloc);
74638887Stegge		goto record;
74717987Speter
74817987Speter	case VSASSIGN:
74917987Speter	case VSQUESTION:
75017987Speter		if (!set) {
75120425Ssteve			if (subevalvar(p, var, 0, subtype, startloc, varflags)) {
75220425Ssteve				varflags &= ~VSNUL;
753155301Sschweikh				/*
754155301Sschweikh				 * Remove any recorded regions beyond
755155301Sschweikh				 * start of variable
75638887Stegge				 */
75738887Stegge				removerecordregions(startloc);
7581556Srgrimes				goto again;
75920425Ssteve			}
76017987Speter			break;
7611556Srgrimes		}
76217987Speter		if (easy)
76317987Speter			goto record;
76417987Speter		break;
76517987Speter
766164003Sstefanf	case VSERROR:
767164003Sstefanf		c = p - var - 1;
768164003Sstefanf		error("${%.*s%s}: Bad substitution", c, var,
769164003Sstefanf		    (c > 0 && *p != CTLENDVAR) ? "..." : "");
770164003Sstefanf
77117987Speter	default:
77217987Speter		abort();
7731556Srgrimes	}
77417987Speter
7751556Srgrimes	if (subtype != VSNORMAL) {	/* skip to end of alternative */
7761556Srgrimes		int nesting = 1;
7771556Srgrimes		for (;;) {
7781556Srgrimes			if ((c = *p++) == CTLESC)
7791556Srgrimes				p++;
7801556Srgrimes			else if (c == CTLBACKQ || c == (CTLBACKQ|CTLQUOTE)) {
7811556Srgrimes				if (set)
7821556Srgrimes					argbackq = argbackq->next;
7831556Srgrimes			} else if (c == CTLVAR) {
7841556Srgrimes				if ((*p++ & VSTYPE) != VSNORMAL)
7851556Srgrimes					nesting++;
7861556Srgrimes			} else if (c == CTLENDVAR) {
7871556Srgrimes				if (--nesting == 0)
7881556Srgrimes					break;
7891556Srgrimes			}
7901556Srgrimes		}
7911556Srgrimes	}
7921556Srgrimes	return p;
7931556Srgrimes}
7941556Srgrimes
7951556Srgrimes
7961556Srgrimes
7971556Srgrimes/*
7981556Srgrimes * Test whether a specialized variable is set.
7991556Srgrimes */
8001556Srgrimes
8011556SrgrimesSTATIC int
80290111Simpvarisset(char *name, int nulok)
80325233Ssteve{
8041556Srgrimes
80525233Ssteve	if (*name == '!')
80625233Ssteve		return backgndpid != -1;
80725233Ssteve	else if (*name == '@' || *name == '*') {
8081556Srgrimes		if (*shellparam.p == NULL)
8091556Srgrimes			return 0;
81025233Ssteve
81125233Ssteve		if (nulok) {
81225233Ssteve			char **av;
81325233Ssteve
81425233Ssteve			for (av = shellparam.p; *av; av++)
81525233Ssteve				if (**av != '\0')
81625233Ssteve					return 1;
81725233Ssteve			return 0;
81825233Ssteve		}
81918202Speter	} else if (is_digit(*name)) {
82025233Ssteve		char *ap;
82120425Ssteve		int num = atoi(name);
82225233Ssteve
82325233Ssteve		if (num > shellparam.nparam)
82425233Ssteve			return 0;
82525233Ssteve
82625233Ssteve		if (num == 0)
82725233Ssteve			ap = arg0;
82825233Ssteve		else
82925233Ssteve			ap = shellparam.p[num - 1];
83025233Ssteve
83125233Ssteve		if (nulok && (ap == NULL || *ap == '\0'))
83225233Ssteve			return 0;
8331556Srgrimes	}
8341556Srgrimes	return 1;
8351556Srgrimes}
8361556Srgrimes
8371556Srgrimes
8381556Srgrimes
8391556Srgrimes/*
8401556Srgrimes * Add the value of a specialized variable to the stack string.
8411556Srgrimes */
8421556Srgrimes
8431556SrgrimesSTATIC void
84490111Simpvarvalue(char *name, int quoted, int allow_split)
84517987Speter{
8461556Srgrimes	int num;
8471556Srgrimes	char *p;
8481556Srgrimes	int i;
84917987Speter	extern int oexitstatus;
8501556Srgrimes	char sep;
8511556Srgrimes	char **ap;
8521556Srgrimes	char const *syntax;
8531556Srgrimes
8541556Srgrimes#define STRTODEST(p) \
8551556Srgrimes	do {\
8561556Srgrimes	if (allow_split) { \
8571556Srgrimes		syntax = quoted? DQSYNTAX : BASESYNTAX; \
8581556Srgrimes		while (*p) { \
85983675Stegge			if (syntax[(int)*p] == CCTL) \
8601556Srgrimes				STPUTC(CTLESC, expdest); \
8611556Srgrimes			STPUTC(*p++, expdest); \
8621556Srgrimes		} \
8631556Srgrimes	} else \
8641556Srgrimes		while (*p) \
8651556Srgrimes			STPUTC(*p++, expdest); \
8661556Srgrimes	} while (0)
8671556Srgrimes
8681556Srgrimes
86918202Speter	switch (*name) {
8701556Srgrimes	case '$':
8711556Srgrimes		num = rootpid;
8721556Srgrimes		goto numvar;
8731556Srgrimes	case '?':
87417987Speter		num = oexitstatus;
8751556Srgrimes		goto numvar;
8761556Srgrimes	case '#':
8771556Srgrimes		num = shellparam.nparam;
8781556Srgrimes		goto numvar;
8791556Srgrimes	case '!':
8801556Srgrimes		num = backgndpid;
8811556Srgrimesnumvar:
88217987Speter		expdest = cvtnum(num, expdest);
8831556Srgrimes		break;
8841556Srgrimes	case '-':
8851556Srgrimes		for (i = 0 ; i < NOPTS ; i++) {
8861556Srgrimes			if (optlist[i].val)
8871556Srgrimes				STPUTC(optlist[i].letter, expdest);
8881556Srgrimes		}
8891556Srgrimes		break;
8901556Srgrimes	case '@':
89138887Stegge		if (allow_split && quoted) {
89238887Stegge			for (ap = shellparam.p ; (p = *ap++) != NULL ; ) {
89338887Stegge				STRTODEST(p);
89438887Stegge				if (*ap)
89538887Stegge					STPUTC('\0', expdest);
89638887Stegge			}
89738887Stegge			break;
8981556Srgrimes		}
899102410Scharnier		/* FALLTHROUGH */
9001556Srgrimes	case '*':
901149825Srse		if (ifsset())
90238887Stegge			sep = ifsval()[0];
90338887Stegge		else
90438887Stegge			sep = ' ';
9051556Srgrimes		for (ap = shellparam.p ; (p = *ap++) != NULL ; ) {
9061556Srgrimes			STRTODEST(p);
90738887Stegge			if (*ap && sep)
9081556Srgrimes				STPUTC(sep, expdest);
9091556Srgrimes		}
9101556Srgrimes		break;
9111556Srgrimes	case '0':
9121556Srgrimes		p = arg0;
9131556Srgrimes		STRTODEST(p);
9141556Srgrimes		break;
9151556Srgrimes	default:
91618202Speter		if (is_digit(*name)) {
91718202Speter			num = atoi(name);
91818202Speter			if (num > 0 && num <= shellparam.nparam) {
91918202Speter				p = shellparam.p[num - 1];
92018202Speter				STRTODEST(p);
92118202Speter			}
9221556Srgrimes		}
9231556Srgrimes		break;
9241556Srgrimes	}
9251556Srgrimes}
9261556Srgrimes
9271556Srgrimes
9281556Srgrimes
9291556Srgrimes/*
9301556Srgrimes * Record the the fact that we have to scan this region of the
9311556Srgrimes * string for IFS characters.
9321556Srgrimes */
9331556Srgrimes
9341556SrgrimesSTATIC void
93590111Simprecordregion(int start, int end, int nulonly)
93617987Speter{
93725233Ssteve	struct ifsregion *ifsp;
9381556Srgrimes
9391556Srgrimes	if (ifslastp == NULL) {
9401556Srgrimes		ifsp = &ifsfirst;
9411556Srgrimes	} else {
9421556Srgrimes		ifsp = (struct ifsregion *)ckmalloc(sizeof (struct ifsregion));
9431556Srgrimes		ifslastp->next = ifsp;
9441556Srgrimes	}
9451556Srgrimes	ifslastp = ifsp;
9461556Srgrimes	ifslastp->next = NULL;
9471556Srgrimes	ifslastp->begoff = start;
9481556Srgrimes	ifslastp->endoff = end;
9491556Srgrimes	ifslastp->nulonly = nulonly;
9501556Srgrimes}
9511556Srgrimes
9521556Srgrimes
9531556Srgrimes
9541556Srgrimes/*
9551556Srgrimes * Break the argument string into pieces based upon IFS and add the
9561556Srgrimes * strings to the argument list.  The regions of the string to be
9571556Srgrimes * searched for IFS characters have been stored by recordregion.
9581556Srgrimes */
9591556SrgrimesSTATIC void
96090111Simpifsbreakup(char *string, struct arglist *arglist)
96190111Simp{
9621556Srgrimes	struct ifsregion *ifsp;
9631556Srgrimes	struct strlist *sp;
9641556Srgrimes	char *start;
96525233Ssteve	char *p;
9661556Srgrimes	char *q;
9671556Srgrimes	char *ifs;
96817987Speter	int ifsspc;
96938887Stegge	int nulonly;
9701556Srgrimes
97117987Speter
9721556Srgrimes	start = string;
97338887Stegge	ifsspc = 0;
97438887Stegge	nulonly = 0;
9751556Srgrimes	if (ifslastp != NULL) {
9761556Srgrimes		ifsp = &ifsfirst;
9771556Srgrimes		do {
9781556Srgrimes			p = string + ifsp->begoff;
97938887Stegge			nulonly = ifsp->nulonly;
980155301Sschweikh			ifs = nulonly ? nullstr :
98138887Stegge				( ifsset() ? ifsval() : " \t\n" );
98238887Stegge			ifsspc = 0;
9831556Srgrimes			while (p < string + ifsp->endoff) {
9841556Srgrimes				q = p;
9851556Srgrimes				if (*p == CTLESC)
9861556Srgrimes					p++;
98738887Stegge				if (strchr(ifs, *p)) {
98838887Stegge					if (!nulonly)
98938887Stegge						ifsspc = (strchr(" \t\n", *p) != NULL);
99038887Stegge					/* Ignore IFS whitespace at start */
99138887Stegge					if (q == start && ifsspc) {
99238887Stegge						p++;
99338887Stegge						start = p;
99438887Stegge						continue;
9951556Srgrimes					}
99638887Stegge					*q = '\0';
99738887Stegge					sp = (struct strlist *)stalloc(sizeof *sp);
99838887Stegge					sp->text = start;
99938887Stegge					*arglist->lastp = sp;
100038887Stegge					arglist->lastp = &sp->next;
100138887Stegge					p++;
100238887Stegge					if (!nulonly) {
10031556Srgrimes						for (;;) {
100438887Stegge							if (p >= string + ifsp->endoff) {
10051556Srgrimes								break;
100638887Stegge							}
10071556Srgrimes							q = p;
10081556Srgrimes							if (*p == CTLESC)
10091556Srgrimes								p++;
101038887Stegge							if (strchr(ifs, *p) == NULL ) {
10111556Srgrimes								p = q;
10121556Srgrimes								break;
101338887Stegge							} else if (strchr(" \t\n",*p) == NULL) {
101438887Stegge								if (ifsspc) {
101538887Stegge									p++;
101638887Stegge									ifsspc = 0;
101738887Stegge								} else {
101838887Stegge									p = q;
101938887Stegge									break;
102038887Stegge								}
102138887Stegge							} else
102238887Stegge								p++;
10231556Srgrimes						}
10241556Srgrimes					}
10251556Srgrimes					start = p;
102638887Stegge				} else
102738887Stegge					p++;
10281556Srgrimes			}
10291556Srgrimes		} while ((ifsp = ifsp->next) != NULL);
1030149825Srse		if (*start || (!ifsspc && start > string)) {
10311556Srgrimes			sp = (struct strlist *)stalloc(sizeof *sp);
10321556Srgrimes			sp->text = start;
10331556Srgrimes			*arglist->lastp = sp;
10341556Srgrimes			arglist->lastp = &sp->next;
10351556Srgrimes		}
10361556Srgrimes	} else {
10371556Srgrimes		sp = (struct strlist *)stalloc(sizeof *sp);
10381556Srgrimes		sp->text = start;
10391556Srgrimes		*arglist->lastp = sp;
10401556Srgrimes		arglist->lastp = &sp->next;
10411556Srgrimes	}
10421556Srgrimes}
10431556Srgrimes
10441556Srgrimes
10451556Srgrimes
10461556Srgrimes/*
10471556Srgrimes * Expand shell metacharacters.  At this point, the only control characters
10481556Srgrimes * should be escapes.  The results are stored in the list exparg.
10491556Srgrimes */
10501556Srgrimes
1051117261SddsSTATIC char *expdir;
10521556Srgrimes
10531556Srgrimes
10541556SrgrimesSTATIC void
105590111Simpexpandmeta(struct strlist *str, int flag __unused)
105617987Speter{
10571556Srgrimes	char *p;
10581556Srgrimes	struct strlist **savelastp;
10591556Srgrimes	struct strlist *sp;
10601556Srgrimes	char c;
10611556Srgrimes	/* TODO - EXP_REDIR */
10621556Srgrimes
10631556Srgrimes	while (str) {
10641556Srgrimes		if (fflag)
10651556Srgrimes			goto nometa;
10661556Srgrimes		p = str->text;
10671556Srgrimes		for (;;) {			/* fast check for meta chars */
10681556Srgrimes			if ((c = *p++) == '\0')
10691556Srgrimes				goto nometa;
10701556Srgrimes			if (c == '*' || c == '?' || c == '[' || c == '!')
10711556Srgrimes				break;
10721556Srgrimes		}
10731556Srgrimes		savelastp = exparg.lastp;
10741556Srgrimes		INTOFF;
10751556Srgrimes		if (expdir == NULL) {
10761556Srgrimes			int i = strlen(str->text);
10771556Srgrimes			expdir = ckmalloc(i < 2048 ? 2048 : i); /* XXX */
10781556Srgrimes		}
10791556Srgrimes
10801556Srgrimes		expmeta(expdir, str->text);
10811556Srgrimes		ckfree(expdir);
10821556Srgrimes		expdir = NULL;
10831556Srgrimes		INTON;
10841556Srgrimes		if (exparg.lastp == savelastp) {
10858855Srgrimes			/*
10868855Srgrimes			 * no matches
10871556Srgrimes			 */
10881556Srgrimesnometa:
10891556Srgrimes			*exparg.lastp = str;
10901556Srgrimes			rmescapes(str->text);
10911556Srgrimes			exparg.lastp = &str->next;
10921556Srgrimes		} else {
10931556Srgrimes			*exparg.lastp = NULL;
10941556Srgrimes			*savelastp = sp = expsort(*savelastp);
10951556Srgrimes			while (sp->next != NULL)
10961556Srgrimes				sp = sp->next;
10971556Srgrimes			exparg.lastp = &sp->next;
10981556Srgrimes		}
10991556Srgrimes		str = str->next;
11001556Srgrimes	}
11011556Srgrimes}
11021556Srgrimes
11031556Srgrimes
11041556Srgrimes/*
11051556Srgrimes * Do metacharacter (i.e. *, ?, [...]) expansion.
11061556Srgrimes */
11071556Srgrimes
11081556SrgrimesSTATIC void
110990111Simpexpmeta(char *enddir, char *name)
111090111Simp{
111125233Ssteve	char *p;
11121556Srgrimes	char *q;
11131556Srgrimes	char *start;
11141556Srgrimes	char *endname;
11151556Srgrimes	int metaflag;
11161556Srgrimes	struct stat statb;
11171556Srgrimes	DIR *dirp;
11181556Srgrimes	struct dirent *dp;
11191556Srgrimes	int atend;
11201556Srgrimes	int matchdot;
11211556Srgrimes
11221556Srgrimes	metaflag = 0;
11231556Srgrimes	start = name;
11241556Srgrimes	for (p = name ; ; p++) {
11251556Srgrimes		if (*p == '*' || *p == '?')
11261556Srgrimes			metaflag = 1;
11271556Srgrimes		else if (*p == '[') {
11281556Srgrimes			q = p + 1;
112926488Sache			if (*q == '!' || *q == '^')
11301556Srgrimes				q++;
11311556Srgrimes			for (;;) {
113238887Stegge				while (*q == CTLQUOTEMARK)
113338887Stegge					q++;
11341556Srgrimes				if (*q == CTLESC)
11351556Srgrimes					q++;
11361556Srgrimes				if (*q == '/' || *q == '\0')
11371556Srgrimes					break;
11381556Srgrimes				if (*++q == ']') {
11391556Srgrimes					metaflag = 1;
11401556Srgrimes					break;
11411556Srgrimes				}
11421556Srgrimes			}
11431556Srgrimes		} else if (*p == '!' && p[1] == '!'	&& (p == name || p[-1] == '/')) {
11441556Srgrimes			metaflag = 1;
11451556Srgrimes		} else if (*p == '\0')
11461556Srgrimes			break;
114738887Stegge		else if (*p == CTLQUOTEMARK)
114838887Stegge			continue;
11491556Srgrimes		else if (*p == CTLESC)
11501556Srgrimes			p++;
11511556Srgrimes		if (*p == '/') {
11521556Srgrimes			if (metaflag)
11531556Srgrimes				break;
11541556Srgrimes			start = p + 1;
11551556Srgrimes		}
11561556Srgrimes	}
11571556Srgrimes	if (metaflag == 0) {	/* we've reached the end of the file name */
11581556Srgrimes		if (enddir != expdir)
11591556Srgrimes			metaflag++;
11601556Srgrimes		for (p = name ; ; p++) {
116138887Stegge			if (*p == CTLQUOTEMARK)
116238887Stegge				continue;
11631556Srgrimes			if (*p == CTLESC)
11641556Srgrimes				p++;
11651556Srgrimes			*enddir++ = *p;
11661556Srgrimes			if (*p == '\0')
11671556Srgrimes				break;
11681556Srgrimes		}
1169147812Sdelphij		if (metaflag == 0 || lstat(expdir, &statb) >= 0)
11701556Srgrimes			addfname(expdir);
11711556Srgrimes		return;
11721556Srgrimes	}
11731556Srgrimes	endname = p;
11741556Srgrimes	if (start != name) {
11751556Srgrimes		p = name;
11761556Srgrimes		while (p < start) {
117738887Stegge			while (*p == CTLQUOTEMARK)
117838887Stegge				p++;
11791556Srgrimes			if (*p == CTLESC)
11801556Srgrimes				p++;
11811556Srgrimes			*enddir++ = *p++;
11821556Srgrimes		}
11831556Srgrimes	}
11841556Srgrimes	if (enddir == expdir) {
11851556Srgrimes		p = ".";
11861556Srgrimes	} else if (enddir == expdir + 1 && *expdir == '/') {
11871556Srgrimes		p = "/";
11881556Srgrimes	} else {
11891556Srgrimes		p = expdir;
11901556Srgrimes		enddir[-1] = '\0';
11911556Srgrimes	}
11921556Srgrimes	if ((dirp = opendir(p)) == NULL)
11931556Srgrimes		return;
11941556Srgrimes	if (enddir != expdir)
11951556Srgrimes		enddir[-1] = '/';
11961556Srgrimes	if (*endname == 0) {
11971556Srgrimes		atend = 1;
11981556Srgrimes	} else {
11991556Srgrimes		atend = 0;
12001556Srgrimes		*endname++ = '\0';
12011556Srgrimes	}
12021556Srgrimes	matchdot = 0;
120338887Stegge	p = start;
120438887Stegge	while (*p == CTLQUOTEMARK)
120538887Stegge		p++;
120638887Stegge	if (*p == CTLESC)
120738887Stegge		p++;
120838887Stegge	if (*p == '.')
12091556Srgrimes		matchdot++;
12101556Srgrimes	while (! int_pending() && (dp = readdir(dirp)) != NULL) {
12111556Srgrimes		if (dp->d_name[0] == '.' && ! matchdot)
12121556Srgrimes			continue;
121345514Stegge		if (patmatch(start, dp->d_name, 0)) {
12141556Srgrimes			if (atend) {
12151556Srgrimes				scopy(dp->d_name, enddir);
12161556Srgrimes				addfname(expdir);
12171556Srgrimes			} else {
121817987Speter				for (p = enddir, q = dp->d_name;
121917987Speter				     (*p++ = *q++) != '\0';)
122017987Speter					continue;
12211556Srgrimes				p[-1] = '/';
12221556Srgrimes				expmeta(p, endname);
12231556Srgrimes			}
12241556Srgrimes		}
12251556Srgrimes	}
12261556Srgrimes	closedir(dirp);
12271556Srgrimes	if (! atend)
12281556Srgrimes		endname[-1] = '/';
12291556Srgrimes}
12301556Srgrimes
12311556Srgrimes
12321556Srgrimes/*
12331556Srgrimes * Add a file name to the list.
12341556Srgrimes */
12351556Srgrimes
12361556SrgrimesSTATIC void
123790111Simpaddfname(char *name)
123890111Simp{
12391556Srgrimes	char *p;
12401556Srgrimes	struct strlist *sp;
12411556Srgrimes
12421556Srgrimes	p = stalloc(strlen(name) + 1);
12431556Srgrimes	scopy(name, p);
12441556Srgrimes	sp = (struct strlist *)stalloc(sizeof *sp);
12451556Srgrimes	sp->text = p;
12461556Srgrimes	*exparg.lastp = sp;
12471556Srgrimes	exparg.lastp = &sp->next;
12481556Srgrimes}
12491556Srgrimes
12501556Srgrimes
12511556Srgrimes/*
12521556Srgrimes * Sort the results of file name expansion.  It calculates the number of
12531556Srgrimes * strings to sort and then calls msort (short for merge sort) to do the
12541556Srgrimes * work.
12551556Srgrimes */
12561556Srgrimes
12571556SrgrimesSTATIC struct strlist *
125890111Simpexpsort(struct strlist *str)
125990111Simp{
12601556Srgrimes	int len;
12611556Srgrimes	struct strlist *sp;
12621556Srgrimes
12631556Srgrimes	len = 0;
12641556Srgrimes	for (sp = str ; sp ; sp = sp->next)
12651556Srgrimes		len++;
12661556Srgrimes	return msort(str, len);
12671556Srgrimes}
12681556Srgrimes
12691556Srgrimes
12701556SrgrimesSTATIC struct strlist *
127190111Simpmsort(struct strlist *list, int len)
127217987Speter{
127317987Speter	struct strlist *p, *q = NULL;
12741556Srgrimes	struct strlist **lpp;
12751556Srgrimes	int half;
12761556Srgrimes	int n;
12771556Srgrimes
12781556Srgrimes	if (len <= 1)
12791556Srgrimes		return list;
12808855Srgrimes	half = len >> 1;
12811556Srgrimes	p = list;
12821556Srgrimes	for (n = half ; --n >= 0 ; ) {
12831556Srgrimes		q = p;
12841556Srgrimes		p = p->next;
12851556Srgrimes	}
12861556Srgrimes	q->next = NULL;			/* terminate first half of list */
12871556Srgrimes	q = msort(list, half);		/* sort first half of list */
12881556Srgrimes	p = msort(p, len - half);		/* sort second half */
12891556Srgrimes	lpp = &list;
12901556Srgrimes	for (;;) {
12911556Srgrimes		if (strcmp(p->text, q->text) < 0) {
12921556Srgrimes			*lpp = p;
12931556Srgrimes			lpp = &p->next;
12941556Srgrimes			if ((p = *lpp) == NULL) {
12951556Srgrimes				*lpp = q;
12961556Srgrimes				break;
12971556Srgrimes			}
12981556Srgrimes		} else {
12991556Srgrimes			*lpp = q;
13001556Srgrimes			lpp = &q->next;
13011556Srgrimes			if ((q = *lpp) == NULL) {
13021556Srgrimes				*lpp = p;
13031556Srgrimes				break;
13041556Srgrimes			}
13051556Srgrimes		}
13061556Srgrimes	}
13071556Srgrimes	return list;
13081556Srgrimes}
13091556Srgrimes
13101556Srgrimes
13111556Srgrimes
13121556Srgrimes/*
13131556Srgrimes * Returns true if the pattern matches the string.
13141556Srgrimes */
13151556Srgrimes
13161556Srgrimesint
131790111Simppatmatch(char *pattern, char *string, int squoted)
131890111Simp{
13191556Srgrimes#ifdef notdef
13201556Srgrimes	if (pattern[0] == '!' && pattern[1] == '!')
13211556Srgrimes		return 1 - pmatch(pattern + 2, string);
13221556Srgrimes	else
13231556Srgrimes#endif
132445514Stegge		return pmatch(pattern, string, squoted);
13251556Srgrimes}
13261556Srgrimes
132717987Speter
132817525SacheSTATIC int
132990111Simppmatch(char *pattern, char *string, int squoted)
133090111Simp{
133125233Ssteve	char *p, *q;
133225233Ssteve	char c;
13331556Srgrimes
13341556Srgrimes	p = pattern;
13351556Srgrimes	q = string;
13361556Srgrimes	for (;;) {
13371556Srgrimes		switch (c = *p++) {
13381556Srgrimes		case '\0':
13391556Srgrimes			goto breakloop;
13401556Srgrimes		case CTLESC:
134145514Stegge			if (squoted && *q == CTLESC)
134245514Stegge				q++;
13431556Srgrimes			if (*q++ != *p++)
13441556Srgrimes				return 0;
13451556Srgrimes			break;
134638887Stegge		case CTLQUOTEMARK:
134738887Stegge			continue;
13481556Srgrimes		case '?':
134945514Stegge			if (squoted && *q == CTLESC)
135045514Stegge				q++;
13511556Srgrimes			if (*q++ == '\0')
13521556Srgrimes				return 0;
13531556Srgrimes			break;
13541556Srgrimes		case '*':
13551556Srgrimes			c = *p;
135638887Stegge			while (c == CTLQUOTEMARK || c == '*')
135738887Stegge				c = *++p;
135838887Stegge			if (c != CTLESC &&  c != CTLQUOTEMARK &&
135938887Stegge			    c != '?' && c != '*' && c != '[') {
13601556Srgrimes				while (*q != c) {
136145514Stegge					if (squoted && *q == CTLESC &&
136245514Stegge					    q[1] == c)
136345514Stegge						break;
13641556Srgrimes					if (*q == '\0')
13651556Srgrimes						return 0;
136645514Stegge					if (squoted && *q == CTLESC)
136745514Stegge						q++;
13681556Srgrimes					q++;
13691556Srgrimes				}
13701556Srgrimes			}
13711556Srgrimes			do {
137245514Stegge				if (pmatch(p, q, squoted))
13731556Srgrimes					return 1;
137445514Stegge				if (squoted && *q == CTLESC)
137545514Stegge					q++;
13761556Srgrimes			} while (*q++ != '\0');
13771556Srgrimes			return 0;
13781556Srgrimes		case '[': {
13791556Srgrimes			char *endp;
13801556Srgrimes			int invert, found;
13811556Srgrimes			char chr;
13821556Srgrimes
13831556Srgrimes			endp = p;
138426488Sache			if (*endp == '!' || *endp == '^')
13851556Srgrimes				endp++;
13861556Srgrimes			for (;;) {
138738887Stegge				while (*endp == CTLQUOTEMARK)
138838887Stegge					endp++;
13891556Srgrimes				if (*endp == '\0')
13901556Srgrimes					goto dft;		/* no matching ] */
13911556Srgrimes				if (*endp == CTLESC)
13921556Srgrimes					endp++;
13931556Srgrimes				if (*++endp == ']')
13941556Srgrimes					break;
13951556Srgrimes			}
13961556Srgrimes			invert = 0;
139726488Sache			if (*p == '!' || *p == '^') {
13981556Srgrimes				invert++;
13991556Srgrimes				p++;
14001556Srgrimes			}
14011556Srgrimes			found = 0;
14021556Srgrimes			chr = *q++;
140345514Stegge			if (squoted && chr == CTLESC)
140445514Stegge				chr = *q++;
140517987Speter			if (chr == '\0')
140617987Speter				return 0;
14071556Srgrimes			c = *p++;
14081556Srgrimes			do {
140938887Stegge				if (c == CTLQUOTEMARK)
141038887Stegge					continue;
14111556Srgrimes				if (c == CTLESC)
14121556Srgrimes					c = *p++;
14131556Srgrimes				if (*p == '-' && p[1] != ']') {
14141556Srgrimes					p++;
141538887Stegge					while (*p == CTLQUOTEMARK)
141638887Stegge						p++;
14171556Srgrimes					if (*p == CTLESC)
14181556Srgrimes						p++;
141917557Sache					if (   collate_range_cmp(chr, c) >= 0
142017557Sache					    && collate_range_cmp(chr, *p) <= 0
142117525Sache					   )
14221556Srgrimes						found = 1;
14231556Srgrimes					p++;
14241556Srgrimes				} else {
14251556Srgrimes					if (chr == c)
14261556Srgrimes						found = 1;
14271556Srgrimes				}
14281556Srgrimes			} while ((c = *p++) != ']');
14291556Srgrimes			if (found == invert)
14301556Srgrimes				return 0;
14311556Srgrimes			break;
14321556Srgrimes		}
14331556Srgrimesdft:	        default:
143445514Stegge			if (squoted && *q == CTLESC)
143545514Stegge				q++;
14361556Srgrimes			if (*q++ != c)
14371556Srgrimes				return 0;
14381556Srgrimes			break;
14391556Srgrimes		}
14401556Srgrimes	}
14411556Srgrimesbreakloop:
14421556Srgrimes	if (*q != '\0')
14431556Srgrimes		return 0;
14441556Srgrimes	return 1;
14451556Srgrimes}
14461556Srgrimes
14471556Srgrimes
14481556Srgrimes
14491556Srgrimes/*
14501556Srgrimes * Remove any CTLESC characters from a string.
14511556Srgrimes */
14521556Srgrimes
14531556Srgrimesvoid
145490111Simprmescapes(char *str)
145538887Stegge{
145625233Ssteve	char *p, *q;
14571556Srgrimes
14581556Srgrimes	p = str;
145938887Stegge	while (*p != CTLESC && *p != CTLQUOTEMARK) {
14601556Srgrimes		if (*p++ == '\0')
14611556Srgrimes			return;
14621556Srgrimes	}
14631556Srgrimes	q = p;
14641556Srgrimes	while (*p) {
146538887Stegge		if (*p == CTLQUOTEMARK) {
146638887Stegge			p++;
146738887Stegge			continue;
146838887Stegge		}
14691556Srgrimes		if (*p == CTLESC)
14701556Srgrimes			p++;
14711556Srgrimes		*q++ = *p++;
14721556Srgrimes	}
14731556Srgrimes	*q = '\0';
14741556Srgrimes}
14751556Srgrimes
14761556Srgrimes
14771556Srgrimes
14781556Srgrimes/*
14791556Srgrimes * See if a pattern matches in a case statement.
14801556Srgrimes */
14811556Srgrimes
14821556Srgrimesint
148390111Simpcasematch(union node *pattern, char *val)
148490111Simp{
14851556Srgrimes	struct stackmark smark;
14861556Srgrimes	int result;
14871556Srgrimes	char *p;
14881556Srgrimes
14891556Srgrimes	setstackmark(&smark);
14901556Srgrimes	argbackq = pattern->narg.backquote;
14911556Srgrimes	STARTSTACKSTR(expdest);
14921556Srgrimes	ifslastp = NULL;
14931556Srgrimes	argstr(pattern->narg.text, EXP_TILDE | EXP_CASE);
14941556Srgrimes	STPUTC('\0', expdest);
14951556Srgrimes	p = grabstackstr(expdest);
149645514Stegge	result = patmatch(p, val, 0);
14971556Srgrimes	popstackmark(&smark);
14981556Srgrimes	return result;
14991556Srgrimes}
150017987Speter
150117987Speter/*
150217987Speter * Our own itoa().
150317987Speter */
150417987Speter
150517987SpeterSTATIC char *
150690111Simpcvtnum(int num, char *buf)
150790111Simp{
150817987Speter	char temp[32];
150917987Speter	int neg = num < 0;
151017987Speter	char *p = temp + 31;
151117987Speter
151217987Speter	temp[31] = '\0';
151317987Speter
151417987Speter	do {
151517987Speter		*--p = num % 10 + '0';
151617987Speter	} while ((num /= 10) != 0);
151717987Speter
151817987Speter	if (neg)
151917987Speter		*--p = '-';
152017987Speter
152117987Speter	while (*p)
152217987Speter		STPUTC(*p++, buf);
152317987Speter	return buf;
152417987Speter}
1525108286Stjr
1526108286Stjr/*
1527108286Stjr * Do most of the work for wordexp(3).
1528108286Stjr */
1529108286Stjr
1530108286Stjrint
1531108286Stjrwordexpcmd(int argc, char **argv)
1532108286Stjr{
1533108286Stjr	size_t len;
1534108286Stjr	int i;
1535108286Stjr
1536108286Stjr	out1fmt("%08x", argc - 1);
1537108286Stjr	for (i = 1, len = 0; i < argc; i++)
1538108286Stjr		len += strlen(argv[i]);
1539108286Stjr	out1fmt("%08x", (int)len);
1540108286Stjr	for (i = 1; i < argc; i++) {
1541108286Stjr		out1str(argv[i]);
1542108286Stjr		out1c('\0');
1543108286Stjr	}
1544108286Stjr        return (0);
1545108286Stjr}
1546