expand.c revision 213775
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 213775 2010-10-13 13:22:11Z jhb $");
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
9890111SimpSTATIC void argstr(char *, int);
9990111SimpSTATIC char *exptilde(char *, int);
10090111SimpSTATIC void expbackq(union node *, int, int);
10190111SimpSTATIC int subevalvar(char *, char *, int, int, int, int);
10290111SimpSTATIC char *evalvar(char *, int);
10390111SimpSTATIC int varisset(char *, int);
104164081SstefanfSTATIC void varvalue(char *, int, int, int);
10590111SimpSTATIC void recordregion(int, int, int);
106155301SschweikhSTATIC void removerecordregions(int);
10790111SimpSTATIC void ifsbreakup(char *, struct arglist *);
10890111SimpSTATIC void expandmeta(struct strlist *, int);
10990111SimpSTATIC void expmeta(char *, char *);
11090111SimpSTATIC void addfname(char *);
11190111SimpSTATIC struct strlist *expsort(struct strlist *);
11290111SimpSTATIC struct strlist *msort(struct strlist *, int);
11390111SimpSTATIC char *cvtnum(int, char *);
11490111SimpSTATIC int collate_range_cmp(int, int);
1151556Srgrimes
11690111SimpSTATIC 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 */
2131556SrgrimesSTATIC 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;
2191556Srgrimes
2201556Srgrimes	if (*p == '~' && (flag & (EXP_TILDE | EXP_VARTILDE)))
2211556Srgrimes		p = exptilde(p, flag);
2221556Srgrimes	for (;;) {
2231556Srgrimes		switch (c = *p++) {
2241556Srgrimes		case '\0':
225212243Sjilles		case CTLENDVAR:
2261556Srgrimes			goto breakloop;
22738887Stegge		case CTLQUOTEMARK:
22838887Stegge			/* "$@" syntax adherence hack */
22938887Stegge			if (p[0] == CTLVAR && p[2] == '@' && p[3] == '=')
23038887Stegge				break;
23139137Stegge			if ((flag & EXP_FULL) != 0)
23239137Stegge				STPUTC(c, expdest);
23338887Stegge			break;
2341556Srgrimes		case CTLESC:
2351556Srgrimes			if (quotes)
2361556Srgrimes				STPUTC(c, expdest);
2371556Srgrimes			c = *p++;
2381556Srgrimes			STPUTC(c, expdest);
2391556Srgrimes			break;
2401556Srgrimes		case CTLVAR:
2411556Srgrimes			p = evalvar(p, flag);
2421556Srgrimes			break;
2431556Srgrimes		case CTLBACKQ:
2441556Srgrimes		case CTLBACKQ|CTLQUOTE:
2451556Srgrimes			expbackq(argbackq->n, c & CTLQUOTE, flag);
2461556Srgrimes			argbackq = argbackq->next;
2471556Srgrimes			break;
2481556Srgrimes		case CTLENDARI:
2491556Srgrimes			expari(flag);
2501556Srgrimes			break;
2511556Srgrimes		case ':':
2521556Srgrimes		case '=':
2531556Srgrimes			/*
2541556Srgrimes			 * sort of a hack - expand tildes in variable
2551556Srgrimes			 * assignments (after the first '=' and after ':'s).
2561556Srgrimes			 */
2571556Srgrimes			STPUTC(c, expdest);
2581556Srgrimes			if (flag & EXP_VARTILDE && *p == '~') {
2591556Srgrimes				if (c == '=') {
2601556Srgrimes					if (firsteq)
2611556Srgrimes						firsteq = 0;
2621556Srgrimes					else
2631556Srgrimes						break;
2641556Srgrimes				}
2651556Srgrimes				p = exptilde(p, flag);
2661556Srgrimes			}
2671556Srgrimes			break;
2681556Srgrimes		default:
2691556Srgrimes			STPUTC(c, expdest);
2701556Srgrimes		}
2711556Srgrimes	}
2721556Srgrimesbreakloop:;
2731556Srgrimes}
2741556Srgrimes
275212243Sjilles/*
276212243Sjilles * Perform tilde expansion, placing the result in the stack string and
277212243Sjilles * returning the next position in the input string to process.
278212243Sjilles */
2791556SrgrimesSTATIC char *
28090111Simpexptilde(char *p, int flag)
28117987Speter{
2821556Srgrimes	char c, *startp = p;
2831556Srgrimes	struct passwd *pw;
2841556Srgrimes	char *home;
285108935Stjr	int quotes = flag & (EXP_FULL | EXP_CASE | EXP_REDIR);
2861556Srgrimes
28717987Speter	while ((c = *p) != '\0') {
2881556Srgrimes		switch(c) {
289200988Sjilles		case CTLESC: /* This means CTL* are always considered quoted. */
290200988Sjilles		case CTLVAR:
291200988Sjilles		case CTLBACKQ:
292200988Sjilles		case CTLBACKQ | CTLQUOTE:
293200988Sjilles		case CTLARI:
294200988Sjilles		case CTLENDARI:
29539137Stegge		case CTLQUOTEMARK:
29639137Stegge			return (startp);
2971556Srgrimes		case ':':
2981556Srgrimes			if (flag & EXP_VARTILDE)
2991556Srgrimes				goto done;
3001556Srgrimes			break;
3011556Srgrimes		case '/':
302206150Sjilles		case CTLENDVAR:
3031556Srgrimes			goto done;
3041556Srgrimes		}
3051556Srgrimes		p++;
3061556Srgrimes	}
3071556Srgrimesdone:
3081556Srgrimes	*p = '\0';
3091556Srgrimes	if (*(startp+1) == '\0') {
3101556Srgrimes		if ((home = lookupvar("HOME")) == NULL)
3111556Srgrimes			goto lose;
3121556Srgrimes	} else {
3131556Srgrimes		if ((pw = getpwnam(startp+1)) == NULL)
3141556Srgrimes			goto lose;
3151556Srgrimes		home = pw->pw_dir;
3161556Srgrimes	}
3171556Srgrimes	if (*home == '\0')
3181556Srgrimes		goto lose;
3191556Srgrimes	*p = c;
32017987Speter	while ((c = *home++) != '\0') {
32183675Stegge		if (quotes && SQSYNTAX[(int)c] == CCTL)
3221556Srgrimes			STPUTC(CTLESC, expdest);
3231556Srgrimes		STPUTC(c, expdest);
3241556Srgrimes	}
3251556Srgrimes	return (p);
3261556Srgrimeslose:
3271556Srgrimes	*p = c;
3281556Srgrimes	return (startp);
3291556Srgrimes}
3301556Srgrimes
3311556Srgrimes
332155301SschweikhSTATIC void
33390111Simpremoverecordregions(int endoff)
33438887Stegge{
33538887Stegge	if (ifslastp == NULL)
33638887Stegge		return;
33738887Stegge
33838887Stegge	if (ifsfirst.endoff > endoff) {
33938887Stegge		while (ifsfirst.next != NULL) {
34038887Stegge			struct ifsregion *ifsp;
34138887Stegge			INTOFF;
34238887Stegge			ifsp = ifsfirst.next->next;
34338887Stegge			ckfree(ifsfirst.next);
34438887Stegge			ifsfirst.next = ifsp;
34538887Stegge			INTON;
34638887Stegge		}
34738887Stegge		if (ifsfirst.begoff > endoff)
34838887Stegge			ifslastp = NULL;
34938887Stegge		else {
35038887Stegge			ifslastp = &ifsfirst;
35138887Stegge			ifsfirst.endoff = endoff;
35238887Stegge		}
35338887Stegge		return;
35438887Stegge	}
355155301Sschweikh
35638887Stegge	ifslastp = &ifsfirst;
35738887Stegge	while (ifslastp->next && ifslastp->next->begoff < endoff)
35838887Stegge		ifslastp=ifslastp->next;
35938887Stegge	while (ifslastp->next != NULL) {
36038887Stegge		struct ifsregion *ifsp;
36138887Stegge		INTOFF;
36238887Stegge		ifsp = ifslastp->next->next;
36338887Stegge		ckfree(ifslastp->next);
36438887Stegge		ifslastp->next = ifsp;
36538887Stegge		INTON;
36638887Stegge	}
36738887Stegge	if (ifslastp->endoff > endoff)
36838887Stegge		ifslastp->endoff = endoff;
36938887Stegge}
37038887Stegge
3711556Srgrimes/*
3721556Srgrimes * Expand arithmetic expression.  Backup to start of expression,
3731556Srgrimes * evaluate, place result in (backed up) result, adjust string position.
3741556Srgrimes */
3751556Srgrimesvoid
37690111Simpexpari(int flag)
37717987Speter{
378207206Sjilles	char *p, *q, *start;
379178631Sstefanf	arith_t result;
38038887Stegge	int begoff;
381108935Stjr	int quotes = flag & (EXP_FULL | EXP_CASE | EXP_REDIR);
38238887Stegge	int quoted;
3831556Srgrimes
3841556Srgrimes	/*
38546684Skris	 * This routine is slightly over-complicated for
3861556Srgrimes	 * efficiency.  First we make sure there is
3871556Srgrimes	 * enough space for the result, which may be bigger
388212243Sjilles	 * than the expression.  Next we
3891556Srgrimes	 * scan backwards looking for the start of arithmetic.  If the
3901556Srgrimes	 * next previous character is a CTLESC character, then we
3911556Srgrimes	 * have to rescan starting from the beginning since CTLESC
3928855Srgrimes	 * characters have to be processed left to right.
3931556Srgrimes	 */
394178631Sstefanf	CHECKSTRSPACE(DIGITS(result) - 2, expdest);
3958855Srgrimes	USTPUTC('\0', expdest);
3961556Srgrimes	start = stackblock();
39783676Stegge	p = expdest - 2;
39883676Stegge	while (p >= start && *p != CTLARI)
3991556Srgrimes		--p;
40083676Stegge	if (p < start || *p != CTLARI)
4011556Srgrimes		error("missing CTLARI (shouldn't happen)");
40283676Stegge	if (p > start && *(p - 1) == CTLESC)
4031556Srgrimes		for (p = start; *p != CTLARI; p++)
4041556Srgrimes			if (*p == CTLESC)
4051556Srgrimes				p++;
40638887Stegge
40738887Stegge	if (p[1] == '"')
40838887Stegge		quoted=1;
40938887Stegge	else
41038887Stegge		quoted=0;
41138887Stegge	begoff = p - start;
41238887Stegge	removerecordregions(begoff);
4131556Srgrimes	if (quotes)
41438887Stegge		rmescapes(p+2);
415207206Sjilles	q = grabstackstr(expdest);
41638887Stegge	result = arith(p+2);
417207206Sjilles	ungrabstackstr(q, expdest);
418178631Sstefanf	fmtstr(p, DIGITS(result), ARITH_FORMAT_STR, result);
4191556Srgrimes	while (*p++)
4201556Srgrimes		;
42138887Stegge	if (quoted == 0)
42238887Stegge		recordregion(begoff, p - 1 - start, 0);
4231556Srgrimes	result = expdest - p + 1;
4241556Srgrimes	STADJUST(-result, expdest);
4251556Srgrimes}
4261556Srgrimes
4271556Srgrimes
4281556Srgrimes/*
429212243Sjilles * Perform command substitution.
4301556Srgrimes */
4311556SrgrimesSTATIC void
43290111Simpexpbackq(union node *cmd, int quoted, int flag)
43317987Speter{
4341556Srgrimes	struct backcmd in;
4351556Srgrimes	int i;
4361556Srgrimes	char buf[128];
4371556Srgrimes	char *p;
4381556Srgrimes	char *dest = expdest;
4391556Srgrimes	struct ifsregion saveifs, *savelastp;
4401556Srgrimes	struct nodelist *saveargbackq;
4411556Srgrimes	char lastc;
4421556Srgrimes	int startloc = dest - stackblock();
4431556Srgrimes	char const *syntax = quoted? DQSYNTAX : BASESYNTAX;
4441556Srgrimes	int saveherefd;
445108935Stjr	int quotes = flag & (EXP_FULL | EXP_CASE | EXP_REDIR);
446115424Sfenner	int nnl;
4471556Srgrimes
4481556Srgrimes	INTOFF;
4491556Srgrimes	saveifs = ifsfirst;
4501556Srgrimes	savelastp = ifslastp;
4511556Srgrimes	saveargbackq = argbackq;
4528855Srgrimes	saveherefd = herefd;
4531556Srgrimes	herefd = -1;
4541556Srgrimes	p = grabstackstr(dest);
4551556Srgrimes	evalbackcmd(cmd, &in);
4561556Srgrimes	ungrabstackstr(p, dest);
4571556Srgrimes	ifsfirst = saveifs;
4581556Srgrimes	ifslastp = savelastp;
4591556Srgrimes	argbackq = saveargbackq;
4601556Srgrimes	herefd = saveherefd;
4611556Srgrimes
4621556Srgrimes	p = in.buf;
4631556Srgrimes	lastc = '\0';
464115424Sfenner	nnl = 0;
465115424Sfenner	/* Don't copy trailing newlines */
4661556Srgrimes	for (;;) {
4671556Srgrimes		if (--in.nleft < 0) {
4681556Srgrimes			if (in.fd < 0)
4691556Srgrimes				break;
4701556Srgrimes			while ((i = read(in.fd, buf, sizeof buf)) < 0 && errno == EINTR);
4711556Srgrimes			TRACE(("expbackq: read returns %d\n", i));
4721556Srgrimes			if (i <= 0)
4731556Srgrimes				break;
4741556Srgrimes			p = buf;
4751556Srgrimes			in.nleft = i - 1;
4761556Srgrimes		}
4771556Srgrimes		lastc = *p++;
4781556Srgrimes		if (lastc != '\0') {
47983675Stegge			if (quotes && syntax[(int)lastc] == CCTL)
4801556Srgrimes				STPUTC(CTLESC, dest);
481115424Sfenner			if (lastc == '\n') {
482115424Sfenner				nnl++;
483115424Sfenner			} else {
484115424Sfenner				while (nnl > 0) {
485115424Sfenner					nnl--;
486115424Sfenner					STPUTC('\n', dest);
487115424Sfenner				}
488115424Sfenner				STPUTC(lastc, dest);
489115424Sfenner			}
4901556Srgrimes		}
4911556Srgrimes	}
49217987Speter
4931556Srgrimes	if (in.fd >= 0)
4941556Srgrimes		close(in.fd);
4951556Srgrimes	if (in.buf)
4961556Srgrimes		ckfree(in.buf);
4971556Srgrimes	if (in.jp)
49845916Scracauer		exitstatus = waitforjob(in.jp, (int *)NULL);
4991556Srgrimes	if (quoted == 0)
5001556Srgrimes		recordregion(startloc, dest - stackblock(), 0);
501213775Sjhb	TRACE(("expbackq: size=%td: \"%.*s\"\n",
502213775Sjhb		((dest - stackblock()) - startloc),
503213775Sjhb		(int)((dest - stackblock()) - startloc),
5041556Srgrimes		stackblock() + startloc));
5051556Srgrimes	expdest = dest;
5061556Srgrimes	INTON;
5071556Srgrimes}
5081556Srgrimes
5091556Srgrimes
5101556Srgrimes
51117987SpeterSTATIC int
51290111Simpsubevalvar(char *p, char *str, int strloc, int subtype, int startloc,
51390111Simp  int varflags)
51417987Speter{
51517987Speter	char *startp;
51617987Speter	char *loc = NULL;
51745514Stegge	char *q;
51817987Speter	int c = 0;
51917987Speter	int saveherefd = herefd;
52017987Speter	struct nodelist *saveargbackq = argbackq;
52120425Ssteve	int amount;
52220425Ssteve
52317987Speter	herefd = -1;
524206150Sjilles	argstr(p, (subtype == VSTRIMLEFT || subtype == VSTRIMLEFTMAX ||
525206147Sjilles	    subtype == VSTRIMRIGHT || subtype == VSTRIMRIGHTMAX ?
526206150Sjilles	    EXP_CASE : 0) | EXP_TILDE);
52717987Speter	STACKSTRNUL(expdest);
52817987Speter	herefd = saveherefd;
52917987Speter	argbackq = saveargbackq;
53017987Speter	startp = stackblock() + startloc;
53120425Ssteve	if (str == NULL)
53220425Ssteve	    str = stackblock() + strloc;
53317987Speter
53417987Speter	switch (subtype) {
53517987Speter	case VSASSIGN:
53617987Speter		setvar(str, startp, 0);
53720425Ssteve		amount = startp - expdest;
53820425Ssteve		STADJUST(amount, expdest);
53917987Speter		varflags &= ~VSNUL;
54017987Speter		if (c != 0)
54117987Speter			*loc = c;
54217987Speter		return 1;
54317987Speter
54417987Speter	case VSQUESTION:
54517987Speter		if (*p != CTLENDVAR) {
546201366Sjilles			outfmt(out2, "%s\n", startp);
54717987Speter			error((char *)NULL);
54817987Speter		}
549112254Sru		error("%.*s: parameter %snot set", (int)(p - str - 1),
55017987Speter		      str, (varflags & VSNUL) ? "null or "
55117987Speter					      : nullstr);
55217987Speter		return 0;
55317987Speter
55417987Speter	case VSTRIMLEFT:
55525233Ssteve		for (loc = startp; loc < str; loc++) {
55617987Speter			c = *loc;
55717987Speter			*loc = '\0';
55845514Stegge			if (patmatch(str, startp, varflags & VSQUOTE)) {
55917987Speter				*loc = c;
56017987Speter				goto recordleft;
56117987Speter			}
56217987Speter			*loc = c;
56345514Stegge			if ((varflags & VSQUOTE) && *loc == CTLESC)
56445514Stegge				loc++;
56517987Speter		}
56617987Speter		return 0;
56717987Speter
56817987Speter	case VSTRIMLEFTMAX:
56945514Stegge		for (loc = str - 1; loc >= startp;) {
57017987Speter			c = *loc;
57117987Speter			*loc = '\0';
57245514Stegge			if (patmatch(str, startp, varflags & VSQUOTE)) {
57317987Speter				*loc = c;
57417987Speter				goto recordleft;
57517987Speter			}
57617987Speter			*loc = c;
57745514Stegge			loc--;
57845514Stegge			if ((varflags & VSQUOTE) && loc > startp &&
57945514Stegge			    *(loc - 1) == CTLESC) {
58045514Stegge				for (q = startp; q < loc; q++)
58145514Stegge					if (*q == CTLESC)
58245514Stegge						q++;
58345514Stegge				if (q > loc)
58445514Stegge					loc--;
58545514Stegge			}
58617987Speter		}
58717987Speter		return 0;
58817987Speter
58917987Speter	case VSTRIMRIGHT:
59045514Stegge		for (loc = str - 1; loc >= startp;) {
59145514Stegge			if (patmatch(str, loc, varflags & VSQUOTE)) {
59220425Ssteve				amount = loc - expdest;
59320425Ssteve				STADJUST(amount, expdest);
59417987Speter				return 1;
59517987Speter			}
59645514Stegge			loc--;
59745514Stegge			if ((varflags & VSQUOTE) && loc > startp &&
598155301Sschweikh			    *(loc - 1) == CTLESC) {
59945514Stegge				for (q = startp; q < loc; q++)
60045514Stegge					if (*q == CTLESC)
60145514Stegge						q++;
60245514Stegge				if (q > loc)
60345514Stegge					loc--;
60445514Stegge			}
60517987Speter		}
60617987Speter		return 0;
60717987Speter
60817987Speter	case VSTRIMRIGHTMAX:
60917987Speter		for (loc = startp; loc < str - 1; loc++) {
61045514Stegge			if (patmatch(str, loc, varflags & VSQUOTE)) {
61120425Ssteve				amount = loc - expdest;
61220425Ssteve				STADJUST(amount, expdest);
61317987Speter				return 1;
61417987Speter			}
61545514Stegge			if ((varflags & VSQUOTE) && *loc == CTLESC)
61645514Stegge				loc++;
61717987Speter		}
61817987Speter		return 0;
61917987Speter
62017987Speter
62117987Speter	default:
62217987Speter		abort();
62317987Speter	}
62417987Speter
62517987Speterrecordleft:
62620425Ssteve	amount = ((str - 1) - (loc - startp)) - expdest;
62720425Ssteve	STADJUST(amount, expdest);
62817987Speter	while (loc != str - 1)
62917987Speter		*startp++ = *loc++;
63017987Speter	return 1;
63117987Speter}
63217987Speter
63317987Speter
6341556Srgrimes/*
6351556Srgrimes * Expand a variable, and return a pointer to the next character in the
6361556Srgrimes * input string.
6371556Srgrimes */
6381556Srgrimes
6391556SrgrimesSTATIC char *
64090111Simpevalvar(char *p, int flag)
64117987Speter{
6421556Srgrimes	int subtype;
6431556Srgrimes	int varflags;
6441556Srgrimes	char *var;
6451556Srgrimes	char *val;
64645644Stegge	int patloc;
6471556Srgrimes	int c;
6481556Srgrimes	int set;
6491556Srgrimes	int special;
6501556Srgrimes	int startloc;
65117987Speter	int varlen;
65217987Speter	int easy;
653108935Stjr	int quotes = flag & (EXP_FULL | EXP_CASE | EXP_REDIR);
6541556Srgrimes
655164081Sstefanf	varflags = (unsigned char)*p++;
6561556Srgrimes	subtype = varflags & VSTYPE;
6571556Srgrimes	var = p;
6581556Srgrimes	special = 0;
6591556Srgrimes	if (! is_name(*p))
6601556Srgrimes		special = 1;
6611556Srgrimes	p = strchr(p, '=') + 1;
6621556Srgrimesagain: /* jump here after setting a variable with ${var=text} */
663179022Sstefanf	if (varflags & VSLINENO) {
664179022Sstefanf		set = 1;
665179022Sstefanf		special = 0;
666179022Sstefanf		val = var;
667179022Sstefanf		p[-1] = '\0';	/* temporarily overwrite '=' to have \0
668179022Sstefanf				   terminated string */
669179022Sstefanf	} else if (special) {
67025233Ssteve		set = varisset(var, varflags & VSNUL);
6711556Srgrimes		val = NULL;
6721556Srgrimes	} else {
67360592Scracauer		val = bltinlookup(var, 1);
67417987Speter		if (val == NULL || ((varflags & VSNUL) && val[0] == '\0')) {
6751556Srgrimes			val = NULL;
6761556Srgrimes			set = 0;
6771556Srgrimes		} else
6781556Srgrimes			set = 1;
6791556Srgrimes	}
68017987Speter	varlen = 0;
6811556Srgrimes	startloc = expdest - stackblock();
682198454Sjilles	if (!set && uflag && *var != '@' && *var != '*') {
68396939Stjr		switch (subtype) {
68496939Stjr		case VSNORMAL:
68596939Stjr		case VSTRIMLEFT:
68696939Stjr		case VSTRIMLEFTMAX:
68796939Stjr		case VSTRIMRIGHT:
68896939Stjr		case VSTRIMRIGHTMAX:
68996939Stjr		case VSLENGTH:
690112254Sru			error("%.*s: parameter not set", (int)(p - var - 1),
691112254Sru			    var);
69296939Stjr		}
69396939Stjr	}
6941556Srgrimes	if (set && subtype != VSPLUS) {
6951556Srgrimes		/* insert the value of the variable */
6961556Srgrimes		if (special) {
697164081Sstefanf			varvalue(var, varflags & VSQUOTE, subtype, flag);
69817987Speter			if (subtype == VSLENGTH) {
69925233Ssteve				varlen = expdest - stackblock() - startloc;
70025233Ssteve				STADJUST(-varlen, expdest);
70117987Speter			}
7021556Srgrimes		} else {
70320425Ssteve			char const *syntax = (varflags & VSQUOTE) ? DQSYNTAX
70417987Speter								  : BASESYNTAX;
7051556Srgrimes
70617987Speter			if (subtype == VSLENGTH) {
70717987Speter				for (;*val; val++)
70817987Speter					varlen++;
7091556Srgrimes			}
71017987Speter			else {
71117987Speter				while (*val) {
71283675Stegge					if (quotes &&
71354132Scracauer					    syntax[(int)*val] == CCTL)
71417987Speter						STPUTC(CTLESC, expdest);
71517987Speter					STPUTC(*val++, expdest);
71617987Speter				}
71717987Speter
71817987Speter			}
7191556Srgrimes		}
7201556Srgrimes	}
72120425Ssteve
7221556Srgrimes	if (subtype == VSPLUS)
7231556Srgrimes		set = ! set;
72417987Speter
72520425Ssteve	easy = ((varflags & VSQUOTE) == 0 ||
72617987Speter		(*var == '@' && shellparam.nparam != 1));
72717987Speter
72817987Speter
72917987Speter	switch (subtype) {
73017987Speter	case VSLENGTH:
73117987Speter		expdest = cvtnum(varlen, expdest);
73217987Speter		goto record;
73317987Speter
73417987Speter	case VSNORMAL:
73517987Speter		if (!easy)
73617987Speter			break;
73717987Speterrecord:
73820425Ssteve		recordregion(startloc, expdest - stackblock(),
73917987Speter			     varflags & VSQUOTE);
74017987Speter		break;
74117987Speter
74217987Speter	case VSPLUS:
74317987Speter	case VSMINUS:
74417987Speter		if (!set) {
7451556Srgrimes			argstr(p, flag);
74617987Speter			break;
74717987Speter		}
74817987Speter		if (easy)
74917987Speter			goto record;
75017987Speter		break;
75117987Speter
75217987Speter	case VSTRIMLEFT:
75317987Speter	case VSTRIMLEFTMAX:
75417987Speter	case VSTRIMRIGHT:
75517987Speter	case VSTRIMRIGHTMAX:
75617987Speter		if (!set)
75717987Speter			break;
75817987Speter		/*
75917987Speter		 * Terminate the string and start recording the pattern
76017987Speter		 * right after it
76117987Speter		 */
76217987Speter		STPUTC('\0', expdest);
76345644Stegge		patloc = expdest - stackblock();
76445644Stegge		if (subevalvar(p, NULL, patloc, subtype,
76538887Stegge			       startloc, varflags) == 0) {
76645644Stegge			int amount = (expdest - stackblock() - patloc) + 1;
76725233Ssteve			STADJUST(-amount, expdest);
76825233Ssteve		}
76938887Stegge		/* Remove any recorded regions beyond start of variable */
77038887Stegge		removerecordregions(startloc);
77138887Stegge		goto record;
77217987Speter
77317987Speter	case VSASSIGN:
77417987Speter	case VSQUESTION:
77517987Speter		if (!set) {
77620425Ssteve			if (subevalvar(p, var, 0, subtype, startloc, varflags)) {
77720425Ssteve				varflags &= ~VSNUL;
778155301Sschweikh				/*
779155301Sschweikh				 * Remove any recorded regions beyond
780155301Sschweikh				 * start of variable
78138887Stegge				 */
78238887Stegge				removerecordregions(startloc);
7831556Srgrimes				goto again;
78420425Ssteve			}
78517987Speter			break;
7861556Srgrimes		}
78717987Speter		if (easy)
78817987Speter			goto record;
78917987Speter		break;
79017987Speter
791164003Sstefanf	case VSERROR:
792164003Sstefanf		c = p - var - 1;
793164003Sstefanf		error("${%.*s%s}: Bad substitution", c, var,
794164003Sstefanf		    (c > 0 && *p != CTLENDVAR) ? "..." : "");
795164003Sstefanf
79617987Speter	default:
79717987Speter		abort();
7981556Srgrimes	}
799179022Sstefanf	p[-1] = '=';	/* recover overwritten '=' */
80017987Speter
8011556Srgrimes	if (subtype != VSNORMAL) {	/* skip to end of alternative */
8021556Srgrimes		int nesting = 1;
8031556Srgrimes		for (;;) {
8041556Srgrimes			if ((c = *p++) == CTLESC)
8051556Srgrimes				p++;
8061556Srgrimes			else if (c == CTLBACKQ || c == (CTLBACKQ|CTLQUOTE)) {
8071556Srgrimes				if (set)
8081556Srgrimes					argbackq = argbackq->next;
8091556Srgrimes			} else if (c == CTLVAR) {
8101556Srgrimes				if ((*p++ & VSTYPE) != VSNORMAL)
8111556Srgrimes					nesting++;
8121556Srgrimes			} else if (c == CTLENDVAR) {
8131556Srgrimes				if (--nesting == 0)
8141556Srgrimes					break;
8151556Srgrimes			}
8161556Srgrimes		}
8171556Srgrimes	}
8181556Srgrimes	return p;
8191556Srgrimes}
8201556Srgrimes
8211556Srgrimes
8221556Srgrimes
8231556Srgrimes/*
8241556Srgrimes * Test whether a specialized variable is set.
8251556Srgrimes */
8261556Srgrimes
8271556SrgrimesSTATIC int
82890111Simpvarisset(char *name, int nulok)
82925233Ssteve{
8301556Srgrimes
83125233Ssteve	if (*name == '!')
832209600Sjilles		return backgndpidset();
83325233Ssteve	else if (*name == '@' || *name == '*') {
8341556Srgrimes		if (*shellparam.p == NULL)
8351556Srgrimes			return 0;
83625233Ssteve
83725233Ssteve		if (nulok) {
83825233Ssteve			char **av;
83925233Ssteve
84025233Ssteve			for (av = shellparam.p; *av; av++)
84125233Ssteve				if (**av != '\0')
84225233Ssteve					return 1;
84325233Ssteve			return 0;
84425233Ssteve		}
84518202Speter	} else if (is_digit(*name)) {
84625233Ssteve		char *ap;
84720425Ssteve		int num = atoi(name);
84825233Ssteve
84925233Ssteve		if (num > shellparam.nparam)
85025233Ssteve			return 0;
85125233Ssteve
85225233Ssteve		if (num == 0)
85325233Ssteve			ap = arg0;
85425233Ssteve		else
85525233Ssteve			ap = shellparam.p[num - 1];
85625233Ssteve
85725233Ssteve		if (nulok && (ap == NULL || *ap == '\0'))
85825233Ssteve			return 0;
8591556Srgrimes	}
8601556Srgrimes	return 1;
8611556Srgrimes}
8621556Srgrimes
8631556Srgrimes
8641556Srgrimes
8651556Srgrimes/*
8661556Srgrimes * Add the value of a specialized variable to the stack string.
8671556Srgrimes */
8681556Srgrimes
8691556SrgrimesSTATIC void
870164081Sstefanfvarvalue(char *name, int quoted, int subtype, int flag)
87117987Speter{
8721556Srgrimes	int num;
8731556Srgrimes	char *p;
8741556Srgrimes	int i;
8751556Srgrimes	char sep;
8761556Srgrimes	char **ap;
8771556Srgrimes	char const *syntax;
8781556Srgrimes
8791556Srgrimes#define STRTODEST(p) \
8801556Srgrimes	do {\
881164081Sstefanf	if (flag & (EXP_FULL | EXP_CASE) && subtype != VSLENGTH) { \
8821556Srgrimes		syntax = quoted? DQSYNTAX : BASESYNTAX; \
8831556Srgrimes		while (*p) { \
88483675Stegge			if (syntax[(int)*p] == CCTL) \
8851556Srgrimes				STPUTC(CTLESC, expdest); \
8861556Srgrimes			STPUTC(*p++, expdest); \
8871556Srgrimes		} \
8881556Srgrimes	} else \
8891556Srgrimes		while (*p) \
8901556Srgrimes			STPUTC(*p++, expdest); \
8911556Srgrimes	} while (0)
8921556Srgrimes
8931556Srgrimes
89418202Speter	switch (*name) {
8951556Srgrimes	case '$':
8961556Srgrimes		num = rootpid;
8971556Srgrimes		goto numvar;
8981556Srgrimes	case '?':
89917987Speter		num = oexitstatus;
9001556Srgrimes		goto numvar;
9011556Srgrimes	case '#':
9021556Srgrimes		num = shellparam.nparam;
9031556Srgrimes		goto numvar;
9041556Srgrimes	case '!':
905209600Sjilles		num = backgndpidval();
9061556Srgrimesnumvar:
90717987Speter		expdest = cvtnum(num, expdest);
9081556Srgrimes		break;
9091556Srgrimes	case '-':
9101556Srgrimes		for (i = 0 ; i < NOPTS ; i++) {
9111556Srgrimes			if (optlist[i].val)
9121556Srgrimes				STPUTC(optlist[i].letter, expdest);
9131556Srgrimes		}
9141556Srgrimes		break;
9151556Srgrimes	case '@':
916164081Sstefanf		if (flag & EXP_FULL && quoted) {
91738887Stegge			for (ap = shellparam.p ; (p = *ap++) != NULL ; ) {
91838887Stegge				STRTODEST(p);
91938887Stegge				if (*ap)
92038887Stegge					STPUTC('\0', expdest);
92138887Stegge			}
92238887Stegge			break;
9231556Srgrimes		}
924102410Scharnier		/* FALLTHROUGH */
9251556Srgrimes	case '*':
926149825Srse		if (ifsset())
92738887Stegge			sep = ifsval()[0];
92838887Stegge		else
92938887Stegge			sep = ' ';
9301556Srgrimes		for (ap = shellparam.p ; (p = *ap++) != NULL ; ) {
9311556Srgrimes			STRTODEST(p);
93238887Stegge			if (*ap && sep)
9331556Srgrimes				STPUTC(sep, expdest);
9341556Srgrimes		}
9351556Srgrimes		break;
9361556Srgrimes	case '0':
9371556Srgrimes		p = arg0;
9381556Srgrimes		STRTODEST(p);
9391556Srgrimes		break;
9401556Srgrimes	default:
94118202Speter		if (is_digit(*name)) {
94218202Speter			num = atoi(name);
94318202Speter			if (num > 0 && num <= shellparam.nparam) {
94418202Speter				p = shellparam.p[num - 1];
94518202Speter				STRTODEST(p);
94618202Speter			}
9471556Srgrimes		}
9481556Srgrimes		break;
9491556Srgrimes	}
9501556Srgrimes}
9511556Srgrimes
9521556Srgrimes
9531556Srgrimes
9541556Srgrimes/*
9551556Srgrimes * Record the the fact that we have to scan this region of the
9561556Srgrimes * string for IFS characters.
9571556Srgrimes */
9581556Srgrimes
9591556SrgrimesSTATIC void
960194975Sjillesrecordregion(int start, int end, int inquotes)
96117987Speter{
96225233Ssteve	struct ifsregion *ifsp;
9631556Srgrimes
9641556Srgrimes	if (ifslastp == NULL) {
9651556Srgrimes		ifsp = &ifsfirst;
9661556Srgrimes	} else {
967194975Sjilles		if (ifslastp->endoff == start
968194975Sjilles		    && ifslastp->inquotes == inquotes) {
969194975Sjilles			/* extend previous area */
970194975Sjilles			ifslastp->endoff = end;
971194975Sjilles			return;
972194975Sjilles		}
9731556Srgrimes		ifsp = (struct ifsregion *)ckmalloc(sizeof (struct ifsregion));
9741556Srgrimes		ifslastp->next = ifsp;
9751556Srgrimes	}
9761556Srgrimes	ifslastp = ifsp;
9771556Srgrimes	ifslastp->next = NULL;
9781556Srgrimes	ifslastp->begoff = start;
9791556Srgrimes	ifslastp->endoff = end;
980194975Sjilles	ifslastp->inquotes = inquotes;
9811556Srgrimes}
9821556Srgrimes
9831556Srgrimes
9841556Srgrimes
9851556Srgrimes/*
9861556Srgrimes * Break the argument string into pieces based upon IFS and add the
9871556Srgrimes * strings to the argument list.  The regions of the string to be
9881556Srgrimes * searched for IFS characters have been stored by recordregion.
989212243Sjilles * CTLESC characters are preserved but have little effect in this pass
990212243Sjilles * other than escaping CTL* characters.  In particular, they do not escape
991212243Sjilles * IFS characters: that should be done with the ifsregion mechanism.
992212243Sjilles * CTLQUOTEMARK characters are used to preserve empty quoted strings.
993212243Sjilles * This pass treats them as a regular character, making the string non-empty.
994212243Sjilles * Later, they are removed along with the other CTL* characters.
9951556Srgrimes */
9961556SrgrimesSTATIC void
99790111Simpifsbreakup(char *string, struct arglist *arglist)
99890111Simp{
9991556Srgrimes	struct ifsregion *ifsp;
10001556Srgrimes	struct strlist *sp;
10011556Srgrimes	char *start;
100225233Ssteve	char *p;
10031556Srgrimes	char *q;
1004201053Sjilles	const char *ifs;
1005194975Sjilles	const char *ifsspc;
1006194975Sjilles	int had_param_ch = 0;
10071556Srgrimes
1008194975Sjilles	start = string;
100917987Speter
1010194975Sjilles	if (ifslastp == NULL) {
1011194975Sjilles		/* Return entire argument, IFS doesn't apply to any of it */
1012194975Sjilles		sp = (struct strlist *)stalloc(sizeof *sp);
1013194975Sjilles		sp->text = start;
1014194975Sjilles		*arglist->lastp = sp;
1015194975Sjilles		arglist->lastp = &sp->next;
1016194975Sjilles		return;
1017194975Sjilles	}
1018194975Sjilles
1019194975Sjilles	ifs = ifsset() ? ifsval() : " \t\n";
1020194975Sjilles
1021194975Sjilles	for (ifsp = &ifsfirst; ifsp != NULL; ifsp = ifsp->next) {
1022194975Sjilles		p = string + ifsp->begoff;
1023194975Sjilles		while (p < string + ifsp->endoff) {
1024194975Sjilles			q = p;
1025194975Sjilles			if (*p == CTLESC)
1026194975Sjilles				p++;
1027194975Sjilles			if (ifsp->inquotes) {
1028194975Sjilles				/* Only NULs (should be from "$@") end args */
1029194977Sjilles				had_param_ch = 1;
1030194975Sjilles				if (*p != 0) {
10311556Srgrimes					p++;
1032194975Sjilles					continue;
1033194975Sjilles				}
1034194975Sjilles				ifsspc = NULL;
1035194975Sjilles			} else {
1036194975Sjilles				if (!strchr(ifs, *p)) {
1037194977Sjilles					had_param_ch = 1;
103838887Stegge					p++;
1039194975Sjilles					continue;
1040194975Sjilles				}
1041194975Sjilles				ifsspc = strchr(" \t\n", *p);
1042194975Sjilles
1043194975Sjilles				/* Ignore IFS whitespace at start */
1044194975Sjilles				if (q == start && ifsspc != NULL) {
1045194975Sjilles					p++;
10461556Srgrimes					start = p;
1047194975Sjilles					continue;
1048194975Sjilles				}
1049194977Sjilles				had_param_ch = 0;
10501556Srgrimes			}
1051194975Sjilles
1052194975Sjilles			/* Save this argument... */
1053194975Sjilles			*q = '\0';
10541556Srgrimes			sp = (struct strlist *)stalloc(sizeof *sp);
10551556Srgrimes			sp->text = start;
10561556Srgrimes			*arglist->lastp = sp;
10571556Srgrimes			arglist->lastp = &sp->next;
1058194975Sjilles			p++;
1059194975Sjilles
1060194975Sjilles			if (ifsspc != NULL) {
1061194975Sjilles				/* Ignore further trailing IFS whitespace */
1062194975Sjilles				for (; p < string + ifsp->endoff; p++) {
1063194975Sjilles					q = p;
1064194975Sjilles					if (*p == CTLESC)
1065194975Sjilles						p++;
1066194975Sjilles					if (strchr(ifs, *p) == NULL) {
1067194975Sjilles						p = q;
1068194975Sjilles						break;
1069194975Sjilles					}
1070194975Sjilles					if (strchr(" \t\n", *p) == NULL) {
1071194975Sjilles						p++;
1072194975Sjilles						break;
1073194975Sjilles					}
1074194975Sjilles				}
1075194975Sjilles			}
1076194975Sjilles			start = p;
10771556Srgrimes		}
1078194975Sjilles	}
1079194975Sjilles
1080194975Sjilles	/*
1081194975Sjilles	 * Save anything left as an argument.
1082194975Sjilles	 * Traditionally we have treated 'IFS=':'; set -- x$IFS' as
1083194975Sjilles	 * generating 2 arguments, the second of which is empty.
1084194975Sjilles	 * Some recent clarification of the Posix spec say that it
1085194975Sjilles	 * should only generate one....
1086194975Sjilles	 */
1087194975Sjilles	if (had_param_ch || *start != 0) {
10881556Srgrimes		sp = (struct strlist *)stalloc(sizeof *sp);
10891556Srgrimes		sp->text = start;
10901556Srgrimes		*arglist->lastp = sp;
10911556Srgrimes		arglist->lastp = &sp->next;
10921556Srgrimes	}
10931556Srgrimes}
10941556Srgrimes
10951556Srgrimes
1096213760Sobrienstatic char expdir[PATH_MAX];
1097212243Sjilles#define expdir_end (expdir + sizeof(expdir))
10981556Srgrimes
10991556Srgrimes/*
1100212243Sjilles * Perform pathname generation and remove control characters.
1101212243Sjilles * At this point, the only control characters should be CTLESC and CTLQUOTEMARK.
1102212243Sjilles * The results are stored in the list exparg.
11031556Srgrimes */
11041556SrgrimesSTATIC void
110590111Simpexpandmeta(struct strlist *str, int flag __unused)
110617987Speter{
11071556Srgrimes	char *p;
11081556Srgrimes	struct strlist **savelastp;
11091556Srgrimes	struct strlist *sp;
11101556Srgrimes	char c;
11111556Srgrimes	/* TODO - EXP_REDIR */
11121556Srgrimes
11131556Srgrimes	while (str) {
11141556Srgrimes		if (fflag)
11151556Srgrimes			goto nometa;
11161556Srgrimes		p = str->text;
11171556Srgrimes		for (;;) {			/* fast check for meta chars */
11181556Srgrimes			if ((c = *p++) == '\0')
11191556Srgrimes				goto nometa;
1120211646Sjilles			if (c == '*' || c == '?' || c == '[')
11211556Srgrimes				break;
11221556Srgrimes		}
11231556Srgrimes		savelastp = exparg.lastp;
11241556Srgrimes		INTOFF;
11251556Srgrimes		expmeta(expdir, str->text);
11261556Srgrimes		INTON;
11271556Srgrimes		if (exparg.lastp == savelastp) {
11288855Srgrimes			/*
11298855Srgrimes			 * no matches
11301556Srgrimes			 */
11311556Srgrimesnometa:
11321556Srgrimes			*exparg.lastp = str;
11331556Srgrimes			rmescapes(str->text);
11341556Srgrimes			exparg.lastp = &str->next;
11351556Srgrimes		} else {
11361556Srgrimes			*exparg.lastp = NULL;
11371556Srgrimes			*savelastp = sp = expsort(*savelastp);
11381556Srgrimes			while (sp->next != NULL)
11391556Srgrimes				sp = sp->next;
11401556Srgrimes			exparg.lastp = &sp->next;
11411556Srgrimes		}
11421556Srgrimes		str = str->next;
11431556Srgrimes	}
11441556Srgrimes}
11451556Srgrimes
11461556Srgrimes
11471556Srgrimes/*
11481556Srgrimes * Do metacharacter (i.e. *, ?, [...]) expansion.
11491556Srgrimes */
11501556Srgrimes
11511556SrgrimesSTATIC void
115290111Simpexpmeta(char *enddir, char *name)
115390111Simp{
115425233Ssteve	char *p;
11551556Srgrimes	char *q;
11561556Srgrimes	char *start;
11571556Srgrimes	char *endname;
11581556Srgrimes	int metaflag;
11591556Srgrimes	struct stat statb;
11601556Srgrimes	DIR *dirp;
11611556Srgrimes	struct dirent *dp;
11621556Srgrimes	int atend;
11631556Srgrimes	int matchdot;
1164207944Sjilles	int esc;
11651556Srgrimes
11661556Srgrimes	metaflag = 0;
11671556Srgrimes	start = name;
1168207944Sjilles	for (p = name; esc = 0, *p; p += esc + 1) {
11691556Srgrimes		if (*p == '*' || *p == '?')
11701556Srgrimes			metaflag = 1;
11711556Srgrimes		else if (*p == '[') {
11721556Srgrimes			q = p + 1;
117326488Sache			if (*q == '!' || *q == '^')
11741556Srgrimes				q++;
11751556Srgrimes			for (;;) {
117638887Stegge				while (*q == CTLQUOTEMARK)
117738887Stegge					q++;
11781556Srgrimes				if (*q == CTLESC)
11791556Srgrimes					q++;
11801556Srgrimes				if (*q == '/' || *q == '\0')
11811556Srgrimes					break;
11821556Srgrimes				if (*++q == ']') {
11831556Srgrimes					metaflag = 1;
11841556Srgrimes					break;
11851556Srgrimes				}
11861556Srgrimes			}
11871556Srgrimes		} else if (*p == '\0')
11881556Srgrimes			break;
118938887Stegge		else if (*p == CTLQUOTEMARK)
119038887Stegge			continue;
1191207944Sjilles		else {
1192207944Sjilles			if (*p == CTLESC)
1193207944Sjilles				esc++;
1194207944Sjilles			if (p[esc] == '/') {
1195207944Sjilles				if (metaflag)
1196207944Sjilles					break;
1197207944Sjilles				start = p + esc + 1;
1198207944Sjilles			}
11991556Srgrimes		}
12001556Srgrimes	}
12011556Srgrimes	if (metaflag == 0) {	/* we've reached the end of the file name */
12021556Srgrimes		if (enddir != expdir)
12031556Srgrimes			metaflag++;
12041556Srgrimes		for (p = name ; ; p++) {
120538887Stegge			if (*p == CTLQUOTEMARK)
120638887Stegge				continue;
12071556Srgrimes			if (*p == CTLESC)
12081556Srgrimes				p++;
12091556Srgrimes			*enddir++ = *p;
12101556Srgrimes			if (*p == '\0')
12111556Srgrimes				break;
1212211155Sjilles			if (enddir == expdir_end)
1213211155Sjilles				return;
12141556Srgrimes		}
1215147812Sdelphij		if (metaflag == 0 || lstat(expdir, &statb) >= 0)
12161556Srgrimes			addfname(expdir);
12171556Srgrimes		return;
12181556Srgrimes	}
12191556Srgrimes	endname = p;
12201556Srgrimes	if (start != name) {
12211556Srgrimes		p = name;
12221556Srgrimes		while (p < start) {
122338887Stegge			while (*p == CTLQUOTEMARK)
122438887Stegge				p++;
12251556Srgrimes			if (*p == CTLESC)
12261556Srgrimes				p++;
12271556Srgrimes			*enddir++ = *p++;
1228211155Sjilles			if (enddir == expdir_end)
1229211155Sjilles				return;
12301556Srgrimes		}
12311556Srgrimes	}
12321556Srgrimes	if (enddir == expdir) {
12331556Srgrimes		p = ".";
12341556Srgrimes	} else if (enddir == expdir + 1 && *expdir == '/') {
12351556Srgrimes		p = "/";
12361556Srgrimes	} else {
12371556Srgrimes		p = expdir;
12381556Srgrimes		enddir[-1] = '\0';
12391556Srgrimes	}
12401556Srgrimes	if ((dirp = opendir(p)) == NULL)
12411556Srgrimes		return;
12421556Srgrimes	if (enddir != expdir)
12431556Srgrimes		enddir[-1] = '/';
12441556Srgrimes	if (*endname == 0) {
12451556Srgrimes		atend = 1;
12461556Srgrimes	} else {
12471556Srgrimes		atend = 0;
1248207944Sjilles		*endname = '\0';
1249207944Sjilles		endname += esc + 1;
12501556Srgrimes	}
12511556Srgrimes	matchdot = 0;
125238887Stegge	p = start;
125338887Stegge	while (*p == CTLQUOTEMARK)
125438887Stegge		p++;
125538887Stegge	if (*p == CTLESC)
125638887Stegge		p++;
125738887Stegge	if (*p == '.')
12581556Srgrimes		matchdot++;
12591556Srgrimes	while (! int_pending() && (dp = readdir(dirp)) != NULL) {
12601556Srgrimes		if (dp->d_name[0] == '.' && ! matchdot)
12611556Srgrimes			continue;
126245514Stegge		if (patmatch(start, dp->d_name, 0)) {
1263211155Sjilles			if (enddir + dp->d_namlen + 1 > expdir_end)
1264211155Sjilles				continue;
1265211155Sjilles			memcpy(enddir, dp->d_name, dp->d_namlen + 1);
1266211155Sjilles			if (atend)
12671556Srgrimes				addfname(expdir);
1268211155Sjilles			else {
1269211155Sjilles				if (enddir + dp->d_namlen + 2 > expdir_end)
127017987Speter					continue;
1271211155Sjilles				enddir[dp->d_namlen] = '/';
1272211155Sjilles				enddir[dp->d_namlen + 1] = '\0';
1273211155Sjilles				expmeta(enddir + dp->d_namlen + 1, endname);
12741556Srgrimes			}
12751556Srgrimes		}
12761556Srgrimes	}
12771556Srgrimes	closedir(dirp);
12781556Srgrimes	if (! atend)
1279207944Sjilles		endname[-esc - 1] = esc ? CTLESC : '/';
12801556Srgrimes}
12811556Srgrimes
12821556Srgrimes
12831556Srgrimes/*
12841556Srgrimes * Add a file name to the list.
12851556Srgrimes */
12861556Srgrimes
12871556SrgrimesSTATIC void
128890111Simpaddfname(char *name)
128990111Simp{
12901556Srgrimes	char *p;
12911556Srgrimes	struct strlist *sp;
12921556Srgrimes
12931556Srgrimes	p = stalloc(strlen(name) + 1);
12941556Srgrimes	scopy(name, p);
12951556Srgrimes	sp = (struct strlist *)stalloc(sizeof *sp);
12961556Srgrimes	sp->text = p;
12971556Srgrimes	*exparg.lastp = sp;
12981556Srgrimes	exparg.lastp = &sp->next;
12991556Srgrimes}
13001556Srgrimes
13011556Srgrimes
13021556Srgrimes/*
13031556Srgrimes * Sort the results of file name expansion.  It calculates the number of
13041556Srgrimes * strings to sort and then calls msort (short for merge sort) to do the
13051556Srgrimes * work.
13061556Srgrimes */
13071556Srgrimes
13081556SrgrimesSTATIC struct strlist *
130990111Simpexpsort(struct strlist *str)
131090111Simp{
13111556Srgrimes	int len;
13121556Srgrimes	struct strlist *sp;
13131556Srgrimes
13141556Srgrimes	len = 0;
13151556Srgrimes	for (sp = str ; sp ; sp = sp->next)
13161556Srgrimes		len++;
13171556Srgrimes	return msort(str, len);
13181556Srgrimes}
13191556Srgrimes
13201556Srgrimes
13211556SrgrimesSTATIC struct strlist *
132290111Simpmsort(struct strlist *list, int len)
132317987Speter{
132417987Speter	struct strlist *p, *q = NULL;
13251556Srgrimes	struct strlist **lpp;
13261556Srgrimes	int half;
13271556Srgrimes	int n;
13281556Srgrimes
13291556Srgrimes	if (len <= 1)
13301556Srgrimes		return list;
13318855Srgrimes	half = len >> 1;
13321556Srgrimes	p = list;
13331556Srgrimes	for (n = half ; --n >= 0 ; ) {
13341556Srgrimes		q = p;
13351556Srgrimes		p = p->next;
13361556Srgrimes	}
13371556Srgrimes	q->next = NULL;			/* terminate first half of list */
13381556Srgrimes	q = msort(list, half);		/* sort first half of list */
13391556Srgrimes	p = msort(p, len - half);		/* sort second half */
13401556Srgrimes	lpp = &list;
13411556Srgrimes	for (;;) {
13421556Srgrimes		if (strcmp(p->text, q->text) < 0) {
13431556Srgrimes			*lpp = p;
13441556Srgrimes			lpp = &p->next;
13451556Srgrimes			if ((p = *lpp) == NULL) {
13461556Srgrimes				*lpp = q;
13471556Srgrimes				break;
13481556Srgrimes			}
13491556Srgrimes		} else {
13501556Srgrimes			*lpp = q;
13511556Srgrimes			lpp = &q->next;
13521556Srgrimes			if ((q = *lpp) == NULL) {
13531556Srgrimes				*lpp = p;
13541556Srgrimes				break;
13551556Srgrimes			}
13561556Srgrimes		}
13571556Srgrimes	}
13581556Srgrimes	return list;
13591556Srgrimes}
13601556Srgrimes
13611556Srgrimes
13621556Srgrimes
13631556Srgrimes/*
13641556Srgrimes * Returns true if the pattern matches the string.
13651556Srgrimes */
13661556Srgrimes
13671556Srgrimesint
1368200956Sjillespatmatch(const char *pattern, const char *string, int squoted)
136990111Simp{
1370200956Sjilles	const char *p, *q;
137125233Ssteve	char c;
13721556Srgrimes
13731556Srgrimes	p = pattern;
13741556Srgrimes	q = string;
13751556Srgrimes	for (;;) {
13761556Srgrimes		switch (c = *p++) {
13771556Srgrimes		case '\0':
13781556Srgrimes			goto breakloop;
13791556Srgrimes		case CTLESC:
138045514Stegge			if (squoted && *q == CTLESC)
138145514Stegge				q++;
13821556Srgrimes			if (*q++ != *p++)
13831556Srgrimes				return 0;
13841556Srgrimes			break;
138538887Stegge		case CTLQUOTEMARK:
138638887Stegge			continue;
13871556Srgrimes		case '?':
138845514Stegge			if (squoted && *q == CTLESC)
138945514Stegge				q++;
13901556Srgrimes			if (*q++ == '\0')
13911556Srgrimes				return 0;
13921556Srgrimes			break;
13931556Srgrimes		case '*':
13941556Srgrimes			c = *p;
139538887Stegge			while (c == CTLQUOTEMARK || c == '*')
139638887Stegge				c = *++p;
139738887Stegge			if (c != CTLESC &&  c != CTLQUOTEMARK &&
139838887Stegge			    c != '?' && c != '*' && c != '[') {
13991556Srgrimes				while (*q != c) {
140045514Stegge					if (squoted && *q == CTLESC &&
140145514Stegge					    q[1] == c)
140245514Stegge						break;
14031556Srgrimes					if (*q == '\0')
14041556Srgrimes						return 0;
140545514Stegge					if (squoted && *q == CTLESC)
140645514Stegge						q++;
14071556Srgrimes					q++;
14081556Srgrimes				}
14091556Srgrimes			}
14101556Srgrimes			do {
1411211646Sjilles				if (patmatch(p, q, squoted))
14121556Srgrimes					return 1;
141345514Stegge				if (squoted && *q == CTLESC)
141445514Stegge					q++;
14151556Srgrimes			} while (*q++ != '\0');
14161556Srgrimes			return 0;
14171556Srgrimes		case '[': {
1418200956Sjilles			const char *endp;
14191556Srgrimes			int invert, found;
14201556Srgrimes			char chr;
14211556Srgrimes
14221556Srgrimes			endp = p;
142326488Sache			if (*endp == '!' || *endp == '^')
14241556Srgrimes				endp++;
14251556Srgrimes			for (;;) {
142638887Stegge				while (*endp == CTLQUOTEMARK)
142738887Stegge					endp++;
14281556Srgrimes				if (*endp == '\0')
14291556Srgrimes					goto dft;		/* no matching ] */
14301556Srgrimes				if (*endp == CTLESC)
14311556Srgrimes					endp++;
14321556Srgrimes				if (*++endp == ']')
14331556Srgrimes					break;
14341556Srgrimes			}
14351556Srgrimes			invert = 0;
143626488Sache			if (*p == '!' || *p == '^') {
14371556Srgrimes				invert++;
14381556Srgrimes				p++;
14391556Srgrimes			}
14401556Srgrimes			found = 0;
14411556Srgrimes			chr = *q++;
144245514Stegge			if (squoted && chr == CTLESC)
144345514Stegge				chr = *q++;
144417987Speter			if (chr == '\0')
144517987Speter				return 0;
14461556Srgrimes			c = *p++;
14471556Srgrimes			do {
144838887Stegge				if (c == CTLQUOTEMARK)
144938887Stegge					continue;
14501556Srgrimes				if (c == CTLESC)
14511556Srgrimes					c = *p++;
14521556Srgrimes				if (*p == '-' && p[1] != ']') {
14531556Srgrimes					p++;
145438887Stegge					while (*p == CTLQUOTEMARK)
145538887Stegge						p++;
14561556Srgrimes					if (*p == CTLESC)
14571556Srgrimes						p++;
145817557Sache					if (   collate_range_cmp(chr, c) >= 0
145917557Sache					    && collate_range_cmp(chr, *p) <= 0
146017525Sache					   )
14611556Srgrimes						found = 1;
14621556Srgrimes					p++;
14631556Srgrimes				} else {
14641556Srgrimes					if (chr == c)
14651556Srgrimes						found = 1;
14661556Srgrimes				}
14671556Srgrimes			} while ((c = *p++) != ']');
14681556Srgrimes			if (found == invert)
14691556Srgrimes				return 0;
14701556Srgrimes			break;
14711556Srgrimes		}
14721556Srgrimesdft:	        default:
147345514Stegge			if (squoted && *q == CTLESC)
147445514Stegge				q++;
14751556Srgrimes			if (*q++ != c)
14761556Srgrimes				return 0;
14771556Srgrimes			break;
14781556Srgrimes		}
14791556Srgrimes	}
14801556Srgrimesbreakloop:
14811556Srgrimes	if (*q != '\0')
14821556Srgrimes		return 0;
14831556Srgrimes	return 1;
14841556Srgrimes}
14851556Srgrimes
14861556Srgrimes
14871556Srgrimes
14881556Srgrimes/*
1489212243Sjilles * Remove any CTLESC and CTLQUOTEMARK characters from a string.
14901556Srgrimes */
14911556Srgrimes
14921556Srgrimesvoid
149390111Simprmescapes(char *str)
149438887Stegge{
149525233Ssteve	char *p, *q;
14961556Srgrimes
14971556Srgrimes	p = str;
149838887Stegge	while (*p != CTLESC && *p != CTLQUOTEMARK) {
14991556Srgrimes		if (*p++ == '\0')
15001556Srgrimes			return;
15011556Srgrimes	}
15021556Srgrimes	q = p;
15031556Srgrimes	while (*p) {
150438887Stegge		if (*p == CTLQUOTEMARK) {
150538887Stegge			p++;
150638887Stegge			continue;
150738887Stegge		}
15081556Srgrimes		if (*p == CTLESC)
15091556Srgrimes			p++;
15101556Srgrimes		*q++ = *p++;
15111556Srgrimes	}
15121556Srgrimes	*q = '\0';
15131556Srgrimes}
15141556Srgrimes
15151556Srgrimes
15161556Srgrimes
15171556Srgrimes/*
15181556Srgrimes * See if a pattern matches in a case statement.
15191556Srgrimes */
15201556Srgrimes
15211556Srgrimesint
1522200956Sjillescasematch(union node *pattern, const char *val)
152390111Simp{
15241556Srgrimes	struct stackmark smark;
15251556Srgrimes	int result;
15261556Srgrimes	char *p;
15271556Srgrimes
15281556Srgrimes	setstackmark(&smark);
15291556Srgrimes	argbackq = pattern->narg.backquote;
15301556Srgrimes	STARTSTACKSTR(expdest);
15311556Srgrimes	ifslastp = NULL;
15321556Srgrimes	argstr(pattern->narg.text, EXP_TILDE | EXP_CASE);
15331556Srgrimes	STPUTC('\0', expdest);
15341556Srgrimes	p = grabstackstr(expdest);
153545514Stegge	result = patmatch(p, val, 0);
15361556Srgrimes	popstackmark(&smark);
15371556Srgrimes	return result;
15381556Srgrimes}
153917987Speter
154017987Speter/*
154117987Speter * Our own itoa().
154217987Speter */
154317987Speter
154417987SpeterSTATIC char *
154590111Simpcvtnum(int num, char *buf)
154690111Simp{
154717987Speter	char temp[32];
154817987Speter	int neg = num < 0;
154917987Speter	char *p = temp + 31;
155017987Speter
155117987Speter	temp[31] = '\0';
155217987Speter
155317987Speter	do {
155417987Speter		*--p = num % 10 + '0';
155517987Speter	} while ((num /= 10) != 0);
155617987Speter
155717987Speter	if (neg)
155817987Speter		*--p = '-';
155917987Speter
156017987Speter	while (*p)
156117987Speter		STPUTC(*p++, buf);
156217987Speter	return buf;
156317987Speter}
1564108286Stjr
1565108286Stjr/*
1566108286Stjr * Do most of the work for wordexp(3).
1567108286Stjr */
1568108286Stjr
1569108286Stjrint
1570108286Stjrwordexpcmd(int argc, char **argv)
1571108286Stjr{
1572108286Stjr	size_t len;
1573108286Stjr	int i;
1574108286Stjr
1575108286Stjr	out1fmt("%08x", argc - 1);
1576108286Stjr	for (i = 1, len = 0; i < argc; i++)
1577108286Stjr		len += strlen(argv[i]);
1578108286Stjr	out1fmt("%08x", (int)len);
1579108286Stjr	for (i = 1; i < argc; i++) {
1580108286Stjr		out1str(argv[i]);
1581108286Stjr		out1c('\0');
1582108286Stjr	}
1583108286Stjr        return (0);
1584108286Stjr}
1585