expand.c revision 216384
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 216384 2010-12-11 22:13:29Z 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
140216384Sjillesstatic char *
141216384Sjillesstputs_quotes(const char *data, const char *syntax, char *p)
142216384Sjilles{
143216384Sjilles	while (*data) {
144216384Sjilles		CHECKSTRSPACE(2, p);
145216384Sjilles		if (syntax[(int)*data] == CCTL)
146216384Sjilles			USTPUTC(CTLESC, p);
147216384Sjilles		USTPUTC(*data++, p);
148216384Sjilles	}
149216384Sjilles	return (p);
150216384Sjilles}
151216384Sjilles#define STPUTS_QUOTES(data, syntax, p) p = stputs_quotes((data), syntax, p)
1521556Srgrimes
1531556Srgrimes/*
154212243Sjilles * Perform expansions on an argument, placing the resulting list of arguments
155212243Sjilles * in arglist.  Parameter expansion, command substitution and arithmetic
156212243Sjilles * expansion are always performed; additional expansions can be requested
157212243Sjilles * via flag (EXP_*).
158212243Sjilles * The result is left in the stack string.
159212243Sjilles * When arglist is NULL, perform here document expansion.  A partial result
160212243Sjilles * may be written to herefd, which is then not included in the stack string.
161212243Sjilles *
162212243Sjilles * Caution: this function uses global state and is not reentrant.
163212243Sjilles * However, a new invocation after an interrupted invocation is safe
164212243Sjilles * and will reset the global state for the new call.
1651556Srgrimes */
1661556Srgrimesvoid
16790111Simpexpandarg(union node *arg, struct arglist *arglist, int flag)
16817987Speter{
1691556Srgrimes	struct strlist *sp;
1701556Srgrimes	char *p;
1711556Srgrimes
1721556Srgrimes	argbackq = arg->narg.backquote;
1731556Srgrimes	STARTSTACKSTR(expdest);
1741556Srgrimes	ifsfirst.next = NULL;
1751556Srgrimes	ifslastp = NULL;
1761556Srgrimes	argstr(arg->narg.text, flag);
1771556Srgrimes	if (arglist == NULL) {
1781556Srgrimes		return;			/* here document expanded */
1791556Srgrimes	}
1801556Srgrimes	STPUTC('\0', expdest);
1811556Srgrimes	p = grabstackstr(expdest);
1821556Srgrimes	exparg.lastp = &exparg.list;
1831556Srgrimes	/*
1841556Srgrimes	 * TODO - EXP_REDIR
1851556Srgrimes	 */
1861556Srgrimes	if (flag & EXP_FULL) {
1871556Srgrimes		ifsbreakup(p, &exparg);
1881556Srgrimes		*exparg.lastp = NULL;
1891556Srgrimes		exparg.lastp = &exparg.list;
1901556Srgrimes		expandmeta(exparg.list, flag);
1911556Srgrimes	} else {
1921556Srgrimes		if (flag & EXP_REDIR) /*XXX - for now, just remove escapes */
1931556Srgrimes			rmescapes(p);
1941556Srgrimes		sp = (struct strlist *)stalloc(sizeof (struct strlist));
1951556Srgrimes		sp->text = p;
1961556Srgrimes		*exparg.lastp = sp;
1971556Srgrimes		exparg.lastp = &sp->next;
1981556Srgrimes	}
1991556Srgrimes	while (ifsfirst.next != NULL) {
2001556Srgrimes		struct ifsregion *ifsp;
2011556Srgrimes		INTOFF;
2021556Srgrimes		ifsp = ifsfirst.next->next;
2031556Srgrimes		ckfree(ifsfirst.next);
2041556Srgrimes		ifsfirst.next = ifsp;
2051556Srgrimes		INTON;
2061556Srgrimes	}
2071556Srgrimes	*exparg.lastp = NULL;
2081556Srgrimes	if (exparg.list) {
2091556Srgrimes		*arglist->lastp = exparg.list;
2101556Srgrimes		arglist->lastp = exparg.lastp;
2111556Srgrimes	}
2121556Srgrimes}
2131556Srgrimes
2141556Srgrimes
2151556Srgrimes
2161556Srgrimes/*
217212243Sjilles * Perform parameter expansion, command substitution and arithmetic
218212243Sjilles * expansion, and tilde expansion if requested via EXP_TILDE/EXP_VARTILDE.
219212243Sjilles * Processing ends at a CTLENDVAR character as well as '\0'.
220212243Sjilles * This is used to expand word in ${var+word} etc.
221212243Sjilles * If EXP_FULL, EXP_CASE or EXP_REDIR are set, keep and/or generate CTLESC
222212243Sjilles * characters to allow for further processing.
223212243Sjilles * If EXP_FULL is set, also preserve CTLQUOTEMARK characters.
2241556Srgrimes */
225213811Sobrienstatic void
22690111Simpargstr(char *p, int flag)
22717987Speter{
22825233Ssteve	char c;
229104672Stjr	int quotes = flag & (EXP_FULL | EXP_CASE | EXP_REDIR);	/* do CTLESC */
2301556Srgrimes	int firsteq = 1;
231214512Sjilles	int split_lit;
232214512Sjilles	int lit_quoted;
2331556Srgrimes
234214512Sjilles	split_lit = flag & EXP_SPLIT_LIT;
235214512Sjilles	lit_quoted = flag & EXP_LIT_QUOTED;
236214512Sjilles	flag &= ~(EXP_SPLIT_LIT | EXP_LIT_QUOTED);
2371556Srgrimes	if (*p == '~' && (flag & (EXP_TILDE | EXP_VARTILDE)))
2381556Srgrimes		p = exptilde(p, flag);
2391556Srgrimes	for (;;) {
240215783Sjilles		CHECKSTRSPACE(2, expdest);
2411556Srgrimes		switch (c = *p++) {
2421556Srgrimes		case '\0':
243212243Sjilles		case CTLENDVAR:
2441556Srgrimes			goto breakloop;
24538887Stegge		case CTLQUOTEMARK:
246214512Sjilles			lit_quoted = 1;
24738887Stegge			/* "$@" syntax adherence hack */
24838887Stegge			if (p[0] == CTLVAR && p[2] == '@' && p[3] == '=')
24938887Stegge				break;
25039137Stegge			if ((flag & EXP_FULL) != 0)
251215783Sjilles				USTPUTC(c, expdest);
25238887Stegge			break;
253214512Sjilles		case CTLQUOTEEND:
254214512Sjilles			lit_quoted = 0;
255214512Sjilles			break;
2561556Srgrimes		case CTLESC:
2571556Srgrimes			if (quotes)
258215783Sjilles				USTPUTC(c, expdest);
2591556Srgrimes			c = *p++;
260215783Sjilles			USTPUTC(c, expdest);
261214512Sjilles			if (split_lit && !lit_quoted)
262214512Sjilles				recordregion(expdest - stackblock() -
263214512Sjilles				    (quotes ? 2 : 1),
264214512Sjilles				    expdest - stackblock(), 0);
2651556Srgrimes			break;
2661556Srgrimes		case CTLVAR:
2671556Srgrimes			p = evalvar(p, flag);
2681556Srgrimes			break;
2691556Srgrimes		case CTLBACKQ:
2701556Srgrimes		case CTLBACKQ|CTLQUOTE:
2711556Srgrimes			expbackq(argbackq->n, c & CTLQUOTE, flag);
2721556Srgrimes			argbackq = argbackq->next;
2731556Srgrimes			break;
2741556Srgrimes		case CTLENDARI:
2751556Srgrimes			expari(flag);
2761556Srgrimes			break;
2771556Srgrimes		case ':':
2781556Srgrimes		case '=':
2791556Srgrimes			/*
2801556Srgrimes			 * sort of a hack - expand tildes in variable
2811556Srgrimes			 * assignments (after the first '=' and after ':'s).
2821556Srgrimes			 */
283215783Sjilles			USTPUTC(c, expdest);
284214512Sjilles			if (split_lit && !lit_quoted)
285214512Sjilles				recordregion(expdest - stackblock() - 1,
286214512Sjilles				    expdest - stackblock(), 0);
287214512Sjilles			if (flag & EXP_VARTILDE && *p == '~' &&
288214512Sjilles			    (c != '=' || firsteq)) {
289214512Sjilles				if (c == '=')
290214512Sjilles					firsteq = 0;
2911556Srgrimes				p = exptilde(p, flag);
2921556Srgrimes			}
2931556Srgrimes			break;
2941556Srgrimes		default:
295215783Sjilles			USTPUTC(c, expdest);
296214512Sjilles			if (split_lit && !lit_quoted)
297214512Sjilles				recordregion(expdest - stackblock() - 1,
298214512Sjilles				    expdest - stackblock(), 0);
2991556Srgrimes		}
3001556Srgrimes	}
3011556Srgrimesbreakloop:;
3021556Srgrimes}
3031556Srgrimes
304212243Sjilles/*
305212243Sjilles * Perform tilde expansion, placing the result in the stack string and
306212243Sjilles * returning the next position in the input string to process.
307212243Sjilles */
308213811Sobrienstatic char *
30990111Simpexptilde(char *p, int flag)
31017987Speter{
3111556Srgrimes	char c, *startp = p;
3121556Srgrimes	struct passwd *pw;
3131556Srgrimes	char *home;
314108935Stjr	int quotes = flag & (EXP_FULL | EXP_CASE | EXP_REDIR);
3151556Srgrimes
31617987Speter	while ((c = *p) != '\0') {
3171556Srgrimes		switch(c) {
318200988Sjilles		case CTLESC: /* This means CTL* are always considered quoted. */
319200988Sjilles		case CTLVAR:
320200988Sjilles		case CTLBACKQ:
321200988Sjilles		case CTLBACKQ | CTLQUOTE:
322200988Sjilles		case CTLARI:
323200988Sjilles		case CTLENDARI:
32439137Stegge		case CTLQUOTEMARK:
32539137Stegge			return (startp);
3261556Srgrimes		case ':':
3271556Srgrimes			if (flag & EXP_VARTILDE)
3281556Srgrimes				goto done;
3291556Srgrimes			break;
3301556Srgrimes		case '/':
331206150Sjilles		case CTLENDVAR:
3321556Srgrimes			goto done;
3331556Srgrimes		}
3341556Srgrimes		p++;
3351556Srgrimes	}
3361556Srgrimesdone:
3371556Srgrimes	*p = '\0';
3381556Srgrimes	if (*(startp+1) == '\0') {
3391556Srgrimes		if ((home = lookupvar("HOME")) == NULL)
3401556Srgrimes			goto lose;
3411556Srgrimes	} else {
3421556Srgrimes		if ((pw = getpwnam(startp+1)) == NULL)
3431556Srgrimes			goto lose;
3441556Srgrimes		home = pw->pw_dir;
3451556Srgrimes	}
3461556Srgrimes	if (*home == '\0')
3471556Srgrimes		goto lose;
3481556Srgrimes	*p = c;
349216384Sjilles	if (quotes)
350216384Sjilles		STPUTS_QUOTES(home, SQSYNTAX, expdest);
351216384Sjilles	else
352216384Sjilles		STPUTS(home, expdest);
3531556Srgrimes	return (p);
3541556Srgrimeslose:
3551556Srgrimes	*p = c;
3561556Srgrimes	return (startp);
3571556Srgrimes}
3581556Srgrimes
3591556Srgrimes
360213811Sobrienstatic void
36190111Simpremoverecordregions(int endoff)
36238887Stegge{
36338887Stegge	if (ifslastp == NULL)
36438887Stegge		return;
36538887Stegge
36638887Stegge	if (ifsfirst.endoff > endoff) {
36738887Stegge		while (ifsfirst.next != NULL) {
36838887Stegge			struct ifsregion *ifsp;
36938887Stegge			INTOFF;
37038887Stegge			ifsp = ifsfirst.next->next;
37138887Stegge			ckfree(ifsfirst.next);
37238887Stegge			ifsfirst.next = ifsp;
37338887Stegge			INTON;
37438887Stegge		}
37538887Stegge		if (ifsfirst.begoff > endoff)
37638887Stegge			ifslastp = NULL;
37738887Stegge		else {
37838887Stegge			ifslastp = &ifsfirst;
37938887Stegge			ifsfirst.endoff = endoff;
38038887Stegge		}
38138887Stegge		return;
38238887Stegge	}
383155301Sschweikh
38438887Stegge	ifslastp = &ifsfirst;
38538887Stegge	while (ifslastp->next && ifslastp->next->begoff < endoff)
38638887Stegge		ifslastp=ifslastp->next;
38738887Stegge	while (ifslastp->next != NULL) {
38838887Stegge		struct ifsregion *ifsp;
38938887Stegge		INTOFF;
39038887Stegge		ifsp = ifslastp->next->next;
39138887Stegge		ckfree(ifslastp->next);
39238887Stegge		ifslastp->next = ifsp;
39338887Stegge		INTON;
39438887Stegge	}
39538887Stegge	if (ifslastp->endoff > endoff)
39638887Stegge		ifslastp->endoff = endoff;
39738887Stegge}
39838887Stegge
3991556Srgrimes/*
4001556Srgrimes * Expand arithmetic expression.  Backup to start of expression,
4011556Srgrimes * evaluate, place result in (backed up) result, adjust string position.
4021556Srgrimes */
4031556Srgrimesvoid
40490111Simpexpari(int flag)
40517987Speter{
406207206Sjilles	char *p, *q, *start;
407178631Sstefanf	arith_t result;
40838887Stegge	int begoff;
409108935Stjr	int quotes = flag & (EXP_FULL | EXP_CASE | EXP_REDIR);
41038887Stegge	int quoted;
4111556Srgrimes
4121556Srgrimes	/*
41346684Skris	 * This routine is slightly over-complicated for
4141556Srgrimes	 * efficiency.  First we make sure there is
4151556Srgrimes	 * enough space for the result, which may be bigger
416212243Sjilles	 * than the expression.  Next we
4171556Srgrimes	 * scan backwards looking for the start of arithmetic.  If the
4181556Srgrimes	 * next previous character is a CTLESC character, then we
4191556Srgrimes	 * have to rescan starting from the beginning since CTLESC
4208855Srgrimes	 * characters have to be processed left to right.
4211556Srgrimes	 */
422178631Sstefanf	CHECKSTRSPACE(DIGITS(result) - 2, expdest);
4238855Srgrimes	USTPUTC('\0', expdest);
4241556Srgrimes	start = stackblock();
42583676Stegge	p = expdest - 2;
42683676Stegge	while (p >= start && *p != CTLARI)
4271556Srgrimes		--p;
42883676Stegge	if (p < start || *p != CTLARI)
4291556Srgrimes		error("missing CTLARI (shouldn't happen)");
43083676Stegge	if (p > start && *(p - 1) == CTLESC)
4311556Srgrimes		for (p = start; *p != CTLARI; p++)
4321556Srgrimes			if (*p == CTLESC)
4331556Srgrimes				p++;
43438887Stegge
43538887Stegge	if (p[1] == '"')
43638887Stegge		quoted=1;
43738887Stegge	else
43838887Stegge		quoted=0;
43938887Stegge	begoff = p - start;
44038887Stegge	removerecordregions(begoff);
4411556Srgrimes	if (quotes)
44238887Stegge		rmescapes(p+2);
443207206Sjilles	q = grabstackstr(expdest);
44438887Stegge	result = arith(p+2);
445207206Sjilles	ungrabstackstr(q, expdest);
446178631Sstefanf	fmtstr(p, DIGITS(result), ARITH_FORMAT_STR, result);
4471556Srgrimes	while (*p++)
4481556Srgrimes		;
44938887Stegge	if (quoted == 0)
45038887Stegge		recordregion(begoff, p - 1 - start, 0);
4511556Srgrimes	result = expdest - p + 1;
4521556Srgrimes	STADJUST(-result, expdest);
4531556Srgrimes}
4541556Srgrimes
4551556Srgrimes
4561556Srgrimes/*
457212243Sjilles * Perform command substitution.
4581556Srgrimes */
459213811Sobrienstatic void
46090111Simpexpbackq(union node *cmd, int quoted, int flag)
46117987Speter{
4621556Srgrimes	struct backcmd in;
4631556Srgrimes	int i;
4641556Srgrimes	char buf[128];
4651556Srgrimes	char *p;
4661556Srgrimes	char *dest = expdest;
4671556Srgrimes	struct ifsregion saveifs, *savelastp;
4681556Srgrimes	struct nodelist *saveargbackq;
4691556Srgrimes	char lastc;
4701556Srgrimes	int startloc = dest - stackblock();
4711556Srgrimes	char const *syntax = quoted? DQSYNTAX : BASESYNTAX;
4721556Srgrimes	int saveherefd;
473108935Stjr	int quotes = flag & (EXP_FULL | EXP_CASE | EXP_REDIR);
474115424Sfenner	int nnl;
4751556Srgrimes
4761556Srgrimes	INTOFF;
4771556Srgrimes	saveifs = ifsfirst;
4781556Srgrimes	savelastp = ifslastp;
4791556Srgrimes	saveargbackq = argbackq;
4808855Srgrimes	saveherefd = herefd;
4811556Srgrimes	herefd = -1;
4821556Srgrimes	p = grabstackstr(dest);
4831556Srgrimes	evalbackcmd(cmd, &in);
4841556Srgrimes	ungrabstackstr(p, dest);
4851556Srgrimes	ifsfirst = saveifs;
4861556Srgrimes	ifslastp = savelastp;
4871556Srgrimes	argbackq = saveargbackq;
4881556Srgrimes	herefd = saveherefd;
4891556Srgrimes
4901556Srgrimes	p = in.buf;
4911556Srgrimes	lastc = '\0';
492115424Sfenner	nnl = 0;
493115424Sfenner	/* Don't copy trailing newlines */
4941556Srgrimes	for (;;) {
4951556Srgrimes		if (--in.nleft < 0) {
4961556Srgrimes			if (in.fd < 0)
4971556Srgrimes				break;
4981556Srgrimes			while ((i = read(in.fd, buf, sizeof buf)) < 0 && errno == EINTR);
4991556Srgrimes			TRACE(("expbackq: read returns %d\n", i));
5001556Srgrimes			if (i <= 0)
5011556Srgrimes				break;
5021556Srgrimes			p = buf;
5031556Srgrimes			in.nleft = i - 1;
5041556Srgrimes		}
5051556Srgrimes		lastc = *p++;
5061556Srgrimes		if (lastc != '\0') {
50783675Stegge			if (quotes && syntax[(int)lastc] == CCTL)
5081556Srgrimes				STPUTC(CTLESC, dest);
509115424Sfenner			if (lastc == '\n') {
510115424Sfenner				nnl++;
511115424Sfenner			} else {
512115424Sfenner				while (nnl > 0) {
513115424Sfenner					nnl--;
514115424Sfenner					STPUTC('\n', dest);
515115424Sfenner				}
516115424Sfenner				STPUTC(lastc, dest);
517115424Sfenner			}
5181556Srgrimes		}
5191556Srgrimes	}
52017987Speter
5211556Srgrimes	if (in.fd >= 0)
5221556Srgrimes		close(in.fd);
5231556Srgrimes	if (in.buf)
5241556Srgrimes		ckfree(in.buf);
5251556Srgrimes	if (in.jp)
52645916Scracauer		exitstatus = waitforjob(in.jp, (int *)NULL);
5271556Srgrimes	if (quoted == 0)
5281556Srgrimes		recordregion(startloc, dest - stackblock(), 0);
529213775Sjhb	TRACE(("expbackq: size=%td: \"%.*s\"\n",
530213775Sjhb		((dest - stackblock()) - startloc),
531213775Sjhb		(int)((dest - stackblock()) - startloc),
5321556Srgrimes		stackblock() + startloc));
5331556Srgrimes	expdest = dest;
5341556Srgrimes	INTON;
5351556Srgrimes}
5361556Srgrimes
5371556Srgrimes
5381556Srgrimes
539213811Sobrienstatic int
54090111Simpsubevalvar(char *p, char *str, int strloc, int subtype, int startloc,
541214524Sjilles  int varflags, int quotes)
54217987Speter{
54317987Speter	char *startp;
54417987Speter	char *loc = NULL;
54545514Stegge	char *q;
54617987Speter	int c = 0;
54717987Speter	int saveherefd = herefd;
54817987Speter	struct nodelist *saveargbackq = argbackq;
54920425Ssteve	int amount;
55020425Ssteve
55117987Speter	herefd = -1;
552206150Sjilles	argstr(p, (subtype == VSTRIMLEFT || subtype == VSTRIMLEFTMAX ||
553206147Sjilles	    subtype == VSTRIMRIGHT || subtype == VSTRIMRIGHTMAX ?
554206150Sjilles	    EXP_CASE : 0) | EXP_TILDE);
55517987Speter	STACKSTRNUL(expdest);
55617987Speter	herefd = saveherefd;
55717987Speter	argbackq = saveargbackq;
55817987Speter	startp = stackblock() + startloc;
55920425Ssteve	if (str == NULL)
56020425Ssteve	    str = stackblock() + strloc;
56117987Speter
56217987Speter	switch (subtype) {
56317987Speter	case VSASSIGN:
56417987Speter		setvar(str, startp, 0);
56520425Ssteve		amount = startp - expdest;
56620425Ssteve		STADJUST(amount, expdest);
56717987Speter		varflags &= ~VSNUL;
56817987Speter		if (c != 0)
56917987Speter			*loc = c;
57017987Speter		return 1;
57117987Speter
57217987Speter	case VSQUESTION:
57317987Speter		if (*p != CTLENDVAR) {
574201366Sjilles			outfmt(out2, "%s\n", startp);
57517987Speter			error((char *)NULL);
57617987Speter		}
577112254Sru		error("%.*s: parameter %snot set", (int)(p - str - 1),
57817987Speter		      str, (varflags & VSNUL) ? "null or "
57917987Speter					      : nullstr);
58017987Speter		return 0;
58117987Speter
58217987Speter	case VSTRIMLEFT:
58325233Ssteve		for (loc = startp; loc < str; loc++) {
58417987Speter			c = *loc;
58517987Speter			*loc = '\0';
586214524Sjilles			if (patmatch(str, startp, quotes)) {
58717987Speter				*loc = c;
58817987Speter				goto recordleft;
58917987Speter			}
59017987Speter			*loc = c;
591214524Sjilles			if (quotes && *loc == CTLESC)
59245514Stegge				loc++;
59317987Speter		}
59417987Speter		return 0;
59517987Speter
59617987Speter	case VSTRIMLEFTMAX:
59745514Stegge		for (loc = str - 1; loc >= startp;) {
59817987Speter			c = *loc;
59917987Speter			*loc = '\0';
600214524Sjilles			if (patmatch(str, startp, quotes)) {
60117987Speter				*loc = c;
60217987Speter				goto recordleft;
60317987Speter			}
60417987Speter			*loc = c;
60545514Stegge			loc--;
606214524Sjilles			if (quotes && loc > startp && *(loc - 1) == CTLESC) {
60745514Stegge				for (q = startp; q < loc; q++)
60845514Stegge					if (*q == CTLESC)
60945514Stegge						q++;
61045514Stegge				if (q > loc)
61145514Stegge					loc--;
61245514Stegge			}
61317987Speter		}
61417987Speter		return 0;
61517987Speter
61617987Speter	case VSTRIMRIGHT:
61745514Stegge		for (loc = str - 1; loc >= startp;) {
618214524Sjilles			if (patmatch(str, loc, quotes)) {
61920425Ssteve				amount = loc - expdest;
62020425Ssteve				STADJUST(amount, expdest);
62117987Speter				return 1;
62217987Speter			}
62345514Stegge			loc--;
624214524Sjilles			if (quotes && loc > startp && *(loc - 1) == CTLESC) {
62545514Stegge				for (q = startp; q < loc; q++)
62645514Stegge					if (*q == CTLESC)
62745514Stegge						q++;
62845514Stegge				if (q > loc)
62945514Stegge					loc--;
63045514Stegge			}
63117987Speter		}
63217987Speter		return 0;
63317987Speter
63417987Speter	case VSTRIMRIGHTMAX:
63517987Speter		for (loc = startp; loc < str - 1; loc++) {
636214524Sjilles			if (patmatch(str, loc, quotes)) {
63720425Ssteve				amount = loc - expdest;
63820425Ssteve				STADJUST(amount, expdest);
63917987Speter				return 1;
64017987Speter			}
641214524Sjilles			if (quotes && *loc == CTLESC)
64245514Stegge				loc++;
64317987Speter		}
64417987Speter		return 0;
64517987Speter
64617987Speter
64717987Speter	default:
64817987Speter		abort();
64917987Speter	}
65017987Speter
65117987Speterrecordleft:
65220425Ssteve	amount = ((str - 1) - (loc - startp)) - expdest;
65320425Ssteve	STADJUST(amount, expdest);
65417987Speter	while (loc != str - 1)
65517987Speter		*startp++ = *loc++;
65617987Speter	return 1;
65717987Speter}
65817987Speter
65917987Speter
6601556Srgrimes/*
6611556Srgrimes * Expand a variable, and return a pointer to the next character in the
6621556Srgrimes * input string.
6631556Srgrimes */
6641556Srgrimes
665213811Sobrienstatic char *
66690111Simpevalvar(char *p, int flag)
66717987Speter{
6681556Srgrimes	int subtype;
6691556Srgrimes	int varflags;
6701556Srgrimes	char *var;
6711556Srgrimes	char *val;
67245644Stegge	int patloc;
6731556Srgrimes	int c;
6741556Srgrimes	int set;
6751556Srgrimes	int special;
6761556Srgrimes	int startloc;
67717987Speter	int varlen;
67817987Speter	int easy;
679108935Stjr	int quotes = flag & (EXP_FULL | EXP_CASE | EXP_REDIR);
6801556Srgrimes
681164081Sstefanf	varflags = (unsigned char)*p++;
6821556Srgrimes	subtype = varflags & VSTYPE;
6831556Srgrimes	var = p;
6841556Srgrimes	special = 0;
6851556Srgrimes	if (! is_name(*p))
6861556Srgrimes		special = 1;
6871556Srgrimes	p = strchr(p, '=') + 1;
6881556Srgrimesagain: /* jump here after setting a variable with ${var=text} */
689179022Sstefanf	if (varflags & VSLINENO) {
690179022Sstefanf		set = 1;
691179022Sstefanf		special = 0;
692179022Sstefanf		val = var;
693179022Sstefanf		p[-1] = '\0';	/* temporarily overwrite '=' to have \0
694179022Sstefanf				   terminated string */
695179022Sstefanf	} else if (special) {
69625233Ssteve		set = varisset(var, varflags & VSNUL);
6971556Srgrimes		val = NULL;
6981556Srgrimes	} else {
69960592Scracauer		val = bltinlookup(var, 1);
70017987Speter		if (val == NULL || ((varflags & VSNUL) && val[0] == '\0')) {
7011556Srgrimes			val = NULL;
7021556Srgrimes			set = 0;
7031556Srgrimes		} else
7041556Srgrimes			set = 1;
7051556Srgrimes	}
70617987Speter	varlen = 0;
7071556Srgrimes	startloc = expdest - stackblock();
708198454Sjilles	if (!set && uflag && *var != '@' && *var != '*') {
70996939Stjr		switch (subtype) {
71096939Stjr		case VSNORMAL:
71196939Stjr		case VSTRIMLEFT:
71296939Stjr		case VSTRIMLEFTMAX:
71396939Stjr		case VSTRIMRIGHT:
71496939Stjr		case VSTRIMRIGHTMAX:
71596939Stjr		case VSLENGTH:
716112254Sru			error("%.*s: parameter not set", (int)(p - var - 1),
717112254Sru			    var);
71896939Stjr		}
71996939Stjr	}
7201556Srgrimes	if (set && subtype != VSPLUS) {
7211556Srgrimes		/* insert the value of the variable */
7221556Srgrimes		if (special) {
723164081Sstefanf			varvalue(var, varflags & VSQUOTE, subtype, flag);
72417987Speter			if (subtype == VSLENGTH) {
72525233Ssteve				varlen = expdest - stackblock() - startloc;
72625233Ssteve				STADJUST(-varlen, expdest);
72717987Speter			}
7281556Srgrimes		} else {
72920425Ssteve			char const *syntax = (varflags & VSQUOTE) ? DQSYNTAX
73017987Speter								  : BASESYNTAX;
7311556Srgrimes
73217987Speter			if (subtype == VSLENGTH) {
73317987Speter				for (;*val; val++)
73417987Speter					varlen++;
7351556Srgrimes			}
73617987Speter			else {
737216384Sjilles				if (quotes)
738216384Sjilles					STPUTS_QUOTES(val, syntax, expdest);
739216384Sjilles				else
740216384Sjilles					STPUTS(val, expdest);
74117987Speter
74217987Speter			}
7431556Srgrimes		}
7441556Srgrimes	}
74520425Ssteve
7461556Srgrimes	if (subtype == VSPLUS)
7471556Srgrimes		set = ! set;
74817987Speter
74920425Ssteve	easy = ((varflags & VSQUOTE) == 0 ||
75017987Speter		(*var == '@' && shellparam.nparam != 1));
75117987Speter
75217987Speter
75317987Speter	switch (subtype) {
75417987Speter	case VSLENGTH:
75517987Speter		expdest = cvtnum(varlen, expdest);
75617987Speter		goto record;
75717987Speter
75817987Speter	case VSNORMAL:
75917987Speter		if (!easy)
76017987Speter			break;
76117987Speterrecord:
76220425Ssteve		recordregion(startloc, expdest - stackblock(),
76317987Speter			     varflags & VSQUOTE);
76417987Speter		break;
76517987Speter
76617987Speter	case VSPLUS:
76717987Speter	case VSMINUS:
76817987Speter		if (!set) {
769214512Sjilles			argstr(p, flag | (flag & EXP_FULL ? EXP_SPLIT_LIT : 0) |
770214512Sjilles			    (varflags & VSQUOTE ? EXP_LIT_QUOTED : 0));
77117987Speter			break;
77217987Speter		}
77317987Speter		if (easy)
77417987Speter			goto record;
77517987Speter		break;
77617987Speter
77717987Speter	case VSTRIMLEFT:
77817987Speter	case VSTRIMLEFTMAX:
77917987Speter	case VSTRIMRIGHT:
78017987Speter	case VSTRIMRIGHTMAX:
78117987Speter		if (!set)
78217987Speter			break;
78317987Speter		/*
78417987Speter		 * Terminate the string and start recording the pattern
78517987Speter		 * right after it
78617987Speter		 */
78717987Speter		STPUTC('\0', expdest);
78845644Stegge		patloc = expdest - stackblock();
78945644Stegge		if (subevalvar(p, NULL, patloc, subtype,
790214524Sjilles		    startloc, varflags, quotes) == 0) {
79145644Stegge			int amount = (expdest - stackblock() - patloc) + 1;
79225233Ssteve			STADJUST(-amount, expdest);
79325233Ssteve		}
79438887Stegge		/* Remove any recorded regions beyond start of variable */
79538887Stegge		removerecordregions(startloc);
79638887Stegge		goto record;
79717987Speter
79817987Speter	case VSASSIGN:
79917987Speter	case VSQUESTION:
80017987Speter		if (!set) {
801214524Sjilles			if (subevalvar(p, var, 0, subtype, startloc, varflags,
802214524Sjilles			    quotes)) {
80320425Ssteve				varflags &= ~VSNUL;
804155301Sschweikh				/*
805155301Sschweikh				 * Remove any recorded regions beyond
806155301Sschweikh				 * start of variable
80738887Stegge				 */
80838887Stegge				removerecordregions(startloc);
8091556Srgrimes				goto again;
81020425Ssteve			}
81117987Speter			break;
8121556Srgrimes		}
81317987Speter		if (easy)
81417987Speter			goto record;
81517987Speter		break;
81617987Speter
817164003Sstefanf	case VSERROR:
818164003Sstefanf		c = p - var - 1;
819164003Sstefanf		error("${%.*s%s}: Bad substitution", c, var,
820164003Sstefanf		    (c > 0 && *p != CTLENDVAR) ? "..." : "");
821164003Sstefanf
82217987Speter	default:
82317987Speter		abort();
8241556Srgrimes	}
825179022Sstefanf	p[-1] = '=';	/* recover overwritten '=' */
82617987Speter
8271556Srgrimes	if (subtype != VSNORMAL) {	/* skip to end of alternative */
8281556Srgrimes		int nesting = 1;
8291556Srgrimes		for (;;) {
8301556Srgrimes			if ((c = *p++) == CTLESC)
8311556Srgrimes				p++;
8321556Srgrimes			else if (c == CTLBACKQ || c == (CTLBACKQ|CTLQUOTE)) {
8331556Srgrimes				if (set)
8341556Srgrimes					argbackq = argbackq->next;
8351556Srgrimes			} else if (c == CTLVAR) {
8361556Srgrimes				if ((*p++ & VSTYPE) != VSNORMAL)
8371556Srgrimes					nesting++;
8381556Srgrimes			} else if (c == CTLENDVAR) {
8391556Srgrimes				if (--nesting == 0)
8401556Srgrimes					break;
8411556Srgrimes			}
8421556Srgrimes		}
8431556Srgrimes	}
8441556Srgrimes	return p;
8451556Srgrimes}
8461556Srgrimes
8471556Srgrimes
8481556Srgrimes
8491556Srgrimes/*
8501556Srgrimes * Test whether a specialized variable is set.
8511556Srgrimes */
8521556Srgrimes
853213811Sobrienstatic int
85490111Simpvarisset(char *name, int nulok)
85525233Ssteve{
8561556Srgrimes
85725233Ssteve	if (*name == '!')
858209600Sjilles		return backgndpidset();
85925233Ssteve	else if (*name == '@' || *name == '*') {
8601556Srgrimes		if (*shellparam.p == NULL)
8611556Srgrimes			return 0;
86225233Ssteve
86325233Ssteve		if (nulok) {
86425233Ssteve			char **av;
86525233Ssteve
86625233Ssteve			for (av = shellparam.p; *av; av++)
86725233Ssteve				if (**av != '\0')
86825233Ssteve					return 1;
86925233Ssteve			return 0;
87025233Ssteve		}
87118202Speter	} else if (is_digit(*name)) {
87225233Ssteve		char *ap;
87320425Ssteve		int num = atoi(name);
87425233Ssteve
87525233Ssteve		if (num > shellparam.nparam)
87625233Ssteve			return 0;
87725233Ssteve
87825233Ssteve		if (num == 0)
87925233Ssteve			ap = arg0;
88025233Ssteve		else
88125233Ssteve			ap = shellparam.p[num - 1];
88225233Ssteve
88325233Ssteve		if (nulok && (ap == NULL || *ap == '\0'))
88425233Ssteve			return 0;
8851556Srgrimes	}
8861556Srgrimes	return 1;
8871556Srgrimes}
8881556Srgrimes
889216384Sjillesstatic void
890216384Sjillesstrtodest(const char *p, int flag, int subtype, int quoted)
891216384Sjilles{
892216384Sjilles	if (flag & (EXP_FULL | EXP_CASE) && subtype != VSLENGTH)
893216384Sjilles		STPUTS_QUOTES(p, quoted ? DQSYNTAX : BASESYNTAX, expdest);
894216384Sjilles	else
895216384Sjilles		STPUTS(p, expdest);
896216384Sjilles}
8971556Srgrimes
8981556Srgrimes/*
8991556Srgrimes * Add the value of a specialized variable to the stack string.
9001556Srgrimes */
9011556Srgrimes
902213811Sobrienstatic void
903164081Sstefanfvarvalue(char *name, int quoted, int subtype, int flag)
90417987Speter{
9051556Srgrimes	int num;
9061556Srgrimes	char *p;
9071556Srgrimes	int i;
9081556Srgrimes	char sep;
9091556Srgrimes	char **ap;
9101556Srgrimes
91118202Speter	switch (*name) {
9121556Srgrimes	case '$':
9131556Srgrimes		num = rootpid;
9141556Srgrimes		goto numvar;
9151556Srgrimes	case '?':
91617987Speter		num = oexitstatus;
9171556Srgrimes		goto numvar;
9181556Srgrimes	case '#':
9191556Srgrimes		num = shellparam.nparam;
9201556Srgrimes		goto numvar;
9211556Srgrimes	case '!':
922209600Sjilles		num = backgndpidval();
9231556Srgrimesnumvar:
92417987Speter		expdest = cvtnum(num, expdest);
9251556Srgrimes		break;
9261556Srgrimes	case '-':
9271556Srgrimes		for (i = 0 ; i < NOPTS ; i++) {
9281556Srgrimes			if (optlist[i].val)
9291556Srgrimes				STPUTC(optlist[i].letter, expdest);
9301556Srgrimes		}
9311556Srgrimes		break;
9321556Srgrimes	case '@':
933164081Sstefanf		if (flag & EXP_FULL && quoted) {
93438887Stegge			for (ap = shellparam.p ; (p = *ap++) != NULL ; ) {
935216384Sjilles				strtodest(p, flag, subtype, quoted);
93638887Stegge				if (*ap)
93738887Stegge					STPUTC('\0', expdest);
93838887Stegge			}
93938887Stegge			break;
9401556Srgrimes		}
941102410Scharnier		/* FALLTHROUGH */
9421556Srgrimes	case '*':
943149825Srse		if (ifsset())
94438887Stegge			sep = ifsval()[0];
94538887Stegge		else
94638887Stegge			sep = ' ';
9471556Srgrimes		for (ap = shellparam.p ; (p = *ap++) != NULL ; ) {
948216384Sjilles			strtodest(p, flag, subtype, quoted);
94938887Stegge			if (*ap && sep)
9501556Srgrimes				STPUTC(sep, expdest);
9511556Srgrimes		}
9521556Srgrimes		break;
9531556Srgrimes	case '0':
9541556Srgrimes		p = arg0;
955216384Sjilles		strtodest(p, flag, subtype, quoted);
9561556Srgrimes		break;
9571556Srgrimes	default:
95818202Speter		if (is_digit(*name)) {
95918202Speter			num = atoi(name);
96018202Speter			if (num > 0 && num <= shellparam.nparam) {
96118202Speter				p = shellparam.p[num - 1];
962216384Sjilles				strtodest(p, flag, subtype, quoted);
96318202Speter			}
9641556Srgrimes		}
9651556Srgrimes		break;
9661556Srgrimes	}
9671556Srgrimes}
9681556Srgrimes
9691556Srgrimes
9701556Srgrimes
9711556Srgrimes/*
9721556Srgrimes * Record the the fact that we have to scan this region of the
9731556Srgrimes * string for IFS characters.
9741556Srgrimes */
9751556Srgrimes
976213811Sobrienstatic void
977194975Sjillesrecordregion(int start, int end, int inquotes)
97817987Speter{
97925233Ssteve	struct ifsregion *ifsp;
9801556Srgrimes
9811556Srgrimes	if (ifslastp == NULL) {
9821556Srgrimes		ifsp = &ifsfirst;
9831556Srgrimes	} else {
984194975Sjilles		if (ifslastp->endoff == start
985194975Sjilles		    && ifslastp->inquotes == inquotes) {
986194975Sjilles			/* extend previous area */
987194975Sjilles			ifslastp->endoff = end;
988194975Sjilles			return;
989194975Sjilles		}
9901556Srgrimes		ifsp = (struct ifsregion *)ckmalloc(sizeof (struct ifsregion));
9911556Srgrimes		ifslastp->next = ifsp;
9921556Srgrimes	}
9931556Srgrimes	ifslastp = ifsp;
9941556Srgrimes	ifslastp->next = NULL;
9951556Srgrimes	ifslastp->begoff = start;
9961556Srgrimes	ifslastp->endoff = end;
997194975Sjilles	ifslastp->inquotes = inquotes;
9981556Srgrimes}
9991556Srgrimes
10001556Srgrimes
10011556Srgrimes
10021556Srgrimes/*
10031556Srgrimes * Break the argument string into pieces based upon IFS and add the
10041556Srgrimes * strings to the argument list.  The regions of the string to be
10051556Srgrimes * searched for IFS characters have been stored by recordregion.
1006212243Sjilles * CTLESC characters are preserved but have little effect in this pass
1007212243Sjilles * other than escaping CTL* characters.  In particular, they do not escape
1008212243Sjilles * IFS characters: that should be done with the ifsregion mechanism.
1009212243Sjilles * CTLQUOTEMARK characters are used to preserve empty quoted strings.
1010212243Sjilles * This pass treats them as a regular character, making the string non-empty.
1011212243Sjilles * Later, they are removed along with the other CTL* characters.
10121556Srgrimes */
1013213811Sobrienstatic void
101490111Simpifsbreakup(char *string, struct arglist *arglist)
101590111Simp{
10161556Srgrimes	struct ifsregion *ifsp;
10171556Srgrimes	struct strlist *sp;
10181556Srgrimes	char *start;
101925233Ssteve	char *p;
10201556Srgrimes	char *q;
1021201053Sjilles	const char *ifs;
1022194975Sjilles	const char *ifsspc;
1023194975Sjilles	int had_param_ch = 0;
10241556Srgrimes
1025194975Sjilles	start = string;
102617987Speter
1027194975Sjilles	if (ifslastp == NULL) {
1028194975Sjilles		/* Return entire argument, IFS doesn't apply to any of it */
1029194975Sjilles		sp = (struct strlist *)stalloc(sizeof *sp);
1030194975Sjilles		sp->text = start;
1031194975Sjilles		*arglist->lastp = sp;
1032194975Sjilles		arglist->lastp = &sp->next;
1033194975Sjilles		return;
1034194975Sjilles	}
1035194975Sjilles
1036194975Sjilles	ifs = ifsset() ? ifsval() : " \t\n";
1037194975Sjilles
1038194975Sjilles	for (ifsp = &ifsfirst; ifsp != NULL; ifsp = ifsp->next) {
1039194975Sjilles		p = string + ifsp->begoff;
1040194975Sjilles		while (p < string + ifsp->endoff) {
1041194975Sjilles			q = p;
1042194975Sjilles			if (*p == CTLESC)
1043194975Sjilles				p++;
1044194975Sjilles			if (ifsp->inquotes) {
1045194975Sjilles				/* Only NULs (should be from "$@") end args */
1046194977Sjilles				had_param_ch = 1;
1047194975Sjilles				if (*p != 0) {
10481556Srgrimes					p++;
1049194975Sjilles					continue;
1050194975Sjilles				}
1051194975Sjilles				ifsspc = NULL;
1052194975Sjilles			} else {
1053194975Sjilles				if (!strchr(ifs, *p)) {
1054194977Sjilles					had_param_ch = 1;
105538887Stegge					p++;
1056194975Sjilles					continue;
1057194975Sjilles				}
1058194975Sjilles				ifsspc = strchr(" \t\n", *p);
1059194975Sjilles
1060194975Sjilles				/* Ignore IFS whitespace at start */
1061194975Sjilles				if (q == start && ifsspc != NULL) {
1062194975Sjilles					p++;
10631556Srgrimes					start = p;
1064194975Sjilles					continue;
1065194975Sjilles				}
1066194977Sjilles				had_param_ch = 0;
10671556Srgrimes			}
1068194975Sjilles
1069194975Sjilles			/* Save this argument... */
1070194975Sjilles			*q = '\0';
10711556Srgrimes			sp = (struct strlist *)stalloc(sizeof *sp);
10721556Srgrimes			sp->text = start;
10731556Srgrimes			*arglist->lastp = sp;
10741556Srgrimes			arglist->lastp = &sp->next;
1075194975Sjilles			p++;
1076194975Sjilles
1077194975Sjilles			if (ifsspc != NULL) {
1078194975Sjilles				/* Ignore further trailing IFS whitespace */
1079194975Sjilles				for (; p < string + ifsp->endoff; p++) {
1080194975Sjilles					q = p;
1081194975Sjilles					if (*p == CTLESC)
1082194975Sjilles						p++;
1083194975Sjilles					if (strchr(ifs, *p) == NULL) {
1084194975Sjilles						p = q;
1085194975Sjilles						break;
1086194975Sjilles					}
1087194975Sjilles					if (strchr(" \t\n", *p) == NULL) {
1088194975Sjilles						p++;
1089194975Sjilles						break;
1090194975Sjilles					}
1091194975Sjilles				}
1092194975Sjilles			}
1093194975Sjilles			start = p;
10941556Srgrimes		}
1095194975Sjilles	}
1096194975Sjilles
1097194975Sjilles	/*
1098194975Sjilles	 * Save anything left as an argument.
1099194975Sjilles	 * Traditionally we have treated 'IFS=':'; set -- x$IFS' as
1100194975Sjilles	 * generating 2 arguments, the second of which is empty.
1101194975Sjilles	 * Some recent clarification of the Posix spec say that it
1102194975Sjilles	 * should only generate one....
1103194975Sjilles	 */
1104194975Sjilles	if (had_param_ch || *start != 0) {
11051556Srgrimes		sp = (struct strlist *)stalloc(sizeof *sp);
11061556Srgrimes		sp->text = start;
11071556Srgrimes		*arglist->lastp = sp;
11081556Srgrimes		arglist->lastp = &sp->next;
11091556Srgrimes	}
11101556Srgrimes}
11111556Srgrimes
11121556Srgrimes
1113213760Sobrienstatic char expdir[PATH_MAX];
1114212243Sjilles#define expdir_end (expdir + sizeof(expdir))
11151556Srgrimes
11161556Srgrimes/*
1117212243Sjilles * Perform pathname generation and remove control characters.
1118212243Sjilles * At this point, the only control characters should be CTLESC and CTLQUOTEMARK.
1119212243Sjilles * The results are stored in the list exparg.
11201556Srgrimes */
1121213811Sobrienstatic void
112290111Simpexpandmeta(struct strlist *str, int flag __unused)
112317987Speter{
11241556Srgrimes	char *p;
11251556Srgrimes	struct strlist **savelastp;
11261556Srgrimes	struct strlist *sp;
11271556Srgrimes	char c;
11281556Srgrimes	/* TODO - EXP_REDIR */
11291556Srgrimes
11301556Srgrimes	while (str) {
11311556Srgrimes		if (fflag)
11321556Srgrimes			goto nometa;
11331556Srgrimes		p = str->text;
11341556Srgrimes		for (;;) {			/* fast check for meta chars */
11351556Srgrimes			if ((c = *p++) == '\0')
11361556Srgrimes				goto nometa;
1137211646Sjilles			if (c == '*' || c == '?' || c == '[')
11381556Srgrimes				break;
11391556Srgrimes		}
11401556Srgrimes		savelastp = exparg.lastp;
11411556Srgrimes		INTOFF;
11421556Srgrimes		expmeta(expdir, str->text);
11431556Srgrimes		INTON;
11441556Srgrimes		if (exparg.lastp == savelastp) {
11458855Srgrimes			/*
11468855Srgrimes			 * no matches
11471556Srgrimes			 */
11481556Srgrimesnometa:
11491556Srgrimes			*exparg.lastp = str;
11501556Srgrimes			rmescapes(str->text);
11511556Srgrimes			exparg.lastp = &str->next;
11521556Srgrimes		} else {
11531556Srgrimes			*exparg.lastp = NULL;
11541556Srgrimes			*savelastp = sp = expsort(*savelastp);
11551556Srgrimes			while (sp->next != NULL)
11561556Srgrimes				sp = sp->next;
11571556Srgrimes			exparg.lastp = &sp->next;
11581556Srgrimes		}
11591556Srgrimes		str = str->next;
11601556Srgrimes	}
11611556Srgrimes}
11621556Srgrimes
11631556Srgrimes
11641556Srgrimes/*
11651556Srgrimes * Do metacharacter (i.e. *, ?, [...]) expansion.
11661556Srgrimes */
11671556Srgrimes
1168213811Sobrienstatic void
116990111Simpexpmeta(char *enddir, char *name)
117090111Simp{
117125233Ssteve	char *p;
11721556Srgrimes	char *q;
11731556Srgrimes	char *start;
11741556Srgrimes	char *endname;
11751556Srgrimes	int metaflag;
11761556Srgrimes	struct stat statb;
11771556Srgrimes	DIR *dirp;
11781556Srgrimes	struct dirent *dp;
11791556Srgrimes	int atend;
11801556Srgrimes	int matchdot;
1181207944Sjilles	int esc;
11821556Srgrimes
11831556Srgrimes	metaflag = 0;
11841556Srgrimes	start = name;
1185207944Sjilles	for (p = name; esc = 0, *p; p += esc + 1) {
11861556Srgrimes		if (*p == '*' || *p == '?')
11871556Srgrimes			metaflag = 1;
11881556Srgrimes		else if (*p == '[') {
11891556Srgrimes			q = p + 1;
119026488Sache			if (*q == '!' || *q == '^')
11911556Srgrimes				q++;
11921556Srgrimes			for (;;) {
119338887Stegge				while (*q == CTLQUOTEMARK)
119438887Stegge					q++;
11951556Srgrimes				if (*q == CTLESC)
11961556Srgrimes					q++;
11971556Srgrimes				if (*q == '/' || *q == '\0')
11981556Srgrimes					break;
11991556Srgrimes				if (*++q == ']') {
12001556Srgrimes					metaflag = 1;
12011556Srgrimes					break;
12021556Srgrimes				}
12031556Srgrimes			}
12041556Srgrimes		} else if (*p == '\0')
12051556Srgrimes			break;
120638887Stegge		else if (*p == CTLQUOTEMARK)
120738887Stegge			continue;
1208207944Sjilles		else {
1209207944Sjilles			if (*p == CTLESC)
1210207944Sjilles				esc++;
1211207944Sjilles			if (p[esc] == '/') {
1212207944Sjilles				if (metaflag)
1213207944Sjilles					break;
1214207944Sjilles				start = p + esc + 1;
1215207944Sjilles			}
12161556Srgrimes		}
12171556Srgrimes	}
12181556Srgrimes	if (metaflag == 0) {	/* we've reached the end of the file name */
12191556Srgrimes		if (enddir != expdir)
12201556Srgrimes			metaflag++;
12211556Srgrimes		for (p = name ; ; p++) {
122238887Stegge			if (*p == CTLQUOTEMARK)
122338887Stegge				continue;
12241556Srgrimes			if (*p == CTLESC)
12251556Srgrimes				p++;
12261556Srgrimes			*enddir++ = *p;
12271556Srgrimes			if (*p == '\0')
12281556Srgrimes				break;
1229211155Sjilles			if (enddir == expdir_end)
1230211155Sjilles				return;
12311556Srgrimes		}
1232147812Sdelphij		if (metaflag == 0 || lstat(expdir, &statb) >= 0)
12331556Srgrimes			addfname(expdir);
12341556Srgrimes		return;
12351556Srgrimes	}
12361556Srgrimes	endname = p;
12371556Srgrimes	if (start != name) {
12381556Srgrimes		p = name;
12391556Srgrimes		while (p < start) {
124038887Stegge			while (*p == CTLQUOTEMARK)
124138887Stegge				p++;
12421556Srgrimes			if (*p == CTLESC)
12431556Srgrimes				p++;
12441556Srgrimes			*enddir++ = *p++;
1245211155Sjilles			if (enddir == expdir_end)
1246211155Sjilles				return;
12471556Srgrimes		}
12481556Srgrimes	}
12491556Srgrimes	if (enddir == expdir) {
12501556Srgrimes		p = ".";
12511556Srgrimes	} else if (enddir == expdir + 1 && *expdir == '/') {
12521556Srgrimes		p = "/";
12531556Srgrimes	} else {
12541556Srgrimes		p = expdir;
12551556Srgrimes		enddir[-1] = '\0';
12561556Srgrimes	}
12571556Srgrimes	if ((dirp = opendir(p)) == NULL)
12581556Srgrimes		return;
12591556Srgrimes	if (enddir != expdir)
12601556Srgrimes		enddir[-1] = '/';
12611556Srgrimes	if (*endname == 0) {
12621556Srgrimes		atend = 1;
12631556Srgrimes	} else {
12641556Srgrimes		atend = 0;
1265207944Sjilles		*endname = '\0';
1266207944Sjilles		endname += esc + 1;
12671556Srgrimes	}
12681556Srgrimes	matchdot = 0;
126938887Stegge	p = start;
127038887Stegge	while (*p == CTLQUOTEMARK)
127138887Stegge		p++;
127238887Stegge	if (*p == CTLESC)
127338887Stegge		p++;
127438887Stegge	if (*p == '.')
12751556Srgrimes		matchdot++;
12761556Srgrimes	while (! int_pending() && (dp = readdir(dirp)) != NULL) {
12771556Srgrimes		if (dp->d_name[0] == '.' && ! matchdot)
12781556Srgrimes			continue;
127945514Stegge		if (patmatch(start, dp->d_name, 0)) {
1280211155Sjilles			if (enddir + dp->d_namlen + 1 > expdir_end)
1281211155Sjilles				continue;
1282211155Sjilles			memcpy(enddir, dp->d_name, dp->d_namlen + 1);
1283211155Sjilles			if (atend)
12841556Srgrimes				addfname(expdir);
1285211155Sjilles			else {
1286211155Sjilles				if (enddir + dp->d_namlen + 2 > expdir_end)
128717987Speter					continue;
1288211155Sjilles				enddir[dp->d_namlen] = '/';
1289211155Sjilles				enddir[dp->d_namlen + 1] = '\0';
1290211155Sjilles				expmeta(enddir + dp->d_namlen + 1, endname);
12911556Srgrimes			}
12921556Srgrimes		}
12931556Srgrimes	}
12941556Srgrimes	closedir(dirp);
12951556Srgrimes	if (! atend)
1296207944Sjilles		endname[-esc - 1] = esc ? CTLESC : '/';
12971556Srgrimes}
12981556Srgrimes
12991556Srgrimes
13001556Srgrimes/*
13011556Srgrimes * Add a file name to the list.
13021556Srgrimes */
13031556Srgrimes
1304213811Sobrienstatic void
130590111Simpaddfname(char *name)
130690111Simp{
13071556Srgrimes	char *p;
13081556Srgrimes	struct strlist *sp;
13091556Srgrimes
13101556Srgrimes	p = stalloc(strlen(name) + 1);
13111556Srgrimes	scopy(name, p);
13121556Srgrimes	sp = (struct strlist *)stalloc(sizeof *sp);
13131556Srgrimes	sp->text = p;
13141556Srgrimes	*exparg.lastp = sp;
13151556Srgrimes	exparg.lastp = &sp->next;
13161556Srgrimes}
13171556Srgrimes
13181556Srgrimes
13191556Srgrimes/*
13201556Srgrimes * Sort the results of file name expansion.  It calculates the number of
13211556Srgrimes * strings to sort and then calls msort (short for merge sort) to do the
13221556Srgrimes * work.
13231556Srgrimes */
13241556Srgrimes
1325213811Sobrienstatic struct strlist *
132690111Simpexpsort(struct strlist *str)
132790111Simp{
13281556Srgrimes	int len;
13291556Srgrimes	struct strlist *sp;
13301556Srgrimes
13311556Srgrimes	len = 0;
13321556Srgrimes	for (sp = str ; sp ; sp = sp->next)
13331556Srgrimes		len++;
13341556Srgrimes	return msort(str, len);
13351556Srgrimes}
13361556Srgrimes
13371556Srgrimes
1338213811Sobrienstatic struct strlist *
133990111Simpmsort(struct strlist *list, int len)
134017987Speter{
134117987Speter	struct strlist *p, *q = NULL;
13421556Srgrimes	struct strlist **lpp;
13431556Srgrimes	int half;
13441556Srgrimes	int n;
13451556Srgrimes
13461556Srgrimes	if (len <= 1)
13471556Srgrimes		return list;
13488855Srgrimes	half = len >> 1;
13491556Srgrimes	p = list;
13501556Srgrimes	for (n = half ; --n >= 0 ; ) {
13511556Srgrimes		q = p;
13521556Srgrimes		p = p->next;
13531556Srgrimes	}
13541556Srgrimes	q->next = NULL;			/* terminate first half of list */
13551556Srgrimes	q = msort(list, half);		/* sort first half of list */
13561556Srgrimes	p = msort(p, len - half);		/* sort second half */
13571556Srgrimes	lpp = &list;
13581556Srgrimes	for (;;) {
13591556Srgrimes		if (strcmp(p->text, q->text) < 0) {
13601556Srgrimes			*lpp = p;
13611556Srgrimes			lpp = &p->next;
13621556Srgrimes			if ((p = *lpp) == NULL) {
13631556Srgrimes				*lpp = q;
13641556Srgrimes				break;
13651556Srgrimes			}
13661556Srgrimes		} else {
13671556Srgrimes			*lpp = q;
13681556Srgrimes			lpp = &q->next;
13691556Srgrimes			if ((q = *lpp) == NULL) {
13701556Srgrimes				*lpp = p;
13711556Srgrimes				break;
13721556Srgrimes			}
13731556Srgrimes		}
13741556Srgrimes	}
13751556Srgrimes	return list;
13761556Srgrimes}
13771556Srgrimes
13781556Srgrimes
13791556Srgrimes
13801556Srgrimes/*
13811556Srgrimes * Returns true if the pattern matches the string.
13821556Srgrimes */
13831556Srgrimes
13841556Srgrimesint
1385200956Sjillespatmatch(const char *pattern, const char *string, int squoted)
138690111Simp{
1387200956Sjilles	const char *p, *q;
138825233Ssteve	char c;
13891556Srgrimes
13901556Srgrimes	p = pattern;
13911556Srgrimes	q = string;
13921556Srgrimes	for (;;) {
13931556Srgrimes		switch (c = *p++) {
13941556Srgrimes		case '\0':
13951556Srgrimes			goto breakloop;
13961556Srgrimes		case CTLESC:
139745514Stegge			if (squoted && *q == CTLESC)
139845514Stegge				q++;
13991556Srgrimes			if (*q++ != *p++)
14001556Srgrimes				return 0;
14011556Srgrimes			break;
140238887Stegge		case CTLQUOTEMARK:
140338887Stegge			continue;
14041556Srgrimes		case '?':
140545514Stegge			if (squoted && *q == CTLESC)
140645514Stegge				q++;
14071556Srgrimes			if (*q++ == '\0')
14081556Srgrimes				return 0;
14091556Srgrimes			break;
14101556Srgrimes		case '*':
14111556Srgrimes			c = *p;
141238887Stegge			while (c == CTLQUOTEMARK || c == '*')
141338887Stegge				c = *++p;
141438887Stegge			if (c != CTLESC &&  c != CTLQUOTEMARK &&
141538887Stegge			    c != '?' && c != '*' && c != '[') {
14161556Srgrimes				while (*q != c) {
141745514Stegge					if (squoted && *q == CTLESC &&
141845514Stegge					    q[1] == c)
141945514Stegge						break;
14201556Srgrimes					if (*q == '\0')
14211556Srgrimes						return 0;
142245514Stegge					if (squoted && *q == CTLESC)
142345514Stegge						q++;
14241556Srgrimes					q++;
14251556Srgrimes				}
14261556Srgrimes			}
14271556Srgrimes			do {
1428211646Sjilles				if (patmatch(p, q, squoted))
14291556Srgrimes					return 1;
143045514Stegge				if (squoted && *q == CTLESC)
143145514Stegge					q++;
14321556Srgrimes			} while (*q++ != '\0');
14331556Srgrimes			return 0;
14341556Srgrimes		case '[': {
1435200956Sjilles			const char *endp;
14361556Srgrimes			int invert, found;
14371556Srgrimes			char chr;
14381556Srgrimes
14391556Srgrimes			endp = p;
144026488Sache			if (*endp == '!' || *endp == '^')
14411556Srgrimes				endp++;
14421556Srgrimes			for (;;) {
144338887Stegge				while (*endp == CTLQUOTEMARK)
144438887Stegge					endp++;
14451556Srgrimes				if (*endp == '\0')
14461556Srgrimes					goto dft;		/* no matching ] */
14471556Srgrimes				if (*endp == CTLESC)
14481556Srgrimes					endp++;
14491556Srgrimes				if (*++endp == ']')
14501556Srgrimes					break;
14511556Srgrimes			}
14521556Srgrimes			invert = 0;
145326488Sache			if (*p == '!' || *p == '^') {
14541556Srgrimes				invert++;
14551556Srgrimes				p++;
14561556Srgrimes			}
14571556Srgrimes			found = 0;
14581556Srgrimes			chr = *q++;
145945514Stegge			if (squoted && chr == CTLESC)
146045514Stegge				chr = *q++;
146117987Speter			if (chr == '\0')
146217987Speter				return 0;
14631556Srgrimes			c = *p++;
14641556Srgrimes			do {
146538887Stegge				if (c == CTLQUOTEMARK)
146638887Stegge					continue;
14671556Srgrimes				if (c == CTLESC)
14681556Srgrimes					c = *p++;
14691556Srgrimes				if (*p == '-' && p[1] != ']') {
14701556Srgrimes					p++;
147138887Stegge					while (*p == CTLQUOTEMARK)
147238887Stegge						p++;
14731556Srgrimes					if (*p == CTLESC)
14741556Srgrimes						p++;
147517557Sache					if (   collate_range_cmp(chr, c) >= 0
147617557Sache					    && collate_range_cmp(chr, *p) <= 0
147717525Sache					   )
14781556Srgrimes						found = 1;
14791556Srgrimes					p++;
14801556Srgrimes				} else {
14811556Srgrimes					if (chr == c)
14821556Srgrimes						found = 1;
14831556Srgrimes				}
14841556Srgrimes			} while ((c = *p++) != ']');
14851556Srgrimes			if (found == invert)
14861556Srgrimes				return 0;
14871556Srgrimes			break;
14881556Srgrimes		}
14891556Srgrimesdft:	        default:
149045514Stegge			if (squoted && *q == CTLESC)
149145514Stegge				q++;
14921556Srgrimes			if (*q++ != c)
14931556Srgrimes				return 0;
14941556Srgrimes			break;
14951556Srgrimes		}
14961556Srgrimes	}
14971556Srgrimesbreakloop:
14981556Srgrimes	if (*q != '\0')
14991556Srgrimes		return 0;
15001556Srgrimes	return 1;
15011556Srgrimes}
15021556Srgrimes
15031556Srgrimes
15041556Srgrimes
15051556Srgrimes/*
1506212243Sjilles * Remove any CTLESC and CTLQUOTEMARK characters from a string.
15071556Srgrimes */
15081556Srgrimes
15091556Srgrimesvoid
151090111Simprmescapes(char *str)
151138887Stegge{
151225233Ssteve	char *p, *q;
15131556Srgrimes
15141556Srgrimes	p = str;
1515214512Sjilles	while (*p != CTLESC && *p != CTLQUOTEMARK && *p != CTLQUOTEEND) {
15161556Srgrimes		if (*p++ == '\0')
15171556Srgrimes			return;
15181556Srgrimes	}
15191556Srgrimes	q = p;
15201556Srgrimes	while (*p) {
1521214512Sjilles		if (*p == CTLQUOTEMARK || *p == CTLQUOTEEND) {
152238887Stegge			p++;
152338887Stegge			continue;
152438887Stegge		}
15251556Srgrimes		if (*p == CTLESC)
15261556Srgrimes			p++;
15271556Srgrimes		*q++ = *p++;
15281556Srgrimes	}
15291556Srgrimes	*q = '\0';
15301556Srgrimes}
15311556Srgrimes
15321556Srgrimes
15331556Srgrimes
15341556Srgrimes/*
15351556Srgrimes * See if a pattern matches in a case statement.
15361556Srgrimes */
15371556Srgrimes
15381556Srgrimesint
1539200956Sjillescasematch(union node *pattern, const char *val)
154090111Simp{
15411556Srgrimes	struct stackmark smark;
15421556Srgrimes	int result;
15431556Srgrimes	char *p;
15441556Srgrimes
15451556Srgrimes	setstackmark(&smark);
15461556Srgrimes	argbackq = pattern->narg.backquote;
15471556Srgrimes	STARTSTACKSTR(expdest);
15481556Srgrimes	ifslastp = NULL;
15491556Srgrimes	argstr(pattern->narg.text, EXP_TILDE | EXP_CASE);
15501556Srgrimes	STPUTC('\0', expdest);
15511556Srgrimes	p = grabstackstr(expdest);
155245514Stegge	result = patmatch(p, val, 0);
15531556Srgrimes	popstackmark(&smark);
15541556Srgrimes	return result;
15551556Srgrimes}
155617987Speter
155717987Speter/*
155817987Speter * Our own itoa().
155917987Speter */
156017987Speter
1561213811Sobrienstatic char *
156290111Simpcvtnum(int num, char *buf)
156390111Simp{
156417987Speter	char temp[32];
156517987Speter	int neg = num < 0;
156617987Speter	char *p = temp + 31;
156717987Speter
156817987Speter	temp[31] = '\0';
156917987Speter
157017987Speter	do {
157117987Speter		*--p = num % 10 + '0';
157217987Speter	} while ((num /= 10) != 0);
157317987Speter
157417987Speter	if (neg)
157517987Speter		*--p = '-';
157617987Speter
1577215783Sjilles	STPUTS(p, buf);
157817987Speter	return buf;
157917987Speter}
1580108286Stjr
1581108286Stjr/*
1582108286Stjr * Do most of the work for wordexp(3).
1583108286Stjr */
1584108286Stjr
1585108286Stjrint
1586108286Stjrwordexpcmd(int argc, char **argv)
1587108286Stjr{
1588108286Stjr	size_t len;
1589108286Stjr	int i;
1590108286Stjr
1591108286Stjr	out1fmt("%08x", argc - 1);
1592108286Stjr	for (i = 1, len = 0; i < argc; i++)
1593108286Stjr		len += strlen(argv[i]);
1594108286Stjr	out1fmt("%08x", (int)len);
1595215567Sjilles	for (i = 1; i < argc; i++)
1596215567Sjilles		outbin(argv[i], strlen(argv[i]) + 1, out1);
1597108286Stjr        return (0);
1598108286Stjr}
1599