expand.c revision 155301
11556Srgrimes/*-
21556Srgrimes * Copyright (c) 1991, 1993
31556Srgrimes *	The Regents of the University of California.  All rights reserved.
41556Srgrimes *
51556Srgrimes * This code is derived from software contributed to Berkeley by
61556Srgrimes * Kenneth Almquist.
71556Srgrimes *
81556Srgrimes * Redistribution and use in source and binary forms, with or without
91556Srgrimes * modification, are permitted provided that the following conditions
101556Srgrimes * are met:
111556Srgrimes * 1. Redistributions of source code must retain the above copyright
121556Srgrimes *    notice, this list of conditions and the following disclaimer.
131556Srgrimes * 2. Redistributions in binary form must reproduce the above copyright
141556Srgrimes *    notice, this list of conditions and the following disclaimer in the
151556Srgrimes *    documentation and/or other materials provided with the distribution.
161556Srgrimes * 4. Neither the name of the University nor the names of its contributors
171556Srgrimes *    may be used to endorse or promote products derived from this software
181556Srgrimes *    without specific prior written permission.
191556Srgrimes *
201556Srgrimes * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
211556Srgrimes * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
221556Srgrimes * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
231556Srgrimes * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
241556Srgrimes * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
251556Srgrimes * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
261556Srgrimes * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
271556Srgrimes * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
281556Srgrimes * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
291556Srgrimes * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
301556Srgrimes * SUCH DAMAGE.
311556Srgrimes */
321556Srgrimes
331556Srgrimes#ifndef lint
3436150Scharnier#if 0
3536150Scharnierstatic char sccsid[] = "@(#)expand.c	8.5 (Berkeley) 5/15/95";
3636150Scharnier#endif
371556Srgrimes#endif /* not lint */
3899110Sobrien#include <sys/cdefs.h>
3999110Sobrien__FBSDID("$FreeBSD: head/bin/sh/expand.c 155301 2006-02-04 14:37:50Z schweikh $");
401556Srgrimes
4117987Speter#include <sys/types.h>
4217987Speter#include <sys/time.h>
4317987Speter#include <sys/stat.h>
4417987Speter#include <errno.h>
4517987Speter#include <dirent.h>
4617987Speter#include <unistd.h>
4717987Speter#include <pwd.h>
4817987Speter#include <stdlib.h>
4919281Sache#include <limits.h>
5038887Stegge#include <stdio.h>
51108286Stjr#include <string.h>
5217987Speter
531556Srgrimes/*
541556Srgrimes * Routines to expand arguments to commands.  We have to deal with
551556Srgrimes * backquotes, shell variables, and file metacharacters.
561556Srgrimes */
571556Srgrimes
581556Srgrimes#include "shell.h"
591556Srgrimes#include "main.h"
601556Srgrimes#include "nodes.h"
611556Srgrimes#include "eval.h"
621556Srgrimes#include "expand.h"
631556Srgrimes#include "syntax.h"
641556Srgrimes#include "parser.h"
651556Srgrimes#include "jobs.h"
661556Srgrimes#include "options.h"
671556Srgrimes#include "var.h"
681556Srgrimes#include "input.h"
691556Srgrimes#include "output.h"
701556Srgrimes#include "memalloc.h"
711556Srgrimes#include "error.h"
721556Srgrimes#include "mystring.h"
7317987Speter#include "arith.h"
7417987Speter#include "show.h"
751556Srgrimes
761556Srgrimes/*
771556Srgrimes * Structure specifying which parts of the string should be searched
781556Srgrimes * for IFS characters.
791556Srgrimes */
801556Srgrimes
811556Srgrimesstruct ifsregion {
821556Srgrimes	struct ifsregion *next;	/* next region in list */
831556Srgrimes	int begoff;		/* offset of start of region */
841556Srgrimes	int endoff;		/* offset of end of region */
851556Srgrimes	int nulonly;		/* search for nul bytes only */
861556Srgrimes};
871556Srgrimes
881556Srgrimes
89117261SddsSTATIC char *expdest;			/* output of current string */
90117261SddsSTATIC struct nodelist *argbackq;	/* list of back quote expressions */
91117261SddsSTATIC struct ifsregion ifsfirst;	/* first struct in list of ifs regions */
92117261SddsSTATIC struct ifsregion *ifslastp;	/* last struct in list */
93117261SddsSTATIC struct arglist exparg;		/* holds expanded arg list */
941556Srgrimes
9590111SimpSTATIC void argstr(char *, int);
9690111SimpSTATIC char *exptilde(char *, int);
9790111SimpSTATIC void expbackq(union node *, int, int);
9890111SimpSTATIC int subevalvar(char *, char *, int, int, int, int);
9990111SimpSTATIC char *evalvar(char *, int);
10090111SimpSTATIC int varisset(char *, int);
10190111SimpSTATIC void varvalue(char *, int, int);
10290111SimpSTATIC void recordregion(int, int, int);
103155301SschweikhSTATIC void removerecordregions(int);
10490111SimpSTATIC void ifsbreakup(char *, struct arglist *);
10590111SimpSTATIC void expandmeta(struct strlist *, int);
10690111SimpSTATIC void expmeta(char *, char *);
10790111SimpSTATIC void addfname(char *);
10890111SimpSTATIC struct strlist *expsort(struct strlist *);
10990111SimpSTATIC struct strlist *msort(struct strlist *, int);
11090111SimpSTATIC int pmatch(char *, char *, int);
11190111SimpSTATIC char *cvtnum(int, char *);
11290111SimpSTATIC int collate_range_cmp(int, int);
1131556Srgrimes
11490111SimpSTATIC int
115118374Sachecollate_range_cmp(int c1, int c2)
11619281Sache{
11719281Sache	static char s1[2], s2[2];
11819281Sache
11919281Sache	s1[0] = c1;
12019281Sache	s2[0] = c2;
121118374Sache	return (strcoll(s1, s2));
12219281Sache}
12319281Sache
1241556Srgrimes/*
1251556Srgrimes * Expand shell variables and backquotes inside a here document.
12690111Simp *	union node *arg		the document
12790111Simp *	int fd;			where to write the expanded version
1281556Srgrimes */
1291556Srgrimes
1301556Srgrimesvoid
13190111Simpexpandhere(union node *arg, int fd)
13290111Simp{
1331556Srgrimes	herefd = fd;
1341556Srgrimes	expandarg(arg, (struct arglist *)NULL, 0);
13539137Stegge	xwrite(fd, stackblock(), expdest - stackblock());
1361556Srgrimes}
1371556Srgrimes
1381556Srgrimes
1391556Srgrimes/*
1401556Srgrimes * Perform variable substitution and command substitution on an argument,
1411556Srgrimes * placing the resulting list of arguments in arglist.  If EXP_FULL is true,
1421556Srgrimes * perform splitting and file name expansion.  When arglist is NULL, perform
1431556Srgrimes * here document expansion.
1441556Srgrimes */
1451556Srgrimes
1461556Srgrimesvoid
14790111Simpexpandarg(union node *arg, struct arglist *arglist, int flag)
14817987Speter{
1491556Srgrimes	struct strlist *sp;
1501556Srgrimes	char *p;
1511556Srgrimes
1521556Srgrimes	argbackq = arg->narg.backquote;
1531556Srgrimes	STARTSTACKSTR(expdest);
1541556Srgrimes	ifsfirst.next = NULL;
1551556Srgrimes	ifslastp = NULL;
1561556Srgrimes	argstr(arg->narg.text, flag);
1571556Srgrimes	if (arglist == NULL) {
1581556Srgrimes		return;			/* here document expanded */
1591556Srgrimes	}
1601556Srgrimes	STPUTC('\0', expdest);
1611556Srgrimes	p = grabstackstr(expdest);
1621556Srgrimes	exparg.lastp = &exparg.list;
1631556Srgrimes	/*
1641556Srgrimes	 * TODO - EXP_REDIR
1651556Srgrimes	 */
1661556Srgrimes	if (flag & EXP_FULL) {
1671556Srgrimes		ifsbreakup(p, &exparg);
1681556Srgrimes		*exparg.lastp = NULL;
1691556Srgrimes		exparg.lastp = &exparg.list;
1701556Srgrimes		expandmeta(exparg.list, flag);
1711556Srgrimes	} else {
1721556Srgrimes		if (flag & EXP_REDIR) /*XXX - for now, just remove escapes */
1731556Srgrimes			rmescapes(p);
1741556Srgrimes		sp = (struct strlist *)stalloc(sizeof (struct strlist));
1751556Srgrimes		sp->text = p;
1761556Srgrimes		*exparg.lastp = sp;
1771556Srgrimes		exparg.lastp = &sp->next;
1781556Srgrimes	}
1791556Srgrimes	while (ifsfirst.next != NULL) {
1801556Srgrimes		struct ifsregion *ifsp;
1811556Srgrimes		INTOFF;
1821556Srgrimes		ifsp = ifsfirst.next->next;
1831556Srgrimes		ckfree(ifsfirst.next);
1841556Srgrimes		ifsfirst.next = ifsp;
1851556Srgrimes		INTON;
1861556Srgrimes	}
1871556Srgrimes	*exparg.lastp = NULL;
1881556Srgrimes	if (exparg.list) {
1891556Srgrimes		*arglist->lastp = exparg.list;
1901556Srgrimes		arglist->lastp = exparg.lastp;
1911556Srgrimes	}
1921556Srgrimes}
1931556Srgrimes
1941556Srgrimes
1951556Srgrimes
1961556Srgrimes/*
1971556Srgrimes * Perform variable and command substitution.  If EXP_FULL is set, output CTLESC
1981556Srgrimes * characters to allow for further processing.  Otherwise treat
1991556Srgrimes * $@ like $* since no splitting will be performed.
2001556Srgrimes */
2011556Srgrimes
2021556SrgrimesSTATIC void
20390111Simpargstr(char *p, int flag)
20417987Speter{
20525233Ssteve	char c;
206104672Stjr	int quotes = flag & (EXP_FULL | EXP_CASE | EXP_REDIR);	/* do CTLESC */
2071556Srgrimes	int firsteq = 1;
2081556Srgrimes
2091556Srgrimes	if (*p == '~' && (flag & (EXP_TILDE | EXP_VARTILDE)))
2101556Srgrimes		p = exptilde(p, flag);
2111556Srgrimes	for (;;) {
2121556Srgrimes		switch (c = *p++) {
2131556Srgrimes		case '\0':
2141556Srgrimes		case CTLENDVAR: /* ??? */
2151556Srgrimes			goto breakloop;
21638887Stegge		case CTLQUOTEMARK:
21738887Stegge			/* "$@" syntax adherence hack */
21838887Stegge			if (p[0] == CTLVAR && p[2] == '@' && p[3] == '=')
21938887Stegge				break;
22039137Stegge			if ((flag & EXP_FULL) != 0)
22139137Stegge				STPUTC(c, expdest);
22238887Stegge			break;
2231556Srgrimes		case CTLESC:
2241556Srgrimes			if (quotes)
2251556Srgrimes				STPUTC(c, expdest);
2261556Srgrimes			c = *p++;
2271556Srgrimes			STPUTC(c, expdest);
2281556Srgrimes			break;
2291556Srgrimes		case CTLVAR:
2301556Srgrimes			p = evalvar(p, flag);
2311556Srgrimes			break;
2321556Srgrimes		case CTLBACKQ:
2331556Srgrimes		case CTLBACKQ|CTLQUOTE:
2341556Srgrimes			expbackq(argbackq->n, c & CTLQUOTE, flag);
2351556Srgrimes			argbackq = argbackq->next;
2361556Srgrimes			break;
2371556Srgrimes		case CTLENDARI:
2381556Srgrimes			expari(flag);
2391556Srgrimes			break;
2401556Srgrimes		case ':':
2411556Srgrimes		case '=':
2421556Srgrimes			/*
2431556Srgrimes			 * sort of a hack - expand tildes in variable
2441556Srgrimes			 * assignments (after the first '=' and after ':'s).
2451556Srgrimes			 */
2461556Srgrimes			STPUTC(c, expdest);
2471556Srgrimes			if (flag & EXP_VARTILDE && *p == '~') {
2481556Srgrimes				if (c == '=') {
2491556Srgrimes					if (firsteq)
2501556Srgrimes						firsteq = 0;
2511556Srgrimes					else
2521556Srgrimes						break;
2531556Srgrimes				}
2541556Srgrimes				p = exptilde(p, flag);
2551556Srgrimes			}
2561556Srgrimes			break;
2571556Srgrimes		default:
2581556Srgrimes			STPUTC(c, expdest);
2591556Srgrimes		}
2601556Srgrimes	}
2611556Srgrimesbreakloop:;
2621556Srgrimes}
2631556Srgrimes
2641556SrgrimesSTATIC char *
26590111Simpexptilde(char *p, int flag)
26617987Speter{
2671556Srgrimes	char c, *startp = p;
2681556Srgrimes	struct passwd *pw;
2691556Srgrimes	char *home;
270108935Stjr	int quotes = flag & (EXP_FULL | EXP_CASE | EXP_REDIR);
2711556Srgrimes
27217987Speter	while ((c = *p) != '\0') {
2731556Srgrimes		switch(c) {
2741556Srgrimes		case CTLESC:
2751556Srgrimes			return (startp);
27639137Stegge		case CTLQUOTEMARK:
27739137Stegge			return (startp);
2781556Srgrimes		case ':':
2791556Srgrimes			if (flag & EXP_VARTILDE)
2801556Srgrimes				goto done;
2811556Srgrimes			break;
2821556Srgrimes		case '/':
2831556Srgrimes			goto done;
2841556Srgrimes		}
2851556Srgrimes		p++;
2861556Srgrimes	}
2871556Srgrimesdone:
2881556Srgrimes	*p = '\0';
2891556Srgrimes	if (*(startp+1) == '\0') {
2901556Srgrimes		if ((home = lookupvar("HOME")) == NULL)
2911556Srgrimes			goto lose;
2921556Srgrimes	} else {
2931556Srgrimes		if ((pw = getpwnam(startp+1)) == NULL)
2941556Srgrimes			goto lose;
2951556Srgrimes		home = pw->pw_dir;
2961556Srgrimes	}
2971556Srgrimes	if (*home == '\0')
2981556Srgrimes		goto lose;
2991556Srgrimes	*p = c;
30017987Speter	while ((c = *home++) != '\0') {
30183675Stegge		if (quotes && SQSYNTAX[(int)c] == CCTL)
3021556Srgrimes			STPUTC(CTLESC, expdest);
3031556Srgrimes		STPUTC(c, expdest);
3041556Srgrimes	}
3051556Srgrimes	return (p);
3061556Srgrimeslose:
3071556Srgrimes	*p = c;
3081556Srgrimes	return (startp);
3091556Srgrimes}
3101556Srgrimes
3111556Srgrimes
312155301SschweikhSTATIC void
31390111Simpremoverecordregions(int endoff)
31438887Stegge{
31538887Stegge	if (ifslastp == NULL)
31638887Stegge		return;
31738887Stegge
31838887Stegge	if (ifsfirst.endoff > endoff) {
31938887Stegge		while (ifsfirst.next != NULL) {
32038887Stegge			struct ifsregion *ifsp;
32138887Stegge			INTOFF;
32238887Stegge			ifsp = ifsfirst.next->next;
32338887Stegge			ckfree(ifsfirst.next);
32438887Stegge			ifsfirst.next = ifsp;
32538887Stegge			INTON;
32638887Stegge		}
32738887Stegge		if (ifsfirst.begoff > endoff)
32838887Stegge			ifslastp = NULL;
32938887Stegge		else {
33038887Stegge			ifslastp = &ifsfirst;
33138887Stegge			ifsfirst.endoff = endoff;
33238887Stegge		}
33338887Stegge		return;
33438887Stegge	}
335155301Sschweikh
33638887Stegge	ifslastp = &ifsfirst;
33738887Stegge	while (ifslastp->next && ifslastp->next->begoff < endoff)
33838887Stegge		ifslastp=ifslastp->next;
33938887Stegge	while (ifslastp->next != NULL) {
34038887Stegge		struct ifsregion *ifsp;
34138887Stegge		INTOFF;
34238887Stegge		ifsp = ifslastp->next->next;
34338887Stegge		ckfree(ifslastp->next);
34438887Stegge		ifslastp->next = ifsp;
34538887Stegge		INTON;
34638887Stegge	}
34738887Stegge	if (ifslastp->endoff > endoff)
34838887Stegge		ifslastp->endoff = endoff;
34938887Stegge}
35038887Stegge
3511556Srgrimes/*
3521556Srgrimes * Expand arithmetic expression.  Backup to start of expression,
3531556Srgrimes * evaluate, place result in (backed up) result, adjust string position.
3541556Srgrimes */
3551556Srgrimesvoid
35690111Simpexpari(int flag)
35717987Speter{
3581556Srgrimes	char *p, *start;
3591556Srgrimes	int result;
36038887Stegge	int begoff;
361108935Stjr	int quotes = flag & (EXP_FULL | EXP_CASE | EXP_REDIR);
36238887Stegge	int quoted;
3631556Srgrimes
36425233Ssteve
3651556Srgrimes	/*
36646684Skris	 * This routine is slightly over-complicated for
3671556Srgrimes	 * efficiency.  First we make sure there is
3681556Srgrimes	 * enough space for the result, which may be bigger
36946684Skris	 * than the expression if we add exponentiation.  Next we
3701556Srgrimes	 * scan backwards looking for the start of arithmetic.  If the
3711556Srgrimes	 * next previous character is a CTLESC character, then we
3721556Srgrimes	 * have to rescan starting from the beginning since CTLESC
3738855Srgrimes	 * characters have to be processed left to right.
3741556Srgrimes	 */
37522777Ssteve#if INT_MAX / 1000000000 >= 10 || INT_MIN / 1000000000 <= -10
37622777Ssteve#error "integers with more than 10 digits are not supported"
37722777Ssteve#endif
37822777Ssteve	CHECKSTRSPACE(12 - 2, expdest);
3798855Srgrimes	USTPUTC('\0', expdest);
3801556Srgrimes	start = stackblock();
38183676Stegge	p = expdest - 2;
38283676Stegge	while (p >= start && *p != CTLARI)
3831556Srgrimes		--p;
38483676Stegge	if (p < start || *p != CTLARI)
3851556Srgrimes		error("missing CTLARI (shouldn't happen)");
38683676Stegge	if (p > start && *(p - 1) == CTLESC)
3871556Srgrimes		for (p = start; *p != CTLARI; p++)
3881556Srgrimes			if (*p == CTLESC)
3891556Srgrimes				p++;
39038887Stegge
39138887Stegge	if (p[1] == '"')
39238887Stegge		quoted=1;
39338887Stegge	else
39438887Stegge		quoted=0;
39538887Stegge	begoff = p - start;
39638887Stegge	removerecordregions(begoff);
3971556Srgrimes	if (quotes)
39838887Stegge		rmescapes(p+2);
39938887Stegge	result = arith(p+2);
40022777Ssteve	fmtstr(p, 12, "%d", result);
4011556Srgrimes	while (*p++)
4021556Srgrimes		;
40338887Stegge	if (quoted == 0)
40438887Stegge		recordregion(begoff, p - 1 - start, 0);
4051556Srgrimes	result = expdest - p + 1;
4061556Srgrimes	STADJUST(-result, expdest);
4071556Srgrimes}
4081556Srgrimes
4091556Srgrimes
4101556Srgrimes/*
4111556Srgrimes * Expand stuff in backwards quotes.
4121556Srgrimes */
4131556Srgrimes
4141556SrgrimesSTATIC void
41590111Simpexpbackq(union node *cmd, int quoted, int flag)
41617987Speter{
4171556Srgrimes	struct backcmd in;
4181556Srgrimes	int i;
4191556Srgrimes	char buf[128];
4201556Srgrimes	char *p;
4211556Srgrimes	char *dest = expdest;
4221556Srgrimes	struct ifsregion saveifs, *savelastp;
4231556Srgrimes	struct nodelist *saveargbackq;
4241556Srgrimes	char lastc;
4251556Srgrimes	int startloc = dest - stackblock();
4261556Srgrimes	char const *syntax = quoted? DQSYNTAX : BASESYNTAX;
4271556Srgrimes	int saveherefd;
428108935Stjr	int quotes = flag & (EXP_FULL | EXP_CASE | EXP_REDIR);
429115424Sfenner	int nnl;
4301556Srgrimes
4311556Srgrimes	INTOFF;
4321556Srgrimes	saveifs = ifsfirst;
4331556Srgrimes	savelastp = ifslastp;
4341556Srgrimes	saveargbackq = argbackq;
4358855Srgrimes	saveherefd = herefd;
4361556Srgrimes	herefd = -1;
4371556Srgrimes	p = grabstackstr(dest);
4381556Srgrimes	evalbackcmd(cmd, &in);
4391556Srgrimes	ungrabstackstr(p, dest);
4401556Srgrimes	ifsfirst = saveifs;
4411556Srgrimes	ifslastp = savelastp;
4421556Srgrimes	argbackq = saveargbackq;
4431556Srgrimes	herefd = saveherefd;
4441556Srgrimes
4451556Srgrimes	p = in.buf;
4461556Srgrimes	lastc = '\0';
447115424Sfenner	nnl = 0;
448115424Sfenner	/* Don't copy trailing newlines */
4491556Srgrimes	for (;;) {
4501556Srgrimes		if (--in.nleft < 0) {
4511556Srgrimes			if (in.fd < 0)
4521556Srgrimes				break;
4531556Srgrimes			while ((i = read(in.fd, buf, sizeof buf)) < 0 && errno == EINTR);
4541556Srgrimes			TRACE(("expbackq: read returns %d\n", i));
4551556Srgrimes			if (i <= 0)
4561556Srgrimes				break;
4571556Srgrimes			p = buf;
4581556Srgrimes			in.nleft = i - 1;
4591556Srgrimes		}
4601556Srgrimes		lastc = *p++;
4611556Srgrimes		if (lastc != '\0') {
46283675Stegge			if (quotes && syntax[(int)lastc] == CCTL)
4631556Srgrimes				STPUTC(CTLESC, dest);
464115424Sfenner			if (lastc == '\n') {
465115424Sfenner				nnl++;
466115424Sfenner			} else {
467115424Sfenner				while (nnl > 0) {
468115424Sfenner					nnl--;
469115424Sfenner					STPUTC('\n', dest);
470115424Sfenner				}
471115424Sfenner				STPUTC(lastc, dest);
472115424Sfenner			}
4731556Srgrimes		}
4741556Srgrimes	}
47517987Speter
4761556Srgrimes	if (in.fd >= 0)
4771556Srgrimes		close(in.fd);
4781556Srgrimes	if (in.buf)
4791556Srgrimes		ckfree(in.buf);
4801556Srgrimes	if (in.jp)
48145916Scracauer		exitstatus = waitforjob(in.jp, (int *)NULL);
4821556Srgrimes	if (quoted == 0)
4831556Srgrimes		recordregion(startloc, dest - stackblock(), 0);
4841556Srgrimes	TRACE(("evalbackq: size=%d: \"%.*s\"\n",
4851556Srgrimes		(dest - stackblock()) - startloc,
4861556Srgrimes		(dest - stackblock()) - startloc,
4871556Srgrimes		stackblock() + startloc));
4881556Srgrimes	expdest = dest;
4891556Srgrimes	INTON;
4901556Srgrimes}
4911556Srgrimes
4921556Srgrimes
4931556Srgrimes
49417987SpeterSTATIC int
49590111Simpsubevalvar(char *p, char *str, int strloc, int subtype, int startloc,
49690111Simp  int varflags)
49717987Speter{
49817987Speter	char *startp;
49917987Speter	char *loc = NULL;
50045514Stegge	char *q;
50117987Speter	int c = 0;
50217987Speter	int saveherefd = herefd;
50317987Speter	struct nodelist *saveargbackq = argbackq;
50420425Ssteve	int amount;
50520425Ssteve
50617987Speter	herefd = -1;
50717987Speter	argstr(p, 0);
50817987Speter	STACKSTRNUL(expdest);
50917987Speter	herefd = saveherefd;
51017987Speter	argbackq = saveargbackq;
51117987Speter	startp = stackblock() + startloc;
51220425Ssteve	if (str == NULL)
51320425Ssteve	    str = stackblock() + strloc;
51417987Speter
51517987Speter	switch (subtype) {
51617987Speter	case VSASSIGN:
51717987Speter		setvar(str, startp, 0);
51820425Ssteve		amount = startp - expdest;
51920425Ssteve		STADJUST(amount, expdest);
52017987Speter		varflags &= ~VSNUL;
52117987Speter		if (c != 0)
52217987Speter			*loc = c;
52317987Speter		return 1;
52417987Speter
52517987Speter	case VSQUESTION:
52617987Speter		if (*p != CTLENDVAR) {
52717987Speter			outfmt(&errout, "%s\n", startp);
52817987Speter			error((char *)NULL);
52917987Speter		}
530112254Sru		error("%.*s: parameter %snot set", (int)(p - str - 1),
53117987Speter		      str, (varflags & VSNUL) ? "null or "
53217987Speter					      : nullstr);
53317987Speter		return 0;
53417987Speter
53517987Speter	case VSTRIMLEFT:
53625233Ssteve		for (loc = startp; loc < str; loc++) {
53717987Speter			c = *loc;
53817987Speter			*loc = '\0';
53945514Stegge			if (patmatch(str, startp, varflags & VSQUOTE)) {
54017987Speter				*loc = c;
54117987Speter				goto recordleft;
54217987Speter			}
54317987Speter			*loc = c;
54445514Stegge			if ((varflags & VSQUOTE) && *loc == CTLESC)
54545514Stegge				loc++;
54617987Speter		}
54717987Speter		return 0;
54817987Speter
54917987Speter	case VSTRIMLEFTMAX:
55045514Stegge		for (loc = str - 1; loc >= startp;) {
55117987Speter			c = *loc;
55217987Speter			*loc = '\0';
55345514Stegge			if (patmatch(str, startp, varflags & VSQUOTE)) {
55417987Speter				*loc = c;
55517987Speter				goto recordleft;
55617987Speter			}
55717987Speter			*loc = c;
55845514Stegge			loc--;
55945514Stegge			if ((varflags & VSQUOTE) && loc > startp &&
56045514Stegge			    *(loc - 1) == CTLESC) {
56145514Stegge				for (q = startp; q < loc; q++)
56245514Stegge					if (*q == CTLESC)
56345514Stegge						q++;
56445514Stegge				if (q > loc)
56545514Stegge					loc--;
56645514Stegge			}
56717987Speter		}
56817987Speter		return 0;
56917987Speter
57017987Speter	case VSTRIMRIGHT:
57145514Stegge		for (loc = str - 1; loc >= startp;) {
57245514Stegge			if (patmatch(str, loc, varflags & VSQUOTE)) {
57320425Ssteve				amount = loc - expdest;
57420425Ssteve				STADJUST(amount, expdest);
57517987Speter				return 1;
57617987Speter			}
57745514Stegge			loc--;
57845514Stegge			if ((varflags & VSQUOTE) && loc > startp &&
579155301Sschweikh			    *(loc - 1) == CTLESC) {
58045514Stegge				for (q = startp; q < loc; q++)
58145514Stegge					if (*q == CTLESC)
58245514Stegge						q++;
58345514Stegge				if (q > loc)
58445514Stegge					loc--;
58545514Stegge			}
58617987Speter		}
58717987Speter		return 0;
58817987Speter
58917987Speter	case VSTRIMRIGHTMAX:
59017987Speter		for (loc = startp; loc < str - 1; loc++) {
59145514Stegge			if (patmatch(str, loc, varflags & VSQUOTE)) {
59220425Ssteve				amount = loc - expdest;
59320425Ssteve				STADJUST(amount, expdest);
59417987Speter				return 1;
59517987Speter			}
59645514Stegge			if ((varflags & VSQUOTE) && *loc == CTLESC)
59745514Stegge				loc++;
59817987Speter		}
59917987Speter		return 0;
60017987Speter
60117987Speter
60217987Speter	default:
60317987Speter		abort();
60417987Speter	}
60517987Speter
60617987Speterrecordleft:
60720425Ssteve	amount = ((str - 1) - (loc - startp)) - expdest;
60820425Ssteve	STADJUST(amount, expdest);
60917987Speter	while (loc != str - 1)
61017987Speter		*startp++ = *loc++;
61117987Speter	return 1;
61217987Speter}
61317987Speter
61417987Speter
6151556Srgrimes/*
6161556Srgrimes * Expand a variable, and return a pointer to the next character in the
6171556Srgrimes * input string.
6181556Srgrimes */
6191556Srgrimes
6201556SrgrimesSTATIC char *
62190111Simpevalvar(char *p, int flag)
62217987Speter{
6231556Srgrimes	int subtype;
6241556Srgrimes	int varflags;
6251556Srgrimes	char *var;
6261556Srgrimes	char *val;
62745644Stegge	int patloc;
6281556Srgrimes	int c;
6291556Srgrimes	int set;
6301556Srgrimes	int special;
6311556Srgrimes	int startloc;
63217987Speter	int varlen;
63317987Speter	int easy;
634108935Stjr	int quotes = flag & (EXP_FULL | EXP_CASE | EXP_REDIR);
6351556Srgrimes
6361556Srgrimes	varflags = *p++;
6371556Srgrimes	subtype = varflags & VSTYPE;
6381556Srgrimes	var = p;
6391556Srgrimes	special = 0;
6401556Srgrimes	if (! is_name(*p))
6411556Srgrimes		special = 1;
6421556Srgrimes	p = strchr(p, '=') + 1;
6431556Srgrimesagain: /* jump here after setting a variable with ${var=text} */
6441556Srgrimes	if (special) {
64525233Ssteve		set = varisset(var, varflags & VSNUL);
6461556Srgrimes		val = NULL;
6471556Srgrimes	} else {
64860592Scracauer		val = bltinlookup(var, 1);
64917987Speter		if (val == NULL || ((varflags & VSNUL) && val[0] == '\0')) {
6501556Srgrimes			val = NULL;
6511556Srgrimes			set = 0;
6521556Srgrimes		} else
6531556Srgrimes			set = 1;
6541556Srgrimes	}
65517987Speter	varlen = 0;
6561556Srgrimes	startloc = expdest - stackblock();
65796939Stjr	if (!set && uflag) {
65896939Stjr		switch (subtype) {
65996939Stjr		case VSNORMAL:
66096939Stjr		case VSTRIMLEFT:
66196939Stjr		case VSTRIMLEFTMAX:
66296939Stjr		case VSTRIMRIGHT:
66396939Stjr		case VSTRIMRIGHTMAX:
66496939Stjr		case VSLENGTH:
665112254Sru			error("%.*s: parameter not set", (int)(p - var - 1),
666112254Sru			    var);
66796939Stjr		}
66896939Stjr	}
6691556Srgrimes	if (set && subtype != VSPLUS) {
6701556Srgrimes		/* insert the value of the variable */
6711556Srgrimes		if (special) {
67218202Speter			varvalue(var, varflags & VSQUOTE, flag & EXP_FULL);
67317987Speter			if (subtype == VSLENGTH) {
67425233Ssteve				varlen = expdest - stackblock() - startloc;
67525233Ssteve				STADJUST(-varlen, expdest);
67617987Speter			}
6771556Srgrimes		} else {
67820425Ssteve			char const *syntax = (varflags & VSQUOTE) ? DQSYNTAX
67917987Speter								  : BASESYNTAX;
6801556Srgrimes
68117987Speter			if (subtype == VSLENGTH) {
68217987Speter				for (;*val; val++)
68317987Speter					varlen++;
6841556Srgrimes			}
68517987Speter			else {
68617987Speter				while (*val) {
68783675Stegge					if (quotes &&
68854132Scracauer					    syntax[(int)*val] == CCTL)
68917987Speter						STPUTC(CTLESC, expdest);
69017987Speter					STPUTC(*val++, expdest);
69117987Speter				}
69217987Speter
69317987Speter			}
6941556Srgrimes		}
6951556Srgrimes	}
69620425Ssteve
6971556Srgrimes	if (subtype == VSPLUS)
6981556Srgrimes		set = ! set;
69917987Speter
70020425Ssteve	easy = ((varflags & VSQUOTE) == 0 ||
70117987Speter		(*var == '@' && shellparam.nparam != 1));
70217987Speter
70317987Speter
70417987Speter	switch (subtype) {
70517987Speter	case VSLENGTH:
70617987Speter		expdest = cvtnum(varlen, expdest);
70717987Speter		goto record;
70817987Speter
70917987Speter	case VSNORMAL:
71017987Speter		if (!easy)
71117987Speter			break;
71217987Speterrecord:
71320425Ssteve		recordregion(startloc, expdest - stackblock(),
71417987Speter			     varflags & VSQUOTE);
71517987Speter		break;
71617987Speter
71717987Speter	case VSPLUS:
71817987Speter	case VSMINUS:
71917987Speter		if (!set) {
7201556Srgrimes			argstr(p, flag);
72117987Speter			break;
72217987Speter		}
72317987Speter		if (easy)
72417987Speter			goto record;
72517987Speter		break;
72617987Speter
72717987Speter	case VSTRIMLEFT:
72817987Speter	case VSTRIMLEFTMAX:
72917987Speter	case VSTRIMRIGHT:
73017987Speter	case VSTRIMRIGHTMAX:
73117987Speter		if (!set)
73217987Speter			break;
73317987Speter		/*
73417987Speter		 * Terminate the string and start recording the pattern
73517987Speter		 * right after it
73617987Speter		 */
73717987Speter		STPUTC('\0', expdest);
73845644Stegge		patloc = expdest - stackblock();
73945644Stegge		if (subevalvar(p, NULL, patloc, subtype,
74038887Stegge			       startloc, varflags) == 0) {
74145644Stegge			int amount = (expdest - stackblock() - patloc) + 1;
74225233Ssteve			STADJUST(-amount, expdest);
74325233Ssteve		}
74438887Stegge		/* Remove any recorded regions beyond start of variable */
74538887Stegge		removerecordregions(startloc);
74638887Stegge		goto record;
74717987Speter
74817987Speter	case VSASSIGN:
74917987Speter	case VSQUESTION:
75017987Speter		if (!set) {
75120425Ssteve			if (subevalvar(p, var, 0, subtype, startloc, varflags)) {
75220425Ssteve				varflags &= ~VSNUL;
753155301Sschweikh				/*
754155301Sschweikh				 * Remove any recorded regions beyond
755155301Sschweikh				 * start of variable
75638887Stegge				 */
75738887Stegge				removerecordregions(startloc);
7581556Srgrimes				goto again;
75920425Ssteve			}
76017987Speter			break;
7611556Srgrimes		}
76217987Speter		if (easy)
76317987Speter			goto record;
76417987Speter		break;
76517987Speter
76617987Speter	default:
76717987Speter		abort();
7681556Srgrimes	}
76917987Speter
7701556Srgrimes	if (subtype != VSNORMAL) {	/* skip to end of alternative */
7711556Srgrimes		int nesting = 1;
7721556Srgrimes		for (;;) {
7731556Srgrimes			if ((c = *p++) == CTLESC)
7741556Srgrimes				p++;
7751556Srgrimes			else if (c == CTLBACKQ || c == (CTLBACKQ|CTLQUOTE)) {
7761556Srgrimes				if (set)
7771556Srgrimes					argbackq = argbackq->next;
7781556Srgrimes			} else if (c == CTLVAR) {
7791556Srgrimes				if ((*p++ & VSTYPE) != VSNORMAL)
7801556Srgrimes					nesting++;
7811556Srgrimes			} else if (c == CTLENDVAR) {
7821556Srgrimes				if (--nesting == 0)
7831556Srgrimes					break;
7841556Srgrimes			}
7851556Srgrimes		}
7861556Srgrimes	}
7871556Srgrimes	return p;
7881556Srgrimes}
7891556Srgrimes
7901556Srgrimes
7911556Srgrimes
7921556Srgrimes/*
7931556Srgrimes * Test whether a specialized variable is set.
7941556Srgrimes */
7951556Srgrimes
7961556SrgrimesSTATIC int
79790111Simpvarisset(char *name, int nulok)
79825233Ssteve{
7991556Srgrimes
80025233Ssteve	if (*name == '!')
80125233Ssteve		return backgndpid != -1;
80225233Ssteve	else if (*name == '@' || *name == '*') {
8031556Srgrimes		if (*shellparam.p == NULL)
8041556Srgrimes			return 0;
80525233Ssteve
80625233Ssteve		if (nulok) {
80725233Ssteve			char **av;
80825233Ssteve
80925233Ssteve			for (av = shellparam.p; *av; av++)
81025233Ssteve				if (**av != '\0')
81125233Ssteve					return 1;
81225233Ssteve			return 0;
81325233Ssteve		}
81418202Speter	} else if (is_digit(*name)) {
81525233Ssteve		char *ap;
81620425Ssteve		int num = atoi(name);
81725233Ssteve
81825233Ssteve		if (num > shellparam.nparam)
81925233Ssteve			return 0;
82025233Ssteve
82125233Ssteve		if (num == 0)
82225233Ssteve			ap = arg0;
82325233Ssteve		else
82425233Ssteve			ap = shellparam.p[num - 1];
82525233Ssteve
82625233Ssteve		if (nulok && (ap == NULL || *ap == '\0'))
82725233Ssteve			return 0;
8281556Srgrimes	}
8291556Srgrimes	return 1;
8301556Srgrimes}
8311556Srgrimes
8321556Srgrimes
8331556Srgrimes
8341556Srgrimes/*
8351556Srgrimes * Add the value of a specialized variable to the stack string.
8361556Srgrimes */
8371556Srgrimes
8381556SrgrimesSTATIC void
83990111Simpvarvalue(char *name, int quoted, int allow_split)
84017987Speter{
8411556Srgrimes	int num;
8421556Srgrimes	char *p;
8431556Srgrimes	int i;
84417987Speter	extern int oexitstatus;
8451556Srgrimes	char sep;
8461556Srgrimes	char **ap;
8471556Srgrimes	char const *syntax;
8481556Srgrimes
8491556Srgrimes#define STRTODEST(p) \
8501556Srgrimes	do {\
8511556Srgrimes	if (allow_split) { \
8521556Srgrimes		syntax = quoted? DQSYNTAX : BASESYNTAX; \
8531556Srgrimes		while (*p) { \
85483675Stegge			if (syntax[(int)*p] == CCTL) \
8551556Srgrimes				STPUTC(CTLESC, expdest); \
8561556Srgrimes			STPUTC(*p++, expdest); \
8571556Srgrimes		} \
8581556Srgrimes	} else \
8591556Srgrimes		while (*p) \
8601556Srgrimes			STPUTC(*p++, expdest); \
8611556Srgrimes	} while (0)
8621556Srgrimes
8631556Srgrimes
86418202Speter	switch (*name) {
8651556Srgrimes	case '$':
8661556Srgrimes		num = rootpid;
8671556Srgrimes		goto numvar;
8681556Srgrimes	case '?':
86917987Speter		num = oexitstatus;
8701556Srgrimes		goto numvar;
8711556Srgrimes	case '#':
8721556Srgrimes		num = shellparam.nparam;
8731556Srgrimes		goto numvar;
8741556Srgrimes	case '!':
8751556Srgrimes		num = backgndpid;
8761556Srgrimesnumvar:
87717987Speter		expdest = cvtnum(num, expdest);
8781556Srgrimes		break;
8791556Srgrimes	case '-':
8801556Srgrimes		for (i = 0 ; i < NOPTS ; i++) {
8811556Srgrimes			if (optlist[i].val)
8821556Srgrimes				STPUTC(optlist[i].letter, expdest);
8831556Srgrimes		}
8841556Srgrimes		break;
8851556Srgrimes	case '@':
88638887Stegge		if (allow_split && quoted) {
88738887Stegge			for (ap = shellparam.p ; (p = *ap++) != NULL ; ) {
88838887Stegge				STRTODEST(p);
88938887Stegge				if (*ap)
89038887Stegge					STPUTC('\0', expdest);
89138887Stegge			}
89238887Stegge			break;
8931556Srgrimes		}
894102410Scharnier		/* FALLTHROUGH */
8951556Srgrimes	case '*':
896149825Srse		if (ifsset())
89738887Stegge			sep = ifsval()[0];
89838887Stegge		else
89938887Stegge			sep = ' ';
9001556Srgrimes		for (ap = shellparam.p ; (p = *ap++) != NULL ; ) {
9011556Srgrimes			STRTODEST(p);
90238887Stegge			if (*ap && sep)
9031556Srgrimes				STPUTC(sep, expdest);
9041556Srgrimes		}
9051556Srgrimes		break;
9061556Srgrimes	case '0':
9071556Srgrimes		p = arg0;
9081556Srgrimes		STRTODEST(p);
9091556Srgrimes		break;
9101556Srgrimes	default:
91118202Speter		if (is_digit(*name)) {
91218202Speter			num = atoi(name);
91318202Speter			if (num > 0 && num <= shellparam.nparam) {
91418202Speter				p = shellparam.p[num - 1];
91518202Speter				STRTODEST(p);
91618202Speter			}
9171556Srgrimes		}
9181556Srgrimes		break;
9191556Srgrimes	}
9201556Srgrimes}
9211556Srgrimes
9221556Srgrimes
9231556Srgrimes
9241556Srgrimes/*
9251556Srgrimes * Record the the fact that we have to scan this region of the
9261556Srgrimes * string for IFS characters.
9271556Srgrimes */
9281556Srgrimes
9291556SrgrimesSTATIC void
93090111Simprecordregion(int start, int end, int nulonly)
93117987Speter{
93225233Ssteve	struct ifsregion *ifsp;
9331556Srgrimes
9341556Srgrimes	if (ifslastp == NULL) {
9351556Srgrimes		ifsp = &ifsfirst;
9361556Srgrimes	} else {
9371556Srgrimes		ifsp = (struct ifsregion *)ckmalloc(sizeof (struct ifsregion));
9381556Srgrimes		ifslastp->next = ifsp;
9391556Srgrimes	}
9401556Srgrimes	ifslastp = ifsp;
9411556Srgrimes	ifslastp->next = NULL;
9421556Srgrimes	ifslastp->begoff = start;
9431556Srgrimes	ifslastp->endoff = end;
9441556Srgrimes	ifslastp->nulonly = nulonly;
9451556Srgrimes}
9461556Srgrimes
9471556Srgrimes
9481556Srgrimes
9491556Srgrimes/*
9501556Srgrimes * Break the argument string into pieces based upon IFS and add the
9511556Srgrimes * strings to the argument list.  The regions of the string to be
9521556Srgrimes * searched for IFS characters have been stored by recordregion.
9531556Srgrimes */
9541556SrgrimesSTATIC void
95590111Simpifsbreakup(char *string, struct arglist *arglist)
95690111Simp{
9571556Srgrimes	struct ifsregion *ifsp;
9581556Srgrimes	struct strlist *sp;
9591556Srgrimes	char *start;
96025233Ssteve	char *p;
9611556Srgrimes	char *q;
9621556Srgrimes	char *ifs;
96317987Speter	int ifsspc;
96438887Stegge	int nulonly;
9651556Srgrimes
96617987Speter
9671556Srgrimes	start = string;
96838887Stegge	ifsspc = 0;
96938887Stegge	nulonly = 0;
9701556Srgrimes	if (ifslastp != NULL) {
9711556Srgrimes		ifsp = &ifsfirst;
9721556Srgrimes		do {
9731556Srgrimes			p = string + ifsp->begoff;
97438887Stegge			nulonly = ifsp->nulonly;
975155301Sschweikh			ifs = nulonly ? nullstr :
97638887Stegge				( ifsset() ? ifsval() : " \t\n" );
97738887Stegge			ifsspc = 0;
9781556Srgrimes			while (p < string + ifsp->endoff) {
9791556Srgrimes				q = p;
9801556Srgrimes				if (*p == CTLESC)
9811556Srgrimes					p++;
98238887Stegge				if (strchr(ifs, *p)) {
98338887Stegge					if (!nulonly)
98438887Stegge						ifsspc = (strchr(" \t\n", *p) != NULL);
98538887Stegge					/* Ignore IFS whitespace at start */
98638887Stegge					if (q == start && ifsspc) {
98738887Stegge						p++;
98838887Stegge						start = p;
98938887Stegge						continue;
9901556Srgrimes					}
99138887Stegge					*q = '\0';
99238887Stegge					sp = (struct strlist *)stalloc(sizeof *sp);
99338887Stegge					sp->text = start;
99438887Stegge					*arglist->lastp = sp;
99538887Stegge					arglist->lastp = &sp->next;
99638887Stegge					p++;
99738887Stegge					if (!nulonly) {
9981556Srgrimes						for (;;) {
99938887Stegge							if (p >= string + ifsp->endoff) {
10001556Srgrimes								break;
100138887Stegge							}
10021556Srgrimes							q = p;
10031556Srgrimes							if (*p == CTLESC)
10041556Srgrimes								p++;
100538887Stegge							if (strchr(ifs, *p) == NULL ) {
10061556Srgrimes								p = q;
10071556Srgrimes								break;
100838887Stegge							} else if (strchr(" \t\n",*p) == NULL) {
100938887Stegge								if (ifsspc) {
101038887Stegge									p++;
101138887Stegge									ifsspc = 0;
101238887Stegge								} else {
101338887Stegge									p = q;
101438887Stegge									break;
101538887Stegge								}
101638887Stegge							} else
101738887Stegge								p++;
10181556Srgrimes						}
10191556Srgrimes					}
10201556Srgrimes					start = p;
102138887Stegge				} else
102238887Stegge					p++;
10231556Srgrimes			}
10241556Srgrimes		} while ((ifsp = ifsp->next) != NULL);
1025149825Srse		if (*start || (!ifsspc && start > string)) {
10261556Srgrimes			sp = (struct strlist *)stalloc(sizeof *sp);
10271556Srgrimes			sp->text = start;
10281556Srgrimes			*arglist->lastp = sp;
10291556Srgrimes			arglist->lastp = &sp->next;
10301556Srgrimes		}
10311556Srgrimes	} else {
10321556Srgrimes		sp = (struct strlist *)stalloc(sizeof *sp);
10331556Srgrimes		sp->text = start;
10341556Srgrimes		*arglist->lastp = sp;
10351556Srgrimes		arglist->lastp = &sp->next;
10361556Srgrimes	}
10371556Srgrimes}
10381556Srgrimes
10391556Srgrimes
10401556Srgrimes
10411556Srgrimes/*
10421556Srgrimes * Expand shell metacharacters.  At this point, the only control characters
10431556Srgrimes * should be escapes.  The results are stored in the list exparg.
10441556Srgrimes */
10451556Srgrimes
1046117261SddsSTATIC char *expdir;
10471556Srgrimes
10481556Srgrimes
10491556SrgrimesSTATIC void
105090111Simpexpandmeta(struct strlist *str, int flag __unused)
105117987Speter{
10521556Srgrimes	char *p;
10531556Srgrimes	struct strlist **savelastp;
10541556Srgrimes	struct strlist *sp;
10551556Srgrimes	char c;
10561556Srgrimes	/* TODO - EXP_REDIR */
10571556Srgrimes
10581556Srgrimes	while (str) {
10591556Srgrimes		if (fflag)
10601556Srgrimes			goto nometa;
10611556Srgrimes		p = str->text;
10621556Srgrimes		for (;;) {			/* fast check for meta chars */
10631556Srgrimes			if ((c = *p++) == '\0')
10641556Srgrimes				goto nometa;
10651556Srgrimes			if (c == '*' || c == '?' || c == '[' || c == '!')
10661556Srgrimes				break;
10671556Srgrimes		}
10681556Srgrimes		savelastp = exparg.lastp;
10691556Srgrimes		INTOFF;
10701556Srgrimes		if (expdir == NULL) {
10711556Srgrimes			int i = strlen(str->text);
10721556Srgrimes			expdir = ckmalloc(i < 2048 ? 2048 : i); /* XXX */
10731556Srgrimes		}
10741556Srgrimes
10751556Srgrimes		expmeta(expdir, str->text);
10761556Srgrimes		ckfree(expdir);
10771556Srgrimes		expdir = NULL;
10781556Srgrimes		INTON;
10791556Srgrimes		if (exparg.lastp == savelastp) {
10808855Srgrimes			/*
10818855Srgrimes			 * no matches
10821556Srgrimes			 */
10831556Srgrimesnometa:
10841556Srgrimes			*exparg.lastp = str;
10851556Srgrimes			rmescapes(str->text);
10861556Srgrimes			exparg.lastp = &str->next;
10871556Srgrimes		} else {
10881556Srgrimes			*exparg.lastp = NULL;
10891556Srgrimes			*savelastp = sp = expsort(*savelastp);
10901556Srgrimes			while (sp->next != NULL)
10911556Srgrimes				sp = sp->next;
10921556Srgrimes			exparg.lastp = &sp->next;
10931556Srgrimes		}
10941556Srgrimes		str = str->next;
10951556Srgrimes	}
10961556Srgrimes}
10971556Srgrimes
10981556Srgrimes
10991556Srgrimes/*
11001556Srgrimes * Do metacharacter (i.e. *, ?, [...]) expansion.
11011556Srgrimes */
11021556Srgrimes
11031556SrgrimesSTATIC void
110490111Simpexpmeta(char *enddir, char *name)
110590111Simp{
110625233Ssteve	char *p;
11071556Srgrimes	char *q;
11081556Srgrimes	char *start;
11091556Srgrimes	char *endname;
11101556Srgrimes	int metaflag;
11111556Srgrimes	struct stat statb;
11121556Srgrimes	DIR *dirp;
11131556Srgrimes	struct dirent *dp;
11141556Srgrimes	int atend;
11151556Srgrimes	int matchdot;
11161556Srgrimes
11171556Srgrimes	metaflag = 0;
11181556Srgrimes	start = name;
11191556Srgrimes	for (p = name ; ; p++) {
11201556Srgrimes		if (*p == '*' || *p == '?')
11211556Srgrimes			metaflag = 1;
11221556Srgrimes		else if (*p == '[') {
11231556Srgrimes			q = p + 1;
112426488Sache			if (*q == '!' || *q == '^')
11251556Srgrimes				q++;
11261556Srgrimes			for (;;) {
112738887Stegge				while (*q == CTLQUOTEMARK)
112838887Stegge					q++;
11291556Srgrimes				if (*q == CTLESC)
11301556Srgrimes					q++;
11311556Srgrimes				if (*q == '/' || *q == '\0')
11321556Srgrimes					break;
11331556Srgrimes				if (*++q == ']') {
11341556Srgrimes					metaflag = 1;
11351556Srgrimes					break;
11361556Srgrimes				}
11371556Srgrimes			}
11381556Srgrimes		} else if (*p == '!' && p[1] == '!'	&& (p == name || p[-1] == '/')) {
11391556Srgrimes			metaflag = 1;
11401556Srgrimes		} else if (*p == '\0')
11411556Srgrimes			break;
114238887Stegge		else if (*p == CTLQUOTEMARK)
114338887Stegge			continue;
11441556Srgrimes		else if (*p == CTLESC)
11451556Srgrimes			p++;
11461556Srgrimes		if (*p == '/') {
11471556Srgrimes			if (metaflag)
11481556Srgrimes				break;
11491556Srgrimes			start = p + 1;
11501556Srgrimes		}
11511556Srgrimes	}
11521556Srgrimes	if (metaflag == 0) {	/* we've reached the end of the file name */
11531556Srgrimes		if (enddir != expdir)
11541556Srgrimes			metaflag++;
11551556Srgrimes		for (p = name ; ; p++) {
115638887Stegge			if (*p == CTLQUOTEMARK)
115738887Stegge				continue;
11581556Srgrimes			if (*p == CTLESC)
11591556Srgrimes				p++;
11601556Srgrimes			*enddir++ = *p;
11611556Srgrimes			if (*p == '\0')
11621556Srgrimes				break;
11631556Srgrimes		}
1164147812Sdelphij		if (metaflag == 0 || lstat(expdir, &statb) >= 0)
11651556Srgrimes			addfname(expdir);
11661556Srgrimes		return;
11671556Srgrimes	}
11681556Srgrimes	endname = p;
11691556Srgrimes	if (start != name) {
11701556Srgrimes		p = name;
11711556Srgrimes		while (p < start) {
117238887Stegge			while (*p == CTLQUOTEMARK)
117338887Stegge				p++;
11741556Srgrimes			if (*p == CTLESC)
11751556Srgrimes				p++;
11761556Srgrimes			*enddir++ = *p++;
11771556Srgrimes		}
11781556Srgrimes	}
11791556Srgrimes	if (enddir == expdir) {
11801556Srgrimes		p = ".";
11811556Srgrimes	} else if (enddir == expdir + 1 && *expdir == '/') {
11821556Srgrimes		p = "/";
11831556Srgrimes	} else {
11841556Srgrimes		p = expdir;
11851556Srgrimes		enddir[-1] = '\0';
11861556Srgrimes	}
11871556Srgrimes	if ((dirp = opendir(p)) == NULL)
11881556Srgrimes		return;
11891556Srgrimes	if (enddir != expdir)
11901556Srgrimes		enddir[-1] = '/';
11911556Srgrimes	if (*endname == 0) {
11921556Srgrimes		atend = 1;
11931556Srgrimes	} else {
11941556Srgrimes		atend = 0;
11951556Srgrimes		*endname++ = '\0';
11961556Srgrimes	}
11971556Srgrimes	matchdot = 0;
119838887Stegge	p = start;
119938887Stegge	while (*p == CTLQUOTEMARK)
120038887Stegge		p++;
120138887Stegge	if (*p == CTLESC)
120238887Stegge		p++;
120338887Stegge	if (*p == '.')
12041556Srgrimes		matchdot++;
12051556Srgrimes	while (! int_pending() && (dp = readdir(dirp)) != NULL) {
12061556Srgrimes		if (dp->d_name[0] == '.' && ! matchdot)
12071556Srgrimes			continue;
120845514Stegge		if (patmatch(start, dp->d_name, 0)) {
12091556Srgrimes			if (atend) {
12101556Srgrimes				scopy(dp->d_name, enddir);
12111556Srgrimes				addfname(expdir);
12121556Srgrimes			} else {
121317987Speter				for (p = enddir, q = dp->d_name;
121417987Speter				     (*p++ = *q++) != '\0';)
121517987Speter					continue;
12161556Srgrimes				p[-1] = '/';
12171556Srgrimes				expmeta(p, endname);
12181556Srgrimes			}
12191556Srgrimes		}
12201556Srgrimes	}
12211556Srgrimes	closedir(dirp);
12221556Srgrimes	if (! atend)
12231556Srgrimes		endname[-1] = '/';
12241556Srgrimes}
12251556Srgrimes
12261556Srgrimes
12271556Srgrimes/*
12281556Srgrimes * Add a file name to the list.
12291556Srgrimes */
12301556Srgrimes
12311556SrgrimesSTATIC void
123290111Simpaddfname(char *name)
123390111Simp{
12341556Srgrimes	char *p;
12351556Srgrimes	struct strlist *sp;
12361556Srgrimes
12371556Srgrimes	p = stalloc(strlen(name) + 1);
12381556Srgrimes	scopy(name, p);
12391556Srgrimes	sp = (struct strlist *)stalloc(sizeof *sp);
12401556Srgrimes	sp->text = p;
12411556Srgrimes	*exparg.lastp = sp;
12421556Srgrimes	exparg.lastp = &sp->next;
12431556Srgrimes}
12441556Srgrimes
12451556Srgrimes
12461556Srgrimes/*
12471556Srgrimes * Sort the results of file name expansion.  It calculates the number of
12481556Srgrimes * strings to sort and then calls msort (short for merge sort) to do the
12491556Srgrimes * work.
12501556Srgrimes */
12511556Srgrimes
12521556SrgrimesSTATIC struct strlist *
125390111Simpexpsort(struct strlist *str)
125490111Simp{
12551556Srgrimes	int len;
12561556Srgrimes	struct strlist *sp;
12571556Srgrimes
12581556Srgrimes	len = 0;
12591556Srgrimes	for (sp = str ; sp ; sp = sp->next)
12601556Srgrimes		len++;
12611556Srgrimes	return msort(str, len);
12621556Srgrimes}
12631556Srgrimes
12641556Srgrimes
12651556SrgrimesSTATIC struct strlist *
126690111Simpmsort(struct strlist *list, int len)
126717987Speter{
126817987Speter	struct strlist *p, *q = NULL;
12691556Srgrimes	struct strlist **lpp;
12701556Srgrimes	int half;
12711556Srgrimes	int n;
12721556Srgrimes
12731556Srgrimes	if (len <= 1)
12741556Srgrimes		return list;
12758855Srgrimes	half = len >> 1;
12761556Srgrimes	p = list;
12771556Srgrimes	for (n = half ; --n >= 0 ; ) {
12781556Srgrimes		q = p;
12791556Srgrimes		p = p->next;
12801556Srgrimes	}
12811556Srgrimes	q->next = NULL;			/* terminate first half of list */
12821556Srgrimes	q = msort(list, half);		/* sort first half of list */
12831556Srgrimes	p = msort(p, len - half);		/* sort second half */
12841556Srgrimes	lpp = &list;
12851556Srgrimes	for (;;) {
12861556Srgrimes		if (strcmp(p->text, q->text) < 0) {
12871556Srgrimes			*lpp = p;
12881556Srgrimes			lpp = &p->next;
12891556Srgrimes			if ((p = *lpp) == NULL) {
12901556Srgrimes				*lpp = q;
12911556Srgrimes				break;
12921556Srgrimes			}
12931556Srgrimes		} else {
12941556Srgrimes			*lpp = q;
12951556Srgrimes			lpp = &q->next;
12961556Srgrimes			if ((q = *lpp) == NULL) {
12971556Srgrimes				*lpp = p;
12981556Srgrimes				break;
12991556Srgrimes			}
13001556Srgrimes		}
13011556Srgrimes	}
13021556Srgrimes	return list;
13031556Srgrimes}
13041556Srgrimes
13051556Srgrimes
13061556Srgrimes
13071556Srgrimes/*
13081556Srgrimes * Returns true if the pattern matches the string.
13091556Srgrimes */
13101556Srgrimes
13111556Srgrimesint
131290111Simppatmatch(char *pattern, char *string, int squoted)
131390111Simp{
13141556Srgrimes#ifdef notdef
13151556Srgrimes	if (pattern[0] == '!' && pattern[1] == '!')
13161556Srgrimes		return 1 - pmatch(pattern + 2, string);
13171556Srgrimes	else
13181556Srgrimes#endif
131945514Stegge		return pmatch(pattern, string, squoted);
13201556Srgrimes}
13211556Srgrimes
132217987Speter
132317525SacheSTATIC int
132490111Simppmatch(char *pattern, char *string, int squoted)
132590111Simp{
132625233Ssteve	char *p, *q;
132725233Ssteve	char c;
13281556Srgrimes
13291556Srgrimes	p = pattern;
13301556Srgrimes	q = string;
13311556Srgrimes	for (;;) {
13321556Srgrimes		switch (c = *p++) {
13331556Srgrimes		case '\0':
13341556Srgrimes			goto breakloop;
13351556Srgrimes		case CTLESC:
133645514Stegge			if (squoted && *q == CTLESC)
133745514Stegge				q++;
13381556Srgrimes			if (*q++ != *p++)
13391556Srgrimes				return 0;
13401556Srgrimes			break;
134138887Stegge		case CTLQUOTEMARK:
134238887Stegge			continue;
13431556Srgrimes		case '?':
134445514Stegge			if (squoted && *q == CTLESC)
134545514Stegge				q++;
13461556Srgrimes			if (*q++ == '\0')
13471556Srgrimes				return 0;
13481556Srgrimes			break;
13491556Srgrimes		case '*':
13501556Srgrimes			c = *p;
135138887Stegge			while (c == CTLQUOTEMARK || c == '*')
135238887Stegge				c = *++p;
135338887Stegge			if (c != CTLESC &&  c != CTLQUOTEMARK &&
135438887Stegge			    c != '?' && c != '*' && c != '[') {
13551556Srgrimes				while (*q != c) {
135645514Stegge					if (squoted && *q == CTLESC &&
135745514Stegge					    q[1] == c)
135845514Stegge						break;
13591556Srgrimes					if (*q == '\0')
13601556Srgrimes						return 0;
136145514Stegge					if (squoted && *q == CTLESC)
136245514Stegge						q++;
13631556Srgrimes					q++;
13641556Srgrimes				}
13651556Srgrimes			}
13661556Srgrimes			do {
136745514Stegge				if (pmatch(p, q, squoted))
13681556Srgrimes					return 1;
136945514Stegge				if (squoted && *q == CTLESC)
137045514Stegge					q++;
13711556Srgrimes			} while (*q++ != '\0');
13721556Srgrimes			return 0;
13731556Srgrimes		case '[': {
13741556Srgrimes			char *endp;
13751556Srgrimes			int invert, found;
13761556Srgrimes			char chr;
13771556Srgrimes
13781556Srgrimes			endp = p;
137926488Sache			if (*endp == '!' || *endp == '^')
13801556Srgrimes				endp++;
13811556Srgrimes			for (;;) {
138238887Stegge				while (*endp == CTLQUOTEMARK)
138338887Stegge					endp++;
13841556Srgrimes				if (*endp == '\0')
13851556Srgrimes					goto dft;		/* no matching ] */
13861556Srgrimes				if (*endp == CTLESC)
13871556Srgrimes					endp++;
13881556Srgrimes				if (*++endp == ']')
13891556Srgrimes					break;
13901556Srgrimes			}
13911556Srgrimes			invert = 0;
139226488Sache			if (*p == '!' || *p == '^') {
13931556Srgrimes				invert++;
13941556Srgrimes				p++;
13951556Srgrimes			}
13961556Srgrimes			found = 0;
13971556Srgrimes			chr = *q++;
139845514Stegge			if (squoted && chr == CTLESC)
139945514Stegge				chr = *q++;
140017987Speter			if (chr == '\0')
140117987Speter				return 0;
14021556Srgrimes			c = *p++;
14031556Srgrimes			do {
140438887Stegge				if (c == CTLQUOTEMARK)
140538887Stegge					continue;
14061556Srgrimes				if (c == CTLESC)
14071556Srgrimes					c = *p++;
14081556Srgrimes				if (*p == '-' && p[1] != ']') {
14091556Srgrimes					p++;
141038887Stegge					while (*p == CTLQUOTEMARK)
141138887Stegge						p++;
14121556Srgrimes					if (*p == CTLESC)
14131556Srgrimes						p++;
141417557Sache					if (   collate_range_cmp(chr, c) >= 0
141517557Sache					    && collate_range_cmp(chr, *p) <= 0
141617525Sache					   )
14171556Srgrimes						found = 1;
14181556Srgrimes					p++;
14191556Srgrimes				} else {
14201556Srgrimes					if (chr == c)
14211556Srgrimes						found = 1;
14221556Srgrimes				}
14231556Srgrimes			} while ((c = *p++) != ']');
14241556Srgrimes			if (found == invert)
14251556Srgrimes				return 0;
14261556Srgrimes			break;
14271556Srgrimes		}
14281556Srgrimesdft:	        default:
142945514Stegge			if (squoted && *q == CTLESC)
143045514Stegge				q++;
14311556Srgrimes			if (*q++ != c)
14321556Srgrimes				return 0;
14331556Srgrimes			break;
14341556Srgrimes		}
14351556Srgrimes	}
14361556Srgrimesbreakloop:
14371556Srgrimes	if (*q != '\0')
14381556Srgrimes		return 0;
14391556Srgrimes	return 1;
14401556Srgrimes}
14411556Srgrimes
14421556Srgrimes
14431556Srgrimes
14441556Srgrimes/*
14451556Srgrimes * Remove any CTLESC characters from a string.
14461556Srgrimes */
14471556Srgrimes
14481556Srgrimesvoid
144990111Simprmescapes(char *str)
145038887Stegge{
145125233Ssteve	char *p, *q;
14521556Srgrimes
14531556Srgrimes	p = str;
145438887Stegge	while (*p != CTLESC && *p != CTLQUOTEMARK) {
14551556Srgrimes		if (*p++ == '\0')
14561556Srgrimes			return;
14571556Srgrimes	}
14581556Srgrimes	q = p;
14591556Srgrimes	while (*p) {
146038887Stegge		if (*p == CTLQUOTEMARK) {
146138887Stegge			p++;
146238887Stegge			continue;
146338887Stegge		}
14641556Srgrimes		if (*p == CTLESC)
14651556Srgrimes			p++;
14661556Srgrimes		*q++ = *p++;
14671556Srgrimes	}
14681556Srgrimes	*q = '\0';
14691556Srgrimes}
14701556Srgrimes
14711556Srgrimes
14721556Srgrimes
14731556Srgrimes/*
14741556Srgrimes * See if a pattern matches in a case statement.
14751556Srgrimes */
14761556Srgrimes
14771556Srgrimesint
147890111Simpcasematch(union node *pattern, char *val)
147990111Simp{
14801556Srgrimes	struct stackmark smark;
14811556Srgrimes	int result;
14821556Srgrimes	char *p;
14831556Srgrimes
14841556Srgrimes	setstackmark(&smark);
14851556Srgrimes	argbackq = pattern->narg.backquote;
14861556Srgrimes	STARTSTACKSTR(expdest);
14871556Srgrimes	ifslastp = NULL;
14881556Srgrimes	argstr(pattern->narg.text, EXP_TILDE | EXP_CASE);
14891556Srgrimes	STPUTC('\0', expdest);
14901556Srgrimes	p = grabstackstr(expdest);
149145514Stegge	result = patmatch(p, val, 0);
14921556Srgrimes	popstackmark(&smark);
14931556Srgrimes	return result;
14941556Srgrimes}
149517987Speter
149617987Speter/*
149717987Speter * Our own itoa().
149817987Speter */
149917987Speter
150017987SpeterSTATIC char *
150190111Simpcvtnum(int num, char *buf)
150290111Simp{
150317987Speter	char temp[32];
150417987Speter	int neg = num < 0;
150517987Speter	char *p = temp + 31;
150617987Speter
150717987Speter	temp[31] = '\0';
150817987Speter
150917987Speter	do {
151017987Speter		*--p = num % 10 + '0';
151117987Speter	} while ((num /= 10) != 0);
151217987Speter
151317987Speter	if (neg)
151417987Speter		*--p = '-';
151517987Speter
151617987Speter	while (*p)
151717987Speter		STPUTC(*p++, buf);
151817987Speter	return buf;
151917987Speter}
1520108286Stjr
1521108286Stjr/*
1522108286Stjr * Do most of the work for wordexp(3).
1523108286Stjr */
1524108286Stjr
1525108286Stjrint
1526108286Stjrwordexpcmd(int argc, char **argv)
1527108286Stjr{
1528108286Stjr	size_t len;
1529108286Stjr	int i;
1530108286Stjr
1531108286Stjr	out1fmt("%08x", argc - 1);
1532108286Stjr	for (i = 1, len = 0; i < argc; i++)
1533108286Stjr		len += strlen(argv[i]);
1534108286Stjr	out1fmt("%08x", (int)len);
1535108286Stjr	for (i = 1; i < argc; i++) {
1536108286Stjr		out1str(argv[i]);
1537108286Stjr		out1c('\0');
1538108286Stjr	}
1539108286Stjr        return (0);
1540108286Stjr}
1541