expand.c revision 215783
11556Srgrimes/*-
21556Srgrimes * Copyright (c) 1991, 1993
31556Srgrimes *	The Regents of the University of California.  All rights reserved.
4207944Sjilles * Copyright (c) 1997-2005
5207944Sjilles *	Herbert Xu <herbert@gondor.apana.org.au>.  All rights reserved.
61556Srgrimes *
71556Srgrimes * This code is derived from software contributed to Berkeley by
81556Srgrimes * Kenneth Almquist.
91556Srgrimes *
101556Srgrimes * Redistribution and use in source and binary forms, with or without
111556Srgrimes * modification, are permitted provided that the following conditions
121556Srgrimes * are met:
131556Srgrimes * 1. Redistributions of source code must retain the above copyright
141556Srgrimes *    notice, this list of conditions and the following disclaimer.
151556Srgrimes * 2. Redistributions in binary form must reproduce the above copyright
161556Srgrimes *    notice, this list of conditions and the following disclaimer in the
171556Srgrimes *    documentation and/or other materials provided with the distribution.
181556Srgrimes * 4. Neither the name of the University nor the names of its contributors
191556Srgrimes *    may be used to endorse or promote products derived from this software
201556Srgrimes *    without specific prior written permission.
211556Srgrimes *
221556Srgrimes * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
231556Srgrimes * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
241556Srgrimes * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
251556Srgrimes * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
261556Srgrimes * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
271556Srgrimes * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
281556Srgrimes * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
291556Srgrimes * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
301556Srgrimes * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
311556Srgrimes * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
321556Srgrimes * SUCH DAMAGE.
331556Srgrimes */
341556Srgrimes
351556Srgrimes#ifndef lint
3636150Scharnier#if 0
3736150Scharnierstatic char sccsid[] = "@(#)expand.c	8.5 (Berkeley) 5/15/95";
3836150Scharnier#endif
391556Srgrimes#endif /* not lint */
4099110Sobrien#include <sys/cdefs.h>
4199110Sobrien__FBSDID("$FreeBSD: head/bin/sh/expand.c 215783 2010-11-23 22:17:39Z jilles $");
421556Srgrimes
4317987Speter#include <sys/types.h>
4417987Speter#include <sys/time.h>
4517987Speter#include <sys/stat.h>
46213775Sjhb#include <dirent.h>
4717987Speter#include <errno.h>
48213775Sjhb#include <inttypes.h>
49213775Sjhb#include <limits.h>
5017987Speter#include <pwd.h>
51213775Sjhb#include <stdio.h>
5217987Speter#include <stdlib.h>
53108286Stjr#include <string.h>
54213775Sjhb#include <unistd.h>
5517987Speter
561556Srgrimes/*
571556Srgrimes * Routines to expand arguments to commands.  We have to deal with
581556Srgrimes * backquotes, shell variables, and file metacharacters.
591556Srgrimes */
601556Srgrimes
611556Srgrimes#include "shell.h"
621556Srgrimes#include "main.h"
631556Srgrimes#include "nodes.h"
641556Srgrimes#include "eval.h"
651556Srgrimes#include "expand.h"
661556Srgrimes#include "syntax.h"
671556Srgrimes#include "parser.h"
681556Srgrimes#include "jobs.h"
691556Srgrimes#include "options.h"
701556Srgrimes#include "var.h"
711556Srgrimes#include "input.h"
721556Srgrimes#include "output.h"
731556Srgrimes#include "memalloc.h"
741556Srgrimes#include "error.h"
751556Srgrimes#include "mystring.h"
7617987Speter#include "arith.h"
7717987Speter#include "show.h"
781556Srgrimes
791556Srgrimes/*
801556Srgrimes * Structure specifying which parts of the string should be searched
811556Srgrimes * for IFS characters.
821556Srgrimes */
831556Srgrimes
841556Srgrimesstruct ifsregion {
851556Srgrimes	struct ifsregion *next;	/* next region in list */
861556Srgrimes	int begoff;		/* offset of start of region */
871556Srgrimes	int endoff;		/* offset of end of region */
88194975Sjilles	int inquotes;		/* search for nul bytes only */
891556Srgrimes};
901556Srgrimes
911556Srgrimes
92213760Sobrienstatic char *expdest;			/* output of current string */
93213760Sobrienstatic struct nodelist *argbackq;	/* list of back quote expressions */
94213760Sobrienstatic struct ifsregion ifsfirst;	/* first struct in list of ifs regions */
95213760Sobrienstatic struct ifsregion *ifslastp;	/* last struct in list */
96213760Sobrienstatic struct arglist exparg;		/* holds expanded arg list */
971556Srgrimes
98213811Sobrienstatic void argstr(char *, int);
99213811Sobrienstatic char *exptilde(char *, int);
100213811Sobrienstatic void expbackq(union node *, int, int);
101214524Sjillesstatic int subevalvar(char *, char *, int, int, int, int, int);
102213811Sobrienstatic char *evalvar(char *, int);
103213811Sobrienstatic int varisset(char *, int);
104213811Sobrienstatic void varvalue(char *, int, int, int);
105213811Sobrienstatic void recordregion(int, int, int);
106213811Sobrienstatic void removerecordregions(int);
107213811Sobrienstatic void ifsbreakup(char *, struct arglist *);
108213811Sobrienstatic void expandmeta(struct strlist *, int);
109213811Sobrienstatic void expmeta(char *, char *);
110213811Sobrienstatic void addfname(char *);
111213811Sobrienstatic struct strlist *expsort(struct strlist *);
112213811Sobrienstatic struct strlist *msort(struct strlist *, int);
113213811Sobrienstatic char *cvtnum(int, char *);
114213811Sobrienstatic int collate_range_cmp(int, int);
1151556Srgrimes
116213811Sobrienstatic int
117118374Sachecollate_range_cmp(int c1, int c2)
11819281Sache{
11919281Sache	static char s1[2], s2[2];
12019281Sache
12119281Sache	s1[0] = c1;
12219281Sache	s2[0] = c2;
123118374Sache	return (strcoll(s1, s2));
12419281Sache}
12519281Sache
1261556Srgrimes/*
1271556Srgrimes * Expand shell variables and backquotes inside a here document.
12890111Simp *	union node *arg		the document
12990111Simp *	int fd;			where to write the expanded version
1301556Srgrimes */
1311556Srgrimes
1321556Srgrimesvoid
13390111Simpexpandhere(union node *arg, int fd)
13490111Simp{
1351556Srgrimes	herefd = fd;
1361556Srgrimes	expandarg(arg, (struct arglist *)NULL, 0);
13739137Stegge	xwrite(fd, stackblock(), expdest - stackblock());
1381556Srgrimes}
1391556Srgrimes
1401556Srgrimes
1411556Srgrimes/*
142212243Sjilles * Perform expansions on an argument, placing the resulting list of arguments
143212243Sjilles * in arglist.  Parameter expansion, command substitution and arithmetic
144212243Sjilles * expansion are always performed; additional expansions can be requested
145212243Sjilles * via flag (EXP_*).
146212243Sjilles * The result is left in the stack string.
147212243Sjilles * When arglist is NULL, perform here document expansion.  A partial result
148212243Sjilles * may be written to herefd, which is then not included in the stack string.
149212243Sjilles *
150212243Sjilles * Caution: this function uses global state and is not reentrant.
151212243Sjilles * However, a new invocation after an interrupted invocation is safe
152212243Sjilles * and will reset the global state for the new call.
1531556Srgrimes */
1541556Srgrimesvoid
15590111Simpexpandarg(union node *arg, struct arglist *arglist, int flag)
15617987Speter{
1571556Srgrimes	struct strlist *sp;
1581556Srgrimes	char *p;
1591556Srgrimes
1601556Srgrimes	argbackq = arg->narg.backquote;
1611556Srgrimes	STARTSTACKSTR(expdest);
1621556Srgrimes	ifsfirst.next = NULL;
1631556Srgrimes	ifslastp = NULL;
1641556Srgrimes	argstr(arg->narg.text, flag);
1651556Srgrimes	if (arglist == NULL) {
1661556Srgrimes		return;			/* here document expanded */
1671556Srgrimes	}
1681556Srgrimes	STPUTC('\0', expdest);
1691556Srgrimes	p = grabstackstr(expdest);
1701556Srgrimes	exparg.lastp = &exparg.list;
1711556Srgrimes	/*
1721556Srgrimes	 * TODO - EXP_REDIR
1731556Srgrimes	 */
1741556Srgrimes	if (flag & EXP_FULL) {
1751556Srgrimes		ifsbreakup(p, &exparg);
1761556Srgrimes		*exparg.lastp = NULL;
1771556Srgrimes		exparg.lastp = &exparg.list;
1781556Srgrimes		expandmeta(exparg.list, flag);
1791556Srgrimes	} else {
1801556Srgrimes		if (flag & EXP_REDIR) /*XXX - for now, just remove escapes */
1811556Srgrimes			rmescapes(p);
1821556Srgrimes		sp = (struct strlist *)stalloc(sizeof (struct strlist));
1831556Srgrimes		sp->text = p;
1841556Srgrimes		*exparg.lastp = sp;
1851556Srgrimes		exparg.lastp = &sp->next;
1861556Srgrimes	}
1871556Srgrimes	while (ifsfirst.next != NULL) {
1881556Srgrimes		struct ifsregion *ifsp;
1891556Srgrimes		INTOFF;
1901556Srgrimes		ifsp = ifsfirst.next->next;
1911556Srgrimes		ckfree(ifsfirst.next);
1921556Srgrimes		ifsfirst.next = ifsp;
1931556Srgrimes		INTON;
1941556Srgrimes	}
1951556Srgrimes	*exparg.lastp = NULL;
1961556Srgrimes	if (exparg.list) {
1971556Srgrimes		*arglist->lastp = exparg.list;
1981556Srgrimes		arglist->lastp = exparg.lastp;
1991556Srgrimes	}
2001556Srgrimes}
2011556Srgrimes
2021556Srgrimes
2031556Srgrimes
2041556Srgrimes/*
205212243Sjilles * Perform parameter expansion, command substitution and arithmetic
206212243Sjilles * expansion, and tilde expansion if requested via EXP_TILDE/EXP_VARTILDE.
207212243Sjilles * Processing ends at a CTLENDVAR character as well as '\0'.
208212243Sjilles * This is used to expand word in ${var+word} etc.
209212243Sjilles * If EXP_FULL, EXP_CASE or EXP_REDIR are set, keep and/or generate CTLESC
210212243Sjilles * characters to allow for further processing.
211212243Sjilles * If EXP_FULL is set, also preserve CTLQUOTEMARK characters.
2121556Srgrimes */
213213811Sobrienstatic void
21490111Simpargstr(char *p, int flag)
21517987Speter{
21625233Ssteve	char c;
217104672Stjr	int quotes = flag & (EXP_FULL | EXP_CASE | EXP_REDIR);	/* do CTLESC */
2181556Srgrimes	int firsteq = 1;
219214512Sjilles	int split_lit;
220214512Sjilles	int lit_quoted;
2211556Srgrimes
222214512Sjilles	split_lit = flag & EXP_SPLIT_LIT;
223214512Sjilles	lit_quoted = flag & EXP_LIT_QUOTED;
224214512Sjilles	flag &= ~(EXP_SPLIT_LIT | EXP_LIT_QUOTED);
2251556Srgrimes	if (*p == '~' && (flag & (EXP_TILDE | EXP_VARTILDE)))
2261556Srgrimes		p = exptilde(p, flag);
2271556Srgrimes	for (;;) {
228215783Sjilles		CHECKSTRSPACE(2, expdest);
2291556Srgrimes		switch (c = *p++) {
2301556Srgrimes		case '\0':
231212243Sjilles		case CTLENDVAR:
2321556Srgrimes			goto breakloop;
23338887Stegge		case CTLQUOTEMARK:
234214512Sjilles			lit_quoted = 1;
23538887Stegge			/* "$@" syntax adherence hack */
23638887Stegge			if (p[0] == CTLVAR && p[2] == '@' && p[3] == '=')
23738887Stegge				break;
23839137Stegge			if ((flag & EXP_FULL) != 0)
239215783Sjilles				USTPUTC(c, expdest);
24038887Stegge			break;
241214512Sjilles		case CTLQUOTEEND:
242214512Sjilles			lit_quoted = 0;
243214512Sjilles			break;
2441556Srgrimes		case CTLESC:
2451556Srgrimes			if (quotes)
246215783Sjilles				USTPUTC(c, expdest);
2471556Srgrimes			c = *p++;
248215783Sjilles			USTPUTC(c, expdest);
249214512Sjilles			if (split_lit && !lit_quoted)
250214512Sjilles				recordregion(expdest - stackblock() -
251214512Sjilles				    (quotes ? 2 : 1),
252214512Sjilles				    expdest - stackblock(), 0);
2531556Srgrimes			break;
2541556Srgrimes		case CTLVAR:
2551556Srgrimes			p = evalvar(p, flag);
2561556Srgrimes			break;
2571556Srgrimes		case CTLBACKQ:
2581556Srgrimes		case CTLBACKQ|CTLQUOTE:
2591556Srgrimes			expbackq(argbackq->n, c & CTLQUOTE, flag);
2601556Srgrimes			argbackq = argbackq->next;
2611556Srgrimes			break;
2621556Srgrimes		case CTLENDARI:
2631556Srgrimes			expari(flag);
2641556Srgrimes			break;
2651556Srgrimes		case ':':
2661556Srgrimes		case '=':
2671556Srgrimes			/*
2681556Srgrimes			 * sort of a hack - expand tildes in variable
2691556Srgrimes			 * assignments (after the first '=' and after ':'s).
2701556Srgrimes			 */
271215783Sjilles			USTPUTC(c, expdest);
272214512Sjilles			if (split_lit && !lit_quoted)
273214512Sjilles				recordregion(expdest - stackblock() - 1,
274214512Sjilles				    expdest - stackblock(), 0);
275214512Sjilles			if (flag & EXP_VARTILDE && *p == '~' &&
276214512Sjilles			    (c != '=' || firsteq)) {
277214512Sjilles				if (c == '=')
278214512Sjilles					firsteq = 0;
2791556Srgrimes				p = exptilde(p, flag);
2801556Srgrimes			}
2811556Srgrimes			break;
2821556Srgrimes		default:
283215783Sjilles			USTPUTC(c, expdest);
284214512Sjilles			if (split_lit && !lit_quoted)
285214512Sjilles				recordregion(expdest - stackblock() - 1,
286214512Sjilles				    expdest - stackblock(), 0);
2871556Srgrimes		}
2881556Srgrimes	}
2891556Srgrimesbreakloop:;
2901556Srgrimes}
2911556Srgrimes
292212243Sjilles/*
293212243Sjilles * Perform tilde expansion, placing the result in the stack string and
294212243Sjilles * returning the next position in the input string to process.
295212243Sjilles */
296213811Sobrienstatic char *
29790111Simpexptilde(char *p, int flag)
29817987Speter{
2991556Srgrimes	char c, *startp = p;
3001556Srgrimes	struct passwd *pw;
3011556Srgrimes	char *home;
302108935Stjr	int quotes = flag & (EXP_FULL | EXP_CASE | EXP_REDIR);
3031556Srgrimes
30417987Speter	while ((c = *p) != '\0') {
3051556Srgrimes		switch(c) {
306200988Sjilles		case CTLESC: /* This means CTL* are always considered quoted. */
307200988Sjilles		case CTLVAR:
308200988Sjilles		case CTLBACKQ:
309200988Sjilles		case CTLBACKQ | CTLQUOTE:
310200988Sjilles		case CTLARI:
311200988Sjilles		case CTLENDARI:
31239137Stegge		case CTLQUOTEMARK:
31339137Stegge			return (startp);
3141556Srgrimes		case ':':
3151556Srgrimes			if (flag & EXP_VARTILDE)
3161556Srgrimes				goto done;
3171556Srgrimes			break;
3181556Srgrimes		case '/':
319206150Sjilles		case CTLENDVAR:
3201556Srgrimes			goto done;
3211556Srgrimes		}
3221556Srgrimes		p++;
3231556Srgrimes	}
3241556Srgrimesdone:
3251556Srgrimes	*p = '\0';
3261556Srgrimes	if (*(startp+1) == '\0') {
3271556Srgrimes		if ((home = lookupvar("HOME")) == NULL)
3281556Srgrimes			goto lose;
3291556Srgrimes	} else {
3301556Srgrimes		if ((pw = getpwnam(startp+1)) == NULL)
3311556Srgrimes			goto lose;
3321556Srgrimes		home = pw->pw_dir;
3331556Srgrimes	}
3341556Srgrimes	if (*home == '\0')
3351556Srgrimes		goto lose;
3361556Srgrimes	*p = c;
33717987Speter	while ((c = *home++) != '\0') {
33883675Stegge		if (quotes && SQSYNTAX[(int)c] == CCTL)
3391556Srgrimes			STPUTC(CTLESC, expdest);
3401556Srgrimes		STPUTC(c, expdest);
3411556Srgrimes	}
3421556Srgrimes	return (p);
3431556Srgrimeslose:
3441556Srgrimes	*p = c;
3451556Srgrimes	return (startp);
3461556Srgrimes}
3471556Srgrimes
3481556Srgrimes
349213811Sobrienstatic void
35090111Simpremoverecordregions(int endoff)
35138887Stegge{
35238887Stegge	if (ifslastp == NULL)
35338887Stegge		return;
35438887Stegge
35538887Stegge	if (ifsfirst.endoff > endoff) {
35638887Stegge		while (ifsfirst.next != NULL) {
35738887Stegge			struct ifsregion *ifsp;
35838887Stegge			INTOFF;
35938887Stegge			ifsp = ifsfirst.next->next;
36038887Stegge			ckfree(ifsfirst.next);
36138887Stegge			ifsfirst.next = ifsp;
36238887Stegge			INTON;
36338887Stegge		}
36438887Stegge		if (ifsfirst.begoff > endoff)
36538887Stegge			ifslastp = NULL;
36638887Stegge		else {
36738887Stegge			ifslastp = &ifsfirst;
36838887Stegge			ifsfirst.endoff = endoff;
36938887Stegge		}
37038887Stegge		return;
37138887Stegge	}
372155301Sschweikh
37338887Stegge	ifslastp = &ifsfirst;
37438887Stegge	while (ifslastp->next && ifslastp->next->begoff < endoff)
37538887Stegge		ifslastp=ifslastp->next;
37638887Stegge	while (ifslastp->next != NULL) {
37738887Stegge		struct ifsregion *ifsp;
37838887Stegge		INTOFF;
37938887Stegge		ifsp = ifslastp->next->next;
38038887Stegge		ckfree(ifslastp->next);
38138887Stegge		ifslastp->next = ifsp;
38238887Stegge		INTON;
38338887Stegge	}
38438887Stegge	if (ifslastp->endoff > endoff)
38538887Stegge		ifslastp->endoff = endoff;
38638887Stegge}
38738887Stegge
3881556Srgrimes/*
3891556Srgrimes * Expand arithmetic expression.  Backup to start of expression,
3901556Srgrimes * evaluate, place result in (backed up) result, adjust string position.
3911556Srgrimes */
3921556Srgrimesvoid
39390111Simpexpari(int flag)
39417987Speter{
395207206Sjilles	char *p, *q, *start;
396178631Sstefanf	arith_t result;
39738887Stegge	int begoff;
398108935Stjr	int quotes = flag & (EXP_FULL | EXP_CASE | EXP_REDIR);
39938887Stegge	int quoted;
4001556Srgrimes
4011556Srgrimes	/*
40246684Skris	 * This routine is slightly over-complicated for
4031556Srgrimes	 * efficiency.  First we make sure there is
4041556Srgrimes	 * enough space for the result, which may be bigger
405212243Sjilles	 * than the expression.  Next we
4061556Srgrimes	 * scan backwards looking for the start of arithmetic.  If the
4071556Srgrimes	 * next previous character is a CTLESC character, then we
4081556Srgrimes	 * have to rescan starting from the beginning since CTLESC
4098855Srgrimes	 * characters have to be processed left to right.
4101556Srgrimes	 */
411178631Sstefanf	CHECKSTRSPACE(DIGITS(result) - 2, expdest);
4128855Srgrimes	USTPUTC('\0', expdest);
4131556Srgrimes	start = stackblock();
41483676Stegge	p = expdest - 2;
41583676Stegge	while (p >= start && *p != CTLARI)
4161556Srgrimes		--p;
41783676Stegge	if (p < start || *p != CTLARI)
4181556Srgrimes		error("missing CTLARI (shouldn't happen)");
41983676Stegge	if (p > start && *(p - 1) == CTLESC)
4201556Srgrimes		for (p = start; *p != CTLARI; p++)
4211556Srgrimes			if (*p == CTLESC)
4221556Srgrimes				p++;
42338887Stegge
42438887Stegge	if (p[1] == '"')
42538887Stegge		quoted=1;
42638887Stegge	else
42738887Stegge		quoted=0;
42838887Stegge	begoff = p - start;
42938887Stegge	removerecordregions(begoff);
4301556Srgrimes	if (quotes)
43138887Stegge		rmescapes(p+2);
432207206Sjilles	q = grabstackstr(expdest);
43338887Stegge	result = arith(p+2);
434207206Sjilles	ungrabstackstr(q, expdest);
435178631Sstefanf	fmtstr(p, DIGITS(result), ARITH_FORMAT_STR, result);
4361556Srgrimes	while (*p++)
4371556Srgrimes		;
43838887Stegge	if (quoted == 0)
43938887Stegge		recordregion(begoff, p - 1 - start, 0);
4401556Srgrimes	result = expdest - p + 1;
4411556Srgrimes	STADJUST(-result, expdest);
4421556Srgrimes}
4431556Srgrimes
4441556Srgrimes
4451556Srgrimes/*
446212243Sjilles * Perform command substitution.
4471556Srgrimes */
448213811Sobrienstatic void
44990111Simpexpbackq(union node *cmd, int quoted, int flag)
45017987Speter{
4511556Srgrimes	struct backcmd in;
4521556Srgrimes	int i;
4531556Srgrimes	char buf[128];
4541556Srgrimes	char *p;
4551556Srgrimes	char *dest = expdest;
4561556Srgrimes	struct ifsregion saveifs, *savelastp;
4571556Srgrimes	struct nodelist *saveargbackq;
4581556Srgrimes	char lastc;
4591556Srgrimes	int startloc = dest - stackblock();
4601556Srgrimes	char const *syntax = quoted? DQSYNTAX : BASESYNTAX;
4611556Srgrimes	int saveherefd;
462108935Stjr	int quotes = flag & (EXP_FULL | EXP_CASE | EXP_REDIR);
463115424Sfenner	int nnl;
4641556Srgrimes
4651556Srgrimes	INTOFF;
4661556Srgrimes	saveifs = ifsfirst;
4671556Srgrimes	savelastp = ifslastp;
4681556Srgrimes	saveargbackq = argbackq;
4698855Srgrimes	saveherefd = herefd;
4701556Srgrimes	herefd = -1;
4711556Srgrimes	p = grabstackstr(dest);
4721556Srgrimes	evalbackcmd(cmd, &in);
4731556Srgrimes	ungrabstackstr(p, dest);
4741556Srgrimes	ifsfirst = saveifs;
4751556Srgrimes	ifslastp = savelastp;
4761556Srgrimes	argbackq = saveargbackq;
4771556Srgrimes	herefd = saveherefd;
4781556Srgrimes
4791556Srgrimes	p = in.buf;
4801556Srgrimes	lastc = '\0';
481115424Sfenner	nnl = 0;
482115424Sfenner	/* Don't copy trailing newlines */
4831556Srgrimes	for (;;) {
4841556Srgrimes		if (--in.nleft < 0) {
4851556Srgrimes			if (in.fd < 0)
4861556Srgrimes				break;
4871556Srgrimes			while ((i = read(in.fd, buf, sizeof buf)) < 0 && errno == EINTR);
4881556Srgrimes			TRACE(("expbackq: read returns %d\n", i));
4891556Srgrimes			if (i <= 0)
4901556Srgrimes				break;
4911556Srgrimes			p = buf;
4921556Srgrimes			in.nleft = i - 1;
4931556Srgrimes		}
4941556Srgrimes		lastc = *p++;
4951556Srgrimes		if (lastc != '\0') {
49683675Stegge			if (quotes && syntax[(int)lastc] == CCTL)
4971556Srgrimes				STPUTC(CTLESC, dest);
498115424Sfenner			if (lastc == '\n') {
499115424Sfenner				nnl++;
500115424Sfenner			} else {
501115424Sfenner				while (nnl > 0) {
502115424Sfenner					nnl--;
503115424Sfenner					STPUTC('\n', dest);
504115424Sfenner				}
505115424Sfenner				STPUTC(lastc, dest);
506115424Sfenner			}
5071556Srgrimes		}
5081556Srgrimes	}
50917987Speter
5101556Srgrimes	if (in.fd >= 0)
5111556Srgrimes		close(in.fd);
5121556Srgrimes	if (in.buf)
5131556Srgrimes		ckfree(in.buf);
5141556Srgrimes	if (in.jp)
51545916Scracauer		exitstatus = waitforjob(in.jp, (int *)NULL);
5161556Srgrimes	if (quoted == 0)
5171556Srgrimes		recordregion(startloc, dest - stackblock(), 0);
518213775Sjhb	TRACE(("expbackq: size=%td: \"%.*s\"\n",
519213775Sjhb		((dest - stackblock()) - startloc),
520213775Sjhb		(int)((dest - stackblock()) - startloc),
5211556Srgrimes		stackblock() + startloc));
5221556Srgrimes	expdest = dest;
5231556Srgrimes	INTON;
5241556Srgrimes}
5251556Srgrimes
5261556Srgrimes
5271556Srgrimes
528213811Sobrienstatic int
52990111Simpsubevalvar(char *p, char *str, int strloc, int subtype, int startloc,
530214524Sjilles  int varflags, int quotes)
53117987Speter{
53217987Speter	char *startp;
53317987Speter	char *loc = NULL;
53445514Stegge	char *q;
53517987Speter	int c = 0;
53617987Speter	int saveherefd = herefd;
53717987Speter	struct nodelist *saveargbackq = argbackq;
53820425Ssteve	int amount;
53920425Ssteve
54017987Speter	herefd = -1;
541206150Sjilles	argstr(p, (subtype == VSTRIMLEFT || subtype == VSTRIMLEFTMAX ||
542206147Sjilles	    subtype == VSTRIMRIGHT || subtype == VSTRIMRIGHTMAX ?
543206150Sjilles	    EXP_CASE : 0) | EXP_TILDE);
54417987Speter	STACKSTRNUL(expdest);
54517987Speter	herefd = saveherefd;
54617987Speter	argbackq = saveargbackq;
54717987Speter	startp = stackblock() + startloc;
54820425Ssteve	if (str == NULL)
54920425Ssteve	    str = stackblock() + strloc;
55017987Speter
55117987Speter	switch (subtype) {
55217987Speter	case VSASSIGN:
55317987Speter		setvar(str, startp, 0);
55420425Ssteve		amount = startp - expdest;
55520425Ssteve		STADJUST(amount, expdest);
55617987Speter		varflags &= ~VSNUL;
55717987Speter		if (c != 0)
55817987Speter			*loc = c;
55917987Speter		return 1;
56017987Speter
56117987Speter	case VSQUESTION:
56217987Speter		if (*p != CTLENDVAR) {
563201366Sjilles			outfmt(out2, "%s\n", startp);
56417987Speter			error((char *)NULL);
56517987Speter		}
566112254Sru		error("%.*s: parameter %snot set", (int)(p - str - 1),
56717987Speter		      str, (varflags & VSNUL) ? "null or "
56817987Speter					      : nullstr);
56917987Speter		return 0;
57017987Speter
57117987Speter	case VSTRIMLEFT:
57225233Ssteve		for (loc = startp; loc < str; loc++) {
57317987Speter			c = *loc;
57417987Speter			*loc = '\0';
575214524Sjilles			if (patmatch(str, startp, quotes)) {
57617987Speter				*loc = c;
57717987Speter				goto recordleft;
57817987Speter			}
57917987Speter			*loc = c;
580214524Sjilles			if (quotes && *loc == CTLESC)
58145514Stegge				loc++;
58217987Speter		}
58317987Speter		return 0;
58417987Speter
58517987Speter	case VSTRIMLEFTMAX:
58645514Stegge		for (loc = str - 1; loc >= startp;) {
58717987Speter			c = *loc;
58817987Speter			*loc = '\0';
589214524Sjilles			if (patmatch(str, startp, quotes)) {
59017987Speter				*loc = c;
59117987Speter				goto recordleft;
59217987Speter			}
59317987Speter			*loc = c;
59445514Stegge			loc--;
595214524Sjilles			if (quotes && loc > startp && *(loc - 1) == CTLESC) {
59645514Stegge				for (q = startp; q < loc; q++)
59745514Stegge					if (*q == CTLESC)
59845514Stegge						q++;
59945514Stegge				if (q > loc)
60045514Stegge					loc--;
60145514Stegge			}
60217987Speter		}
60317987Speter		return 0;
60417987Speter
60517987Speter	case VSTRIMRIGHT:
60645514Stegge		for (loc = str - 1; loc >= startp;) {
607214524Sjilles			if (patmatch(str, loc, quotes)) {
60820425Ssteve				amount = loc - expdest;
60920425Ssteve				STADJUST(amount, expdest);
61017987Speter				return 1;
61117987Speter			}
61245514Stegge			loc--;
613214524Sjilles			if (quotes && loc > startp && *(loc - 1) == CTLESC) {
61445514Stegge				for (q = startp; q < loc; q++)
61545514Stegge					if (*q == CTLESC)
61645514Stegge						q++;
61745514Stegge				if (q > loc)
61845514Stegge					loc--;
61945514Stegge			}
62017987Speter		}
62117987Speter		return 0;
62217987Speter
62317987Speter	case VSTRIMRIGHTMAX:
62417987Speter		for (loc = startp; loc < str - 1; loc++) {
625214524Sjilles			if (patmatch(str, loc, quotes)) {
62620425Ssteve				amount = loc - expdest;
62720425Ssteve				STADJUST(amount, expdest);
62817987Speter				return 1;
62917987Speter			}
630214524Sjilles			if (quotes && *loc == CTLESC)
63145514Stegge				loc++;
63217987Speter		}
63317987Speter		return 0;
63417987Speter
63517987Speter
63617987Speter	default:
63717987Speter		abort();
63817987Speter	}
63917987Speter
64017987Speterrecordleft:
64120425Ssteve	amount = ((str - 1) - (loc - startp)) - expdest;
64220425Ssteve	STADJUST(amount, expdest);
64317987Speter	while (loc != str - 1)
64417987Speter		*startp++ = *loc++;
64517987Speter	return 1;
64617987Speter}
64717987Speter
64817987Speter
6491556Srgrimes/*
6501556Srgrimes * Expand a variable, and return a pointer to the next character in the
6511556Srgrimes * input string.
6521556Srgrimes */
6531556Srgrimes
654213811Sobrienstatic char *
65590111Simpevalvar(char *p, int flag)
65617987Speter{
6571556Srgrimes	int subtype;
6581556Srgrimes	int varflags;
6591556Srgrimes	char *var;
6601556Srgrimes	char *val;
66145644Stegge	int patloc;
6621556Srgrimes	int c;
6631556Srgrimes	int set;
6641556Srgrimes	int special;
6651556Srgrimes	int startloc;
66617987Speter	int varlen;
66717987Speter	int easy;
668108935Stjr	int quotes = flag & (EXP_FULL | EXP_CASE | EXP_REDIR);
6691556Srgrimes
670164081Sstefanf	varflags = (unsigned char)*p++;
6711556Srgrimes	subtype = varflags & VSTYPE;
6721556Srgrimes	var = p;
6731556Srgrimes	special = 0;
6741556Srgrimes	if (! is_name(*p))
6751556Srgrimes		special = 1;
6761556Srgrimes	p = strchr(p, '=') + 1;
6771556Srgrimesagain: /* jump here after setting a variable with ${var=text} */
678179022Sstefanf	if (varflags & VSLINENO) {
679179022Sstefanf		set = 1;
680179022Sstefanf		special = 0;
681179022Sstefanf		val = var;
682179022Sstefanf		p[-1] = '\0';	/* temporarily overwrite '=' to have \0
683179022Sstefanf				   terminated string */
684179022Sstefanf	} else if (special) {
68525233Ssteve		set = varisset(var, varflags & VSNUL);
6861556Srgrimes		val = NULL;
6871556Srgrimes	} else {
68860592Scracauer		val = bltinlookup(var, 1);
68917987Speter		if (val == NULL || ((varflags & VSNUL) && val[0] == '\0')) {
6901556Srgrimes			val = NULL;
6911556Srgrimes			set = 0;
6921556Srgrimes		} else
6931556Srgrimes			set = 1;
6941556Srgrimes	}
69517987Speter	varlen = 0;
6961556Srgrimes	startloc = expdest - stackblock();
697198454Sjilles	if (!set && uflag && *var != '@' && *var != '*') {
69896939Stjr		switch (subtype) {
69996939Stjr		case VSNORMAL:
70096939Stjr		case VSTRIMLEFT:
70196939Stjr		case VSTRIMLEFTMAX:
70296939Stjr		case VSTRIMRIGHT:
70396939Stjr		case VSTRIMRIGHTMAX:
70496939Stjr		case VSLENGTH:
705112254Sru			error("%.*s: parameter not set", (int)(p - var - 1),
706112254Sru			    var);
70796939Stjr		}
70896939Stjr	}
7091556Srgrimes	if (set && subtype != VSPLUS) {
7101556Srgrimes		/* insert the value of the variable */
7111556Srgrimes		if (special) {
712164081Sstefanf			varvalue(var, varflags & VSQUOTE, subtype, flag);
71317987Speter			if (subtype == VSLENGTH) {
71425233Ssteve				varlen = expdest - stackblock() - startloc;
71525233Ssteve				STADJUST(-varlen, expdest);
71617987Speter			}
7171556Srgrimes		} else {
71820425Ssteve			char const *syntax = (varflags & VSQUOTE) ? DQSYNTAX
71917987Speter								  : BASESYNTAX;
7201556Srgrimes
72117987Speter			if (subtype == VSLENGTH) {
72217987Speter				for (;*val; val++)
72317987Speter					varlen++;
7241556Srgrimes			}
72517987Speter			else {
72617987Speter				while (*val) {
72783675Stegge					if (quotes &&
72854132Scracauer					    syntax[(int)*val] == CCTL)
72917987Speter						STPUTC(CTLESC, expdest);
73017987Speter					STPUTC(*val++, expdest);
73117987Speter				}
73217987Speter
73317987Speter			}
7341556Srgrimes		}
7351556Srgrimes	}
73620425Ssteve
7371556Srgrimes	if (subtype == VSPLUS)
7381556Srgrimes		set = ! set;
73917987Speter
74020425Ssteve	easy = ((varflags & VSQUOTE) == 0 ||
74117987Speter		(*var == '@' && shellparam.nparam != 1));
74217987Speter
74317987Speter
74417987Speter	switch (subtype) {
74517987Speter	case VSLENGTH:
74617987Speter		expdest = cvtnum(varlen, expdest);
74717987Speter		goto record;
74817987Speter
74917987Speter	case VSNORMAL:
75017987Speter		if (!easy)
75117987Speter			break;
75217987Speterrecord:
75320425Ssteve		recordregion(startloc, expdest - stackblock(),
75417987Speter			     varflags & VSQUOTE);
75517987Speter		break;
75617987Speter
75717987Speter	case VSPLUS:
75817987Speter	case VSMINUS:
75917987Speter		if (!set) {
760214512Sjilles			argstr(p, flag | (flag & EXP_FULL ? EXP_SPLIT_LIT : 0) |
761214512Sjilles			    (varflags & VSQUOTE ? EXP_LIT_QUOTED : 0));
76217987Speter			break;
76317987Speter		}
76417987Speter		if (easy)
76517987Speter			goto record;
76617987Speter		break;
76717987Speter
76817987Speter	case VSTRIMLEFT:
76917987Speter	case VSTRIMLEFTMAX:
77017987Speter	case VSTRIMRIGHT:
77117987Speter	case VSTRIMRIGHTMAX:
77217987Speter		if (!set)
77317987Speter			break;
77417987Speter		/*
77517987Speter		 * Terminate the string and start recording the pattern
77617987Speter		 * right after it
77717987Speter		 */
77817987Speter		STPUTC('\0', expdest);
77945644Stegge		patloc = expdest - stackblock();
78045644Stegge		if (subevalvar(p, NULL, patloc, subtype,
781214524Sjilles		    startloc, varflags, quotes) == 0) {
78245644Stegge			int amount = (expdest - stackblock() - patloc) + 1;
78325233Ssteve			STADJUST(-amount, expdest);
78425233Ssteve		}
78538887Stegge		/* Remove any recorded regions beyond start of variable */
78638887Stegge		removerecordregions(startloc);
78738887Stegge		goto record;
78817987Speter
78917987Speter	case VSASSIGN:
79017987Speter	case VSQUESTION:
79117987Speter		if (!set) {
792214524Sjilles			if (subevalvar(p, var, 0, subtype, startloc, varflags,
793214524Sjilles			    quotes)) {
79420425Ssteve				varflags &= ~VSNUL;
795155301Sschweikh				/*
796155301Sschweikh				 * Remove any recorded regions beyond
797155301Sschweikh				 * start of variable
79838887Stegge				 */
79938887Stegge				removerecordregions(startloc);
8001556Srgrimes				goto again;
80120425Ssteve			}
80217987Speter			break;
8031556Srgrimes		}
80417987Speter		if (easy)
80517987Speter			goto record;
80617987Speter		break;
80717987Speter
808164003Sstefanf	case VSERROR:
809164003Sstefanf		c = p - var - 1;
810164003Sstefanf		error("${%.*s%s}: Bad substitution", c, var,
811164003Sstefanf		    (c > 0 && *p != CTLENDVAR) ? "..." : "");
812164003Sstefanf
81317987Speter	default:
81417987Speter		abort();
8151556Srgrimes	}
816179022Sstefanf	p[-1] = '=';	/* recover overwritten '=' */
81717987Speter
8181556Srgrimes	if (subtype != VSNORMAL) {	/* skip to end of alternative */
8191556Srgrimes		int nesting = 1;
8201556Srgrimes		for (;;) {
8211556Srgrimes			if ((c = *p++) == CTLESC)
8221556Srgrimes				p++;
8231556Srgrimes			else if (c == CTLBACKQ || c == (CTLBACKQ|CTLQUOTE)) {
8241556Srgrimes				if (set)
8251556Srgrimes					argbackq = argbackq->next;
8261556Srgrimes			} else if (c == CTLVAR) {
8271556Srgrimes				if ((*p++ & VSTYPE) != VSNORMAL)
8281556Srgrimes					nesting++;
8291556Srgrimes			} else if (c == CTLENDVAR) {
8301556Srgrimes				if (--nesting == 0)
8311556Srgrimes					break;
8321556Srgrimes			}
8331556Srgrimes		}
8341556Srgrimes	}
8351556Srgrimes	return p;
8361556Srgrimes}
8371556Srgrimes
8381556Srgrimes
8391556Srgrimes
8401556Srgrimes/*
8411556Srgrimes * Test whether a specialized variable is set.
8421556Srgrimes */
8431556Srgrimes
844213811Sobrienstatic int
84590111Simpvarisset(char *name, int nulok)
84625233Ssteve{
8471556Srgrimes
84825233Ssteve	if (*name == '!')
849209600Sjilles		return backgndpidset();
85025233Ssteve	else if (*name == '@' || *name == '*') {
8511556Srgrimes		if (*shellparam.p == NULL)
8521556Srgrimes			return 0;
85325233Ssteve
85425233Ssteve		if (nulok) {
85525233Ssteve			char **av;
85625233Ssteve
85725233Ssteve			for (av = shellparam.p; *av; av++)
85825233Ssteve				if (**av != '\0')
85925233Ssteve					return 1;
86025233Ssteve			return 0;
86125233Ssteve		}
86218202Speter	} else if (is_digit(*name)) {
86325233Ssteve		char *ap;
86420425Ssteve		int num = atoi(name);
86525233Ssteve
86625233Ssteve		if (num > shellparam.nparam)
86725233Ssteve			return 0;
86825233Ssteve
86925233Ssteve		if (num == 0)
87025233Ssteve			ap = arg0;
87125233Ssteve		else
87225233Ssteve			ap = shellparam.p[num - 1];
87325233Ssteve
87425233Ssteve		if (nulok && (ap == NULL || *ap == '\0'))
87525233Ssteve			return 0;
8761556Srgrimes	}
8771556Srgrimes	return 1;
8781556Srgrimes}
8791556Srgrimes
8801556Srgrimes
8811556Srgrimes
8821556Srgrimes/*
8831556Srgrimes * Add the value of a specialized variable to the stack string.
8841556Srgrimes */
8851556Srgrimes
886213811Sobrienstatic void
887164081Sstefanfvarvalue(char *name, int quoted, int subtype, int flag)
88817987Speter{
8891556Srgrimes	int num;
8901556Srgrimes	char *p;
8911556Srgrimes	int i;
8921556Srgrimes	char sep;
8931556Srgrimes	char **ap;
8941556Srgrimes	char const *syntax;
8951556Srgrimes
8961556Srgrimes#define STRTODEST(p) \
8971556Srgrimes	do {\
898164081Sstefanf	if (flag & (EXP_FULL | EXP_CASE) && subtype != VSLENGTH) { \
8991556Srgrimes		syntax = quoted? DQSYNTAX : BASESYNTAX; \
9001556Srgrimes		while (*p) { \
90183675Stegge			if (syntax[(int)*p] == CCTL) \
9021556Srgrimes				STPUTC(CTLESC, expdest); \
9031556Srgrimes			STPUTC(*p++, expdest); \
9041556Srgrimes		} \
9051556Srgrimes	} else \
906215783Sjilles		STPUTS(p, expdest); \
9071556Srgrimes	} while (0)
9081556Srgrimes
9091556Srgrimes
91018202Speter	switch (*name) {
9111556Srgrimes	case '$':
9121556Srgrimes		num = rootpid;
9131556Srgrimes		goto numvar;
9141556Srgrimes	case '?':
91517987Speter		num = oexitstatus;
9161556Srgrimes		goto numvar;
9171556Srgrimes	case '#':
9181556Srgrimes		num = shellparam.nparam;
9191556Srgrimes		goto numvar;
9201556Srgrimes	case '!':
921209600Sjilles		num = backgndpidval();
9221556Srgrimesnumvar:
92317987Speter		expdest = cvtnum(num, expdest);
9241556Srgrimes		break;
9251556Srgrimes	case '-':
9261556Srgrimes		for (i = 0 ; i < NOPTS ; i++) {
9271556Srgrimes			if (optlist[i].val)
9281556Srgrimes				STPUTC(optlist[i].letter, expdest);
9291556Srgrimes		}
9301556Srgrimes		break;
9311556Srgrimes	case '@':
932164081Sstefanf		if (flag & EXP_FULL && quoted) {
93338887Stegge			for (ap = shellparam.p ; (p = *ap++) != NULL ; ) {
93438887Stegge				STRTODEST(p);
93538887Stegge				if (*ap)
93638887Stegge					STPUTC('\0', expdest);
93738887Stegge			}
93838887Stegge			break;
9391556Srgrimes		}
940102410Scharnier		/* FALLTHROUGH */
9411556Srgrimes	case '*':
942149825Srse		if (ifsset())
94338887Stegge			sep = ifsval()[0];
94438887Stegge		else
94538887Stegge			sep = ' ';
9461556Srgrimes		for (ap = shellparam.p ; (p = *ap++) != NULL ; ) {
9471556Srgrimes			STRTODEST(p);
94838887Stegge			if (*ap && sep)
9491556Srgrimes				STPUTC(sep, expdest);
9501556Srgrimes		}
9511556Srgrimes		break;
9521556Srgrimes	case '0':
9531556Srgrimes		p = arg0;
9541556Srgrimes		STRTODEST(p);
9551556Srgrimes		break;
9561556Srgrimes	default:
95718202Speter		if (is_digit(*name)) {
95818202Speter			num = atoi(name);
95918202Speter			if (num > 0 && num <= shellparam.nparam) {
96018202Speter				p = shellparam.p[num - 1];
96118202Speter				STRTODEST(p);
96218202Speter			}
9631556Srgrimes		}
9641556Srgrimes		break;
9651556Srgrimes	}
9661556Srgrimes}
9671556Srgrimes
9681556Srgrimes
9691556Srgrimes
9701556Srgrimes/*
9711556Srgrimes * Record the the fact that we have to scan this region of the
9721556Srgrimes * string for IFS characters.
9731556Srgrimes */
9741556Srgrimes
975213811Sobrienstatic void
976194975Sjillesrecordregion(int start, int end, int inquotes)
97717987Speter{
97825233Ssteve	struct ifsregion *ifsp;
9791556Srgrimes
9801556Srgrimes	if (ifslastp == NULL) {
9811556Srgrimes		ifsp = &ifsfirst;
9821556Srgrimes	} else {
983194975Sjilles		if (ifslastp->endoff == start
984194975Sjilles		    && ifslastp->inquotes == inquotes) {
985194975Sjilles			/* extend previous area */
986194975Sjilles			ifslastp->endoff = end;
987194975Sjilles			return;
988194975Sjilles		}
9891556Srgrimes		ifsp = (struct ifsregion *)ckmalloc(sizeof (struct ifsregion));
9901556Srgrimes		ifslastp->next = ifsp;
9911556Srgrimes	}
9921556Srgrimes	ifslastp = ifsp;
9931556Srgrimes	ifslastp->next = NULL;
9941556Srgrimes	ifslastp->begoff = start;
9951556Srgrimes	ifslastp->endoff = end;
996194975Sjilles	ifslastp->inquotes = inquotes;
9971556Srgrimes}
9981556Srgrimes
9991556Srgrimes
10001556Srgrimes
10011556Srgrimes/*
10021556Srgrimes * Break the argument string into pieces based upon IFS and add the
10031556Srgrimes * strings to the argument list.  The regions of the string to be
10041556Srgrimes * searched for IFS characters have been stored by recordregion.
1005212243Sjilles * CTLESC characters are preserved but have little effect in this pass
1006212243Sjilles * other than escaping CTL* characters.  In particular, they do not escape
1007212243Sjilles * IFS characters: that should be done with the ifsregion mechanism.
1008212243Sjilles * CTLQUOTEMARK characters are used to preserve empty quoted strings.
1009212243Sjilles * This pass treats them as a regular character, making the string non-empty.
1010212243Sjilles * Later, they are removed along with the other CTL* characters.
10111556Srgrimes */
1012213811Sobrienstatic void
101390111Simpifsbreakup(char *string, struct arglist *arglist)
101490111Simp{
10151556Srgrimes	struct ifsregion *ifsp;
10161556Srgrimes	struct strlist *sp;
10171556Srgrimes	char *start;
101825233Ssteve	char *p;
10191556Srgrimes	char *q;
1020201053Sjilles	const char *ifs;
1021194975Sjilles	const char *ifsspc;
1022194975Sjilles	int had_param_ch = 0;
10231556Srgrimes
1024194975Sjilles	start = string;
102517987Speter
1026194975Sjilles	if (ifslastp == NULL) {
1027194975Sjilles		/* Return entire argument, IFS doesn't apply to any of it */
1028194975Sjilles		sp = (struct strlist *)stalloc(sizeof *sp);
1029194975Sjilles		sp->text = start;
1030194975Sjilles		*arglist->lastp = sp;
1031194975Sjilles		arglist->lastp = &sp->next;
1032194975Sjilles		return;
1033194975Sjilles	}
1034194975Sjilles
1035194975Sjilles	ifs = ifsset() ? ifsval() : " \t\n";
1036194975Sjilles
1037194975Sjilles	for (ifsp = &ifsfirst; ifsp != NULL; ifsp = ifsp->next) {
1038194975Sjilles		p = string + ifsp->begoff;
1039194975Sjilles		while (p < string + ifsp->endoff) {
1040194975Sjilles			q = p;
1041194975Sjilles			if (*p == CTLESC)
1042194975Sjilles				p++;
1043194975Sjilles			if (ifsp->inquotes) {
1044194975Sjilles				/* Only NULs (should be from "$@") end args */
1045194977Sjilles				had_param_ch = 1;
1046194975Sjilles				if (*p != 0) {
10471556Srgrimes					p++;
1048194975Sjilles					continue;
1049194975Sjilles				}
1050194975Sjilles				ifsspc = NULL;
1051194975Sjilles			} else {
1052194975Sjilles				if (!strchr(ifs, *p)) {
1053194977Sjilles					had_param_ch = 1;
105438887Stegge					p++;
1055194975Sjilles					continue;
1056194975Sjilles				}
1057194975Sjilles				ifsspc = strchr(" \t\n", *p);
1058194975Sjilles
1059194975Sjilles				/* Ignore IFS whitespace at start */
1060194975Sjilles				if (q == start && ifsspc != NULL) {
1061194975Sjilles					p++;
10621556Srgrimes					start = p;
1063194975Sjilles					continue;
1064194975Sjilles				}
1065194977Sjilles				had_param_ch = 0;
10661556Srgrimes			}
1067194975Sjilles
1068194975Sjilles			/* Save this argument... */
1069194975Sjilles			*q = '\0';
10701556Srgrimes			sp = (struct strlist *)stalloc(sizeof *sp);
10711556Srgrimes			sp->text = start;
10721556Srgrimes			*arglist->lastp = sp;
10731556Srgrimes			arglist->lastp = &sp->next;
1074194975Sjilles			p++;
1075194975Sjilles
1076194975Sjilles			if (ifsspc != NULL) {
1077194975Sjilles				/* Ignore further trailing IFS whitespace */
1078194975Sjilles				for (; p < string + ifsp->endoff; p++) {
1079194975Sjilles					q = p;
1080194975Sjilles					if (*p == CTLESC)
1081194975Sjilles						p++;
1082194975Sjilles					if (strchr(ifs, *p) == NULL) {
1083194975Sjilles						p = q;
1084194975Sjilles						break;
1085194975Sjilles					}
1086194975Sjilles					if (strchr(" \t\n", *p) == NULL) {
1087194975Sjilles						p++;
1088194975Sjilles						break;
1089194975Sjilles					}
1090194975Sjilles				}
1091194975Sjilles			}
1092194975Sjilles			start = p;
10931556Srgrimes		}
1094194975Sjilles	}
1095194975Sjilles
1096194975Sjilles	/*
1097194975Sjilles	 * Save anything left as an argument.
1098194975Sjilles	 * Traditionally we have treated 'IFS=':'; set -- x$IFS' as
1099194975Sjilles	 * generating 2 arguments, the second of which is empty.
1100194975Sjilles	 * Some recent clarification of the Posix spec say that it
1101194975Sjilles	 * should only generate one....
1102194975Sjilles	 */
1103194975Sjilles	if (had_param_ch || *start != 0) {
11041556Srgrimes		sp = (struct strlist *)stalloc(sizeof *sp);
11051556Srgrimes		sp->text = start;
11061556Srgrimes		*arglist->lastp = sp;
11071556Srgrimes		arglist->lastp = &sp->next;
11081556Srgrimes	}
11091556Srgrimes}
11101556Srgrimes
11111556Srgrimes
1112213760Sobrienstatic char expdir[PATH_MAX];
1113212243Sjilles#define expdir_end (expdir + sizeof(expdir))
11141556Srgrimes
11151556Srgrimes/*
1116212243Sjilles * Perform pathname generation and remove control characters.
1117212243Sjilles * At this point, the only control characters should be CTLESC and CTLQUOTEMARK.
1118212243Sjilles * The results are stored in the list exparg.
11191556Srgrimes */
1120213811Sobrienstatic void
112190111Simpexpandmeta(struct strlist *str, int flag __unused)
112217987Speter{
11231556Srgrimes	char *p;
11241556Srgrimes	struct strlist **savelastp;
11251556Srgrimes	struct strlist *sp;
11261556Srgrimes	char c;
11271556Srgrimes	/* TODO - EXP_REDIR */
11281556Srgrimes
11291556Srgrimes	while (str) {
11301556Srgrimes		if (fflag)
11311556Srgrimes			goto nometa;
11321556Srgrimes		p = str->text;
11331556Srgrimes		for (;;) {			/* fast check for meta chars */
11341556Srgrimes			if ((c = *p++) == '\0')
11351556Srgrimes				goto nometa;
1136211646Sjilles			if (c == '*' || c == '?' || c == '[')
11371556Srgrimes				break;
11381556Srgrimes		}
11391556Srgrimes		savelastp = exparg.lastp;
11401556Srgrimes		INTOFF;
11411556Srgrimes		expmeta(expdir, str->text);
11421556Srgrimes		INTON;
11431556Srgrimes		if (exparg.lastp == savelastp) {
11448855Srgrimes			/*
11458855Srgrimes			 * no matches
11461556Srgrimes			 */
11471556Srgrimesnometa:
11481556Srgrimes			*exparg.lastp = str;
11491556Srgrimes			rmescapes(str->text);
11501556Srgrimes			exparg.lastp = &str->next;
11511556Srgrimes		} else {
11521556Srgrimes			*exparg.lastp = NULL;
11531556Srgrimes			*savelastp = sp = expsort(*savelastp);
11541556Srgrimes			while (sp->next != NULL)
11551556Srgrimes				sp = sp->next;
11561556Srgrimes			exparg.lastp = &sp->next;
11571556Srgrimes		}
11581556Srgrimes		str = str->next;
11591556Srgrimes	}
11601556Srgrimes}
11611556Srgrimes
11621556Srgrimes
11631556Srgrimes/*
11641556Srgrimes * Do metacharacter (i.e. *, ?, [...]) expansion.
11651556Srgrimes */
11661556Srgrimes
1167213811Sobrienstatic void
116890111Simpexpmeta(char *enddir, char *name)
116990111Simp{
117025233Ssteve	char *p;
11711556Srgrimes	char *q;
11721556Srgrimes	char *start;
11731556Srgrimes	char *endname;
11741556Srgrimes	int metaflag;
11751556Srgrimes	struct stat statb;
11761556Srgrimes	DIR *dirp;
11771556Srgrimes	struct dirent *dp;
11781556Srgrimes	int atend;
11791556Srgrimes	int matchdot;
1180207944Sjilles	int esc;
11811556Srgrimes
11821556Srgrimes	metaflag = 0;
11831556Srgrimes	start = name;
1184207944Sjilles	for (p = name; esc = 0, *p; p += esc + 1) {
11851556Srgrimes		if (*p == '*' || *p == '?')
11861556Srgrimes			metaflag = 1;
11871556Srgrimes		else if (*p == '[') {
11881556Srgrimes			q = p + 1;
118926488Sache			if (*q == '!' || *q == '^')
11901556Srgrimes				q++;
11911556Srgrimes			for (;;) {
119238887Stegge				while (*q == CTLQUOTEMARK)
119338887Stegge					q++;
11941556Srgrimes				if (*q == CTLESC)
11951556Srgrimes					q++;
11961556Srgrimes				if (*q == '/' || *q == '\0')
11971556Srgrimes					break;
11981556Srgrimes				if (*++q == ']') {
11991556Srgrimes					metaflag = 1;
12001556Srgrimes					break;
12011556Srgrimes				}
12021556Srgrimes			}
12031556Srgrimes		} else if (*p == '\0')
12041556Srgrimes			break;
120538887Stegge		else if (*p == CTLQUOTEMARK)
120638887Stegge			continue;
1207207944Sjilles		else {
1208207944Sjilles			if (*p == CTLESC)
1209207944Sjilles				esc++;
1210207944Sjilles			if (p[esc] == '/') {
1211207944Sjilles				if (metaflag)
1212207944Sjilles					break;
1213207944Sjilles				start = p + esc + 1;
1214207944Sjilles			}
12151556Srgrimes		}
12161556Srgrimes	}
12171556Srgrimes	if (metaflag == 0) {	/* we've reached the end of the file name */
12181556Srgrimes		if (enddir != expdir)
12191556Srgrimes			metaflag++;
12201556Srgrimes		for (p = name ; ; p++) {
122138887Stegge			if (*p == CTLQUOTEMARK)
122238887Stegge				continue;
12231556Srgrimes			if (*p == CTLESC)
12241556Srgrimes				p++;
12251556Srgrimes			*enddir++ = *p;
12261556Srgrimes			if (*p == '\0')
12271556Srgrimes				break;
1228211155Sjilles			if (enddir == expdir_end)
1229211155Sjilles				return;
12301556Srgrimes		}
1231147812Sdelphij		if (metaflag == 0 || lstat(expdir, &statb) >= 0)
12321556Srgrimes			addfname(expdir);
12331556Srgrimes		return;
12341556Srgrimes	}
12351556Srgrimes	endname = p;
12361556Srgrimes	if (start != name) {
12371556Srgrimes		p = name;
12381556Srgrimes		while (p < start) {
123938887Stegge			while (*p == CTLQUOTEMARK)
124038887Stegge				p++;
12411556Srgrimes			if (*p == CTLESC)
12421556Srgrimes				p++;
12431556Srgrimes			*enddir++ = *p++;
1244211155Sjilles			if (enddir == expdir_end)
1245211155Sjilles				return;
12461556Srgrimes		}
12471556Srgrimes	}
12481556Srgrimes	if (enddir == expdir) {
12491556Srgrimes		p = ".";
12501556Srgrimes	} else if (enddir == expdir + 1 && *expdir == '/') {
12511556Srgrimes		p = "/";
12521556Srgrimes	} else {
12531556Srgrimes		p = expdir;
12541556Srgrimes		enddir[-1] = '\0';
12551556Srgrimes	}
12561556Srgrimes	if ((dirp = opendir(p)) == NULL)
12571556Srgrimes		return;
12581556Srgrimes	if (enddir != expdir)
12591556Srgrimes		enddir[-1] = '/';
12601556Srgrimes	if (*endname == 0) {
12611556Srgrimes		atend = 1;
12621556Srgrimes	} else {
12631556Srgrimes		atend = 0;
1264207944Sjilles		*endname = '\0';
1265207944Sjilles		endname += esc + 1;
12661556Srgrimes	}
12671556Srgrimes	matchdot = 0;
126838887Stegge	p = start;
126938887Stegge	while (*p == CTLQUOTEMARK)
127038887Stegge		p++;
127138887Stegge	if (*p == CTLESC)
127238887Stegge		p++;
127338887Stegge	if (*p == '.')
12741556Srgrimes		matchdot++;
12751556Srgrimes	while (! int_pending() && (dp = readdir(dirp)) != NULL) {
12761556Srgrimes		if (dp->d_name[0] == '.' && ! matchdot)
12771556Srgrimes			continue;
127845514Stegge		if (patmatch(start, dp->d_name, 0)) {
1279211155Sjilles			if (enddir + dp->d_namlen + 1 > expdir_end)
1280211155Sjilles				continue;
1281211155Sjilles			memcpy(enddir, dp->d_name, dp->d_namlen + 1);
1282211155Sjilles			if (atend)
12831556Srgrimes				addfname(expdir);
1284211155Sjilles			else {
1285211155Sjilles				if (enddir + dp->d_namlen + 2 > expdir_end)
128617987Speter					continue;
1287211155Sjilles				enddir[dp->d_namlen] = '/';
1288211155Sjilles				enddir[dp->d_namlen + 1] = '\0';
1289211155Sjilles				expmeta(enddir + dp->d_namlen + 1, endname);
12901556Srgrimes			}
12911556Srgrimes		}
12921556Srgrimes	}
12931556Srgrimes	closedir(dirp);
12941556Srgrimes	if (! atend)
1295207944Sjilles		endname[-esc - 1] = esc ? CTLESC : '/';
12961556Srgrimes}
12971556Srgrimes
12981556Srgrimes
12991556Srgrimes/*
13001556Srgrimes * Add a file name to the list.
13011556Srgrimes */
13021556Srgrimes
1303213811Sobrienstatic void
130490111Simpaddfname(char *name)
130590111Simp{
13061556Srgrimes	char *p;
13071556Srgrimes	struct strlist *sp;
13081556Srgrimes
13091556Srgrimes	p = stalloc(strlen(name) + 1);
13101556Srgrimes	scopy(name, p);
13111556Srgrimes	sp = (struct strlist *)stalloc(sizeof *sp);
13121556Srgrimes	sp->text = p;
13131556Srgrimes	*exparg.lastp = sp;
13141556Srgrimes	exparg.lastp = &sp->next;
13151556Srgrimes}
13161556Srgrimes
13171556Srgrimes
13181556Srgrimes/*
13191556Srgrimes * Sort the results of file name expansion.  It calculates the number of
13201556Srgrimes * strings to sort and then calls msort (short for merge sort) to do the
13211556Srgrimes * work.
13221556Srgrimes */
13231556Srgrimes
1324213811Sobrienstatic struct strlist *
132590111Simpexpsort(struct strlist *str)
132690111Simp{
13271556Srgrimes	int len;
13281556Srgrimes	struct strlist *sp;
13291556Srgrimes
13301556Srgrimes	len = 0;
13311556Srgrimes	for (sp = str ; sp ; sp = sp->next)
13321556Srgrimes		len++;
13331556Srgrimes	return msort(str, len);
13341556Srgrimes}
13351556Srgrimes
13361556Srgrimes
1337213811Sobrienstatic struct strlist *
133890111Simpmsort(struct strlist *list, int len)
133917987Speter{
134017987Speter	struct strlist *p, *q = NULL;
13411556Srgrimes	struct strlist **lpp;
13421556Srgrimes	int half;
13431556Srgrimes	int n;
13441556Srgrimes
13451556Srgrimes	if (len <= 1)
13461556Srgrimes		return list;
13478855Srgrimes	half = len >> 1;
13481556Srgrimes	p = list;
13491556Srgrimes	for (n = half ; --n >= 0 ; ) {
13501556Srgrimes		q = p;
13511556Srgrimes		p = p->next;
13521556Srgrimes	}
13531556Srgrimes	q->next = NULL;			/* terminate first half of list */
13541556Srgrimes	q = msort(list, half);		/* sort first half of list */
13551556Srgrimes	p = msort(p, len - half);		/* sort second half */
13561556Srgrimes	lpp = &list;
13571556Srgrimes	for (;;) {
13581556Srgrimes		if (strcmp(p->text, q->text) < 0) {
13591556Srgrimes			*lpp = p;
13601556Srgrimes			lpp = &p->next;
13611556Srgrimes			if ((p = *lpp) == NULL) {
13621556Srgrimes				*lpp = q;
13631556Srgrimes				break;
13641556Srgrimes			}
13651556Srgrimes		} else {
13661556Srgrimes			*lpp = q;
13671556Srgrimes			lpp = &q->next;
13681556Srgrimes			if ((q = *lpp) == NULL) {
13691556Srgrimes				*lpp = p;
13701556Srgrimes				break;
13711556Srgrimes			}
13721556Srgrimes		}
13731556Srgrimes	}
13741556Srgrimes	return list;
13751556Srgrimes}
13761556Srgrimes
13771556Srgrimes
13781556Srgrimes
13791556Srgrimes/*
13801556Srgrimes * Returns true if the pattern matches the string.
13811556Srgrimes */
13821556Srgrimes
13831556Srgrimesint
1384200956Sjillespatmatch(const char *pattern, const char *string, int squoted)
138590111Simp{
1386200956Sjilles	const char *p, *q;
138725233Ssteve	char c;
13881556Srgrimes
13891556Srgrimes	p = pattern;
13901556Srgrimes	q = string;
13911556Srgrimes	for (;;) {
13921556Srgrimes		switch (c = *p++) {
13931556Srgrimes		case '\0':
13941556Srgrimes			goto breakloop;
13951556Srgrimes		case CTLESC:
139645514Stegge			if (squoted && *q == CTLESC)
139745514Stegge				q++;
13981556Srgrimes			if (*q++ != *p++)
13991556Srgrimes				return 0;
14001556Srgrimes			break;
140138887Stegge		case CTLQUOTEMARK:
140238887Stegge			continue;
14031556Srgrimes		case '?':
140445514Stegge			if (squoted && *q == CTLESC)
140545514Stegge				q++;
14061556Srgrimes			if (*q++ == '\0')
14071556Srgrimes				return 0;
14081556Srgrimes			break;
14091556Srgrimes		case '*':
14101556Srgrimes			c = *p;
141138887Stegge			while (c == CTLQUOTEMARK || c == '*')
141238887Stegge				c = *++p;
141338887Stegge			if (c != CTLESC &&  c != CTLQUOTEMARK &&
141438887Stegge			    c != '?' && c != '*' && c != '[') {
14151556Srgrimes				while (*q != c) {
141645514Stegge					if (squoted && *q == CTLESC &&
141745514Stegge					    q[1] == c)
141845514Stegge						break;
14191556Srgrimes					if (*q == '\0')
14201556Srgrimes						return 0;
142145514Stegge					if (squoted && *q == CTLESC)
142245514Stegge						q++;
14231556Srgrimes					q++;
14241556Srgrimes				}
14251556Srgrimes			}
14261556Srgrimes			do {
1427211646Sjilles				if (patmatch(p, q, squoted))
14281556Srgrimes					return 1;
142945514Stegge				if (squoted && *q == CTLESC)
143045514Stegge					q++;
14311556Srgrimes			} while (*q++ != '\0');
14321556Srgrimes			return 0;
14331556Srgrimes		case '[': {
1434200956Sjilles			const char *endp;
14351556Srgrimes			int invert, found;
14361556Srgrimes			char chr;
14371556Srgrimes
14381556Srgrimes			endp = p;
143926488Sache			if (*endp == '!' || *endp == '^')
14401556Srgrimes				endp++;
14411556Srgrimes			for (;;) {
144238887Stegge				while (*endp == CTLQUOTEMARK)
144338887Stegge					endp++;
14441556Srgrimes				if (*endp == '\0')
14451556Srgrimes					goto dft;		/* no matching ] */
14461556Srgrimes				if (*endp == CTLESC)
14471556Srgrimes					endp++;
14481556Srgrimes				if (*++endp == ']')
14491556Srgrimes					break;
14501556Srgrimes			}
14511556Srgrimes			invert = 0;
145226488Sache			if (*p == '!' || *p == '^') {
14531556Srgrimes				invert++;
14541556Srgrimes				p++;
14551556Srgrimes			}
14561556Srgrimes			found = 0;
14571556Srgrimes			chr = *q++;
145845514Stegge			if (squoted && chr == CTLESC)
145945514Stegge				chr = *q++;
146017987Speter			if (chr == '\0')
146117987Speter				return 0;
14621556Srgrimes			c = *p++;
14631556Srgrimes			do {
146438887Stegge				if (c == CTLQUOTEMARK)
146538887Stegge					continue;
14661556Srgrimes				if (c == CTLESC)
14671556Srgrimes					c = *p++;
14681556Srgrimes				if (*p == '-' && p[1] != ']') {
14691556Srgrimes					p++;
147038887Stegge					while (*p == CTLQUOTEMARK)
147138887Stegge						p++;
14721556Srgrimes					if (*p == CTLESC)
14731556Srgrimes						p++;
147417557Sache					if (   collate_range_cmp(chr, c) >= 0
147517557Sache					    && collate_range_cmp(chr, *p) <= 0
147617525Sache					   )
14771556Srgrimes						found = 1;
14781556Srgrimes					p++;
14791556Srgrimes				} else {
14801556Srgrimes					if (chr == c)
14811556Srgrimes						found = 1;
14821556Srgrimes				}
14831556Srgrimes			} while ((c = *p++) != ']');
14841556Srgrimes			if (found == invert)
14851556Srgrimes				return 0;
14861556Srgrimes			break;
14871556Srgrimes		}
14881556Srgrimesdft:	        default:
148945514Stegge			if (squoted && *q == CTLESC)
149045514Stegge				q++;
14911556Srgrimes			if (*q++ != c)
14921556Srgrimes				return 0;
14931556Srgrimes			break;
14941556Srgrimes		}
14951556Srgrimes	}
14961556Srgrimesbreakloop:
14971556Srgrimes	if (*q != '\0')
14981556Srgrimes		return 0;
14991556Srgrimes	return 1;
15001556Srgrimes}
15011556Srgrimes
15021556Srgrimes
15031556Srgrimes
15041556Srgrimes/*
1505212243Sjilles * Remove any CTLESC and CTLQUOTEMARK characters from a string.
15061556Srgrimes */
15071556Srgrimes
15081556Srgrimesvoid
150990111Simprmescapes(char *str)
151038887Stegge{
151125233Ssteve	char *p, *q;
15121556Srgrimes
15131556Srgrimes	p = str;
1514214512Sjilles	while (*p != CTLESC && *p != CTLQUOTEMARK && *p != CTLQUOTEEND) {
15151556Srgrimes		if (*p++ == '\0')
15161556Srgrimes			return;
15171556Srgrimes	}
15181556Srgrimes	q = p;
15191556Srgrimes	while (*p) {
1520214512Sjilles		if (*p == CTLQUOTEMARK || *p == CTLQUOTEEND) {
152138887Stegge			p++;
152238887Stegge			continue;
152338887Stegge		}
15241556Srgrimes		if (*p == CTLESC)
15251556Srgrimes			p++;
15261556Srgrimes		*q++ = *p++;
15271556Srgrimes	}
15281556Srgrimes	*q = '\0';
15291556Srgrimes}
15301556Srgrimes
15311556Srgrimes
15321556Srgrimes
15331556Srgrimes/*
15341556Srgrimes * See if a pattern matches in a case statement.
15351556Srgrimes */
15361556Srgrimes
15371556Srgrimesint
1538200956Sjillescasematch(union node *pattern, const char *val)
153990111Simp{
15401556Srgrimes	struct stackmark smark;
15411556Srgrimes	int result;
15421556Srgrimes	char *p;
15431556Srgrimes
15441556Srgrimes	setstackmark(&smark);
15451556Srgrimes	argbackq = pattern->narg.backquote;
15461556Srgrimes	STARTSTACKSTR(expdest);
15471556Srgrimes	ifslastp = NULL;
15481556Srgrimes	argstr(pattern->narg.text, EXP_TILDE | EXP_CASE);
15491556Srgrimes	STPUTC('\0', expdest);
15501556Srgrimes	p = grabstackstr(expdest);
155145514Stegge	result = patmatch(p, val, 0);
15521556Srgrimes	popstackmark(&smark);
15531556Srgrimes	return result;
15541556Srgrimes}
155517987Speter
155617987Speter/*
155717987Speter * Our own itoa().
155817987Speter */
155917987Speter
1560213811Sobrienstatic char *
156190111Simpcvtnum(int num, char *buf)
156290111Simp{
156317987Speter	char temp[32];
156417987Speter	int neg = num < 0;
156517987Speter	char *p = temp + 31;
156617987Speter
156717987Speter	temp[31] = '\0';
156817987Speter
156917987Speter	do {
157017987Speter		*--p = num % 10 + '0';
157117987Speter	} while ((num /= 10) != 0);
157217987Speter
157317987Speter	if (neg)
157417987Speter		*--p = '-';
157517987Speter
1576215783Sjilles	STPUTS(p, buf);
157717987Speter	return buf;
157817987Speter}
1579108286Stjr
1580108286Stjr/*
1581108286Stjr * Do most of the work for wordexp(3).
1582108286Stjr */
1583108286Stjr
1584108286Stjrint
1585108286Stjrwordexpcmd(int argc, char **argv)
1586108286Stjr{
1587108286Stjr	size_t len;
1588108286Stjr	int i;
1589108286Stjr
1590108286Stjr	out1fmt("%08x", argc - 1);
1591108286Stjr	for (i = 1, len = 0; i < argc; i++)
1592108286Stjr		len += strlen(argv[i]);
1593108286Stjr	out1fmt("%08x", (int)len);
1594215567Sjilles	for (i = 1; i < argc; i++)
1595215567Sjilles		outbin(argv[i], strlen(argv[i]) + 1, out1);
1596108286Stjr        return (0);
1597108286Stjr}
1598