expand.c revision 200988
1/*-
2 * Copyright (c) 1991, 1993
3 *	The Regents of the University of California.  All rights reserved.
4 *
5 * This code is derived from software contributed to Berkeley by
6 * Kenneth Almquist.
7 *
8 * Redistribution and use in source and binary forms, with or without
9 * modification, are permitted provided that the following conditions
10 * are met:
11 * 1. Redistributions of source code must retain the above copyright
12 *    notice, this list of conditions and the following disclaimer.
13 * 2. Redistributions in binary form must reproduce the above copyright
14 *    notice, this list of conditions and the following disclaimer in the
15 *    documentation and/or other materials provided with the distribution.
16 * 4. Neither the name of the University nor the names of its contributors
17 *    may be used to endorse or promote products derived from this software
18 *    without specific prior written permission.
19 *
20 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
21 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
22 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
23 * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
24 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
25 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
26 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
27 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
28 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
29 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
30 * SUCH DAMAGE.
31 */
32
33#ifndef lint
34#if 0
35static char sccsid[] = "@(#)expand.c	8.5 (Berkeley) 5/15/95";
36#endif
37#endif /* not lint */
38#include <sys/cdefs.h>
39__FBSDID("$FreeBSD: head/bin/sh/expand.c 200988 2009-12-25 15:29:18Z jilles $");
40
41#include <sys/types.h>
42#include <sys/time.h>
43#include <sys/stat.h>
44#include <errno.h>
45#include <dirent.h>
46#include <unistd.h>
47#include <pwd.h>
48#include <stdlib.h>
49#include <limits.h>
50#include <stdio.h>
51#include <string.h>
52
53/*
54 * Routines to expand arguments to commands.  We have to deal with
55 * backquotes, shell variables, and file metacharacters.
56 */
57
58#include "shell.h"
59#include "main.h"
60#include "nodes.h"
61#include "eval.h"
62#include "expand.h"
63#include "syntax.h"
64#include "parser.h"
65#include "jobs.h"
66#include "options.h"
67#include "var.h"
68#include "input.h"
69#include "output.h"
70#include "memalloc.h"
71#include "error.h"
72#include "mystring.h"
73#include "arith.h"
74#include "show.h"
75
76/*
77 * Structure specifying which parts of the string should be searched
78 * for IFS characters.
79 */
80
81struct ifsregion {
82	struct ifsregion *next;	/* next region in list */
83	int begoff;		/* offset of start of region */
84	int endoff;		/* offset of end of region */
85	int inquotes;		/* search for nul bytes only */
86};
87
88
89STATIC char *expdest;			/* output of current string */
90STATIC struct nodelist *argbackq;	/* list of back quote expressions */
91STATIC struct ifsregion ifsfirst;	/* first struct in list of ifs regions */
92STATIC struct ifsregion *ifslastp;	/* last struct in list */
93STATIC struct arglist exparg;		/* holds expanded arg list */
94
95STATIC void argstr(char *, int);
96STATIC char *exptilde(char *, int);
97STATIC void expbackq(union node *, int, int);
98STATIC int subevalvar(char *, char *, int, int, int, int);
99STATIC char *evalvar(char *, int);
100STATIC int varisset(char *, int);
101STATIC void varvalue(char *, int, int, int);
102STATIC void recordregion(int, int, int);
103STATIC void removerecordregions(int);
104STATIC void ifsbreakup(char *, struct arglist *);
105STATIC void expandmeta(struct strlist *, int);
106STATIC void expmeta(char *, char *);
107STATIC void addfname(char *);
108STATIC struct strlist *expsort(struct strlist *);
109STATIC struct strlist *msort(struct strlist *, int);
110STATIC int pmatch(const char *, const char *, int);
111STATIC char *cvtnum(int, char *);
112STATIC int collate_range_cmp(int, int);
113
114STATIC int
115collate_range_cmp(int c1, int c2)
116{
117	static char s1[2], s2[2];
118
119	s1[0] = c1;
120	s2[0] = c2;
121	return (strcoll(s1, s2));
122}
123
124/*
125 * Expand shell variables and backquotes inside a here document.
126 *	union node *arg		the document
127 *	int fd;			where to write the expanded version
128 */
129
130void
131expandhere(union node *arg, int fd)
132{
133	herefd = fd;
134	expandarg(arg, (struct arglist *)NULL, 0);
135	xwrite(fd, stackblock(), expdest - stackblock());
136}
137
138
139/*
140 * Perform variable substitution and command substitution on an argument,
141 * placing the resulting list of arguments in arglist.  If EXP_FULL is true,
142 * perform splitting and file name expansion.  When arglist is NULL, perform
143 * here document expansion.
144 */
145
146void
147expandarg(union node *arg, struct arglist *arglist, int flag)
148{
149	struct strlist *sp;
150	char *p;
151
152	argbackq = arg->narg.backquote;
153	STARTSTACKSTR(expdest);
154	ifsfirst.next = NULL;
155	ifslastp = NULL;
156	argstr(arg->narg.text, flag);
157	if (arglist == NULL) {
158		return;			/* here document expanded */
159	}
160	STPUTC('\0', expdest);
161	p = grabstackstr(expdest);
162	exparg.lastp = &exparg.list;
163	/*
164	 * TODO - EXP_REDIR
165	 */
166	if (flag & EXP_FULL) {
167		ifsbreakup(p, &exparg);
168		*exparg.lastp = NULL;
169		exparg.lastp = &exparg.list;
170		expandmeta(exparg.list, flag);
171	} else {
172		if (flag & EXP_REDIR) /*XXX - for now, just remove escapes */
173			rmescapes(p);
174		sp = (struct strlist *)stalloc(sizeof (struct strlist));
175		sp->text = p;
176		*exparg.lastp = sp;
177		exparg.lastp = &sp->next;
178	}
179	while (ifsfirst.next != NULL) {
180		struct ifsregion *ifsp;
181		INTOFF;
182		ifsp = ifsfirst.next->next;
183		ckfree(ifsfirst.next);
184		ifsfirst.next = ifsp;
185		INTON;
186	}
187	*exparg.lastp = NULL;
188	if (exparg.list) {
189		*arglist->lastp = exparg.list;
190		arglist->lastp = exparg.lastp;
191	}
192}
193
194
195
196/*
197 * Perform variable and command substitution.  If EXP_FULL is set, output CTLESC
198 * characters to allow for further processing.  Otherwise treat
199 * $@ like $* since no splitting will be performed.
200 */
201
202STATIC void
203argstr(char *p, int flag)
204{
205	char c;
206	int quotes = flag & (EXP_FULL | EXP_CASE | EXP_REDIR);	/* do CTLESC */
207	int firsteq = 1;
208
209	if (*p == '~' && (flag & (EXP_TILDE | EXP_VARTILDE)))
210		p = exptilde(p, flag);
211	for (;;) {
212		switch (c = *p++) {
213		case '\0':
214		case CTLENDVAR: /* ??? */
215			goto breakloop;
216		case CTLQUOTEMARK:
217			/* "$@" syntax adherence hack */
218			if (p[0] == CTLVAR && p[2] == '@' && p[3] == '=')
219				break;
220			if ((flag & EXP_FULL) != 0)
221				STPUTC(c, expdest);
222			break;
223		case CTLESC:
224			if (quotes)
225				STPUTC(c, expdest);
226			c = *p++;
227			STPUTC(c, expdest);
228			break;
229		case CTLVAR:
230			p = evalvar(p, flag);
231			break;
232		case CTLBACKQ:
233		case CTLBACKQ|CTLQUOTE:
234			expbackq(argbackq->n, c & CTLQUOTE, flag);
235			argbackq = argbackq->next;
236			break;
237		case CTLENDARI:
238			expari(flag);
239			break;
240		case ':':
241		case '=':
242			/*
243			 * sort of a hack - expand tildes in variable
244			 * assignments (after the first '=' and after ':'s).
245			 */
246			STPUTC(c, expdest);
247			if (flag & EXP_VARTILDE && *p == '~') {
248				if (c == '=') {
249					if (firsteq)
250						firsteq = 0;
251					else
252						break;
253				}
254				p = exptilde(p, flag);
255			}
256			break;
257		default:
258			STPUTC(c, expdest);
259		}
260	}
261breakloop:;
262}
263
264STATIC char *
265exptilde(char *p, int flag)
266{
267	char c, *startp = p;
268	struct passwd *pw;
269	char *home;
270	int quotes = flag & (EXP_FULL | EXP_CASE | EXP_REDIR);
271
272	while ((c = *p) != '\0') {
273		switch(c) {
274		case CTLESC: /* This means CTL* are always considered quoted. */
275		case CTLVAR:
276		case CTLENDVAR:
277		case CTLBACKQ:
278		case CTLBACKQ | CTLQUOTE:
279		case CTLARI:
280		case CTLENDARI:
281		case CTLQUOTEMARK:
282			return (startp);
283		case ':':
284			if (flag & EXP_VARTILDE)
285				goto done;
286			break;
287		case '/':
288			goto done;
289		}
290		p++;
291	}
292done:
293	*p = '\0';
294	if (*(startp+1) == '\0') {
295		if ((home = lookupvar("HOME")) == NULL)
296			goto lose;
297	} else {
298		if ((pw = getpwnam(startp+1)) == NULL)
299			goto lose;
300		home = pw->pw_dir;
301	}
302	if (*home == '\0')
303		goto lose;
304	*p = c;
305	while ((c = *home++) != '\0') {
306		if (quotes && SQSYNTAX[(int)c] == CCTL)
307			STPUTC(CTLESC, expdest);
308		STPUTC(c, expdest);
309	}
310	return (p);
311lose:
312	*p = c;
313	return (startp);
314}
315
316
317STATIC void
318removerecordregions(int endoff)
319{
320	if (ifslastp == NULL)
321		return;
322
323	if (ifsfirst.endoff > endoff) {
324		while (ifsfirst.next != NULL) {
325			struct ifsregion *ifsp;
326			INTOFF;
327			ifsp = ifsfirst.next->next;
328			ckfree(ifsfirst.next);
329			ifsfirst.next = ifsp;
330			INTON;
331		}
332		if (ifsfirst.begoff > endoff)
333			ifslastp = NULL;
334		else {
335			ifslastp = &ifsfirst;
336			ifsfirst.endoff = endoff;
337		}
338		return;
339	}
340
341	ifslastp = &ifsfirst;
342	while (ifslastp->next && ifslastp->next->begoff < endoff)
343		ifslastp=ifslastp->next;
344	while (ifslastp->next != NULL) {
345		struct ifsregion *ifsp;
346		INTOFF;
347		ifsp = ifslastp->next->next;
348		ckfree(ifslastp->next);
349		ifslastp->next = ifsp;
350		INTON;
351	}
352	if (ifslastp->endoff > endoff)
353		ifslastp->endoff = endoff;
354}
355
356/*
357 * Expand arithmetic expression.  Backup to start of expression,
358 * evaluate, place result in (backed up) result, adjust string position.
359 */
360void
361expari(int flag)
362{
363	char *p, *start;
364	arith_t result;
365	int begoff;
366	int quotes = flag & (EXP_FULL | EXP_CASE | EXP_REDIR);
367	int quoted;
368
369
370	/*
371	 * This routine is slightly over-complicated for
372	 * efficiency.  First we make sure there is
373	 * enough space for the result, which may be bigger
374	 * than the expression if we add exponentiation.  Next we
375	 * scan backwards looking for the start of arithmetic.  If the
376	 * next previous character is a CTLESC character, then we
377	 * have to rescan starting from the beginning since CTLESC
378	 * characters have to be processed left to right.
379	 */
380	CHECKSTRSPACE(DIGITS(result) - 2, expdest);
381	USTPUTC('\0', expdest);
382	start = stackblock();
383	p = expdest - 2;
384	while (p >= start && *p != CTLARI)
385		--p;
386	if (p < start || *p != CTLARI)
387		error("missing CTLARI (shouldn't happen)");
388	if (p > start && *(p - 1) == CTLESC)
389		for (p = start; *p != CTLARI; p++)
390			if (*p == CTLESC)
391				p++;
392
393	if (p[1] == '"')
394		quoted=1;
395	else
396		quoted=0;
397	begoff = p - start;
398	removerecordregions(begoff);
399	if (quotes)
400		rmescapes(p+2);
401	result = arith(p+2);
402	fmtstr(p, DIGITS(result), ARITH_FORMAT_STR, result);
403	while (*p++)
404		;
405	if (quoted == 0)
406		recordregion(begoff, p - 1 - start, 0);
407	result = expdest - p + 1;
408	STADJUST(-result, expdest);
409}
410
411
412/*
413 * Expand stuff in backwards quotes.
414 */
415
416STATIC void
417expbackq(union node *cmd, int quoted, int flag)
418{
419	struct backcmd in;
420	int i;
421	char buf[128];
422	char *p;
423	char *dest = expdest;
424	struct ifsregion saveifs, *savelastp;
425	struct nodelist *saveargbackq;
426	char lastc;
427	int startloc = dest - stackblock();
428	char const *syntax = quoted? DQSYNTAX : BASESYNTAX;
429	int saveherefd;
430	int quotes = flag & (EXP_FULL | EXP_CASE | EXP_REDIR);
431	int nnl;
432
433	INTOFF;
434	saveifs = ifsfirst;
435	savelastp = ifslastp;
436	saveargbackq = argbackq;
437	saveherefd = herefd;
438	herefd = -1;
439	p = grabstackstr(dest);
440	evalbackcmd(cmd, &in);
441	ungrabstackstr(p, dest);
442	ifsfirst = saveifs;
443	ifslastp = savelastp;
444	argbackq = saveargbackq;
445	herefd = saveherefd;
446
447	p = in.buf;
448	lastc = '\0';
449	nnl = 0;
450	/* Don't copy trailing newlines */
451	for (;;) {
452		if (--in.nleft < 0) {
453			if (in.fd < 0)
454				break;
455			while ((i = read(in.fd, buf, sizeof buf)) < 0 && errno == EINTR);
456			TRACE(("expbackq: read returns %d\n", i));
457			if (i <= 0)
458				break;
459			p = buf;
460			in.nleft = i - 1;
461		}
462		lastc = *p++;
463		if (lastc != '\0') {
464			if (quotes && syntax[(int)lastc] == CCTL)
465				STPUTC(CTLESC, dest);
466			if (lastc == '\n') {
467				nnl++;
468			} else {
469				while (nnl > 0) {
470					nnl--;
471					STPUTC('\n', dest);
472				}
473				STPUTC(lastc, dest);
474			}
475		}
476	}
477
478	if (in.fd >= 0)
479		close(in.fd);
480	if (in.buf)
481		ckfree(in.buf);
482	if (in.jp)
483		exitstatus = waitforjob(in.jp, (int *)NULL);
484	if (quoted == 0)
485		recordregion(startloc, dest - stackblock(), 0);
486	TRACE(("evalbackq: size=%d: \"%.*s\"\n",
487		(dest - stackblock()) - startloc,
488		(dest - stackblock()) - startloc,
489		stackblock() + startloc));
490	expdest = dest;
491	INTON;
492}
493
494
495
496STATIC int
497subevalvar(char *p, char *str, int strloc, int subtype, int startloc,
498  int varflags)
499{
500	char *startp;
501	char *loc = NULL;
502	char *q;
503	int c = 0;
504	int saveherefd = herefd;
505	struct nodelist *saveargbackq = argbackq;
506	int amount;
507
508	herefd = -1;
509	argstr(p, 0);
510	STACKSTRNUL(expdest);
511	herefd = saveherefd;
512	argbackq = saveargbackq;
513	startp = stackblock() + startloc;
514	if (str == NULL)
515	    str = stackblock() + strloc;
516
517	switch (subtype) {
518	case VSASSIGN:
519		setvar(str, startp, 0);
520		amount = startp - expdest;
521		STADJUST(amount, expdest);
522		varflags &= ~VSNUL;
523		if (c != 0)
524			*loc = c;
525		return 1;
526
527	case VSQUESTION:
528		if (*p != CTLENDVAR) {
529			outfmt(&errout, "%s\n", startp);
530			error((char *)NULL);
531		}
532		error("%.*s: parameter %snot set", (int)(p - str - 1),
533		      str, (varflags & VSNUL) ? "null or "
534					      : nullstr);
535		return 0;
536
537	case VSTRIMLEFT:
538		for (loc = startp; loc < str; loc++) {
539			c = *loc;
540			*loc = '\0';
541			if (patmatch(str, startp, varflags & VSQUOTE)) {
542				*loc = c;
543				goto recordleft;
544			}
545			*loc = c;
546			if ((varflags & VSQUOTE) && *loc == CTLESC)
547				loc++;
548		}
549		return 0;
550
551	case VSTRIMLEFTMAX:
552		for (loc = str - 1; loc >= startp;) {
553			c = *loc;
554			*loc = '\0';
555			if (patmatch(str, startp, varflags & VSQUOTE)) {
556				*loc = c;
557				goto recordleft;
558			}
559			*loc = c;
560			loc--;
561			if ((varflags & VSQUOTE) && loc > startp &&
562			    *(loc - 1) == CTLESC) {
563				for (q = startp; q < loc; q++)
564					if (*q == CTLESC)
565						q++;
566				if (q > loc)
567					loc--;
568			}
569		}
570		return 0;
571
572	case VSTRIMRIGHT:
573		for (loc = str - 1; loc >= startp;) {
574			if (patmatch(str, loc, varflags & VSQUOTE)) {
575				amount = loc - expdest;
576				STADJUST(amount, expdest);
577				return 1;
578			}
579			loc--;
580			if ((varflags & VSQUOTE) && loc > startp &&
581			    *(loc - 1) == CTLESC) {
582				for (q = startp; q < loc; q++)
583					if (*q == CTLESC)
584						q++;
585				if (q > loc)
586					loc--;
587			}
588		}
589		return 0;
590
591	case VSTRIMRIGHTMAX:
592		for (loc = startp; loc < str - 1; loc++) {
593			if (patmatch(str, loc, varflags & VSQUOTE)) {
594				amount = loc - expdest;
595				STADJUST(amount, expdest);
596				return 1;
597			}
598			if ((varflags & VSQUOTE) && *loc == CTLESC)
599				loc++;
600		}
601		return 0;
602
603
604	default:
605		abort();
606	}
607
608recordleft:
609	amount = ((str - 1) - (loc - startp)) - expdest;
610	STADJUST(amount, expdest);
611	while (loc != str - 1)
612		*startp++ = *loc++;
613	return 1;
614}
615
616
617/*
618 * Expand a variable, and return a pointer to the next character in the
619 * input string.
620 */
621
622STATIC char *
623evalvar(char *p, int flag)
624{
625	int subtype;
626	int varflags;
627	char *var;
628	char *val;
629	int patloc;
630	int c;
631	int set;
632	int special;
633	int startloc;
634	int varlen;
635	int easy;
636	int quotes = flag & (EXP_FULL | EXP_CASE | EXP_REDIR);
637
638	varflags = (unsigned char)*p++;
639	subtype = varflags & VSTYPE;
640	var = p;
641	special = 0;
642	if (! is_name(*p))
643		special = 1;
644	p = strchr(p, '=') + 1;
645again: /* jump here after setting a variable with ${var=text} */
646	if (varflags & VSLINENO) {
647		set = 1;
648		special = 0;
649		val = var;
650		p[-1] = '\0';	/* temporarily overwrite '=' to have \0
651				   terminated string */
652	} else if (special) {
653		set = varisset(var, varflags & VSNUL);
654		val = NULL;
655	} else {
656		val = bltinlookup(var, 1);
657		if (val == NULL || ((varflags & VSNUL) && val[0] == '\0')) {
658			val = NULL;
659			set = 0;
660		} else
661			set = 1;
662	}
663	varlen = 0;
664	startloc = expdest - stackblock();
665	if (!set && uflag && *var != '@' && *var != '*') {
666		switch (subtype) {
667		case VSNORMAL:
668		case VSTRIMLEFT:
669		case VSTRIMLEFTMAX:
670		case VSTRIMRIGHT:
671		case VSTRIMRIGHTMAX:
672		case VSLENGTH:
673			error("%.*s: parameter not set", (int)(p - var - 1),
674			    var);
675		}
676	}
677	if (set && subtype != VSPLUS) {
678		/* insert the value of the variable */
679		if (special) {
680			varvalue(var, varflags & VSQUOTE, subtype, flag);
681			if (subtype == VSLENGTH) {
682				varlen = expdest - stackblock() - startloc;
683				STADJUST(-varlen, expdest);
684			}
685		} else {
686			char const *syntax = (varflags & VSQUOTE) ? DQSYNTAX
687								  : BASESYNTAX;
688
689			if (subtype == VSLENGTH) {
690				for (;*val; val++)
691					varlen++;
692			}
693			else {
694				while (*val) {
695					if (quotes &&
696					    syntax[(int)*val] == CCTL)
697						STPUTC(CTLESC, expdest);
698					STPUTC(*val++, expdest);
699				}
700
701			}
702		}
703	}
704
705	if (subtype == VSPLUS)
706		set = ! set;
707
708	easy = ((varflags & VSQUOTE) == 0 ||
709		(*var == '@' && shellparam.nparam != 1));
710
711
712	switch (subtype) {
713	case VSLENGTH:
714		expdest = cvtnum(varlen, expdest);
715		goto record;
716
717	case VSNORMAL:
718		if (!easy)
719			break;
720record:
721		recordregion(startloc, expdest - stackblock(),
722			     varflags & VSQUOTE);
723		break;
724
725	case VSPLUS:
726	case VSMINUS:
727		if (!set) {
728			argstr(p, flag);
729			break;
730		}
731		if (easy)
732			goto record;
733		break;
734
735	case VSTRIMLEFT:
736	case VSTRIMLEFTMAX:
737	case VSTRIMRIGHT:
738	case VSTRIMRIGHTMAX:
739		if (!set)
740			break;
741		/*
742		 * Terminate the string and start recording the pattern
743		 * right after it
744		 */
745		STPUTC('\0', expdest);
746		patloc = expdest - stackblock();
747		if (subevalvar(p, NULL, patloc, subtype,
748			       startloc, varflags) == 0) {
749			int amount = (expdest - stackblock() - patloc) + 1;
750			STADJUST(-amount, expdest);
751		}
752		/* Remove any recorded regions beyond start of variable */
753		removerecordregions(startloc);
754		goto record;
755
756	case VSASSIGN:
757	case VSQUESTION:
758		if (!set) {
759			if (subevalvar(p, var, 0, subtype, startloc, varflags)) {
760				varflags &= ~VSNUL;
761				/*
762				 * Remove any recorded regions beyond
763				 * start of variable
764				 */
765				removerecordregions(startloc);
766				goto again;
767			}
768			break;
769		}
770		if (easy)
771			goto record;
772		break;
773
774	case VSERROR:
775		c = p - var - 1;
776		error("${%.*s%s}: Bad substitution", c, var,
777		    (c > 0 && *p != CTLENDVAR) ? "..." : "");
778
779	default:
780		abort();
781	}
782	p[-1] = '=';	/* recover overwritten '=' */
783
784	if (subtype != VSNORMAL) {	/* skip to end of alternative */
785		int nesting = 1;
786		for (;;) {
787			if ((c = *p++) == CTLESC)
788				p++;
789			else if (c == CTLBACKQ || c == (CTLBACKQ|CTLQUOTE)) {
790				if (set)
791					argbackq = argbackq->next;
792			} else if (c == CTLVAR) {
793				if ((*p++ & VSTYPE) != VSNORMAL)
794					nesting++;
795			} else if (c == CTLENDVAR) {
796				if (--nesting == 0)
797					break;
798			}
799		}
800	}
801	return p;
802}
803
804
805
806/*
807 * Test whether a specialized variable is set.
808 */
809
810STATIC int
811varisset(char *name, int nulok)
812{
813
814	if (*name == '!')
815		return backgndpid != -1;
816	else if (*name == '@' || *name == '*') {
817		if (*shellparam.p == NULL)
818			return 0;
819
820		if (nulok) {
821			char **av;
822
823			for (av = shellparam.p; *av; av++)
824				if (**av != '\0')
825					return 1;
826			return 0;
827		}
828	} else if (is_digit(*name)) {
829		char *ap;
830		int num = atoi(name);
831
832		if (num > shellparam.nparam)
833			return 0;
834
835		if (num == 0)
836			ap = arg0;
837		else
838			ap = shellparam.p[num - 1];
839
840		if (nulok && (ap == NULL || *ap == '\0'))
841			return 0;
842	}
843	return 1;
844}
845
846
847
848/*
849 * Add the value of a specialized variable to the stack string.
850 */
851
852STATIC void
853varvalue(char *name, int quoted, int subtype, int flag)
854{
855	int num;
856	char *p;
857	int i;
858	extern int oexitstatus;
859	char sep;
860	char **ap;
861	char const *syntax;
862
863#define STRTODEST(p) \
864	do {\
865	if (flag & (EXP_FULL | EXP_CASE) && subtype != VSLENGTH) { \
866		syntax = quoted? DQSYNTAX : BASESYNTAX; \
867		while (*p) { \
868			if (syntax[(int)*p] == CCTL) \
869				STPUTC(CTLESC, expdest); \
870			STPUTC(*p++, expdest); \
871		} \
872	} else \
873		while (*p) \
874			STPUTC(*p++, expdest); \
875	} while (0)
876
877
878	switch (*name) {
879	case '$':
880		num = rootpid;
881		goto numvar;
882	case '?':
883		num = oexitstatus;
884		goto numvar;
885	case '#':
886		num = shellparam.nparam;
887		goto numvar;
888	case '!':
889		num = backgndpid;
890numvar:
891		expdest = cvtnum(num, expdest);
892		break;
893	case '-':
894		for (i = 0 ; i < NOPTS ; i++) {
895			if (optlist[i].val)
896				STPUTC(optlist[i].letter, expdest);
897		}
898		break;
899	case '@':
900		if (flag & EXP_FULL && quoted) {
901			for (ap = shellparam.p ; (p = *ap++) != NULL ; ) {
902				STRTODEST(p);
903				if (*ap)
904					STPUTC('\0', expdest);
905			}
906			break;
907		}
908		/* FALLTHROUGH */
909	case '*':
910		if (ifsset())
911			sep = ifsval()[0];
912		else
913			sep = ' ';
914		for (ap = shellparam.p ; (p = *ap++) != NULL ; ) {
915			STRTODEST(p);
916			if (*ap && sep)
917				STPUTC(sep, expdest);
918		}
919		break;
920	case '0':
921		p = arg0;
922		STRTODEST(p);
923		break;
924	default:
925		if (is_digit(*name)) {
926			num = atoi(name);
927			if (num > 0 && num <= shellparam.nparam) {
928				p = shellparam.p[num - 1];
929				STRTODEST(p);
930			}
931		}
932		break;
933	}
934}
935
936
937
938/*
939 * Record the the fact that we have to scan this region of the
940 * string for IFS characters.
941 */
942
943STATIC void
944recordregion(int start, int end, int inquotes)
945{
946	struct ifsregion *ifsp;
947
948	if (ifslastp == NULL) {
949		ifsp = &ifsfirst;
950	} else {
951		if (ifslastp->endoff == start
952		    && ifslastp->inquotes == inquotes) {
953			/* extend previous area */
954			ifslastp->endoff = end;
955			return;
956		}
957		ifsp = (struct ifsregion *)ckmalloc(sizeof (struct ifsregion));
958		ifslastp->next = ifsp;
959	}
960	ifslastp = ifsp;
961	ifslastp->next = NULL;
962	ifslastp->begoff = start;
963	ifslastp->endoff = end;
964	ifslastp->inquotes = inquotes;
965}
966
967
968
969/*
970 * Break the argument string into pieces based upon IFS and add the
971 * strings to the argument list.  The regions of the string to be
972 * searched for IFS characters have been stored by recordregion.
973 */
974STATIC void
975ifsbreakup(char *string, struct arglist *arglist)
976{
977	struct ifsregion *ifsp;
978	struct strlist *sp;
979	char *start;
980	char *p;
981	char *q;
982	char *ifs;
983	const char *ifsspc;
984	int had_param_ch = 0;
985
986	start = string;
987
988	if (ifslastp == NULL) {
989		/* Return entire argument, IFS doesn't apply to any of it */
990		sp = (struct strlist *)stalloc(sizeof *sp);
991		sp->text = start;
992		*arglist->lastp = sp;
993		arglist->lastp = &sp->next;
994		return;
995	}
996
997	ifs = ifsset() ? ifsval() : " \t\n";
998
999	for (ifsp = &ifsfirst; ifsp != NULL; ifsp = ifsp->next) {
1000		p = string + ifsp->begoff;
1001		while (p < string + ifsp->endoff) {
1002			q = p;
1003			if (*p == CTLESC)
1004				p++;
1005			if (ifsp->inquotes) {
1006				/* Only NULs (should be from "$@") end args */
1007				had_param_ch = 1;
1008				if (*p != 0) {
1009					p++;
1010					continue;
1011				}
1012				ifsspc = NULL;
1013			} else {
1014				if (!strchr(ifs, *p)) {
1015					had_param_ch = 1;
1016					p++;
1017					continue;
1018				}
1019				ifsspc = strchr(" \t\n", *p);
1020
1021				/* Ignore IFS whitespace at start */
1022				if (q == start && ifsspc != NULL) {
1023					p++;
1024					start = p;
1025					continue;
1026				}
1027				had_param_ch = 0;
1028			}
1029
1030			/* Save this argument... */
1031			*q = '\0';
1032			sp = (struct strlist *)stalloc(sizeof *sp);
1033			sp->text = start;
1034			*arglist->lastp = sp;
1035			arglist->lastp = &sp->next;
1036			p++;
1037
1038			if (ifsspc != NULL) {
1039				/* Ignore further trailing IFS whitespace */
1040				for (; p < string + ifsp->endoff; p++) {
1041					q = p;
1042					if (*p == CTLESC)
1043						p++;
1044					if (strchr(ifs, *p) == NULL) {
1045						p = q;
1046						break;
1047					}
1048					if (strchr(" \t\n", *p) == NULL) {
1049						p++;
1050						break;
1051					}
1052				}
1053			}
1054			start = p;
1055		}
1056	}
1057
1058	/*
1059	 * Save anything left as an argument.
1060	 * Traditionally we have treated 'IFS=':'; set -- x$IFS' as
1061	 * generating 2 arguments, the second of which is empty.
1062	 * Some recent clarification of the Posix spec say that it
1063	 * should only generate one....
1064	 */
1065	if (had_param_ch || *start != 0) {
1066		sp = (struct strlist *)stalloc(sizeof *sp);
1067		sp->text = start;
1068		*arglist->lastp = sp;
1069		arglist->lastp = &sp->next;
1070	}
1071}
1072
1073
1074
1075/*
1076 * Expand shell metacharacters.  At this point, the only control characters
1077 * should be escapes.  The results are stored in the list exparg.
1078 */
1079
1080STATIC char *expdir;
1081
1082
1083STATIC void
1084expandmeta(struct strlist *str, int flag __unused)
1085{
1086	char *p;
1087	struct strlist **savelastp;
1088	struct strlist *sp;
1089	char c;
1090	/* TODO - EXP_REDIR */
1091
1092	while (str) {
1093		if (fflag)
1094			goto nometa;
1095		p = str->text;
1096		for (;;) {			/* fast check for meta chars */
1097			if ((c = *p++) == '\0')
1098				goto nometa;
1099			if (c == '*' || c == '?' || c == '[' || c == '!')
1100				break;
1101		}
1102		savelastp = exparg.lastp;
1103		INTOFF;
1104		if (expdir == NULL) {
1105			int i = strlen(str->text);
1106			expdir = ckmalloc(i < 2048 ? 2048 : i); /* XXX */
1107		}
1108
1109		expmeta(expdir, str->text);
1110		ckfree(expdir);
1111		expdir = NULL;
1112		INTON;
1113		if (exparg.lastp == savelastp) {
1114			/*
1115			 * no matches
1116			 */
1117nometa:
1118			*exparg.lastp = str;
1119			rmescapes(str->text);
1120			exparg.lastp = &str->next;
1121		} else {
1122			*exparg.lastp = NULL;
1123			*savelastp = sp = expsort(*savelastp);
1124			while (sp->next != NULL)
1125				sp = sp->next;
1126			exparg.lastp = &sp->next;
1127		}
1128		str = str->next;
1129	}
1130}
1131
1132
1133/*
1134 * Do metacharacter (i.e. *, ?, [...]) expansion.
1135 */
1136
1137STATIC void
1138expmeta(char *enddir, char *name)
1139{
1140	char *p;
1141	char *q;
1142	char *start;
1143	char *endname;
1144	int metaflag;
1145	struct stat statb;
1146	DIR *dirp;
1147	struct dirent *dp;
1148	int atend;
1149	int matchdot;
1150
1151	metaflag = 0;
1152	start = name;
1153	for (p = name ; ; p++) {
1154		if (*p == '*' || *p == '?')
1155			metaflag = 1;
1156		else if (*p == '[') {
1157			q = p + 1;
1158			if (*q == '!' || *q == '^')
1159				q++;
1160			for (;;) {
1161				while (*q == CTLQUOTEMARK)
1162					q++;
1163				if (*q == CTLESC)
1164					q++;
1165				if (*q == '/' || *q == '\0')
1166					break;
1167				if (*++q == ']') {
1168					metaflag = 1;
1169					break;
1170				}
1171			}
1172		} else if (*p == '!' && p[1] == '!'	&& (p == name || p[-1] == '/')) {
1173			metaflag = 1;
1174		} else if (*p == '\0')
1175			break;
1176		else if (*p == CTLQUOTEMARK)
1177			continue;
1178		else if (*p == CTLESC)
1179			p++;
1180		if (*p == '/') {
1181			if (metaflag)
1182				break;
1183			start = p + 1;
1184		}
1185	}
1186	if (metaflag == 0) {	/* we've reached the end of the file name */
1187		if (enddir != expdir)
1188			metaflag++;
1189		for (p = name ; ; p++) {
1190			if (*p == CTLQUOTEMARK)
1191				continue;
1192			if (*p == CTLESC)
1193				p++;
1194			*enddir++ = *p;
1195			if (*p == '\0')
1196				break;
1197		}
1198		if (metaflag == 0 || lstat(expdir, &statb) >= 0)
1199			addfname(expdir);
1200		return;
1201	}
1202	endname = p;
1203	if (start != name) {
1204		p = name;
1205		while (p < start) {
1206			while (*p == CTLQUOTEMARK)
1207				p++;
1208			if (*p == CTLESC)
1209				p++;
1210			*enddir++ = *p++;
1211		}
1212	}
1213	if (enddir == expdir) {
1214		p = ".";
1215	} else if (enddir == expdir + 1 && *expdir == '/') {
1216		p = "/";
1217	} else {
1218		p = expdir;
1219		enddir[-1] = '\0';
1220	}
1221	if ((dirp = opendir(p)) == NULL)
1222		return;
1223	if (enddir != expdir)
1224		enddir[-1] = '/';
1225	if (*endname == 0) {
1226		atend = 1;
1227	} else {
1228		atend = 0;
1229		*endname++ = '\0';
1230	}
1231	matchdot = 0;
1232	p = start;
1233	while (*p == CTLQUOTEMARK)
1234		p++;
1235	if (*p == CTLESC)
1236		p++;
1237	if (*p == '.')
1238		matchdot++;
1239	while (! int_pending() && (dp = readdir(dirp)) != NULL) {
1240		if (dp->d_name[0] == '.' && ! matchdot)
1241			continue;
1242		if (patmatch(start, dp->d_name, 0)) {
1243			if (atend) {
1244				scopy(dp->d_name, enddir);
1245				addfname(expdir);
1246			} else {
1247				for (p = enddir, q = dp->d_name;
1248				     (*p++ = *q++) != '\0';)
1249					continue;
1250				p[-1] = '/';
1251				expmeta(p, endname);
1252			}
1253		}
1254	}
1255	closedir(dirp);
1256	if (! atend)
1257		endname[-1] = '/';
1258}
1259
1260
1261/*
1262 * Add a file name to the list.
1263 */
1264
1265STATIC void
1266addfname(char *name)
1267{
1268	char *p;
1269	struct strlist *sp;
1270
1271	p = stalloc(strlen(name) + 1);
1272	scopy(name, p);
1273	sp = (struct strlist *)stalloc(sizeof *sp);
1274	sp->text = p;
1275	*exparg.lastp = sp;
1276	exparg.lastp = &sp->next;
1277}
1278
1279
1280/*
1281 * Sort the results of file name expansion.  It calculates the number of
1282 * strings to sort and then calls msort (short for merge sort) to do the
1283 * work.
1284 */
1285
1286STATIC struct strlist *
1287expsort(struct strlist *str)
1288{
1289	int len;
1290	struct strlist *sp;
1291
1292	len = 0;
1293	for (sp = str ; sp ; sp = sp->next)
1294		len++;
1295	return msort(str, len);
1296}
1297
1298
1299STATIC struct strlist *
1300msort(struct strlist *list, int len)
1301{
1302	struct strlist *p, *q = NULL;
1303	struct strlist **lpp;
1304	int half;
1305	int n;
1306
1307	if (len <= 1)
1308		return list;
1309	half = len >> 1;
1310	p = list;
1311	for (n = half ; --n >= 0 ; ) {
1312		q = p;
1313		p = p->next;
1314	}
1315	q->next = NULL;			/* terminate first half of list */
1316	q = msort(list, half);		/* sort first half of list */
1317	p = msort(p, len - half);		/* sort second half */
1318	lpp = &list;
1319	for (;;) {
1320		if (strcmp(p->text, q->text) < 0) {
1321			*lpp = p;
1322			lpp = &p->next;
1323			if ((p = *lpp) == NULL) {
1324				*lpp = q;
1325				break;
1326			}
1327		} else {
1328			*lpp = q;
1329			lpp = &q->next;
1330			if ((q = *lpp) == NULL) {
1331				*lpp = p;
1332				break;
1333			}
1334		}
1335	}
1336	return list;
1337}
1338
1339
1340
1341/*
1342 * Returns true if the pattern matches the string.
1343 */
1344
1345int
1346patmatch(const char *pattern, const char *string, int squoted)
1347{
1348#ifdef notdef
1349	if (pattern[0] == '!' && pattern[1] == '!')
1350		return 1 - pmatch(pattern + 2, string);
1351	else
1352#endif
1353		return pmatch(pattern, string, squoted);
1354}
1355
1356
1357STATIC int
1358pmatch(const char *pattern, const char *string, int squoted)
1359{
1360	const char *p, *q;
1361	char c;
1362
1363	p = pattern;
1364	q = string;
1365	for (;;) {
1366		switch (c = *p++) {
1367		case '\0':
1368			goto breakloop;
1369		case CTLESC:
1370			if (squoted && *q == CTLESC)
1371				q++;
1372			if (*q++ != *p++)
1373				return 0;
1374			break;
1375		case CTLQUOTEMARK:
1376			continue;
1377		case '?':
1378			if (squoted && *q == CTLESC)
1379				q++;
1380			if (*q++ == '\0')
1381				return 0;
1382			break;
1383		case '*':
1384			c = *p;
1385			while (c == CTLQUOTEMARK || c == '*')
1386				c = *++p;
1387			if (c != CTLESC &&  c != CTLQUOTEMARK &&
1388			    c != '?' && c != '*' && c != '[') {
1389				while (*q != c) {
1390					if (squoted && *q == CTLESC &&
1391					    q[1] == c)
1392						break;
1393					if (*q == '\0')
1394						return 0;
1395					if (squoted && *q == CTLESC)
1396						q++;
1397					q++;
1398				}
1399			}
1400			do {
1401				if (pmatch(p, q, squoted))
1402					return 1;
1403				if (squoted && *q == CTLESC)
1404					q++;
1405			} while (*q++ != '\0');
1406			return 0;
1407		case '[': {
1408			const char *endp;
1409			int invert, found;
1410			char chr;
1411
1412			endp = p;
1413			if (*endp == '!' || *endp == '^')
1414				endp++;
1415			for (;;) {
1416				while (*endp == CTLQUOTEMARK)
1417					endp++;
1418				if (*endp == '\0')
1419					goto dft;		/* no matching ] */
1420				if (*endp == CTLESC)
1421					endp++;
1422				if (*++endp == ']')
1423					break;
1424			}
1425			invert = 0;
1426			if (*p == '!' || *p == '^') {
1427				invert++;
1428				p++;
1429			}
1430			found = 0;
1431			chr = *q++;
1432			if (squoted && chr == CTLESC)
1433				chr = *q++;
1434			if (chr == '\0')
1435				return 0;
1436			c = *p++;
1437			do {
1438				if (c == CTLQUOTEMARK)
1439					continue;
1440				if (c == CTLESC)
1441					c = *p++;
1442				if (*p == '-' && p[1] != ']') {
1443					p++;
1444					while (*p == CTLQUOTEMARK)
1445						p++;
1446					if (*p == CTLESC)
1447						p++;
1448					if (   collate_range_cmp(chr, c) >= 0
1449					    && collate_range_cmp(chr, *p) <= 0
1450					   )
1451						found = 1;
1452					p++;
1453				} else {
1454					if (chr == c)
1455						found = 1;
1456				}
1457			} while ((c = *p++) != ']');
1458			if (found == invert)
1459				return 0;
1460			break;
1461		}
1462dft:	        default:
1463			if (squoted && *q == CTLESC)
1464				q++;
1465			if (*q++ != c)
1466				return 0;
1467			break;
1468		}
1469	}
1470breakloop:
1471	if (*q != '\0')
1472		return 0;
1473	return 1;
1474}
1475
1476
1477
1478/*
1479 * Remove any CTLESC characters from a string.
1480 */
1481
1482void
1483rmescapes(char *str)
1484{
1485	char *p, *q;
1486
1487	p = str;
1488	while (*p != CTLESC && *p != CTLQUOTEMARK) {
1489		if (*p++ == '\0')
1490			return;
1491	}
1492	q = p;
1493	while (*p) {
1494		if (*p == CTLQUOTEMARK) {
1495			p++;
1496			continue;
1497		}
1498		if (*p == CTLESC)
1499			p++;
1500		*q++ = *p++;
1501	}
1502	*q = '\0';
1503}
1504
1505
1506
1507/*
1508 * See if a pattern matches in a case statement.
1509 */
1510
1511int
1512casematch(union node *pattern, const char *val)
1513{
1514	struct stackmark smark;
1515	int result;
1516	char *p;
1517
1518	setstackmark(&smark);
1519	argbackq = pattern->narg.backquote;
1520	STARTSTACKSTR(expdest);
1521	ifslastp = NULL;
1522	argstr(pattern->narg.text, EXP_TILDE | EXP_CASE);
1523	STPUTC('\0', expdest);
1524	p = grabstackstr(expdest);
1525	result = patmatch(p, val, 0);
1526	popstackmark(&smark);
1527	return result;
1528}
1529
1530/*
1531 * Our own itoa().
1532 */
1533
1534STATIC char *
1535cvtnum(int num, char *buf)
1536{
1537	char temp[32];
1538	int neg = num < 0;
1539	char *p = temp + 31;
1540
1541	temp[31] = '\0';
1542
1543	do {
1544		*--p = num % 10 + '0';
1545	} while ((num /= 10) != 0);
1546
1547	if (neg)
1548		*--p = '-';
1549
1550	while (*p)
1551		STPUTC(*p++, buf);
1552	return buf;
1553}
1554
1555/*
1556 * Do most of the work for wordexp(3).
1557 */
1558
1559int
1560wordexpcmd(int argc, char **argv)
1561{
1562	size_t len;
1563	int i;
1564
1565	out1fmt("%08x", argc - 1);
1566	for (i = 1, len = 0; i < argc; i++)
1567		len += strlen(argv[i]);
1568	out1fmt("%08x", (int)len);
1569	for (i = 1; i < argc; i++) {
1570		out1str(argv[i]);
1571		out1c('\0');
1572	}
1573        return (0);
1574}
1575